コード例 #1
0
void DodecaudionOSCBridgeApp::guiEvent(ofxUIEventArgs &e)
{
    std::cout << e.widget->getID() << " / " << e.widget->getParent()->getName() << " / " << e.widget->getName() <<  std::endl;
      
    //init new serial port
    if(e.widget->getParent()->getName() == UI_SERIAL_PORT_SELECT_DROPDOWN_NAME){
        ofxUIDropDownList *dropdown = (ofxUIDropDownList *) e.widget;
        string serialPath = e.widget->getName();
        initSerialPort(serialPath, serialPortBaudRateCurrent);
        //dropdown->setToggleVisibility( false );
    }
    
    if( e.widget->getName() == UI_DODECAUDION_CALIBRATE_TOGGLE_NAME ){
        ofxUIToggle *toggle = (ofxUIToggle *) e.widget;
        isCalibrating = toggle->getValue();
        calibrationStartFrame = ofGetFrameNum();
    }
    if( e.widget->getName() == UI_DODECAUDION_DRAW_PLOTS_TOGGLE_NAME ){
        ofxUIToggle *toggle = (ofxUIToggle *) e.widget;
        drawPlots = toggle->getValue();
    }
    if( e.widget->getName() == UI_OSC_HOST_TEXTINPUT_NAME ){
        ofxUITextInput *textfield = (ofxUITextInput *) e.widget;
        string oscHostToSet = textfield->getTextString();
        initOSC(oscHostToSet, oscPortCurrent);
    }
    if( e.widget->getName() == UI_OSC_PORT_TEXTINPUT_NAME ){
        ofxUITextInput *textfield = (ofxUITextInput *) e.widget;
        int oscPortToSet = atoi(textfield->getTextString().c_str());
        initOSC(oscHostCurrent, oscPortToSet);
    }

}
コード例 #2
0
ファイル: serialShims.c プロジェクト: DanIverson/OpenVnmrJ
initSerialShims()
{
	int	ival;

	if (shimPort >= 0) {
		close( shimPort );
	}

	shimPort = initSerialPort( SERIAL_PORT_NUMBER );
        setSerialTimeout(shimPort,25);	/* set timeout to 1/4 sec */

	if (shimPort < 0)
	  return( -1 );

	if (pShimMutex == NULL)  
        {
           pShimMutex = semMCreate(SEM_Q_PRIORITY | SEM_INVERSION_SAFE |
                                        SEM_DELETE_SAFE);
        }

	ival = testSerialShims( shimPort );
	if ((ival == -1) || (ival == TIMEOUT))
        {
		close( shimPort );
		shimPort = -1;
		return( -1 );
	}

	return( 0 );
}
コード例 #3
0
int main(int argc, char *argv[]){
    initSerialPort();
    char string[] = "This is a string written to output";
    int i = 0;
    while(string[i] != '\0'){
      writeChar(string[i]);
      i++;
    }
    
    char* inputLine = readLine();
    printf("%s", inputLine);
    while(1);
}
コード例 #4
0
ファイル: guesttools.cpp プロジェクト: uwolfer/qtemu
GuestTools::GuestTools(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    blockSize = 0;
    initSerialPort();

    createActions();
    createTrayIcon();
    createModules();

    connect(port, SIGNAL(readyRead()), this, SLOT(ioReceived()));

    trayIcon->show();
}
コード例 #5
0
ファイル: mainwindow.cpp プロジェクト: f4deb/Raspberry-Pi
MainWindow::MainWindow(){

    createActions();
    createMenus();
    createToolBars();
    createCentral();
    createStatus();

    initServer();
    initSerialPort();
    initTerminalConnections();

    serial = new QSerialPort;
    //Terminal::instances()->setEtatConnexionSerial (0);
    etat_serial_port = 0;
    etat_serveur_port=0;

    setWindowTitle(tr("Titan Control Center V 0.2.3"));
}
コード例 #6
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    activeGUIMsg = new GUI_message();
    activeFIlterMsg = new FILTER_message();
    initSerialPort();
    dacDebug = NULL;
    ui->setupUi(this);
    initDials();
    initSliders();
    initButtonGroups();
    initVUMeter();
    initSeqThermo();
    initSpinBoxes();
    createConnections();
    updateOSC1();
    updateOSC2();
    updateLFO();
    updateENV();
    updateDelay();
    seq_counter = 0;

}
コード例 #7
0
ファイル: library.c プロジェクト: BaliSolutions/gibbot
// Perform initial initialization
void initalizePIC(void)
{
    initLEDs();
    initSerialPort();
}
コード例 #8
0
ファイル: serialdemo.c プロジェクト: DanIverson/OpenVnmrJ
int quartTm(int porta, int chEcho, int portb)
{
int sPort,dPort;
int QdemoInt;
int XitCode;
int sread0,swrite0,sreadd,swrited;
char sChrBuf,dChrBuf,dChrCr,dChrNl;
char sChrPer;
unsigned char *sStat;
unsigned char *sIO;
unsigned char *dStat;
unsigned char *dIO;

	QdemoInt = tyQCoDv[0].created;

	dChrNl = '\n';
	dChrCr = '\r';

	/* Resolve ambiguity of ports! if porta=0 then if portb=0 make it 4.
	*  Port 4 is to be understood as stdin.
	*/

	if( (porta == 0) && (portb == 0) ) portb = 4;

	/* check if illegal port requested */
	if( (porta == portb) || (porta > 3) || (portb > 4) ||
		 (porta < 0) || (portb < 0) )
	{
		printf("\nquartTm Qporta(0-3),echo,portb(0-3,4{4=stdin})\n");
		return(1);
	}

	printf("\nquartTm: portA=%d, portB=%d, Int=%d\n",porta,portb,QdemoInt);
	taskDelay(60);

	if(portb == 4)
	{
		sPort = open("/tyCo/0", O_RDWR, 0777);	/* open stdin */
		if(sPort < 1) return(2);
		/* Clear buffer */
		while(pifchr( sPort )) sread0 = read( sPort, &sChrBuf, 1);
	}
	else
	{
		if(QdemoInt)
		{
			sPort = initSerialPort( portb );	/* open target QUART port */
			if(sPort < 1) return(3);
			while(pifchr( sPort )) sread0 = read( sPort, &sChrBuf, 1);
		}
		else
		{
			switch(portb)
			{
				case 0:
					sStat = (unsigned char *) 0x200002;
					sIO = (unsigned char *) 0x200006;
					break;
				case 1:
					sStat = (unsigned char *) 0x200012;
					sIO = (unsigned char *) 0x200016;
					break;
				case 2:
					sStat = (unsigned char *) 0x200022;
					sIO = (unsigned char *) 0x200026;
					break;
				case 3:
					sStat = (unsigned char *) 0x200032;
					sIO = (unsigned char *) 0x200036;
					break;
	
			}
			setupQ(portb,TRUE);
			while( *sStat & 0x1 ) sChrBuf = *dIO;
		}
	}

	if(QdemoInt)
	{
		dPort = initSerialPort( porta );	/* open target QUART port */
		if(dPort < 1)
		{
			close(sPort);
			return(2);
		}
		while(pifchr( sPort )) sread0 = read( sPort, &sChrBuf, 1);
	}
	else
	{
		switch(porta)
		{
			case 0:
				dStat = (unsigned char *) 0x200002;
				dIO = (unsigned char *) 0x200006;
				break;
			case 1:
				dStat = (unsigned char *) 0x200012;
				dIO = (unsigned char *) 0x200016;
				break;
			case 2:
				dStat = (unsigned char *) 0x200022;
				dIO = (unsigned char *) 0x200026;
				break;
			case 3:
				dStat = (unsigned char *) 0x200032;
				dIO = (unsigned char *) 0x200036;
				break;

				dStat = (unsigned char *) 0x200002;
				dIO = (unsigned char *) 0x200006;
		}
		setupQ(porta,TRUE);
		while( *dStat & 0x1 ) dChrBuf = *dIO;
	}

	FOREVER
	{
		if(QdemoInt)
		{
			if(pifchr( sPort ))
			{
				sread0 = read( sPort, &sChrBuf, 1);
    		if(sread0 < 1)
				{
					XitCode = 0x24;
					break;
				}
			}
		}
		else
		{
			if( *sStat & 0x1 )
			{
				sChrBuf = *sIO;
				sread0 = 1;
			}
		}
		if(sread0 > 0)
		{
			sread0 = 0;
			if(sChrBuf == '!')
			{
				XitCode = 0x10;
				break;
			}
			if(chEcho != 0)
			{
				if(QdemoInt)
				{
					swrite0 = write( sPort, &sChrBuf, 1 );
					if(swrite0 != 1)
					{
						XitCode = 0x11;
						break;
					}
					if(sChrBuf == '\r')
					{
						swrite0 = write( sPort, &dChrNl, 1 );
						if(swrite0 != 1)
						{
							XitCode = 0x12;
							break;
						}
					}
					if(sChrBuf == '\n')
					{
						swrite0 = write( sPort, &dChrCr, 1 );
						if(swrite0 != 1)
						{
							XitCode = 0x13;
							break;
						}
					}
				}
				else
				{
					*sIO = sChrBuf;
					if(sChrBuf == '\n') *sIO = '\r';
					if(sChrBuf == '\r') *sIO = '\n';
				}
			}

			if(QdemoInt)
			{
				swrite0 = write( dPort, &sChrBuf, 1 );
				if(swrite0 != 1)
				{
					sChrPer = '0' + swrite0;
					swrite0 = write( sPort, &sChrPer, 1 );
					if(swrite0 != 1)
					{
						XitCode = 0x31;
						break;
					}
				}
				if(sChrBuf == '\r')
				{
					swrite0 = write( dPort, &dChrNl, 1 );
					if(swrite0 != 1)
					{
						XitCode = 0x15;
						break;
					}
				}
				if(sChrBuf == '\n')
				{
					swrite0 = write( dPort, &dChrCr, 1 );
					if(swrite0 != 1)
					{
						XitCode = 0x16;
						break;
					}
				}
			}
			else
			{
				*dIO = sChrBuf;
				if(sChrBuf == '\n') *dIO = '\r';
				if(sChrBuf == '\r') *dIO = '\n';
			}
		}
		
		/* Here check for character on portb */

		if(QdemoInt)
		{
			if(pifchr( dPort ))
			{
				sreadd = read( dPort, &dChrBuf, 1);
    		if(sreadd < 1)
				{
					XitCode = 0x24;
					break;
				}
			}
		}
		else
		{
			if( *dStat & 0x1 )
			{
				dChrBuf = *dIO;
				sreadd = 1;
			}
		}
		if(sreadd > 0)
		{
			sreadd = 0;
			if(dChrBuf == '!')
			{
				XitCode = 0x20;
				break;
			}

			if(chEcho != 0)
			{
				if(QdemoInt)
				{
					swrited = write( dPort, &dChrBuf, 1 );
					if(swrited != 1)
					{
						XitCode = 0x23;
						break;
					}
					if(dChrBuf == '\n')
					{
						swrited = write( dPort, &dChrCr, 1 );
						if(swrited != 1)
						{
							XitCode = 0x21;
							break;
						}
					}
					if(dChrBuf == '\r')
					{
						swrited = write( dPort, &dChrNl, 1 );
						if(swrited != 1)
						{
							XitCode = 0x22;
							break;
						}
					}
				}
				else
				{
					*dIO = dChrBuf;
					if(dChrBuf == '\n') *dIO = '\r';
					if(dChrBuf == '\r') *dIO = '\n';
				}
			}

			/* Here echo portb to porta */

			if(QdemoInt)
			{
				swrited = write( sPort, &dChrBuf, 1 );
				if(swrited != 1)
				{
					XitCode = 0x23;
					break;
				}
				if(dChrBuf == '\n')
				{
					swrited = write( sPort, &dChrCr, 1 );
					if(swrited != 1)
					{
						XitCode = 0x21;
						break;
					}
				}
				if(dChrBuf == '\r')
				{
					swrited = write( sPort, &dChrNl, 1 );
					if(swrited != 1)
					{
						XitCode = 0x22;
						break;
					}
				}
			}
			else
			{
				*sIO = dChrBuf;
				if(dChrBuf == '\n') *sIO = '\r';
				if(dChrBuf == '\r') *sIO = '\n';
			}
		} /* end if (sreadd > 0) */
		taskDelay(2);
	} /* end FOREVER */

	if( (QdemoInt) || (portb == 4) ) close(sPort);
	else setupQ(portb,FALSE);

	if(QdemoInt) close(dPort);
	else setupQ(porta,FALSE);

	return(XitCode);
} /* end quartTm */
コード例 #9
0
ファイル: pp3.c プロジェクト: jaromir-sukuba/a-p-prog
int main(int argc, char *argv[])
    {
    int i,j,pages_performed,config,econfig;
    unsigned char * pm_point, * cm_point;
    unsigned char tdat[200];
    parseArgs(argc,argv);
    if (verbose>0) printf ("PP programmer, version %s\n",PP_VERSION);
    if (verbose>1) printf ("Opening serial port\n");
    initSerialPort();
    if (sleep_time>0)
        {
        if (verbose>0) printf ("Sleeping for %d ms while arduino bootloader expires\n", sleep_time);
        fflush(stdout);
        sleep_ms (sleep_time);
        }

    for (i=0; i<PROGMEM_LEN; i++) progmem[i] = 0xFF;		//assume erased memories (0xFF)
    for (i=0; i<CONFIG_LEN; i++) config_bytes[i] = 0xFF;

    char* filename=argv[argc-1];
    pm_point = (unsigned char *)(&progmem);
    cm_point = (unsigned char *)(&config_bytes);
    parse_hex(filename,pm_point,cm_point);					//parse and write content of hex file into buffers

    //now this is ugly kludge
    //my original programmer expected only file_image holding the image of memory to be programmed
    //for PIC18, it is divided into two regions, program memory and config. to glue those two
    //different approaches, I made this. not particulary proud of having this mess
    for (i=0; i<70000; i++) file_image [i] = progmem[i];
    for (i=0; i<4; i++) file_image [2*0x8007 + i] = config_bytes[i];
    for (i=0; i<70000; i++)
        {
        if ((i%2)!=0)
            file_image[i] = 0x3F&file_image[i];
        }

    prog_enter_progmode();									//enter programming mode and probe the target
    i = prog_get_device_id();
    if (i==devid_expected)
		{
        if (verbose>0) printf ("Device ID: %4.4x \n", i);
		}
    else
        {
        printf ("Wrong device ID: %4.4x, expected: %4.4x\n", i,devid_expected);
        printf ("Check for connection to target MCU, exiting now\n");
        prog_exit_progmode();
        return 1;
        }
    //ah, I need to unify programming interfaces for PIC16 and PIC18
    if ((chip_family==CF_P18F_A)|(chip_family==CF_P18F_B)|(chip_family==CF_P18F_D)|(chip_family==CF_P18F_E))
        {
        if (program==1)
            {
            pages_performed = 0;
            if (chip_family==CF_P18F_A)						//erase whole device
                p18a_mass_erase();
            if (chip_family==CF_P18F_B)
                p18b_mass_erase();
            if (chip_family==CF_P18F_D)
                p18d_mass_erase();
            if (chip_family==CF_P18F_E)
                p18e_mass_erase();
            if (verbose>0) printf ("Programming FLASH (%d B in %d pages per %d bytes): \n",flash_size,flash_size/page_size,page_size);
            fflush(stdout);
            for (i=0; i<flash_size; i=i+page_size)
                {
                if (is_empty(progmem+i,page_size)==0)
                    {
					if ((chip_family==CF_P18F_D)|(chip_family==CF_P18F_E))
						p18d_write_page(progmem+i,i,page_size);
					else
						p18a_write_page(progmem+i,i,page_size);
                    pages_performed++;
                    if (verbose>1) 
						{
						printf ("#");
						fflush(stdout);
						}
                    }
                else if (verbose>2)
                    {
                    printf (".");
                    fflush(stdout);
                    }
                }
				
            if (verbose>0) printf ("%d pages programmed\n",pages_performed);
            if (verbose>0) printf ("Programming config\n");
            for (i=0; i<config_size; i=i+2) //write config bytes for PIC18Fxxxx and 18FxxKxx devices
				{
                if (chip_family==CF_P18F_A) p18a_write_cfg(config_bytes[i],config_bytes[i+1],0x300000+i);
                if (chip_family==CF_P18F_D) p18d_write_cfg(config_bytes[i],config_bytes[i+1],0x300000+i);
                if (chip_family==CF_P18F_E) p18d_write_cfg(config_bytes[i],config_bytes[i+1],0x300000+i);
				}
															//for PIC18FxxJxx, config bytes are at the end of FLASH memory
            }
        if (verify==1)
            {
            pages_performed = 0;
            if (verbose>0) printf ("Verifying FLASH (%d B in %d pages per %d bytes): \n",flash_size,flash_size/page_size,page_size);
            for (i=0; i<flash_size; i=i+page_size)
                {
                if (is_empty(progmem+i,page_size))
                    {
                    if (verbose>2)
                        {
                        printf ("#");
                        fflush(stdout);
                        }
                    }
                else
                    {
                    p18a_read_page(tdat,i,page_size);
                    pages_performed++;
                    if (verbose>3) printf ("Verifying page at 0x%4.4X\n",i);
                    if (verbose>1)
                        {
                        printf ("#");
                        fflush(stdout);
                        }
                    for (j=0; j<page_size; j++)
                        {
                        if (progmem[i+j] != tdat[j])
                            {
                            printf ("Error at 0x%4.4X E:0x%2.2X R:0x%2.2X\n",i+j,progmem[i+j],tdat[j]);
                            printf ("Exiting now\n");
                            prog_exit_progmode();
                            exit(0);
                            }
                        }
                    }
                }
            p18a_read_page(tdat,0x300000,page_size);
            if (verbose>0) printf ("%d pages verified\n",pages_performed);
            }
        }
    else
        {
        if (program==1)
            {
            p16a_mass_erase();
            p16a_rst_pointer();				//pointer reset is needed before every "big" operation
            if (verbose>0) printf ("Programming FLASH (%d B in %d pages)",flash_size,flash_size/page_size);
            fflush(stdout);
            for (i=0; i<flash_size; i=i+page_size)
                {
                if (verbose>1)
                    {
                    printf (".");
                    fflush(stdout);
                    }
                p16a_program_page(i,page_size,0);
                }
            if (verbose>0) printf ("\n");
            if (verbose>0) printf ("Programming config\n");
            p16a_program_config();
            }
        if (verify==1)
            {
            if (verbose>0) printf ("Verifying FLASH (%d B in %d pages)",flash_size,flash_size/page_size);
            fflush(stdout);
            p16a_rst_pointer();
            for (i=0; i<flash_size; i=i+page_size)
                {
                if (verbose>1)
                    {
                    printf (".");
                    fflush(stdout);
                    }
                p16a_read_page(tdat,page_size);
                for (j=0; j<page_size; j++)
                    {
                    if (file_image[i+j] != tdat[j])
                        {
                        printf ("Error at 0x%4.4X E:0x%2.2X R:0x%2.2X\n",i+j,file_image[i+j],tdat[j]);
                        prog_exit_progmode();
                        exit(0);
                        }
                    }
                }
            if (verbose>0) printf ("\n");
            if (verbose>0) printf ("Verifying config\n");
            config = p16a_get_config(7);
            econfig = (((unsigned int)(file_image[2*0x8007]))<<0) + (((unsigned int)(file_image[2*0x8007+1]))<<8);

            if (config==econfig)
                {
                if (verbose>1) printf ("config 1 OK: %4.4X\n",config);
                }
            else	printf ("config 1 error: E:0x%4.4X R:0x%4.4X\n",config,econfig);
            config = p16a_get_config(8);
            econfig = (((unsigned int)(file_image[2*0x8008]))<<0) + (((unsigned int)(file_image[2*0x8008+1]))<<8);
            if (config==econfig)
                {
                if (verbose>1) printf ("config 2 OK: %4.4X\n",config);
                }
            else	printf ("config 2 error: E:0x%4.4X R:0x%4.4X\n",config,econfig);
            }
        }
    prog_exit_progmode();
    return 0;
    }
コード例 #10
0
ファイル: drvLove.c プロジェクト: epics-modules/love
/****************************************************************************
 * Define public interface methods
 ****************************************************************************/
int drvLoveInit(const char* lovPort,const char* serPort,int serAddr)
{
    asynStatus sts;
    int len,attr;
    Port* plov;
    Serport* pser;
    asynUser* pasynUser;
    asynInt32* pasynInt32;
    asynUInt32Digital* pasynUInt32;

    len = sizeof(Port) + sizeof(Serport) + sizeof(asynInt32) + sizeof(asynUInt32Digital);
    len += strlen(lovPort) + strlen(serPort) + 2;
    plov = callocMustSucceed(len,sizeof(char),"drvLoveInit");

    pser = (Serport*)(plov + 1);
    pasynInt32 = (asynInt32*)(pser + 1);
    pasynUInt32 = (asynUInt32Digital*)(pasynInt32 + 1);
    plov->name = (char*)(pasynUInt32 + 1);
    pser->name = plov->name + strlen(lovPort) + 1;

    plov->isConn = 0;
    plov->pserport = pser;
    strcpy(plov->name,lovPort);

    sts = initSerialPort(plov,serPort,serAddr);
    if( ISNOTOK(sts) )
    {
        printf("drvLoveInit::failure to initialize serial port %s\n",serPort);
        free(plov);
        return( -1 );
    }

    attr = (pser->canBlock)?(ASYN_MULTIDEVICE|ASYN_CANBLOCK):ASYN_MULTIDEVICE;
    sts = pasynManager->registerPort(lovPort,attr,pser->autoConnect,0,0);
    if( ISNOTOK(sts) )
    {
        printf("drvLoveInit::failure to register love port %s\n",lovPort);
        pasynManager->disconnect(pser->pasynUser);
        pasynManager->freeAsynUser(pser->pasynUser);
        free(plov);
        return( -1 );
    }

    plov->asynCommon.interfaceType = asynCommonType;
    plov->asynCommon.pinterface = &common;
    plov->asynCommon.drvPvt = plov;

    sts = pasynManager->registerInterface(lovPort,&plov->asynCommon);
    if( ISNOTOK(sts) )
    {
        printf("drvLoveInit::failure to register asynCommon\n");
        return( -1 );
    }

    plov->asynDrvUser.interfaceType = asynDrvUserType;
    plov->asynDrvUser.pinterface = &drvuser;
    plov->asynDrvUser.drvPvt = plov;

    sts = pasynManager->registerInterface(lovPort,&plov->asynDrvUser);
    if( ISNOTOK(sts) )
    {
        printf("drvLoveInit::failure to register asynDrvUser\n");
        return( -1 );
    }

    pasynInt32->read = readInt32;
    pasynInt32->write = writeInt32;
    plov->asynInt32.interfaceType = asynInt32Type;
    plov->asynInt32.pinterface = pasynInt32;
    plov->asynInt32.drvPvt = plov;

    sts = pasynInt32Base->initialize(lovPort,&plov->asynInt32);
    if( ISNOTOK(sts) )
    {
        printf("drvLoveInit::failure to initialize asynInt32Base\n");
        return( -1 );
    }

    pasynUInt32->read = readUInt32;
    pasynUInt32->write = writeUInt32;
    plov->asynUInt32.interfaceType = asynUInt32DigitalType;
    plov->asynUInt32.pinterface = pasynUInt32;
    plov->asynUInt32.drvPvt = plov;

    sts = pasynUInt32DigitalBase->initialize(lovPort,&plov->asynUInt32);
    if( ISNOTOK(sts) )
    {
        printf("drvLoveInit::failure to initialize asynUInt32DigitalBase\n");
        return( -1 );
    }

    pasynUser = pasynManager->createAsynUser(NULL,NULL);
    if( pasynUser )
    {
        plov->pasynUser = pasynUser;
        pasynUser->userPvt = plov;
        pasynUser->timeout = K_COMTMO;
    }
    else
    {
        printf("drvLoveInit::create asynUser failure\n");
        return( -1 );
    }

    sts = pasynManager->connectDevice(pasynUser,lovPort,-1);
    if( ISNOTOK(sts) )
    {
        printf("drvLoveInit::failure to connect with device %s\n",lovPort);
        plov->isConn = 0;
        return( -1 );
    }

    pasynManager->exceptionCallbackAdd(pser->pasynUser,exceptCallback);

    if( pports )
        plov->pport = pports;
    pports = plov;

    sts = setDefaultEos(plov);
    if( ISNOTOK(sts) )
    {
        printf("drvLoveInit::failure to set %s EOS\n",lovPort);
        return( -1 );
    }

    return( 0 );
}
コード例 #11
0
ファイル: rfm12pigw.c プロジェクト: 1pilo/openhab
int main(int argc, char **argv)
{
    char *device = "/dev/ttyAMA0";
    char *address = "127.0.0.1";

    char defaultcmd[20] = "8b 200g";
    char *initcmd = defaultcmd;

    int port = 9997;
    int c;
    
    opterr = 0;
    
    while ((c = getopt (argc, argv, "hvd:a:p:i:")) != -1)
        switch (c)
    {
        case 'v':
            verbose++;
            break;
            
        case 'd':
            device = optarg;
            break;
            
        case 'a':
            address = optarg;
            break;
            
        case 'p':
            port = atoi(optarg);
            break;

        case 'i':
            initcmd = optarg;
            break;
            
        case '?':
            if (optopt == 'd' || optopt == 'a' || optopt == 'p')
                fprintf (stderr, "Option -%c requires an argument.\n", optopt);
            else if (isprint (optopt))
                fprintf (stderr, "Unknown option `-%c'.\n", optopt);
            else
                fprintf (stderr,
                         "Unknown option character `\\x%x'.\n",
                         optopt);
            return 1;
            
        case 'h':
        default:
            printUsage(argv[0]);
            return 1;
    }
    
    // Install signal handlers
    signal(SIGINT, signalCallbackHandler);
    
    int serialport_fd = -1;
    int udp_fd = -1;
    
    // Initialize destination address
    struct sockaddr_in dest;
    dest.sin_family = AF_INET;
    dest.sin_addr.s_addr = inet_addr(address);
    dest.sin_port = htons(port);
    
    #define MAX_DATA_LEN 200
    
    unsigned char buffer[MAX_DATA_LEN];
    unsigned char message[MAX_DATA_LEN];
    
    for (;;)
    {
        /*
         * Error tolerant solution.
         *
         * Try to open serial port and udp socket on every round,
         * if open has failed.
         *
         */
        
        if ( serialport_fd < 0 )
        {
            // Open the serial port
            if (verbose) printf("open serial port: %s\n", device);
            serialport_fd = open(device, O_RDWR | O_NOCTTY ); // | O_NDELAY
            
            if (serialport_fd < 0)
            {
                fprintf(stderr, "Failed to open %s: %s\n", device, strerror(errno));
                //return 1;
            }
            
            // Initialize serial port
            if (initSerialPort(serialport_fd) == -1)
            {
                fprintf(stderr, "Failed to set serial port: %s\n", strerror(errno));
                close(serialport_fd);
            }
            
            // Initialize RFM12Pi
            if (verbose) printf("Whole initialization command '%s'\n", initcmd);
            sleep(1);
            
            char *cmd = strtok(initcmd, " ");
            while (cmd != NULL)
            {
                if (verbose) printf("Write initialization command '%s'\n", cmd);
                
                if (write(serialport_fd, cmd, sizeof(cmd)) != sizeof(cmd))
                {
                    fprintf(stderr, "Failed to initialize RFM12Pi: %s\n", strerror(errno));
                    close(serialport_fd);
                }
                
                sleep(1);
                cmd = strtok(NULL, " ");
            }
            
            tcflush(serialport_fd, TCIOFLUSH);
        }
        
        
        if ( udp_fd < 0 )
        {
            // Open UDP socket
            udp_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
            
            if (udp_fd < 0)
            {
                fprintf(stderr, "Failed to open UDP socket: %s\n", strerror(errno));
                //return 1;
            }
            
            if (verbose) printf("UDP address %s:%u\n", address, port);
            
        }
        
        int msg_len = 0;
        
        // ignore first message
        int ignore_message = 1;
        
        if (serialport_fd > 0)
        {
            ssize_t len = 0;
            
            while ((len = read(serialport_fd, buffer, MAX_DATA_LEN)) > 0)
            {
                if (verbose > 3) 
                {
                	printf("read %u bytes from serial port: ", len);
                	printData( "", buffer, len, "\n");
                }
                
                for (int i = 0; i < len; i++)
                {
                    if (verbose > 4) printf("%u: 0x%02X\n", i, buffer[i]);
                    
                    if (buffer[i] == 0x0D || buffer[i] == 0x0A )
                    {
                    	if (msg_len > 0 && ignore_message == 0)
                    	{
                    		if (verbose > 1)
                    		{
								printf("sending UDP data to %s:%u", address, port);
								printData( ", data: ", message, msg_len, "\n");
							}
								
							if (sendto(udp_fd, message, msg_len, 0 , (struct sockaddr *)&dest, sizeof(dest)) == -1)
							{
								fprintf(stderr, "Failed to send udp packet: %s\n", strerror(errno));
							}
                    	}
                    	
                    	ignore_message = 0;
                    	msg_len = 0;
                    }
                    else
                    {
                    	if (msg_len > MAX_DATA_LEN)
                    	{
                    		fprintf(stderr, "too long message\n");
                    		
                    		ignore_message = 1;
                    		msg_len = 0;
                    	}
                    	else
                    	{
                    		message[msg_len++] = buffer[i];	
                    	}
                    }
                    
                }
            }
            
            if (len < 0 )
            {
                if (errno == EINTR)
                {
                    if (verbose) printf("Interrupted\n");
                    break;
                }
                else
                {
                    fprintf(stderr, "Read failed: %s\n", strerror(errno));
                    sleep(1);
                }
            }
            else if (len == 0)
            {
                if (verbose) printf("Read return 0\n");
            }
        }
        else
        {
            sleep(1);
        }
    }
    
    close(serialport_fd);
    close(udp_fd);
    
    return 0;
}
コード例 #12
0
ファイル: nibegw.c プロジェクト: ingen63/openhab
int main(int argc, char **argv)
{
	char *device = "/dev/ttySO";
	char *address = "127.0.0.1";
	int port = 9999;
	int c;
	
	opterr = 0;
	
	while ((c = getopt (argc, argv, "hvd:a:p:")) != -1)
		switch (c)
	{
		case 'v':
			verbose++;
			break;
			
		case 'd':
			device = optarg;
			break;
			
		case 'a':
			address = optarg;
			break;
			
		case 'p':
			port = atoi(optarg);
			break;
			
		case '?':
			if (optopt == 'd' || optopt == 'a' || optopt == 'p')
				fprintf (stderr, "Option -%c requires an argument.\n", optopt);
			else if (isprint (optopt))
				fprintf (stderr, "Unknown option `-%c'.\n", optopt);
			else
				fprintf (stderr,
						 "Unknown option character `\\x%x'.\n",
						 optopt);
			return 1;
			
		case 'h':
		default:
			printUsage(argv[0]);
			return 1;
	}
	
	// Install signal handlers
	signal(SIGINT, signalCallbackHandler);
	
	int serialport_fd = -1;
	int udp_fd = -1;
	
	// Initialize destination address
	struct sockaddr_in dest;
	dest.sin_family = AF_INET;
	dest.sin_addr.s_addr = inet_addr(address);
	dest.sin_port = htons(port);
	
	#define MAX_DATA_LEN 200
	
	unsigned char buffer[MAX_DATA_LEN];
	unsigned char message[MAX_DATA_LEN];
	
	for (;;)
	{
		/*
		 * Error tolerant solution.
		 *
		 * Try to open serial port and udp socket on every round,
		 * if open has failed.
		 *
		 */
		
		if ( serialport_fd < 0 )
		{
			// Open the serial port
			if (verbose) printf("Open serial port: %s\n", device);
			serialport_fd = open(device, O_RDWR | O_NOCTTY); // | O_NDELAY
			
			if (serialport_fd < 0)
			{
				fprintf(stderr, "Failed to open %s: %s\n", device, strerror(errno));
				//return 1;
			}
			
			// Initialize serial port
			if (initSerialPort(serialport_fd) == -1)
			{
				fprintf(stderr, "Failed to set serial port: %s\n", strerror(errno));
				//return 1;
			}
			
		}
		
		
		if ( udp_fd < 0 )
		{
			// Open UDP socket
			udp_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
			
			if (udp_fd < 0)
			{
				fprintf(stderr, "Failed to open UDP socket: %s\n", strerror(errno));
				//return 1;
			}
			
			if (verbose) printf("UDP address %s:%u\n", address, port);
			
		}
		
		int start_found = FALSE;
		int index = 0;
		
		/*
		unsigned char testdata[] = "\x01\x02" \
		"\x5C\x00\x20\x6B\x00\x4B" \
		"\x5C\x00\x20\x69\x00\x49\xC0\x69\x00\xA9" \
		"\x5C\x00\x20\x68\x50\x01\xA8\x1F\x01\x00\xA8\x64\x00\xFD" \
		"\xA7\xD0\x03\x44\x9C\x1E\x00\x4F\x9C\xA0\x00\x50\x9C\x78" \
		"\x00\x51\x9C\x03\x01\x52\x9C\x1B\x01\x87\x9C\x14\x01\x4E" \
		"\x9C\xC6\x01\x47\x9C\x01\x01\x15\xB9\xB0\xFF\x3A\xB9\x4B" \
		"\x00\xC9\xAF\x00\x00\x48\x9C\x0D\x01\x4C\x9C\xE7\x00\x4B" \
		"\x9C\x00\x00\xFF\xFF\x00\x00\xFF\xFF\x00\x00\xFF\xFF\x00" \
		"\x00\x45";
		
		ssize_t len = sizeof(testdata);
		
		memcpy( buffer, testdata, len);
		*/
		
		if (serialport_fd > 0)
		{
			ssize_t len = 0;
			
			while ((len = read(serialport_fd, buffer, MAX_DATA_LEN)) > 0)
			{
				for (int i = 0; i < len; i++)
				{
					if (verbose) printf("%02X ", buffer[i]);
					
					if (start_found == FALSE && buffer[i] == 0x5C)
					{
						start_found = TRUE;
						index = 0;
					}
					
					if (start_found)
					{
						if ((index+1) >= MAX_DATA_LEN)
						{
							start_found = FALSE;
						}
						else
						{
							message[index++] = buffer[i];
							
							int msglen = checkMessage(message, index);
							
							switch (msglen)
							{
								case 0: // Ok, but not ready
									break;
									
								case -1: // Invalid message
									start_found = FALSE;
									break;
									
								case -2: // Checksum error
									sendNak(serialport_fd);
									start_found = FALSE;
									break;
									
								default:
									if (verbose) printf("Valid message received, len=%u\n", msglen);
									
									sendAck(serialport_fd);
									
									// send UDP packet if message is a data packet
									// if data contains 0x5C (start character), message len can be bigger than 0x50 
									if (buffer[0] == 0x5C && buffer[1] == 0x00 && 
										buffer[2] == 0x20 && buffer[3] == 0x68 && 
										buffer[4] >= 0x50)
									{
										if (verbose) printf("Send UDP data to %s:%u\n", address, port);
										if (verbose) printMessage( message, msglen);
									
										if (sendto(udp_fd, message, msglen + 1, 0 , (struct sockaddr *)&dest, sizeof(dest)) == -1)
										{
											fprintf(stderr, "Failed to send udp packet: %s\n", strerror(errno));
										}
									}

									// Wait new message
									start_found = FALSE;
									break;
							}
						}
						
					}
					
				}
			}
			
			if (len < 0 )
			{
				if (errno == EINTR)
				{
					if (verbose) printf("Interrupted\n");
					break;
				}
				else
				{
					fprintf(stderr, "Read failed: %s\n", strerror(errno));
					sleep(1);
				}
			}
			else if (len == 0)
			{
				if (verbose) printf("Read return 0\n");
			}
		}
		else
		{
			sleep(1);
		}
	}
	
	close(serialport_fd);
	close(udp_fd);
	
	return 0;
}