Esempio n. 1
0
// Ticktimer Handler Update
// s_nearbyStopsWindow: get current bus stop selection and scrolling offset. Request new data.
// s_busArrivalsWindow: get current bus service selection and scrolling offset. Reqeust new data.
static void tickHandler(struct tm *tickTime, TimeUnits unitsChanged) {
    if (window_stack_get_top_window() == s_nearbyStopsWindow) {
        requestData("location");
    } else if (window_stack_get_top_window() == s_busArrivalsWindow) {
        requestData(lastStopRequest);
    }
}
Esempio n. 2
0
void UniqueIDBDatabase::handleOpenDatabaseOperations()
{
    ASSERT(isMainThread());
    LOG(IndexedDB, "(main) UniqueIDBDatabase::handleOpenDatabaseOperations");

    // If a version change transaction is currently in progress, no new connections can be opened right now.
    // We will try again later.
    if (m_versionChangeDatabaseConnection)
        return;

    auto operation = m_pendingOpenDatabaseOperations.takeFirst();

    // 3.3.1 Opening a database
    // If requested version is undefined, then let requested version be 1 if db was created in the previous step,
    // or the current version of db otherwise.
    uint64_t requestedVersion = operation->requestData().requestedVersion();
    if (!requestedVersion)
        requestedVersion = m_databaseInfo->version() ? m_databaseInfo->version() : 1;

    // 3.3.1 Opening a database
    // If the database version higher than the requested version, abort these steps and return a VersionError.
    if (requestedVersion < m_databaseInfo->version()) {
        auto result = IDBResultData::error(operation->requestData().requestIdentifier(), IDBError(IDBExceptionCode::VersionError));
        operation->connection().didOpenDatabase(result);
        return;
    }

    Ref<UniqueIDBDatabaseConnection> connection = UniqueIDBDatabaseConnection::create(*this, operation->connection());
    UniqueIDBDatabaseConnection* rawConnection = &connection.get();
    m_server.registerDatabaseConnection(*rawConnection);

    if (requestedVersion == m_databaseInfo->version()) {
        addOpenDatabaseConnection(WTF::move(connection));

        auto result = IDBResultData::openDatabaseSuccess(operation->requestData().requestIdentifier(), *rawConnection);
        operation->connection().didOpenDatabase(result);
        return;
    }

    ASSERT(!m_versionChangeOperation);
    ASSERT(!m_versionChangeDatabaseConnection);

    m_versionChangeOperation = adoptRef(operation.leakRef());
    m_versionChangeDatabaseConnection = rawConnection;

    // 3.3.7 "versionchange" transaction steps
    // If there's no other open connections to this database, the version change process can begin immediately.
    if (!hasAnyOpenConnections()) {
        startVersionChangeTransaction();
        return;
    }

    // Otherwise we have to notify all those open connections and wait for them to close.
    notifyConnectionsOfVersionChange();
}
Esempio n. 3
0
char *
MavlinkFTP::Request::dataAsCString()
{
	// guarantee nul termination
	if (header()->size < kMaxDataLength) {
		requestData()[header()->size] = '\0';
	} else {
		requestData()[kMaxDataLength - 1] = '\0';
	}

	// and return data
	return (char *)&(header()->data[0]);
}
Esempio n. 4
0
// Accelerometer Handler Update
// s_nearbyStopsWindow: get current bus stop selection and scrolling offset. Request new data.
// s_busArrivalsWindow: get current bus service selection and scrolling offset. Reqeust new data.
static void accelerometerHandler(AccelAxisType axis, int32_t direction) {
    light_enable_interaction();
    
    time_t now = time(NULL);
    if (difftime(now, lastUpdate) < MINIMUM_UPDATE_SECONDS) {
        return;
    }

    if (window_stack_get_top_window() == s_nearbyStopsWindow) {
        requestData("location");
    } else if (window_stack_get_top_window() == s_busArrivalsWindow) {
        requestData(lastStopRequest);
    } 
}
Esempio n. 5
0
// Menu Item Selection
// Last index item: View more bus stops
// Other items: request data using the stop details which is selected
// Stop description is retrieved to be used for the busArrivalsWindow showing bus services
static void menu_select_callback(MenuLayer *menu_layer, MenuIndex *cell_index, void *data) {
    int index = cell_index->row;
    if (strcmp(busStops[index].stopDescription, "DISPLAY MORE") == 0) {
        requestData("more");
    } else {
        snprintf(lastStopRequest, sizeof(lastStopRequest), "%s", busStops[index].stopDetails);
        snprintf(lastStopDescription, sizeof(lastStopDescription), "%s", busStops[index].stopDescription);
        // APP_LOG(// APP_LOG_LEVEL_DEBUG, "Selected: %s", stopDetails[index]);

        window_stack_push(s_splashWindow, true);
        text_layer_set_text(s_splashText, "Getting estimated bus arrival timings...");

        requestData(lastStopRequest);
    }
}
Esempio n. 6
0
void SerialThrustMasterBase::open() {
    SerialDevice::open();

    struct termios settings;
    if (tcgetattr(handle, &settings) == -1) {
        throw IOException(name + " failed to get termios attributes: " + std::strerror(errno));
    }

    if (cfsetspeed(&settings, B9600) == -1) {
        throw IOException(name + " failed to set baud speed: " + std::strerror(errno));
    }

    // set the terminal to "raw" mode, see TERMIOS(3)
    settings.c_iflag &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF);
    settings.c_oflag &= ~OPOST;
    settings.c_cflag &= ~(CSIZE | PARENB | CSTOPB | HUPCL);
    settings.c_cflag |= CS8 | CLOCAL | CREAD;
    settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHONL | IEXTEN);
    settings.c_cc[VTIME] = 0;
    settings.c_cc[VMIN] = 0;

    if (tcsetattr(handle, TCSANOW, &settings) == -1) {
        throw IOException(name + " failed to set termios attributes: " + std::strerror(errno));
    }

    // start getting data
    requestData();
}
Esempio n. 7
0
void Table::process( const Eref& e, ProcPtr p )
{
	lastTime_ = p->currTime;
	// send out a request for data. This magically comes back in the
	// RecvDataBuf and is handled.
	requestData()->send( e, p->threadIndexInGroup, recvDataBuf()->getFid());
}
Esempio n. 8
0
void PostScene::widgetTouchUp(Widget *_widget){
	if (btnBack == _widget){
		SceneManager::instance()->showScene("listScene");
	}
	else if (btnSubmit == _widget){
		if (isEdit)
			tool->act = "3";
		else
			tool->act = "1";
		tool->userid = SceneManager::instance()->userid;
		tool->customid = customID;
		for (std::map<string, tabCheck::AttType>::iterator it = tool->mapAtt.begin(); it != tool->mapAtt.end(); it++)
		{
			TextField* _txt = static_cast<TextField*>(rootNode->getChildByName(it->first));
			//	if (_txt != NULL&&_txt->getString() != ""){
			if (_txt != NULL){
				if (_txt->getString() == "" || _txt->getString() == "完善此处信息"){
					_txt->setPlaceHolder("完善此处信息");
					_txt->setPlaceHolderColor(Color3B::RED);
					return;
				}
				_txt->setPlaceHolderColor(Color3B::GRAY);
				tool->*(it->second) = _txt->getString();
			}
		}
		requestData(tool);
	}
}
Esempio n. 9
0
    void frameDraw( const eq::uint128_t& )
    {
        applyCamera();
        initializeLivreFrustum();
        requestData();

        const eq::fabric::Viewport& vp = _channel->getViewport( );
        const Viewport viewport( vp.x, vp.y, vp.w, vp.h );
        _renderViewPtr->setViewport( viewport );

        livre::Node* node = static_cast< livre::Node* >( _channel->getNode( ));
        livre::Window* window = static_cast< livre::Window* >( _channel->getWindow( ));
        AvailableSetGenerator generateSet( node->getDashTree( ),
                                           window->getTextureCache( ));

        _frameInfo.clear();
        generateSet.generateRenderingSet( _currentFrustum, _frameInfo );

        EqRenderViewPtr renderViewPtr =
                boost::static_pointer_cast< EqRenderView >( _renderViewPtr );
        RayCastRendererPtr renderer =
                boost::static_pointer_cast< RayCastRenderer >(
                    renderViewPtr->getRenderer( ));

        const livre::Pipe* pipe = static_cast< const livre::Pipe* >( _channel->getPipe( ));
        renderer->initTransferFunction(
            pipe->getFrameData()->getRenderSettings()->getTransferFunction( ));

        RenderBricks renderBricks;
        generateRenderBricks( _frameInfo.renderNodes, renderBricks );
        renderViewPtr->render( _frameInfo, renderBricks, *_glWidgetPtr );
    }
Esempio n. 10
0
void Table::reinit( const Eref& e, ProcPtr p )
{
	input_ = 0.0;
	vec().resize( 0 );
	lastTime_ = 0;
	// cout << "tabReinit on :" << p->groupId << ":" << p->threadIndexInGroup << endl << flush;
	requestData()->send( e, p->threadIndexInGroup, recvDataBuf()->getFid());
}
float testTemperatureGetDataHandler() {
  byte cmd_buffer[8] = { 0xFF, 0x00, 0xFC, 0x01, 0x00, 0x00, 0x00, 0x00};
  const byte write_pipe[] = { "2Node" };
  float value = requestData(cmd_buffer, write_pipe);
  debugPrint("FLOAT VALUE: ", value);
  
  return value;
}
float testPresenceGetDataHandler() {
  byte cmd_buffer[8] = { 0xFF, 0x00, 0xFC, 0x03, 0x00, 0x00, 0x00, 0x00};
  
  const byte write_pipe[] = { "3Node" };
  float value = requestData(cmd_buffer, write_pipe);
  debugPrint("PRESENCE VALUE: ", value);  
  
  return value;
}
Esempio n. 13
0
    void frameDraw( const eq::uint128_t& )
    {
        livre::Node* node = static_cast< livre::Node* >( _channel->getNode( ));
        const DashRenderStatus& renderStatus = node->getDashTree()->getRenderStatus();
        const uint32_t frame = renderStatus.getFrameID();
        if( frame >= INVALID_FRAME )
            return;

        applyCamera();
        initializeLivreFrustum();
        const DashRenderNodes& visibles = requestData();

        const eq::fabric::Viewport& vp = _channel->getViewport( );
        const Viewport viewport( vp.x, vp.y, vp.w, vp.h );
        _renderViewPtr->setViewport( viewport );

        livre::Window* window = static_cast< livre::Window* >( _channel->getWindow( ));
        const livre::Pipe* pipe = static_cast< const livre::Pipe* >( _channel->getPipe( ));

        const bool isSynchronous = pipe->getFrameData()->getVRParameters()->getSynchronousMode();

        // #75: only wait for data in synchronous mode
        const bool dashTreeUpdated = window->apply( isSynchronous );

        if( dashTreeUpdated )
        {
            const Frustum& receivedFrustum = renderStatus.getFrustum();

            // If there are multiple channels, this may cause the ping-pong
            // because every channel will try to update the same DashTree in
            // node with their own frustum.
            if( !isSynchronous && receivedFrustum != _currentFrustum )
                _channel->getConfig()->sendEvent( REDRAW );
        }

        const AvailableSetGenerator generateSet( node->getDashTree(),
                                                 window->getTextureCache( ));

        _frameInfo.clear();
        for( const auto& visible : visibles )
            _frameInfo.allNodes.push_back(visible.getLODNode().getNodeId());
        generateSet.generateRenderingSet( _frameInfo );

        EqRenderViewPtr renderViewPtr =
                boost::static_pointer_cast< EqRenderView >( _renderViewPtr );
        RayCastRendererPtr renderer =
                boost::static_pointer_cast< RayCastRenderer >(
                    renderViewPtr->getRenderer( ));

        renderer->update( *pipe->getFrameData( ));

        RenderBricks renderBricks;
        generateRenderBricks( _frameInfo.renderNodes, renderBricks );
        renderViewPtr->render( _frameInfo, renderBricks, *_glWidgetPtr );
        updateRegions( renderBricks );
    }
Esempio n. 14
0
byte PulsePlug::getReg (byte reg) {
    // get a register
    beginTransmission();
    Wire.write(reg);
    endTransmission();
    requestData(1);
    byte result = Wire.read();
    delay(10); // XXX Nothing in datasheet indicates this is required; was in original code.
    return result;
}
void IDBConnectionToServer::openDatabase(IDBOpenDBRequest& request)
{
    LOG(IndexedDB, "IDBConnectionToServer::openDatabase - %s", request.databaseIdentifier().debugString().utf8().data());

    ASSERT(!m_openDBRequestMap.contains(request.requestIdentifier()));
    m_openDBRequestMap.set(request.requestIdentifier(), &request);
    
    IDBRequestData requestData(*this, request);
    m_delegate->openDatabase(requestData);
}
void LLGroupMoneyTabEventHandler::onClickLater()
{
	if ( mImplementationp->mTextEditorp )
	{
		mImplementationp->mTextEditorp->setText(mImplementationp->mLoadingText);
	}
	mImplementationp->mCurrentInterval--;

	mImplementationp->updateButtons();

	requestData(gMessageSystem);
}
/******************************************************
 * 
 *  Main; the master of functions, the definer of variables.
 * 
 * ***************************************************/
int main( int argc, char **argv )
{
	
	int i, j;

	ros::init(argc, argv, "sonar");
	
	ros::NodeHandle n;
	
	//ros::Publisher nodenameVariablenameMsg = handle.outsidness<libraryname::type>("nodenameVariablename", bufflen?);					
	ros::Publisher sonarBearingMsg = n.advertise<std_msgs::Float32>("sonarBearing", 100);
	ros::Publisher sonarBinsMsg = n.advertise<std_msgs::Float32>("sonarBins", 100);
	
	std_msgs::Float32 sonarBearing;
	std_msgs::Float32 sonarBins;
	
	/* Open and Configure the Serial Port. */
	open_port();	
	config_port();
	
	//printf("dihqwdi %d\n", getU16(0x0A, 0x80));
	
	/* Initilise the sonar */
	initSonar();
	
	/* optional, sendBBUser command, doesnt work :/ */
	//sendBB();
	
	/* Make and send the head parameters, currently defined at the top of this file */
	headSetup();

	/* ask for some data, will get datas */
	for( i = 0; i < 200; i ++)
	{
		requestData();


		//pass datas	
		sonarBearing.data = (float) bearing;
		sonarBins.data = (float) bins;
		
		//publish
		sonarBearingMsg.publish(sonarBearing);
		sonarBinsMsg.publish(sonarBins);
		
		ros::spinOnce();
	}
				
	/* close file and exit program */			
	close(fd);
	return 0;
}
Esempio n. 18
0
void UniqueIDBDatabase::startVersionChangeTransaction()
{
    LOG(IndexedDB, "(main) UniqueIDBDatabase::startVersionChangeTransaction");

    ASSERT(!m_versionChangeTransaction);
    ASSERT(m_versionChangeOperation);
    ASSERT(m_versionChangeDatabaseConnection);

    auto operation = m_versionChangeOperation;
    m_versionChangeOperation = nullptr;

    uint64_t requestedVersion = operation->requestData().requestedVersion();
    if (!requestedVersion)
        requestedVersion = m_databaseInfo->version() ? m_databaseInfo->version() : 1;

    addOpenDatabaseConnection(*m_versionChangeDatabaseConnection);

    m_versionChangeTransaction = &m_versionChangeDatabaseConnection->createVersionChangeTransaction(requestedVersion);

    auto result = IDBResultData::openDatabaseUpgradeNeeded(operation->requestData().requestIdentifier(), *m_versionChangeTransaction);
    operation->connection().didOpenDatabase(result);
}
Esempio n. 19
0
void UniqueIDBDatabase::startVersionChangeTransaction()
{
    LOG(IndexedDB, "(main) UniqueIDBDatabase::startVersionChangeTransaction");

    ASSERT(!m_versionChangeTransaction);
    ASSERT(m_versionChangeOperation);
    ASSERT(m_versionChangeDatabaseConnection);

    auto operation = m_versionChangeOperation;
    m_versionChangeOperation = nullptr;

    uint64_t requestedVersion = operation->requestData().requestedVersion();
    if (!requestedVersion)
        requestedVersion = m_databaseInfo->version() ? m_databaseInfo->version() : 1;

    addOpenDatabaseConnection(*m_versionChangeDatabaseConnection);

    m_versionChangeTransaction = &m_versionChangeDatabaseConnection->createVersionChangeTransaction(requestedVersion);
    m_inProgressTransactions.set(m_versionChangeTransaction->info().identifier(), m_versionChangeTransaction);
    m_server.postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::beginTransactionInBackingStore, m_versionChangeTransaction->info()));

    auto result = IDBResultData::openDatabaseUpgradeNeeded(operation->requestData().requestIdentifier(), *m_versionChangeTransaction);
    operation->connection().didOpenDatabase(result);
}
Esempio n. 20
0
void TimeExchangeView::onEnterFrame(float dt)
{
    if (!m_st) {
        return;
    }
    
    int tmpMaxRwdLv = PortActController::getInstance()->getMaxRwdLv();
    if (tmpMaxRwdLv != m_maxRwdLv) {
        m_maxRwdLv = tmpMaxRwdLv;
        generateData(NULL);
    }
    
    if (PortActController::getInstance()->isNewDay()) {
        requestData(NULL);
    }
}
Esempio n. 21
0
void VLongPollClient::onServerDataReceived()
{
	QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
	QByteArray rawData = reply->readAll();
	debug() << Q_FUNC_INFO << rawData;
	QVariantMap data = Json::parse(rawData).toMap().value("response").toMap();
	if (data.isEmpty() || reply->error() != QNetworkReply::NoError) {
		if (m_connection->connectionState() == Connected)
			QTimer::singleShot(1000, this, SLOT(requestServer()));
		return;
	}
	QString url("http://%1?act=a_check&key=%2&wait=25");
	m_url = url.arg(data.value("server").toString(), data.value("key").toString());
	
	if (m_connection->connectionState() == Connected)
		requestData(data.value("ts").toString());
}
Esempio n. 22
0
void KAudioPlayStream::fillData( Arts::DataPacket<Arts::mcopbyte> *packet )
{
	//kdDebug( 400 ) << k_funcinfo << "packet->size=" << packet->size << endl;
	if ( d->_polling )
	{
		QByteArray bytearray( packet->size );
		bytearray.setRawData( ( char* )packet->contents, packet->size );
		bytearray.fill( 0 );
		emit requestData( bytearray );
		bytearray.resetRawData( ( char* )packet->contents, packet->size );

		//for ( int i=0; i<10; i++ )
		//	kdDebug() << packet->contents[ i ] << " : " << bytearray.data()[ i ] << endl;
	} else {
		/// TODO: Implement a queue and fetching from it...
	}
}
Esempio n. 23
0
// Fetch data from the PS1, PS2 and PS3 registers.
// They are stored as LSB-MSB pairs of bytes there; convert them to 16bit ints here.
uint16_t* PulsePlug::fetchLedData() {
    static uint16_t ps[3];
    static uint16_t tmp;

    beginTransmission();
    Wire.write(PulsePlug::PS1_DATA0);
    endTransmission();
    requestData(6);

    for (int i=0; i<=2; i++) {
        ps[i] = Wire.read();

        tmp = Wire.read();
        ps[i] += (tmp << 8);
    }

    return ps;
}
Esempio n. 24
0
// Returns ambient light values as an array
// First item is visual light, second is IR light.
uint16_t* PulsePlug::fetchALSData () {
    static uint16_t als_data[2];
    static uint16_t tmp;
    // read out all result registers as lsb-msb pairs of bytes
    beginTransmission();
    Wire.write(ALS_VIS_DATA0);
    endTransmission();
    requestData(4);

    for (int i=0; i<=1; i++) {
        als_data[i] = Wire.read();

        tmp = Wire.read();
        als_data[i] += (tmp << 8);
    }

    return als_data;
}
Esempio n. 25
0
    void frameDraw( const eq::uint128_t& )
    {
        applyCamera();
        initializeLivreFrustum();
        requestData();

        const eq::fabric::Viewport& vp = _channel->getViewport( );
        const Viewportf viewport( Vector2f( vp.x, vp.y ),
                                  Vector2f( vp.w, vp.h ));
        _renderViewPtr->setViewport( viewport );

        Viewporti pixelViewport;
        _glWidgetPtr->setViewport( _renderViewPtr.get( ), pixelViewport );

        livre::Node* node = static_cast< livre::Node* >( _channel->getNode( ));
        AvailableSetGenerator generateSet( node->getDashTree( ));

        FrameInfo frameInfo( _currentFrustum );
        generateSet.generateRenderingSet( _currentFrustum,
                                          frameInfo);

        EqRenderViewPtr renderViewPtr =
                boost::static_pointer_cast< EqRenderView >( _renderViewPtr );

        renderViewPtr->setParameters( getFrameData()->getVRParameters( ));

        RayCastRendererPtr renderer =
                boost::static_pointer_cast< RayCastRenderer >(
                    renderViewPtr->getRenderer( ));

        const livre::Pipe* pipe = static_cast< const livre::Pipe* >( _channel->getPipe());
        renderer->initTransferFunction(
                    pipe->getFrameData()->getRenderSettings()->getTransferFunction( ));

        RenderBricks renderBricks;
        generateRenderBricks( frameInfo.renderNodeList,
                              renderBricks );

        renderViewPtr->render( frameInfo,
                               renderBricks,
                               *_glWidgetPtr );
    }
Esempio n. 26
0
std::vector<std::vector<unsigned char> > SerialThrustMasterBase::read() {
    std::vector<std::vector<unsigned char> > results;

    int availableBytes;
    if (ioctl(handle, FIONREAD, &availableBytes) == -1) {
        throw IOException("Failed to get number of bytes available for " + name + ": " + std::strerror(errno));
    }

    // If a full packet is available or a timeout has occurred, process all available data.
    if (availableBytes >= 9 || getTime() > timeout) {
        int remainingBytes = availableBytes;
        std::vector<unsigned char> buffer(remainingBytes);

        /**
         * While we know how many bytes are avialable, read can still be interrupted by signals,
         * so call it in a loop.
         */
        while (remainingBytes) {
            remainingBytes -= SerialDevice::read(&buffer[0] + (availableBytes - remainingBytes), remainingBytes);
        }

        /**
         * Only return the data to the caller if exactly one full packet arrived. If a timeout
         * occurred or extra bytes arrived, discard all of the data.
         */
        if (availableBytes == 9) {
            results.push_back(buffer);
        }

        /**
         * Request the next state update from the device. Sending requests too quickly can corrupt
         * the device's output, so we only send a new request when at least a full packet has
         * arrived or a timeout occured.
         */
        requestData();
    }

    return results;
}
void LLGroupMoneyTabEventHandler::onClickTab()
{
	requestData(gMessageSystem);
}
Esempio n. 28
0
void PostScene::getTickData(){
	tabCheck* _tabTick = new tabCheck();
	_tabTick->act = "4";
	_tabTick->customid = customID;
	requestData(_tabTick);
}
Esempio n. 29
0
void WebPage::receivedApplicationSchemeRequest(const QNetworkRequest& request, QtNetworkReply* reply)
{
    QtNetworkRequestData requestData(request, reply);
    m_applicationSchemeReplies.add(requestData.m_replyUuid, reply);
    send(Messages::WebPageProxy::ResolveApplicationSchemeRequest(requestData));
}
Esempio n. 30
0
/******************************************************
 * 
 *  Main; the master of functions, the definer of variables.
 * 
 * ***************************************************/
int main( int argc, char **argv )
{

	int i, j;

	ros::init(argc, argv, "sonar");

	ros::NodeHandle n;

	//ros::Publisher nodenameVariablenameMsg = handle.outsidness<libraryname::type>("nodenameVariablename", bufflen?);					
	ros::Publisher sonarBearingMsg = n.advertise<std_msgs::Float32>("sonarBearing", 100);
	ros::Publisher sonarBinsMsg = n.advertise<std_msgs::Float32>("sonarBins", 100);
	ros::Publisher sonarBinsArrMsg = n.advertise<std_msgs::Int32MultiArray>("sonarBinsArr", 100);
	ros::Publisher sonarScanMsg = n.advertise<sensor_msgs::LaserScan>("sonarScan", 100);

	
	ros::Subscriber sub1 = n.subscribe("sonarCmd", 100, cmdCallback);
	ros::Subscriber sub2 = n.subscribe("sonarRange", 100, rangeCallback);
	ros::Subscriber sub3 = n.subscribe("sonarLeft", 100, leftCallback);

	std_msgs::Float32 sonarBearing;
	std_msgs::Float32 sonarBins;
	std_msgs::Int32MultiArray sonarBinsArr;
	sensor_msgs::LaserScan sonarScan;
	
	//ros::Time scan_time = ros::Time::now();

	//Set up a LaserScan message:
	initLaserData(sonarScan);


	/* Open and Configure the Serial Port. */
	open_port();	

	if( tcgetattr(fd, &orig_terimos) < 0)
	{
		ROS_ERROR("Probably didn't get the serial port (is it connected?).\n");
		return 0;
	}

	config_port();

	//makePacket(mtReBoot);

	//printf("dihqwdi %d\n", getU16(0x0A, 0x80));

	/* Initilise the sonar */
	initSonar();

	/* optional, sendBBUser command, doesnt work :/ */
	//sendBB();


	while(ros::ok())
	{
		ros::Time scan_time = ros::Time::now();

		switchCmd = 1;
		//Stare LL
		if(switchCmd == 0)
		{

			/* Make and send the head parameters, currently defined at the top of this file */
			if(switchFlag == 0)
			{
				//SCANSTARE = 0x2B;
				//RANGE = 5;
				LEFTANGLE = 3300;
				RIGHTANGLE = 3600;
				
				headSetup();
				switchFlag = 1;
				
				ROS_INFO("Stare Initilized");
			}

//			i = 0;

			//makePacket(mtStopAlive);	
			/* ask for some data, will get datas */
//			while(i < 30)
//			{

				requestData();
				//
				//tcflush(fd, TCIFLUSH);//remove
				//pass datas	
				sonarBearing.data = (float) bearing;
				
				//printf("%d", bearing);
				
				sonarBins.data = (float) bins;
				
				sonarBinsArr.data.clear();
				for (int k = 0; k < 90; k++)
				{
					sonarBinsArr.data.push_back(tempBinArray[k]);
				}

				//publish
				sonarBearingMsg.publish(sonarBearing);
				sonarBinsMsg.publish(sonarBins);
				sonarBinsArrMsg.publish(sonarBinsArr);


				//ROS_INFO("Bearing: %f, Bins: %f", bearing, bins);
				//printf("%d - %d\n", bearing, bins);
				//ros::spinOnce();
				i++;

//			}
		}
		//scanner
		else
		{
			
			/* Make and send the head parameters, currently defined at the top of this file */
			if(switchFlag == 0)
			{
				
				SCANSTARE = 0xC0;
				RANGE = 45;
				LEFTANGLE = 0;
				RIGHTANGLE = 6399;
				
				headSetup();
				switchFlag = 1;
				
				ROS_INFO("Scanner Activated");
			}

			i = 0;

			//makePacket(mtStopAlive);	
			/* ask for some data, will get datas */
//			while(i < 30)
//			{

				requestData();
				//
				//tcflush(fd, TCIFLUSH);//remove
				//pass datas	
				
/*	Hack to fix the bearing mess up between ~3327-3599, dafuq. */

				//printf("%d - ", bearing);

				if(sonarDirection == UP)
				{

					if( bearingOld != bearing - (STEPANGLE * 2) && bearingOld != 0)
					{
						if((bearing >= 0 && bearing <= 100) && (bearingOld <= 6399 && bearingOld >= 6300))  
							bearingFail = 0;
						else
							bearingFail = 1;
					}
					if( (bearing > bearingOld + 700)  && bearingFail == 1)
						bearingFail = 0;
	
				}
				else
				{

					if( bearingOld != bearing + (STEPANGLE * 2) && bearingOld != 0)
					{
						if((bearingOld >= 0 && bearingOld <= 100) && (bearing <= 6399 && bearing >= 6300))  
							bearingFail = 0;
						else
							bearingFail = 1;
					}
					if( (bearing > bearingOld + 700)  && bearingFail == 1)
						bearingFail = 0;
	
				}				
				if(bearingFail == 1)
				{
					//bearing = bearing + 768;
					sonarBearing.data = (float) bearing + 768;
				}
				else
				{
				 	sonarBearing.data = (float) bearing;
				}
				//printf("%d -- %d\n", bearing, bearingFail);

/* end fix */				

				//sonarBearing.data = (float) bearing;
				sonarBins.data = (float) bins;
				
				sonarBinsArr.data.clear();
				for (int k = 0; k < 90; k++)
				{
					sonarBinsArr.data.push_back(tempBinArray[k]);
				}

				// Create laser scan data from the sonar bins array.
				createLaserData(sonarScan, tempBinArray, scan_time);

				//publish
				sonarBearingMsg.publish(sonarBearing);
				sonarBinsMsg.publish(sonarBins);
				sonarBinsArrMsg.publish(sonarBinsArr);
			
				sonarScanMsg.publish(sonarScan);

				//ROS_INFO("Bearing: %f, Bins: %f", bearing, bins);
				//printf("%d - %d\n", bearing, bins);
				//ros::spinOnce();
				i++;	
				bearingOld = bearing;


					
				
				

//			}			
			
		}
		
		ros::spinOnce();
		//sleep(1);
		
	}

	/* close file and exit program */	

	tcflush(fd, TCIFLUSH);

	tcsetattr(fd, TCSANOW, &(orig_terimos));

	close(fd);
	return 0;
}