예제 #1
0
RegisterWidget::RegisterWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RegisterWidget)
{
    ui->setupUi(this);

    this->setWindowTitle("Register QQ");
    //pixmap.load("./images/register.png");
    //ui->PictureLabel->setPixmap(pixmap);
    //ui->PictureLabel->resize(pixmap.size());
    this->move(500,250);

    /*设置密码显示模式*/
    ui->PasswdLineEdit->setEchoMode(QLineEdit::Password);
    ui->CheckPasswdLineEdit->setEchoMode(QLineEdit::Password);

    /*设置TCP连接*/
    M_TcpPort = 6666;
    M_TcpSocket = new QTcpSocket();

    connect(M_TcpSocket, SIGNAL(readyRead()), this, SLOT(ReadMessage()));
    connect(M_TcpSocket, SIGNAL(disconnected()), M_TcpSocket, SLOT(deleteLater()));
   // connect(M_TcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(DisplayError(QAbstractSocket::SocketError)));

}
예제 #2
0
//---メッセージを全て表示
void CrMesManager::ReadMessageAll(int window /*= 0*/)
{
	while(ReadMessage(1,window)){
		Draw();
	}
//	ReadMessage(9999,window);
}
// ---------------------------------------------------------------------------
// CAtSmsStoreReadAll::EventSignal
// other items were commented in a header
// ---------------------------------------------------------------------------
void CAtSmsStoreReadAll::EventSignal(TAtEventSource aEventSource, TInt aStatus)
	{
	LOGTEXT3(_L8("CAtSmsStoreReadAll::EventSignal aStatus=%D iSource=%D"),
			                          aStatus,aEventSource);
	if(aStatus == KErrNone)
		{
		if((aEventSource == EWriteCompletion))
			{
			LOGTEXT(_L8("CAtSmsStoreRead::EventSignal,EWriteCompletion!"));
			return;
			}
		aStatus = iError;
		}		
		
	if(iIndex < iPhoneGlobals.iStoreTotal)
		{
		iCtsyDispatcherCallback.CallbackPhonebookSmsStoreReadAllComp(aStatus,iSmsData,iIndex,ETrue,EFalse);
		iIndex++;
		ReadMessage();
		}
	else 
		{
		//Handle last message 
		Complete();
		iPhoneGlobals.iEventSignalActive = EFalse;
		iCtsyDispatcherCallback.CallbackPhonebookSmsStoreReadAllComp(aStatus,iSmsData,iIndex,EFalse,EFalse);
		}
	}
예제 #4
0
void Client::MainLoop(){
	bool run = true;
	while(msgsRead<msgsMax){

		run = ReadMessage();
		std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
	}
}
예제 #5
0
/**
 * Let's connect up the client and set the connections to the server. We also must keep
 * track of the connect and disconnect--esp (signals and slots).
 * @param username is a QString to the client's username
 * @param parent is just basically a pointer to the parent.
 */
Client::Client(QString username, QObject *parent)
        : QTcpSocket(parent)
        , m_username(username)
        , nextBlockSize(0)
{
        connect(this, SIGNAL(connected()), SLOT(SlotConnected()));
        connect(this, SIGNAL(disconnected()), SLOT(SlotDisconnected()));
        connect(this, SIGNAL(readyRead()), SLOT(ReadMessage()));
        connect(this, SIGNAL(error(QAbstractSocket::SocketError)),
                SLOT (SlotError(QAbstractSocket::SocketError)));
}
예제 #6
0
int CrMesManager::ReadDraw(int line /*= 1*/,int window /*= 0*/,int mode /*= 0*/)
{
	int a;

	for(a = 0;a < line;a ++){
		ReadMessage(1,window,mode);
		Draw();
	}

	return 1;
}
예제 #7
0
파일: object.cpp 프로젝트: vseryakov/lmbox
Variant DynamicObject::m_Message(int numargs, Variant args[])
{
    Variant rc = VARNULL;

    if (!strcmp(args[0], "send")) {
        SendMessage(args[1]);
    } else

    if (!strcmp(args[0], "read")) {
        char *msg = ReadMessage(args[1]);
        if (msg) {
            rc = anytovariant(msg);
            free(msg);
        }
    }
    return rc;
}
예제 #8
0
void ESP8266::update()
{
	currentTimestamp = millis();

	switch (state) {
	case STATE_IDLE:
		ReadMessage();
		break;
	case STATE_joinAP:
	case STATE_createTCP:

		readResponse(serialResponseTimestamp);
		break;
		//case STATE_CONNECTED:
		//	if (requests[0].serverIP != NULL) {
		//		connectToServer();
		//	}
		//	break;
	}
	/*if (connected) {
	ipWatchdog();
	}*/
}
예제 #9
0
cXVDRResponsePacket* cXVDRSession::ReadResult(cRequestPacket* vrp)
{
  if(!SendMessage(vrp))
  {
    SignalConnectionLost();
    return NULL;
  }

  cXVDRResponsePacket *pkt = NULL;

  while((pkt = ReadMessage()))
  {
    /* Discard everything other as response packets until it is received */
    if (pkt->getChannelID() == XVDR_CHANNEL_REQUEST_RESPONSE && pkt->getRequestID() == vrp->getSerial())
    {
      return pkt;
    }
    else
      delete pkt;
  }

  SignalConnectionLost();
  return NULL;
}
예제 #10
0
void* ReadServerResponse(void* msgQueue)
{
    Mesg rcv;
    rcv.mesg_len = 0;

    while(1)
    {     

        fflush(stdout);

        if(ReadMessage((*(int*)msgQueue), &rcv, getpid()) == 0){
            if(rcv.mesg_len == 0) {
                break;
            }
            
            printf("%s", rcv.mesg_data);
        }

    }

    running = 0;

    return 0;
}
예제 #11
0
/*----------------------------------------------------------------------------+
 | Function     : JournalBillcycleEnd
 |
 | Description  : JNL entry point for billcycle end processing
 |
 | Input        : None
 |
 | Output       : None
 |
 | Return       : None
 +----------------------------------------------------------------------------*/
void
JournalBillcycleEnd (void)
{
char            *name = "JournalBillcycleEnd";
JNL_MESSAGE     message;
JNL_CYCLE_DATES jcd;
t_smp_mode      process_mode = SMP_MULTITASK;
t_proc_arr      *process_array;
FILE            *ctrl_fd;
int             n_exec;
int             result;
int             timer_total;
int             timer_item;

   tracef (name, "<<<************* TYPE ONE RUN **************>>>");
   tracef (name, "Initializing billcycle end journal task");

   emit (JNLMOD, JNL_TASK_START, JNL_TYPE_BILLCYCLE_END, JnlTypeDescription (JNL_TYPE_BILLCYCLE_END));

   clear_cycle_run_error();

   if (crt_jnl_refno() == FAILURE)
   {
      return;
   }

   JNL_START_TIMER (g_iJnl_ref_no, JNL_TYPE_BILLCYCLE_END, "TOTAL", timer_total);

   AddTaskToControlLog();

   if (lock_run() == FAILURE) return;

   check_jnl_subcycle_period (JNL_TYPE_BILLCYCLE_END);

   InitialiseJnlCycleDates (&jcd, &g_spJnl_cycle_list->jnl_start_dt, 
                                  &g_spJnl_cycle_list->jnl_end_dt,
                                  &g_spJnl_cycle_list->jnl_subcycle_start_dt,
                                  &g_spJnl_cycle_list->jnl_subcycle_end_dt);

   proc_work_new (JNL_CREATE_WORK_LIST_KEY, JNL_TYPE1_KEY, JnlRefNoToString (g_iJnl_ref_no), JNL_CREATE_WORK_LIST_LLCV);
   CreateJNL_WORK_LIST (g_spDBcustfetch, &jcd, g_iHold_Bills, g_iSuppressNonJournaledBackouts);
   proc_work_end (JNL_CREATE_WORK_LIST_KEY, JNL_TYPE1_KEY, JnlRefNoToString (g_iJnl_ref_no), JNL_CREATE_WORK_LIST_CV,
                 0, NumQueuedInvoices(), 0, 0, JNL_LOG_SUCCESS);

   if (NumQueuedInvoices() != 0)
   {
      if (LoadEmfConfigIds (g_spDBcustfetch) != SUCCESS)
         jnl_post_error (JNLMOD, JNL_ERR_ABORT_RUN, JNL_LOAD_FAIL, "EMF_CONFIGURATION");
   }

   arb_put_state (g_spDBcustfetch, ARB_STATUS_PROC);
 
   if (!(process_array  = InitialiseProcesses (JNL_TYPE_BILLCYCLE_END, &jcd, process_mode,
                                               processes, pipes, pipe_attachments)))
   {
      emit (JNLMOD, JNL_PROCESS_ERROR, "InitialiseProcesses");
      jnl_post_error (JNLMOD, JNL_ERR_ABORT_RUN, JNL_PROCESS_ERROR, "InitialiseProcesses");
   }

   /*----------------------------------------------------------------------------+
    | Fork processes and read control data from pipe
    +----------------------------------------------------------------------------*/
   JNL_START_TIMER (g_iJnl_ref_no, JNL_TYPE_BILLCYCLE_END, "FORKED_STUFF", timer_item);
   n_exec = ExecuteParallelProcesses (process_array, processes, process_mode);
   if (n_exec > 0)
   {
      proc_arr_init_pipes (process_array, proc_by_idx (process_array, PARENT_PROCESS));
 
      ctrl_fd = GetCurrentProcessPipeStream (process_array, JNL_CTRL_PIPE);
 
      while (ReadMessage (ctrl_fd, &message, &result))
      {
         if (ProcessMessage (&message, processes, JNL_TYPE_BILLCYCLE_END, PARENT_PROCESS) != SUCCESS)
         {
            emit (JNLMOD, JNL_PROC_MSG_FAIL, message.type, message.process_id);
            jnl_post_error (JNLMOD, JNL_ERR_ABORT_RUN, JNL_PROC_MSG_FAIL, message.type, message.process_id);
         }
      }
 
      /* Check if ReadMessage failed due to error condition, or just EOF */
      if (result != SUCCESS)
      {
         emit (JNLMOD, JNL_PIPE_RD_FAIL, errno, strerror(errno));
         jnl_post_error (JNLMOD, JNL_ERR_ABORT_RUN, JNL_PIPE_WRT_FAIL, errno, strerror(errno));
      }
 
      /*----------------------------------------------------------------------------+
       | Close pipes related to parent process and wait for all forked process statuses
       | so we can get results (maybe do non-blocking wait in loop above?). If we fail getting
       | the status of a process or a process has failed, abort the run.
       +----------------------------------------------------------------------------*/
      proc_arr_term_pipes (process_array, proc_by_idx (process_array, PARENT_PROCESS));
 
      if (GetForkedProcessExitStatuses (process_array) != SUCCESS)
      {
         emit (JNLMOD, JNL_WAIT_ERROR, g_iJnl_ref_no);
         jnl_post_error (JNLMOD, JNL_ERR_ABORT_RUN, JNL_WAIT_ERROR, g_iJnl_ref_no);
      }

      if (CheckProcessExitStatuses (processes, PARALLEL) != SUCCESS)
      {
         emit (JNLMOD, JNL_PROC_FAILED, g_iJnl_ref_no);
         jnl_post_error (JNLMOD, JNL_ERR_ABORT_RUN, JNL_PROC_FAILED, g_iJnl_ref_no);
      }
   }
   else
   if (n_exec == 0)
   {
      emit (JNLMOD, JNL_NO_PROCESSES, g_iJnl_ref_no);
      jnl_post_error (JNLMOD, JNL_ERR_ABORT_RUN, JNL_NO_PROCESSES, g_iJnl_ref_no);
   }
   else
   {
      emit (JNLMOD, JNL_FORK_FAIL, g_iJnl_ref_no);
      jnl_post_error (JNLMOD, JNL_ERR_ABORT_RUN, JNL_FORK_FAIL, g_iJnl_ref_no);
   }
   JNL_LOG_TIMER (timer_item); /* FORKED_STUFF */

   /*----------------------------------------------------------------------------+
    | If there are any functions that need to be executed in parent process - execute them
    +----------------------------------------------------------------------------*/
   JNL_START_TIMER (g_iJnl_ref_no, JNL_TYPE_BILLCYCLE_END, "SEQUENTIAL_STUFF", timer_item);
   ExecuteSequentialProcesses (processes, JNL_TYPE_BILLCYCLE_END, g_iJnl_ref_no);
   JNL_LOG_TIMER (timer_item);
   if (CheckProcessExitStatuses (processes, SEQUENTIAL) != SUCCESS)
   {
      emit (JNLMOD, JNL_PROC_FAILED, g_iJnl_ref_no);
      jnl_post_error (JNLMOD, JNL_ERR_ABORT_RUN, JNL_PROC_FAILED, g_iJnl_ref_no);
   }

   /*----------------------------------------------------------------------------+
    | Clean the process array and free all the structures 
    +----------------------------------------------------------------------------*/
   ClearUpProcesses (process_array, processes, pipes, pipe_attachments);

   /*----------------------------------------------------------------------------+
    | Commit the journals that were creating during the transaction processing.
    | This involves updating the status of the JNL_RUNS table to SUCCESS and updating
    | the earned-through-dates and journal status of the appropriate BILL_INVOICE records.
    +----------------------------------------------------------------------------*/
   JNL_START_TIMER (g_iJnl_ref_no, JNL_TYPE_BILLCYCLE_END, "COMMIT", timer_item);
   CommitJournalRun();
   JNL_LOG_TIMER (timer_item);

   JNL_LOG_TIMER (timer_total);

   tracef (name, "Completed billcycle end journal task");
   tracef (name, "***********************************************");

   emit (JNLMOD, JNL_TASK_FINISHED, JNL_TYPE_BILLCYCLE_END, JnlTypeDescription (JNL_TYPE_BILLCYCLE_END));

   return;
}
예제 #12
0
// ---------------------------------------------------------------------------
// CAtSmsStoreReadAll::ExecuteCommand
// other items were commented in a header
// ---------------------------------------------------------------------------
void CAtSmsStoreReadAll::ExecuteCommand()
	{
	LOGTEXT(_L8("CAtSmsStoreReadAll::ExecuteCommand callded"));
	ReadMessage();
	}
예제 #13
0
bool module_renderer::ReadAMS(const uint8_t * const lpStream, const uint32_t dwMemLength)
//-----------------------------------------------------------------------
{
    uint8_t pkinf[MAX_SAMPLES];
    AMSFILEHEADER *pfh = (AMSFILEHEADER *)lpStream;
    uint32_t dwMemPos;
    UINT tmp, tmp2;

    if ((!lpStream) || (dwMemLength < 126)) return false;
    if ((pfh->verhi != 0x01) || (strncmp(pfh->szHeader, "Extreme", 7))
     || (!pfh->patterns) || (!pfh->orders) || (!pfh->samples) || (pfh->samples > MAX_SAMPLES)
     || (pfh->patterns > MAX_PATTERNS) || (pfh->orders > MAX_ORDERS))
    {
        return ReadAMS2(lpStream, dwMemLength);
    }
    dwMemPos = sizeof(AMSFILEHEADER) + pfh->extra;
    if (dwMemPos + pfh->samples * sizeof(AMSSAMPLEHEADER) >= dwMemLength) return false;
    m_nType = MOD_TYPE_AMS;
    m_nInstruments = 0;
    m_nChannels = (pfh->chncfg & 0x1F) + 1;
    m_nSamples = pfh->samples;
    for (UINT nSmp=1; nSmp <= m_nSamples; nSmp++, dwMemPos += sizeof(AMSSAMPLEHEADER))
    {
        AMSSAMPLEHEADER *psh = (AMSSAMPLEHEADER *)(lpStream + dwMemPos);
        modsample_t *pSmp = &Samples[nSmp];
        pSmp->length = psh->length;
        pSmp->loop_start = psh->loopstart;
        pSmp->loop_end = psh->loopend;
        pSmp->global_volume = 64;
        pSmp->default_volume = psh->volume << 1;
        pSmp->c5_samplerate = psh->samplerate;
        pSmp->default_pan = (psh->finetune_and_pan & 0xF0);
        if (pSmp->default_pan < 0x80) pSmp->default_pan += 0x10;
        pSmp->nFineTune = MOD2XMFineTune(psh->finetune_and_pan & 0x0F);
        pSmp->flags = (psh->infobyte & 0x80) ? CHN_16BIT : 0;
        if ((pSmp->loop_end <= pSmp->length) && (pSmp->loop_start+4 <= pSmp->loop_end)) pSmp->flags |= CHN_LOOP;
        pkinf[nSmp] = psh->infobyte;
    }

    // Read Song Name
    if (dwMemPos + 1 >= dwMemLength) return true;
    tmp = lpStream[dwMemPos++];
    if (dwMemPos + tmp + 1 >= dwMemLength) return true;
    tmp2 = (tmp < 32) ? tmp : 31;
    if (tmp2) assign_without_padding(this->song_name, reinterpret_cast<const char *>(lpStream + dwMemPos), tmp2);
    this->song_name.erase(tmp2);
    dwMemPos += tmp;

    // Read sample names
    for (UINT sNam=1; sNam<=m_nSamples; sNam++)
    {
        if (dwMemPos + 32 >= dwMemLength) return true;
        tmp = lpStream[dwMemPos++];
        tmp2 = (tmp < 32) ? tmp : 31;
        if (tmp2) memcpy(m_szNames[sNam], lpStream+dwMemPos, tmp2);
        SpaceToNullStringFixed(m_szNames[sNam], tmp2);
        dwMemPos += tmp;
    }

    // Read Channel names
    for (UINT cNam=0; cNam<m_nChannels; cNam++)
    {
        if (dwMemPos + 32 >= dwMemLength) return true;
        uint8_t chnnamlen = lpStream[dwMemPos++];
        if ((chnnamlen) && (chnnamlen < MAX_CHANNELNAME))
        {
            memcpy(ChnSettings[cNam].szName, lpStream + dwMemPos, chnnamlen);
            SpaceToNullStringFixed(ChnSettings[cNam].szName, chnnamlen);
        }
        dwMemPos += chnnamlen;
    }

    // Read Pattern Names
    for (UINT pNam = 0; pNam < pfh->patterns; pNam++)
    {
        if (dwMemPos + 1 >= dwMemLength) return true;
        tmp = lpStream[dwMemPos++];
        tmp2 = bad_min(tmp, MAX_PATTERNNAME - 1);            // not counting null char
        if (dwMemPos + tmp >= dwMemLength) return true;
        Patterns.Insert(pNam, 64);    // Create pattern now, so that the name won't be overwritten later.
        if(tmp2)
        {
            Patterns[pNam].SetName((char *)(lpStream + dwMemPos), tmp2 + 1);
        }
        dwMemPos += tmp;
    }

    // Read Song Comments
    tmp = *((uint16_t *)(lpStream+dwMemPos));
    dwMemPos += 2;
    if (dwMemPos + tmp >= dwMemLength) return true;
    if (tmp)
    {
        ReadMessage(lpStream + dwMemPos, tmp, leCR, &Convert_AMS_Text_Chars);
    }
    dwMemPos += tmp;

    // Read Order List
    Order.resize(pfh->orders, Order.GetInvalidPatIndex());
    for (UINT iOrd=0; iOrd < pfh->orders; iOrd++, dwMemPos += 2)
    {
        Order[iOrd] = (modplug::tracker::patternindex_t)*((uint16_t *)(lpStream + dwMemPos));
    }

    // Read Patterns
    for (UINT iPat=0; iPat<pfh->patterns; iPat++)
    {
        if (dwMemPos + 4 >= dwMemLength) return true;
        UINT len = *((uint32_t *)(lpStream + dwMemPos));
        dwMemPos += 4;
        if ((len >= dwMemLength) || (dwMemPos + len > dwMemLength)) return true;
        // Pattern has been inserted when reading pattern names
        modplug::tracker::modevent_t* m = Patterns[iPat];
        if (!m) return true;
        const uint8_t *p = lpStream + dwMemPos;
        UINT row = 0, i = 0;
        while ((row < Patterns[iPat].GetNumRows()) && (i+2 < len))
        {
            uint8_t b0 = p[i++];
            uint8_t b1 = p[i++];
            uint8_t b2 = 0;
            UINT ch = b0 & 0x3F;
            // Note+Instr
            if (!(b0 & 0x40))
            {
                b2 = p[i++];
                if (ch < m_nChannels)
                {
                    if (b1 & 0x7F) m[ch].note = (b1 & 0x7F) + 25;
                    m[ch].instr = b2;
                }
                if (b1 & 0x80)
                {
                    b0 |= 0x40;
                    b1 = p[i++];
                }
            }
            // Effect
            if (b0 & 0x40)
            {
            anothercommand:
                if (b1 & 0x40)
                {
                    if (ch < m_nChannels)
                    {
                        m[ch].volcmd = VolCmdVol;
                        m[ch].vol = b1 & 0x3F;
                    }
                } else
                {
                    b2 = p[i++];
                    if (ch < m_nChannels)
                    {
                        UINT cmd = b1 & 0x3F;
                        if (cmd == 0x0C)
                        {
                            m[ch].volcmd = VolCmdVol;
                            m[ch].vol = b2 >> 1;
                        } else
                        if (cmd == 0x0E)
                        {
                            if (!m[ch].command)
                            {
                                UINT command = CmdS3mCmdEx;
                                UINT param = b2;
                                switch(param & 0xF0)
                                {
                                case 0x00:    if (param & 0x08) { param &= 0x07; param |= 0x90; } else {command=param=0;} break;
                                case 0x10:    command = CmdPortaUp; param |= 0xF0; break;
                                case 0x20:    command = CmdPortaDown; param |= 0xF0; break;
                                case 0x30:    param = (param & 0x0F) | 0x10; break;
                                case 0x40:    param = (param & 0x0F) | 0x30; break;
                                case 0x50:    param = (param & 0x0F) | 0x20; break;
                                case 0x60:    param = (param & 0x0F) | 0xB0; break;
                                case 0x70:    param = (param & 0x0F) | 0x40; break;
                                case 0x90:    command = CmdRetrig; param &= 0x0F; break;
                                case 0xA0:    if (param & 0x0F) { command = CmdVolSlide; param = (param << 4) | 0x0F; } else command=param=0; break;
                                case 0xB0:    if (param & 0x0F) { command = CmdVolSlide; param |= 0xF0; } else command=param=0; break;
                                }
                                //XXXih: gross
                                m[ch].command = (modplug::tracker::cmd_t) command;
                                m[ch].param = param;
                            }
                        } else
                        {
                            //XXXih: gross
                            m[ch].command = (modplug::tracker::cmd_t) cmd;
                            m[ch].param = b2;
                            ConvertModCommand(&m[ch]);
                        }
                    }
                }
예제 #14
0
//---シーンをさがす
void CrMesManager::SeekScene(int scene,int window /*= 0*/)
{
	ReadMessage(scene,window,1);
}
예제 #15
0
//============================================================================
//		NMessageServer::ServerThread : Server thread.
//----------------------------------------------------------------------------
void NMessageServer::ServerThread(NSocket *theSocket)
{	NNetworkMessage			msgServerInfo, msgConnectRequest, msgConnectResponse;
	NStatus					theErr, acceptErr;
	NMessageHandshake		clientHandshake;
	NString					thePassword;
	NDictionary				serverInfo;
	bool					addClient;
	NEntityID				clientID;



	// Validate our state
	NN_ASSERT(mStatus == kNServerStarted);



	// Do the handshake
	theErr = ReadHandshake(theSocket, clientHandshake);

	if (theErr == kNoErr)
		theErr = WriteHandshake(theSocket, CreateHandshake());

	if (theErr == kNoErr)
		theErr = ValidateHandshake(clientHandshake);

	if (theErr != kNoErr)
		{
		theSocket->Close(theErr);
		return;
		}



	// Send the server info
	mLock.Lock();
	serverInfo    = GetConnectionInfo();
	msgServerInfo = CreateMessage(kNMessageServerInfoMsg, kNEntityEveryone);
	msgServerInfo.SetProperties(serverInfo);
	mLock.Unlock();

	theErr = WriteMessage(theSocket, msgServerInfo);
	if (theErr != kNoErr)
		{
		theSocket->Close(theErr);
		return;
		}



	// Read the connection request
	//
	// If the client does not wish to continue connecting, they will disconnect.
	theErr = ReadMessage(theSocket, msgConnectRequest);
	if (theErr != kNoErr)
		{
		theSocket->Close();
		return;
		}

	NN_ASSERT(msgConnectRequest.GetType()   == kNMessageConnectRequestMsg);
	NN_ASSERT(msgConnectRequest.GetSource() == kNEntityInvalid);



	// Accept the connection
	mLock.Lock();

	clientID  = GetNextClientID();
	acceptErr = AcceptConnection(serverInfo, msgConnectRequest.GetProperties(), clientID);

	msgConnectResponse = CreateMessage(kNMessageConnectResponseMsg, clientID);
	msgConnectResponse.SetValue(kNMessageStatusKey, acceptErr);

	theErr    = WriteMessage(theSocket, msgConnectResponse);
	addClient = (theErr == kNoErr && acceptErr == kNoErr);
	
	if (addClient)
		AddClient(clientID, theSocket);

	mLock.Unlock();

	if (!addClient)
		{
		theSocket->Close(theErr);
		return;
		}



	// Process messages
	ClientConnected(clientID);

	ProcessMessages(theSocket);
}
예제 #16
0
bool module_renderer::ReadITProject(const uint8_t * lpStream, const uint32_t dwMemLength)
//-----------------------------------------------------------------------
{
    UINT i,n,nsmp;
    uint32_t id,len,size;
    uint32_t dwMemPos = 0;
    uint32_t version;

    ASSERT_CAN_READ(12);

    // Check file ID

    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    if(id != ITP_FILE_ID) return false;
    dwMemPos += sizeof(uint32_t);

    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    version = id;
    dwMemPos += sizeof(uint32_t);

    // bad_max supported version
    if(version > ITP_VERSION)
    {
        return false;
    }

    m_nType = MOD_TYPE_IT;

    // Song name

    // name string length
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    len = id;
    dwMemPos += sizeof(uint32_t);

    // name string
    ASSERT_CAN_READ(len);
    if (len <= MAX_SAMPLENAME)
    {
        assign_without_padding(this->song_name, reinterpret_cast<const char *>(lpStream + dwMemPos), len);
        dwMemPos += len;
    }
    else return false;

    // Song comments

    // comment string length
    ASSERT_CAN_READ(4);
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    dwMemPos += sizeof(uint32_t);
    if(id > UINT16_MAX) return false;

    // allocate and copy comment string
    ASSERT_CAN_READ(id);
    if(id > 0)
    {
        ReadMessage(lpStream + dwMemPos, id - 1, leCR);
    }
    dwMemPos += id;

    // Song global config
    ASSERT_CAN_READ(5*4);

    // m_dwSongFlags
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    m_dwSongFlags = (id & SONG_FILE_FLAGS);
    dwMemPos += sizeof(uint32_t);

    if(!(m_dwSongFlags & SONG_ITPROJECT)) return false;

    // m_nDefaultGlobalVolume
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    m_nDefaultGlobalVolume = id;
    dwMemPos += sizeof(uint32_t);

    // m_nSamplePreAmp
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    m_nSamplePreAmp = id;
    dwMemPos += sizeof(uint32_t);

    // m_nDefaultSpeed
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    m_nDefaultSpeed = id;
    dwMemPos += sizeof(uint32_t);

    // m_nDefaultTempo
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    m_nDefaultTempo = id;
    dwMemPos += sizeof(uint32_t);

    // Song channels data
    ASSERT_CAN_READ(2*4);

    // m_nChannels
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    m_nChannels = (modplug::tracker::chnindex_t)id;
    dwMemPos += sizeof(uint32_t);
    if(m_nChannels > 127) return false;

    // channel name string length (=MAX_CHANNELNAME)
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    len = id;
    dwMemPos += sizeof(uint32_t);
    if(len > MAX_CHANNELNAME) return false;

    // Channels' data
    for(i=0; i<m_nChannels; i++){
        ASSERT_CAN_READ(3*4 + len);

        // ChnSettings[i].nPan
        memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
        ChnSettings[i].nPan = id;
        dwMemPos += sizeof(uint32_t);

        // ChnSettings[i].dwFlags
        memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
        ChnSettings[i].dwFlags = id;
        dwMemPos += sizeof(uint32_t);

        // ChnSettings[i].nVolume
        memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
        ChnSettings[i].nVolume = id;
        dwMemPos += sizeof(uint32_t);

        // ChnSettings[i].szName
        memcpy(&ChnSettings[i].szName[0],lpStream+dwMemPos,len);
        SetNullTerminator(ChnSettings[i].szName);
        dwMemPos += len;
    }

    // Song mix plugins
    // size of mix plugins data
    ASSERT_CAN_READ(4);
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    dwMemPos += sizeof(uint32_t);

    // mix plugins
    ASSERT_CAN_READ(id);
    dwMemPos += LoadMixPlugins(lpStream+dwMemPos, id);

    // Song midi config

    // midi cfg data length
    ASSERT_CAN_READ(4);
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    dwMemPos += sizeof(uint32_t);

    // midi cfg
    ASSERT_CAN_READ(id);
    if (id <= sizeof(m_MidiCfg))
    {
        memcpy(&m_MidiCfg, lpStream + dwMemPos, id);
        SanitizeMacros();
        dwMemPos += id;
    }

    // Song Instruments

    // m_nInstruments
    ASSERT_CAN_READ(4);
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    m_nInstruments = (modplug::tracker::instrumentindex_t)id;
    if(m_nInstruments > MAX_INSTRUMENTS) return false;
    dwMemPos += sizeof(uint32_t);

    // path string length (=_MAX_PATH)
    ASSERT_CAN_READ(4);
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    len = id;
    if(len > _MAX_PATH) return false;
    dwMemPos += sizeof(uint32_t);

    // instruments' paths
    for(i=0; i<m_nInstruments; i++){
        ASSERT_CAN_READ(len);
        memcpy(&m_szInstrumentPath[i][0],lpStream+dwMemPos,len);
        SetNullTerminator(m_szInstrumentPath[i]);
        dwMemPos += len;
    }

    // Song Orders

    // size of order array (=MAX_ORDERS)
    ASSERT_CAN_READ(4);
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    size = id;
    if(size > MAX_ORDERS) return false;
    dwMemPos += sizeof(uint32_t);

    // order data
    ASSERT_CAN_READ(size);
    Order.ReadAsByte(lpStream+dwMemPos, size, dwMemLength-dwMemPos);
    dwMemPos += size;



    // Song Patterns

    ASSERT_CAN_READ(3*4);
    // number of patterns (=MAX_PATTERNS)
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    size = id;
    dwMemPos += sizeof(uint32_t);
    if(size > MAX_PATTERNS) return false;

    // m_nPatternNames
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    const modplug::tracker::patternindex_t numNamedPats = id;
    dwMemPos += sizeof(uint32_t);

    // pattern name string length (=MAX_PATTERNNAME)
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    const uint32_t patNameLen = id;
    dwMemPos += sizeof(uint32_t);

    // m_lpszPatternNames
    ASSERT_CAN_READ(numNamedPats * patNameLen);
    char *patNames = (char *)(lpStream + dwMemPos);
    dwMemPos += numNamedPats * patNameLen;

    // modcommand data length
    ASSERT_CAN_READ(4);
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    n = id;
    if(n != 6) return false;
    dwMemPos += sizeof(uint32_t);

    for(modplug::tracker::patternindex_t npat=0; npat<size; npat++)
    {
        // Patterns[npat].GetNumRows()
        ASSERT_CAN_READ(4);
        memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
        if(id > MAX_PATTERN_ROWS) return false;
        const modplug::tracker::rowindex_t nRows = id;
        dwMemPos += sizeof(uint32_t);

        // Try to allocate & read only sized patterns
        if(nRows)
        {

            // Allocate pattern
            if(Patterns.Insert(npat, nRows))
            {
                dwMemPos += m_nChannels * Patterns[npat].GetNumRows() * n;
                continue;
            }
            if(npat < numNamedPats && patNameLen > 0)
            {
                Patterns[npat].SetName(patNames, patNameLen);
                patNames += patNameLen;
            }

            // Pattern data
            long datasize = m_nChannels * Patterns[npat].GetNumRows() * n;
            //if (streamPos+datasize<=dwMemLength) {
            if(Patterns[npat].ReadITPdata(lpStream, dwMemPos, datasize, dwMemLength))
            {
                ErrorBox(IDS_ERR_FILEOPEN, NULL);
                return false;
            }
            //memcpy(Patterns[npat],lpStream+streamPos,datasize);
            //streamPos += datasize;
            //}
        }
    }

    // Load embeded samples

    ITSAMPLESTRUCT pis;

    // Read original number of samples
    ASSERT_CAN_READ(4);
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    if(id > MAX_SAMPLES) return false;
    m_nSamples = (modplug::tracker::sampleindex_t)id;
    dwMemPos += sizeof(uint32_t);

    // Read number of embeded samples
    ASSERT_CAN_READ(4);
    memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
    if(id > MAX_SAMPLES) return false;
    n = id;
    dwMemPos += sizeof(uint32_t);

    // Read samples
    for(i=0; i<n; i++){

        ASSERT_CAN_READ(4 + sizeof(ITSAMPLESTRUCT) + 4);

        // Sample id number
        memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
        nsmp = id;
        dwMemPos += sizeof(uint32_t);

        if(nsmp < 1 || nsmp >= MAX_SAMPLES)
            return false;

        // Sample struct
        memcpy(&pis,lpStream+dwMemPos,sizeof(ITSAMPLESTRUCT));
        dwMemPos += sizeof(ITSAMPLESTRUCT);

        // Sample length
        memcpy(&id,lpStream+dwMemPos,sizeof(uint32_t));
        len = id;
        dwMemPos += sizeof(uint32_t);
        if(dwMemPos >= dwMemLength || len > dwMemLength - dwMemPos) return false;

        // Copy sample struct data (ut-oh... this code looks very familiar!)
        if(pis.id == LittleEndian(IT_IMPS))
        {
            modsample_t *pSmp = &Samples[nsmp];
            memcpy(pSmp->legacy_filename, pis.filename, 12);
            pSmp->flags = 0;
            pSmp->length = 0;
            pSmp->loop_start = pis.loopbegin;
            pSmp->loop_end = pis.loopend;
            pSmp->sustain_start = pis.susloopbegin;
            pSmp->sustain_end = pis.susloopend;
            pSmp->c5_samplerate = pis.C5Speed;
            if(!pSmp->c5_samplerate) pSmp->c5_samplerate = 8363;
            if(pis.C5Speed < 256) pSmp->c5_samplerate = 256;
            pSmp->default_volume = pis.vol << 2;
            if(pSmp->default_volume > 256) pSmp->default_volume = 256;
            pSmp->global_volume = pis.gvl;
            if(pSmp->global_volume > 64) pSmp->global_volume = 64;
            if(pis.flags & 0x10) pSmp->flags |= CHN_LOOP;
            if(pis.flags & 0x20) pSmp->flags |= CHN_SUSTAINLOOP;
            if(pis.flags & 0x40) pSmp->flags |= CHN_PINGPONGLOOP;
            if(pis.flags & 0x80) pSmp->flags |= CHN_PINGPONGSUSTAIN;
            pSmp->default_pan = (pis.dfp & 0x7F) << 2;
            if(pSmp->default_pan > 256) pSmp->default_pan = 256;
            if(pis.dfp & 0x80) pSmp->flags |= CHN_PANNING;
            pSmp->vibrato_type = autovibit2xm[pis.vit & 7];
            pSmp->vibrato_rate = pis.vis;
            pSmp->vibrato_depth = pis.vid & 0x7F;
            pSmp->vibrato_sweep = pis.vir;
            if(pis.length){
                pSmp->length = pis.length;
                if (pSmp->length > MAX_SAMPLE_LENGTH) pSmp->length = MAX_SAMPLE_LENGTH;
                UINT flags = (pis.cvt & 1) ? RS_PCM8S : RS_PCM8U;
                if (pis.flags & 2){
                    flags += 5;
                    if (pis.flags & 4) flags |= RSF_STEREO;
                    pSmp->flags |= CHN_16BIT;
                }
                else{
                    if (pis.flags & 4) flags |= RSF_STEREO;
                }
                // Read sample data
                ReadSample(&Samples[nsmp], flags, (LPSTR)(lpStream+dwMemPos), len);
                dwMemPos += len;
                memcpy(m_szNames[nsmp], pis.name, 26);
            }
        }
    }

    // Load instruments

    CMappedFile f;
    LPBYTE lpFile;

    for(modplug::tracker::instrumentindex_t i = 0; i < m_nInstruments; i++)
    {

        if(m_szInstrumentPath[i][0] == '\0' || !f.Open(m_szInstrumentPath[i])) continue;

        len = f.GetLength();
        lpFile = f.Lock(len);
        if(!lpFile) { f.Close(); continue; }

        ReadInstrumentFromFile(i+1, lpFile, len);
        f.Unlock();
        f.Close();
    }

    // Extra info data

    __int32 fcode = 0;
    const uint8_t * ptr = lpStream + bad_min(dwMemPos, dwMemLength);

    if (dwMemPos <= dwMemLength - 4) {
        fcode = (*((__int32 *)ptr));
    }

    // Embed instruments' header [v1.01]
    if(version >= 0x00000101 && m_dwSongFlags & SONG_ITPEMBEDIH && fcode == 'EBIH')
    {
        // jump embeded instrument header tag
        ptr += sizeof(__int32);

        // set first instrument's header as current
        i = 1;

        // parse file
        while( uintptr_t(ptr - lpStream) <= dwMemLength - 4 && i <= m_nInstruments )
        {

            fcode = (*((__int32 *)ptr));                    // read field code

            switch( fcode )
            {
            case 'MPTS': goto mpts; //:)            // reached end of instrument headers
            case 'SEP@': case 'MPTX':
                ptr += sizeof(__int32);                    // jump code
                i++;                                                    // switch to next instrument
                break;

            default:
                ptr += sizeof(__int32);                    // jump field code
                ReadExtendedInstrumentProperty(Instruments[i], fcode, ptr, lpStream + dwMemLength);
                break;
            }
        }
    }

    //HACK: if we fail on i <= m_nInstruments above, arrive here without having set fcode as appropriate,
    //      hence the code duplication.
    if ( (uintptr_t)(ptr - lpStream) <= dwMemLength - 4 )
    {
        fcode = (*((__int32 *)ptr));
    }

    // Song extensions
mpts:
    if( fcode == 'MPTS' )
        LoadExtendedSongProperties(MOD_TYPE_IT, ptr, lpStream, dwMemLength);

    m_nMaxPeriod = 0xF000;
    m_nMinPeriod = 8;

    if(m_dwLastSavedWithVersion < MAKE_VERSION_NUMERIC(1, 17, 2, 50))
    {
        SetModFlag(MSF_COMPATIBLE_PLAY, false);
        SetModFlag(MSF_MIDICC_BUGEMULATION, true);
        SetModFlag(MSF_OLDVOLSWING, true);
    }

    return true;
}
예제 #17
0
//--------------------------------------------------------------------------------
//  JS NOTE:  Add sound as buffer to audiao manager
//--------------------------------------------------------------------------------
int CVehicleSound::Read (SStream *stream, Tag tag)
{ CAudioManager *snd = globals->snd;
  int rc = TAG_IGNORED;
  SMessage fmsg;
  char fint[64];
  char fext[64];
  switch (tag) {
  case 'cach':
    //---  pre-cache sfx files- ---------------------
    cach = true;;
    return TAG_READ;
    //---  Engine sounds ----------------------------
    //--- Crash sounds ------------------------------
  case 'crsh':
    ReadCrashSounds(stream);
    return TAG_READ;
  //--- Volume for next sound -----------------------
  case 'volu':
    ReadFloat(&volu,stream);
    return TAG_READ;
  //--- Loop back sample for next engine sound  -----
  case 'back':
    ReadInt(&sample,stream);
    return TAG_READ;
  //--- Cranking sound ----------------------------
	case 'crkE':
    // Engine Crank 
		ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetEngineSound('crkE',fext);
	  sample  = 0;
    return TAG_READ;
	//--- Catching sound ----------------------------
  case 'catE':
    // internal engine catching 
		ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
		SetEngineSound('catE',fext);
	  sample  = 0;
    return TAG_READ;
	//--- Running sound -----------------------------
	case 'runE':
    // internal engine runing 
		ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
		SetEngineSound('runE',fext);
	  sample  = 0;
    return TAG_READ;
	//--- short stop sound --------------------------
  case 'hltE':
    // internal engine idle-stop
		ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetEngineSound('hltE',fext);
	  sample  = 0;
    return TAG_READ;
	//--- Failing at start up -----------------------
  case 'falE':
    // internal engine stop 
		ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetEngineSound('falE',fext);
	  sample  = 0;
    return TAG_READ;
  //--- Miss fire sound ---------------------------
	case 'misE':
    // internal engine miss fire
		ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
		SetEngineSound('misE',fext);
	  sample  = 0;
    return TAG_READ;

  case 'prsi':
    // Propeller start->idle
    ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('prsi',fext);
    return TAG_READ;
  case 'pris':
    // Propeller idle->stop
    ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('pris',fext);
    return TAG_READ;

    //--- Wind------------------------------------ 
  case 'wind':
    // internal wind 
    ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('wind',fext);
    return TAG_READ;
    //--- Tires------------------------------------ 
  case 'tire':
    ReadTireSound(stream);
    return TAG_READ;
    //--- Stall horn------------------------------- 
  case 'stal':
    // internal stall horn 
    ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('stal',fext);
    return TAG_READ;
    //--- FLAPS ------------------------------- 
  case 'flap':
    ReadFlapSound(stream);
    return TAG_READ;
  case 'fmsg':
    // flaps message 
    ReadMessage (&fmsg, stream);
    rc = TAG_READ;
    break;
    //--- Ground------------------------------- 
  case 'grnd':
    ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('grnd',fext);
    return TAG_READ;
    //--- Gear UP------------------------------- 
  case 'geru':
    ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('geru',fext);
    return TAG_READ;
  case 'gerd':
    //--- Gear Down --------------------------------- 
    ReadString (fint, sizeof (fint) - 1, stream);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('gerd',fext);
    return TAG_READ;
    //----Outter marker-------------------------------
  case 'outr':
    // outer marker 
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('outr',fext);
    return TAG_READ;
    //----middle marker-------------------------------
  case 'midl':
    // middle marker 
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('midl',fext);
    return TAG_READ;
    //--- Inner marker ------------------------------- 
  case 'innr':
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('innr',fext);
    return TAG_READ;

  case 'gyro':
    //--- gyro sounds ---------------------------------
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('gyrl',fext);
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('gyrs',fext);
    return TAG_READ;
  case 'gmsg':
    //---- gyro message ------------------------------
    ReadMessage (&fmsg, stream);
    return TAG_READ;
  case 'elt_':
    // elt warning sound 
    ReadString (fext, sizeof (fext) - 1, stream);
    SetSound('elts',fext);
    //snd->ReserveSoundBUF('elts',fext,sample); // lc 052310 -
    return TAG_READ;
  case 'bend':
    // 
    ReadFloat (&pMin, stream);
    ReadFloat (&pMax, stream);
    return TAG_READ;
  }

  if (rc != TAG_READ) {
    // Tag was not processed by this object, it is unrecognized
    WARNINGLOG ("CVehicleSound::Read : Unrecognized tag <%s>", TagToString(tag));
  }

  return rc;
}
예제 #18
0
 void MessageHandler::HandleConnected() {
   connect(socket_, SIGNAL(readyRead()), this, SLOT(ReadMessage()));
   SocketConnected(); // Emits this signal
 }
예제 #19
0
//读取串口缓冲区的消息并分析
void Gprs::ReadMsg(QString strRecv)
{	
 	//读取信息内容,并将信息内容写到本地
	if(strRecv.indexOf("+CMGR:",Qt::CaseInsensitive)>=0)
	{
		//readFlag=0;
		QString strNum;
		QString strMsgContent=ProcessMessage(strRecv,strNum);
                
                if(!isRemoteCtl&&!isLocationInfo){
                MessageRecieved *messageRecieved=new MessageRecieved(0,this,strNum,strMsgContent);
                messageRecieved->init();
		}
                isRemoteCtl=false;
                isLocationInfo=false;
                const char *chCmd;		
		QString cmd="AT+CMGD="+msgIndex+"\r\n";
		chCmd=cmd.toLatin1().data();
		int len=strlen(chCmd);
		SerialPort::nwrite(fd, chCmd, len);
	}
        //获取短信中心号码
	if(serverNumFlag)
	{
		int ITmp=strRecv.indexOf("+CSCA:\"+86", Qt::CaseInsensitive);
		if(ITmp>0 )
		{
	    		serverNumFlag=0;
			serverNumber=strRecv.mid(ITmp+sizeof("+CSCA:\"+86")-1,11);
			qDebug()<<("Init success"+serverNumber);
		}
		else{
			QMessageBox::warning(0, tr("Warning:"),
                                  tr("Can't get the server number!"));
                    }
	}
        //收到新消息
	if(strRecv.indexOf("+CMTI",Qt::CaseInsensitive)>=0)
	{
		int index=strRecv.indexOf(",");		
		msgIndex=strRecv.mid(index+2,2);
		//readFlag=1;
		qDebug()<<("New message arrive!");	
		ReadMessage(msgIndex);
	}
        //待发送短信
	if(strRecv.indexOf(">",Qt::CaseInsensitive)>=0)
	{
	        const char *sendata=sendContent.toLatin1().data();
	 	int len=strlen(sendata);
		if(fd>0){
			SerialPort::nwrite(fd,sendata,len);
                }
                qDebug()<<("send success");	
	}
        //获得来电者信息
        if(strRecv.indexOf("+CLIP:",Qt::CaseInsensitive)>=0)
	{
		if(ringFlag==0){
                
                int index1=strRecv.indexOf(" ");
                int index2=strRecv.indexOf(",");
                QString number=strRecv.mid(index1+2,index2-index1-3);
		ringFlag=1;
                
                calledView->setNum(number);
                calledView->setVisible(true);
                // ringFlag = 0;	
	}
}
        //来电结束
        if(strRecv.indexOf("ATH",Qt::CaseInsensitive)>=0||strRecv.indexOf("NO CARRIER",Qt::CaseInsensitive)>=0)
	{
               ringFlag = 0;
               calledView->stopTimer();
               calledView->setVisible(false);	
	}

        //对方挂断
        if(strRecv.indexOf("BUSY",Qt::CaseInsensitive)>=0||strRecv.indexOf("NO CARRIER",Qt::CaseInsensitive)>=0)
	{
               emit hangUp();	
	}
}
예제 #20
0
int main(void) {
	users_t users[MAX_USERS];
	char buf[100];
	int done = 0;

//	BusyWork();

	// set a global pointer for easier function access
	USERS = users;

	// init some vars
	ADMIN_ACCESS = 0;
	CURRENT_USER = -1;
	NUM_USERS = 0;
	zero((char *)USERS, sizeof(users_t)*MAX_USERS);

	while (!done) {
		if (ADMIN_ACCESS) {
			zero(buf, 100);
			PrintAdminMenu();
			if (read_until(buf, '\n', 100) == -1) {
				_terminate(-1);
			}
			if (strlen(buf) > 1) {
				print("[-] Invalid choice\n");
				continue;
			}
			switch (buf[0]) {
				case '1':
					SendBroadcastMessage();
					break;

				case '2':
					ADMIN_ACCESS = 0;
					break;

				case '3':
					print("Exiting...\n");
					done = 1;
					break;

				default:
					continue;
			}
		} else if (CURRENT_USER == -1) {
			zero(buf, 100);
			PrintLoggedOutMenu();
			if (read_until(buf, '\n', 100) == -1) {
				_terminate(-1);
			}
			if (strlen(buf) > 1) {
				print("[-] Invalid choice\n");
				continue;
			}
			switch (buf[0]) {
				case '1':
					CreateUser();
					break;
				case '2':
					Login();
					break;
				case '3':
					print("Exiting...\n");
					_terminate(0);
					break;
				default:
					print("[-] Invalid choice\n");
					continue;
			}
		} else {
			zero(buf, 100);
			PrintNewMessages();
			PrintLoggedInMenu();
			if (read_until(buf, '\n', 100) == -1) {
				_terminate(-1);
			}
			if (strlen(buf) > 1) {
				print("[-] Invalid choice\n");
				continue;
			}
			switch (buf[0]) {
				case '1':
					SendMessage();
					break;
				case '2':
					ReadMessage();
					break;
				case '3':
					ListMessages();
					break;
				case '4':
					DeleteMessage();
					break;
				case '5':
					CURRENT_USER = -1;
					print("Logging out...\n");
					break;
				case '6':
					print("Exiting...\n");
					_terminate(0);
					break;
				case 'a':
					AdminLogin();
					break;
				default:
					print("[-] Invalid choice\n");
					continue;
			}
		}
	}

	return(0);
}
예제 #21
0
// Основная функция
int main() {

  // Создание трех событий
  for (int i = 0; i < 2; i++) {

    // Создаем событие
    hEvents[i] = CreateEvent(NULL, FALSE, FALSE, NULL);

    // Если создание события завершилось ошибкой, сообщаем об этом и выходим из прораммы
    if (hEvents[i] == NULL) {
      printf("Function <CreateEvent> failed! ErrorID : %d.\n", GetLastError());
      getch();
      return 0;
    } // Неудачное создание события

    // Присваиваем собтие структуре OVERLAPPED
    oOverlapped[i].hEvent = hEvents[i];

  } // for

  // Подключаемся к серверу
  printf("Try connect to server...\n");

  if (!ConnectToServer()) {
    CloseHandle(hPipe);
    return 0;
  }

  while(1) {

    // Ждем сигнализации какого-нибудь события
    dwEventIndex = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);

    // Определяем какой по номеру событие сигнализировало
    dwEventIndex -= WAIT_OBJECT_0;

    // Проверяем есть ли у нас такой номер события, если нет, то аварийно закрываемся
    if (dwEventIndex < 0 || dwEventIndex > 1) {
      printf("Index of event out of range.\n");
      CloseHandle(hPipe);
      getch();
      return 0;
    }

    // Какая-то операция еще не завершена
    if (PendingIO) {

      // Получаем статус завершенности операции
      Success = GetOverlappedResult( hPipe, &oOverlapped[dwEventIndex], &dwTransfered, FALSE);

      // В зависимости от статуса сервера выполняем нужное действие
      switch(dwState) {

        // Выполнялась операция чтения
        case READING_STATE:

          // Функция GetOverlappedResult сработала неверно или неверно сработала функция ReadFile (0 байт передано)
          if (!Success || dwTransfered == 0) {
            // Завершаем работу клиента
            //printf("Function <ReadFile> or <GetOverlappedResult> failed! ErrorID : %d", GetLastError());
            printf("\nSystem message : Connection broken, try reconnect to server.\n\n");

            if (!ConnectToServer()) {
              CloseHandle(hPipe);
              return 0;
            }

            continue;
          }

          // Устанавливаем статус клиента к записи
          dwState = WRITING_STATE;
          break;

        // Выполнялась операция записи
        case WRITING_STATE:

          // Функция GetOverlappedResult сработала неверно или неверно сработала функция WriteFile (должно быть передно байт не совпадает с переданными)
          if (!Success || dwTransfered != dwToWrite) {
            // Завершаем работу клиента
            //printf("Function <WriteFile> failed! ErrorID : %d", GetLastError());
            //CloseHandle(hPipe);
            printf("\nSystem message : Connection broken, try reconnect to server.\n\n");

            if (!ConnectToServer()) {
              CloseHandle(hPipe);
              return 0;
            }

            continue;
          }

          // Устанавливаем статус сервера к чтению
          dwState = READING_STATE;
          break;

        // Ошибочный статус клиента, завершаем работу
        default:
          printf("System message : Invalid client state.\n");
          CloseHandle(hPipe);
          getch();
          return 0;

      } // switch(dwState)
    } // if (PendingIO)

    // Определяем операцию
    switch(dwState) {

      // Читаем сообщение от сервера
      case READING_STATE:

        // Читаем сообщение
        Success = ReadFile(hPipe, chBuffer, BUFSIZE * sizeof(TCHAR), &dwTransfered, &oOverlapped[1]);

        // Операция чтения завершилась успешно
        if (Success && dwTransfered != 0) {
          // Выполняющихся операций нет
          PendingIO = FALSE;
          // Устанавливаем статус клиента к записи
          dwState = WRITING_STATE;
          // Переходим на новую итерацию цикла
          continue;
        }

        // Операция чтения все еще выполняется
        if (!Success && (GetLastError() == ERROR_IO_PENDING)) {
          // Есть выполняющиеся операции
          PendingIO = TRUE;
          // Переходим на новую итерацию цикла
          continue;
        }

        // Произошла ошибка, закрываем клиент
        //printf("Function <ReadFile> failed! ErrorID : %d", GetLastError());
        //CloseHandle(hPipe);
        printf("\nSystem message : Connection broken, try reconnect to server.\n\n");

        if (!ConnectToServer()) {
          CloseHandle(hPipe);
          return 0;
        }

        break;

      // Посылаем серверу сообщение
      case WRITING_STATE:

        // Сначала выводим полученное сообщение
        printf("Server : %s\n", chBuffer);

        // Затем считываем пересылаемое сообщение
        printf("Client : ");
        ReadMessage();

        // Завершаем работу сервера, если введена команда выхода "exit"
        if (!stricmp(chBuffer, "exit")) {
          printf("System message : Server closing...\n");
          CloseHandle(hPipe);
          getch();
          return 1;
        }

        // Считаем размер сообщения
        dwToWrite  = (strlen(chBuffer) + 1) * sizeof(TCHAR);

        // Посылаем сообщение
        Success = WriteFile(hPipe, chBuffer, dwToWrite, &dwTransfered, &oOverlapped[0]);

        // Операция записи завершилась удачно
        if (Success && dwTransfered == dwToWrite) {
          // Выполняющихся операций нет
          PendingIO = FALSE;
          // Устанавливаем статус клиента к чтению
          dwState = READING_STATE;
          // Переходим на новую итерацию цикла
          continue;
        }

        // Операция записи еще выполняется
        if (! Success && (GetLastError() == ERROR_IO_PENDING)) {
          // Есть выполняющиеся операции
          PendingIO = TRUE;
          // Переходим на новую итерацию цикла
          continue;
        }

        // Произошла ошибка, закрываем клиент
        //printf("Function <WriteFile> failed! ErrorID : %d", GetLastError());
        //CloseHandle(hPipe);
        printf("\nSystem message : Connection broken, try reconnect to server.\n\n");

        if (!ConnectToServer()) {
          CloseHandle(hPipe);
          return 0;
        }

        break;

      // Ошибочный статус сервера, завершаем работу
      default:
        printf("System message : Invalid client state.\n");
        CloseHandle(hPipe);
        getch();
        return 0;

    } // switch

  } // while (1)

  return 1;
}
예제 #22
0
//----------------------------------------------------------------------
//  read parameters
//----------------------------------------------------------------------
int CNeedle::Read (SStream *stream, Tag tag)
{ int pm;
  double dm;
  char name[128];

  switch (tag) {
    //--- Vertical amplitude-----------
    case 'ampv':
      ReadFloat(&ampv, stream);
      return TAG_READ;
    //--- Horizontal amplitude----------
    case 'amph':
      ReadFloat (&amph, stream);
      return TAG_READ;
    //--- Starting angle --------------
    case 'sang':
      ReadFloat (&sang, stream);
      return TAG_READ;
    //--- ???? -----------------------
    case 'dunt':
      ReadFloat (&dunt, stream);
      return TAG_READ;
    //--- Range ----------------------
    case 'clmp':
      ReadFloat(&gmin, stream);
      ReadFloat(&gmax, stream);
      return TAG_READ;
    //--- Offset ?? ------------------
    case 'noff':
      ReadInt (&pm, stream);
      ReadInt (&pm, stream);
      return TAG_READ;
    //--- Vertical adjustment ---------
    case 'vadj':
      ReadDouble(&dm, stream);
      rotn.SetVADJ(dm);
      return TAG_READ;
    //--- No what ??? ----------------
    case 'noac':
      return TAG_READ;
    //--- needle position in gauge ---
    case 'posn':
      ReadPOSN(stream);
      return TAG_READ;
    //--- needle projector in gauge ---
    case 'proj':
      ReadPROJ(stream);
      return TAG_READ;

    //--- Rotation center ------------
    case 'rotc':
      ReadROTC(stream);
      return TAG_READ;
    //--- Needle center ------------
    case 'nctr':
      ReadNCTR(stream);
      return TAG_READ;
      
    //--- Texture file ---------------
    case 'file':
    case 'bmap':
			rotn.GetTexture(stream);
      return TAG_READ;
    //----Table look up -----------------
    case 'gtbl':
    { CDataSearch map(stream);
      gmap = map.GetTable();
      gmap->IncUse();
      return TAG_READ;
    }
    //---- Message for update -----------
    case 'mesg':
      ReadMessage (&mesg, stream);
      return TAG_READ;
    //--- Cursor -----------------------
    case 'curs':
    case 'crsr':
      cTag = mgg->BindCursor(stream);
      return TAG_READ;
    //--- Help message ---------------
    case 'help':
      ReadString (help, 64, stream);
      return TAG_READ;

  }
  TagToString(name,tag);
  WARNINGLOG("CNeedle: %s Tag ignored",name);
  return TAG_IGNORED;
}
예제 #23
0
DemuxPacket* cXVDRDemux::Read()
{
    if(ConnectionLost())
    {
        SleepMs(100);
        return PVR->AllocateDemuxPacket(0);
    }

    cResponsePacket *resp = ReadMessage();

    if(resp == NULL)
        return PVR->AllocateDemuxPacket(0);

    if (resp->getChannelID() != XVDR_CHANNEL_STREAM)
    {
        delete resp;
        return PVR->AllocateDemuxPacket(0);
    }

    DemuxPacket* pkt = NULL;
    int iStreamId = -1;

    switch (resp->getOpCodeID())
    {
    case XVDR_STREAM_CHANGE:
        StreamChange(resp);
        pkt = PVR->AllocateDemuxPacket(0);
        pkt->iStreamId  = DMX_SPECIALID_STREAMCHANGE;
        delete resp;
        return pkt;

    case XVDR_STREAM_STATUS:
        StreamStatus(resp);
        break;

    case XVDR_STREAM_SIGNALINFO:
        StreamSignalInfo(resp);
        break;

    case XVDR_STREAM_CONTENTINFO:
        // send stream updates only if there are changes
        if(!StreamContentInfo(resp))
            break;

        pkt = PVR->AllocateDemuxPacket(sizeof(PVR_STREAM_PROPERTIES));
        memcpy(pkt->pData, &m_Streams, sizeof(PVR_STREAM_PROPERTIES));
        pkt->iStreamId  = DMX_SPECIALID_STREAMINFO;
        pkt->iSize      = sizeof(PVR_STREAM_PROPERTIES);
        delete resp;
        return pkt;

    case XVDR_STREAM_MUXPKT:
        // figure out the stream id for this packet
        for(unsigned int i = 0; i < m_Streams.iStreamCount; i++)
        {
            if(m_Streams.stream[i].iPhysicalId == (unsigned int)resp->getStreamID())
            {
                iStreamId = i;
                break;
            }
        }

        // stream found ?
        if(iStreamId != -1)
        {
            pkt = (DemuxPacket*)resp->getUserData();

            pkt->iSize     = resp->getUserDataLength();
            pkt->duration  = (double)resp->getDuration() * DVD_TIME_BASE / 1000000;
            pkt->dts       = (double)resp->getDTS() * DVD_TIME_BASE / 1000000;
            pkt->pts       = (double)resp->getPTS() * DVD_TIME_BASE / 1000000;
            pkt->iStreamId = iStreamId;

            delete resp;
            return pkt;
        }
        else
        {
            XBMC->Log(LOG_DEBUG, "stream id %i not found", resp->getStreamID());
        }
        break;
    }

    delete resp;
    return PVR->AllocateDemuxPacket(0);
}
예제 #24
0
 void MessageHandler::SetSocket(QTcpSocket* socket) {
   socket_ = socket;
   connect(socket_, SIGNAL(readyRead()), this, SLOT(ReadMessage()));
 }