/* * Set projection value into srs structure */ bool ows_srs_set(ows * o, ows_srs * c, const buffer * auth_name, int auth_srid) { PGresult *res; buffer *sql; assert(o); assert(c); assert(o->pg); assert(auth_name); sql = buffer_init(); buffer_add_str(sql, "SELECT srid, position('+units=m ' in proj4text)"); buffer_add_str(sql, ", (position('AXIS[\"X\",NORTH]]' in srtext) + position('AXIS[\"Northing\",NORTH]]' in srtext))"); buffer_add_str(sql, " FROM spatial_ref_sys WHERE auth_name='"); buffer_copy(sql, auth_name); buffer_add_str(sql, "' AND auth_srid="); buffer_add_int(sql, auth_srid); res = ows_psql_exec(o, sql->buf); buffer_free(sql); /* If query dont return exactly 1 result, it means projection is not handled */ if (PQresultStatus(res) != PGRES_TUPLES_OK || PQntuples(res) != 1) { PQclear(res); return false; } buffer_empty(c->auth_name); buffer_copy(c->auth_name, auth_name); c->auth_srid = auth_srid; c->srid = atoi(PQgetvalue(res, 0, 0)); /* Such a way to know if units is meter or degree */ if (atoi(PQgetvalue(res, 0, 1)) == 0) c->is_degree = true; else c->is_degree = false; /* Is easting-northing SRID ? */ if (atoi(PQgetvalue(res, 0, 2)) != 0) c->is_eastern_axis = true; PQclear(res); return true; }
mcxstatus mcxIOreset ( mcxIO* xf ) { xf->lc = 0 ; xf->lo = 0 ; xf->lo_ = 0 ; xf->bc = 0 ; xf->ateof = 0 /* regardless of read/write */ ; buffer_empty(xf) /* xf->fp not touched; promote user care */ ; if (xf->usr && xf->usr_reset) return xf->usr_reset(xf->usr) ; return STATUS_OK ; }
void TESession::zmodemDone() { if (zmodemProc) { delete zmodemProc; zmodemProc = 0; zmodemBusy = false; disconnect( sh,SIGNAL(block_in(const char*,int)), this ,SLOT(zmodemRcvBlock(const char*,int)) ); disconnect( sh,SIGNAL(buffer_empty()), this, SLOT(zmodemContinue())); connect( sh,SIGNAL(block_in(const char*,int)), this, SLOT(onRcvBlock(const char*,int)) ); sh->send_bytes("\030\030\030\030", 4); // Abort sh->send_bytes("\001\013\n", 3); // Try to get prompt back zmodemProgress->done(); } }
int mcxIOstep ( mcxIO* xf ) { int c #if 0 ;if (xf->buffer) fprintf(stderr, "buffer [%s]\n", xf->buffer->str) ;else fprintf(stderr, "nobuffer\n") #endif ; if (xf->ateof) c = EOF ; else if (inbuffer(xf)) { c = xf->buffer->str[xf->buffer_consumed++] ; if (!inbuffer(xf)) buffer_empty(xf) ; } else c = fgetc(xf->fp) ; switch(c) { case '\n' : xf->lc++ ; xf->bc++ ; xf->lo_ = xf->lo ; xf->lo = 0 ; break ; case EOF : xf->ateof = 1 ; break ; default : xf->bc++ ; xf->lo++ ; break ; } return c ; }
static inline isc_result_t fromwire_spf(ARGS_FROMWIRE) { isc_result_t result; REQUIRE(type == 99); UNUSED(type); UNUSED(dctx); UNUSED(rdclass); UNUSED(options); do { result = txt_fromwire(source, target); if (result != ISC_R_SUCCESS) return (result); } while (!buffer_empty(source)); return (ISC_R_SUCCESS); }
u8 tty_get_noblock(void) { #ifdef BUFFERED u8 ch; //check if buffer is empty if (buffer_empty(&u1rx) == SUCCESS) { return 0; } else { buffer_get(&u1rx, &ch); return ch; } #else return usart_recv_blocking(USART1); #endif }
cpCommand cpRecogniseCommand(void) { //Basic case: Nothing was captured if(buffer_empty()) return cpCmdUnknown; struct timeval tCurr; gettimeofday(&tCurr, 0); int64_t elapsedMs = timeDiff(&tCurr, &tStart); if(elapsedMs >= (COMMAND_BUFFER_SIZE * 200)) { //Matched 'Last Command' (Single clap) pattern if(!memcmp(buffer, repeatLastCmdPattern, COMMAND_BUFFER_SIZE) && lastCommand != cpCmdUnknown) { reset(); return lastCommand; } int i, j; for(i = 0; i < ARRAY_SIZE(commands); i++) { for(j = 0; j < ARRAY_SIZE(commands[i].patterns); j++) { //We've found a match! if(!memcmp(buffer, commands[i].patterns[j], COMMAND_BUFFER_SIZE)) { reset(); //Remember last command (so that it can be repeated via a single clap) //Exclude cpCmdPower command from this rule if(commands[i].commandId == cpCmdPower) lastCommand = cpCmdUnknown; else lastCommand = commands[i].commandId; return commands[i].commandId; } } } lastCommand = cpCmdUnknown; } return cpCmdUnknown; }
bool Lexer::skipWhitespace() { bool consumed = false; for (;;) { if (buffer_empty()) { buffer_put(m_input->get()); } char current = buffer_peek(); // TODO: Replace it with std::isspace in the future. if (!isspace(current)) { break; } buffer_pop(); consumed = true; } return consumed; }
//This is a very important function. It writes all registered buffers, all variables and the command history to the directory specified in the first argument. Also, it generates eps-files from the switching histogram buffer and log-normalized escape rate buffer. variable flux_write_all_data(opts o,interpreter *i) { char *s; char *vars; FILE *f; char buffer[1024]; variable v=init_variable(); if (i->cast_string(&s,o,0)) { sprintf(buffer,"mkdir \"./data/%s\"",s); system(buffer); sprintf(buffer,"./data/%s/history.ini",s); f=fopen(buffer,"w"); if(f==NULL) return v; if (i->get_history()!=NULL) fwrite((void *)(i->get_history()),strlen((i->get_history()))+1,1,f); fclose(f); for(int x=0;x<n_buffers();x++) { if (buffer_filename(x)!=NULL && buffer_empty(x)==0) { sprintf(buffer,"write_buffer(%d,\"./data/%s/%s\");",x,s,buffer_filename(x)); i->eval_str(buffer,1); sprintf(buffer,"plot_buffer(%d,\"./data/%s/%s.eps\");",x,s,buffer_filename(x)); i->eval_str(buffer,1); } } sprintf(buffer,"./data/%s/vars.ini",s); f=fopen(buffer,"w"); if(f==NULL) return v; vars=i->output_all_variables(); fwrite((void *)vars,strlen(vars),1,f); fclose(f); free(vars); } return v; }
/* * Replace all occurences of string 'before' inside the buffer by string 'after' */ buffer *buffer_replace(buffer * buf, char *before, char *after) { buffer *new_buf, *rest; size_t length; char *pos; assert(before); assert(after); assert(buf); if (!strcmp(before, after)) return buf; /* To prevent infinite loop */ new_buf = buffer_init(); buffer_copy(new_buf, buf); pos = strstr(new_buf->buf, before); /* Look for first occurence */ while (pos) { length = strlen(pos); buffer_pop(new_buf, length); /* Copy the first part without occurence */ buffer_add_str(new_buf, after); /* Add the string after */ /* Add the remaining string */ rest = buffer_init(); buffer_copy(rest, buf); buffer_shift(rest, buf->use - length + strlen(before)); buffer_copy(new_buf, rest); buffer_free(rest); pos = strstr(new_buf->buf, before); /* Search the next occurence */ } buffer_empty(buf); buffer_copy(buf, new_buf); buffer_free(new_buf); return buf; }
void TESession::startZModem(const TQString &zmodem, const TQString &dir, const TQStringList &list) { zmodemBusy = true; zmodemProc = new KProcIO; (*zmodemProc) << zmodem << "-v"; for(TQStringList::ConstIterator it = list.begin(); it != list.end(); ++it) { (*zmodemProc) << (*it); } if (!dir.isEmpty()) zmodemProc->setWorkingDirectory(dir); zmodemProc->start(KProcIO::NotifyOnExit, false); // Override the read-processing of KProcIO disconnect(zmodemProc,TQT_SIGNAL (receivedStdout (TDEProcess *, char *, int)), 0, 0); connect(zmodemProc,TQT_SIGNAL (receivedStdout (TDEProcess *, char *, int)), this, TQT_SLOT(zmodemSendBlock(TDEProcess *, char *, int))); connect(zmodemProc,TQT_SIGNAL (receivedStderr (TDEProcess *, char *, int)), this, TQT_SLOT(zmodemStatus(TDEProcess *, char *, int))); connect(zmodemProc,TQT_SIGNAL (processExited(TDEProcess *)), this, TQT_SLOT(zmodemDone())); disconnect( sh,TQT_SIGNAL(block_in(const char*,int)), this, TQT_SLOT(onRcvBlock(const char*,int)) ); connect( sh,TQT_SIGNAL(block_in(const char*,int)), this, TQT_SLOT(zmodemRcvBlock(const char*,int)) ); connect( sh,TQT_SIGNAL(buffer_empty()), this, TQT_SLOT(zmodemContinue())); zmodemProgress = new ZModemDialog(te->topLevelWidget(), false, i18n("ZModem Progress")); connect(zmodemProgress, TQT_SIGNAL(user1Clicked()), this, TQT_SLOT(zmodemDone())); zmodemProgress->show(); }
void Lexer::consumeText() { m_value = ""; for (;;) { while (skipComments()) { } if (buffer_empty()) { buffer_put(m_input->get()); } char current = buffer_peek(); // TODO: Escape '<' and '>' as '<' and '>'; if (current == '<' || current == '>' || current == std::char_traits<char>::eof()) { break; } m_value.push_back(buffer_pop()); } }
/* * Set a geobbox matching a layer's extent */ ows_geobbox *ows_geobbox_compute(ows * o, buffer * layer_name) { double xmin, ymin, xmax, ymax; buffer *sql; PGresult *res; ows_geobbox *g; ows_bbox *bb; list *geom; list_node *ln; bool first = true; assert(o); assert(layer_name); sql = buffer_init(); geom = ows_psql_geometry_column(o, layer_name); assert(geom); g = ows_geobbox_init(); xmin = ymin = xmax = ymax = 0.0; for (ln = geom->first; ln ; ln = ln->next) { buffer_add_str(sql, "SELECT ST_xmin(g), ST_ymin(g), ST_xmax(g), ST_ymax(g) FROM "); if (o->estimated_extent) { buffer_add_str(sql, "(SELECT ST_Transform(ST_SetSRID(ST_Estimated_Extent('"); buffer_copy(sql, ows_psql_schema_name(o, layer_name)); buffer_add_str(sql, "','"); buffer_copy(sql, ows_psql_table_name(o, layer_name)); buffer_add_str(sql, "','"); buffer_copy(sql, ln->value); buffer_add_str(sql, "'), (SELECT ST_SRID(\""); buffer_copy(sql, ln->value); buffer_add_str(sql, "\") FROM "); buffer_copy(sql, ows_psql_schema_name(o, layer_name)); buffer_add_str(sql, ".\""); buffer_copy(sql, ows_psql_table_name(o, layer_name)); buffer_add_str(sql, "\" LIMIT 1)) ,4326) AS g) AS foo"); } else { buffer_add_str(sql, "(SELECT ST_Transform(ST_SetSRID(ST_Extent(\""); buffer_copy(sql, ln->value); buffer_add_str(sql, "\"), (SELECT ST_SRID(\""); buffer_copy(sql, ln->value); buffer_add_str(sql, "\") FROM "); buffer_copy(sql, ows_psql_schema_name(o, layer_name)); buffer_add_str(sql, ".\""); buffer_copy(sql, ows_psql_table_name(o, layer_name)); buffer_add_str(sql, "\" LIMIT 1)), 4326) AS g "); buffer_add_str(sql, " FROM "); buffer_copy(sql, ows_psql_schema_name(o, layer_name)); buffer_add_str(sql, ".\""); buffer_copy(sql, ows_psql_table_name(o, layer_name)); buffer_add_str(sql, "\" ) AS foo"); } res = ows_psql_exec(o, sql->buf); buffer_empty(sql); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); buffer_free(sql); return g; } if (first || atof(PQgetvalue(res, 0, 0)) < xmin) xmin = atof(PQgetvalue(res, 0, 0)); if (first || atof(PQgetvalue(res, 0, 1)) < ymin) ymin = atof(PQgetvalue(res, 0, 1)); if (first || atof(PQgetvalue(res, 0, 2)) > xmax) xmax = atof(PQgetvalue(res, 0, 2)); if (first || atof(PQgetvalue(res, 0, 3)) > ymax) ymax = atof(PQgetvalue(res, 0, 3)); first = false; PQclear(res); } buffer_free(sql); bb = ows_bbox_init(); ows_bbox_set(o, bb, xmin, ymin, xmax, ymax, 4326); ows_geobbox_set_from_bbox(o, g, bb); ows_bbox_free(bb); return g; }
/* * Execute the wfs get capabilities 1.1.0 request */ static void wfs_get_capabilities_110(ows * o, wfs_request * wr) { buffer *name; assert(o); assert(wr); if (wr->format == WFS_TEXT_XML) fprintf(o->output, "Content-Type: text/xml\n\n"); else fprintf(o->output, "Content-Type: application/xml\n\n"); fprintf(o->output, "<?xml version='1.0' encoding='%s'?>\n", o->encoding->buf); fprintf(o->output, "<WFS_Capabilities"); fprintf(o->output, " version='1.1.0' updateSequence='0'\n"); fprintf(o->output, " xmlns='http://www.opengis.net/wfs'\n"); fprintf(o->output, " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n"); fprintf(o->output, " xmlns:ogc='http://www.opengis.net/ogc'\n"); fprintf(o->output, " xmlns:gml='http://www.opengis.net/gml'\n"); fprintf(o->output, " xmlns:ows='http://www.opengis.net/ows'\n"); fprintf(o->output, " xmlns:xlink='http://www.w3.org/1999/xlink'\n"); fprintf(o->output, " xsi:schemaLocation='http://www.opengis.net/wfs\n"); fprintf(o->output, " http://schemas.opengis.net/wfs/1.1.0/wfs.xsd' >\n"); name = buffer_init(); /* Service Identification Section : provides information about the WFS service iself */ buffer_add_str(name, "ServiceIdentification"); if (wr->sections) { if (in_list(wr->sections, name) || buffer_case_cmp(wr->sections->first->value, "all")) ows_service_identification(o); } else ows_service_identification(o); /* Service Provider Section : provides metadata about the organization operating the WFS server */ buffer_empty(name); buffer_add_str(name, "ServiceProvider"); if (wr->sections) { if (in_list(wr->sections, name) || buffer_case_cmp(wr->sections->first->value, "all")) ows_service_provider(o); } else ows_service_provider(o); /* Operation Metadata Section : specifies the list of requests that the WFS can handle */ buffer_empty(name); buffer_add_str(name, "OperationsMetadata"); if (wr->sections) { if (in_list(wr->sections, name) || buffer_case_cmp(wr->sections->first->value, "all")) wfs_operations_metadata(o); } else wfs_operations_metadata(o); /* FeatureType list Section : specifies the list of feature types available from the wfs */ buffer_empty(name); buffer_add_str(name, "FeatureTypeList"); if (wr->sections) { if (in_list(wr->sections, name) || buffer_case_cmp(wr->sections->first->value, "all")) wfs_feature_type_list(o); } else wfs_feature_type_list(o); /* No ServesGMLObjectType list Section since there isn't any supported GML Object types not derived from gml:AbstractFeatureType */ /* SupportsGMLObjectType list Section : defines the list of GML Object types that the WFS server would be capable of serving */ buffer_empty(name); buffer_add_str(name, "SupportsGMLObjectTypeList"); if (wr->sections) { if (in_list(wr->sections, name) || buffer_case_cmp(wr->sections->first->value, "all")) wfs_gml_object_type_list(o); } else wfs_gml_object_type_list(o); /* Filter Capabilities Section : describe what specific filter capabilties are supported by the wfs */ fe_filter_capabilities_110(o); fprintf(o->output, "</WFS_Capabilities>\n"); fclose(o->output); buffer_free(name); }
/* * Transform a GML geometry to PostGIS EWKT * Return NULL on error */ buffer * ows_psql_gml_to_sql(ows * o, xmlNodePtr n, int srid) { PGresult *res; xmlNodePtr g; buffer *result, *sql, *gml; assert(o); assert(n); g = ows_psql_recursive_parse_gml(o, n, NULL); if (!g) return NULL; /* No Geometry founded in GML doc */ /* Retrieve the sub doc and launch GML parse via PostGIS */ gml = buffer_init(); cgi_add_xml_into_buffer(gml, g); sql = buffer_init(); buffer_add_str(sql, "SELECT ST_GeomFromGML('"); buffer_add_str(sql, gml->buf); if (ows_version_get(o->postgis_version) >= 200) { buffer_add_str(sql, "',"); buffer_add_int(sql, srid); buffer_add_str(sql, ")"); } else { /* Means PostGIS 1.5 */ buffer_add_str(sql, "')"); } res = ows_psql_exec(o, sql->buf); buffer_free(gml); /* GML Parse errors cases */ if (PQresultStatus(res) != PGRES_TUPLES_OK || PQntuples(res) != 1) { buffer_free(sql); PQclear(res); return NULL; } result = buffer_init(); buffer_add_str(result, PQgetvalue(res, 0, 0)); PQclear(res); /* Check if geometry is valid */ if (o->check_valid_geom) { buffer_empty(sql); buffer_add_str(sql, "SELECT ST_IsValid('"); buffer_add_str(sql, result->buf); buffer_add_str(sql, "')"); res = ows_psql_exec(o, sql->buf); if ( PQresultStatus(res) != PGRES_TUPLES_OK || PQntuples(res) != 1 || (char) PQgetvalue(res, 0, 0)[0] != 't') { buffer_free(sql); buffer_free(result); PQclear(res); return NULL; } PQclear(res); } buffer_free(sql); return result; }
int main(void) { SystemCoreClockUpdate(); uint32_t i; callback = data_recv_callback; iox_led_init(); timer_init(); uart_init(31250, callback); for (i = 0; i < TBUF_SIZE; i++) { timer[i] = 0; } head = 0; tail = 0; headt = 0; tailt = 0; n = 0; light = true; iox_led_on(false, light, false, false); while (1) { #ifdef TESTING timer_delay(10); // wait 1s midi_on(1, n, 90); light = !light; n > 127 ? n = 0 : n; iox_led_on(true, light, false, false); timer_delay(5); // wait 0.5s midi_off(1, n++, 90); #endif #ifdef GHDRUMS /* * If full command received, send ON data and * store timer. */ if (n >= 3) { if (!buffer_empty()) { midi_on(0, data[(tail + 1)], data[(tail + 2)]); timer[headt++] = timer_get() + 5; headt %= TBUF_SIZE; light = !light; iox_led_on(false, false, false, light); n -= 3; } } /* * If time has passed, send OFF command. */ if (!tbuffer_empty()) { if (timer[tailt] > timer_get()) { if (!buffer_empty()) { midi_off(0, data[(tail + 1)], data[(tail + 2)]); tail = (tail + MIDI_CMD_LEN) % BUF_SIZE; tailt = (tailt + 1) % TBUF_SIZE; } } } #endif } return 0; }
void cs_do(CSSession *cs) { /* Codec session should always be protected by call mutex so no need to check for cs validity */ if (!cs) return; Payload *p; int rc; int success = 0; pthread_mutex_lock(cs->queue_mutex); RTPMessage *msg; while ((msg = jbuf_read(cs->j_buf, &success)) || success == 2) { pthread_mutex_unlock(cs->queue_mutex); uint16_t fsize = ((cs->audio_decoder_sample_rate * cs->audio_decoder_frame_duration) / 1000); int16_t tmp[fsize * cs->audio_decoder_channels]; if (success == 2) { rc = opus_decode(cs->audio_decoder, 0, 0, tmp, fsize, 1); } else { rc = opus_decode(cs->audio_decoder, msg->data, msg->length, tmp, fsize, 0); rtp_free_msg(NULL, msg); } if (rc < 0) { LOGGER_WARNING("Decoding error: %s", opus_strerror(rc)); } else if (cs->acb.first) { /* Play */ cs->acb.first(cs->agent, cs->call_idx, tmp, rc, cs->acb.second); } pthread_mutex_lock(cs->queue_mutex); } if (cs->vbuf_raw && !buffer_empty(cs->vbuf_raw)) { /* Decode video */ buffer_read(cs->vbuf_raw, &p); /* Leave space for (possibly) other thread to queue more data after we read it here */ pthread_mutex_unlock(cs->queue_mutex); rc = vpx_codec_decode(&cs->v_decoder, p->data, p->size, NULL, MAX_DECODE_TIME_US); free(p); if (rc != VPX_CODEC_OK) { LOGGER_ERROR("Error decoding video: %s", vpx_codec_err_to_string(rc)); } else { vpx_codec_iter_t iter = NULL; vpx_image_t *dest = vpx_codec_get_frame(&cs->v_decoder, &iter); /* Play decoded images */ for (; dest; dest = vpx_codec_get_frame(&cs->v_decoder, &iter)) { if (cs->vcb.first) cs->vcb.first(cs->agent, cs->call_idx, dest, cs->vcb.second); vpx_img_free(dest); } } return; } pthread_mutex_unlock(cs->queue_mutex); }
static void sensorServer() { char com1Name[] = IOSERVERCOM1_NAME; int com1 = WhoIs(com1Name); char sensorName[] = SENSOR_NAME; RegisterAs(sensorName); int i, j; CURR_SENSOR_BOX = 0; CURR_HIGH_BITS = 0; responseIndex = 0; for (i = 0; i < NUM_SENSOR_BOX; ++i) { for (j = 0; j < 16; ++j) { SENSOR_VALUE[i][j] = 0; } } subscriberIndex = 0; subscriberUpdateIndex = 0; sensorBufferHead = 0; sensorBufferTail = 0; int queryWorker = Create(7, sensorQueryWorker); Create(8, sensorQueryResponseWorker); int queryTimeoutWorker = Create(7, sensorQueryTimeoutWorker); int queryResponseTimeoutWorker = Create(7, sensorQueryResponseTimeoutWorker); int courier = Create(7, sensorCourier); int queryWorkerReady = 0; int queryTimeout = 0; int queryResponseTimeout = 0; int startQueryResponseTimeout = 0; int courierReady = 0; char timerName[] = TIMESERVER_NAME; int timer = WhoIs(timerName); IGNORE_RESULT = 1; // sensor server is time sensitive, it delays and tries // to avoid the initialization period where there are // a lot of chars in com1 buffer Delay(700, timer); // Clear sensor memory after reading. Putc(com1, 192); // end init for ( ;; ) { if (queryTimeout && queryWorkerReady) { queryTimeout = 0; queryWorkerReady = 0; Reply(queryWorker, (char *)NULL, 0); Reply(queryTimeoutWorker, (char *)NULL, 0); } int tid = -1; SensorMsg msg; Receive(&tid, (char*)&msg, sizeof(SensorMsg)); switch (msg.type) { case QUERY_WORKER: { queryWorkerReady = 1; break; } case QUERY_RESPONSE_WORKER: { Reply(tid, (char *)NULL, 0); char response = msg.data; if (responseIndex == 0) { if (queryResponseTimeout) { queryResponseTimeout = 0; Reply(queryResponseTimeoutWorker, (char *)NULL, 0); } else { startQueryResponseTimeout = 1; } } responseBuffer[responseIndex++] = response; if (responseIndex == 10) { for (int i = 0; i < 10; i++) { sensorResponded(responseBuffer[i], msg.time); } responseIndex = 0; } break; } case QUERY_TIMEOUT_WORKER: { queryTimeout = 1; break; } case QUERY_RESPONSE_TIMEOUT_WORKER: { if (startQueryResponseTimeout) { startQueryResponseTimeout = 0; Reply(queryResponseTimeoutWorker, (char *)NULL, 0); } else { queryResponseTimeout = 1; responseIndex = 0; CURR_SENSOR_BOX = 0; CURR_HIGH_BITS = 0; } break; } case QUERY_RECENT: { sensorSubscriber[subscriberIndex++] = tid; Reply(tid, (char *)NULL, 0); break; } case SENSOR_COURIER: { courierReady = 1; break; } case FAKE_TRIGGER: { Reply(tid, (char *)NULL, 0); Sensor s; s.box = msg.box; s.val = msg.data; s.time = msg.time; add_to_buffer(s); break; } default: { ASSERT(FALSE, "invalid sensor msg type."); } } if (courierReady && !buffer_empty() && subscriberIndex != 0) { Sensor s = sensorBuffer[sensorBufferTail]; SensorWorkUnit work; work.sensor = s; work.tid = sensorSubscriber[subscriberUpdateIndex++]; Reply(courier, (char *)&work, sizeof(SensorWorkUnit)); if (subscriberUpdateIndex == subscriberIndex) { subscriberUpdateIndex = 0; remove_from_buffer(); } } } }
/* * Retrieve pkey column of a table related a given layer * And if success try also to retrieve a related pkey sequence */ static void ows_storage_fill_pkey(ows * o, ows_layer * l) { buffer *sql; PGresult *res; assert(o); assert(l); assert(l->storage); sql = buffer_init(); buffer_add_str(sql, "SELECT c.column_name FROM information_schema.constraint_column_usage c, pg_namespace n "); buffer_add_str(sql, "WHERE n.nspname = '"); buffer_copy(sql, l->storage->schema); buffer_add_str(sql, "' AND c.table_name = '"); buffer_copy(sql, l->storage->table); buffer_add_str(sql, "' AND c.constraint_name = ("); buffer_add_str(sql, "SELECT c.conname FROM pg_class r, pg_constraint c, pg_namespace n "); buffer_add_str(sql, "WHERE r.oid = c.conrelid AND relname = '"); buffer_copy(sql, l->storage->table); buffer_add_str(sql, "' AND r.relnamespace = n.oid AND n.nspname = '"); buffer_copy(sql, l->storage->schema); buffer_add_str(sql, "' AND c.contype = 'p')"); res = ows_psql_exec(o, sql->buf); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); buffer_free(sql); ows_error(o, OWS_ERROR_REQUEST_SQL_FAILED, "Unable to access pg_* tables.", "pkey column"); return; } /* Layer could have no Pkey indeed... (An SQL view for example) */ if (l->pkey || PQntuples(res) == 1) { l->storage->pkey = buffer_init(); if (l->pkey) { /*TODO check the column (l->pkey) in the table */ buffer_copy(l->storage->pkey, l->pkey); } else { buffer_add_str(l->storage->pkey, PQgetvalue(res, 0, 0)); } buffer_empty(sql); PQclear(res); /* Retrieve the Pkey column number */ buffer_add_str(sql, "SELECT a.attnum FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n"); buffer_add_str(sql, " WHERE a.attrelid = c.oid AND a.atttypid = t.oid AND n.nspname='"); buffer_copy(sql, l->storage->schema); buffer_add_str(sql, "' AND c.relname='"); buffer_copy(sql, l->storage->table); buffer_add_str(sql, "' AND a.attname='"); buffer_copy(sql, l->storage->pkey); buffer_add_str(sql, "'"); res = ows_psql_exec(o, sql->buf); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); buffer_free(sql); ows_error(o, OWS_ERROR_REQUEST_SQL_FAILED, "Unable to find pkey column number.", "pkey_column number"); return; } /* -1 because column number start at 1 */ l->storage->pkey_column_number = atoi(PQgetvalue(res, 0, 0)) - 1; buffer_empty(sql); PQclear(res); /* Now try to find a sequence related to this Pkey */ buffer_add_str(sql, "SELECT pg_get_serial_sequence('"); buffer_copy(sql, l->storage->schema); buffer_add_str(sql, ".\""); buffer_copy(sql, l->storage->table); buffer_add_str(sql, "\"', '"); buffer_copy(sql, l->storage->pkey); buffer_add_str(sql, "');"); res = ows_psql_exec(o, sql->buf); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); buffer_free(sql); ows_error(o, OWS_ERROR_REQUEST_SQL_FAILED, "Unable to use pg_get_serial_sequence.", "pkey_sequence retrieve"); return; } /* Even if no sequence found, this function return an empty row * so we must check that result string returned > 0 char */ if (PQntuples(res) == 1 && strlen((char *) PQgetvalue(res, 0, 0)) > 0) { l->storage->pkey_sequence = buffer_init(); buffer_add_str(l->storage->pkey_sequence, PQgetvalue(res, 0, 0)); } buffer_empty(sql); PQclear(res); /* Now try to find a DEFAULT value related to this Pkey */ buffer_add_str(sql, "SELECT column_default FROM information_schema.columns WHERE table_schema = '"); buffer_copy(sql, l->storage->schema); buffer_add_str(sql, "' AND table_name = '"); buffer_copy(sql, l->storage->table); buffer_add_str(sql, "' AND column_name = '"); buffer_copy(sql, l->storage->pkey); buffer_add_str(sql, "' AND table_catalog = current_database();"); res = ows_psql_exec(o, sql->buf); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); buffer_free(sql); ows_error(o, OWS_ERROR_REQUEST_SQL_FAILED, "Unable to SELECT column_default FROM information_schema.columns.", "pkey_default retrieve"); return; } /* Even if no DEFAULT value found, this function return an empty row * so we must check that result string returned > 0 char */ if (PQntuples(res) == 1 && strlen((char *) PQgetvalue(res, 0, 0)) > 0) { l->storage->pkey_default = buffer_init(); buffer_add_str(l->storage->pkey_default, PQgetvalue(res, 0, 0)); } } PQclear(res); buffer_free(sql); }
int main(int argc, char** argv) { int i,r; int rbuf[20]; int data; int format; processor_init(); uart1_init(); uart2_init(); TRISDbits.TRISD0 = 0; TRISBbits.TRISB12 = 0; TRISBbits.TRISB11 = 0; TRISBbits.TRISB0 = 1; TRISBbits.TRISB1 = 1; TRISBbits.TRISB2 = 1; ADPCFGbits.PCFG0 = 1; ADPCFGbits.PCFG1 = 1; ADPCFGbits.PCFG2 = 1; ledstatus = 0; cb = buffer_init(); while(1) { if ( buffer_full(cb) ) /* Signal buffer overflow */ PORTDbits.RD0 = 1; if ( !buffer_empty(cb) ) { int data; /* Get a 'char' from the buffer */ buffer_read(cb, &data); if ( data & 0x0100 ) { format = (~PORTB) & 0x3; /* Print the last sentence and begin reading the new one */ PORTBbits.RB12 = 1; //transmit_raw_buffer(rbuf, r); process_seatalk_string(rbuf, r, format); PORTBbits.RB12 = 0; r = 0; rbuf[r++] = data; } else { /* Accumulate data into the buffer */ //printf("rx: %x\n",data); rbuf[r++] = data; } } } return (EXIT_SUCCESS); }
void cis_run (void) { int temp_int = 0, temp_int2 = 0; int i = 0, r, w; int eventcount = 0; connection *read_events[__MAXFDS__]; connection *write_events[__MAXFDS__]; fifo_root *global_recvq = NULL; linklist_iter *reaper_iter = NULL; connection *temp = NULL; char *line; int patience = 250; reactor_running = true; global_recvq = fifo_create(); /* main loop */ for(;reactor_running;) { /** Grab some socket events to play with */ eventcount = socketengine->wait(read_events, write_events, patience); r = w = 0; /** Run through the existing connections looking for data to read */ for(i = 0; (r+w) < eventcount; i++) { if (read_events[i] != NULL) { r++; temp_int = read_events[i]->recvq->queue_size; conn_read_to_recvq(read_events[i]); if ((read_events[i]->recvq->queue_size > temp_int) && ((equal_fairness == 0) || (temp_int == 0))) fifo_add(global_recvq, read_events[i]); /* Don't wait for data! too much to do! */ patience = 0; } if (write_events[i] != NULL) { w++; if (write_events[i]->state.connecting == 1) { assert(getsockopt(write_events[i]->fd, SOL_SOCKET, SO_ERROR, &temp_int, &temp_int2) == 0); if (temp_int == 0) { write_events[i]->connected(write_events[i]); write_events[i]->state.connecting = 0; } else { write_events[i]->connect_failed(write_events[i], temp_int); write_events[i]->state.remote_closed = 1; write_events[i]->state.local_read_shutdown = 1; write_events[i]->state.local_write_shutdown = 1; socketengine->del(write_events[i]); cis_reap_connection(write_events[i]); } } else conn_send_from_sendq(write_events[i]); } } // foreach (event) /** Process some of the readq */ if (global_recvq->members > 0) { for (i = 0; i <= 20; i++) { temp = fifo_pop(global_recvq); if (temp == NULL) { /* We seem to be out of connections to process... Have more patience waiting for new data ...*/ patience = 250; break; } if ((temp->state.local_read_shutdown == 0)&&(temp->recvq->queue_size > 0)) { /* Local dead connections don't get processed ... remote dead ones -do- (since they died after sending this...) */ if (temp->callback_read) temp->callback_read(temp); else buffer_empty(temp->recvq); /* If it doesn't have any more messages left, nuke it from the queue... */ if (temp->recvq->queue_size == 0) fifo_del(global_recvq, temp); else { if (equal_fairness == 1) { fifo_del(global_recvq, temp); fifo_add(global_recvq, temp); } else { /* We shove it back on the end of the queue, * just in case there are insufficent instances to cover the buffer content. * * While this behaviour won't break the code it isn't true first come first served, * and it will have a performance impact. * * TODO: It would be nice to have an alternative ... * possibly making conn_read_to_recvq return a line count to allow multiple additions */ fifo_add(global_recvq, temp); } } if (global_recvq->members == 0) { patience = 250; /* Nothing to do, so I don't mind wait a while */ } break; } else { /* So this is either locally dead, or has no recvq ... both could happen, but ignore it either way */ if (temp->recvq->queue_size > 0) { /* Must be locally dead but with a recvq still ... this shouldn't be possible? */ buffer_empty(temp->recvq); } /* In any case, if we're ignoring it, might as well remove it completely ... */ fifo_del(global_recvq, temp); /* Since we didn't do much with this one, we'll try another pass... */ i--; } } } /** Attempt to reap connections... */ reaper_iter = linklist_iter_create(reaper_list); while (temp = linklist_iter_next(reaper_iter)) { /* Has this connection reached the end of it's life? */ if (((temp->state.remote_closed == 1) && (temp->recvq->queue_size == 0)) || (temp->state.local_read_shutdown == 1) && (temp->sendq->queue_size == 0)) { /* Remove it from any relevant queues... */ linklist_iter_del(reaper_iter); fifo_del(global_recvq,temp); /* Make sure it's all closed down... */ temp->state.local_write_shutdown = 1; temp->close(temp); /* Free the important stuff.... */ if (temp->recvq) buffer_free(temp->recvq); if (temp->sendq) buffer_free(temp->sendq); sfree(temp); } } linklist_iter_free(reaper_iter); timers_process(); } return; }
/* Flush all buffer to the fd. */ int buffer_flush_vty_all (struct buffer *b, int fd, int erase_flag, int no_more_flag) { int nbytes; int iov_index; struct iovec *iov; struct iovec small_iov[3]; char more[] = " --More-- "; char erase[] = { 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08}; struct buffer_data *data; struct buffer_data *out; struct buffer_data *next; /* For erase and more data add two to b's buffer_data count.*/ if (b->alloc == 1) iov = small_iov; else iov = XCALLOC (MTYPE_TMP, sizeof (struct iovec) * (b->alloc + 2)); data = b->head; iov_index = 0; /* Previously print out is performed. */ if (erase_flag) { iov[iov_index].iov_base = erase; iov[iov_index].iov_len = sizeof erase; iov_index++; } /* Output data. */ for (data = b->head; data; data = data->next) { iov[iov_index].iov_base = (char *)(data->data + data->sp); iov[iov_index].iov_len = data->cp - data->sp; iov_index++; } /* In case of `more' display need. */ if (! buffer_empty (b) && !no_more_flag) { iov[iov_index].iov_base = more; iov[iov_index].iov_len = sizeof more; iov_index++; } /* We use write or writev*/ nbytes = writev (fd, iov, iov_index); /* Error treatment. */ if (nbytes < 0) { if (errno == EINTR) ; if (errno == EWOULDBLOCK) ; } /* Free printed buffer data. */ for (out = b->head; out && out != data; out = next) { next = out->next; if (next) next->prev = NULL; else b->tail = next; b->head = next; buffer_data_free (out); b->alloc--; } if (iov != small_iov) XFREE (MTYPE_TMP, iov); return nbytes; }
/* Flush buffer to the file descriptor. Mainly used from vty interface. */ int buffer_flush_vty (struct buffer *b, int fd, int size, int erase_flag, int no_more_flag) { int nbytes; int iov_index; struct iovec *iov; struct iovec small_iov[3]; char more[] = " --More-- "; char erase[] = { 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08}; struct buffer_data *data; struct buffer_data *out; struct buffer_data *next; #ifdef IOV_MAX int iov_size; int total_size; struct iovec *c_iov; int c_nbytes; #endif /* IOV_MAX */ /* For erase and more data add two to b's buffer_data count.*/ if (b->alloc == 1) iov = small_iov; else iov = XCALLOC (MTYPE_TMP, sizeof (struct iovec) * (b->alloc + 2)); data = b->head; iov_index = 0; /* Previously print out is performed. */ if (erase_flag) { iov[iov_index].iov_base = erase; iov[iov_index].iov_len = sizeof erase; iov_index++; } /* Output data. */ for (data = b->head; data; data = data->next) { iov[iov_index].iov_base = (char *)(data->data + data->sp); if (size <= (data->cp - data->sp)) { iov[iov_index++].iov_len = size; data->sp += size; if (data->sp == data->cp) data = data->next; break; } else { iov[iov_index++].iov_len = data->cp - data->sp; size -= (data->cp - data->sp); data->sp = data->cp; } } /* In case of `more' display need. */ if (!buffer_empty (b) && !no_more_flag) { iov[iov_index].iov_base = more; iov[iov_index].iov_len = sizeof more; iov_index++; } /* We use write or writev*/ #ifdef IOV_MAX /* IOV_MAX are normally defined in <sys/uio.h> , Posix.1g. example: Solaris2.6 are defined IOV_MAX size at 16. */ c_iov = iov; total_size = iov_index; nbytes = 0; while( total_size > 0 ) { /* initialize write vector size at once */ iov_size = ( total_size > IOV_MAX ) ? IOV_MAX : total_size; c_nbytes = writev (fd, c_iov, iov_size ); if( c_nbytes < 0 ) { if(errno == EINTR) ; ; if(errno == EWOULDBLOCK) ; ; nbytes = c_nbytes; break; } nbytes += c_nbytes; /* move pointer io-vector */ c_iov += iov_size; total_size -= iov_size; } #else /* IOV_MAX */ nbytes = writev (fd, iov, iov_index); /* Error treatment. */ if (nbytes < 0) { if (errno == EINTR) ; if (errno == EWOULDBLOCK) ; } #endif /* IOV_MAX */ /* Free printed buffer data. */ for (out = b->head; out && out != data; out = next) { next = out->next; if (next) next->prev = NULL; else b->tail = next; b->head = next; buffer_data_free (out); b->alloc--; } if (iov != small_iov) XFREE (MTYPE_TMP, iov); return nbytes; }
/* * Retrieve columns name and type of a table related a given layer */ static void ows_storage_fill_attributes(ows * o, ows_layer * l) { buffer *sql; PGresult *res; buffer *b, *t; int i, end; list_node *ln; assert(o); assert(l); assert(l->storage); sql = buffer_init(); buffer_add_str(sql, "SELECT a.attname AS field, t.typname AS type "); buffer_add_str(sql, "FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n WHERE n.nspname = '"); buffer_copy(sql, l->storage->schema); buffer_add_str(sql, "' AND c.relname = '"); buffer_copy(sql, l->storage->table); buffer_add_str(sql, "' AND c.relnamespace = n.oid AND a.attrelid = c.oid AND a.atttypid = t.oid"); if (l->include_items) { buffer_add_str(sql, " AND a.attname IN ("); for (ln = l->include_items->first ; ln ; ln = ln->next) { buffer_add_str(sql, "'"); buffer_copy(sql, ln->value); buffer_add_str(sql, "', "); } if (l->include_items->first && l->storage->pkey) { buffer_add_str(sql, "'"); buffer_copy(sql, l->storage->pkey ); buffer_add_str(sql, "',"); } buffer_add_str(sql, " '');"); } else { buffer_add_str(sql, " AND a.attnum > 0;"); } res = ows_psql_exec(o, sql->buf); buffer_free(sql); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); ows_error(o, OWS_ERROR_REQUEST_SQL_FAILED, "Unable to access pg_* tables.", "fill_attributes"); return; } for (i = 0, end = PQntuples(res); i < end; i++) { b = buffer_init(); t = buffer_init(); buffer_add_str(b, PQgetvalue(res, i, 0)); buffer_add_str(t, PQgetvalue(res, i, 1)); /* If the column is a geometry, get its real geometry type */ if (buffer_cmp(t, "geometry")) { PGresult *geom_res; buffer *geom_sql = buffer_init(); buffer_add_str(geom_sql, "SELECT type from geometry_columns where f_table_schema='"); buffer_copy(geom_sql, l->storage->schema); buffer_add_str(geom_sql,"' and f_table_name='"); buffer_copy(geom_sql, l->storage->table); buffer_add_str(geom_sql,"' and f_geometry_column='"); buffer_copy(geom_sql, b); buffer_add_str(geom_sql,"';"); geom_res = ows_psql_exec(o, geom_sql->buf); buffer_free(geom_sql); if (PQresultStatus(geom_res) != PGRES_TUPLES_OK || PQntuples(geom_res) == 0) { PQclear(res); PQclear(geom_res); ows_error(o, OWS_ERROR_REQUEST_SQL_FAILED, "Unable to access geometry_columns table, try Populate_Geometry_Columns()", "fill_attributes"); return; } buffer_empty(t); buffer_add_str(t, PQgetvalue(geom_res, 0, 0)); PQclear(geom_res); } array_add(l->storage->attributes, b, t); } PQclear(res); }
/* Receive up to <count> bytes from connection <conn>'s socket and store them * into buffer <buf>. Only one call to recv() is performed, unless the * buffer wraps, in which case a second call may be performed. The connection's * flags are updated with whatever special event is detected (error, read0, * empty). The caller is responsible for taking care of those events and * avoiding the call if inappropriate. The function does not call the * connection's polling update function, so the caller is responsible for this. * errno is cleared before starting so that the caller knows that if it spots an * error without errno, it's pending and can be retrieved via getsockopt(SO_ERROR). */ static int raw_sock_to_buf(struct connection *conn, struct buffer *buf, int count) { int ret, done = 0; int try; if (!conn_ctrl_ready(conn)) return 0; if (!fd_recv_ready(conn->t.sock.fd)) return 0; errno = 0; if (unlikely(!(fdtab[conn->t.sock.fd].ev & FD_POLL_IN))) { /* stop here if we reached the end of data */ if ((fdtab[conn->t.sock.fd].ev & (FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_HUP) goto read0; /* report error on POLL_ERR before connection establishment */ if ((fdtab[conn->t.sock.fd].ev & FD_POLL_ERR) && (conn->flags & CO_FL_WAIT_L4_CONN)) { conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH; return done; } } /* let's realign the buffer to optimize I/O */ if (buffer_empty(buf)) buf->p = buf->data; /* read the largest possible block. For this, we perform only one call * to recv() unless the buffer wraps and we exactly fill the first hunk, * in which case we accept to do it once again. A new attempt is made on * EINTR too. */ while (count > 0) { /* first check if we have some room after p+i */ try = buf->data + buf->size - (buf->p + buf->i); /* otherwise continue between data and p-o */ if (try <= 0) { try = buf->p - (buf->data + buf->o); if (try <= 0) break; } if (try > count) try = count; ret = recv(conn->t.sock.fd, bi_end(buf), try, 0); if (ret > 0) { buf->i += ret; done += ret; if (ret < try) { /* unfortunately, on level-triggered events, POLL_HUP * is generally delivered AFTER the system buffer is * empty, so this one might never match. */ if (fdtab[conn->t.sock.fd].ev & FD_POLL_HUP) goto read0; fd_done_recv(conn->t.sock.fd); break; } count -= ret; } else if (ret == 0) { goto read0; } else if (errno == EAGAIN) { fd_cant_recv(conn->t.sock.fd); break; } else if (errno != EINTR) { conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH; break; } }
int CAN_buffer_empty(can_stream_data_t *data) { return buffer_empty(&data->byte_buffer); }
static void ows_layer_storage_fill(ows * o, ows_layer * l, bool is_geom) { buffer * sql; PGresult *res; int i, end; assert(o); assert(l); assert(l->storage); sql = buffer_init(); if (is_geom) buffer_add_str(sql, "SELECT srid, f_geometry_column FROM geometry_columns"); else buffer_add_str(sql, "SELECT srid, f_geography_column FROM geography_columns"); buffer_add_str(sql, " WHERE f_table_schema='"); buffer_copy(sql, l->storage->schema); buffer_add_str(sql, "' AND f_table_name='"); buffer_copy(sql, l->storage->table); buffer_add_str(sql, "'"); if (l->include_items) { buffer_add_str(sql, is_geom?" AND f_geometry_column IN ('":" AND f_geography_column IN ('"); list_implode(sql, "','", l->include_items); buffer_add_str(sql, "')"); } if (l->exclude_items) { buffer_add_str(sql, is_geom?" AND f_geometry_column NOT IN ('":" AND f_geography_column NOT IN ('"); list_implode(sql, "','", l->exclude_items); buffer_add_str(sql, "')"); } buffer_add_str(sql, ";"); res = ows_psql_exec(o, sql->buf); buffer_empty(sql); if (PQresultStatus(res) != PGRES_TUPLES_OK || PQntuples(res) == 0) { PQclear(res); ows_error(o, OWS_ERROR_REQUEST_SQL_FAILED, "All config file layers are not availables in geometry_columns or geography_columns", "storage"); return; } l->storage->srid = atoi(PQgetvalue(res, 0, 0)); for (i = 0, end = PQntuples(res); i < end; i++) list_add_str(l->storage->geom_columns, PQgetvalue(res, i, 1)); buffer_add_str(sql, "SELECT * FROM spatial_ref_sys WHERE srid="); buffer_add_str(sql, PQgetvalue(res, 0, 0)); buffer_add_str(sql, " AND proj4text like '%%units=m%%'"); PQclear(res); res = ows_psql_exec(o, sql->buf); buffer_free(sql); if (PQntuples(res) != 1) l->storage->is_degree = true; else l->storage->is_degree = false; PQclear(res); ows_storage_fill_pkey(o, l); ows_storage_fill_attributes(o, l); ows_storage_fill_not_null(o, l); }
u8 tty_rx_empty(void) { return buffer_empty(&u1rx); }