Exemple #1
0
// read the next channel data.. fill it in *tone
// if tone isn't touched.. it should be inited so it just plays silence
// return 0 if it's passing more data
// return -1 if it's passing nothing (end of data)
int SoundGenPCJr::getNextNote_v2(int ch) {
	ToneChan *tpcm;
	SndGenChan *chan;
	const byte *data;

	assert(ch < CHAN_MAX);

	if (!_vm->getFlag(VM_FLAG_SOUND_ON))
		return -1;

	tpcm = &_tchannel[ch];
	chan = &_channel[ch];
	if (!chan->avail)
		return -1;

	while (chan->duration <= 0) {
		data = chan->data;

		// read the duration of the note
		chan->duration = READ_LE_UINT16(data);  // duration

		// if it's 0 then it's not going to be played
		// if it's 0xFFFF then the channel data has finished.
		if ((chan->duration == 0) || (chan->duration == 0xFFFF)) {
			tpcm->genTypePrev = -1;
			tpcm->freqCountPrev = -1;

			break;
		}

		_tchannel[ch].genTypePrev = -1;
		_tchannel[ch].freqCountPrev = -1;

		// only tone channels dissolve
		if ((ch != 3) && (_dissolveMethod != 0))    // != noise??
			chan->dissolveCount = 0;

		// attenuation (volume)
		writeData(data[4]);

		// frequency
		writeData(data[3]);
		writeData(data[2]);

		// data now points to the next data seg-a-ment
		chan->data += 5;
	}

	if (chan->duration == 0xFFFF) {
		// kill channel
		chan->avail = 0;
		chan->attenuation = 0x0F;   // silent
		chan->attenuationCopy = 0x0F;   // dunno really

		return -1;
	}

	chan->duration--;

	return 0;
}
Exemple #2
0
void AQCM0802::character(int column, int row, int c) {
    int a = address(column, row);
    writeCommand(a);
    writeData(c);
}
Exemple #3
0
// Initialise the display with the require screen orientation
void ILI9163::init(Rotation rotation) {

	width = ILI9163_WIDTH;
	height = ILI9163_HEIGHT;

    m_cs->write(1);
    m_reset->write(1);
   
    // Hardware reset the LCD
    reset();
    
    writeCommand(ILI9163_CMD_EXIT_SLEEP_MODE);
    _delay_ms(5); // Wait for the screen to wake up
    
    writeCommand(ILI9163_CMD_SET_PIXEL_FORMAT);
    writeData(0x05); // 16 bits per pixel
   
    writeCommand(ILI9163_CMD_SET_GAMMA_CURVE);
    writeData(0x04); // Select gamma curve 3
    
    writeCommand(ILI9163_CMD_GAM_R_SEL);
    writeData(0x01); // Gamma adjustment enabled
    
    writeCommand(ILI9163_CMD_POSITIVE_GAMMA_CORRECT);
    writeData(0x3f); // 1st Parameter
    writeData(0x25); // 2nd Parameter
    writeData(0x1c); // 3rd Parameter
    writeData(0x1e); // 4th Parameter
    writeData(0x20); // 5th Parameter
    writeData(0x12); // 6th Parameter
    writeData(0x2a); // 7th Parameter
    writeData(0x90); // 8th Parameter
    writeData(0x24); // 9th Parameter
    writeData(0x11); // 10th Parameter
    writeData(0x00); // 11th Parameter
    writeData(0x00); // 12th Parameter
    writeData(0x00); // 13th Parameter
    writeData(0x00); // 14th Parameter
    writeData(0x00); // 15th Parameter
     
    writeCommand(ILI9163_CMD_NEGATIVE_GAMMA_CORRECT);
    writeData(0x20); // 1st Parameter
    writeData(0x20); // 2nd Parameter
    writeData(0x20); // 3rd Parameter
    writeData(0x20); // 4th Parameter
    writeData(0x05); // 5th Parameter
    writeData(0x00); // 6th Parameter
    writeData(0x15); // 7th Parameter
    writeData(0xa7); // 8th Parameter
    writeData(0x3d); // 9th Parameter
    writeData(0x18); // 10th Parameter
    writeData(0x25); // 11th Parameter
    writeData(0x2a); // 12th Parameter
    writeData(0x2b); // 13th Parameter
    writeData(0x2b); // 14th Parameter
    writeData(0x3a); // 15th Parameter
    
    writeCommand(ILI9163_CMD_FRAME_RATE_CONTROL1);
    writeData(0x08); // DIVA = 8
    writeData(0x08); // VPA = 8
    
    writeCommand(ILI9163_CMD_DISPLAY_INVERSION);
    writeData(0x07); // NLA = 1, NLB = 1, NLC = 1 (all on Frame Inversion)
   
    writeCommand(ILI9163_CMD_POWER_CONTROL1);
    writeData(0x0a); // VRH = 10:  GVDD = 4.30
    writeData(0x02); // VC = 2: VCI1 = 2.65
      
    writeCommand(ILI9163_CMD_POWER_CONTROL2);
    writeData(0x02); // BT = 2: AVDD = 2xVCI1, VCL = -1xVCI1, VGH = 5xVCI1, VGL = -2xVCI1

    writeCommand(ILI9163_CMD_VCOM_CONTROL1);
    writeData(0x50); // VMH = 80: VCOMH voltage = 4.5
    writeData(0x5b); // VML = 91: VCOML voltage = -0.225
    
    writeCommand(ILI9163_CMD_VCOM_OFFSET_CONTROL);
    writeData(0x40); // nVM = 0, VMF = 64: VCOMH output = VMH, VCOML output = VML
    
    writeCommand(ILI9163_CMD_SET_COLUMN_ADDRESS);
    writeData(0x00); // XSH
    writeData(0x00); // XSL
    writeData(0x00); // XEH
    writeData(0x7f); // XEL (128 pixels x)
   
    writeCommand(ILI9163_CMD_SET_PAGE_ADDRESS);
    writeData(0x00);
    writeData(0x00);
    writeData(0x00);
    writeData(0x7f); // 128 pixels y
    
    // Select display orientation
    //writeCommand(ILI9163_CMD_SET_ADDRESS_MODE);
    //writeData(rotation);
    setRotation(rotation);

    // Set the display to on
    writeCommand(ILI9163_CMD_SET_DISPLAY_ON);
    writeCommand(ILI9163_CMD_WRITE_MEMORY_START);
}
/**
 * \par Function
 *   writeReg
 * \par Description
 *   Write the registor of i2c device.
 * \param[in]
 *   reg - the address of registor.
 * \param[in]
 *   data - the data that will be written to the registor.
 * \par Output
 *   None
 * \return
 *   Return the error code.
 *   the definition of the value of variable return_value:
 *   0:success
 *   1:BUFFER_LENGTH is shorter than size
 *   2:address send, nack received
 *   3:data send, nack received
 *   4:other twi error
 *   refer to the arduino official library twi.c
 * \par Others
 *   To set the registor for initializing.
 */
int8_t MeGyro::writeReg(int16_t reg, uint8_t data)
{
    int8_t return_value = 0;
    return_value = writeData(reg, &data, 1);
    return(return_value);
}
Exemple #5
0
int runCommand(int argc, char *argv[]){

	if (!readData()) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: Error reading mystore.dat\n\n%s|\n", Usage);
		return 1;
	}

	if (command == ADD && !add(argv[1],argv[2])) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: Failure to add new item|\n");
		return 1;
	}
	if (command == STAT) {
		printf("running stat\n");
		status();
	}
	if (command == SEARCH && !search(argv[1])) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: Cannot search %s|\n",argv[1]);
		return 1;
	}

	if (command == DISPLAY && !display(argv[1])) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: Cannot display %s|\n",argv[1]);
		return 1;
	}
	
	if (command == DELETE && !delete(argv[1])) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: Cannot delete %s|\n", argv[1]);
		return 1;
	}
	
	if (command == EDIT && !edit(argv[1])) {
		if (errmsg[0] != '\0')
			printf("|status: ERROR: %s|\n", errmsg);
		else
			printf("|status: ERROR: cannot edit %s|\n",argv[1]);
		return 1;
	}
	
	if (rewrite) {
		printf("rewriting\n");
		if (!writeData()) {
			if (errmsg[0] != '\0')
				printf("|status: ERROR: %s|\n", errmsg);
			else
				printf("|status: ERROR: Could not write the data, file may be destroyed|\n");
			return 1;
		}
	}
	return 0;
}
void processCommand( unsigned char cmd ) {
	
	if ( cmd == CMD_SELECT_DEVICE ) {
		selectedDevice = uart_getc( );
		uart_putc( BYTE_CR );
	} else if ( cmd == CMD_SHOW_ID ) {
		uart_puts( AVRISP_IDENTIFIER );
	} else if ( cmd == CMD_SOFTWARE_VERSION ) {
		uart_puts( AVRISP_SWVER );
	} else if ( cmd == CMD_HARDWARE_VERSION ) {
		uart_puts( AVRISP_HWVER );
	} else if ( cmd == CMD_LIST_SUPPORTED_DEVICES ) {
		uart_puts( AVRISP_SUPPORTED_DEVICES );
		uart_putc( 0 ); // terminating null character needs to be sent
	} else if ( cmd == CMD_PROGRAMMER_TYPE ) {
		uart_putc( AVRISP_PROGRAMMER_TYPE );
	} else if ( cmd == CMD_SUPPORTS_AUTOINCREMENT ) {
		uart_putc( AVRISP_RESP_YES );
	} else if ( cmd == CMD_SET_LED ) {
		LED_on( );
		uart_putc( BYTE_CR );
	} else if ( cmd == CMD_CLEAR_LED ) {
		LED_off( );
		uart_putc( BYTE_CR );
	} else if ( selectedDevice == 0 ) {
		// require a device for the rest of the commands
		uart_putc( AVRISP_RESP_UNKNOWN );
		return;
	}
	
	// command not specified above
	
	if ( cmd == CMD_ENTER_PROGRAM_MODE ) {
		enableProgramMode( );
	} else if ( cmd == CMD_LEAVE_PROGRAM_MODE ) {
		leaveProgramMode( );
	} else if ( cmd == CMD_WRITE_PROG_H ) {
		writeProgH( );
	} else if ( cmd == CMD_WRITE_PROG_L ) {
		writeProgL( );
	} else if ( cmd == CMD_READ_PROG ) {
		readProg( );
	} else if ( cmd == CMD_LOAD_ADDRESS ) {
		loadAddress( );
	} else if ( cmd == CMD_WRITE_DATA ) {
		writeData( );
	} else if ( cmd == CMD_READ_DATA ) {
		readData( );
	} else if ( cmd == CMD_CHIP_ERASE ) {
		chipErase( );
	} else if ( cmd == CMD_WRITE_LOCK_BITS ) {
		writeLockBits( );
	} else if ( cmd == CMD_READ_SIGNATURE ) {
		readSignature( );
	} else if ( cmd == CMD_WRITE_PROGRAM_PAGE ) {
		writeProgramPage( );
	} else if ( cmd == CMD_UNIVERSAL_3 ) {
		universalWrite3( );
	} else if ( cmd == CMD_UNIVERSAL_4 ) {
		universalWrite4( );
	} else if ( cmd == CMD_LOAD_ADDRESS_0 ) {
		currentAddress = 0;
		uart_putc( BYTE_CR );
	}
}
Exemple #7
0
void doShell(Client* shellClient) {
    Client* p;
    char head[HEAD_SIZE], value[VALUE_SIZE];

    char fileBuffer[FILE_BUFFER_SIZE + 1];
    char fileChunk[FILE_CHUNK_SIZE];
    char filename[256];
    unsigned long fileSize;
    int fd;
    FILE* fp;

    FDEBUG(("shell start\n"));
    while (1) {
        // shell 담당 서버는 shell 클라이언트로부터 신호를 받아야만 일합니다.
        readMsg(shellClient->socket, head, value);

        if ( !strcmp(head, ADD) ) {
            // 파일 추가
            FDEBUG(("get ADD message\n"));
            fileSize = 0;

            // 우선 해당 이름으로 파일을 엽니다.
            strcpy(filename, value);
            fd = open(filename, O_WRONLY | O_CREAT, 0644);
            if (fd == -1) {
                writeMsg(shellClient->socket, ERR, "fileopen_err");
                continue;
            }

            // 다른 일반 클라이언트들에게도 이 사실을 알립니다.
            writeMsg(shellClient->socket, ACCEPT, "fileadd");
            p = front;
            while (p) {
                writeMsg(p->pipe[1], ADD, filename);
                p = p->nextClient;
            }

            // 파일 구분자를 입력받습니다.
            readMsg(shellClient->socket, head, fileChunk);
            writeMsg(shellClient->socket, ACCEPT, "filechunk");
            p = front;
            while (p) {
                writeMsg(p->pipe[1], CHUNK, fileChunk);
                p = p->nextClient;
            }

            // 파일을 읽어서 클라이언트에게 전달합니다. 서버에도 한 부 저장합니다.
            FDEBUG(("start reading file\n"));
            while (true) {
                memset(fileBuffer, 0, sizeof(fileBuffer));
                readData(shellClient->socket, fileBuffer);

                p = front;
                while (p) {
                    writeData(p->pipe[1], fileBuffer);
                    p = p->nextClient;
                }

                // 파일 전송이 끝나면 끝냅니다.
                if ( !strcmp(fileBuffer, fileChunk) ) break;
                // 아니라면 서버에 저장하고 다음 부분을 보내달라고 요청합니다.
                else writeData(fd, fileBuffer);
                writeMsg(shellClient->socket, CHUNK, fileChunk);
                fileSize += strlen(fileBuffer);
            }
            // 파일을 전부 기록했습니다. 닫고 EOF 메시지를 전달합니다.
            close(fd);
            writeMsg(shellClient->socket, ACCEPT, "eof");
            p = front;
            while (p) {
                writeMsg(p->pipe[1], ACCEPT, "eof");
                p = p->nextClient;
            }

            // 결과를 출력합니다.
            Notice("ADD ");
            printf("[%s][%ldbyte] from Client(%d)\n", filename, fileSize, shellClient->clientNo);

        } else
        if ( !strcmp(head, DEL) ) {
            // 삭제할 파일의 크기를 구합니다.
            fp = fopen(value, "r");
            fseek(fp, 0L, SEEK_END);
            fileSize = ftell(fp);
            fclose(fp);

            // 결과를 출력합니다.
            Notice ("DELETE ");
            printf("[%s][%ldbyte] from Client(%d)\n", value, fileSize, shellClient->clientNo);

            // 파일을 삭제하고 다른 클라이언트에게 알립니다.
            remove( value );

            p = front;
            while (p) {
                writeMsg(p->pipe[1], head, value);
                p = p->nextClient;
            }

        }
    }
}
Exemple #8
0
qint64 AudioRingBuffer::writeSamples(const int16_t* source, qint64 maxSamples) {    
    return writeData((const char*) source, maxSamples * sizeof(int16_t));
}
Exemple #9
0
int AudioRingBuffer::parseData(const QByteArray& packet) {
    int numBytesPacketHeader = numBytesForPacketHeader(packet);
    return writeData(packet.data() + numBytesPacketHeader, packet.size() - numBytesPacketHeader);
}
Exemple #10
0
void TextLCD::character(int column, int row, int c) {
      int address = 0x80 + (row * 40) + column; // memory starts at 0x80, and is 40 chars long per row
      writeCommand(address);           
      writeData(c); 
}
Exemple #11
0
	void Profiler::shutdown()
	{
		writeData();
	}
Exemple #12
0
void TFTLCD::writeRegister(uint16_t addr, uint16_t data) {
   writeCommand(addr);
   writeData(data);
}
Exemple #13
0
void VTKExporter::writeVTKSimple()
{
    std::string filename = vtkFilename.getFullPath();

    std::ostringstream oss;
    oss << "_" << nbFiles;

    if (filename.size() > 3) {
        std::string ext;
        std::string baseName;
        if (filename.substr(filename.size()-4)==".vtu") {
            ext = ".vtu";
            baseName = filename.substr(0, filename.size()-4);
        }

        if (filename.substr(filename.size()-4)==".vtk") {
            ext = ".vtk";
            baseName = filename.substr(0, filename.size()-4);
        }

        /// no extension given => default "vtu"
        if (ext == "") {
            ext = ".vtu";
            baseName = filename;
        }

        if (overwrite.getValue())
            filename = baseName + ext;
        else
            filename = baseName + oss.str() + ext;

    }

    /*if ( filename.size() > 3 && filename.substr(filename.size()-4)==".vtu")
    {
        if (!overwrite.getValue())
            filename = filename.substr(0,filename.size()-4) + oss.str() + ".vtu";
    }
    else
    {
        if (!overwrite.getValue())
            filename += oss.str();
        filename += ".vtu";
    }*/

    outfile = new std::ofstream(filename.c_str());
    if( !outfile->is_open() )
    {
        msg_error() << "Error creating file "<<filename;
        delete outfile;
        outfile = NULL;
        return;
    }

    const helper::vector<std::string>& pointsData = dPointsDataFields.getValue();
    const helper::vector<std::string>& cellsData = dCellsDataFields.getValue();

    helper::ReadAccessor<Data<defaulttype::Vec3Types::VecCoord> > pointsPos = position;

    const int nbp = (!pointsPos.empty()) ? pointsPos.size() : topology->getNbPoints();

    //Write header
    *outfile << "# vtk DataFile Version 2.0" << std::endl;

    //write Title
    *outfile << "Exported VTK file" << std::endl;

    //write Data type
    *outfile << "ASCII" << std::endl;

    *outfile << std::endl;

    //write dataset (geometry, unstructured grid)
    *outfile << "DATASET " << "UNSTRUCTURED_GRID" << std::endl;

    *outfile << "POINTS " << nbp << " float" << std::endl;
    //write Points
    if (!pointsPos.empty())
    {
        for (int i=0 ; i<nbp; i++)
        {
            *outfile << pointsPos[i] << std::endl;
        }
    }
    else if (mstate && mstate->getSize() == (size_t)nbp)
    {
        for (size_t i=0 ; i<mstate->getSize() ; i++)
        {
            *outfile << mstate->getPX(i) << " " << mstate->getPY(i) << " " << mstate->getPZ(i) << std::endl;
        }
    }
    else
    {
        for (int i=0 ; i<nbp ; i++)
        {
            *outfile << topology->getPX(i) << " " << topology->getPY(i) << " " << topology->getPZ(i) << std::endl;
        }
    }

    *outfile << std::endl;

    //Write Cells
    unsigned int numberOfCells, totalSize;
    numberOfCells = ( (writeEdges.getValue()) ? topology->getNbEdges() : 0 )
            +( (writeTriangles.getValue()) ? topology->getNbTriangles() : 0 )
            +( (writeQuads.getValue()) ? topology->getNbQuads() : 0 )
            +( (writeTetras.getValue()) ? topology->getNbTetras() : 0 )
            +( (writeHexas.getValue()) ? topology->getNbHexas() : 0 );
    totalSize =     ( (writeEdges.getValue()) ? 3 * topology->getNbEdges() : 0 )
            +( (writeTriangles.getValue()) ? 4 *topology->getNbTriangles() : 0 )
            +( (writeQuads.getValue()) ? 5 *topology->getNbQuads() : 0 )
            +( (writeTetras.getValue()) ? 5 *topology->getNbTetras() : 0 )
            +( (writeHexas.getValue()) ? 9 *topology->getNbHexas() : 0 );


    *outfile << "CELLS " << numberOfCells << " " << totalSize << std::endl;

    if (writeEdges.getValue())
    {
        for (int i=0 ; i<topology->getNbEdges() ; i++)
            *outfile << 2 << " " << topology->getEdge(i) << std::endl;
    }

    if (writeTriangles.getValue())
    {
        for (int i=0 ; i<topology->getNbTriangles() ; i++)
            *outfile << 3 << " " <<  topology->getTriangle(i) << std::endl;
    }
    if (writeQuads.getValue())
    {
        for (int i=0 ; i<topology->getNbQuads() ; i++)
            *outfile << 4 << " " << topology->getQuad(i) << std::endl;
    }

    if (writeTetras.getValue())
    {
        for (int i=0 ; i<topology->getNbTetras() ; i++)
            *outfile << 4 << " " <<  topology->getTetra(i) << std::endl;
    }
    if (writeHexas.getValue())
    {
        for (int i=0 ; i<topology->getNbHexas() ; i++)
            *outfile << 8 << " " <<  topology->getHexa(i) << std::endl;
    }

    *outfile << std::endl;

    *outfile << "CELL_TYPES " << numberOfCells << std::endl;

    if (writeEdges.getValue())
    {
        for (int i=0 ; i<topology->getNbEdges() ; i++)
            *outfile << 3 << std::endl;
    }

    if (writeTriangles.getValue())
    {
        for (int i=0 ; i<topology->getNbTriangles() ; i++)
            *outfile << 5 << std::endl;
    }
    if (writeQuads.getValue())
    {
        for (int i=0 ; i<topology->getNbQuads() ; i++)
            *outfile << 9 << std::endl;
    }

    if (writeTetras.getValue())
    {
        for (int i=0 ; i<topology->getNbTetras() ; i++)
            *outfile << 10 << std::endl;
    }
    if (writeHexas.getValue())
    {
        for (int i=0 ; i<topology->getNbHexas() ; i++)
            *outfile << 12 << std::endl;
    }

    *outfile << std::endl;

    //write dataset attributes
    if (!pointsData.empty())
    {
        *outfile << "POINT_DATA " << nbp << std::endl;
        writeData(pointsDataObject, pointsDataField, pointsDataName);
    }

    if (!cellsData.empty())
    {
        *outfile << "CELL_DATA " << numberOfCells << std::endl;
        writeData(cellsDataObject, cellsDataField, cellsDataName);
    }

    outfile->close();

    ++nbFiles;

    msg_info() << "Export VTK in file " << filename << "  done.";
}
void RawData::writeData(const QByteArray& data)
{
    writeData(data,data.length());
}
Exemple #15
0
bool Foam::regIOobject::writeObject
(
    IOstream::streamFormat fmt,
    IOstream::versionNumber ver,
    IOstream::compressionType cmp
) const
{
    if (!good())
    {
        SeriousErrorIn("regIOobject::write()")
            << "bad object " << name()
            << endl;

        return false;
    }

    if (instance().empty())
    {
        SeriousErrorIn("regIOobject::write()")
            << "instance undefined for object " << name()
            << endl;

        return false;
    }

    if
    (
        instance() != time().timeName()
     && instance() != time().system()
     && instance() != time().caseSystem()
     && instance() != time().constant()
     && instance() != time().caseConstant()
    )
    {
        const_cast<regIOobject&>(*this).instance() = time().timeName();
    }

    mkDir(path());

    if (OFstream::debug)
    {
        Info<< "regIOobject::write() : "
            << "writing file " << objectPath();
    }


    bool osGood = false;

    {
        // Try opening an OFstream for object
        OFstream os(objectPath(), fmt, ver, cmp);

        // If any of these fail, return (leave error handling to Ostream class)
        if (!os.good())
        {
            return false;
        }

        if (!writeHeader(os))
        {
            return false;
        }

        // Write the data to the Ostream
        if (!writeData(os))
        {
            return false;
        }

        writeEndDivider(os);

        osGood = os.good();
    }

    if (OFstream::debug)
    {
        Info<< " .... written" << endl;
    }

    // Only update the lastModified_ time if this object is re-readable,
    // i.e. lastModified_ is already set
    if (lastModified_)
    {
        lastModified_ = lastModified(objectPath());
    }

    return osGood;
}
Exemple #16
0
void SocksClient::processOutgoing(const QByteArray &block)
{
#ifdef PROX_DEBUG
    // show hex
    fprintf(stderr, "SocksClient: client recv { ");
    for(int n = 0; n < (int)block.size(); ++n)
        fprintf(stderr, "%02X ", (unsigned char)block[n]);
    fprintf(stderr, " } \n");
#endif
    d->recvBuf += block;

    if(d->step == StepVersion) {
        SPSS_VERSION s;
        int r = sps_get_version(d->recvBuf, &s);
        if(r == -1) {
            resetConnection(true);
            setError(ErrProxyNeg);
            return;
        }
        else if(r == 1) {
            if(s.version != 0x05 || s.method == 0xff) {
#ifdef PROX_DEBUG
                fprintf(stderr, "SocksClient: Method selection failed\n");
#endif
                resetConnection(true);
                setError(ErrProxyNeg);
                return;
            }

            QString str;
            if(s.method == 0x00) {
                str = "None";
                d->authMethod = AuthNone;
            }
            else if(s.method == 0x02) {
                str = "Username/Password";
                d->authMethod = AuthUsername;
            }
            else {
#ifdef PROX_DEBUG
                fprintf(stderr, "SocksClient: Server wants to use unknown method '%02x'\n", s.method);
#endif
                resetConnection(true);
                setError(ErrProxyNeg);
                return;
            }

            if(d->authMethod == AuthNone) {
                // no auth, go straight to the request
                do_request();
            }
            else if(d->authMethod == AuthUsername) {
                d->step = StepAuth;
#ifdef PROX_DEBUG
                fprintf(stderr, "SocksClient: Authenticating [Username] ...\n");
#endif
                writeData(spc_set_authUsername(d->user.toLatin1(), d->pass.toLatin1()));
            }
        }
    }
    if(d->step == StepAuth) {
        if(d->authMethod == AuthUsername) {
            SPSS_AUTHUSERNAME s;
            int r = sps_get_authUsername(d->recvBuf, &s);
            if(r == -1) {
                resetConnection(true);
                setError(ErrProxyNeg);
                return;
            }
            else if(r == 1) {
                if(s.version != 0x01) {
                    resetConnection(true);
                    setError(ErrProxyNeg);
                    return;
                }
                if(!s.success) {
                    resetConnection(true);
                    setError(ErrProxyAuth);
                    return;
                }

                do_request();
            }
        }
    }
    else if(d->step == StepRequest) {
        SPS_CONNREQ s;
        int r = sp_get_request(d->recvBuf, &s);
        if(r == -1) {
            resetConnection(true);
            setError(ErrProxyNeg);
            return;
        }
        else if(r == 1) {
            if(s.cmd != RET_SUCCESS) {
#ifdef PROX_DEBUG
                fprintf(stderr, "SocksClient: client << Error >> [%02x]\n", s.cmd);
#endif
                resetConnection(true);
                if(s.cmd == RET_UNREACHABLE)
                    setError(ErrHostNotFound);
                else if(s.cmd == RET_CONNREFUSED)
                    setError(ErrConnectionRefused);
                else
                    setError(ErrProxyNeg);
                return;
            }

#ifdef PROX_DEBUG
            fprintf(stderr, "SocksClient: client << Success >>\n");
#endif
            if(d->udp) {
                if(s.address_type == 0x03)
                    d->udpAddr = s.host;
                else
                    d->udpAddr = s.addr.toString();
                d->udpPort = s.port;
            }

            setOpenMode(QIODevice::ReadWrite);

            QPointer<QObject> self = this;
            setOpenMode(QIODevice::ReadWrite);
            emit connected();
            if(!self)
                return;

            if(!d->recvBuf.isEmpty()) {
                appendRead(d->recvBuf);
                d->recvBuf.resize(0);
                readyRead();
            }
        }
    }
}
Exemple #17
0
uint8_t DisplayCom::writeEscSeq(const uint8_t *escSeq)
{
	bool isEsc = false;
	uint8_t cmd;
	uint8_t value;

	// Loop until we find the ESC_END command.
	for (;;)
	{
		value = pgm_read_byte(escSeq);

		if (!isEsc)
		{
			if (value != 0xff)
			{
#ifdef __AVR__
				writeData(value);
#else
				writeData(value, false);
#endif
			}
			else
			{
				isEsc = true;
			}
		}
		else
		{
			escSeq++;

			cmd = value;
			value = pgm_read_byte(escSeq);

			switch (cmd)
			{
			case DC_DELAY:
				delay(value);
				break;

			case DC_CS:
				enableChip(value);
				break;

			case DC_ADR:
				setData(value);
				break;

			case DC_RESET:
				reset(value);
				break;

			case DC_END:
				// This is the end of the read so return.
				return 0;
			}

			isEsc = false;
		}

		escSeq++;
	}
}
Exemple #18
0
void  writeReg(uint8_t reg, uint8_t val)
{
  writeCommand(reg);
  writeData(val);
}
Exemple #19
0
void JSONVertexArray::write(std::ostream& str, WriteVisitor& visitor)
{
    bool _useExternalBinaryArray = visitor._useExternalBinaryArray;
    bool _mergeAllBinaryFiles = visitor._mergeAllBinaryFiles;
    std::string basename = visitor._baseName;

    addUniqueID();

    std::stringstream url;
    if (visitor._useExternalBinaryArray) {
        if (visitor._mergeAllBinaryFiles)
            url << visitor.getBinaryFilename();
        else
            url << basename << "_" << _uniqueID << ".bin";
    }

    std::string type;
        
    osg::ref_ptr<const osg::Array> array = _arrayData;

    switch (array->getType()) {
    case osg::Array::FloatArrayType:
    case osg::Array::Vec2ArrayType:
    case osg::Array::Vec3ArrayType:
    case osg::Array::Vec4ArrayType:
        type = "Float32Array";
        break;
    case osg::Array::Vec4ubArrayType:
    {
        osg::ref_ptr<osg::Vec4Array> converted = new osg::Vec4Array;
        converted->reserve(array->getNumElements());
            
        const osg::Vec4ubArray* a = dynamic_cast<const osg::Vec4ubArray*>(array.get());
        for (unsigned int i = 0; i < a->getNumElements(); ++i) {
            converted->push_back(osg::Vec4( (*a)[i][0]/255.0,
                                            (*a)[i][1]/255.0,
                                            (*a)[i][2]/255.0,
                                            (*a)[i][3]/255.0));
        }
        array = converted;
        type = "Float32Array";
    }
    break;
    case osg::Array::UShortArrayType:
        type = "Uint16Array";
        break;
    default:
        osg::notify(osg::WARN) << "Array of type " << array->getType() << " not supported" << std::endl;
        break;
    }

    str << "{ " << std::endl;
    JSONObjectBase::level++;
    str << JSONObjectBase::indent() << "\"" << type << "\"" << ": { " << std::endl;
    JSONObjectBase::level++;
    if (_useExternalBinaryArray) {
        str << JSONObjectBase::indent() << "\"File\": \"" << url.str() << "\","<< std::endl;
    } else {
        if (array->getNumElements() == 0) {
            str << JSONObjectBase::indent() << "\"Elements\": [ ],";

        } else {

            switch (array->getType()) {
            case osg::Array::FloatArrayType:
            case osg::Array::Vec2ArrayType:
            case osg::Array::Vec3ArrayType:
            case osg::Array::Vec4ArrayType:
            {
                const float* a = static_cast<const float*>(array->getDataPointer());
                unsigned int size = array->getNumElements() * array->getDataSize();
                writeInlineArrayReal<float>(str, size, a);
            }
            break;
            case osg::Array::DoubleArrayType:
            case osg::Array::Vec2dArrayType:
            case osg::Array::Vec3dArrayType:
            case osg::Array::Vec4dArrayType:
            {
                const double* a = static_cast<const double*>(array->getDataPointer());
                unsigned int size = array->getNumElements() * array->getDataSize();
                writeInlineArrayReal<double>(str, size, a);
            }
            break;
            case osg::Array::ByteArrayType:
            case osg::Array::Vec2bArrayType:
            case osg::Array::Vec3bArrayType:
            case osg::Array::Vec4bArrayType:
            {
                const char* a = static_cast<const char*>(array->getDataPointer());
                unsigned int size = array->getNumElements() * array->getDataSize();
                writeInlineArray<char>(str, size, a);
            }
            break;
            case osg::Array::UByteArrayType:
            case osg::Array::Vec4ubArrayType:
            {
                const unsigned char* a = static_cast<const unsigned char*>(array->getDataPointer());
                unsigned int size = array->getNumElements() * array->getDataSize();
                writeInlineArray<unsigned char>(str, size, a);
            }
            break;
            case osg::Array::UShortArrayType:
            {
                const unsigned short* a = static_cast<const unsigned short*>(array->getDataPointer());
                unsigned int size = array->getNumElements() * array->getDataSize();
                writeInlineArray<unsigned short>(str, size, a);
            }
            break;
            case osg::Array::ShortArrayType:
            case osg::Array::Vec2sArrayType:
            case osg::Array::Vec3sArrayType:
            case osg::Array::Vec4sArrayType:
            {
                const short* a = static_cast<const short*>(array->getDataPointer());
                unsigned int size = array->getNumElements() * array->getDataSize();
                writeInlineArray<short>(str, size, a);
            }
            break;
            case osg::Array::IntArrayType:
            {
                const int* a = static_cast<const int*>(array->getDataPointer());
                unsigned int size = array->getNumElements() * array->getDataSize();
                writeInlineArray<int>(str, size, a);
            }
            break;
            case osg::Array::UIntArrayType:
            {
                const unsigned int* a = static_cast<const unsigned int*>(array->getDataPointer());
                unsigned int size = array->getNumElements() * array->getDataSize();
                writeInlineArray<unsigned int>(str, size, a);
            }
            break;

            }
        }
    }

    str << JSONObjectBase::indent() << "\"Size\": " << array->getNumElements();
    if (_useExternalBinaryArray) {
        str << "," << std::endl;
    } else {
        str << std::endl;
    }

    if (_useExternalBinaryArray) {
        unsigned int size;
        if (_mergeAllBinaryFiles) {
            std::pair<unsigned int, unsigned int> result;
            result = writeMergeData(array.get(), visitor);
            unsigned int offset = result.first;
            size = result.second;
            str << JSONObjectBase::indent() << "\"Offset\": " << offset << std::endl;
        } else {
            size = writeData(array.get(), url.str());
            str << JSONObjectBase::indent() << "\"Offset\": " << 0 << std::endl;
        }
        std::stringstream b;
        osg::notify(osg::NOTICE) << "TypedArray " << type << " " << url.str() << " ";
        if (size/1024.0 < 1.0) {
            osg::notify(osg::NOTICE) << size << " bytes" << std::endl;
        } else if (size/(1024.0*1024.0) < 1.0) { 
            osg::notify(osg::NOTICE) << size/1024.0 << " kb" << std::endl;
        } else {
            osg::notify(osg::NOTICE) << size/(1024.0*1024.0) << " mb" << std::endl;
        }

    }

    JSONObjectBase::level--;
    str << JSONObjectBase::indent() << "}" << std::endl;
    JSONObjectBase::level--;

    str << JSONObjectBase::indent() << "}";
}
Exemple #20
0
/********************************f******************************************/
void graphicsMode(void) {
  writeCommand(RA8875_MWCR0);
  uint8_t temp = readData();
  temp &= ~RA8875_MWCR0_TXTMODE; // bit #7
  writeData(temp);
}
void NativeBlockOutputStream::writeData(const IDataType & type, const ColumnPtr & column, WriteBuffer & ostr, size_t offset, size_t limit)
{
    /** If there are columns-constants - then we materialize them.
      * (Since the data type does not know how to serialize / deserialize constants.)
      */
    ColumnPtr full_column;

    if (auto converted = column->convertToFullColumnIfConst())
        full_column = converted;
    else
        full_column = column;

    if (type.isNullable())
    {
        const DataTypeNullable & nullable_type = static_cast<const DataTypeNullable &>(type);
        const IDataType & nested_type = *nullable_type.getNestedType();

        const ColumnNullable & nullable_col = static_cast<const ColumnNullable &>(*full_column.get());
        const ColumnPtr & nested_col = nullable_col.getNestedColumn();

        const IColumn & null_map = nullable_col.getNullMapConcreteColumn();
        DataTypeUInt8{}.serializeBinaryBulk(null_map, ostr, offset, limit);

        writeData(nested_type, nested_col, ostr, offset, limit);
    }
    else if (const DataTypeArray * type_arr = typeid_cast<const DataTypeArray *>(&type))
    {
        /** For arrays, you first need to serialize the offsets, and then the values.
          */
        const ColumnArray & column_array = typeid_cast<const ColumnArray &>(*full_column);
        type_arr->getOffsetsType()->serializeBinaryBulk(*column_array.getOffsetsColumn(), ostr, offset, limit);

        if (!typeid_cast<const ColumnArray &>(*full_column).getData().empty())
        {
            const ColumnArray::Offsets_t & offsets = column_array.getOffsets();

            if (offset > offsets.size())
                return;

            /** offset - from which array to write.
              * limit - how many arrays should be written, or 0, if you write everything that is.
              * end - up to which array written part finishes.
              *
              * nested_offset - from which nested element to write.
              * nested_limit - how many nested elements to write, or 0, if you write everything that is.
              */

            size_t end = std::min(offset + limit, offsets.size());

            size_t nested_offset = offset ? offsets[offset - 1] : 0;
            size_t nested_limit = limit
                ? offsets[end - 1] - nested_offset
                : 0;

            const DataTypePtr & nested_type = type_arr->getNestedType();

            DataTypePtr actual_type;
            if (nested_type->isNull())
            {
                /// Special case: an array of Null is actually an array of Nullable(UInt8).
                actual_type = std::make_shared<DataTypeNullable>(std::make_shared<DataTypeUInt8>());
            }
            else
                actual_type = nested_type;

            if (limit == 0 || nested_limit)
                writeData(*actual_type, typeid_cast<const ColumnArray &>(*full_column).getDataPtr(), ostr, nested_offset, nested_limit);
        }
    }
    else
        type.serializeBinaryBulk(*full_column, ostr, offset, limit);
}
Exemple #22
0
int main(int argc, char **argv)
{
	TSS_RESULT tResult;
	TSS_HTPM hTpm;
	TSS_HKEY hEk;
	TSS_FLAG fEkAttrs;
	int iRc = -1;

#ifdef TSS_LIB_IS_12
	struct option opts[] = {{"revocable", no_argument, NULL, 'r'},
	{"generate-secret", no_argument, NULL, 'g'},
	{"infile", required_argument, NULL, 'i'},
	{"outfile", required_argument, NULL, 'o'},
	};
	UINT32 revDataSz;
	BYTE revokeData[TPM_SHA1BASED_NONCE_LEN];
	BYTE *pRevData;
#endif

	initIntlSys();

#ifdef TSS_LIB_IS_12
	if (genericOptHandler(argc, argv, "rgi:o:", opts, sizeof(opts) / sizeof(struct option),
			      parse, help) != 0)
		goto out;

	//Check commands for command hierarchy
	if (isRevocable) {
		if (needGenerateSecret) {
			if (!outFileSet) {
				logError(_("Please specify an output file\n"));
				goto out;
			}
			if (inFileSet) {
				logError(_("The option -i, --infile is not valid with -g\n"));
				goto out;
			}
		} else if (!inFileSet) {
			logError(_("Please specify -i, --infile or -g, --generate-secret\n"));
			goto out;
		} else if (outFileSet) {
			logError(_("The option -o, --outfile is not valid with -i, --infile"));
			goto out;
		}
	}
	logDebug("Input file name: %s\n", in_filename);
	logDebug("Output file name: %s\n", out_filename);

	if (inFileSet) {
		pRevData = revokeData;
		revDataSz = sizeof(revokeData);
		if (readData(revDataSz, &pRevData))
			goto out;
	} else if (outFileSet) {
		FILE *outfile = fopen(out_filename, "w");
		if (!outfile) {
			iRc = -1;
			logError(_("Unable to open output file: %s\n"), out_filename);
			goto out;
		}
		fclose(outfile);

		//TPM should generate the revoke data
		revDataSz = 0;
		pRevData = NULL;
	}
#else
	if (genericOptHandler(argc, argv, NULL, NULL, 0, NULL, NULL) != 0){
		logError(_("See man pages for details.\n"));
		goto out;
	}
#endif

	if (contextCreate(&hContext) != TSS_SUCCESS)
		goto out;

	if (contextConnect(hContext) != TSS_SUCCESS)
		goto out_close;

	if (contextGetTpm(hContext, &hTpm) != TSS_SUCCESS)
		goto out_close;

	//Initialize EK attributes here
	fEkAttrs = TSS_KEY_SIZE_2048 | TSS_KEY_TYPE_LEGACY;
	if (contextCreateObject(hContext, TSS_OBJECT_TYPE_RSAKEY, fEkAttrs, &hEk) != TSS_SUCCESS)
		goto out_close;

#ifdef TSS_LIB_IS_12
	if (isRevocable){
		tResult = tpmCreateRevEk(hTpm, hEk, NULL, &revDataSz, &pRevData);
		if (tResult != TSS_SUCCESS)
			goto out_close;
		//Writes the generated secret into the output file
		if (outFileSet) {
			if (writeData(revDataSz, pRevData)) {
				logError(_("Creating revocable EK succeeded, but writing the EK "
					   "revoke authorization to disk failed.\nPrinting the "
					   "revoke authorization instead:\n"));
				logHex(revDataSz, pRevData);
				logError(_("You should record this data, as its the authorization "
					   "you'll need to revoke your EK!\n"));
				goto out_close;
			}
		}
	} else
#endif
		tResult = tpmCreateEk(hTpm, hEk, NULL);
	if (tResult != TSS_SUCCESS)
		goto out_close;

	iRc = 0;
	logSuccess(argv[0]);

      out_close:
	contextClose(hContext);

      out:
	return iRc;
}
Preferences::~Preferences()
{
    if ( d->dirty_ )
		writeData();
	delete d;
}
void TextLCD::character(int column, int row, int c) {
    int a = address(column, row);
    writeCommand(a);
    writeData(c);
}
Exemple #25
0
void KeePass2Writer::writeDatabase(QIODevice* device, Database* db)
{
    m_error = false;
    m_errorStr.clear();

    QByteArray masterSeed = Random::randomArray(32);
    QByteArray encryptionIV = Random::randomArray(16);
    QByteArray protectedStreamKey = Random::randomArray(32);
    QByteArray startBytes = Random::randomArray(32);
    QByteArray endOfHeader = "\r\n\r\n";

    CryptoHash hash(CryptoHash::Sha256);
    hash.addData(masterSeed);
    Q_ASSERT(!db->transformedMasterKey().isEmpty());
    hash.addData(db->transformedMasterKey());
    QByteArray finalKey = hash.result();

    QBuffer header;
    header.open(QIODevice::WriteOnly);
    m_device = &header;

    CHECK_RETURN(writeData(Endian::int32ToBytes(KeePass2::SIGNATURE_1, KeePass2::BYTEORDER)));
    CHECK_RETURN(writeData(Endian::int32ToBytes(KeePass2::SIGNATURE_2, KeePass2::BYTEORDER)));
    CHECK_RETURN(writeData(Endian::int32ToBytes(KeePass2::FILE_VERSION, KeePass2::BYTEORDER)));

    CHECK_RETURN(writeHeaderField(KeePass2::CipherID, db->cipher().toByteArray()));
    CHECK_RETURN(writeHeaderField(KeePass2::CompressionFlags,
                                  Endian::int32ToBytes(db->compressionAlgo(),
                                                       KeePass2::BYTEORDER)));
    CHECK_RETURN(writeHeaderField(KeePass2::MasterSeed, masterSeed));
    CHECK_RETURN(writeHeaderField(KeePass2::TransformSeed, db->transformSeed()));
    CHECK_RETURN(writeHeaderField(KeePass2::TransformRounds,
                                  Endian::int64ToBytes(db->transformRounds(),
                                                       KeePass2::BYTEORDER)));
    CHECK_RETURN(writeHeaderField(KeePass2::EncryptionIV, encryptionIV));
    CHECK_RETURN(writeHeaderField(KeePass2::ProtectedStreamKey, protectedStreamKey));
    CHECK_RETURN(writeHeaderField(KeePass2::StreamStartBytes, startBytes));
    CHECK_RETURN(writeHeaderField(KeePass2::InnerRandomStreamID,
                                  Endian::int32ToBytes(KeePass2::Salsa20,
                                                       KeePass2::BYTEORDER)));
    CHECK_RETURN(writeHeaderField(KeePass2::EndOfHeader, endOfHeader));

    header.close();
    m_device = device;
    QByteArray headerHash = CryptoHash::hash(header.data(), CryptoHash::Sha256);
    CHECK_RETURN(writeData(header.data()));

    SymmetricCipherStream cipherStream(device, SymmetricCipher::Aes256, SymmetricCipher::Cbc,
                                       SymmetricCipher::Encrypt, finalKey, encryptionIV);
    cipherStream.open(QIODevice::WriteOnly);
    m_device = &cipherStream;
    CHECK_RETURN(writeData(startBytes));

    HashedBlockStream hashedStream(&cipherStream);
    hashedStream.open(QIODevice::WriteOnly);

    QScopedPointer<QtIOCompressor> ioCompressor;

    if (db->compressionAlgo() == Database::CompressionNone) {
        m_device = &hashedStream;
    }
    else {
        ioCompressor.reset(new QtIOCompressor(&hashedStream));
        ioCompressor->setStreamFormat(QtIOCompressor::GzipFormat);
        ioCompressor->open(QIODevice::WriteOnly);
        m_device = ioCompressor.data();
    }

    KeePass2RandomStream randomStream(protectedStreamKey);

    KeePass2XmlWriter xmlWriter;
    xmlWriter.writeDatabase(m_device, db, &randomStream, headerHash);
}
Exemple #26
0
void ConnectionBOSH::onRequestFinished(QNetworkReply *reply)
{
	Q_D(ConnectionBOSH);
	reply->deleteLater();
	Logger::debug() << Q_FUNC_INFO << reply->error() << reply->errorString();
	if (reply->error() != QNetworkReply::NoError) {
		// TODO: Implement
		return;
	}
	bool header = reply->property("header").toBool();
	QByteArray data = reply->readAll();
	Logger::debug() << Q_FUNC_INFO << header << data;
	d->reader.addData(data);
	// Hook for parsers invoked in eventloops, which are run inside parser
	if (d->depth != 0)
		return;
	while (d->reader.readNext() > QXmlStreamReader::Invalid) {
		switch(d->reader.tokenType()) {
		case QXmlStreamReader::StartElement:
			d->depth++;
			if (d->depth > 1) {
				d->streamParser->handleStartElement(d->reader.name(), d->reader.namespaceUri(),
													d->reader.attributes());
			} else {
				Q_ASSERT(d->reader.name() == QLatin1String("body"));
				const QXmlStreamAttributes attributes = d->reader.attributes();
				if (d->streamInitiation) {
					d->streamInitiation = false;
					d->sessionId = attributes.value(QLatin1String("sid")).toString();
					emit connected();
				}
				if (header)
					d->streamParser->handleStartElement(QStringRef(), QStringRef(),
														QXmlStreamAttributes());
			}
			break;
		case QXmlStreamReader::EndElement:
			if (d->depth > 1)
				d->streamParser->handleEndElement(d->reader.name(), d->reader.namespaceUri());
			d->depth--;
			break;
		case QXmlStreamReader::Characters:
			if (d->depth > 1)
				d->streamParser->handleCharacterData(d->reader.text());
			break;
		default:
			break;
		}
	}
	Q_ASSERT(d->depth == 0);
	if (!d->payloads.isEmpty() && reply == d->dataRequest) {
		d->dataRequest = 0;
		writeData(d->payloads.constData(), d->payloads.size());
		d->payloads.clear();
		return;
	} else if (reply == d->dataRequest) {
		d->dataRequest = 0;
	}
	if (reply == d->emptyRequest)
		d->emptyRequest = 0;
	if (d->authorized && !d->emptyRequest) {
		char c;
		writeData(&c, 0);
	}
}
Exemple #27
0
QT_USE_NAMESPACE

int main(int argc, char *argv[])
{
    QCoreApplication coreApplication(argc, argv);
    int argumentCount = QCoreApplication::arguments().size();
    QStringList argumentList = QCoreApplication::arguments();

    QTextStream standardOutput(stdout);

    if (argumentCount == 1) {
        standardOutput << QObject::tr("Usage: %1 <serialportname> [baudrate]").arg(argumentList.first()) << endl;
        return 1;
    }

    QSerialPort serialPort;
    QString serialPortName = argumentList.at(1);
    serialPort.setPortName(serialPortName);

    if (!serialPort.open(QIODevice::WriteOnly)) {
        standardOutput << QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    int serialPortBaudRate = (argumentCount > 2) ? argumentList.at(2).toInt() : QSerialPort::Baud9600;
    if (!serialPort.setBaudRate(serialPortBaudRate)) {
        standardOutput << QObject::tr("Failed to set 9600 baud for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    if (!serialPort.setDataBits(QSerialPort::Data8)) {
        standardOutput << QObject::tr("Failed to set 8 data bits for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    if (!serialPort.setParity(QSerialPort::NoParity)) {
        standardOutput << QObject::tr("Failed to set no parity for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    if (!serialPort.setStopBits(QSerialPort::OneStop)) {
        standardOutput << QObject::tr("Failed to set 1 stop bit for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    if (!serialPort.setFlowControl(QSerialPort::NoFlowControl)) {
        standardOutput << QObject::tr("Failed to set no flow control for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    QFile dataFile;
    if (!dataFile.open(stdin, QIODevice::ReadOnly)) {
        standardOutput << QObject::tr("Failed to open stdin for reading") << endl;
        return 1;
    }

    QByteArray writeData(dataFile.readAll());
    dataFile.close();

    if (writeData.isEmpty()) {
        standardOutput << QObject::tr("Either no data was currently available on the standard input for reading, or an error occurred for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    SerialPortWriter serialPortWriter(&serialPort);
    serialPortWriter.write(writeData);

    return coreApplication.exec();
}
int SecureDescriptorStream::writeData(std::vector<uint8_t> &buf, int buflen) {
  if (static_cast<int>(buf.capacity()) < buflen) {
    return -1;
  }
  return writeData(reinterpret_cast<uint8_t *>(&buf[0]), buflen);
}
Exemple #29
0
// From TMrfTal
void TMrfTal_RBUDP::writeRemoteData(const TMrfData& data) const
{
    write(rb_address::bitcountreg, (mrf::registertype) data.getNumBits());
    writeData(rb_address::inputreg, data);
    setFlag(rb_address::control, rb_value::startinput, true);
}
Exemple #30
0
void E_ink_ESP8266::closeBump(void)
{
  writeComm(0x22);   
  writeData(0x03);
  writeComm(0x20);
}