Exemple #1
0
static uint16_t wbsio_get_spibase(uint16_t port)
{
	uint8_t id;
	uint16_t flashport = 0;

	w836xx_ext_enter(port);
	id = sio_read(port, 0x20);
	if (id != 0xa0) {
		msg_perr("\nW83627 not found at 0x%x, id=0x%02x want=0xa0.\n", port, id);
		goto done;
	}

	if (0 == (sio_read(port, 0x24) & 2)) {
		msg_perr("\nW83627 found at 0x%x, but SPI pins are not enabled. (CR[0x24] bit 1=0)\n", port);
		goto done;
	}

	sio_write(port, 0x07, 0x06);
	if (0 == (sio_read(port, 0x30) & 1)) {
		msg_perr("\nW83627 found at 0x%x, but SPI is not enabled. (LDN6[0x30] bit 0=0)\n", port);
		goto done;
	}

	flashport = (sio_read(port, 0x62) << 8) | sio_read(port, 0x63);

done:
	w836xx_ext_leave(port);
	return flashport;
}
Exemple #2
0
uint16_t probe_id_ite(uint16_t port)
{
	uint16_t id;

	enter_conf_mode_ite(port);
	id = sio_read(port, CHIP_ID_BYTE1_REG) << 8;
	id |= sio_read(port, CHIP_ID_BYTE2_REG);
	exit_conf_mode_ite(port);

	return id;
}
Exemple #3
0
// MT safe
int sio_readexpect(std::string &msg, const char * prefix, int * preflen, int timeout) {

  std::deque<std::string> rejected;

  // true timeout
  int64 stoptime = time64() + timeout*1000;

  int rv;
  while (stoptime > time64()) {
	int delta = (int)( (stoptime - time64()) / 1000 );
	rv=sio_read(msg, (delta>0)?delta:0);
	if (rv <= 0) break; //  error or timeout
	rv = sio_matchpref(msg.c_str(), prefix, preflen);
	if (rv > 0) break; // found it
	rejected.push_back(msg); 
	//printf("rejected: [%s] (%d)\n", msg.c_str(), rejected.size());
  };

  // push back the unanswered messages...
  std::string tmp;
  while (!rejected.empty()) {
	tmp = rejected.back();
	rejected.pop_back();
	postponed.push_front(tmp);
	//printf("postponed: [%s] (%d)\n", tmp.c_str(), postponed.size());
  };

  //printf("MESSAGE [%s] is number %d in list of\n%s\n", msg.c_str(), rv, prefix);
  return rv;
};
Exemple #4
0
/* Retrieves the just recorded buffer, if there is one. */
static int
sndio_rec_read(void *buf)
{
	struct pollfd pfd;
	nfds_t nfds;
	int ret, nbytes, offset = 0;

	/* make sure counters have been updated */
	nfds = sio_pollfd(hdl, &pfd, POLLIN);
	poll(&pfd, nfds, 0);
	sio_revents(hdl, &pfd);
	if (!(sio_revents(hdl, &pfd) & POLLIN))
		return 0;

	nbytes = sndio_rec_bufsize;
	while (nbytes) {
		ret = sio_read(hdl, buf + offset, nbytes);
		if (sio_eof(hdl))
			return 0;
		offset += ret;
		nbytes -= ret;
	}

	return 1;
}
Exemple #5
0
/**
 * Dedicated thread to read data from the serial port.
 */
static void gprs_thread(void *arg)
{
    gprs_t * gprs = (gprs_t *)arg;


    LWIP_DEBUGF(GPRS_DEBUG,("gprs: Thread: Started on device %d size %u\n",gprs->device,GPRS_MODEM_BUFFER_SIZE));


    for (;;)
    {
        gprs->recvLen  = sio_read(gprs->fd,(u8_t *)gprs->recvBuffer,GPRS_MODEM_BUFFER_SIZE);

        if (gprs->recvLen > 0)
        {
#if GPRS_SERIAL_STAT
        	gprs->rcvdBtes += gprs->recvLen;
#endif

            if (tcpip_callback(gprs_input_callback,(void *)gprs) != ERR_OK)
            {
                LWIP_DEBUGF(GPRS_DEBUG,("gprs: Thread tcpip_callback() failed\n"));
            }
            else
            {
                sys_sem_wait(&gprs->recvSem);
            }

        }

    }
}
Exemple #6
0
static PaError
BlockingReadStream(PaStream *stream, void *data, unsigned long numFrames)
{
	PaSndioStream *s = (PaSndioStream *)stream;
	unsigned n, res, todo;
	void *buf;
	
	while (numFrames > 0) {
		n = s->par.round;
		if (n > numFrames)
			n = numFrames;
		buf = s->rbuf;
		todo = n * s->par.rchan * s->par.bps;
		while (todo > 0) {
			res = sio_read(s->hdl, buf, todo);
			if (res == 0)
				return paUnanticipatedHostError;
			buf = (char *)buf + res;
			todo -= res;
		}
		s->rpos += n;
		PaUtil_SetInputFrameCount(&s->bufproc, n);
		PaUtil_SetInterleavedInputChannels(&s->bufproc, 0, s->rbuf, s->par.rchan);
		res = PaUtil_CopyInput(&s->bufproc, &data, n);
		if (res != n) {
			DPR("BlockingReadStream: copyInput: %u != %u\n");
			return paUnanticipatedHostError;
		}
		numFrames -= n;
	}
	return paNoError;
}
Exemple #7
0
static void *
read_thread(void *dp)
{
	sndio_in_driver *d = dp;
	struct pollfd pfd;
	int size, ret, off, nfds;

	if (!sio_start(d->hdl)) {
		error_error("could not start sndio");
		goto done;
	}

	while (d->read_trun) {
		nfds = sio_pollfd(d->hdl, &pfd, POLLIN);
		poll(&pfd, nfds, -1);
		if (sio_revents(d->hdl, &pfd) & POLLIN) {
			size = d->par.rchan * d->par.bps * d->bufsize;
			off = 0;
			while (size > 0) {
				ret = sio_read(d->hdl, d->sndbuf + off, size);
				off += ret;
				size -= ret;
			}
			sample_editor_sampled(d->sndbuf, d->bufsize,
			    d->par.rate, d->mf);
		}
	}
done:
	pthread_exit(NULL);
	return NULL;
}
Exemple #8
0
static int audio_read_packet(AVFormatContext *s1, AVPacket *pkt)
{
    SndioData *s = s1->priv_data;
    int64_t bdelay, cur_time;
    int ret;

    if ((ret = av_new_packet(pkt, s->buffer_size)) < 0)
        return ret;

    ret = sio_read(s->hdl, pkt->data, pkt->size);
    if (ret == 0 || sio_eof(s->hdl)) {
        av_free_packet(pkt);
        return AVERROR_EOF;
    }

    pkt->size   = ret;
    s->softpos += ret;

    /* compute pts of the start of the packet */
    cur_time = av_gettime();

    bdelay = ret + s->hwpos - s->softpos;

    /* convert to pts */
    pkt->pts = cur_time - ((bdelay * 1000000) /
        (s->bps * s->channels * s->sample_rate));

    return 0;
}
Exemple #9
0
//---------------------------------------------------------------------------
bool __fastcall CSerialPort::ReadData(char *pBuffer,char EndByte)
{
        DWORD dwStart=GetTickCount();
        char Rx[MAX_BUFFER]={0};
        int nIndex=0;
        int nRet;
        while(1)
        {
                nRet=sio_read(m_nPortNo,pBuffer,MAX_BUFFER);
                if(nRet>0)
                {
                        strncpy(Rx+nIndex,pBuffer,nRet);
                        nIndex+=nRet;
                         if(pBuffer[nRet-1]==EndByte)
                         {
                                strcpy(pBuffer,Rx);
                                return true;
                         }
                }
                if(nRet<0) return false;

                if((GetTickCount()-dwStart)>2000) break;
                ::Sleep(1);
                
        }

    return false;

}
Exemple #10
0
void probe_superio_ite(void)
{
	struct superio s = {};
	uint16_t ite_ports[] = {ITE_SUPERIO_PORT1, ITE_SUPERIO_PORT2, 0};
	uint16_t *i = ite_ports;

	s.vendor = SUPERIO_VENDOR_ITE;
	for (; *i; i++) {
		s.port = *i;
		s.model = probe_id_ite(s.port);
		switch (s.model >> 8) {
		case 0x82:
		case 0x86:
		case 0x87:
			/* FIXME: Print revision for all models? */
			msg_pdbg("Found ITE Super I/O, ID 0x%04hx on port "
				 "0x%x\n", s.model, s.port);
			register_superio(s);
			break;
		case 0x85:
			msg_pdbg("Found ITE EC, ID 0x%04hx,"
			         "Rev 0x%02x on port 0x%x.\n",
			         s.model,
			         sio_read(s.port, CHIP_VER_REG),
			         s.port);
			register_superio(s);
			break;
		}
	}

	return;
}
Exemple #11
0
/* Core streaming function for this module
 * This is what actually produces the data which gets streamed.
 *
 * returns:  >0  Number of bytes read
 *            0  Non-fatal error.
 *           <0  Fatal error.
 */
static int sndio_read(void *self, ref_buffer *rb)
{
    int result;
    im_sndio_state *s = self;

    rb->buf = malloc(BUFSIZE * s->par.bps * s->par.rchan);
    if(!rb->buf)
        return -1;
    result = sio_read(s->hdl, rb->buf, BUFSIZE * s->par.bps * s->par.rchan);

    rb->len = result;
    rb->aux_data = s->par.rate * s->par.rchan * s->par.bps;

    if(s->newtrack)
    {
        rb->critical = 1;
        s->newtrack = 0;
    }

    if(result == 0)
    {
        if(sio_eof(s->hdl))
        {
            LOG_ERROR0("Error reading from audio device");
            free(rb->buf);
            return -1;
        }
    }

    return rb->len;
}
Exemple #12
0
/**
 * Static function for easy use of blockig or non-blocking
 * sio_read
 *
 * @param fd serial device handle
 * @param data pointer to data buffer for receiving
 * @param len maximum length (in bytes) of data to receive
 * @param block if 1, call sio_read; if 0, call sio_tryread
 * @return return value of sio_read of sio_tryread
 */
static u32_t
slip_sio_read(sio_fd_t fd, u8_t* data, u32_t len, u8_t block)
{
  if (block) {
    return sio_read(fd, data, len);
  } else {
    return sio_tryread(fd, data, len);
  }
}
Exemple #13
0
static int it85xx_spi_common_init(struct superio s)
{
	chipaddr base;

	msg_pdbg("%s():%d superio.vendor=0x%02x\n", __func__, __LINE__,
	         s.vendor);

	if (register_shutdown(it85xx_shutdown, NULL))
		return 1;

#ifdef LPC_IO
	/* Get LPCPNP of SHM. That's big-endian */
	sio_write(s.port, LDNSEL, 0x0F); /* Set LDN to SHM (0x0F) */
	shm_io_base = (sio_read(s.port, SHM_IO_BAR0) << 8) +
	              sio_read(s.port, SHM_IO_BAR1);
	msg_pdbg("%s():%d shm_io_base=0x%04x\n", __func__, __LINE__,
	         shm_io_base);

	/* These pointers are not used directly. They will be send to EC's
	 * register for indirect access. */
	base = 0xFFFFF000;
	ce_high = ((unsigned char*)base) + 0xE00;  /* 0xFFFFFE00 */
	ce_low = ((unsigned char*)base) + 0xD00;  /* 0xFFFFFD00 */

	/* pre-set indirect-access registers since in most of cases they are
	 * 0xFFFFxx00. */
	INDIRECT_A0(shm_io_base, base & 0xFF);
	INDIRECT_A2(shm_io_base, (base >> 16) & 0xFF);
	INDIRECT_A3(shm_io_base, (base >> 24));
#endif
#ifdef LPC_MEMORY
	base = (chipaddr)programmer_map_flash_region("it85 communication",
						     0xFFFFF000, 0x1000);
	msg_pdbg("%s():%d base=0x%08x\n", __func__, __LINE__,
	         (unsigned int)base);
	ce_high = (unsigned char*)(base + 0xE00);  /* 0xFFFFFE00 */
	ce_low = (unsigned char*)(base + 0xD00);  /* 0xFFFFFD00 */
#endif

	return 0;
}
Exemple #14
0
int sio_read(char * buff, int maxbuff, int timeout, int pollfd) {
  std::string data;
  int rv= sio_read(data, timeout, pollfd);
  if (rv > 0) {
	if (rv > (maxbuff-4)) rv = maxbuff-4;
	memcpy(buff, data.data(), rv);
	buff[rv]=0;	
  } else {
	buff[0] = 0;
  };
  return rv;
};
Exemple #15
0
/**
 * The SLIP input thread.
 *
 * Feed the IP layer with incoming packets
 *
 * @param nf the lwip network interface structure for this slipif
 */
static void
slipif_loop_thread(void *nf)
{
  u8_t c;
  struct netif *netif = (struct netif *)nf;
  struct slipif_priv *priv = (struct slipif_priv *)netif->state;

  while (1) {
    if (sio_read(priv->sd, &c, 1) > 0) {
      slipif_rxbyte_input(netif, c);
    }
  }
}
Exemple #16
0
unsigned int
siofile_read(struct file *file, unsigned char *data, unsigned int count)
{
	struct siofile *f = (struct siofile *)file;
	unsigned int n;

#ifdef DEBUG
	if (f->rtickets == 0) {
		file_dbg(&f->file);
		dbg_puts(": called with no read tickets\n");
	}
#endif
	if (count > f->rtickets)
		count = f->rtickets;
	n = f->started ? sio_read(f->hdl, data, count) : 0;
	if (n == 0) {
		f->file.state &= ~FILE_ROK;
		if (sio_eof(f->hdl)) {
#ifdef DEBUG
			dbg_puts(f->file.name);
			dbg_puts(": failed to read from device\n");
#endif
			file_eof(&f->file);
		} else {
#ifdef DEBUG
			if (debug_level >= 4) {
				file_dbg(&f->file);
				dbg_puts(": reading blocked\n");
			}
#endif
		}
		return 0;
	} else {
		f->rtickets -= n;
		if (f->rtickets == 0) {
			f->file.state &= ~FILE_ROK;
#ifdef DEBUG
			if (debug_level >= 4) {
				file_dbg(&f->file);
				dbg_puts(": read tickets exhausted\n");
			}
#endif
		}
	}
	return n;

}
Exemple #17
0
u8_t
sio_recv( sio_fd_t fd )
{
    u8_t            data;
    serdev_t       *dev = fd;

    if( dev->ready )
    {
        while( sio_read( fd, &data, 1 ) != 1 );
    }
    else
    {
        LWIP_ASSERT( "sio_recv: dev->ready != 0 ", dev->ready != 0 );
        data = '\0';
    }
    return data;
}
Exemple #18
0
/*
=======================================
    RS232 接收线程
=======================================
*/
CR_API uint_t STDCALL
qst_rs232_main (
  __CR_IN__ void_t* parm
    )
{
    sQstComm*   ctx = (sQstComm*)parm;

    /* 工作循环 */
    while (!ctx->comm.quit)
    {
        uint_t  back;
        ansi_t  cha, *data;

        /* 一个个字节读 */
        back = sio_read(ctx->comm.obj.port, &cha, 1);
        if (back == 1) {
            if (CR_VCALL(ctx->bufs)->putb_no(ctx->bufs, cha))
                ctx->size += 1;
            continue;
        }
        if (back != 0) {
            thread_sleep(20);
            continue;
        }

        /* 文本模式处理 */
        if (ctx->size == 0)
            continue;
        data = (ansi_t*)(CR_VCALL(ctx->bufs)->flush(ctx->bufs));
        if (ctx->comm.text)
            ctx->size = qst_txt_mode(data, ctx->size);

        /* 渲染读到的内容 */
        _ENTER_COM_SINGLE_
        ctx->comm.render(parm, data, ctx->size);
        _LEAVE_COM_SINGLE_

        /* 缓存指针复位 */
        CR_VCALL(ctx->bufs)->reput(ctx->bufs, 0);
        ctx->size = 0;
    }

    /* 退出时关闭串口 */
    sio_close(ctx->comm.obj.port);
    return (QST_OKAY);
}
Exemple #19
0
static void *read_thread(void *arg)
{
	struct ausrc_st *st = arg;

	if (!sio_start(st->hdl)) {
		warning("sndio: could not start record\n");
		goto out;
	}

	while (st->run) {
		size_t n = sio_read(st->hdl, st->sampv, st->sampc*2);
		st->rh(st->sampv, n/2, st->arg);
	}

 out:
	return NULL;
}
Exemple #20
0
/***************************************************************
【函数功能】: 报文接收回调函数
【输    入】: 回传的串口号
【输    出】: 无
【全局变量】:	g_pGyro
【说    明】: sio_read得到的可能是一个完整报文,可能是一半报文,
				也可能是单个字节。len返回实际读取的字节数量。
	!!!只有RecvCall这个线程,不再需要Mutex互斥量!!!
***************************************************************/
VOID CALLBACK CGyro::RecvCall(int port)
{
	if (port != g_pGyro->m_iPort)
		return;
	int len = sio_read(port, g_pGyro->m_pRecvBuf, 20);
	if (len == 0)
		return;
	/**********************************************/
	//int err = g_pGyro->RecvProcess(len);
	//if (err == -1)	// 报文长度不对,入接收队列了,试图处理接收队列
	//{
	//	err = g_pGyro->RecvQueueProcess();
	//}
	g_pGyro->m_pRecvQueue->QueueNWrite(g_pGyro->m_pRecvBuf, len);
	g_pGyro->RecvQueueProcess();
	/**********************************************/
}
Exemple #21
0
static void
pppos_rx_thread(void *arg)
{
  u32_t len;
  u8_t buffer[128];
  LWIP_UNUSED_ARG(arg);

  /* Please read the "PPPoS input path" chapter in the PPP documentation. */
  while (1) {
    len = sio_read(ppp_sio, buffer, sizeof(buffer));
    if (len > 0) {
      /* Pass received raw characters from PPPoS to be decoded through lwIP
       * TCPIP thread using the TCPIP API. This is thread safe in all cases
       * but you should avoid passing data byte after byte. */
      pppos_input_tcpip(ppp, buffer, len);
    }
  }
}
Exemple #22
0
/***************************************************************
【函数功能】: 报文接收的回调函数
【输    入】: 回传的串口号
【输    出】: 无
【全局变量】:	g_pSensor
【说    明】: sio_read得到的可能是一个完整报文,可能是一半报文,
				也可能是单个字节。len返回实际读取的字节数量。
	!!!接收回调线程 和 定时发送的回调线程 用m_hMutex做互斥!!!
***************************************************************/
VOID CALLBACK CSensor::RecvCall(int port)
{
	if (port != g_pSensor->m_iPort)
		return;
	int len = sio_read(port,g_pSensor->m_pRecvBuf, MAX_SENSOR_BUF_SIZE);
	if(len == 0)
		return;
	/**********************************************/
	WaitForSingleObject(g_pSensor->m_hMutex,1000);
	// 将报文写入接收队列,长度len可能是1或半个报文或整个报文长度
	g_pSensor->m_pRecvQueue->QueueNWrite(g_pSensor->m_pRecvBuf, len);
	int err = g_pSensor->RecvQueueProcess();		// 在队列中处理
	if (err != -1)	// 接收到一个完整报文,可能正确或错误
	{
		g_pSensor->m_sCmd.stat = STAT_SENSOR_R2T;
	}
	else // 等待下一个报文,或超时处理
	{}		

	ReleaseMutex(g_pSensor->m_hMutex);
	/**********************************************/
}
Exemple #23
0
/**
 * Waits for an response from the modem. This function returns:
 *   -1: when no more data could be read from the serial (polling)
 *   CHAT_ERR_OK: when the correct response was received
 *   CHAT_ERR_ABORT: when an abort response was received
 *   CHAT_ERR_TIMEOUT: when a timeout occured
 * @param chat Chat
 * @param item Item to wait for
 * @return See above.
 */
static int chat_wait(struct chat *chat, const struct chat_item *item)
{
  int count;
  const struct chat_item *abort;

  while (chat->recvd < BUFSIZE) {
    /* Receive data from serial */
    if ((count = sio_read(chat->sd, (u8_t *) &chat->buf[chat->recvd],
                          BUFSIZE - chat->recvd)) < 1)
      break;
    chat->recvd += count;
    chat->buf[chat->recvd] = '\0';

    /* Check abort strings */
    for (abort = chat->items; abort->cmd != CHAT_LAST; abort++) {
      if (abort->cmd != CHAT_ABORT)
        continue;
      if (strstr(chat->buf, abort->arg)) {
        LWIP_DEBUGF(PPP_DEBUG, ("chat_wait: ABORT '%s'\n", abort->arg));
        return CHAT_ERR_ABORT;
      }
    }

    /* Check wait string */
    if (strstr(chat->buf, item->arg)) {
      LWIP_DEBUGF(PPP_DEBUG, ("chat_wait: SUCCESS\n"));
      return CHAT_ERR_OK;
    }
  }

  /* Check for timeout */
  if (chat->timeleft == 0) {
    LWIP_DEBUGF(PPP_DEBUG, ("chat_wait: TIMEOUT\n"));
    return CHAT_ERR_TIMEOUT;
  }

  return -1;
}
Exemple #24
0
static void *
sndio_mainloop(void *arg)
{
#define MAXFDS 8
  struct pollfd pfds[MAXFDS];
  cubeb_stream *s = arg;
  int n, eof = 0, prime, nfds, events, revents, state = CUBEB_STATE_STARTED;
  size_t pstart = 0, pend = 0, rstart = 0, rend = 0;
  long nfr;

  DPR("sndio_mainloop()\n");
  s->state_cb(s, s->arg, CUBEB_STATE_STARTED);
  pthread_mutex_lock(&s->mtx);
  if (!sio_start(s->hdl)) {
    pthread_mutex_unlock(&s->mtx);
    return NULL;
  }
  DPR("sndio_mainloop(), started\n");

  if (s->mode & SIO_PLAY) {
    pstart = pend = s->nfr * s->pbpf;
    prime = s->nblks;
    if (s->mode & SIO_REC) {
      memset(s->rbuf, 0, s->nfr * s->rbpf);
      rstart = rend = s->nfr * s->rbpf;
    }
  } else {
    prime = 0;
    rstart = 0;
    rend = s->nfr * s->rbpf;
  }

  for (;;) {
    if (!s->active) {
      DPR("sndio_mainloop() stopped\n");
      state = CUBEB_STATE_STOPPED;
      break;
    }

    /* do we have a complete block? */
    if ((!(s->mode & SIO_PLAY) || pstart == pend) &&
	(!(s->mode & SIO_REC) || rstart == rend)) {

      if (eof) {
        DPR("sndio_mainloop() drained\n");
        state = CUBEB_STATE_DRAINED;
        break;
      }

      if ((s->mode & SIO_REC) && s->conv)
        s16_to_float(s->rbuf, s->nfr * s->rchan);

      /* invoke call-back, it returns less that s->nfr if done */
      pthread_mutex_unlock(&s->mtx);
      nfr = s->data_cb(s, s->arg, s->rbuf, s->pbuf, s->nfr);
      pthread_mutex_lock(&s->mtx);
      if (nfr < 0) {
        DPR("sndio_mainloop() cb err\n");
        state = CUBEB_STATE_ERROR;
        break;
      }
      s->swpos += nfr;

      /* was this last call-back invocation (aka end-of-stream) ? */
      if (nfr < s->nfr) {

        if (!(s->mode & SIO_PLAY) || nfr == 0) {
          state = CUBEB_STATE_DRAINED;
          break;
	}

        /* need to write (aka drain) the partial play block we got */
        pend = nfr * s->pbpf;
        eof = 1;
      }

      if (prime > 0)
        prime--;

      if ((s->mode & SIO_PLAY) && s->conv)
          float_to_s16(s->pbuf, nfr * s->pchan);

      if (s->mode & SIO_REC)
        rstart = 0;
      if (s->mode & SIO_PLAY)
        pstart = 0;
    }

    events = 0;
    if ((s->mode & SIO_REC) && rstart < rend && prime == 0)
      events |= POLLIN;
    if ((s->mode & SIO_PLAY) && pstart < pend)
      events |= POLLOUT;
    nfds = sio_pollfd(s->hdl, pfds, events);

    if (nfds > 0) {
      pthread_mutex_unlock(&s->mtx);
      n = poll(pfds, nfds, -1);
      pthread_mutex_lock(&s->mtx);
      if (n < 0)
        continue;
    }

    revents = sio_revents(s->hdl, pfds);

    if (revents & POLLHUP) {
      state = CUBEB_STATE_ERROR;
      break;
    }

    if (revents & POLLOUT) {
      n = sio_write(s->hdl, s->pbuf + pstart, pend - pstart);
      if (n == 0 && sio_eof(s->hdl)) {
        DPR("sndio_mainloop() werr\n");
        state = CUBEB_STATE_ERROR;
        break;
      }
      pstart += n;
    }

    if (revents & POLLIN) {
      n = sio_read(s->hdl, s->rbuf + rstart, rend - rstart);
      if (n == 0 && sio_eof(s->hdl)) {
        DPR("sndio_mainloop() rerr\n");
        state = CUBEB_STATE_ERROR;
        break;
      }
      rstart += n;
    }

    /* skip rec block, if not recording (yet) */
    if (prime > 0 && (s->mode & SIO_REC))
      rstart = rend;
  }
  sio_stop(s->hdl);
  s->hwpos = s->swpos;
  pthread_mutex_unlock(&s->mtx);
  s->state_cb(s, s->arg, state);
  return NULL;
}
Exemple #25
0
/* This is somewhat different to other ports: we have a main loop here:
 * a dedicated task that waits for packets to arrive. This would normally be
 * done from interrupt context with embedded hardware, but we don't get an
 * interrupt in windows for that :-) */
void main_loop()
{
#if !NO_SYS
  err_t err;
  sys_sem_t init_sem;
#endif /* NO_SYS */
#if PPP_SUPPORT
#if !USE_ETHERNET
  int count;
  u8_t rxbuf[1024];
#endif
  volatile int callClosePpp = 0;
#endif /* PPP_SUPPORT */

  /* initialize lwIP stack, network interfaces and applications */
#if NO_SYS
  lwip_init();
  test_init(NULL);
#else /* NO_SYS */
  err = sys_sem_new(&init_sem, 0);
  tcpip_init(test_init, &init_sem);
  /* we have to wait for initialization to finish before
   * calling update_adapter()! */
  sys_sem_wait(&init_sem);
  sys_sem_free(&init_sem);
#endif /* NO_SYS */

  /* MAIN LOOP for driver update (and timers if NO_SYS) */
  while (!_kbhit()) {
#if NO_SYS
    /* handle timers (already done in tcpip.c when NO_SYS=0) */
    sys_check_timeouts();
#endif /* NO_SYS */

#if USE_ETHERNET
#if !PCAPIF_RX_USE_THREAD
    /* check for packets and link status*/
    pcapif_poll(&netif);
    /* When pcapif_poll comes back, there are not packets, so sleep to
       prevent 100% CPU load. Don't do this in an embedded system since it
       increases latency! */
    sys_msleep(1);
#else /* !PCAPIF_RX_USE_THREAD */
    sys_msleep(50);
#endif /* !PCAPIF_RX_USE_THREAD */
#else /* USE_ETHERNET */
#if 0 /* set this to 1 if PPP_INPROC_OWNTHREAD==0 or not defined (see ppp.c) */
    /* try to read characters from serial line and pass them to PPPoS */
    count = sio_read(ppp_sio, (u8_t*)rxbuf, 1024);
    if(count > 0) {
      pppos_input(ppp_desc, rxbuf, count);
    } else
#endif
    {
      /* nothing received, give other tasks a chance to run */
      sys_msleep(1);
    }

#endif /* USE_ETHERNET */
#if !LWIP_NETIF_LOOPBACK_MULTITHREADING
    /* check for loopback packets on all netifs */
    netif_poll_all();
#endif /* !LWIP_NETIF_LOOPBACK_MULTITHREADING */
#if PPP_SUPPORT
    {
    int do_hup = 0;
    if(do_hup) {
      pppSigHUP(ppp_desc);
      do_hup = 0;
    }
    }
    if(callClosePpp && (ppp_desc >= 0)) {
      /* make sure to disconnect PPP before stopping the program... */
      callClosePpp = 0;
#if NO_SYS
      pppClose(ppp_desc);
#else
      tcpip_callback_with_block(pppCloseCallback, (void*)ppp_desc, 0);
#endif
      ppp_desc = -1;
    }
#endif /* PPP_SUPPORT */
  }

#if PPP_SUPPORT
    if(ppp_desc >= 0) {
      u32_t started;
      printf("Closing PPP connection...\n");
      /* make sure to disconnect PPP before stopping the program... */
#if NO_SYS
      pppClose(ppp_desc);
#else
      tcpip_callback_with_block(pppCloseCallback, (void*)ppp_desc, 0);
#endif
      ppp_desc = -1;
      /* Wait for some time to let PPP finish... */
      started = sys_now();
      do
      {
#if USE_ETHERNET && !PCAPIF_RX_USE_THREAD
        pcapif_poll(&netif);
#else /* USE_ETHERNET && !PCAPIF_RX_USE_THREAD */
        sys_msleep(50);
#endif /* USE_ETHERNET && !PCAPIF_RX_USE_THREAD */
        /* @todo: need a better check here: only wait until PPP is down */
      } while(sys_now() - started < 5000);
    }
#endif /* PPP_SUPPORT */
#if USE_ETHERNET
  /* release the pcap library... */
  pcapif_shutdown(&netif);
#endif /* USE_ETHERNET */
}
Exemple #26
0
int
sio_getc(struct siobuf *sio)
{
  char ch;
  return sio_read(sio, &ch, 1) == 1 ? ch : -1;
}
Exemple #27
0
/* Main routine for the server threads */
thr_startfunc_t serve_pipe(void *data)
{
	char sio_buf[BUFSIZ], sock_buf[BUFSIZ];
	int fd_max, sio_fd, sock_fd;
	int sio_count, sock_count;
	int res, port;
	fd_set rfds, wfds;
	pipe_s *pipe = (pipe_s *)data;
#if defined(__UNIX__)
	struct timeval tv = {pipe->timeout, 0};
	struct timeval *ptv = &tv;
#elif defined(__WIN32__)
	struct timeval tv = {0,10000};
	struct timeval *ptv = &tv;
	DWORD msecs = 0, timeout = pipe->timeout * 1000;
#endif

	port = pipe->sio.info.port;

	/* Only proceed if we can lock the mutex */
	if (thr_mutex_trylock(pipe->mutex))
	{
		error("server(%d) - resource is locked", port);
	}
	else
	{

		sio_count = 0;
		sock_count = 0;
		sio_fd = pipe->sio.fd;
		sock_fd = pipe->sock.fd;
#if defined(__UNIX__)
		fd_max = sio_fd > sock_fd ? sio_fd : sock_fd;	
#elif defined(__WIN32__)
		fd_max = sock_fd;
		msecs = GetTickCount();
#endif
		fprintf(stderr, "server(%d) - thread started\n", port);
		
		while (1)
		{
			FD_ZERO(&rfds);
			FD_ZERO(&wfds);

#if defined(__UNIX__)
			/* Always ask for read notification to check for EOF */			
			FD_SET(sio_fd, &rfds);
			/* Only ask for write notification if we have something to write */
			if (sock_count > 0)
				FD_SET(sio_fd, &wfds);

			/* Reset timeout values */
			tv.tv_sec = pipe->timeout;
			tv.tv_usec = 0;

#endif
			/* Always ask for read notification to check for EOF */
			FD_SET(sock_fd, &rfds);
			/* Only ask for write notification if we have something to write */
			if (sio_count > 0)
				FD_SET(sock_fd, &wfds);

			//DBG_MSG2("server(%d) waiting for events", port);
			
			/* Wait for read/write events */
			res = select(fd_max + 1, &rfds, &wfds, NULL, ptv);
			if (res == -1)
			{
				perror2("server(%d) - select()", port);
				break;
			}
#if defined(__UNIX__)

			/* Use the select result for timeout detection */
			if (res == 0)
			{
				fprintf(stderr, "server(%d) - timed out\n", port);
				break;
			}

			/* Input from serial port? */
			if (FD_ISSET(sio_fd, &rfds))
#elif defined(__WIN32__)
				
			if (1)
#endif
			{
				/* Only read input if buffer is empty */
				if (sio_count == 0)
				{
					sio_count = sio_read(&pipe->sio, sio_buf, sizeof(sio_buf));
					if (sio_count <= 0)
					{
						if (sio_count == 0)
						{
#if defined(__UNIX__)
							fprintf(stderr, "server(%d) - EOF from sio\n", port);
							break;
#endif
						}
						else
						{
							perror2("server(%d) - read(sio)", port);
							break;
						}
					}
					else 
					{
						DBG_MSG3("server(%d) - read %d bytes from sio", port, sio_count);
					}
				}
			}

			/* Write to socket possible? */
			if (FD_ISSET(sock_fd, &wfds))
			{
				if (sio_count > 0)
				{
					if ((res = tcp_write(&pipe->sock, sio_buf, sio_count)) < 0)
					{
						perror2("server(%d) - write(sock)", port);
						break;
					}
					DBG_MSG3("server(%d) - Wrote %d bytes to sock", port, res);
					sio_count -= res;
				}
			}


			/* Input from socket? */
			if (FD_ISSET(sock_fd, &rfds))
			{
				/* Only read input if buffer is empty */
				if (sock_count == 0)
				{
					sock_count = tcp_read(&pipe->sock, sock_buf, sizeof(sock_buf));
					if (sock_count <= 0)
					{
						if (sock_count == 0)
						{
							fprintf(stderr, "server(%d) - EOF from sock\n", port);
							break;
						}
						else
						{
							perror2("server(%d) - read(sock)", port);
							break;
						}
					}
					DBG_MSG3("server(%d) - read %d bytes from sock", port, sock_count);
				}
			}

#if defined(__UNIX__)
			/* Write to serial port possible? */
			if (FD_ISSET(sio_fd, &wfds))
#elif defined(__WIN32__)
			
			/* No socket IO performed? */
			if ((!FD_ISSET(sock_fd, &rfds)) && (!FD_ISSET(sock_fd, &wfds)))
			{
				/* Break on a time out */
				if (GetTickCount() - msecs > timeout)
				{
					fprintf(stderr, "server(%d) - timed out\n", port);
					break;					
				}
			}
			else
			{
				msecs = GetTickCount();
			}

			if (1)
#endif
			{
				if (sock_count > 0)
				{
					if ((res = sio_write(&pipe->sio, sock_buf, sock_count)) < 0)
					{
						perror2("server(%d) - write(sio)", port);
						break;
					}
					DBG_MSG3("server(%d) - wrote %d bytes to sio", port, res);
					sock_count -= res;
				}
			}

		}
		
		/* Unlock our mutex */
		thr_mutex_unlock(pipe->mutex);		
	}

   	fprintf(stderr, "server(%d) exiting\n", port);

	/* Clean up - don't call pipe_cleanup() as that would nuke our mutex */
	sio_cleanup(&pipe->sio);
	tcp_cleanup(&pipe->sock);


	free(pipe);
	
	thr_exit((thr_exitcode_t)0);

	return (thr_exitcode_t)0;
}
Exemple #28
0
//嗅探模式读取应答通讯报文
int CComm_Thread::CommRecv(unsigned char *m_data)
{
    COApp * pApp = (COApp *)AfxGetApp();
    unsigned char x_ucLength;
    unsigned char x_ucDataR[100],x_ucCrc[2];

    //数据缓存初始化
    x_ucLength = 0;
    memset(x_ucCrc,0,sizeof(x_ucCrc));
    memset(x_ucDataR,0,sizeof(x_ucDataR));

    //开始进行嗅探读取数据
    for(int k1=0; k1<10; k1++)
    {
        if(sio_read(pApp->x_Port,(char *)x_ucDataR,1) > 0)
            break;
        Sleep(10);
    }

    //嗅探失败退出
    if(k1 >=10)
    {
        pApp->test.Format("嗅探失败!");
        SendMessage(pApp->m_pMainWnd->m_hWnd,WM_MSGCOMMANS,0x10,0x00);
        return x_ucLength;
    }

    //提取应答命令中的命令码,判断数据长度
    if(sio_read(pApp->x_Port,(char *)&x_ucDataR[1],1) != 1)
        return x_ucLength;

    //根据命令码的不同,读取相应的后续内容数据
    switch(x_ucDataR[1])
    {
    case 0x03:  //数据提取
        //读取数据长度
        if(sio_read(pApp->x_Port,(char *)&x_ucDataR[2],1) == 1)
        {
            //判断数据是否超界
            if(x_ucDataR[2] > 100)
            {
                sio_flush(pApp->x_Port,2);
                return 0;
            }
            //读取后续数据
            x_ucLength = x_ucDataR[2]+2;
            if(sio_read(pApp->x_Port,(char *)&x_ucDataR[3],x_ucLength) == x_ucLength)
            {   //应答长度合法
                x_ucLength += 3;
                //数据读取完毕,校验数据
                CRC16(x_ucDataR,x_ucLength-2,x_ucCrc);
                if((x_ucDataR[x_ucLength-2] != x_ucCrc[0]) || (x_ucDataR[x_ucLength-1] != x_ucCrc[1]))
                {
                    pApp->test.Format("校验错误!");
                    SendMessage(pApp->m_pMainWnd->m_hWnd,WM_MSGCOMMANS,0x10,0x00);
                    x_ucLength = 0;
                }
            }
            else
            {   //应答长度非法
                x_ucLength = 0;
            }
        }
        break;
    case 0x10:  //参数设定
        if(sio_read(pApp->x_Port,(char *)&x_ucDataR[2],6) == 6)
        {   //长度合法
            x_ucLength = 8;

            //数据读取完毕,校验数据
            CRC16(x_ucDataR,x_ucLength-2,x_ucCrc);
            if((x_ucDataR[x_ucLength-2] != x_ucCrc[0]) || (x_ucDataR[x_ucLength-1] != x_ucCrc[1]))
            {
                pApp->test.Format("校验错误!");
                SendMessage(pApp->m_pMainWnd->m_hWnd,WM_MSGCOMMANS,0x10,0x00);
                x_ucLength = 0;
            }
        }
        break;
    default:
        x_ucLength = 0;
        break;
    }

    //拷贝输出应答报文
    memcpy(m_data,x_ucDataR,x_ucLength);

    //TEST
    //pApp->test.Format("收到报文: ← %02X %02X %02X %02X %02X %02X %02X %02X",x_ucDataR[0],x_ucDataR[1],x_ucDataR[2],x_ucDataR[3],x_ucDataR[4],x_ucDataR[5],x_ucDataR[6],x_ucDataR[7]);
    //SendMessage(pApp->m_pMainWnd->m_hWnd,WM_MSGCOMMANS,0x17,0x00);
    //TEST

    //清除缓冲区内的垃圾
    sio_flush(pApp->x_Port,2);

    return x_ucLength;
}
Exemple #29
0
/*
 * I/O loop for callback interface
 */
static void *
sndioThread(void *arg)
{
	PaSndioStream *s = (PaSndioStream *)arg;
	PaStreamCallbackTimeInfo ti;
	unsigned char *data;
	unsigned todo, rblksz, wblksz;
	int n, result;
	
	rblksz = s->par.round * s->par.rchan * s->par.bps;
	wblksz = s->par.round * s->par.pchan * s->par.bps;
	
	DPR("sndioThread: mode = %x, round = %u, rblksz = %u, wblksz = %u\n",
	    s->mode, s->par.round, rblksz, wblksz);
	
	while (!s->stopped) {
		if (s->mode & SIO_REC) {
			todo = rblksz;
			data = s->rbuf;
			while (todo > 0) {
				n = sio_read(s->hdl, data, todo);
				if (n == 0) {
					DPR("sndioThread: sio_read failed\n");
					goto failed;
				}
				todo -= n;
				data += n;
			}
			s->rpos += s->par.round;
			ti.inputBufferAdcTime = 
			    (double)s->realpos / s->par.rate;
		}
		if (s->mode & SIO_PLAY) {
			ti.outputBufferDacTime =
			    (double)(s->realpos + s->par.bufsz) / s->par.rate;
		}
		ti.currentTime = s->realpos / (double)s->par.rate;
		PaUtil_BeginBufferProcessing(&s->bufproc, &ti, 0);
		if (s->mode & SIO_PLAY) {
			PaUtil_SetOutputFrameCount(&s->bufproc, s->par.round);
			PaUtil_SetInterleavedOutputChannels(&s->bufproc,
			    0, s->wbuf, s->par.pchan);
		}
		if (s->mode & SIO_REC) {
			PaUtil_SetInputFrameCount(&s->bufproc, s->par.round);
			PaUtil_SetInterleavedInputChannels(&s->bufproc,
			    0, s->rbuf, s->par.rchan);
		}
		result = paContinue;
		n = PaUtil_EndBufferProcessing(&s->bufproc, &result);
		if (n != s->par.round) {
			DPR("sndioThread: %d < %u frames, result = %d\n",
			    n, s->par.round, result);
		}
		if (result != paContinue) {
			break;
		}
		if (s->mode & SIO_PLAY) {
			n = sio_write(s->hdl, s->wbuf, wblksz);
			if (n < wblksz) {
				DPR("sndioThread: sio_write failed\n");
				goto failed;
			}
			s->wpos += s->par.round;
		}
	}
 failed:
	s->active = 0;
	DPR("sndioThread: done\n");
}
Exemple #30
0
int
main(int argc, char **argv) {
	int ch;
	struct sio_hdl *hdl;
	ssize_t n;
	
	/*
	 * defaults parameters
	 */
	sio_initpar(&par);
	par.sig = 1;
	par.bits = 16;
	par.rchan = 2;
	par.rate = 44100;

	while ((ch = getopt(argc, argv, "r:c:e:b:x:")) != -1) {
		switch(ch) {
		case 'r':
			if (sscanf(optarg, "%u", &par.rate) != 1) {
				fprintf(stderr, "%s: bad rate\n", optarg);
				exit(1);
			}
			break;
		case 'c':
			if (sscanf(optarg, "%u", &par.rchan) != 1) {
				fprintf(stderr, "%s: channels number\n", optarg);
				exit(1);
			}
			break;
		case 'e':
			if (!sio_strtoenc(&par, optarg)) {
				fprintf(stderr, "%s: unknown encoding\n", optarg);
				exit(1);
			}
			break;
		case 'x':
			for (par.xrun = 0;; par.xrun++) {
				if (par.xrun == sizeof(xstr) / sizeof(char *)) {
					fprintf(stderr, 
					    "%s: bad xrun mode\n", optarg);
					exit(1);
				}
				if (strcmp(xstr[par.xrun], optarg) == 0)
					break;
			}
			break;			
		default:
			usage();
			exit(1);
			break;
		}
	}

	hdl = sio_open(SIO_DEVANY, SIO_REC, 0);
	if (hdl == NULL) {
		fprintf(stderr, "sio_open() failed\n");
		exit(1);
	}
	sio_onmove(hdl, cb, NULL);
	if (!sio_setpar(hdl, &par)) {
		fprintf(stderr, "sio_setpar() failed\n");
		exit(1);
	}
	if (!sio_getpar(hdl, &par)) {
		fprintf(stderr, "sio_getpar() failed\n");
		exit(1);
	}
	if (!sio_start(hdl)) {
		fprintf(stderr, "sio_start() failed\n");
		exit(1);
	}
	for (;;) {
		n = sio_read(hdl, buf, BUFSZ);
		if (n == 0) {
			fprintf(stderr, "sio_write: failed\n");
			exit(1);
		}
		rlat -= n / (int)(par.bps * par.rchan);
		if (write(STDOUT_FILENO, buf, n) < 0) {
			perror("stdout");
			exit(1);
		}
	}
	sio_close(hdl);
	return 0;
}