<commit_before>/*! \brief serial_controller_node.
 *         Manages serial communications with AVR-Master.
 *
 *  This node manages serial communications with the AVR-Master.
 *  Therefore it first requests all data from AVR-Master and then sends all
 *  commands to AVR-Master in a Loop. Data read is stored in md49_data.txt,
 *  commands to be send are read from md49_commands.txt.
 *
 */

// Includes
// *********************************************************
#include <iostream>                                         /* allows to perform standard input and output operations */
//#include <fstream>                                          /* Input/output stream class to operate on files. */
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
//#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <errno.h>                                          /* Error number definitions */
#include <termios.h>                                        /* POSIX terminal control definitions */
//#include <ctype.h>                                          /* isxxx() */
//#include<ros/ros.h>
#include <sqlite3.h>

// Global variables
const char* serialport_name="//dev/ttyAMA0";                   /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/
int serialport_bps=B9600;                                  /* defines used baudrate on serialport */
//int filedesc;                                             /* File descriptor of serial port we will talk to*/
int fd;                                                     /* serial port file descriptor */
int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128;                     /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128;           /* speed to set for MD49 */
unsigned char serialBuffer[16];                             /* Serial buffer to store uart data */
struct termios orig;                                        // backuped port options

// sqlite globals
sqlite3 *db;
char *zErrMsg = 0;
int  rc;
const char *sql;
const char* data = "Callback function called";

using namespace std;

// Declare functions
// *********************************************************
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void open_sqlite_db_md49data(void);
static int sql_callback(void *data, int argc, char **argv, char **azColName);
void read_MD49_Data_serial (void);
void read_md49_commands(void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);

int main( int argc, char* argv[] ){

    // Init as ROS node
    // ****************
    //ros::init(argc, argv, "serial_controller");
    //ros::NodeHandle n;

    // Open sqlite database md49data.db
    // ********************************
    open_sqlite_db_md49data();

    // Open serial port
    // ****************
    fd = openSerialPort(serialport_name, serialport_bps);
    if (fd == -1) exit(1);
    //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps);
    usleep(10000);                                          // Sleep for UART to power up and set options

    //ROS_DEBUG("Starting Mainloop...");
    //ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 5Hz...");

    // Mainloop
    // ***********************************
    //while(  n.ok() ){
    while( 1 ){
        // Read encodervalues and other data from MD49
        // serial. Data ist stored in md49_data.txt
        // ****************************************
        read_MD49_Data_serial();
        usleep(100000);

        // Read commands from md49_commands.txt:
        // *************************************
        read_md49_commands();

        // Set speed and other commands as
        // read from md49_commands.txt
        // *******************************
        if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
            set_MD49_speed(speed_l, speed_r);
            last_speed_l=speed_l;
            last_speed_r=speed_r;
        }

        usleep(100000);

    }// end.mainloop
    sqlite3_close(db);
    return 1;
} // end.main

void read_MD49_Data_serial (void){
    // Read serial MD49 data from AVR-Master
    // *************************************
    serialBuffer[0] = 82;                                   // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
    writeBytes(fd, 1);
    readBytes(fd, 18);

    // Put toghether encoder values from their
    // corresponding bytes, read from MD49
    // ***************************************
    EncoderL = serialBuffer[0] << 24;                       // Put together first encoder value
    EncoderL |= (serialBuffer[1] << 16);
    EncoderL |= (serialBuffer[2] << 8);
    EncoderL |= (serialBuffer[3]);
    EncoderR = serialBuffer[4] << 24;                       // Put together second encoder value
    EncoderR |= (serialBuffer[5] << 16);
    EncoderR |= (serialBuffer[6] << 8);
    EncoderR |= (serialBuffer[7]);

    // Write data read from MD49 into
    // sqlite3 database md49data.db
    // ******************************
    char sql_buffer[400];
    int cx;
    // EncoderL & EncoderR
    cx = snprintf (sql_buffer,400,"UPDATE md49data SET EncoderL=%i, EncoderR=%i WHERE ID=1;", EncoderL, EncoderR);
    rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }
    // Encoderbytes 1-4 left
    cx = snprintf (sql_buffer,400,"UPDATE md49data SET Encoderbyte1L=%i, Encoderbyte2L=%i, " \
                   "Encoderbyte3L=%i, Encoderbyte4L=%i WHERE ID=1;", serialBuffer[0], serialBuffer[1], serialBuffer[2], serialBuffer[3]);
    rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }
    // Encoderbytes 1-4 right
    cx = snprintf (sql_buffer,400,"UPDATE md49data SET Encoderbyte1R=%i, Encoderbyte2R=%i, " \
                   "Encoderbyte3R=%i, Encoderbyte4R=%i WHERE ID=1;", serialBuffer[4], serialBuffer[5], serialBuffer[6], serialBuffer[7]);
    rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }

    // Output MD49 data on screen
    // **************************
    printf("\033[2J");                                      //  clear the screen
    printf("\033[H");                                       //  position cursor at top-left corner
    printf ("MD49-Data read from AVR-Master: \n");
    printf("========================================\n");
    printf("Encoder1 Byte1: %i ",serialBuffer[0]);
    printf("Byte2: %i ",serialBuffer[1]);
    printf("Byte3: % i ",serialBuffer[2]);
    printf("Byte4: %i \n",serialBuffer[3]);
    printf("Encoder2 Byte1: %i ",serialBuffer[4]);
    printf("Byte2: %i ",serialBuffer[5]);
    printf("Byte3: %i ",serialBuffer[6]);
    printf("Byte4: %i \n",serialBuffer[7]);
    printf("EncoderL: %i ",EncoderL);
    printf("EncoderR: %i \n",EncoderR);
    printf("========================================\n");
    printf("SpeedL: %i ",serialBuffer[8]);
    printf("SpeedR: %i \n",serialBuffer[9]);
    printf("Volts: %i \n",serialBuffer[10]);
    printf("CurrentL: %i ",serialBuffer[11]);
    printf("CurrentR: %i \n",serialBuffer[12]);
    printf("Error: %i \n",serialBuffer[13]);
    printf("Acceleration: %i \n",serialBuffer[14]);
    printf("Mode: %i \n",serialBuffer[15]);
    printf("Regulator: %i \n",serialBuffer[16]);
    printf("Timeout: %i \n",serialBuffer[17]);

}

// Write serial command to change left and right speed
// ***************************************************
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){

    serialBuffer[0] = 88;                                   // 88 =X Steuerbyte um Commands an MD49 zu senden
    serialBuffer[1] = 115;                                  // 115=s Steuerbyte setSpeed
    serialBuffer[2] = speed_l;                              // set speed1
    serialBuffer[3] = speed_r;                              // set speed2
    writeBytes(fd, 4);
}

// Read SpeedL and SpeedR from
// table md49commands(md49data.db)
// *******************************
void read_md49_commands(void){

   // Create SQL statement
   sql = "SELECT * from md49commands WHERE ID=1";

   // Execute SQL statement
   rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL message: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      //fprintf(stdout, "Query done successfully\n");
   }
}

// Open serialport
// ***************
int openSerialPort(const char * device, int bps){

   struct termios neu;
   char buf[128];

   //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
   fd = open(device, O_RDWR | O_NOCTTY);

   if (fd == -1)
   {
      sprintf(buf, "openSerialPort %s error", device);
      perror(buf);
   }
   else
   {
      tcgetattr(fd, &orig);                                 /* save current serial settings */
      tcgetattr(fd, &neu);
      cfmakeraw(&neu);
      cfsetispeed(&neu, bps);
      cfsetospeed(&neu, bps);
      tcflush(fd, TCIFLUSH);
      tcsetattr(fd, TCSANOW, &neu);                         /* set new serial settings */
      fcntl (fd, F_SETFL, O_RDWR);
   }
   return fd;
}

// Write bytes serial to UART
// **************************
void writeBytes(int descriptor, int count) {
    if ((write(descriptor, serialBuffer, count)) == -1) {   // Send data out
        perror("Error writing");
        close(descriptor);                                  // Close port if there is an error
        exit(1);
    }

}

// Read bytes serial from UART
// ***************************
void readBytes(int descriptor, int count) {
    if (read(descriptor, serialBuffer, count) == -1) {      // Read back data into buf[]
        perror("Error reading ");
        close(descriptor);                                  // Close port if there is an error
        exit(1);
    }
}

// Open sqlite db md49data.db and create
// table md49data if not existing
// *************************************
void open_sqlite_db_md49data(void){

    // Open database md49data.db and add table md49data
    // ************************************************
    rc = sqlite3_open("data/md49data.db", &db);
    if( rc ){
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        exit(0);
    }else{
        fprintf(stdout, "Opened database successfully,\n");
    }

    // Create table md49data
    // *********************
    sql = "CREATE TABLE md49data("  \
     "ID INT PRIMARY KEY     NOT NULL," \
     "Encoderbyte1L  INT DEFAULT 0, Encoderbyte2L  INT DEFAULT 0," \
     "Encoderbyte3L  INT DEFAULT 0, Encoderbyte4L  INT DEFAULT 0," \
     "Encoderbyte1R  INT DEFAULT 0, Encoderbyte2R  INT DEFAULT 0," \
     "Encoderbyte3R  INT DEFAULT 0, Encoderbyte4R  INT DEFAULT 0," \
     "EncoderL       INT DEFAULT 0, EncoderR       INT DEFAULT 0," \
     "SpeedL         INT DEFAULT 0, SpeedR         INT DEFAULT 0," \
     "Volts          INT DEFAULT 0," \
     "CurrentL       INT DEFAULT 0, CurrentR       INT DEFAULT 0," \
     "Error          INT DEFAULT 0, Acceleration   INT DEFAULT 0," \
     "Mode           INT DEFAULT 0, Regulator      INT DEFAULT 0," \
     "Timeout        INT DEFAULT 0 );" \
     "INSERT INTO md49data (ID) VALUES (1);";

    /* Execute SQL statement */
    rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        fprintf(stdout, "table created successfully\n");
    }
}

// Callbackfunction executed if table md49commands in md49data.db is queried
// *************************************************************************
static int sql_callback(void *data, int argc, char **argv, char **azColName){
   speed_l= atoi(argv[1]);
   speed_r= atoi(argv[2]);
   return 0;
}

<commit_msg>Remove txt files<commit_after>/*! \brief serial_controller_node.
 *         Manages serial communications with AVR-Master.
 *
 *  This node manages serial communications with the AVR-Master.
 *  Therefore it first requests all data from AVR-Master and then sends all
 *  commands to AVR-Master in a Loop. Data read is stored in md49_data.txt,
 *  commands to be send are read from md49_commands.txt.
 *
 */

// Includes
// *********************************************************
#include <iostream>                                         /* allows to perform standard input and output operations */
//#include <fstream>                                          /* Input/output stream class to operate on files. */
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
//#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <errno.h>                                          /* Error number definitions */
#include <termios.h>                                        /* POSIX terminal control definitions */
//#include <ctype.h>                                          /* isxxx() */
//#include<ros/ros.h>
#include <sqlite3.h>

// Global variables
const char* serialport_name="//dev/ttyAMA0";                   /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/
int serialport_bps=B9600;                                  /* defines used baudrate on serialport */
//int filedesc;                                             /* File descriptor of serial port we will talk to*/
int fd;                                                     /* serial port file descriptor */
int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128;                     /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128;           /* speed to set for MD49 */
unsigned char serialBuffer[16];                             /* Serial buffer to store uart data */
struct termios orig;                                        // backuped port options

// sqlite globals
sqlite3 *db;
char *zErrMsg = 0;
int  rc;
const char *sql;
const char* data = "Callback function called";

using namespace std;

// Declare functions
// *********************************************************
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void open_sqlite_db_md49data(void);
static int sql_callback(void *data, int argc, char **argv, char **azColName);
void read_MD49_Data_serial (void);
void read_md49_commands(void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);

int main( int argc, char* argv[] ){

    // Init as ROS node
    // ****************
    //ros::init(argc, argv, "serial_controller");
    //ros::NodeHandle n;

    // Open sqlite database md49data.db
    // ********************************
    open_sqlite_db_md49data();

    // Open serial port
    // ****************
    fd = openSerialPort(serialport_name, serialport_bps);
    if (fd == -1) exit(1);
    //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps);
    usleep(10000);                                          // Sleep for UART to power up and set options

    //ROS_DEBUG("Starting Mainloop...");
    //ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 5Hz...");

    // Mainloop
    // ***********************************
    //while(  n.ok() ){
    while( 1 ){
        // Read encodervalues and other data from MD49
        // serial. Data ist stored in md49_data.txt
        // ****************************************
        read_MD49_Data_serial();
        usleep(100000);

        // Read commands from md49_commands.txt:
        // *************************************
        read_md49_commands();

        // Set speed and other commands as
        // read from md49_commands.txt
        // *******************************
        if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
            set_MD49_speed(speed_l, speed_r);
            last_speed_l=speed_l;
            last_speed_r=speed_r;
        }

        usleep(100000);

    }// end.mainloop
    sqlite3_close(db);
    return 1;
} // end.main

void read_MD49_Data_serial (void){
    // Read serial MD49 data from AVR-Master
    // *************************************
    serialBuffer[0] = 82;                                   // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
    writeBytes(fd, 1);
    readBytes(fd, 18);

    // Put toghether encoder values from their
    // corresponding bytes, read from MD49
    // ***************************************
    EncoderL = serialBuffer[0] << 24;                       // Put together first encoder value
    EncoderL |= (serialBuffer[1] << 16);
    EncoderL |= (serialBuffer[2] << 8);
    EncoderL |= (serialBuffer[3]);
    EncoderR = serialBuffer[4] << 24;                       // Put together second encoder value
    EncoderR |= (serialBuffer[5] << 16);
    EncoderR |= (serialBuffer[6] << 8);
    EncoderR |= (serialBuffer[7]);

    // Write data read from MD49 into
    // sqlite3 database md49data.db
    // ******************************
    char sql_buffer[400];
    int cx;
    // EncoderL & EncoderR
    cx = snprintf (sql_buffer,400,"UPDATE md49data SET EncoderL=%i, EncoderR=%i WHERE ID=1;", EncoderL, EncoderR);
    rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }
    // Encoderbytes 1-4 left
    cx = snprintf (sql_buffer,400,"UPDATE md49data SET Encoderbyte1L=%i, Encoderbyte2L=%i, " \
                   "Encoderbyte3L=%i, Encoderbyte4L=%i WHERE ID=1;", serialBuffer[0], serialBuffer[1], serialBuffer[2], serialBuffer[3]);
    rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }
    // Encoderbytes 1-4 right
    cx = snprintf (sql_buffer,400,"UPDATE md49data SET Encoderbyte1R=%i, Encoderbyte2R=%i, " \
                   "Encoderbyte3R=%i, Encoderbyte4R=%i WHERE ID=1;", serialBuffer[4], serialBuffer[5], serialBuffer[6], serialBuffer[7]);
    rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }
    // SpeedL, SpeedR, Volts, CurrentL, CurrentR, Error, Acceleration, Mode, Regulator, Timeout
    cx = snprintf (sql_buffer,400,"UPDATE md49data SET SpeedL=%i, SpeedR=%i, " \
                   "Volts=%i, CurrentL=%i, CurrentR=%i, Error=%i, Acceleration=%i, Mode=%i, " \
                   "Regulator=%i, Timeout=%i " \
                   "WHERE ID=1;", serialBuffer[8], serialBuffer[9], serialBuffer[10], serialBuffer[11], serialBuffer[12], serialBuffer[13], serialBuffer[14], serialBuffer[15], serialBuffer[16], serialBuffer[17]);
    rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        //fprintf(stdout, "Operation done successfully\n");
    }

    // Output MD49 data on screen
    // **************************
    printf("\033[2J");                                      //  clear the screen
    printf("\033[H");                                       //  position cursor at top-left corner
    printf ("MD49-Data read from AVR-Master: \n");
    printf("========================================\n");
    printf("Encoder1 Byte1: %i ",serialBuffer[0]);
    printf("Byte2: %i ",serialBuffer[1]);
    printf("Byte3: % i ",serialBuffer[2]);
    printf("Byte4: %i \n",serialBuffer[3]);
    printf("Encoder2 Byte1: %i ",serialBuffer[4]);
    printf("Byte2: %i ",serialBuffer[5]);
    printf("Byte3: %i ",serialBuffer[6]);
    printf("Byte4: %i \n",serialBuffer[7]);
    printf("EncoderL: %i ",EncoderL);
    printf("EncoderR: %i \n",EncoderR);
    printf("========================================\n");
    printf("SpeedL: %i ",serialBuffer[8]);
    printf("SpeedR: %i \n",serialBuffer[9]);
    printf("Volts: %i \n",serialBuffer[10]);
    printf("CurrentL: %i ",serialBuffer[11]);
    printf("CurrentR: %i \n",serialBuffer[12]);
    printf("Error: %i \n",serialBuffer[13]);
    printf("Acceleration: %i \n",serialBuffer[14]);
    printf("Mode: %i \n",serialBuffer[15]);
    printf("Regulator: %i \n",serialBuffer[16]);
    printf("Timeout: %i \n",serialBuffer[17]);

}

// Write serial command to change left and right speed
// ***************************************************
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){

    serialBuffer[0] = 88;                                   // 88 =X Steuerbyte um Commands an MD49 zu senden
    serialBuffer[1] = 115;                                  // 115=s Steuerbyte setSpeed
    serialBuffer[2] = speed_l;                              // set speed1
    serialBuffer[3] = speed_r;                              // set speed2
    writeBytes(fd, 4);
}

// Read SpeedL and SpeedR from
// table md49commands(md49data.db)
// *******************************
void read_md49_commands(void){

   // Create SQL statement
   sql = "SELECT * from md49commands WHERE ID=1";

   // Execute SQL statement
   rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL message: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      //fprintf(stdout, "Query done successfully\n");
   }
}

// Open serialport
// ***************
int openSerialPort(const char * device, int bps){

   struct termios neu;
   char buf[128];

   //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
   fd = open(device, O_RDWR | O_NOCTTY);

   if (fd == -1)
   {
      sprintf(buf, "openSerialPort %s error", device);
      perror(buf);
   }
   else
   {
      tcgetattr(fd, &orig);                                 /* save current serial settings */
      tcgetattr(fd, &neu);
      cfmakeraw(&neu);
      cfsetispeed(&neu, bps);
      cfsetospeed(&neu, bps);
      tcflush(fd, TCIFLUSH);
      tcsetattr(fd, TCSANOW, &neu);                         /* set new serial settings */
      fcntl (fd, F_SETFL, O_RDWR);
   }
   return fd;
}

// Write bytes serial to UART
// **************************
void writeBytes(int descriptor, int count) {
    if ((write(descriptor, serialBuffer, count)) == -1) {   // Send data out
        perror("Error writing");
        close(descriptor);                                  // Close port if there is an error
        exit(1);
    }

}

// Read bytes serial from UART
// ***************************
void readBytes(int descriptor, int count) {
    if (read(descriptor, serialBuffer, count) == -1) {      // Read back data into buf[]
        perror("Error reading ");
        close(descriptor);                                  // Close port if there is an error
        exit(1);
    }
}

// Open sqlite db md49data.db and create
// table md49data if not existing
// *************************************
void open_sqlite_db_md49data(void){

    // Open database md49data.db and add table md49data
    // ************************************************
    rc = sqlite3_open("data/md49data.db", &db);
    if( rc ){
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        exit(0);
    }else{
        fprintf(stdout, "Opened database successfully,\n");
    }

    // Create table md49data
    // *********************
    sql = "CREATE TABLE md49data("  \
     "ID INT PRIMARY KEY     NOT NULL," \
     "Encoderbyte1L  INT DEFAULT 0, Encoderbyte2L  INT DEFAULT 0," \
     "Encoderbyte3L  INT DEFAULT 0, Encoderbyte4L  INT DEFAULT 0," \
     "Encoderbyte1R  INT DEFAULT 0, Encoderbyte2R  INT DEFAULT 0," \
     "Encoderbyte3R  INT DEFAULT 0, Encoderbyte4R  INT DEFAULT 0," \
     "EncoderL       INT DEFAULT 0, EncoderR       INT DEFAULT 0," \
     "SpeedL         INT DEFAULT 0, SpeedR         INT DEFAULT 0," \
     "Volts          INT DEFAULT 0," \
     "CurrentL       INT DEFAULT 0, CurrentR       INT DEFAULT 0," \
     "Error          INT DEFAULT 0, Acceleration   INT DEFAULT 0," \
     "Mode           INT DEFAULT 0, Regulator      INT DEFAULT 0," \
     "Timeout        INT DEFAULT 0 );" \
     "INSERT INTO md49data (ID) VALUES (1);";

    /* Execute SQL statement */
    rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg);
    if( rc != SQLITE_OK ){
        fprintf(stderr, "SQL message: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }else{
        fprintf(stdout, "table created successfully\n");
    }
}

// Callbackfunction executed if table md49commands in md49data.db is queried
// *************************************************************************
static int sql_callback(void *data, int argc, char **argv, char **azColName){
   speed_l= atoi(argv[1]);
   speed_r= atoi(argv[2]);
   return 0;
}

<|endoftext|>


<commit_before>#include <stan/agrad/rev/var_stack.hpp>
#include <stan/agrad/rev/operators/operator_multiplication.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>

struct foo : public stan::agrad::chainable_alloc {
  std::vector<double> x_;
  foo() : x_(3) { }
  ~foo() { }
  void chain() { }
};

TEST(AgradRev, varStackRecoverNestedSegFaultFix) {
  // this test failed in 2.5, but passes in 2.6
  stan::agrad::start_nested();
  foo* x = new foo();
  x->chain();
  stan::agrad::recover_memory_nested();
  // should be able to do this redundantly:
  stan::agrad::recover_memory();
}

// just test basic autodiff;  no more free_memory operation
TEST(AgradRev,varStack) {
  AVAR a = 2.0;
  AVAR b = -3.0;
  AVAR f = a * b;
  EXPECT_FLOAT_EQ(-6.0,f.val());

  AVEC x = createAVEC(a,b);
  VEC grad_f;
  f.grad(x,grad_f);
  EXPECT_FLOAT_EQ(-3.0,grad_f[0]);
  EXPECT_FLOAT_EQ(2.0,grad_f[1]);

  AVAR aa = 2.0;
  AVAR bb = -3.0;
  AVAR ff = aa * bb;
  EXPECT_FLOAT_EQ(-6.0,ff.val());

  AVEC xx = createAVEC(aa,bb);
  VEC grad_ff;
  ff.grad(xx,grad_ff);
  EXPECT_FLOAT_EQ(-3.0,grad_ff[0]);
  EXPECT_FLOAT_EQ(2.0,grad_ff[1]);
}

TEST(AgradRev, recoverMemoryLogicError) {
  stan::agrad::start_nested();
  EXPECT_THROW(stan::agrad::recover_memory(), std::logic_error);
  stan::agrad::recover_memory_nested(); // clean up for next test
}

TEST(AgradRev, recoverMemoryNestedLogicError) {
  EXPECT_THROW(stan::agrad::recover_memory_nested(), std::logic_error);
}
<commit_msg>var_stack_test was moved<commit_after><|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
// FILE:          CanonEDSDK.cpp
// PROJECT:       Micro-Manager
// SUBSYSTEM:     DeviceAdapters
// ----------------------------------------------------------------------------
// DESCRIPTION:   Adapter for Canon EDSDK
// COPYRIGHT:     USCF, 2010
// AUTHOR:        Nico Stuurman
// License:       LGPL
//
//

#ifdef __APPLE__
#define __MACOS__ 1
#endif

#include "CanonEDSDK.h"

#include "../../../3rdparty/trunk/Canon/EDSDK2.9/Mac/EDSDK/Header/EDSDK.h"
#include "../../../3rdparty/trunk/Canon/EDSDK2.9/Mac/EDSDK/Header/EDSDKErrors.h"
#include "../../../3rdparty/trunk/Canon/EDSDK2.9/Mac/EDSDK/Header/EDSDKTypes.h"

//////////////////////////////////////////////////////////////////////////////
// Error codes
#define ERR_NO_CAMERA      200001
#define ERR_DRIVER         200002

/////////////////////////////////////////////////////////////////////////////
// Global strings

const char* g_CameraDeviceName = "Canon SLR";

//////////////////////////////////////////////////////////////////////////////
// Module Interface

MODULE_API void InitializeModuleData()
{
   AddAvailableDeviceName(g_CameraDeviceName, "Canon SLR");
}

MODULE_API MM::Device* CreateDevice(const char* deviceName)
{
   if (deviceName == 0)
      return 0;

   // decide which device class to create based on the deviceName parameter
   if (strcmp(deviceName, g_CameraDeviceName) == 0)
   {
      // create camera
      return new CanonEDCamera();
   }

   return 0;
}

MODULE_API void DeleteDevice(MM::Device* pDevice)
{
   delete pDevice;
}

//////////////////////////////////////////////////////////////////////////////
//  CanonEDCamera class

void* CanonEDCamera::g_Self;

CanonEDCamera::CanonEDCamera() :
   nComponents_(4),
   isSDKLoaded_(false),
   isLegacy_(false),
   camera_(NULL)
{
   SetErrorText(ERR_NO_CAMERA, "No Canon SLR found");
   SetErrorText(ERR_DRIVER, "Canon driver reported an error");

}

CanonEDCamera::~CanonEDCamera()
{
   Shutdown();
}

void CanonEDCamera::GetName(char* name) const
{
   // We just return the name we use for referring to this device adapter.
   CDeviceUtils::CopyLimitedString(name, g_CameraDeviceName);
}

int CanonEDCamera::Shutdown()
{
   // save images on the memory card
   if (isLegacy_)
      EdsSendStatusCommand (camera_,  kEdsCameraStatusCommand_UILock, 0);
   EdsSaveTo toCamera = kEdsSaveTo_Camera;
   EdsError err = EdsSetPropertyData(camera_,  kEdsPropID_SaveTo, 0 , sizeof(EdsSaveTo),  &toCamera);
   if (isLegacy_)
      EdsSendStatusCommand (camera_,  kEdsCameraStatusCommand_UIUnLock, 0);

   // Close session with camera
   err = EdsCloseSession(camera_);

   // Release camera
   if(camera_ != NULL)
   {
      EdsRelease(camera_);
   }

   // Terminate SDK
   if(isSDKLoaded_)
   {
      EdsTerminateSDK();
   }

   return DEVICE_OK;
}

int CanonEDCamera::Initialize()
{
   EdsError err = EDS_ERR_OK;

   // Initialize SDK
   err = EdsInitializeSDK();
   if(err == EDS_ERR_OK)
   {
     isSDKLoaded_ = true;
   }

   // Get first camera
   if(err == EDS_ERR_OK)
   {
      err = getFirstCamera (&camera_);
   }

   if (err == EDS_ERR_DEVICE_NOT_FOUND)
      return ERR_NO_CAMERA;

   // event handlers are static functions that need a reference to this camera object to function
   // provide that static ref here.  This approach will fail with multiple cameras.  In that case,
   // consider making a map with cameras and references to our CanonEDCamera objects
   g_Self = this;

   // Set event handler
   if(err == EDS_ERR_OK)
   {
      err = EdsSetObjectEventHandler(camera_,  kEdsObjectEvent_All, &CanonEDCamera::handleObjectEvent,  NULL);
   }

   // Set event handler
   if(err == EDS_ERR_OK)
   {
      err = EdsSetPropertyEventHandler(camera_,  kEdsPropertyEvent_All, &CanonEDCamera::handlePropertyEvent,  NULL);
   }

   // Set event handler
   if(err == EDS_ERR_OK)
   {
      err = EdsSetCameraStateEventHandler(camera_,  kEdsStateEvent_All, &CanonEDCamera::handleStateEvent,  NULL);
   }

   if(err == EDS_ERR_OK)
   {
      err = EdsOpenSession(camera_);
   }

   // Camera name
   if (err == EDS_ERR_OK)
   {
      EdsDeviceInfo  deviceInfo;
      err = EdsGetDeviceInfo(camera_, &deviceInfo);
      if (err == EDS_ERR_OK)
      {
         std::ostringstream os;
         os << "Canon SLR device subtype: " << deviceInfo.deviceSubType;
         LogMessage(os.str().c_str());
         if (deviceInfo.deviceSubType == 0)
            isLegacy_ = true;
         cameraModel_ = deviceInfo.szDeviceDescription;
         int nRet = CreateProperty("Model", cameraModel_.c_str(), MM::String, true);
         if (nRet != DEVICE_OK)
            return nRet;
      }

      // Set and Get various camera properties

      // lock the UI before setting properties - only needed on legacy cameras
      if (isLegacy_)
         EdsSendStatusCommand (camera_,  kEdsCameraStatusCommand_UILock, 0);
      EdsSaveTo toPC = kEdsSaveTo_Host;
      err = EdsSetPropertyData(camera_,  kEdsPropID_SaveTo, 0 , sizeof(EdsSaveTo),  &toPC);
      if (isLegacy_)
         EdsSendStatusCommand (camera_, kEdsCameraStatusCommand_UIUnLock, 0);
   }

   if (err == EDS_ERR_OK)
   {
      CPropertyAction* pAct = new CPropertyAction(this, &CanonEDCamera::OnBinning);
      int nRet = CreateProperty(MM::g_Keyword_Binning, "1", MM::Integer, false, pAct);
      if (nRet != DEVICE_OK)
         return nRet;
   }

   if (err == EDS_ERR_OK)
   {
      return DEVICE_OK;
   }

   std::ostringstream os;
   os << "Error during initialization: " << std::hex << err;
   LogMessage(os.str().c_str());

   return err;
}

EdsError  CanonEDCamera::getFirstCamera(EdsCameraRef  *camera)
{
    EdsError err = EDS_ERR_OK;
    EdsCameraListRef  cameraList = NULL;
    EdsUInt32  count = 0;

    // Get camera list
    err = EdsGetCameraList(&cameraList);

    // Get number of cameras
    if(err == EDS_ERR_OK)
    {
       err = EdsGetChildCount(cameraList,  &count);
       if(count == 0)
       {
          err = EDS_ERR_DEVICE_NOT_FOUND;
       }
    }

    // Get first camera retrieved
   if(err == EDS_ERR_OK)
   {
       err = EdsGetChildAtIndex(cameraList ,  0 ,  camera);
   }

   // Release camera list
   if(cameraList != NULL)
   {
      EdsRelease(cameraList);
      cameraList = NULL;
   }

   return err;

}

int CanonEDCamera::EdsToMMError(EdsError err)
{
   if (err == EDS_ERR_OK)
      return DEVICE_OK;

   std::ostringstream os;
   os << "Canon driver reported error: " << std::hex << err;
   LogMessage(os.str().c_str());

   return ERR_DRIVER;
}

EdsError EDSCALLBACK CanonEDCamera::handleObjectEvent( EdsObjectEvent event, EdsBaseRef  object, EdsVoid * context)
{

   CanonEDCamera* mmCanon = (CanonEDCamera*) g_Self;
   // do something

   /*
    switch(event)
   {
    case kEdsObjectEvent_DirItemRequestTransfer:
      downloadImage(object);
      break;

      default:

      break;
   }
   */

   // Object must be released
   if(object)
   {
      EdsRelease(object);
   }
}

EdsError EDSCALLBACK  CanonEDCamera::handlePropertyEvent (EdsPropertyEvent event, EdsPropertyID  property, EdsUInt32 param, EdsVoid * context)
{
   CanonEDCamera* mmCanon = (CanonEDCamera*) g_Self;
    // do something
}

EdsError EDSCALLBACK  CanonEDCamera::handleStateEvent (EdsStateEvent event, EdsUInt32 parameter, EdsVoid * context)
{
   CanonEDCamera* mmCanon = (CanonEDCamera*) g_Self;
   // do something
}

// MMCamera API
int CanonEDCamera::SnapImage()
{
   EdsError err = EdsSendCommand(camera_, kEdsCameraCommand_TakePicture , 0);
   if (err != EDS_ERR_OK)
      return (int) err;

   return DEVICE_OK;
}

const unsigned char* CanonEDCamera::GetImageBuffer()
{
   return 0;
}

unsigned CanonEDCamera::GetImageWidth() const
{
   return 0;
}

unsigned CanonEDCamera::GetImageHeight() const
{
   return 0;
}

unsigned CanonEDCamera::GetImageBytesPerPixel() const
{
   return 0;
}

unsigned CanonEDCamera::GetBitDepth() const
{
   return 0;
}

long CanonEDCamera::GetImageBufferSize() const
{
   return 0;
}

double CanonEDCamera::GetExposure() const
{
   return 0;
}

void CanonEDCamera::SetExposure(double exp)
{
}

int CanonEDCamera::SetROI(unsigned x, unsigned y, unsigned xSize, unsigned ySize)
{
   return DEVICE_OK;
}

int CanonEDCamera::GetROI(unsigned& x, unsigned& y, unsigned& xSize, unsigned& ySize)
{
   return DEVICE_OK;
}

int CanonEDCamera::ClearROI()
{
   return DEVICE_OK;
}

int CanonEDCamera::StartSequenceAcquisition(double interval)
{
   return DEVICE_OK;
}

int CanonEDCamera::StartSequenceAcquisition(long numImages, double interval_ms, bool stopOnOverflow)
{
   return DEVICE_OK;
}

int CanonEDCamera::StopSequenceAcquisition()
{
   return DEVICE_OK;
}

int CanonEDCamera::InsertImage()
{
   return DEVICE_OK;
}

/*
int CanonEDCamera::ThreadRun()
{
   return DEVICE_OK;
}
*/

bool CanonEDCamera::IsCapturing()
{
   return false;
}

int CanonEDCamera::GetBinning() const
{
   return 1;
}

int CanonEDCamera::SetBinning(int bS)
{
   return DEVICE_OK;
}

// action interface
int CanonEDCamera::OnBinning(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   return DEVICE_OK;
}

int CanonEDCamera::OnPixelType(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   return DEVICE_OK;
}

int CanonEDCamera::OnBitDepth(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   return DEVICE_OK;
}

int CanonEDCamera::OnReadoutTime(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   return DEVICE_OK;
}

int CanonEDCamera::OnCameraCCDXSize(MM::PropertyBase* , MM::ActionType )
{
   return DEVICE_OK;
}

int CanonEDCamera::OnCameraCCDYSize(MM::PropertyBase* , MM::ActionType )
{
   return DEVICE_OK;
}

<commit_msg>Added code to download image, however, events are not being called<commit_after>///////////////////////////////////////////////////////////////////////////////
// FILE:          CanonEDSDK.cpp
// PROJECT:       Micro-Manager
// SUBSYSTEM:     DeviceAdapters
// ----------------------------------------------------------------------------
// DESCRIPTION:   Adapter for Canon EDSDK
// COPYRIGHT:     USCF, 2010
// AUTHOR:        Nico Stuurman
// License:       LGPL
//
//

#ifdef __APPLE__
#define __MACOS__ 1
#endif

#include "CanonEDSDK.h"

#include "../../../3rdparty/trunk/Canon/EDSDK2.9/Mac/EDSDK/Header/EDSDK.h"
#include "../../../3rdparty/trunk/Canon/EDSDK2.9/Mac/EDSDK/Header/EDSDKErrors.h"
#include "../../../3rdparty/trunk/Canon/EDSDK2.9/Mac/EDSDK/Header/EDSDKTypes.h"

//////////////////////////////////////////////////////////////////////////////
// Error codes
#define ERR_NO_CAMERA      200001
#define ERR_DRIVER         200002

/////////////////////////////////////////////////////////////////////////////
// Global strings

const char* g_CameraDeviceName = "Canon SLR";

//////////////////////////////////////////////////////////////////////////////
// Module Interface

MODULE_API void InitializeModuleData()
{
   AddAvailableDeviceName(g_CameraDeviceName, "Canon SLR");
}

MODULE_API MM::Device* CreateDevice(const char* deviceName)
{
   if (deviceName == 0)
      return 0;

   // decide which device class to create based on the deviceName parameter
   if (strcmp(deviceName, g_CameraDeviceName) == 0)
   {
      // create camera
      return new CanonEDCamera();
   }

   return 0;
}

MODULE_API void DeleteDevice(MM::Device* pDevice)
{
   delete pDevice;
}

//////////////////////////////////////////////////////////////////////////////
//  CanonEDCamera class

void* CanonEDCamera::g_Self;

CanonEDCamera::CanonEDCamera() :
   nComponents_(4),
   isSDKLoaded_(false),
   isLegacy_(false),
   camera_(NULL)
{
   SetErrorText(ERR_NO_CAMERA, "No Canon SLR found");
   SetErrorText(ERR_DRIVER, "Canon driver reported an error");

}

CanonEDCamera::~CanonEDCamera()
{
   Shutdown();
}

void CanonEDCamera::GetName(char* name) const
{
   // We just return the name we use for referring to this device adapter.
   CDeviceUtils::CopyLimitedString(name, g_CameraDeviceName);
}

int CanonEDCamera::Shutdown()
{
   // save images on the memory card
   if (isLegacy_)
      EdsSendStatusCommand (camera_,  kEdsCameraStatusCommand_UILock, 0);
   EdsSaveTo toCamera = kEdsSaveTo_Camera;
   EdsError err = EdsSetPropertyData(camera_,  kEdsPropID_SaveTo, 0 , sizeof(EdsSaveTo),  &toCamera);
   if (isLegacy_)
      EdsSendStatusCommand (camera_,  kEdsCameraStatusCommand_UIUnLock, 0);

   // Close session with camera
   err = EdsCloseSession(camera_);

   // Release camera
   if(camera_ != NULL)
   {
      EdsRelease(camera_);
   }

   // Terminate SDK
   if(isSDKLoaded_)
   {
      EdsTerminateSDK();
   }

   return DEVICE_OK;
}

int CanonEDCamera::Initialize()
{
   EdsError err = EDS_ERR_OK;

   // Initialize SDK
   err = EdsInitializeSDK();
   if(err == EDS_ERR_OK)
   {
     isSDKLoaded_ = true;
   }

   // Get first camera
   if(err == EDS_ERR_OK)
   {
      err = getFirstCamera (&camera_);
   }

   if (err == EDS_ERR_DEVICE_NOT_FOUND)
      return ERR_NO_CAMERA;

   // event handlers are static functions that need a reference to this camera object to function
   // provide that static ref here.  This approach will fail with multiple cameras.  In that case,
   // consider making a map with cameras and references to our CanonEDCamera objects
   g_Self = this;

   // Set event handler
   if(err == EDS_ERR_OK)
   {
      err = EdsSetObjectEventHandler(camera_,  kEdsObjectEvent_All, &CanonEDCamera::handleObjectEvent,  NULL);
   }

   // Set event handler
   if(err == EDS_ERR_OK)
   {
      err = EdsSetPropertyEventHandler(camera_,  kEdsPropertyEvent_All, &CanonEDCamera::handlePropertyEvent,  NULL);
   }

   // Set event handler
   if(err == EDS_ERR_OK)
   {
      err = EdsSetCameraStateEventHandler(camera_,  kEdsStateEvent_All, &CanonEDCamera::handleStateEvent,  NULL);
   }

   if(err == EDS_ERR_OK)
   {
      err = EdsOpenSession(camera_);
   }

   // Camera name
   if (err == EDS_ERR_OK)
   {
      EdsDeviceInfo  deviceInfo;
      err = EdsGetDeviceInfo(camera_, &deviceInfo);
      if (err == EDS_ERR_OK)
      {
         std::ostringstream os;
         os << "Canon SLR device subtype: " << deviceInfo.deviceSubType;
         LogMessage(os.str().c_str());
         if (deviceInfo.deviceSubType == 0)
            isLegacy_ = true;
         cameraModel_ = deviceInfo.szDeviceDescription;
         int nRet = CreateProperty("Model", cameraModel_.c_str(), MM::String, true);
         if (nRet != DEVICE_OK)
            return nRet;
      }

      // Set and Get various camera properties

      // lock the UI before setting properties - only needed on legacy cameras
      if (isLegacy_)
         EdsSendStatusCommand (camera_,  kEdsCameraStatusCommand_UILock, 0);
      EdsSaveTo toPC = kEdsSaveTo_Host;
      err = EdsSetPropertyData(camera_,  kEdsPropID_SaveTo, 0 , sizeof(EdsSaveTo),  &toPC);
      if (isLegacy_)
         EdsSendStatusCommand (camera_, kEdsCameraStatusCommand_UIUnLock, 0);
   }

   if (err == EDS_ERR_OK)
   {
      CPropertyAction* pAct = new CPropertyAction(this, &CanonEDCamera::OnBinning);
      int nRet = CreateProperty(MM::g_Keyword_Binning, "1", MM::Integer, false, pAct);
      if (nRet != DEVICE_OK)
         return nRet;
   }

   if (err == EDS_ERR_OK)
   {
      return DEVICE_OK;
   }

   std::ostringstream os;
   os << "Error during initialization: " << std::hex << err;
   LogMessage(os.str().c_str());

   return err;
}

EdsError  CanonEDCamera::getFirstCamera(EdsCameraRef  *camera)
{
    EdsError err = EDS_ERR_OK;
    EdsCameraListRef  cameraList = NULL;
    EdsUInt32  count = 0;

    // Get camera list
    err = EdsGetCameraList(&cameraList);

    // Get number of cameras
    if(err == EDS_ERR_OK)
    {
       err = EdsGetChildCount(cameraList,  &count);
       if(count == 0)
       {
          err = EDS_ERR_DEVICE_NOT_FOUND;
       }
    }

    // Get first camera retrieved
   if(err == EDS_ERR_OK)
   {
       err = EdsGetChildAtIndex(cameraList ,  0 ,  camera);
   }

   // Release camera list
   if(cameraList != NULL)
   {
      EdsRelease(cameraList);
      cameraList = NULL;
   }

   return err;

}

int CanonEDCamera::EdsToMMError(EdsError err)
{
   if (err == EDS_ERR_OK)
      return DEVICE_OK;

   std::ostringstream os;
   os << "Canon driver reported error: " << std::hex << err;
   LogMessage(os.str().c_str());

   return ERR_DRIVER;
}

EdsError EDSCALLBACK CanonEDCamera::handleObjectEvent( EdsObjectEvent event, EdsBaseRef  object, EdsVoid * context)
{
   printf ("Object Event triggered\n");

   CanonEDCamera* mmCanon = (CanonEDCamera*) g_Self;

   switch(event)
   {
      case kEdsObjectEvent_DirItemRequestTransfer:
         {
            EdsError err = EDS_ERR_OK;
            EdsStreamRef stream = NULL;

            EdsDirectoryItemInfo dirItemInfo;
            err = EdsGetDirectoryItemInfo(object, &dirItemInfo);

            // do we need to notify the camera?
            /*
             if (err == EDS_ERR_OK)
             {
             CameraEvent e("DownloadStart");
             _model->notifyObservers(&e);
             }
             */

            if (err == EDS_ERR_OK)
            {
               //err = EdsCreateFileStream(dirItemInfo.szFileName, kEdsFileCreateDisposition_CreateAlways, kEdsAccess_ReadWrite, &stream);
               err = EdsCreateMemoryStream(0, &stream);
            }

            // Set Progress Callback???

            // Download Image
            if (err == EDS_ERR_OK)
            {
               err = EdsDownload(object,  dirItemInfo.size, stream);
            }

            if (err == EDS_ERR_OK)
            {
               err = EdsDownloadComplete(object);
            }

            EdsImageRef imageRef = NULL;

            if (err == EDS_ERR_OK)
            {
               err = EdsCreateImageRef(stream, &imageRef);
            }

            EdsImageInfo imageInfo;

            if (err == EDS_ERR_OK)
            {
               err = EdsGetImageInfo(imageRef, kEdsImageSrc_FullView, &imageInfo);
            }
            if (err == EDS_ERR_OK)
            {
               printf ("Image Width: %d\n", imageInfo.width);
            }

         }
         break;

         default:

         break;
      }

   // Object must be released
   if(object)
   {
      EdsRelease(object);
   }
}

EdsError EDSCALLBACK  CanonEDCamera::handlePropertyEvent (EdsPropertyEvent event, EdsPropertyID  property, EdsUInt32 param, EdsVoid * context)
{
   printf ("Property Event triggered\n");
   CanonEDCamera* mmCanon = (CanonEDCamera*) g_Self;
    // do something
}

EdsError EDSCALLBACK  CanonEDCamera::handleStateEvent (EdsStateEvent event, EdsUInt32 parameter, EdsVoid * context)
{
   printf ("Camera State Event triggered\n");
   CanonEDCamera* mmCanon = (CanonEDCamera*) g_Self;
   // do something
}

// MMCamera API
int CanonEDCamera::SnapImage()
{
   EdsError err = EdsSendCommand(camera_, kEdsCameraCommand_TakePicture , 0);
   if (err != EDS_ERR_OK)
      return EdsToMMError(err);

   return DEVICE_OK;
}

const unsigned char* CanonEDCamera::GetImageBuffer()
{
   return 0;
}

unsigned CanonEDCamera::GetImageWidth() const
{
   return 0;
}

unsigned CanonEDCamera::GetImageHeight() const
{
   return 0;
}

unsigned CanonEDCamera::GetImageBytesPerPixel() const
{
   return 0;
}

unsigned CanonEDCamera::GetBitDepth() const
{
   return 0;
}

long CanonEDCamera::GetImageBufferSize() const
{
   return 0;
}

double CanonEDCamera::GetExposure() const
{
   return 0;
}

void CanonEDCamera::SetExposure(double exp)
{
}

int CanonEDCamera::SetROI(unsigned x, unsigned y, unsigned xSize, unsigned ySize)
{
   return DEVICE_OK;
}

int CanonEDCamera::GetROI(unsigned& x, unsigned& y, unsigned& xSize, unsigned& ySize)
{
   return DEVICE_OK;
}

int CanonEDCamera::ClearROI()
{
   return DEVICE_OK;
}

int CanonEDCamera::StartSequenceAcquisition(double interval)
{
   return DEVICE_OK;
}

int CanonEDCamera::StartSequenceAcquisition(long numImages, double interval_ms, bool stopOnOverflow)
{
   return DEVICE_OK;
}

int CanonEDCamera::StopSequenceAcquisition()
{
   return DEVICE_OK;
}

int CanonEDCamera::InsertImage()
{
   return DEVICE_OK;
}

/*
int CanonEDCamera::ThreadRun()
{
   return DEVICE_OK;
}
*/

bool CanonEDCamera::IsCapturing()
{
   return false;
}

int CanonEDCamera::GetBinning() const
{
   return 1;
}

int CanonEDCamera::SetBinning(int bS)
{
   return DEVICE_OK;
}

// action interface
int CanonEDCamera::OnBinning(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   return DEVICE_OK;
}

int CanonEDCamera::OnPixelType(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   return DEVICE_OK;
}

int CanonEDCamera::OnBitDepth(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   return DEVICE_OK;
}

int CanonEDCamera::OnReadoutTime(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   return DEVICE_OK;
}

int CanonEDCamera::OnCameraCCDXSize(MM::PropertyBase* , MM::ActionType )
{
   return DEVICE_OK;
}

int CanonEDCamera::OnCameraCCDYSize(MM::PropertyBase* , MM::ActionType )
{
   return DEVICE_OK;
}

<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

/************************************************************************
**
**	Set up the various dprintf variables based on the configuration file.
**
************************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_string.h"
#include "condor_sys_types.h"
#include "dprintf_internal.h"

#if HAVE_BACKTRACE
#include "sig_install.h"
#endif

int		Termlog = 0;

extern int		DebugFlags;
extern FILE		*DebugFPs[D_NUMLEVELS+1];
extern std::vector<DebugFileInfo> *DebugLogs;
extern char		*DebugLock;
extern const char		*_condor_DebugFlagNames[];
extern int		_condor_dprintf_works;
extern time_t	DebugLastMod;
extern int		DebugUseTimestamps;
extern int      DebugContinueOnOpenFailure;
extern int		log_keep_open;

extern void		_condor_set_debug_flags( const char *strflags );
extern void		_condor_dprintf_saved_lines( void );

param_functions *dprintf_param_funcs = NULL;

#if HAVE_EXT_GCB
void	_condor_gcb_dprintf_va( int flags, char* fmt, va_list args );
extern "C" void Generic_set_log_va(void(*app_log_va)(int level, char *fmt, va_list args));
#endif

#if HAVE_BACKTRACE
static void
sig_backtrace_handler(int signum)
{
	dprintf_dump_stack();

		// terminate for the same reason.
	struct sigaction sa;
	sa.sa_handler = SIG_DFL;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sigaction(signum, &sa, NULL);
	sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);

	raise(signum);
}

static void
install_backtrace_handler(void)
{
	sigset_t fullset;
	sigfillset( &fullset );
	install_sig_handler_with_mask(SIGSEGV, &fullset, sig_backtrace_handler);
	install_sig_handler_with_mask(SIGABRT, &fullset, sig_backtrace_handler);
	install_sig_handler_with_mask(SIGILL, &fullset, sig_backtrace_handler);
	install_sig_handler_with_mask(SIGFPE, &fullset, sig_backtrace_handler);
	install_sig_handler_with_mask(SIGBUS, &fullset, sig_backtrace_handler);
}
#endif

int
dprintf_config_ContinueOnFailure ( int fContinue )
{
    int fOld = DebugContinueOnOpenFailure;
	DebugContinueOnOpenFailure = fContinue;
	return fOld;
}

void
dprintf_config( const char *subsys, param_functions *p_funcs )
{
	char pname[ BUFSIZ ];
	char *pval;
	static int first_time = 1;
	int want_truncate;
	int debug_level;
	FILE *debug_file_fp;
	int log_open_default = TRUE;
	std::vector<DebugFileInfo> *debugLogsOld = DebugLogs;
	bool debug_zero = false;	//This indicates whether debug level zero has been initialized.

	DebugLogs = new std::vector<DebugFileInfo>();
	if(!dprintf_param_funcs)
		dprintf_param_funcs = new param_functions();

	/*
	 * The duplication of the param_function instance is to ensure no one else can change
	 * the data structure out from under dprintf.  It is also to prevent transfer of ownership/
	 * responsibility for the block of memory used to store the function pointers.
	 */
	if(p_funcs)
	{
		dprintf_param_funcs->set_param_func(p_funcs->get_param_func());
		dprintf_param_funcs->set_param_bool_int_func(p_funcs->get_param_bool_int_func());
		dprintf_param_funcs->set_param_wo_default_func(p_funcs->get_param_wo_default_func());
	}

	/*
	**  We want to initialize this here so if we reconfig and the
	**	debug flags have changed, we actually use the new
	**  flags.  -Derek Wright 12/8/97
	*/
	DebugFlags = D_ALWAYS;

	/*
	** First, add the debug flags that are shared by everyone.
	*/
	pval = dprintf_param_funcs->param("ALL_DEBUG");
	if( pval ) {
		_condor_set_debug_flags( pval );
		free( pval );
	}

	/*
	**  Then, pick up the subsys_DEBUG parameters.   Note: if we don't have
	**  anything set, we just leave it as D_ALWAYS.
	*/
	(void)sprintf(pname, "%s_DEBUG", subsys);
	pval = dprintf_param_funcs->param(pname);
	if( pval ) {
		_condor_set_debug_flags( pval );
		free( pval );
	}

#ifdef WIN32
		/* Two reasons why we need to lock the log in Windows
		 * (when a lock is configured)
		 * 1) File rotation requires exclusive access in Windows.
		 * 2) O_APPEND doesn't guarantee atomic writes in Windows
		 */
	DebugShouldLockToAppend = 1;
#else
	DebugShouldLockToAppend = dprintf_param_funcs->param_boolean_int("LOCK_DEBUG_LOG_TO_APPEND",0);
#endif

	/*
	**	If this is not going to the terminal, pick up the name
	**	of the log file, maximum log size, and the name of the
	**	lock file (if it is specified).
	*/
	if( !( Termlog) ) {
		std::vector<DebugFileInfo>::iterator it;	//iterator indicating the file we got to.
		for (debug_level = 0; debug_level <= D_NUMLEVELS; debug_level++) {
			std::string logPath;
			want_truncate = 0;
			if (debug_level == 0) {
				/*
				** the level 0 file gets all debug messages; thus, the
				** offset into DebugFlagNames is off by one, since the
				** first level-specific file goes into the other arrays at
				** index 1
				*/
				(void)sprintf(pname, "%s_LOG", subsys);
			} else {
				(void)sprintf(pname, "%s_%s_LOG", subsys,
							  _condor_DebugFlagNames[debug_level-1]+2);
			}

			// Hold a temporary copy of the old file pointer until
			// *after* the param -- param can dprintf() in some cases
			{
				// NEGOTIATOR_MATCH_LOG is necessary by default, but debug_level
				// is not 0
				char *logPathParam = NULL;
				bool file_found = false;
				if(debug_level == 0)
				{
					logPathParam = param(pname);

					// No default value found, so use $(LOG)/$(SUBSYSTEM)Log
					if(!logPathParam) {
						char *str;
						char *log = param("LOG");
						char *lsubsys = param("SUBSYSTEM");
						if(!log || !lsubsys) {
							EXCEPT("Unable to find LOG or SUBSYSTEM.\n");
						}

						sprintf(logPath, "%s%c%sLog", log, DIR_DELIM_CHAR, lsubsys);

						free(log);
						free(lsubsys);
					}
					else {
						logPath.insert(0, logPathParam);
					}
				}
				else {
					// This is looking up configuration options that I can't
					// find documentation for, so instead of coding in an
					// incorrect default value, I'm gonna use
					// param_without_default.
					// tristan 5/29/09
					logPathParam = param_without_default(pname);
					if(logPathParam)
						logPath.insert(0, logPathParam);
				}

				if(!logPath.empty())
				{
					if(!DebugLogs->empty())
					{
						for(it = DebugLogs->begin(); it < DebugLogs->end(); it++)
						{
							if(it->logPath != logPath)
								continue;
							it->debugFlags |= debug_level;
							file_found = true;
							break;
						}
					}
					if(!file_found)
					{
						DebugFileInfo logFileInfo;
						logFileInfo.debugFlags = debug_level;
						logFileInfo.logPath = logPath;
						it = DebugLogs->insert(DebugLogs->end(), logFileInfo);
					}
				}

				if(logPathParam)
				{
					free(logPathParam);
					logPathParam = NULL;
				}
			}

			debug_zero = true;

			if( debug_level == 0 && !debug_zero ) {
				EXCEPT("No '%s' parameter specified.", pname);
			} else if ( !logPath.empty() ) {

				if (debug_level == 0 && first_time) {
					struct stat stat_buf;
					if ( stat( logPath.c_str(), &stat_buf ) >= 0 ) {
						DebugLastMod = stat_buf.st_mtime > stat_buf.st_ctime ? stat_buf.st_mtime : stat_buf.st_ctime;
					} else {
						DebugLastMod = -errno;
					}
				}

				if (debug_level == 0) {
					(void)sprintf(pname, "TRUNC_%s_LOG_ON_OPEN", subsys);
				} else {
					(void)sprintf(pname, "TRUNC_%s_%s_LOG_ON_OPEN", subsys,
								  _condor_DebugFlagNames[debug_level-1]+2);
				}
				want_truncate = param_boolean_crufty(pname, false) ? 1 : 0;

				if (debug_level == 0) {
					(void)sprintf(pname, "%s_LOCK", subsys);
					if (DebugLock) {
						free(DebugLock);
					}
					DebugLock = param(pname);
				}

				if( first_time && want_truncate ) {
					debug_file_fp = debug_lock(debug_level, "wN", 0);
				} else {
					debug_file_fp = debug_lock(debug_level, "aN", 0);
				}

				if( debug_file_fp == NULL && debug_level == 0 ) {
                   #ifdef WIN32
					/*
					** If we could not open the log file, we might want to keep running anyway.
					** If we do, then set the log filename to NUL so we don't keep trying
					** (and failing) to open the file.
					*/
					if (DebugContinueOnOpenFailure) {

						// change the debug file to point to the NUL device.
						it->logPath.insert(0, NULL_FILE);

					} else
                   #endif
					{
					    EXCEPT("Cannot open log file '%s'",
							logPath.c_str());
					}
				}

				if (debug_file_fp) (void)debug_unlock( debug_level );
				debug_file_fp = NULL;

				if (debug_level == 0) {
					(void)sprintf(pname, "MAX_%s_LOG", subsys);
				} else {
					(void)sprintf(pname, "MAX_%s_%s_LOG", subsys,
								  _condor_DebugFlagNames[debug_level-1]+2);
				}

                off_t maxlog = 0;
				pval = param(pname);
				if (pval != NULL) {
                    // because there is nothing like param_long_long() or param_off_t()
                    bool r = lex_cast(pval, maxlog);
                    if (!r || (maxlog < 0)) {
                        EXCEPT("Invalid config: %s = %s", pname, pval);
                    }
                    it->maxLog = maxlog;
					free(pval);
				} else {
					it->maxLog = 1024*1024;
				}

				if (debug_level == 0) {
					(void)sprintf(pname, "MAX_NUM_%s_LOG", subsys);
				} else {
					(void)sprintf(pname, "MAX_NUM_%s_%s_LOG", subsys,
								  _condor_DebugFlagNames[debug_level-1]+2);
				}

				pval = param(pname);
				if (pval != NULL) {
					it->maxLogNum = param_integer(pname, 1, 0);
					free(pval);
				} else {
					it->maxLogNum = 1;
				}
			}
		}
	} else {

#if !defined(WIN32)
		setlinebuf( stderr );
#endif

		(void)fflush( stderr );	/* Don't know why we need this, but if not here
							   the first couple dprintf don't come out right */
	}

#ifndef WIN32
	if((strcmp(subsys, "SHADOW") == 0) || (strcmp(subsys, "GRIDMANAGER") == 0))
	{
		log_open_default = FALSE;
	}
#endif

	if(!DebugLock) {
		sprintf(pname, "%s_LOG_KEEP_OPEN", subsys);
		log_keep_open = dprintf_param_funcs->param_boolean_int(pname, log_open_default);
	}

	first_time = 0;
	_condor_dprintf_works = 1;
#if HAVE_EXT_GCB
		/*
		  this method currently only lives in libGCB.a, so don't even
		  try to param() or call this function unless we're on a
		  platform where we're using the GCB external
		*/
    if ( dprintf_param_funcs->param_boolean_int("NET_REMAP_ENABLE", 0) ) {
        Generic_set_log_va(_condor_gcb_dprintf_va);
    }
#endif

		/*
		  If LOGS_USE_TIMESTAMP is enabled, we will print out Unix timestamps
		  instead of the standard date format in all the log messages
		*/
	DebugUseTimestamps = dprintf_param_funcs->param_boolean_int( "LOGS_USE_TIMESTAMP", FALSE );

#if HAVE_BACKTRACE
	install_backtrace_handler();
#endif

	if(debugLogsOld)
	{
		delete debugLogsOld;
	}

	_condor_dprintf_saved_lines();
}

#if HAVE_EXT_GCB
void
_condor_gcb_dprintf_va( int flags, char* fmt, va_list args )
{
	char* new_fmt;
	int len;

	len = strlen(fmt);
	new_fmt = (char*) malloc( (len + 6) * sizeof(char) );
	if( ! new_fmt ) {
		EXCEPT( "_condor_gcb_dprintf_va() out of memory!" );
	}
	snprintf( new_fmt, len + 6, "GCB: %s", fmt );
	_condor_dprintf_va( flags, new_fmt, args );
	free( new_fmt );
}
#endif /* HAVE_EXT_GCB */
<commit_msg>Fix major oversight where we could drop all debug levels besides D_ALWAYS.  Ticket #2306.<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

/************************************************************************
**
**	Set up the various dprintf variables based on the configuration file.
**
************************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_string.h"
#include "condor_sys_types.h"
#include "dprintf_internal.h"

#if HAVE_BACKTRACE
#include "sig_install.h"
#endif

int		Termlog = 0;

extern int		DebugFlags;
extern FILE		*DebugFPs[D_NUMLEVELS+1];
extern std::vector<DebugFileInfo> *DebugLogs;
extern char		*DebugLock;
extern const char		*_condor_DebugFlagNames[];
extern int		_condor_dprintf_works;
extern time_t	DebugLastMod;
extern int		DebugUseTimestamps;
extern int      DebugContinueOnOpenFailure;
extern int		log_keep_open;

extern void		_condor_set_debug_flags( const char *strflags );
extern void		_condor_dprintf_saved_lines( void );

param_functions *dprintf_param_funcs = NULL;

#if HAVE_EXT_GCB
void	_condor_gcb_dprintf_va( int flags, char* fmt, va_list args );
extern "C" void Generic_set_log_va(void(*app_log_va)(int level, char *fmt, va_list args));
#endif

#if HAVE_BACKTRACE
static void
sig_backtrace_handler(int signum)
{
	dprintf_dump_stack();

		// terminate for the same reason.
	struct sigaction sa;
	sa.sa_handler = SIG_DFL;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sigaction(signum, &sa, NULL);
	sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);

	raise(signum);
}

static void
install_backtrace_handler(void)
{
	sigset_t fullset;
	sigfillset( &fullset );
	install_sig_handler_with_mask(SIGSEGV, &fullset, sig_backtrace_handler);
	install_sig_handler_with_mask(SIGABRT, &fullset, sig_backtrace_handler);
	install_sig_handler_with_mask(SIGILL, &fullset, sig_backtrace_handler);
	install_sig_handler_with_mask(SIGFPE, &fullset, sig_backtrace_handler);
	install_sig_handler_with_mask(SIGBUS, &fullset, sig_backtrace_handler);
}
#endif

int
dprintf_config_ContinueOnFailure ( int fContinue )
{
    int fOld = DebugContinueOnOpenFailure;
	DebugContinueOnOpenFailure = fContinue;
	return fOld;
}

void
dprintf_config( const char *subsys, param_functions *p_funcs )
{
	char pname[ BUFSIZ ];
	char *pval;
	static int first_time = 1;
	int want_truncate;
	int debug_level;
	FILE *debug_file_fp;
	int log_open_default = TRUE;
	std::vector<DebugFileInfo> *debugLogsOld = DebugLogs;
	bool debug_zero = false;	//This indicates whether debug level zero has been initialized.

	DebugLogs = new std::vector<DebugFileInfo>();
	if(!dprintf_param_funcs)
		dprintf_param_funcs = new param_functions();

	/*
	 * The duplication of the param_function instance is to ensure no one else can change
	 * the data structure out from under dprintf.  It is also to prevent transfer of ownership/
	 * responsibility for the block of memory used to store the function pointers.
	 */
	if(p_funcs)
	{
		dprintf_param_funcs->set_param_func(p_funcs->get_param_func());
		dprintf_param_funcs->set_param_bool_int_func(p_funcs->get_param_bool_int_func());
		dprintf_param_funcs->set_param_wo_default_func(p_funcs->get_param_wo_default_func());
	}

	/*
	**  We want to initialize this here so if we reconfig and the
	**	debug flags have changed, we actually use the new
	**  flags.  -Derek Wright 12/8/97
	*/
	DebugFlags = D_ALWAYS;

	/*
	** First, add the debug flags that are shared by everyone.
	*/
	pval = dprintf_param_funcs->param("ALL_DEBUG");
	if( pval ) {
		_condor_set_debug_flags( pval );
		free( pval );
	}

	/*
	**  Then, pick up the subsys_DEBUG parameters.   Note: if we don't have
	**  anything set, we just leave it as D_ALWAYS.
	*/
	(void)sprintf(pname, "%s_DEBUG", subsys);
	pval = dprintf_param_funcs->param(pname);
	if( pval ) {
		_condor_set_debug_flags( pval );
		free( pval );
	}

#ifdef WIN32
		/* Two reasons why we need to lock the log in Windows
		 * (when a lock is configured)
		 * 1) File rotation requires exclusive access in Windows.
		 * 2) O_APPEND doesn't guarantee atomic writes in Windows
		 */
	DebugShouldLockToAppend = 1;
#else
	DebugShouldLockToAppend = dprintf_param_funcs->param_boolean_int("LOCK_DEBUG_LOG_TO_APPEND",0);
#endif

	/*
	**	If this is not going to the terminal, pick up the name
	**	of the log file, maximum log size, and the name of the
	**	lock file (if it is specified).
	*/
	if( !( Termlog) ) {
		std::vector<DebugFileInfo>::iterator it;	//iterator indicating the file we got to.
		for (debug_level = 0; debug_level <= D_NUMLEVELS; debug_level++) {
			std::string logPath;
			want_truncate = 0;
			if (debug_level == 0) {
				/*
				** the level 0 file gets all debug messages; thus, the
				** offset into DebugFlagNames is off by one, since the
				** first level-specific file goes into the other arrays at
				** index 1
				*/
				(void)sprintf(pname, "%s_LOG", subsys);
			} else {
				(void)sprintf(pname, "%s_%s_LOG", subsys,
							  _condor_DebugFlagNames[debug_level-1]+2);
			}

			// Hold a temporary copy of the old file pointer until
			// *after* the param -- param can dprintf() in some cases
			{
				// NEGOTIATOR_MATCH_LOG is necessary by default, but debug_level
				// is not 0
				char *logPathParam = NULL;
				bool file_found = false;
				if(debug_level == 0)
				{
					logPathParam = param(pname);

					// No default value found, so use $(LOG)/$(SUBSYSTEM)Log
					if(!logPathParam) {
						char *str;
						char *log = param("LOG");
						char *lsubsys = param("SUBSYSTEM");
						if(!log || !lsubsys) {
							EXCEPT("Unable to find LOG or SUBSYSTEM.\n");
						}

						sprintf(logPath, "%s%c%sLog", log, DIR_DELIM_CHAR, lsubsys);

						free(log);
						free(lsubsys);
					}
					else {
						logPath.insert(0, logPathParam);
					}
				}
				else {
					// This is looking up configuration options that I can't
					// find documentation for, so instead of coding in an
					// incorrect default value, I'm gonna use
					// param_without_default.
					// tristan 5/29/09
					logPathParam = param_without_default(pname);
					if(logPathParam)
						logPath.insert(0, logPathParam);
				}

				if(!logPath.empty())
				{
					if(!DebugLogs->empty())
					{
						for(it = DebugLogs->begin(); it < DebugLogs->end(); it++)
						{
							if(it->logPath != logPath)
								continue;
							it->debugFlags |= debug_level;
							file_found = true;
							break;
						}
					}
					if(!file_found)
					{
						DebugFileInfo logFileInfo;
						if(!debug_level)
							logFileInfo.debugFlags = DebugFlags;
						else
							logFileInfo.debugFlags = debug_level;
						logFileInfo.logPath = logPath;
						it = DebugLogs->insert(DebugLogs->end(), logFileInfo);
					}
				}

				if(logPathParam)
				{
					free(logPathParam);
					logPathParam = NULL;
				}
			}

			debug_zero = true;

			if( debug_level == 0 && !debug_zero ) {
				EXCEPT("No '%s' parameter specified.", pname);
			} else if ( !logPath.empty() ) {

				if (debug_level == 0 && first_time) {
					struct stat stat_buf;
					if ( stat( logPath.c_str(), &stat_buf ) >= 0 ) {
						DebugLastMod = stat_buf.st_mtime > stat_buf.st_ctime ? stat_buf.st_mtime : stat_buf.st_ctime;
					} else {
						DebugLastMod = -errno;
					}
				}

				if (debug_level == 0) {
					(void)sprintf(pname, "TRUNC_%s_LOG_ON_OPEN", subsys);
				} else {
					(void)sprintf(pname, "TRUNC_%s_%s_LOG_ON_OPEN", subsys,
								  _condor_DebugFlagNames[debug_level-1]+2);
				}
				want_truncate = param_boolean_crufty(pname, false) ? 1 : 0;

				if (debug_level == 0) {
					(void)sprintf(pname, "%s_LOCK", subsys);
					if (DebugLock) {
						free(DebugLock);
					}
					DebugLock = param(pname);
				}

				if( first_time && want_truncate ) {
					debug_file_fp = debug_lock(debug_level, "wN", 0);
				} else {
					debug_file_fp = debug_lock(debug_level, "aN", 0);
				}

				if( debug_file_fp == NULL && debug_level == 0 ) {
                   #ifdef WIN32
					/*
					** If we could not open the log file, we might want to keep running anyway.
					** If we do, then set the log filename to NUL so we don't keep trying
					** (and failing) to open the file.
					*/
					if (DebugContinueOnOpenFailure) {

						// change the debug file to point to the NUL device.
						it->logPath.insert(0, NULL_FILE);

					} else
                   #endif
					{
					    EXCEPT("Cannot open log file '%s'",
							logPath.c_str());
					}
				}

				if (debug_file_fp) (void)debug_unlock( debug_level );
				debug_file_fp = NULL;

				if (debug_level == 0) {
					(void)sprintf(pname, "MAX_%s_LOG", subsys);
				} else {
					(void)sprintf(pname, "MAX_%s_%s_LOG", subsys,
								  _condor_DebugFlagNames[debug_level-1]+2);
				}

                off_t maxlog = 0;
				pval = param(pname);
				if (pval != NULL) {
                    // because there is nothing like param_long_long() or param_off_t()
                    bool r = lex_cast(pval, maxlog);
                    if (!r || (maxlog < 0)) {
                        EXCEPT("Invalid config: %s = %s", pname, pval);
                    }
                    it->maxLog = maxlog;
					free(pval);
				} else {
					it->maxLog = 1024*1024;
				}

				if (debug_level == 0) {
					(void)sprintf(pname, "MAX_NUM_%s_LOG", subsys);
				} else {
					(void)sprintf(pname, "MAX_NUM_%s_%s_LOG", subsys,
								  _condor_DebugFlagNames[debug_level-1]+2);
				}

				pval = param(pname);
				if (pval != NULL) {
					it->maxLogNum = param_integer(pname, 1, 0);
					free(pval);
				} else {
					it->maxLogNum = 1;
				}
			}
		}
	} else {

#if !defined(WIN32)
		setlinebuf( stderr );
#endif

		(void)fflush( stderr );	/* Don't know why we need this, but if not here
							   the first couple dprintf don't come out right */
	}

#ifndef WIN32
	if((strcmp(subsys, "SHADOW") == 0) || (strcmp(subsys, "GRIDMANAGER") == 0))
	{
		log_open_default = FALSE;
	}
#endif

	if(!DebugLock) {
		sprintf(pname, "%s_LOG_KEEP_OPEN", subsys);
		log_keep_open = dprintf_param_funcs->param_boolean_int(pname, log_open_default);
	}

	first_time = 0;
	_condor_dprintf_works = 1;
#if HAVE_EXT_GCB
		/*
		  this method currently only lives in libGCB.a, so don't even
		  try to param() or call this function unless we're on a
		  platform where we're using the GCB external
		*/
    if ( dprintf_param_funcs->param_boolean_int("NET_REMAP_ENABLE", 0) ) {
        Generic_set_log_va(_condor_gcb_dprintf_va);
    }
#endif

		/*
		  If LOGS_USE_TIMESTAMP is enabled, we will print out Unix timestamps
		  instead of the standard date format in all the log messages
		*/
	DebugUseTimestamps = dprintf_param_funcs->param_boolean_int( "LOGS_USE_TIMESTAMP", FALSE );

#if HAVE_BACKTRACE
	install_backtrace_handler();
#endif

	if(debugLogsOld)
	{
		delete debugLogsOld;
	}

	_condor_dprintf_saved_lines();
}

#if HAVE_EXT_GCB
void
_condor_gcb_dprintf_va( int flags, char* fmt, va_list args )
{
	char* new_fmt;
	int len;

	len = strlen(fmt);
	new_fmt = (char*) malloc( (len + 6) * sizeof(char) );
	if( ! new_fmt ) {
		EXCEPT( "_condor_gcb_dprintf_va() out of memory!" );
	}
	snprintf( new_fmt, len + 6, "GCB: %s", fmt );
	_condor_dprintf_va( flags, new_fmt, args );
	free( new_fmt );
}
#endif /* HAVE_EXT_GCB */
<|endoftext|>


<commit_before>#include "terminal.h"

#include <termios.h>
#include <unistd.h>

#include "filefinder.h"
#include "options.h"

terminal::terminal(){
  // save and copy terminal settings
  tcgetattr( STDIN_FILENO, &oldt);
  newt = oldt;

  // set new terminal settings
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr( STDIN_FILENO, TCSANOW, &newt);

  // print as many newlines as number_of_result_lines to
  // enable moving the cursor up and down.
  for(int i=0; i < options.number_of_result_lines; ++i){
    fprintf(stderr,"\n");
  }
  cursor_up(options.number_of_result_lines);
  save_cursor_pos();
  restore_cursor_pos();
}

terminal::~terminal(){
  // restore terminal settings
  tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
}

void terminal::save_cursor_pos() const{
  fprintf(stderr,"\033[s");
}

void terminal::restore_cursor_pos() const{
  fprintf(stderr,"\033[u");
}

void terminal::erase_line() const{
  fprintf(stderr,"\033[K");
}

void terminal::cursor_left(int n) const{
  fprintf(stderr,"\033[%dD",n);
}

void terminal::cursor_right(int n) const{
  fprintf(stderr,"\033[%dC",n);
}

void terminal::cursor_up(int n) const{
  fprintf(stderr,"\033[%dA",n);
}

void terminal::cursor_down(int n) const{
  fprintf(stderr,"\033[%dB",n);
}

void terminal::print_search_line(std::string str, int pos) const{
  restore_cursor_pos();
  erase_line();
  fprintf(stderr,">%s", str.c_str());
  restore_cursor_pos();
  cursor_right(1+pos);
}

void terminal::print_result(const std::vector<node>& result, std::size_t selected) const{
  restore_cursor_pos();
  for(int i=0; i < options.number_of_result_lines; ++i){
    fprintf(stderr,"\n");
    erase_line();
  }
  restore_cursor_pos();

  for(std::size_t i=1; i <= result.size(); ++i){
    fprintf(stderr,"\n");
    if(i-1==selected) fprintf(stderr,"\033[7m");
    fprintf(stderr,"%lu: %s%s",(unsigned long)i,result[i-1].location.c_str(), result[i-1].filename.c_str());
    if(i-1==selected) fprintf(stderr,"\033[0m");
  }
}
<commit_msg>Update terminal.cpp<commit_after>#include "terminal.h"

#include <termios.h>
#include <unistd.h>

#include "filefinder.h"
#include "options.h"

terminal::terminal(){
  // save old terminal settings
  tcgetattr( STDIN_FILENO, &oldt);
  newt = oldt;

  // set new terminal settings
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr( STDIN_FILENO, TCSANOW, &newt);

  // print as many newlines as number_of_result_lines to
  // enable moving the cursor up and down.
  for(int i=0; i < options.number_of_result_lines; ++i){
    fprintf(stderr,"\n");
  }
  cursor_up(options.number_of_result_lines);
  save_cursor_pos();
  restore_cursor_pos();
}

terminal::~terminal(){
  // restore old terminal settings
  tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
}

void terminal::save_cursor_pos() const{
  fprintf(stderr,"\033[s");
}

void terminal::restore_cursor_pos() const{
  fprintf(stderr,"\033[u");
}

void terminal::erase_line() const{
  fprintf(stderr,"\033[K");
}

void terminal::cursor_left(int n) const{
  fprintf(stderr,"\033[%dD",n);
}

void terminal::cursor_right(int n) const{
  fprintf(stderr,"\033[%dC",n);
}

void terminal::cursor_up(int n) const{
  fprintf(stderr,"\033[%dA",n);
}

void terminal::cursor_down(int n) const{
  fprintf(stderr,"\033[%dB",n);
}

void terminal::print_search_line(std::string str, int pos) const{
  restore_cursor_pos();
  erase_line();
  fprintf(stderr,">%s", str.c_str());
  restore_cursor_pos();
  cursor_right(1+pos);
}

void terminal::print_result(const std::vector<node>& result, std::size_t selected) const{
  restore_cursor_pos();
  for(int i=0; i < options.number_of_result_lines; ++i){
    fprintf(stderr,"\n");
    erase_line();
  }
  restore_cursor_pos();

  for(std::size_t i=1; i <= result.size(); ++i){
    fprintf(stderr,"\n");
    if(i-1==selected) fprintf(stderr,"\033[7m");
    fprintf(stderr,"%lu: %s%s",(unsigned long)i,result[i-1].location.c_str(), result[i-1].filename.c_str());
    if(i-1==selected) fprintf(stderr,"\033[0m");
  }
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_ocb_indir_setup_linear.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file p8_ocb_indir_setup_linear.C
/// @brief  Configure OCB Channel for Linear Streaming or Non-streaming mode

// *HWP HWP Owner       : Amit Kumar <akumar3@us.ibm.com>
// *HWP Backup HWP Owner:
// *HWP FW Owner        : Bilicon Patil <bilpatil@in.ibm.com>
// *HWP Team            : PM
// *HWP Level           : 1
// *HWP Consumed by     : HS

/// High-level procedure flow:
/// @verbatim
///  Setup specified channel to linear streaming or non-streaming mode by
///  calling proc proc_ocb_init
///
///  Procedure Prereq:
///     - System clocks are running
/// @endverbatim
///
//------------------------------------------------------------------------------

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------

#include <p9_pm.H>
#include <p9_pm_ocb_indir_setup_linear.H>

// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------
fapi2::ReturnCode p9_pm_ocb_indir_setup_linear(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    p9ocb::P9_OCB_CHAN_NUM  i_ocb_chan,
    p9ocb::P9_OCB_CHAN_TYPE i_ocb_type,
    const uint32_t      i_ocb_bar)
{
    FAPI_IMP("Entering...");
    FAPI_DBG("For channel %x as type %x, OCB Bar %x",
             i_ocb_chan, i_ocb_type, i_ocb_bar);

    return fapi2::FAPI2_RC_SUCCESS;
}
<commit_msg>JET: Level 2, Make p9_pm_ocb_init FAPI 2.0 compliant<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_ocb_indir_setup_linear.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file p8_ocb_indir_setup_linear.C
/// @brief  Configure OCB Channel for Linear Streaming or Non-streaming mode

// *HWP HWP Owner       : Amit Kumar <akumar3@us.ibm.com>
// *HWP Backup HWP Owner:
// *HWP FW Owner        : Bilicon Patil <bilpatil@in.ibm.com>
// *HWP Team            : PM
// *HWP Level           : 1
// *HWP Consumed by     : HS

/// High-level procedure flow:
/// @verbatim
///  Setup specified channel to linear streaming or non-streaming mode by
///  calling proc proc_ocb_init
///
///  Procedure Prereq:
///     - System clocks are running
/// @endverbatim
///
//------------------------------------------------------------------------------

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------

#include <p9_pm.H>
#include <p9_pm_ocb_indir_setup_linear.H>

// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------
fapi2::ReturnCode p9_pm_ocb_indir_setup_linear(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    p9ocb::PM_OCB_CHAN_NUM  i_ocb_chan,
    p9ocb::PM_OCB_CHAN_TYPE i_ocb_type,
    const uint32_t      i_ocb_bar)
{
    FAPI_IMP("Entering...");
    FAPI_DBG("For channel %x as type %x, OCB Bar %x",
             i_ocb_chan, i_ocb_type, i_ocb_bar);

    return fapi2::FAPI2_RC_SUCCESS;
}
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013-2015, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

#include "examples/HelloSPTP.cpp" // run()
#include "gtest/gtest.h"

namespace testing {

TEST(HelloSPTPTest, performance) {
  using namespace examples;
  run();
}

} //ns
<commit_msg>tiny cleanup<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013-2015, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

#include "examples/HelloSPTP.cpp" // run()
#include "gtest/gtest.h"

namespace testing {

TEST(HelloSPTPTest, performance) {
  examples::run();
}

} //ns
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: scmdstrm.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:25:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif

#ifndef _SCMDSTRM_HXX
#include "scmdstrm.hxx"
#endif
#include "svcommstream.hxx"
#include "rcontrol.hxx"

#if OSL_DEBUG_LEVEL > 1
#ifndef _EDITWIN_HXX
#include "editwin.hxx"
#endif
#include "statemnt.hxx"
#endif

SCmdStream::SCmdStream(SvStream *pIn)
{
    pSammel = pIn;
    pCommStream = new SvCommStream( pSammel );
//  SetCommStream( pCommStream );
}

SCmdStream::~SCmdStream()
{
    delete pCommStream;
}

void SCmdStream::Read (String* &pString)
{
    if ( !pString )
        pString = new String();
    comm_UniChar* pStr;
    USHORT nLenInChars;
    CmdBaseStream::Read( pStr, nLenInChars );

    *pString = String( pStr, nLenInChars );
    delete [] pStr;
}

void SCmdStream::Read (String &aString)
{
    comm_UniChar* pStr;
    USHORT nLenInChars;
    CmdBaseStream::Read( pStr, nLenInChars );

    aString = String( pStr, nLenInChars );
    delete [] pStr;
}

void SCmdStream::Read ( SfxPoolItem *&pItem )
{
    USHORT nType;
    USHORT nId;
    Read(nId);
#if OSL_DEBUG_LEVEL > 1
        StatementList::m_pDbgWin->AddText( "Parameter: " );
        StatementList::m_pDbgWin->AddText( String::CreateFromInt32( nId ) );
        StatementList::m_pDbgWin->AddText( " " );
#endif
    Read( nType );
    switch (nType)
    {
        case BinUSHORT:
            {
                USHORT nNr;
                Read (nNr );
                pItem = new SfxUInt16Item(nId,nNr);
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "USHORT:" );
                StatementList::m_pDbgWin->AddText( String::CreateFromInt32( nNr ) );
#endif
            }
            break;
        case BinULONG:
            {
                ULONG nNr;
                Read (nNr );
                pItem = new SfxUInt32Item(nId,nNr);
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "ULONG:" );
                StatementList::m_pDbgWin->AddText( String::CreateFromInt64( nNr ) );
#endif
            }
            break;
        case BinString:
            {
                String aString;
                Read (aString);

                pItem = new SfxStringItem(nId,aString);
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "String:" );
                StatementList::m_pDbgWin->AddText( aString );
#endif
            }
            break;
        case BinBool:
            {
                BOOL bBool;
                Read (bBool);
                pItem = new SfxBoolItem(nId,bBool);
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "BOOL:" );
                StatementList::m_pDbgWin->AddText( bBool ? "TRUE" : "FALSE" );
#endif
            }
            break;
        default:
            DBG_ERROR1( "Ungltiger Typ im Stream:%hu", nType );
#if OSL_DEBUG_LEVEL > 1
            StatementList::m_pDbgWin->AddText( "Ungltiger Typ !!!! " );
#endif
            break;
    }
#if OSL_DEBUG_LEVEL > 1
        StatementList::m_pDbgWin->AddText( "\n" );
#endif
}

void SCmdStream::Read ( ::com::sun::star::beans::PropertyValue &rItem )
{
    USHORT nType;
    String aId;
    Read(aId);
    rItem.Name = rtl::OUString( aId );
#if OSL_DEBUG_LEVEL > 1
        StatementList::m_pDbgWin->AddText( "Parameter: " );
        StatementList::m_pDbgWin->AddText( aId );
        StatementList::m_pDbgWin->AddText( " " );
#endif
    nType = GetNextType();
    switch (nType)
    {
        case BinUSHORT:
            {
                USHORT nNr;
                Read (nNr );
                rItem.Value <<= nNr;
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "USHORT:" );
                StatementList::m_pDbgWin->AddText( String::CreateFromInt32( nNr ) );
#endif
            }
            break;
        case BinULONG:
            {
                ULONG nNr;
                Read (nNr );
                rItem.Value <<= nNr;
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "ULONG:" );
                StatementList::m_pDbgWin->AddText( String::CreateFromInt64( nNr ) );
#endif
            }
            break;
        case BinString:
            {
                String aString;
                Read (aString);
                rItem.Value <<= ::rtl::OUString( aString );
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "String:" );
                StatementList::m_pDbgWin->AddText( aString );
#endif
            }
            break;
        case BinBool:
            {
                BOOL bBool;
                Read (bBool);
                rItem.Value <<= bBool;
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "BOOL:" );
                StatementList::m_pDbgWin->AddText( bBool ? "TRUE" : "FALSE" );
#endif
            }
            break;
        default:
            DBG_ERROR1( "Ungltiger Typ im Stream:%hu", nType );
#if OSL_DEBUG_LEVEL > 1
            StatementList::m_pDbgWin->AddText( "Ungltiger Typ !!!! " );
#endif
            break;
    }
#if OSL_DEBUG_LEVEL > 1
        StatementList::m_pDbgWin->AddText( "\n" );
#endif
}

<commit_msg>INTEGRATION: CWS sixtyfour05 (1.4.30); FILE MERGED 2006/04/13 10:31:53 cmc 1.4.30.1: #i63183# automation 64bit fixes<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: scmdstrm.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-04-19 13:58:35 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif

#ifndef _SCMDSTRM_HXX
#include "scmdstrm.hxx"
#endif
#include "svcommstream.hxx"
#include "rcontrol.hxx"

#if OSL_DEBUG_LEVEL > 1
#ifndef _EDITWIN_HXX
#include "editwin.hxx"
#endif
#include "statemnt.hxx"
#endif

SCmdStream::SCmdStream(SvStream *pIn)
{
    pSammel = pIn;
    pCommStream = new SvCommStream( pSammel );
//  SetCommStream( pCommStream );
}

SCmdStream::~SCmdStream()
{
    delete pCommStream;
}

void SCmdStream::Read (String* &pString)
{
    if ( !pString )
        pString = new String();
    comm_UniChar* pStr;
    USHORT nLenInChars;
    CmdBaseStream::Read( pStr, nLenInChars );

    *pString = String( pStr, nLenInChars );
    delete [] pStr;
}

void SCmdStream::Read (String &aString)
{
    comm_UniChar* pStr;
    USHORT nLenInChars;
    CmdBaseStream::Read( pStr, nLenInChars );

    aString = String( pStr, nLenInChars );
    delete [] pStr;
}

void SCmdStream::Read ( SfxPoolItem *&pItem )
{
    USHORT nType;
    USHORT nId;
    Read(nId);
#if OSL_DEBUG_LEVEL > 1
        StatementList::m_pDbgWin->AddText( "Parameter: " );
        StatementList::m_pDbgWin->AddText( String::CreateFromInt32( nId ) );
        StatementList::m_pDbgWin->AddText( " " );
#endif
    Read( nType );
    switch (nType)
    {
        case BinUSHORT:
            {
                comm_USHORT nNr;
                Read (nNr );
                pItem = new SfxUInt16Item(nId,nNr);
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "USHORT:" );
                StatementList::m_pDbgWin->AddText( String::CreateFromInt32( nNr ) );
#endif
            }
            break;
        case BinULONG:
            {
                comm_ULONG nNr;
                Read (nNr );
                pItem = new SfxUInt32Item(nId,nNr);
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "ULONG:" );
                StatementList::m_pDbgWin->AddText( String::CreateFromInt64( nNr ) );
#endif
            }
            break;
        case BinString:
            {
                String aString;
                Read (aString);

                pItem = new SfxStringItem(nId,aString);
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "String:" );
                StatementList::m_pDbgWin->AddText( aString );
#endif
            }
            break;
        case BinBool:
            {
                comm_BOOL bBool;
                Read (bBool);
                pItem = new SfxBoolItem(nId,bBool);
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "BOOL:" );
                StatementList::m_pDbgWin->AddText( bBool ? "TRUE" : "FALSE" );
#endif
            }
            break;
        default:
            DBG_ERROR1( "Ungltiger Typ im Stream:%hu", nType );
#if OSL_DEBUG_LEVEL > 1
            StatementList::m_pDbgWin->AddText( "Ungltiger Typ !!!! " );
#endif
            break;
    }
#if OSL_DEBUG_LEVEL > 1
        StatementList::m_pDbgWin->AddText( "\n" );
#endif
}

void SCmdStream::Read ( ::com::sun::star::beans::PropertyValue &rItem )
{
    USHORT nType;
    String aId;
    Read(aId);
    rItem.Name = rtl::OUString( aId );
#if OSL_DEBUG_LEVEL > 1
        StatementList::m_pDbgWin->AddText( "Parameter: " );
        StatementList::m_pDbgWin->AddText( aId );
        StatementList::m_pDbgWin->AddText( " " );
#endif
    nType = GetNextType();
    switch (nType)
    {
        case BinUSHORT:
            {
                comm_USHORT nNr;
                Read (nNr );
                rItem.Value <<= nNr;
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "USHORT:" );
                StatementList::m_pDbgWin->AddText( String::CreateFromInt32( nNr ) );
#endif
            }
            break;
        case BinULONG:
            {
                comm_ULONG nNr;
                Read (nNr );
                rItem.Value <<= nNr;
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "ULONG:" );
                StatementList::m_pDbgWin->AddText( String::CreateFromInt64( nNr ) );
#endif
            }
            break;
        case BinString:
            {
                String aString;
                Read (aString);
                rItem.Value <<= ::rtl::OUString( aString );
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "String:" );
                StatementList::m_pDbgWin->AddText( aString );
#endif
            }
            break;
        case BinBool:
            {
                comm_BOOL bBool;
                Read (bBool);
                rItem.Value <<= bBool;
#if OSL_DEBUG_LEVEL > 1
                StatementList::m_pDbgWin->AddText( "BOOL:" );
                StatementList::m_pDbgWin->AddText( bBool ? "TRUE" : "FALSE" );
#endif
            }
            break;
        default:
            DBG_ERROR1( "Ungltiger Typ im Stream:%hu", nType );
#if OSL_DEBUG_LEVEL > 1
            StatementList::m_pDbgWin->AddText( "Ungltiger Typ !!!! " );
#endif
            break;
    }
#if OSL_DEBUG_LEVEL > 1
        StatementList::m_pDbgWin->AddText( "\n" );
#endif
}

<|endoftext|>