コード例 #1
0
int asCRestore::Save() 
{
	unsigned long i, count;

	// structTypes[]
	count = module->structTypes.GetLength();
	WRITE_NUM(count);
	for( i = 0; i < count; ++i )
	{
		WriteObjectTypeDeclaration(module->structTypes[i]);
	}

	// usedTypeIndices[]
	count = module->usedTypes.GetLength();
	WRITE_NUM(count);
	for( i = 0; i < count; ++i )
	{
		WriteObjectType(module->usedTypes[i]);
	}

	// scriptGlobals[]
	count = module->scriptGlobals.GetLength();
	WRITE_NUM(count);
	for( i = 0; i < count; ++i ) 
		WriteProperty(module->scriptGlobals[i]);

	// globalMem size (can restore data using @init())
	count = module->globalMem.GetLength();
	WRITE_NUM(count);
	
	// globalVarPointers[]
	WriteGlobalVarPointers();

	// initFunction
	WriteFunction(&module->initFunction);

	// scriptFunctions[]
	count = module->scriptFunctions.GetLength();
	WRITE_NUM(count);
	for( i = 0; i < count; ++i )
		WriteFunction(module->scriptFunctions[i]);

	// stringConstants[]
	count = module->stringConstants.GetLength();
	WRITE_NUM(count);
	for( i = 0; i < count; ++i ) 
		WriteString(module->stringConstants[i]);

	// importedFunctions[] and bindInformations[]
	count = module->importedFunctions.GetLength();
	WRITE_NUM(count);
	for( i = 0; i < count; ++i )
	{
		WriteFunction(module->importedFunctions[i]);
		WRITE_NUM(module->bindInformations[i].importFrom);
	}

	// usedTypeIds[]
	WriteUsedTypeIds();

	return asSUCCESS;
}
コード例 #2
0
ファイル: Ini.cpp プロジェクト: gregggdavis/ww-merging-cpp
BOOL CIni::WriteChar(LPCTSTR lpSection, LPCTSTR lpKey, TCHAR c) const
{
	TCHAR sz[2] = { c, _T('\0') };
	return WriteString(lpSection, lpKey, sz);
}
コード例 #3
0
ファイル: NetMessage.cpp プロジェクト: afa311/eddyserver
	void NetMessage::WriteLenghtAndString(const std::string &value)
	{
		WriteUInt32(value.length());
		WriteString(value);
	}
コード例 #4
0
main()
{
    // Disable JTAG (on RA0 and RA1 )
    mJTAGPortEnable( DEBUG_JTAGPORT_OFF );

    // Configure the device for maximum performance but do not change the PBDIV
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option above..
    SYSTEMConfig(GetSystemClock(), SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    initializeUART();
    initializeADC();
    initializeLCD();
    initializeRPG();
    
    /* Initialize SD card */
    setup_SDSPI();
    SD_setStart();
    /* Fill tempBuffer[] with int 0 to 63
     * Write it to the current block.
     * Empty tempBuffer[] to all 0.
     * Read from the current block to make sure that it returns the right value.
     */
    fillTempBuffer();
    testSDReadWrite(tempBuffer);

    curr_read_block = curr_block;
    
    ConfigTimer1(); // Enable Timer1 for second counts
    configureInterrupts();

    // T2CON = 0x8030; // TMR1 on, prescale 1:256 PB

    mPORTASetPinsDigitalOut( LED_MASK ); // LEDs = output
    mPORTDSetPinsDigitalIn( PB_MASK_D ); // PBs on D = input

    curr_state = READY;
    // enable interrupts
    INTEnableInterrupts();
    int i = 0;
    while( 1 )
    {
        if (getPrintToUARTFlag() == 1){
            LCDMenuControl();
        
            //mPORTAToggleBits( LED_MASK );
            convertAndPrintIntegerToString("i => ", i++);
            convertAndPrintIntegerToString("timeElapse => ", timeElapsed);
            convertAndPrintIntegerToString("timeElapsedLEDSample => ", timeElapsedLEDSample);
            convertAndPrintIntegerToString("timeElapsedLEDTurnedOff => ", timeElapsedLEDTurnedOff);
            convertAndPrintIntegerToString("sampleLEDNow => ", sampleLEDNow);

            convertAndPrintIntegerToString(" ADC Value => ", getChannel5Value());
            printShadowDetect();
            printLightLevel();
            drawLightDetectedBar();
            controlPowerRelay();

            switch(curr_state) {
            case READY : WriteString("State => READY     ");
                        break;
            case SLEEP : WriteString("State => SLEEP    ");
                        break;
            case HIBERNATE : WriteString("State => HIBERNATE");
                        break;
            case BUSY : WriteString("State => BUSY     ");
                        break;
            }

            WriteString("\r");
            
            setPrintToUARTFlag(0);
        }
        if (NEW_BYTE_RECEIVED == 1){
            curr_state = READY;
            NEW_BYTE_RECEIVED = 0;
            //mPORTAToggleBits( LED_MASK );
            char tempArray[] = "g";
            tempArray[0] = characterByteReceived;
            WriteString(tempArray);
            if(curr_state = HIBERNATE) {
                addByteToBuffer(characterByteReceived);
            }
            else {
                PutCharacter(characterByteReceived);
            }
        }
        if(bufferIndex == 512) {
            SDWriteBlock(currBlock);
            currBlock++;
            bufferIndex = 0;
        }
         if((curr_state == READY) && (timeElapsed >= SLEEP_TIMEOUT) && (timeElapsed < HIBERNATE_TIMEOUT)) {
             curr_state = SLEEP;
         }
         else if((curr_state == SLEEP) && (timeElapsed >= HIBERNATE_TIMEOUT)) {
             curr_state = HIBERNATE;
             timeElapsed = 0;
         }
        if (transmitDataFromSDCard == 1) {
            transmitDataFromSDCard = 0;
            forwardDataToPrinter();
        }
    } // main (while) loop

    return 0;

} // main
コード例 #5
0
ファイル: bbPlugin+.cpp プロジェクト: Jmos/bbclean-xzero450
void BBP_write_string(struct plugin_info *PI, const char *rcs, const char *val)
{
    char buffer[256];
    if (PI->rc_key)
        WriteString(PI->rcpath, make_key(buffer, PI, rcs), val);
}
コード例 #6
0
ファイル: MainFormUnit.cpp プロジェクト: jeeb/kirikiri2
//---------------------------------------------------------------------------
void __fastcall tTVPProfileHolder::WriteStrings(const AnsiString &section,
	const AnsiString &ident, TStrings * strings)
{
	WriteString(section, ident, TVPEscapeAnsiString(strings->Text));
}
コード例 #7
0
void DataString::Write(Buffer *buf, const DataString *s)
{
  WriteString(buf, s->m_value, s->m_value_length);
}
コード例 #8
0
int main(int argc,char **argv)
{
	int MySocket,MyControlPort;
	char SocketsBuffer[SOCKETS_BUFFER_SIZE];
	struct sockaddr_in MyAddress,MyControlAddress;
	unsigned int ControlPort;
	int status;
	int retval;
	
	// Create socket (allocate resources)
	if((MySocket=socket(
		PF_INET, // IPv4
		SOCK_STREAM, // TCP
		0))==-1) {
 		printf("Error: Unable to create socket (%i)...\n",errno);
		perror("sockets"); // Print error message based on errno
		exit(1);
	}
	
	// Establish TCP connection
	memset(&MyAddress,0,sizeof(struct sockaddr_in)); // Set structure to zero
	MyAddress.sin_family=PF_INET; // IPv4
	MyAddress.sin_port=htons(SOCKETS_PORT); // Port number (in network order)
	MyAddress.sin_addr.s_addr=
		inet_addr(SOCKETS_IP_ADDRESS); // IP address (in network order)
	if(connect(MySocket,(struct sockaddr *)&MyAddress,
		sizeof(struct sockaddr_in))==-1) {
		printf("Error: Unable to establish connection to socket (%i)...\n",
			errno);
		perror("sockets"); // Print error message based on errno
		exit(1);
	}
	
	// Minimize latency by setting TCP_NODELAY option
	SetNODELAY(MySocket);
	
	// Clear status and reset instrument
	WriteString(MySocket,"*CLS;*RST\n");

	// Get instrument's ID string
	WriteString(MySocket,"*IDN?\n");
	ReadString(MySocket,SocketsBuffer);
	printf("Instrument ID: %s\n",SocketsBuffer);
	
	// Ask for control port
	WriteString(MySocket,"SYST:COMM:TCPIP:CONTROL?\n");
	if(ReadString(MySocket,SocketsBuffer)==0)
	{
		printf("Warning: No response from instrument (control port).\n");
		retval=0;
		goto SocketMainClose;
	}
	sscanf(SocketsBuffer,"%u",&ControlPort);
	printf("Control Port: %u\n",ControlPort);
	
	// Create socket for control port
	if((MyControlPort=socket(PF_INET,SOCK_STREAM,0))==-1)
	{
		printf("Error: Unable to create control port socket (%i)...\n",errno);
		perror("sockets"); // Print error message based on errno
		retval=1;
		goto SocketMainClose;
	}

	// Establish TCP connection to control port
	memset(&MyControlAddress,0,
		sizeof(struct sockaddr_in)); // Set structure to zero
	MyControlAddress.sin_family=PF_INET; // IPv4
	MyControlAddress.sin_port=
		htons(ControlPort); // Port number (in network order)
	MyControlAddress.sin_addr.s_addr=
		inet_addr(SOCKETS_IP_ADDRESS); // IP address (in network order)
	if(connect(MyControlPort,(struct sockaddr *)&MyControlAddress,
		sizeof(struct sockaddr_in))==-1) {
		printf(
			"Error: Unable to establish connection to control port (%i)...\n",
			errno);
		perror("sockets"); // Print error message based on errno
		retval=1;	
		goto SocketMainClose;
	}
	
	// Do a device clear
	DeviceClear(MyControlPort,SocketsBuffer);
	
	// Demonstrate SRQ... First, tell the instrument when to generate an SRQ
	// NOTE: The following commands are dependant of the instrument
	// This example is for the Agilent L4410A, L4411A,34410A or 34411A
	WriteString(MySocket,
		"*ESE 1\n"); // Operation Complete causes Standard Event
	WriteString(MySocket,
		"*SRE 32\n"); // Standard Event causes SRQ
	
	// Now perform some operation(s) and raise SRQ when done
	WriteString(MySocket,"CONF:FREQ\n"); // Go to frequency measurement mode
	WriteString(MySocket,"*OPC\n"); // Tell us when you're ready!
   
	// Now wait until data becomes available on the control link
	if(WaitForData(MyControlPort)==0)
	{
		printf("Warning: Instrument did not generate SRQ.\n");
		retval=0;
		goto SocketClose;
	}
	
	// Data available... Read and interpret!
	ReadString(MyControlPort,SocketsBuffer);
	printf("Data read on control port: %s\n",SocketsBuffer);
	if(strncmp(SocketsBuffer,"SRQ",3)!=0) {
		printf("Warning: Didn't receive an SRQ!\n");
		retval=0;
		goto SocketClose;
	}
	sscanf(SocketsBuffer,"SRQ%i",&status);
	printf("Status is: %d",status);

SocketClose:	
	
	// Close control port
	if(close(MyControlPort)==-1) {
		printf("Error: Unable to close control port socket (%i)...\n",errno);
		perror("sockets"); // Print error message based on errno
		retval=1;
	}

SocketMainClose:
	
	// Close main port
	if(close(MySocket)==-1) {
		printf("Error: Unable to close socket (%i)...\n",errno);
		perror("sockets"); // Print error message based on errno
		retval=1;;
	}

	exit(retval);
}
コード例 #9
0
ファイル: IdlePageMain.c プロジェクト: kiapper/Watch
static void DrawConnectionScreen()
{
	unsigned char const* pSwash;

    unsigned char row;
    unsigned char col;

	/* this is part of the idle update
	 * timing is controlled by the idle update timer
	 * buffer was already cleared when drawing the time
	 */
	etConnectionState cs = QueryConnectionState();
	switch (cs)
	{
	case RadioOn:
		if (QueryValidPairingInfo())
		{
			pSwash = pBootPageConnectionSwash;
		}
		else
		{
			pSwash = pBootPagePairingSwash;
		}
		break;
	case Paired:
		pSwash = pBootPageConnectionSwash;
		break;
	case Connected:
		//pSwash = pBootPageConnectionSwash;
		//break;
		// Think we should do something here?
		pSwash = pBootPageUnknownSwash;
		break;
	case Initializing:
	case ServerFailure:
	case RadioOff:
	case RadioOffLowBattery:
	case ShippingMode:
	default:
		pSwash = pBootPageBluetoothOffSwash;
		break;
	}

  CopyRowsIntoMyBuffer(pSwash ,WATCH_DRAWN_IDLE_BUFFER_ROWS+1, 32);

  /* characters are 10h then add space of 2 lines */
  row = 65;
  col = 0;
  col = WriteString(GetLocalBluetoothAddressString(),row,col,DONT_ADD_SPACE_AT_END);

  /* add the firmware version */
  row = 75;
  col = 0;
  col = WriteString("App", row, col, ADD_SPACE_AT_END);
  col = WriteString("0.0.1", row, col, ADD_SPACE_AT_END);

  /* and the stack version */
  row = 85;
  col = 0;
  col = WriteString("Stack", row, col, ADD_SPACE_AT_END);
  col = WriteString("n/a", row, col, ADD_SPACE_AT_END);

}
コード例 #10
0
void handle_request_NOTIFY(CLIENT_t *ptC, CONN_SESSION *ptSession)
{
    CONN_SESSION   *ptResp;
    BYTE           *pbMsg;

    do
    {
        // each NOTIFY message will be considered to KEEP-ALIVE message.
        ptC->n32TimeGotKA = time( (time_t *)NULL );

        // if state already inactive | x | x ..., then we need resume media plane.
        if (ptC->eState == eCLIENT_STATE_INACTIVE) {
            ptC->eState = eCLIENT_STATE_CONNECTED;

            // resume media plane
            sdp_process_type_t eClientType = (ptC == &patClient[0]) ? SDP_F : SDP_C;
            data_plane_suspend(eClientType, ptC->tMedia, SUSPEND_OFF);

        }

        // keep-alive NOTIFY. simply break-out.
        if (0 == ptSession->bMap[EVENT_SEQ_NUM]) {
            break;
        }

        BYTE *pbEvName   = &ptSession->tEvent.bName[0];
        BYTE *pbEvParams = NULL;

        // get name & params
        {
            BYTE   bLocation = 0;
            while(pbEvName[bLocation] != '\0')
            {
                bLocation++;
                if (pbEvName[bLocation] == ' ') {
                    pbEvName[bLocation++]  = '\0';
                    pbEvParams = &pbEvName[bLocation];
                    break;
                }
            }
        }

        // client request for self-state
        //if (StrICmp(ptSession->tEvent.bName, (BYTE *)"logon-state")) {
        if (StrICmp(pbEvName, (BYTE *)"logon-state")) {
            BYTE   *pbMsg = &ptSession->bBody[0];

            WriteString(&pbMsg, (BYTE *)"State: ", MAX_BODY_LTH);
            WriteString(&pbMsg, abClientState[ptC->eState], MAX_BODY_LTH);
            //&pbMsg++ = '\0';

            ptSession->wBdyLth = pbMsg - &ptSession->bBody[0];

            break;
        }

        // F request for C-list
        //else if (StrICmp(ptSession->tEvent.bName, (BYTE *)"listener-list")) {
        else if (StrICmp(pbEvName, (BYTE *)"listener-list")) {
            BYTE   *pbMsg = &ptSession->bBody[0];
            BYTE    i;
            BYTE    bString[COMMEN_LTH];

            if (ptC != &patClient[0]) {
                /* requirement update: C CAN request F'state, F CAN request C state-list.  */
                WriteString(&pbMsg, (BYTE *)"1:", COMMEN_LTH);
                WriteString(&pbMsg, (BYTE *)&patClient[0].aName[0], USER_LTH);
                if ('\0' != patClient[0].aID[0]) {
                    WriteString(&pbMsg, (BYTE *)"<", 2);
                    WriteString(&pbMsg, (BYTE *)&patClient[0].aID[0], USER_LTH);
                    WriteString(&pbMsg, (BYTE *)">", 2);
                }
                *pbMsg++ = ':';
                WriteString(&pbMsg, (BYTE *)inet_ntoa( *((struct in_addr *)&patClient[0].tAddrRemoteSignal.ip_addr) ), HOST_NAME_LTH);

                *pbMsg++ = '\r';
                *pbMsg++ = '\n';

                ptSession->wBdyLth = pbMsg - &ptSession->bBody[0];

                break;
            }

            // Now, F request C-list.

            if (!pbEvParams) {
                // only get total number

                BYTE bCnt = 0;
                for (i=1; i<MAX_CONNECT_CLIENT; i++) {
                    if (patClient[i].eState == eCLIENT_STATE_NONE) {
                        continue;
                    }

                    bCnt++;
                }

                // format as:
                //    Total: xx
                WriteString(&pbMsg, (BYTE *)"Total: ", 8);
                sprintf((char*)bString, "%d", bCnt);
                WriteString(&pbMsg, &bString[0], COMMEN_LTH);

                *pbMsg++ = '\r';
                *pbMsg++ = '\n';

            } else {
                // get No.x detail info

                BYTE bIndex = atoi((const char*)pbEvParams);
                if ( (bIndex < 1) || (bIndex >= MAX_CONNECT_CLIENT)) {
                    bIndex = 1;   // No.0 is F self.
                }

                BYTE bCnt = 0;
                BOOL8 blFound = FALSE_B8;

                for (i=1; i<MAX_CONNECT_CLIENT; i++) {
                    if (patClient[i].eState == eCLIENT_STATE_NONE) {
                        continue;
                    }

                    if (++bCnt < bIndex) {
                        continue;
                    }

                    // found
                    blFound = TRUE_B8;
                    break;

                }

                if (blFound) {
                    //     format as: "slot-No.:Name<ID>:IP"
                    // OR: format as: "index-No.:Name<ID>:IP"
                    sprintf((char*)bString, "%d", i);
                    WriteString(&pbMsg, &bString[0], COMMEN_LTH);
                    *pbMsg++ = ':';
                    WriteString(&pbMsg, (BYTE *)&patClient[i].aName[0], USER_LTH);
                    if ('\0' != patClient[i].aID[0]) {
                        WriteString(&pbMsg, (BYTE *)"<", 2);
                        WriteString(&pbMsg, (BYTE *)&patClient[i].aID[0], USER_LTH);
                        WriteString(&pbMsg, (BYTE *)">", 2);
                    }
                    *pbMsg++ = ':';
                    WriteString(&pbMsg, (BYTE *)inet_ntoa( *((struct in_addr *)&patClient[i].tAddrRemoteSignal.ip_addr) ), HOST_NAME_LTH);

                    *pbMsg++ = '\r';
                    *pbMsg++ = '\n';

                } else {
                    // index error, return
                    sendMgrResponse(&ptC->tAddrRemoteSignal, ptSession, 400, reinterpret_cast<const unsigned char *>("Index not found."));
                    return;
                }

            }

            ptSession->wBdyLth = pbMsg - &ptSession->bBody[0];

            break;

        }

        else {
            // NOT supported event.
            sendMgrResponse(&ptC->tAddrRemoteSignal, ptSession, 400, reinterpret_cast<const unsigned char *>("Unknown event type."));
            return;
        }
    } while(0);

    // send out response
    ptResp = ptSession;

    memset(&ptResp->bMap[0], 0, sizeof(ptResp->bMap));

    ptResp->bMap[CALLID_SEQ_NUM] = 1;
    ptResp->bMap[CSEQ_SEQ_NUM] = 1;

    // content-length: Automatic done.
    //

    // send response to peer.
    sendResponse(&ptC->tAddrRemoteSignal, ptResp, 200, reinterpret_cast<const unsigned char *>("OK"));

    return;
}
コード例 #11
0
ファイル: kfm.cpp プロジェクト: europop/morrgraphext
void KfmEventString::Write( ostream & out, unsigned int version ) {
    WriteUInt(unk_int, out);
    WriteString(event, out);
};
コード例 #12
0
void handle_request_reCONN(CLIENT_t *ptC, CONN_SESSION *ptSession)
{
    // reset-media request...

    CONN_SESSION   *ptResp;
    BYTE           *pbMsg;
    UINT32          u32IP   = INADDR_NONE;
    UINT16          u16Port = 0;


    // remote-media ip + port
    if (ptSession->bMap[MEDIA_SEQ_NUM] && ptSession->tMedia.bMap[0] && ptSession->tMedia.tUrl.bMap[1])
    {
        u32IP = inet_addr((const char *)ptSession->tMedia.tUrl.tHost.unHost.bHostName);
    }
    if (u32IP == INADDR_NONE)
    {
        syslog(LOG_WARNING, "receive re-CONN request, but Media IP is invalid. Ignore request...\n");

        sendMgrResponse(&ptC->tAddrRemoteSignal, ptSession, 400, reinterpret_cast<const unsigned char *>("Media header error."));
        return;
    }

    if (ptSession->bMap[MEDIA_SEQ_NUM] && ptSession->tMedia.bMap[0] && ptSession->tMedia.tUrl.bMap[2])
    {
        //u16Port = htons(ptSession->tMedia.tUrl.wPort);
        u16Port = ptSession->tMedia.tUrl.wPort;
    }


    // send to media-plane
    if ( (u32IP == ptC->tAddrRemoteMedia.ip_addr) && (u16Port == ptC->tAddrRemoteMedia.ip_addr) ) {
        // goto below, just return 200-OK.
    }
    else {
        ptC->tAddrRemoteMedia.ip_addr = u32IP;
        ptC->tAddrRemoteMedia.port = u16Port;

        // update media plane
        sdp_process_type_t eClientType = (ptC == &patClient[0]) ? SDP_F : SDP_C;
        data_plane_del_sender(eClientType, ptC->tMedia);
        ptC->tMedia = data_plane_add_sender(eClientType, ptC->tAddrRemoteMedia.ip_addr, ptC->tAddrRemoteMedia.port);

    }

    // send out response
    ptResp = ptSession;

    memset(&ptResp->bMap[0], 0, sizeof(ptResp->bMap));

    ptResp->bMap[CALLID_SEQ_NUM] = 1;
    ptResp->bMap[CSEQ_SEQ_NUM] = 1;

    ptResp->bMap[MEDIA_SEQ_NUM] = 1;
    {
        URL   *ptUrl = &ptResp->tMedia.tUrl;
        char  *pStrIp;

        ptResp->tMedia.bMap[0] = 1;

        ptUrl->bMap[1] = 1;
        ptUrl->tHost.eType = eNAT_HOSTNAME;
        pbMsg = &ptUrl->tHost.unHost.bHostName[0];

        pStrIp = inet_ntoa( *((struct in_addr *)&ptC->tMedia.s_addr) );
        if (!pStrIp) {
            syslog(LOG_ERR, "Can NOT get host ip. Check media plane.\n");

            pStrIp = &m_confs.aLocalIp[0];
        }
        WriteString(&pbMsg, (BYTE *)pStrIp, NODE_ADDR_LTH);
        pbMsg[0] = '\0';

        ptUrl->bMap[2] = 1;
        ptUrl->wPort = ptC->tMedia.s_port;
    }

    // send response to peer.
    sendResponse(&ptC->tAddrRemoteSignal, ptResp, 200, reinterpret_cast<const unsigned char *>("OK"));

    return;
}
コード例 #13
0
void handle_request_CONN(CLIENT_t *ptC, CONN_SESSION *ptSession)
{
    //WORD    wMediaPort;
    CONN_SESSION   *ptResp;
    BYTE           *pbMsg;


    // save remote-media ip + port
    ptC->tAddrRemoteMedia.ip_addr = INADDR_NONE;
    if (ptSession->bMap[MEDIA_SEQ_NUM] && ptSession->tMedia.bMap[0] && ptSession->tMedia.tUrl.bMap[1])
    {
        ptC->tAddrRemoteMedia.ip_addr = inet_addr((const char *)ptSession->tMedia.tUrl.tHost.unHost.bHostName);
    }
    if (ptC->tAddrRemoteMedia.ip_addr == INADDR_NONE)
    {
        syslog(LOG_ERR, "receive CONN request, but Media IP is invalid. Ignore request AND release instance...\n");

        freeClient(ptC);
        sendMgrResponse(&ptC->tAddrRemoteSignal, ptSession, 400, reinterpret_cast<const unsigned char *>("Media header error."));
        return;
    }

    if (ptSession->bMap[MEDIA_SEQ_NUM] && ptSession->tMedia.bMap[0] && ptSession->tMedia.tUrl.bMap[2])
    {
        ptC->tAddrRemoteMedia.port = ptSession->tMedia.tUrl.wPort;
    }


    // activate media plane
    sdp_process_type_t eClientType = (ptC == &patClient[0]) ? SDP_F : SDP_C;
    ptC->tMedia = data_plane_add_sender(eClientType, ptC->tAddrRemoteMedia.ip_addr, ptC->tAddrRemoteMedia.port);

    // send out response
    ptResp = ptSession;

    memset(&ptResp->bMap[0], 0, sizeof(ptResp->bMap));

    ptResp->bMap[CALLID_SEQ_NUM] = 1;

    ptResp->bMap[CSEQ_SEQ_NUM] = 1;

    ptResp->bMap[MEDIA_SEQ_NUM] = 1;
    {
        URL   *ptUrl = &ptResp->tMedia.tUrl;
        char  *pStrIp;

        ptResp->tMedia.bMap[0] = 1;

        ptUrl->bMap[1] = 1;
        ptUrl->tHost.eType = eNAT_HOSTNAME;
        pbMsg = &ptUrl->tHost.unHost.bHostName[0];

        pStrIp = inet_ntoa( *((struct in_addr *)&ptC->tMedia.s_addr) );
        if (!pStrIp) {
            syslog(LOG_ERR, "Can NOT get host ip. Check media plane.\n");
            pStrIp = &m_confs.aLocalIp[0];
        }
        WriteString(&pbMsg, (BYTE *)pStrIp, NODE_ADDR_LTH);
        pbMsg[0] = '\0';

        ptUrl->bMap[2] = 1;
        ptUrl->wPort = ptC->tMedia.s_port;
    }

    // send response to peer.
    sendResponse(&ptC->tAddrRemoteSignal, ptResp, 200, reinterpret_cast<const unsigned char *>("OK"));

    return;
}
コード例 #14
0
ファイル: cpcout.c プロジェクト: noddybox/casm
int CPCOutput(const char *filename, const char *filename_bank,
              MemoryBank **bank, int count, char *error, size_t error_size)
{
    FILE *fp = fopen(filename, "wb");
    int f;

    if (!fp)
    {
        snprintf(error, error_size, "Failed to create %s", filename);
        return FALSE;
    }

    /* First get the initial address is none defined
    */
    if (options.start_addr == -1)
    {
        options.start_addr = bank[0]->min_address_used;
    }

    /* Output the binary files
    */
    WriteString(fp, "ZXTape!", 7, 0, CP_ASCII, 0);
    WriteByte(fp, 0x1a, 0);
    WriteByte(fp, 1, 0);
    WriteByte(fp, 13, 0);

    for(f = 0; f < count; f++)
    {
        const Byte *mem;
        int min, max, len, blocks, addr;
        int block, blocklen;

        mem = bank[f]->memory;
        min = bank[f]->min_address_used;
        addr = min;
        max = bank[f]->max_address_used;
        len = max - min + 1;
        blocks = len / BLOCK_SIZE;

        if ((len % BLOCK_SIZE) == 0)
        {
            blocks--;
        }

        for(block = 0; block <= blocks; block++)
        {
            Byte chk;
            int first, last;

            first = 0;
            last = 0;

            WriteByte(fp, 0x11, 0);     /* Block type */

            WriteWord(fp, 0x626, 0);    /* PILOT */
            WriteWord(fp, 0x34f, 0);    /* SYNC1 */
            WriteWord(fp, 0x302, 0);    /* SYNC2 */
            WriteWord(fp, 0x33a, 0);    /* ZERO */
            WriteWord(fp, 0x673, 0);    /* ONE */
            WriteWord(fp, 0xffe, 0);    /* PILOT LEN */
            WriteByte(fp, 8, 0);        /* USED BITS */
            WriteWord(fp, 0x10, 0);     /* PAUSE */
            Write3Word(fp, 0x0041, 0);  /* LEN */

            chk = 0;

            if (f == 0)
            {
                chk = WriteString(fp, filename, 16, 0, CP_ASCII, chk);
            }
            else
            {
                char fn[16];

                snprintf(fn, sizeof fn, filename_bank, bank[f]->number);
                chk = WriteString(fp, fn, 16, 0, CP_ASCII, chk);
            }

            chk = WriteByte(fp, block+1, chk);

            if (block == 0)
            {
                first = 255;

                if (len > BLOCK_SIZE)
                {
                    blocklen = BLOCK_SIZE;
                }
                else
                {
                    blocklen = len;
                }
            }

            if (block == blocks)
            {
                last = 255;
                blocklen = len % BLOCK_SIZE;
            }

            chk = WriteByte(fp, last, chk);
            chk = WriteByte(fp, 2, chk);
            chk = WriteWord(fp, blocklen, chk);
            chk = WriteWord(fp, addr, chk);
            chk = WriteByte(fp, first, chk);
            chk = WriteWord(fp, len, chk);
            chk = WriteWord(fp, options.start_addr, chk);
            chk = WriteString(fp, "", 64 - 28, 0, CP_ASCII, chk);

            WriteByte(fp, chk, 0);

            addr += blocklen;

            /* Output file data
            */
            WriteByte(fp, 0x11, 0);             /* Block type */

            WriteWord(fp, 0x626, 0);            /* PILOT */
            WriteWord(fp, 0x34f, 0);            /* SYNC1 */
            WriteWord(fp, 0x302, 0);            /* SYNC2 */
            WriteWord(fp, 0x33a, 0);            /* ZERO */
            WriteWord(fp, 0x673, 0);            /* ONE */
            WriteWord(fp, 0xffe, 0);            /* PILOT LEN */
            WriteByte(fp, 8, 0);                /* USED BITS */
            WriteWord(fp, 0x10, 0);             /* PAUSE */
            Write3Word(fp, blocklen + 1, 0);    /* LEN */

            chk = 0;

            while(min < addr)
            {
                chk = WriteByte(fp, mem[min], chk);
                min++;
            }

            WriteByte(fp, chk, 0);
        }
    }

    fclose(fp);

    return TRUE;
}
コード例 #15
0
ファイル: entry.cpp プロジェクト: jjaaddiicc/stserver
int main(int argc, char *argv[])
{
	CNV11* NV11 = new CNV11(); // Create instance of validator class
	// Start the polling thread, this will not send any polls until
	// the IsPolling variable is true
	HANDLE nv11Thread = StartPollThread(NV11); 
	// Set output to std::cout
	NV11->SetOutputStream(&cout);
	WriteString("Example C++ NV11 SDK\n\nSearching for ports...\n");

	// Find out about the validator and create a connection struct to pass
	// to the validator class
	SSP_COMMAND commandStructure;
	commandStructure.BaudRate = 9600;
	commandStructure.Timeout = 1000;
	commandStructure.RetryLevel = 3;
	commandStructure.IgnoreError = 1;

	char* end;
	// Get port number
	std::vector<string> ports = GetComPorts();
	for (unsigned int i = 0; i < ports.size(); ++i)
		cout << ports[i] << endl;
	string in = "";
	unsigned int portIndex = 0;
	do
	{
		in = GetInputString("Select a port: ");
		portIndex = strtol(in.c_str(), &end, 0);
	} while (portIndex <= 0 || portIndex > ports.size());
	commandStructure.PortNumber = FormatComPort(ports[portIndex-1]); 
		
	// Get ssp address
	int ssp = 0;
	do
	{
		in = GetInputString("SSP Address (Default = 0): ");
		ssp = strtol(in.c_str(), &end, 0);
	} while (ssp < 0 || ssp > 32 || end == in.c_str());
	commandStructure.SSPAddress = (unsigned char)ssp;

	// Get protocol version to use
	int p = 0;
	do
	{
		in = GetInputString("Protocol version: ");
		p = strtol(in.c_str(), &end, 0);
	} while (p <= 0 || p > MAX_PROTOCOL_VERSION);

	// Now connect to validator
	if (NV11->ConnectToValidator(commandStructure, p, 5))
	{
		WriteString("Connected to validator successfully");
		DisplayCommands();
		while  (true)
		{
			// Parse the keys, if this returns false then the user has selected
			// to exit the program
			if (!ParseKeys(NV11))
			{
				IsPolling = false; // Stop polling before exit
				break;
			}

			// If PollFailed is set by the polling thread, attempt to reconnect to the unit
			if (PollFailed)
			{
				// Make 5 attempts to reconnect, if none successful break out
				if (NV11->ConnectToValidator(commandStructure, p, 5)) 
				{
					// If successful reconnect, restart the polling thread and continue
					PollFailed = false;
					TerminateThread(nv11Thread, 0);
					CloseHandle(nv11Thread);
					nv11Thread = StartPollThread(NV11);
				}
				else
					break;
			}
		}
		WriteString("Poll loop stopped");
	}
	TerminateThread(nv11Thread, 0);
	CloseHandle(nv11Thread);
	delete NV11;
	WriteString("Press any key to exit...");
	_getch();
}
コード例 #16
0
ファイル: fileutil.c プロジェクト: DrItanium/maya
int LLGetcBatch(
  Environment *theEnv,
  const char *logicalName,
  bool returnOnEOF)
  {
   int rv = EOF, flag = 1;

   /*=================================================*/
   /* Get a character until a valid character appears */
   /* or no more batch files are left.                */
   /*=================================================*/

   while ((rv == EOF) && (flag == 1))
     {
      if (FileCommandData(theEnv)->BatchType == FILE_BATCH)
        { rv = getc(FileCommandData(theEnv)->BatchFileSource); }
      else
        { rv = ReadRouter(theEnv,FileCommandData(theEnv)->BatchLogicalSource); }

      if (rv == EOF)
        {
         if (FileCommandData(theEnv)->BatchCurrentPosition > 0) WriteString(theEnv,STDOUT,(char *) FileCommandData(theEnv)->BatchBuffer);
         flag = RemoveBatch(theEnv);
        }
     }

   /*=========================================================*/
   /* If the character retrieved is an end-of-file character, */
   /* then there are no batch files with character input      */
   /* remaining. Remove the batch router.                     */
   /*=========================================================*/

   if (rv == EOF)
     {
      if (FileCommandData(theEnv)->BatchCurrentPosition > 0) WriteString(theEnv,STDOUT,(char *) FileCommandData(theEnv)->BatchBuffer);
      DeleteRouter(theEnv,"batch");
      RemoveBatch(theEnv);
      if (returnOnEOF == true)
        { return (EOF); }
      else
        { return ReadRouter(theEnv,logicalName); }
     }

   /*========================================*/
   /* Add the character to the batch buffer. */
   /*========================================*/

   if (RouterData(theEnv)->InputUngets == 0)
     {
      FileCommandData(theEnv)->BatchBuffer = ExpandStringWithChar(theEnv,(char) rv,FileCommandData(theEnv)->BatchBuffer,&FileCommandData(theEnv)->BatchCurrentPosition,
                                         &FileCommandData(theEnv)->BatchMaximumPosition,FileCommandData(theEnv)->BatchMaximumPosition+BUFFER_SIZE);
     }
      
   /*======================================*/
   /* If a carriage return is encountered, */
   /* then flush the batch buffer.         */
   /*======================================*/

   if ((char) rv == '\n')
     {
      WriteString(theEnv,STDOUT,(char *) FileCommandData(theEnv)->BatchBuffer);
      FileCommandData(theEnv)->BatchCurrentPosition = 0;
      if ((FileCommandData(theEnv)->BatchBuffer != NULL) && (FileCommandData(theEnv)->BatchMaximumPosition > BUFFER_SIZE))
        {
         rm(theEnv,FileCommandData(theEnv)->BatchBuffer,FileCommandData(theEnv)->BatchMaximumPosition);
         FileCommandData(theEnv)->BatchMaximumPosition = 0;
         FileCommandData(theEnv)->BatchBuffer = NULL;
        }
     }

   /*=============================*/
   /* Increment the line counter. */
   /*=============================*/

   if (((char) rv == '\r') || ((char) rv == '\n'))
     { IncrementLineCount(theEnv); }

   /*=====================================================*/
   /* Return the character retrieved from the batch file. */
   /*=====================================================*/

   return(rv);
  }
コード例 #17
0
ファイル: usb_host_hub.c プロジェクト: AlexGeControl/tiva-c
//*****************************************************************************
//
// The main application loop.
//
//*****************************************************************************
int
main(void)
{
    int32_t i32Status, i32Idx;
    uint32_t ui32SysClock, ui32PLLRate;
#ifdef USE_ULPI
    uint32_t ui32Setting;
#endif

    ui32SysClock = MAP_SysCtlClockFreqSet((SYSCTL_XTAL_25MHZ |
                                           SYSCTL_OSC_MAIN | SYSCTL_USE_PLL |
                                           SYSCTL_CFG_VCO_480), 120000000);

    //
    // Set the part pin out appropriately for this device.
    //
    PinoutSet();

#ifdef USE_ULPI
    //
    // Switch the USB ULPI Pins over.
    //
    USBULPIPinoutSet();

    //
    // Enable USB ULPI with high speed support.
    //
    ui32Setting = USBLIB_FEATURE_ULPI_HS;
    USBOTGFeatureSet(0, USBLIB_FEATURE_USBULPI, &ui32Setting);

    //
    // Setting the PLL frequency to zero tells the USB library to use the
    // external USB clock.
    //
    ui32PLLRate = 0;
#else
    //
    // Save the PLL rate used by this application.
    //
    ui32PLLRate = 480000000;
#endif

    //
    // Initialize the hub port status.
    //
    for(i32Idx = 0; i32Idx < NUM_HUB_STATUS; i32Idx++)
    {
        g_psHubStatus[i32Idx].bConnected = false;
    }

    //
    // Enable Clocking to the USB controller.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_USB0);

    //
    // Enable Interrupts
    //
    ROM_IntMasterEnable();

    //
    // Initialize the USB stack mode and pass in a mode callback.
    //
    USBStackModeSet(0, eUSBModeHost, 0);

    //
    // Register the host class drivers.
    //
    USBHCDRegisterDrivers(0, g_ppHostClassDrivers, g_ui32NumHostClassDrivers);

    //
    // Open the Keyboard interface.
    //
    KeyboardOpen();
    MSCOpen(ui32SysClock);

    //
    // Open a hub instance and provide it with the memory required to hold
    // configuration descriptors for each attached device.
    //
    USBHHubOpen(HubCallback);

    //
    // Initialize the power configuration. This sets the power enable signal
    // to be active high and does not enable the power fault.
    //
    USBHCDPowerConfigInit(0, USBHCD_VBUS_AUTO_HIGH | USBHCD_VBUS_FILTER);

    //
    // Tell the USB library the CPU clock and the PLL frequency.
    //
    USBOTGFeatureSet(0, USBLIB_FEATURE_CPUCLK, &ui32SysClock);
    USBOTGFeatureSet(0, USBLIB_FEATURE_USBPLL, &ui32PLLRate);

    //
    // Initialize the USB controller for Host mode.
    //
    USBHCDInit(0, g_pui8HCDPool, sizeof(g_pui8HCDPool));

    //
    // Initialize the display driver.
    //
    Kentec320x240x16_SSD2119Init(ui32SysClock);

    //
    // Initialize the graphics context.
    //
    GrContextInit(&g_sContext, &g_sKentec320x240x16_SSD2119);

    //
    // Draw the application frame.
    //
    FrameDraw(&g_sContext, "usb-host-hub");

    //
    // Calculate the number of characters that will fit on a line.
    // Make sure to leave a small border for the text box.
    //
    g_ui32CharsPerLine = (GrContextDpyWidthGet(&g_sContext) - 16) /
                         GrFontMaxWidthGet(g_psFontFixed6x8);

    //
    // Calculate the number of lines per usable text screen.  This requires
    // taking off space for the top and bottom banners and adding a small bit
    // for a border.
    //
    g_ui32LinesPerScreen = (GrContextDpyHeightGet(&g_sContext) -
                           (2*(DISPLAY_BANNER_HEIGHT + 1)))/
                           GrFontHeightGet(g_psFontFixed6x8);

    //
    // Initial update of the screen.
    //
    UpdateStatus(0);
    UpdateStatus(1);
    UpdateStatus(2);
    UpdateStatus(3);

    g_ui32CmdIdx = 0;
    g_ui32CurrentLine = 0;

    //
    // Initialize the file system.
    //
    FileInit();

    //
    // The main loop for the application.
    //
    while(1)
    {
        //
        // Print a prompt to the console.  Show the CWD.
        //
        WriteString("> ");

        //
        // Is there a command waiting to be processed?
        //
        while((g_ui32Flags & FLAG_CMD_READY) == 0)
        {
            //
            // Call the YSB library to let non-interrupt code run.
            //
            USBHCDMain();

            //
            // Call the keyboard and mass storage main routines.
            //
            KeyboardMain();
            MSCMain();
        }

        //
        // Pass the line from the user to the command processor.
        // It will be parsed and valid commands executed.
        //
        i32Status = CmdLineProcess(g_pcCmdBuf);

        //
        // Handle the case of bad command.
        //
        if(i32Status == CMDLINE_BAD_CMD)
        {
            WriteString("Bad command!\n");
        }
        //
        // Handle the case of too many arguments.
        //
        else if(i32Status == CMDLINE_TOO_MANY_ARGS)
        {
            WriteString("Too many arguments for command processor!\n");
        }
        //
        // Otherwise the command was executed.  Print the error
        // code if one was returned.
        //
        else if(i32Status != 0)
        {
            WriteString("Command returned error code\n");
            WriteString((char *)StringFromFresult((FRESULT)i32Status));
            WriteString("\n");
        }

        //
        // Reset the command flag and the command index.
        //
        g_ui32Flags &= ~FLAG_CMD_READY;
        g_ui32CmdIdx = 0;
    }
}
コード例 #18
0
ファイル: CLog.cpp プロジェクト: swak/Source
int CLog::EventStr( DWORD wMask, LPCTSTR pszMsg )
{
	// NOTE: This could be called in odd interrupt context so don't use dynamic stuff
	if ( !IsLogged(wMask) )	// I don't care about these.
		return 0;
	else if ( !pszMsg || !*pszMsg )
		return 0;

	int iRet = 0;
	m_mutex.lock();

	try
	{

		// Put up the date/time.
		CGTime datetime = CGTime::GetCurrentTime();	// last real time stamp.

		if ( datetime.GetDaysTotal() != m_dateStamp.GetDaysTotal())
		{
			// it's a new day, open with new day name.
			Close();	// LINUX should alrady be closed.

			OpenLog( NULL );
			Printf( "%s", datetime.Format(NULL));
		}
		else
		{
#ifndef _WIN32
			UINT	mode = OF_READWRITE|OF_TEXT;
			mode |= OF_SHARE_DENY_WRITE;
			Open(NULL, mode);	// LINUX needs to close and re-open for each log line !
#endif
		}

		TCHAR szTime[32];
		sprintf(szTime, "%02d:%02d:", datetime.GetHour(), datetime.GetMinute());
		m_dateStamp = datetime;

		LPCTSTR pszLabel = NULL;

		switch (wMask & 0x07)
		{
			case LOGL_FATAL:	// fatal error !
				pszLabel = "FATAL:";
				break;
			case LOGL_CRIT:	// critical.
				pszLabel = "CRITICAL:";
				break;
			case LOGL_ERROR:	// non-fatal errors.
				pszLabel = "ERROR:";
				break;
			case LOGL_WARN:
				pszLabel = "WARNING:";
				break;
		}
		if ( !pszLabel && ( wMask & LOGM_DEBUG ) && !( wMask & LOGM_INIT ))
			pszLabel = "DEBUG:";

		// Get the script context. (if there is one)
		TCHAR szScriptContext[ _MAX_PATH + 16 ];
		if ( !( wMask&LOGM_NOCONTEXT ) && m_pScriptContext )
		{
			CScriptLineContext LineContext = m_pScriptContext->GetContext();
			sprintf( szScriptContext, "(%s,%d)", m_pScriptContext->GetFileTitle(), LineContext.m_iLineNum );
		}
		else
		{
			szScriptContext[0] = '\0';
		}

		// Print to screen.
		if ( ! ( wMask & LOGM_INIT ) && ! g_Serv.IsLoading())
		{
			SetColor(YELLOW);
			g_Serv.PrintStr( szTime );
			SetColor(DEFAULT);
		}

		if ( pszLabel )	// some sort of error
		{
			SetColor(RED);
			g_Serv.PrintStr( pszLabel );
			SetColor(DEFAULT);
		}

		if ( szScriptContext[0] )
		{
			SetColor(CYAN);
			g_Serv.PrintStr( szScriptContext );
			SetColor(DEFAULT);
		}
		g_Serv.PrintStr( pszMsg );

		// Back to normal color.
		SetColor(DEFAULT);

		// Print to log file.
		WriteString( szTime );
		if ( pszLabel )	WriteString( pszLabel );
		if ( szScriptContext[0] )
		{
			WriteString( szScriptContext );
		}
		WriteString( pszMsg );

		iRet = 1;

#ifndef _WIN32
		Close();
#endif
	}
	catch (...)
	{
		// Not much we can do about this
		iRet = 0;
		CurrentProfileData.Count(PROFILE_STAT_FAULTS, 1);
	}

	m_mutex.unlock();

	return( iRet );
}
コード例 #19
0
ファイル: globldef.c プロジェクト: DrItanium/maya
void QSetDefglobalValue(
  Environment *theEnv,
  Defglobal *theGlobal,
  UDFValue *vPtr,
  bool resetVar)
  {
   CLIPSValue newValue;
   
   /*====================================================*/
   /* If the new value passed for the defglobal is NULL, */
   /* then reset the defglobal to the initial value it   */
   /* had when it was defined.                           */
   /*====================================================*/

   if (resetVar)
     {
      EvaluateExpression(theEnv,theGlobal->initial,vPtr);
      if (EvaluationData(theEnv)->EvaluationError)
        { vPtr->value = FalseSymbol(theEnv); }
     }

   /*==========================================*/
   /* If globals are being watch, then display */
   /* the change to the global variable.       */
   /*==========================================*/

#if DEBUGGING_FUNCTIONS
   if (theGlobal->watch &&
       (! ConstructData(theEnv)->ClearReadyInProgress) &&
       (! ConstructData(theEnv)->ClearInProgress))
     {
      WriteString(theEnv,STDOUT,":== ?*");
      WriteString(theEnv,STDOUT,theGlobal->header.name->contents);
      WriteString(theEnv,STDOUT,"* ==> ");
      WriteUDFValue(theEnv,STDOUT,vPtr);
      WriteString(theEnv,STDOUT," <== ");
      WriteCLIPSValue(theEnv,STDOUT,&theGlobal->current);
      WriteString(theEnv,STDOUT,"\n");
     }
#endif

   /*==============================================*/
   /* Retain the new value of the global variable. */
   /*==============================================*/
   
   NormalizeMultifield(theEnv,vPtr);
   if (vPtr->header->type != MULTIFIELD_TYPE)
     { newValue.value = vPtr->value; }
   else
     { newValue.value = CopyMultifield(theEnv,vPtr->multifieldValue); }
   Retain(theEnv,newValue.header);

   /*==============================================*/
   /* Remove the old value of the global variable. */
   /*==============================================*/

   Release(theEnv,theGlobal->current.header);
   if (theGlobal->current.header->type == MULTIFIELD_TYPE)
     {
      if (theGlobal->current.multifieldValue->busyCount == 0)
        { ReturnMultifield(theEnv,theGlobal->current.multifieldValue); }
      else
        { AddToMultifieldList(theEnv,theGlobal->current.multifieldValue); }
     }

   /*===========================================*/
   /* Set the new value of the global variable. */
   /*===========================================*/

   theGlobal->current.value = newValue.value;

   /*===========================================*/
   /* Set the variable indicating that a change */
   /* has been made to a global variable.       */
   /*===========================================*/

   DefglobalData(theEnv)->ChangeToGlobals = true;

   if (EvaluationData(theEnv)->CurrentExpression == NULL)
     {
      CleanCurrentGarbageFrame(theEnv,NULL);
      CallPeriodicTasks(theEnv);
     }
  }
コード例 #20
0
ファイル: IniFile_s.cpp プロジェクト: code4hunter/oldpts
bool CIniFile::WriteInteger(TCHAR * Section ,TCHAR * Item,int Val)
{
	TCHAR buf[100];
	_stprintf_s(buf,100,_T("%d"),Val);
	return WriteString(Section,Item,buf); 
}
コード例 #21
0
void String::Write(Buffer *buf, const String *s)
{
  WriteString(buf, (const uint8_t*) s->m_value,
              strlen(s->m_value) + 1);
}
コード例 #22
0
ファイル: IniFile_s.cpp プロジェクト: code4hunter/oldpts
bool CIniFile::WriteDouble(TCHAR * Section ,TCHAR * Item,double Val)
{
	TCHAR buf[100];
	_stprintf_s(buf,100,_T("%.15f"),Val);
	return WriteString(Section,Item,buf); 
}
コード例 #23
0
/*********************************************************************\
	Function name    : CDialogCustomElement::Save
	Description      :
	Created at       : 27.03.02, @ 14:54:04
	Created by       : Thomas Kunert
	Modified by      :
\*********************************************************************/
Bool CDialogCustomElement::Save(BaseFile* pFile, String strFill)
{
    if (g_pCustomElements && m_lElement >= 0 && m_lElement < g_pCustomElements->Entries())
    {
        CustomProperty* pProp;

        CCustomElements* pElement = g_pCustomElements->GetItem(m_lElement);
        if (!pElement) return true;
        if (!m_pbcGUI) return false;
        BaseContainer* pBC = &m_pbcGUI[m_lElement];

        pProp = pElement->m_pProp;

        WriteString(pFile, pElement->m_pChResSym);
        WriteString(pFile, " ");
        WriteString(pFile, m_strControlID);
        LineBreak(pFile, strFill);

        WriteString(pFile, "{");
        LineBreak(pFile, strFill + *g_pstrFillSave);
        SaveAlignment(pFile);
        LineBreak(pFile, strFill);

        if (pElement->m_bIsOpen)
        {
            WriteString(pFile, *g_pstrFillSave);
            WriteString(pFile, "OPEN");
            WriteString(pFile, "; ");
            LineBreak(pFile, strFill);
        }

        Int32 i;
        for (i = 0; pProp && pProp[i].type != CUSTOMTYPE_END; i++)
        {
            Bool b = false;
            if (pProp[i].type == CUSTOMTYPE_FLAG)
            {
                if (pBC->GetBool(pProp[i].id))
                {
                    WriteString(pFile, *g_pstrFillSave);
                    WriteString(pFile, pProp[i].ident);
                    WriteString(pFile, "; ");
                    b = true;
                }
            }
            else if (pProp[i].type == CUSTOMTYPE_LONG)
            {
                WriteString(pFile, *g_pstrFillSave);
                WriteString(pFile, pProp[i].ident);
                WriteString(pFile, " ");
                WriteString(pFile, String::IntToString(pBC->GetInt32(pProp[i].id)));

                // XXX: BITMAPBUTTON SIZE is a CUSTOMTYPE_LONG property, yet it
                // requires a tuple for the SIZE parameter. Can we find a better
                // way than hardcoding this?
                // https://github.com/nr-plugins/resedit/issues/2
                if (String(pElement->m_pChResSym) == String("BITMAPBUTTON") &&
                        String(pProp[i].ident) == String("SIZE")) {
                    WriteString(pFile, ", ");
                    WriteString(pFile, String::IntToString(pBC->GetInt32(pProp[i].id)));
                }

                WriteString(pFile, "; ");
                b = true;
            }
            else if (pProp[i].type == CUSTOMTYPE_REAL)
            {
                WriteString(pFile, *g_pstrFillSave);
                WriteString(pFile, pProp[i].ident);
                WriteString(pFile, " ");
                WriteString(pFile, String::FloatToString(pBC->GetFloat(pProp[i].id)));
                WriteString(pFile, "; ");
                b = true;
            }
            else if (pProp[i].type == CUSTOMTYPE_STRING)
            {
                if (pBC->GetString(pProp[i].id).Content())
                {
                    WriteString(pFile, *g_pstrFillSave);
                    WriteString(pFile, pProp[i].ident);
                    WriteString(pFile, " ");
                    WriteString(pFile, pBC->GetString(pProp[i].id));
                    WriteString(pFile, "; ");
                    b = true;
                }
            }
            else if (pProp[i].type == CUSTOMTYPE_VECTOR)
            {
                WriteString(pFile, *g_pstrFillSave);
                WriteString(pFile, pProp[i].ident);
                WriteString(pFile, " ");
                WriteString(pFile, String::FloatToString(pBC->GetVector(pProp[i].id).x));
                WriteString(pFile, " ");
                WriteString(pFile, String::FloatToString(pBC->GetVector(pProp[i].id).y));
                WriteString(pFile, " ");
                WriteString(pFile, String::FloatToString(pBC->GetVector(pProp[i].id).z));
                WriteString(pFile, " ");
                WriteString(pFile, "; ");
                b = true;
            }

            if (b)
                LineBreak(pFile, strFill);
        }
        WriteString(pFile, "}");
    }

    return true;
}
コード例 #24
0
ファイル: IniFile_s.cpp プロジェクト: code4hunter/oldpts
bool CIniFile::WriteFloat(TCHAR * Section ,TCHAR * Item,float Val)
{
	TCHAR buf[100];
	_stprintf_s(buf,100,_T("%.7f"),Val);
	return WriteString(Section,Item,buf); 
}
コード例 #25
0
ファイル: Ini.cpp プロジェクト: gregggdavis/ww-merging-cpp
// Write an unsigned value to the ini file
BOOL CIni::WriteUInt(LPCTSTR lpSection, LPCTSTR lpKey, UINT nValue, int nBase) const
{
	TCHAR szValue[DEF_PROFILE_NUM_LEN + 1] = _T("");
	__UIntToString(nValue, szValue, nBase);
	return WriteString(lpSection, lpKey, szValue);
}
コード例 #26
0
ファイル: IniFile_s.cpp プロジェクト: code4hunter/oldpts
bool CIniFile::WriteBoolean(TCHAR * Section ,TCHAR * Item,bool Val)
{
	return WriteString(Section,Item,Val==1 ? _T("1") : _T("0")); 
}
コード例 #27
0
ファイル: D3DCompilerWrapper.cpp プロジェクト: dgkae/KlayGE
// http://wine-wiki.org/index.php/WineLib#Calling_a_Native_Windows_dll_from_Linux
int main(int argc, char* argv[])
{
	D3DCompiler d3d_compiler;

	if (argc < 2)
	{
		PrintHelps();
		return -1;
	}

	if (0 == strcmp(argv[1], "compile"))
	{
		if (argc < 8)
		{
			PrintHelps();
			return -1;
		}

		char const * input_file = argv[2];
		char const * entry_point = argv[3];
		char const * target = argv[4];
		int flags1 = atoi(argv[5]);
		int flags2 = atoi(argv[6]);
		char const * output_file = argv[7];

		FILE* fp = fopen(input_file, "rb");
		int hlsl_size;
		fread(&hlsl_size, sizeof(hlsl_size), 1, fp);
		char* hlsl = new char[hlsl_size + 1];
		fread(hlsl, sizeof(char), hlsl_size, fp);
		hlsl[hlsl_size] = 0;

		int num_macros;
		fread(&num_macros, sizeof(num_macros), 1, fp);
		D3D_SHADER_MACRO* macros = new D3D_SHADER_MACRO[num_macros + 1];
		char line_name[1024];
		char line_definition[1024];
		int idx = 0;
		while (fgets(line_name, 1024, fp) && fgets(line_definition, 1024, fp))
		{
			char* t1 = new char[strlen(line_name) + 1];
			strcpy(t1, line_name);
			if ('\n' == t1[strlen(t1) - 1])
			{
				t1[strlen(t1) - 1] = '\0';
			}
			char* t2 = new char[strlen(line_definition) + 1];
			strcpy(t2, line_definition);
			if ('\n' == t2[strlen(t2) - 1])
			{
				t2[strlen(t2) - 1] = '\0';
			}
			macros[idx].Name = t1;
			macros[idx].Definition = t2;
			++ idx;
		}
		macros[idx].Name = NULL;
		macros[idx].Definition = NULL;
		fclose(fp);

		ID3DBlob* code = NULL;
		ID3DBlob* err_msg = NULL;
		int hr = d3d_compiler.D3DCompile(hlsl, hlsl_size, NULL, macros, NULL, entry_point,
			target, flags1, flags2, &code, &err_msg);
		if (FAILED(hr))
		{
			printf("Compiling error: 0x%x\n", hr);
		}
		fp = fopen(output_file, "wb");
		fwrite(&hr, sizeof(hr), 1, fp);
		if (code != NULL)
		{
			int const size = static_cast<int>(code->GetBufferSize());
			fwrite(&size, sizeof(size), 1, fp);
			fwrite(code->GetBufferPointer(), sizeof(char), size, fp);
		}
		else
		{
			int const size = 0;
			fwrite(&size, sizeof(size), 1, fp);
		}
		if (err_msg != NULL)
		{
			int const size = static_cast<int>(err_msg->GetBufferSize());
			fwrite(&size, sizeof(size), 1, fp);
			fwrite(err_msg->GetBufferPointer(), sizeof(char), err_msg->GetBufferSize(), fp);
		}
		else
		{
			int const size = 0;
			fwrite(&size, sizeof(size), 1, fp);
		}
		fclose(fp);

		for (int i = 0; i < num_macros; ++ i)
		{
			delete[] macros[i].Name;
			delete[] macros[i].Definition;
		}
		delete[] macros;
		delete[] hlsl;
	}
	else if (0 == strcmp(argv[1], "reflect"))
	{
		if (argc < 4)
		{
			PrintHelps();
			return -1;
		}

		char const * input_file = argv[2];
		char const * output_file = argv[3];

		FILE* fp = fopen(input_file, "rb");
		fseek(fp, 0, SEEK_END);
		long bytecode_size = ftell(fp);
		fseek(fp, 0, SEEK_SET);
		char* bytecode = new char[bytecode_size];
		fread(bytecode, sizeof(char), bytecode_size, fp);
		fclose(fp);

		ID3D11ShaderReflection* reflection;
		int hr = d3d_compiler.D3DReflect(bytecode, bytecode_size, IID_ID3D11ShaderReflection_47,
			reinterpret_cast<void**>(&reflection));
		if (FAILED(hr))
		{
			printf("Reflect error: 0x%x\n", hr);
		}

		if (reflection != NULL)
		{
			fp = fopen(output_file, "wb");

			D3D11_SHADER_DESC desc;
			reflection->GetDesc(&desc);
			fwrite(&desc.Version, sizeof(desc.Version), 1, fp);
			WriteString(desc.Creator, fp);
			fwrite(&desc.Flags, sizeof(desc.Flags), 1, fp);
			fwrite(&desc.ConstantBuffers, sizeof(desc.ConstantBuffers), 1, fp);
			fwrite(&desc.BoundResources, sizeof(desc.BoundResources), 1, fp);
			fwrite(&desc.InputParameters, sizeof(desc.InputParameters), 1, fp);
			fwrite(&desc.OutputParameters, sizeof(desc.OutputParameters), 1, fp);
			fwrite(&desc.InstructionCount, sizeof(desc.InstructionCount), 1, fp);
			fwrite(&desc.TempRegisterCount, sizeof(desc.TempRegisterCount), 1, fp);
			fwrite(&desc.TempArrayCount, sizeof(desc.TempArrayCount), 1, fp);
			fwrite(&desc.DefCount, sizeof(desc.DefCount), 1, fp);
			fwrite(&desc.DclCount, sizeof(desc.DclCount), 1, fp);
			fwrite(&desc.TextureNormalInstructions, sizeof(desc.TextureNormalInstructions), 1, fp);
			fwrite(&desc.TextureLoadInstructions, sizeof(desc.TextureLoadInstructions), 1, fp);
			fwrite(&desc.TextureCompInstructions, sizeof(desc.TextureCompInstructions), 1, fp);
			fwrite(&desc.TextureBiasInstructions, sizeof(desc.TextureBiasInstructions), 1, fp);
			fwrite(&desc.TextureGradientInstructions, sizeof(desc.TextureGradientInstructions), 1, fp);
			fwrite(&desc.FloatInstructionCount, sizeof(desc.FloatInstructionCount), 1, fp);
			fwrite(&desc.IntInstructionCount, sizeof(desc.IntInstructionCount), 1, fp);
			fwrite(&desc.UintInstructionCount, sizeof(desc.UintInstructionCount), 1, fp);
			fwrite(&desc.StaticFlowControlCount, sizeof(desc.StaticFlowControlCount), 1, fp);
			fwrite(&desc.DynamicFlowControlCount, sizeof(desc.DynamicFlowControlCount), 1, fp);
			fwrite(&desc.MacroInstructionCount, sizeof(desc.MacroInstructionCount), 1, fp);
			fwrite(&desc.ArrayInstructionCount, sizeof(desc.ArrayInstructionCount), 1, fp);
			fwrite(&desc.CutInstructionCount, sizeof(desc.CutInstructionCount), 1, fp);
			fwrite(&desc.EmitInstructionCount, sizeof(desc.EmitInstructionCount), 1, fp);
			fwrite(&desc.GSOutputTopology, sizeof(desc.GSOutputTopology), 1, fp);
			fwrite(&desc.GSMaxOutputVertexCount, sizeof(desc.GSMaxOutputVertexCount), 1, fp);
			fwrite(&desc.InputPrimitive, sizeof(desc.InputPrimitive), 1, fp);
			fwrite(&desc.PatchConstantParameters, sizeof(desc.PatchConstantParameters), 1, fp);
			fwrite(&desc.cGSInstanceCount, sizeof(desc.cGSInstanceCount), 1, fp);
			fwrite(&desc.cControlPoints, sizeof(desc.cControlPoints), 1, fp);
			fwrite(&desc.HSOutputPrimitive, sizeof(desc.HSOutputPrimitive), 1, fp);
			fwrite(&desc.HSPartitioning, sizeof(desc.HSPartitioning), 1, fp);
			fwrite(&desc.TessellatorDomain, sizeof(desc.TessellatorDomain), 1, fp);
			fwrite(&desc.cBarrierInstructions, sizeof(desc.cBarrierInstructions), 1, fp);
			fwrite(&desc.cInterlockedInstructions, sizeof(desc.cInterlockedInstructions), 1, fp);
			fwrite(&desc.cTextureStoreInstructions, sizeof(desc.cTextureStoreInstructions), 1, fp);
			
			for (UINT c = 0; c < desc.ConstantBuffers; ++ c)
			{
				ID3D11ShaderReflectionConstantBuffer* reflection_cb = reflection->GetConstantBufferByIndex(c);

				D3D11_SHADER_BUFFER_DESC d3d_cb_desc;
				reflection_cb->GetDesc(&d3d_cb_desc);
				WriteString(d3d_cb_desc.Name, fp);
				fwrite(&d3d_cb_desc.Type, sizeof(d3d_cb_desc.Type), 1, fp);
				fwrite(&d3d_cb_desc.Variables, sizeof(d3d_cb_desc.Variables), 1, fp);
				fwrite(&d3d_cb_desc.Size, sizeof(d3d_cb_desc.Size), 1, fp);
				fwrite(&d3d_cb_desc.uFlags, sizeof(d3d_cb_desc.uFlags), 1, fp);

				for (UINT v = 0; v < d3d_cb_desc.Variables; ++ v)
				{
					ID3D11ShaderReflectionVariable* reflection_var = reflection_cb->GetVariableByIndex(v);

					D3D11_SHADER_VARIABLE_DESC var_desc;
					reflection_var->GetDesc(&var_desc);
					fwrite(&var_desc, sizeof(var_desc), 1, fp);

					WriteString(var_desc.Name, fp);
					fwrite(&var_desc.StartOffset, sizeof(var_desc.StartOffset), 1, fp);
					fwrite(&var_desc.Size, sizeof(var_desc.Size), 1, fp);
					fwrite(&var_desc.uFlags, sizeof(var_desc.uFlags), 1, fp);
					fwrite(var_desc.DefaultValue, var_desc.Size, 1, fp);
					fwrite(&var_desc.StartTexture, sizeof(var_desc.StartTexture), 1, fp);
					fwrite(&var_desc.TextureSize, sizeof(var_desc.TextureSize), 1, fp);
					fwrite(&var_desc.StartSampler, sizeof(var_desc.StartSampler), 1, fp);
					fwrite(&var_desc.SamplerSize, sizeof(var_desc.SamplerSize), 1, fp);

					D3D11_SHADER_TYPE_DESC type_desc;
					reflection_var->GetType()->GetDesc(&type_desc);
					fwrite(&type_desc.Class, sizeof(type_desc.Class), 1, fp);
					fwrite(&type_desc.Type, sizeof(type_desc.Type), 1, fp);
					fwrite(&type_desc.Rows, sizeof(type_desc.Rows), 1, fp);
					fwrite(&type_desc.Columns, sizeof(type_desc.Columns), 1, fp);
					fwrite(&type_desc.Elements, sizeof(type_desc.Elements), 1, fp);
					fwrite(&type_desc.Members, sizeof(type_desc.Members), 1, fp);
					fwrite(&type_desc.Offset, sizeof(type_desc.Offset), 1, fp);
					WriteString(type_desc.Name, fp);
				}
			}

			for (UINT i = 0; i < desc.BoundResources; ++ i)
			{
				D3D11_SHADER_INPUT_BIND_DESC si_desc;
				reflection->GetResourceBindingDesc(i, &si_desc);
				WriteString(si_desc.Name, fp);
				fwrite(&si_desc.Type, sizeof(si_desc.Type), 1, fp);
				fwrite(&si_desc.BindPoint, sizeof(si_desc.BindPoint), 1, fp);
				fwrite(&si_desc.BindCount, sizeof(si_desc.BindCount), 1, fp);
				fwrite(&si_desc.uFlags, sizeof(si_desc.uFlags), 1, fp);
				fwrite(&si_desc.ReturnType, sizeof(si_desc.ReturnType), 1, fp);
				fwrite(&si_desc.Dimension, sizeof(si_desc.Dimension), 1, fp);
				fwrite(&si_desc.NumSamples, sizeof(si_desc.NumSamples), 1, fp);
			}

			UINT const shader_type = D3D11_SHVER_GET_TYPE(desc.Version);
			if (shader_type == D3D11_SHVER_VERTEX_SHADER)
			{
				D3D11_SIGNATURE_PARAMETER_DESC_47 signature;
				for (UINT i = 0; i < desc.InputParameters; ++i)
				{
					reflection->GetInputParameterDesc(i, reinterpret_cast<D3D11_SIGNATURE_PARAMETER_DESC*>(&signature));
					WriteString(signature.SemanticName, fp);
					fwrite(&signature.SemanticIndex, sizeof(signature.SemanticIndex), 1, fp);
					fwrite(&signature.Register, sizeof(signature.Register), 1, fp);
					fwrite(&signature.SystemValueType, sizeof(signature.SystemValueType), 1, fp);
					fwrite(&signature.ComponentType, sizeof(signature.ComponentType), 1, fp);
					fwrite(&signature.Mask, sizeof(signature.Mask), 1, fp);
					fwrite(&signature.ReadWriteMask, sizeof(signature.ReadWriteMask), 1, fp);
					fwrite(&signature.Stream, sizeof(signature.Stream), 1, fp);
					fwrite(&signature.MinPrecision, sizeof(signature.MinPrecision), 1, fp);
				}
			}
			else if (shader_type == D3D11_SHVER_COMPUTE_SHADER)
			{
				UINT cs_block_size[3];
				reflection->GetThreadGroupSize(&cs_block_size[0], &cs_block_size[1], &cs_block_size[2]);
				fwrite(cs_block_size, sizeof(cs_block_size), 1, fp);
			}

			reflection->Release();

			fclose(fp);
		}

		delete[] bytecode;
	}
	else if (0 == strcmp(argv[1], "strip"))
	{
		if (argc < 5)
		{
			PrintHelps();
			return -1;
		}

		char const * input_file = argv[2];
		int flags = atoi(argv[3]);
		char const * output_file = argv[4];

		FILE* fp = fopen(input_file, "rb");
		fseek(fp, 0, SEEK_END);
		long bytecode_size = ftell(fp);
		fseek(fp, 0, SEEK_SET);
		char* bytecode = new char[bytecode_size];
		fread(bytecode, sizeof(char), bytecode_size, fp);
		fclose(fp);

		ID3DBlob* code = NULL;
		int hr = d3d_compiler.D3DStripShader(bytecode, bytecode_size, flags, &code);
		if (FAILED(hr))
		{
			printf("Strip error: 0x%x\n", hr);
		}

		fp = fopen(output_file, "wb");
		fwrite(code->GetBufferPointer(), sizeof(char), code->GetBufferSize(), fp);
		fclose(fp);

		delete[] bytecode;
	}

	return 0;
}
コード例 #28
0
ファイル: entry.cpp プロジェクト: jjaaddiicc/stserver
bool ParseKeys(CNV11* nv11)
{
	// If a keyboard hit is detected
	if (_kbhit())
	{
		char c = _getch(); // Get the key
		switch (c)
		{
		case 'x': return false;
		case 'e': 
				// Enable unit
				nv11->EnableValidator();
				break;
		case 'd':
				// Disable unit
				nv11->DisableValidator();
				break;
		case 'p':
			{
				if (IsPolling)
				{
					IsPolling = false; 
					cout << "Stopped polling" << endl;
				}
				else
				{
					IsPolling = true;
					cout << "Started polling" << endl;
				}
				break;
			}
		case 'r':
			{
				// Report the positions of any notes stored in the NV11
				cout << "Note positions: " << endl;
				nv11->OutputNoteLevelInfo();

				// Report which channel is recycling (1 recycling at once in NV11)
				nv11->OutputCurrentRecycling();
				WriteString(" is currently recycling");
				break;
			}
		case 'h': DisplayCommands(); break;
		case 't': 
				// Wait for thread release then reset the unit
				nv11->ResetValidator();
				nv11->CloseComPort();
				break;
		case 'c': 
			{
				string denom = GetInputString("Enter note value and currency E.g. 10 EUR: ");

				// Break into 2 strings, first contains value, second currency
				string s1 = "";	
				size_t pos = denom.find_first_of(' ');
				if (pos == denom.npos)
				{
					WriteString("Input was not in the correct format");
					break;
				}
				s1 = denom.substr(pos+1, s1.npos);
				denom.erase(pos, denom.npos);

				// Convert value to float
				float value = (float)atof(denom.c_str()) * 100.0f;

				if (value <= 0)
				{
					WriteString("Value was less than or equal to zero");
					break;
				}

				// Make sure each char in the currency is uppercase and
				// only 3 chars were entered
				if (s1.length() != 3)
				{
					WriteString("Invalid currency");
					break;
				}
				for (int i = 0; i < 3; ++i)
					s1[i] = toupper(s1[i]);

				// Get whether to stack or store note
				char stack = GetInputChar("1 = Store note\n2 = Stack note\n");
				int b = atoi(&stack)-1;
				if (b < 0 || b > 1)
				{
					WriteString("Invalid input");
					break;
				}
				nv11->ChangeRouting((int)value, (char*)s1.c_str(), b);
				break;
			}
		case 's':
				nv11->StackNextNote(); // Move the next note in the recycler to the cashbox
				break;
		case 'n': 
				nv11->PayoutNextNote(); // Payout the next note in the recycler
				break;
		case 'm': 
				nv11->EmptyPayout(); // Move all the notes in the recycler to the cashbox
				break;
		default: break;
		}
	}
	return true;
}
コード例 #29
0
ファイル: File.cpp プロジェクト: Arcadiaor/CNTK
// Put a zero/space terminated string into a file
// val - value to write to the file
File& File::operator<<(const std::string& val)
{
    WriteString(val.c_str());
    return *this;
}
コード例 #30
0
void asCRestore::WriteProperty(asCProperty* prop) 
{
	WriteString(&prop->name);
	WriteDataType(&prop->type);
	WRITE_NUM(prop->index);
}