int database_add_orphan_transaction(struct database* db, unsigned char const* hash, struct transaction const* tx) { mongoc_collection_t* collection = mongoc_client_get_collection(db->client, database_name(db), "transactions"); // Convert the transaction to a bson document bson_t* doc = bson_new(); transaction_bson(tx, doc); // Set the hash BSON_APPEND_BINARY(doc, "hash", BSON_SUBTYPE_BINARY, (uint8_t*)hash, 32); // Give it a new id bson_oid_t oid; bson_oid_init(&oid, NULL); BSON_APPEND_OID(doc, "_id", &oid); // Orphan -> height = -1 BSON_APPEND_INT32(doc, "height", -1); #if 0 // Print json char* str = bson_as_json(doc, NULL); printf("%s\n", str); bson_free(str); #endif // Perform insert bson_error_t error; if(mongoc_collection_insert(collection, MONGOC_INSERT_NONE, doc, NULL, &error) == 0) { printf("MongoDB error: %s\n", error.message); } bson_destroy(doc); mongoc_collection_destroy(collection); return 0; }
static void getaddressbyID(char *msg,mongoc_collection_t *coll,char * deviceId,char * device_name){ mongoc_cursor_t *cursor; bson_t *doc; bson_t *query; char *str; query = bson_new (); bson_oid_t de_oid; bson_oid_init_from_string(&de_oid, deviceId); BSON_APPEND_OID (query, "_id",&de_oid); cursor = mongoc_collection_find (coll, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL); double ivalue=0; int buse=0; double lat; double lon; //char lat[256]; //char lon[256]; //memset(lat,'\0',256); //memset(lon,'\0',256); while (mongoc_cursor_next (cursor, &doc)) { str = bson_as_json (doc, NULL); //printf ("%s\n", str); bson_free (str); bson_iter_t iter; bson_iter_t sub_iter; if (bson_iter_init (&iter, doc)) { while (bson_iter_next (&iter)) { //printf ("Found a field named: %s\n", bson_iter_key (&iter)); bson_value_t *value; value = bson_iter_value (&iter); //printf("type %d\n",value->value_type); if (value->value_type == BSON_TYPE_DOUBLE) { if(strcmp(bson_iter_key (&iter),"lat")==0){ (lat=value->value.v_double); } if(strcmp(bson_iter_key (&iter),"lon")==0){ (lon=value->value.v_double); } } if (value->value_type == BSON_TYPE_UTF8) { if(strcmp(bson_iter_key (&iter),"device_name")==0){ strcpy(device_name,value->value.v_utf8.str); } } } } } bson_destroy (query); CURL *curl; CURLcode res; curl = curl_easy_init(); if (curl) { static char str[20480]; memset(str,'\0',20480); char url[1028]; memset(url,'\0',1028); sprintf(url,"http://api.map.baidu.com/geocoder/v2/?ak=IDvNBsejl9oqMbPF316iKsXR&output=json&location=%.8f,%.8f",lat,lon); printf("%s\n",url); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, str); res = curl_easy_perform(curl); printf("%s\n",str); char *s = strstr(str, "formatted_address"); if(NULL!=s){ s=strstr(s, "\""); s=strstr(s+1, "\""); printf("\n%s\n",s); char *p=strstr(s+1, "\""); int len=strlen(s)-strlen(p)-1; strncpy(msg,s+1,len); msg[len]='\0'; printf("msg:%s\n",msg); printf("\n\n"); } curl_easy_cleanup(curl); } }
static void do_alarm(mongoc_collection_t *sensorcoll,char * se_id,char * alarmType,char * upperBoundC,char *lowerBoundC, char *duration,char *target,char * contactId,char* addr,mongoc_collection_t *alarmlogcoll,char* userId,char *device_name,char * de_id){ mongoc_cursor_t *cursor; bson_t *doc; bson_t *query; char *str; query = bson_new (); bson_oid_t se_oid; bson_oid_init_from_string(&se_oid, se_id); BSON_APPEND_OID (query, "_id",&se_oid); cursor = mongoc_collection_find (sensorcoll, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL); double ivalue=0; double dalarmtime=0; int interval=0; int balarm=0; int buse=0; char name[1024]; memset(name,0,1024); while (mongoc_cursor_next (cursor, &doc)) { str = bson_as_json (doc, NULL); printf ("%s\n", str); bson_free (str); bson_iter_t iter; bson_iter_t sub_iter; if (bson_iter_init (&iter, doc)) { while (bson_iter_next (&iter)) { //printf ("Found a field named: %s\n", bson_iter_key (&iter)); bson_value_t *value; value = bson_iter_value (&iter); //printf("type %d\n",value->value_type); if (value->value_type == BSON_TYPE_INT32) { if(strcmp(bson_iter_key (&iter),"value")==0){ printf("value %d\n", value->value.v_int32); ivalue=value->value.v_double; buse =1; }else if(strcmp(bson_iter_key (&iter),"interval")==0){ interval=value->value.v_int32; }else if(strcmp(bson_iter_key (&iter),"balarm")==0){ balarm=value->value.v_int32; } } if(strcmp(bson_iter_key (&iter),"value")==0){ printf("value type %d,%d\n",value->value_type,BSON_TYPE_INT32); } if (value->value_type == BSON_TYPE_DOUBLE) { if(strcmp(bson_iter_key (&iter),"value")==0){ //printf("value %d\n", (int)value->value.v_double); buse =1; ivalue=value->value.v_double; } if(strcmp(bson_iter_key (&iter),"alarmtime")==0){ dalarmtime=value->value.v_double; } } if (value->value_type == BSON_TYPE_UTF8) { if(strcmp(bson_iter_key (&iter),"name")==0){ //printf("value %d\n", (int)value->value.v_double); strcpy(name,value->value.v_utf8.str); } if(strcmp(bson_iter_key (&iter),"value")==0){ //printf("value %d\n", (int)value->value.v_double); ivalue=atof(value->value.v_utf8.str); buse =1; } } } } } bson_destroy (query); printf("se_id:%s,buse:%d\n",se_id,buse); printf("alarmType:%s,%f : %s,%s",alarmType,ivalue,upperBoundC,lowerBoundC); time_t t; t = time(NULL); struct tm *lt; int ii = time(&t); int bdoalarm=1; if(balarm==1){ bdoalarm=1; if(dalarmtime>0 &&interval>0){ if((ii-dalarmtime)<3600){ bdoalarm=0; } } } if(buse ==1){ if(strcmp(alarmType,"val_above")==0){ int iupper=atoi(upperBoundC); if(iupper<ivalue){ printf("val_above %d value\n",iupper,ivalue); char msg[2048]; memset(msg,0,2048); snprintf(msg, sizeof(msg) - 1, "故障报警:%s的%s数值高于%d,位置是%s,请及时处理!", device_name, name, iupper, addr); char buf[1024]; URLEncodeGBK(msg, strlen(msg), buf,sizeof(buf)); printf("%s\n",buf); printf("alarm info: %s\n",msg); if(bdoalarm>0){ int code=sendsms_c(buf,contactId); saveAlarmLog(alarmlogcoll,se_id,code,contactId,msg,userId,device_name,name,de_id); updateAlarm(sensorcoll,se_id,interval+1,1); printf("send sms \n"); } }else { updateAlarm(sensorcoll,se_id,0,0); } }else if(strcmp(alarmType,"val_below")==0){ int iupper=atoi(lowerBoundC); if(iupper>ivalue){ printf("val_below %d value %d\n",iupper,ivalue); char msg[2048]; memset(msg,0,2048); snprintf(msg, sizeof(msg) - 1, "故障报警:%s的%s数值低于%d,位置是%s,请及时处理!", device_name, name, iupper, addr); char buf[1024]; URLEncodeGBK(msg, strlen(msg), buf,sizeof(buf)); printf("%s\n",buf); printf("alarm info: %s\n",msg); if(bdoalarm>0){ int code=sendsms_c(buf,contactId); saveAlarmLog(alarmlogcoll,se_id,code,contactId,msg,userId,device_name,name,de_id); updateAlarm(sensorcoll,se_id,interval+1,1); printf("send sms \n"); } }else { updateAlarm(sensorcoll,se_id,0,0); } }else if(strcmp(alarmType,"switch_on")==0){ if(ivalue==1){ char msg[2048]; memset(msg,0,2048); snprintf(msg, sizeof(msg) - 1, "故障报警:%s,%s,位置是%s,请及时处理!", device_name, name, addr); char buf[1024]; URLEncodeGBK(msg, strlen(msg), buf,sizeof(buf)); printf("%s\n",buf); printf("alarm info: %s\n",msg); if(bdoalarm>0){ int code=sendsms_c(buf,contactId); saveAlarmLog(alarmlogcoll,se_id,code,contactId,msg,userId,device_name,name,de_id); updateAlarm(sensorcoll,se_id,interval+1,1); printf("send sms \n"); } }else { updateAlarm(sensorcoll,se_id,0,0); } }else if(strcmp(alarmType,"offline")==0){ if(ivalue==1){ char msg[2048]; memset(msg,0,2048); snprintf(msg, sizeof(msg) - 1, "故障报警:%s,%s,位置是%s,请及时处理!", device_name, name, addr); char buf[1024]; URLEncodeGBK(msg, strlen(msg), buf,sizeof(buf)); printf("%s\n",buf); printf("alarm info: %s\n",msg); if(bdoalarm>0){ int code=sendsms_c(buf,contactId); saveAlarmLog(alarmlogcoll,se_id,code,contactId,msg,userId,device_name,name,de_id); updateAlarm(sensorcoll,se_id,interval+1,1); printf("send sms \n"); } }else { updateAlarm(sensorcoll,se_id,0,0); } } } }
static void test_split_insert (void) { mongoc_bulk_write_flags_t write_flags = MONGOC_BULK_WRITE_FLAGS_INIT; mongoc_write_command_t command; mongoc_write_result_t result; mongoc_collection_t *collection; mongoc_client_t *client; bson_oid_t oid; bson_t **docs; bson_t reply = BSON_INITIALIZER; bson_error_t error; mongoc_server_stream_t *server_stream; int i; bool r; client = test_framework_client_new (); assert (client); collection = get_test_collection (client, "test_split_insert"); assert (collection); docs = (bson_t **)bson_malloc (sizeof(bson_t*) * 3000); for (i = 0; i < 3000; i++) { docs [i] = bson_new (); bson_oid_init (&oid, NULL); BSON_APPEND_OID (docs [i], "_id", &oid); } _mongoc_write_result_init (&result); _mongoc_write_command_init_insert (&command, docs[0], write_flags, ++client->cluster.operation_id, true); for (i = 1; i < 3000; i++) { _mongoc_write_command_insert_append (&command, docs[i]); } server_stream = mongoc_cluster_stream_for_writes (&client->cluster, &error); ASSERT_OR_PRINT (server_stream, error); _mongoc_write_command_execute (&command, client, server_stream, collection->db, collection->collection, NULL, 0, &result); r = _mongoc_write_result_complete (&result, 2, collection->write_concern, &reply, &error); ASSERT_OR_PRINT (r, error); assert (result.nInserted == 3000); _mongoc_write_command_destroy (&command); _mongoc_write_result_destroy (&result); ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error); for (i = 0; i < 3000; i++) { bson_destroy (docs [i]); } bson_free (docs); mongoc_server_stream_cleanup (server_stream); mongoc_collection_destroy (collection); mongoc_client_destroy (client); }
void switch_value(lua_State *L, int index, bson_t* bson, int level, const char* key) { switch(lua_type(L, index)) { case LUA_TTABLE: { int is_a=is_array(L, index); if (is_a) { bson_t child; //start array BSON_APPEND_ARRAY_BEGIN(bson, key, &child); iterate_table(L, index, &child, 0, level+1, NULL); bson_append_array_end(bson, &child); } else { bson_t child; //start map BSON_APPEND_DOCUMENT_BEGIN(bson, key, &child); iterate_table(L, index, &child, 1, level+1, NULL); bson_append_document_end(bson, &child); } break; } case LUA_TNIL: { BSON_APPEND_NULL(bson, key); break; } case LUA_TNUMBER: { BSON_APPEND_DOUBLE(bson, key, lua_tonumber(L, index)); break; } case LUA_TBOOLEAN: { BSON_APPEND_BOOL(bson, key, lua_toboolean(L, index)); break; } case LUA_TSTRING: { BSON_APPEND_UTF8(bson, key, lua_tostring(L, index)); break; } case LUA_TUSERDATA: { // switch userdata type if (luaL_checkudata_ex(L, index, REGEX_METATABLE)) { cbson_regex_t* regex = check_cbson_regex(L, index); BSON_APPEND_REGEX (bson, key, regex->regex, regex->options); } else if (luaL_checkudata_ex(L, index, OID_METATABLE)) { cbson_oid_t* oid = check_cbson_oid(L, index); bson_oid_t boid; bson_oid_init_from_string (&boid, oid->oid); BSON_APPEND_OID (bson, key, &boid); } else if (luaL_checkudata_ex(L, index, BINARY_METATABLE)) { cbson_binary_t* bin = check_cbson_binary(L, index); size_t binary_len = b64_pton (bin->data, NULL, 0); unsigned char* buf=malloc(binary_len+1); b64_pton(bin->data, buf, binary_len+1); BSON_APPEND_BINARY(bson, key, bin->type, buf, binary_len); free(buf); } else if (luaL_checkudata_ex(L, index, SYMBOL_METATABLE)) { cbson_symbol_t* sym = check_cbson_symbol(L, index); BSON_APPEND_SYMBOL(bson, key, sym->symbol); } else if (luaL_checkudata_ex(L, index, REF_METATABLE)) { cbson_ref_t* ref = check_cbson_ref(L, index); bson_oid_t boid; bson_oid_init_from_string (&boid, ref->id); BSON_APPEND_DBPOINTER(bson, key, ref->ref, &boid); } else if (luaL_checkudata_ex(L, index, MINKEY_METATABLE)) { check_cbson_minkey(L, index); BSON_APPEND_MINKEY(bson, key); } else if (luaL_checkudata_ex(L, index, MAXKEY_METATABLE)) { check_cbson_maxkey(L, index); BSON_APPEND_MAXKEY(bson, key); } else if (luaL_checkudata_ex(L, index, TIMESTAMP_METATABLE)) { cbson_timestamp_t* time = check_cbson_timestamp(L, index); BSON_APPEND_TIMESTAMP(bson, key, time->timestamp, time->increment); } else if (luaL_checkudata_ex(L, index, INT64_METATABLE) || luaL_checkudata_ex(L, index, UINT64_METATABLE)) { cbson_int64_t i = cbson_int64_check(L, index); if (i < INT32_MIN || i > INT32_MAX) { BSON_APPEND_INT64(bson, key, i); } else { BSON_APPEND_INT32(bson, key, (int32_t)i); } } else if (luaL_checkudata_ex(L, index, CODE_METATABLE)) { cbson_code_t* code = check_cbson_code(L, index); BSON_APPEND_CODE(bson, key, code->code); } else if (luaL_checkudata_ex(L, index, CODEWSCOPE_METATABLE)) { cbson_codewscope_t* code = check_cbson_codewscope(L, index); BSON_APPEND_CODE_WITH_SCOPE(bson, key, code->code, NULL); } else if (luaL_checkudata_ex(L, index, UNDEFINED_METATABLE)) { check_cbson_undefined(L, index); BSON_APPEND_UNDEFINED(bson, key); } else if (luaL_checkudata_ex(L, index, DATE_METATABLE)) { BSON_APPEND_DATE_TIME(bson, key, cbson_date_check(L, index)); } break; } case LUA_TFUNCTION: case LUA_TTHREAD: case LUA_TLIGHTUSERDATA: default: break; // or bail out? } }
static void test_many_return (void) { mongoc_collection_t *collection; mongoc_client_t *client; mongoc_cursor_t *cursor; bson_error_t error; const bson_t *doc = NULL; bson_oid_t oid; bson_t query = BSON_INITIALIZER; bson_t **docs; size_t len; bool r; int i; client = mongoc_client_new (gTestUri); ASSERT (client); collection = get_test_collection (client, "test_many_return"); ASSERT (collection); docs = bson_malloc (sizeof(bson_t*) * 5000); for (i = 0; i < 5000; i++) { docs [i] = bson_new (); bson_oid_init (&oid, NULL); BSON_APPEND_OID (docs [i], "_id", &oid); } BEGIN_IGNORE_DEPRECATIONS; r = mongoc_collection_insert_bulk (collection, MONGOC_INSERT_NONE, (const bson_t **)docs, 5000, NULL, &error); END_IGNORE_DEPRECATIONS; assert (r); for (i = 0; i < 5000; i++) { bson_destroy (docs [i]); } bson_free (docs); cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 6000, &query, NULL, NULL); assert (cursor); bson_destroy (&query); i = 0; while (mongoc_cursor_next (cursor, &doc)) { assert (doc); i++; } assert (i == 5000); r = mongoc_cursor_next (cursor, &doc); assert (!r); mongoc_cursor_destroy (cursor); r = mongoc_collection_drop (collection, &error); assert (r); mongoc_collection_destroy (collection); mongoc_client_destroy (client); }
static int mongodb_log(struct ast_cdr *cdr) { int ret = -1; bson_t *doc = NULL; mongoc_collection_t *collection = NULL; if(dbpool == NULL) { ast_log(LOG_ERROR, "unexpected error, no connection pool\n"); return ret; } mongoc_client_t *dbclient = mongoc_client_pool_pop(dbpool); if(dbclient == NULL) { ast_log(LOG_ERROR, "unexpected error, no client allocated\n"); return ret; } do { bson_error_t error; doc = bson_new(); if(doc == NULL) { ast_log(LOG_ERROR, "cannot make a document\n"); break; } mongoc_collection_t *collection = mongoc_client_get_collection(dbclient, dbname, dbcollection); if(collection == NULL) { ast_log(LOG_ERROR, "cannot get such a collection, %s, %s\n", dbname, dbcollection); break; } BSON_APPEND_UTF8(doc, "clid", cdr->clid); BSON_APPEND_UTF8(doc, "src", cdr->src); BSON_APPEND_UTF8(doc, "dst", cdr->dst); BSON_APPEND_UTF8(doc, "dcontext", cdr->dcontext); BSON_APPEND_UTF8(doc, "channel", cdr->channel); BSON_APPEND_UTF8(doc, "dstchannel", cdr->dstchannel); BSON_APPEND_UTF8(doc, "lastapp", cdr->lastapp); BSON_APPEND_UTF8(doc, "lastdata", cdr->lastdata); BSON_APPEND_UTF8(doc, "disposition", ast_cdr_disp2str(cdr->disposition)); BSON_APPEND_UTF8(doc, "amaflags", ast_channel_amaflags2string(cdr->amaflags)); BSON_APPEND_UTF8(doc, "accountcode", cdr->accountcode); BSON_APPEND_UTF8(doc, "uniqueid", cdr->uniqueid); BSON_APPEND_UTF8(doc, "userfield", cdr->userfield); BSON_APPEND_UTF8(doc, "peeraccount", cdr->peeraccount); BSON_APPEND_UTF8(doc, "linkedid", cdr->linkedid); BSON_APPEND_INT32(doc, "duration", cdr->duration); BSON_APPEND_INT32(doc, "billsec", cdr->billsec); BSON_APPEND_INT32(doc, "sequence", cdr->sequence); BSON_APPEND_TIMEVAL(doc, "start", &cdr->start); BSON_APPEND_TIMEVAL(doc, "answer", &cdr->answer); BSON_APPEND_TIMEVAL(doc, "end", &cdr->end); if (serverid) BSON_APPEND_OID(doc, SERVERID, serverid); if(!mongoc_collection_insert(collection, MONGOC_INSERT_NONE, doc, NULL, &error)) ast_log(LOG_ERROR, "insertion failed, %s\n", error.message); ret = 0; // success } while(0); if (collection) mongoc_collection_destroy(collection); if (doc) bson_destroy(doc); mongoc_client_pool_push(dbpool, dbclient); return ret; }
static bool appendBsonValue(bson_t *bson, const QString &key, const QVariant &value) { const QLatin1String oidkey("_id"); bool ok = true; int type = value.type(); // _id if (key == oidkey) { QByteArray oidVal = value.toByteArray(); if (oidVal.length() == 24) { // ObjectId bson_oid_t oid; bson_oid_init_from_string(&oid, oidVal.data()); BSON_APPEND_OID(bson, oidkey.latin1(), &oid); } else { int id = value.toInt(&ok); if (ok) { BSON_APPEND_INT32(bson, oidkey.latin1(), id); } else { BSON_APPEND_UTF8(bson, oidkey.latin1(), value.toString().toUtf8().data()); } } return true; } switch (type) { case QVariant::Int: BSON_APPEND_INT32(bson, qPrintable(key), value.toInt(&ok)); break; case QVariant::String: BSON_APPEND_UTF8(bson, qPrintable(key), value.toString().toUtf8().data()); break; case QVariant::LongLong: BSON_APPEND_INT64(bson, qPrintable(key), value.toLongLong(&ok)); break; case QVariant::Map: BSON_APPEND_DOCUMENT(bson, qPrintable(key), (const bson_t *)TBson::toBson(value.toMap()).constData()); break; case QVariant::Double: BSON_APPEND_DOUBLE(bson, qPrintable(key), value.toDouble(&ok)); break; case QVariant::Bool: BSON_APPEND_BOOL(bson, qPrintable(key), value.toBool()); break; case QVariant::DateTime: { #if QT_VERSION >= 0x040700 BSON_APPEND_DATE_TIME(bson, qPrintable(key), value.toDateTime().toMSecsSinceEpoch()); #else QDateTime utcDate = value.toDateTime().toUTC(); qint64 ms = utcDate.time().msec(); qint64 tm = utcDate.toTime_t() * 1000LL; if (ms > 0) { tm += ms; } BSON_APPEND_DATE_TIME(bson, qPrintable(key), tm); #endif break; } case QVariant::ByteArray: { QByteArray ba = value.toByteArray(); BSON_APPEND_BINARY(bson, qPrintable(key), BSON_SUBTYPE_BINARY, (uint8_t *)ba.constData(), ba.length()); break; } case QVariant::List: // FALL THROUGH case QVariant::StringList: { bson_t child; BSON_APPEND_ARRAY_BEGIN(bson, qPrintable(key), &child); int i = 0; for (auto &var : value.toList()) { appendBsonValue(&child, QString::number(i++), var); } bson_append_array_end(bson, &child); break; } case QVariant::Invalid: BSON_APPEND_UNDEFINED(bson, qPrintable(key)); break; default: tError("toBson() failed to convert name:%s type:%d", qPrintable(key), type); ok = false; break; } return ok; }
/********************************************************************************************* F_SECUNDARIA: Creando un BSON del archivo, para insertalo en la DB TESTEADO =) ****************************/ bson_t * crearDocumentoParaLaDB(char * nombreDelArchivo, long tamanioDelArchivo, int dirPadreDelArchivo, t_dictionary * diccionarioDeBloques) //Va eliminando el diccionario que ingresa por parametro :D { bson_t child; bson_t child2; bson_t child3; bson_t child4; bson_oid_t oid; int cantidadTotalDeBloques; int identificadorDelBloque = 0; t_dictionary* copiasDelBloqueX; t_copiaX* copiaX; char * iDelBloque; //FIN DECLARACION DE VARIABLES bson_t * documento = bson_new(); // ::: Estructura BASICA del documento ::: bson_oid_init (&oid, NULL); BSON_APPEND_OID (documento, "_id", &oid); BSON_APPEND_UTF8 (documento, "nombreDelArchivo", nombreDelArchivo); BSON_APPEND_INT32 (documento, "tamanio", tamanioDelArchivo); BSON_APPEND_INT32 (documento, "dirPadre", dirPadreDelArchivo); BSON_APPEND_INT32 (documento, "estado", 1); cantidadTotalDeBloques = dictionary_size(diccionarioDeBloques); BSON_APPEND_INT32 (documento, "cantidadDeBloques", cantidadTotalDeBloques); // ::: Estructura de BLOQUES del documento ::: //Guardando los N bloques con copias 3 bson_append_document_begin (documento, "Bloques", 7, &child); while(identificadorDelBloque < cantidadTotalDeBloques) { iDelBloque = string_itoa(identificadorDelBloque); bson_append_document_begin (&child, iDelBloque, 1, &child2); copiasDelBloqueX = (t_dictionary*) dictionary_get( diccionarioDeBloques, iDelBloque ); //Guardando la cantidad de copias del bloque X BSON_APPEND_INT32 (&child2, "cantidadDeCopias", 3); //Guardando las 3 copias para el bloque X bson_append_array_begin (&child2, "copias", 6, &child4); copiaX = (t_copiaX*) dictionary_get( copiasDelBloqueX, "1" ); int Guachin= dictionary_size(copiasDelBloqueX); bson_append_document_begin (&child4, "0", 1, &child3); bson_append_int32(&child3,"IP", 2, (*copiaX).IP); bson_append_int32(&child3, "puerto", 6, (*copiaX).puerto); bson_append_int32(&child3, "numBloque", 9, (*copiaX).numBloque); bson_append_document_end (&child4, &child3); copiaX = (t_copiaX*) dictionary_get( copiasDelBloqueX, "2" ); bson_append_document_begin (&child4, "1", 1, &child3); bson_append_int32(&child3,"IP", 2, (*copiaX).IP); bson_append_int32(&child3, "puerto", 6, (*copiaX).puerto); bson_append_int32(&child3, "numBloque", 9, (*copiaX).numBloque); bson_append_document_end (&child4, &child3); copiaX = (t_copiaX*) dictionary_get( copiasDelBloqueX, "3" ); bson_append_document_begin (&child4, "2", 1, &child3); bson_append_int32(&child3,"IP", 2, (*copiaX).IP); bson_append_int32(&child3, "puerto", 6, (*copiaX).puerto); bson_append_int32(&child3, "numBloque", 9, (*copiaX).numBloque); bson_append_document_end (&child4, &child3); bson_append_array_end (&child2, &child4); dictionary_clean(copiasDelBloqueX); dictionary_destroy(copiasDelBloqueX); //Anido las 3 copias al bloque X bson_append_document_end (&child, &child2); free(iDelBloque); identificadorDelBloque++; }; //::Estructura BASICA + estructura BLOQUES:: bson_append_document_end (documento, &child); //Elimino el diccionarioDeBloques dictionary_clean(diccionarioDeBloques); dictionary_destroy(diccionarioDeBloques); return documento; }
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Event Function //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ void gps_gateway_process(int x, short int y, void *pargs) { unsigned int unFromAddrLen; int nByte = 0; int nSendByte = 0; unsigned char aReqBuffer[512]; unsigned char aRespBuffer[512]; struct sockaddr_in stFromAddr; bson_oid_t oid; bson_t *doc; const bson_t *result; bson_t *query; int i = 0; int command = 0; int monitor_type = 0; char telephone[10]; char text_message[240]; int length; char strBaseinfo[10]; AGPS_info * agps; cell_info * cell; unFromAddrLen = sizeof(stFromAddr); memset(aReqBuffer,0x00,512); memset(aRespBuffer,0x00,512); if ((nByte = recvfrom(x, aReqBuffer, sizeof(aReqBuffer), 0, (struct sockaddr *)&stFromAddr, &unFromAddrLen)) == -1) { printf("error occured while receivingn"); } //proc(); data_frame_head *msg = (data_frame_head *) aReqBuffer; content_gps_up *g = (content_gps_up *)(aReqBuffer + sizeof(data_frame_head)); //异或校验 //异或校验 unsigned char xor = *(aReqBuffer + nByte - 2); if( xor != check_xor(aReqBuffer, nByte - 2)) { return ;//drop down BAD check xor. } switch (msg->cmd) { case CMD_TERMINAL_GPS_UP : //解析位置信息,得到经纬度 fprintf(stderr,"protocal head %x \n",msg->data_head[0] ); fprintf(stderr,"cmd %x \n", msg->cmd ); fprintf(stderr,"length %d \n", ntohs(msg->length) ); //fprintf(stderr,"product_id %u\n",get_product_id(msg->terminal_id)); fprintf(stderr,"product_id %u\n",get_product_id(g->terminal_id)); fprintf(stderr,"flow_id %x \n", ntohs(g->flow_id) ); fprintf(stderr,"data_type %x \n", g->data_type ); fprintf(stderr," time " ); for ( i = 0 ; i< 6 ;i++) fprintf(stderr," %x \n", g->base_info.date_time[i] ); ///////// //经纬度 fprintf(stderr," latitude " ); for ( i = 0 ; i< 4 ;i++) fprintf(stderr,"%x \n", g->base_info.latitude[i] ); fprintf(stderr," longitude " ); for ( i = 0 ; i< 4 ;i++) fprintf(stderr," %x \n", g->base_info.longitude[i] ); ///////// fprintf(stderr,"speed %u \n", ntohs(g->base_info.speed)); fprintf(stderr,"fangxiang %u \n", ntohs(g->base_info.direction)); fprintf(stderr,"gaodu %u\n", ntohs(g->base_info.high)); fprintf(stderr,"定位状态 %c\n", g->base_info.pos_station); fprintf(stderr,"是否应答 %x\n", g->base_info.need_response); if (ntohs(msg->length) > sizeof (content_gps_up)) { fprintf(stderr,"含有附带信息\n"); unsigned char *attach_info = aReqBuffer + sizeof(data_frame_head) + sizeof(content_gps_up); fprintf(stderr,"附带信息类型:%x\n",*attach_info); fprintf(stderr,"附带信息长度:%d\n",*(attach_info+1)); switch (*(attach_info)) { case 0x01: break; case 0x02: fprintf(stderr,"基站信息\n"); agps = (AGPS_info * ) ( attach_info + 2); cell = (cell_info * ) ( attach_info + 2 + sizeof(AGPS_info)); fprintf(stderr,"\n国家编码"); fprintf(stderr," %x ", ntohl(agps->country_code) ); fprintf(stderr,"\n运营编码"); fprintf(stderr," %x ", ntohl(agps->mobile_code) ); fprintf(stderr,"\n运基站定位\n"); for ( i = 0 ; i< agps->base_count ;i++){ fprintf(stderr," 基站 %d 位置区编码 %d\n", i+1, ntohs(cell->lacN) ); fprintf(stderr," 基站 %d 小区编码 %d \n", i+1, ntohs(cell->cellN) ); fprintf(stderr," 基站 %d 信号强度 %x \n", i+1, cell->signalN ); cell++; } break; case 0x0C: case 0x1E: case 0x1F: case 0x28: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: break; } } if( g->data_type == 0x80 || g->data_type == 0x82 || g->data_type == 0x8E ) { //保存mongodb unsigned char timegps[15]; unsigned char latitude[10]; unsigned char longitude[10]; double lat; double lng; doc = bson_new (); bson_oid_init (&oid, NULL); BSON_APPEND_OID (doc, "_id", &oid); BSON_APPEND_INT32 (doc, "id",get_product_id(g->terminal_id)); get_gps_time(g->base_info.date_time, timegps ); BSON_APPEND_UTF8 (doc, "timestamp", timegps); lat = bcd2longitude(g->base_info.latitude, latitude ); lng = bcd2longitude(g->base_info.longitude, longitude ); BSON_APPEND_UTF8 (doc, "latitude", latitude); BSON_APPEND_UTF8 (doc, "longitude", longitude); BSON_APPEND_DOUBLE (doc, "lat", lat); BSON_APPEND_DOUBLE (doc, "lng", lng); BSON_APPEND_INT32 (doc, "speed", ntohs(g->base_info.speed)); BSON_APPEND_INT32 (doc, "direction", ntohs(g->base_info.direction)); BSON_APPEND_INT32 (doc, "high", ntohs(g->base_info.high)); BSON_APPEND_INT32 (doc, "pos_station", g->base_info.pos_station); if (ntohs(msg->length) > sizeof (content_gps_up)) { unsigned char *attach_info = aReqBuffer + sizeof(data_frame_head) + sizeof(content_gps_up); switch (*(attach_info)) { case 0x01: break; case 0x02: agps = (AGPS_info * ) ( attach_info + 2); cell = (cell_info * ) ( attach_info + 2 + sizeof(AGPS_info)); fprintf(stderr,"\n国家编码"); fprintf(stderr," %x ", ntohl(agps->country_code) ); BSON_APPEND_INT32 (doc, "country_code", ntohl(agps->country_code)); fprintf(stderr,"\n运营编码"); fprintf(stderr," %x ", ntohl(agps->mobile_code) ); BSON_APPEND_INT32 (doc, "mobile_code", ntohl(agps->mobile_code)); fprintf(stderr,"\n运基站定位\n"); for ( i = 0 ; i< agps->base_count ;i++){ fprintf(stderr," 基站 %d 位置区编码 %d\n", i+1, ntohs(cell->lacN) ); fprintf(stderr," 基站 %d 小区编码 %d \n", i+1, ntohs(cell->cellN) ); fprintf(stderr," 基站 %d 信号强度 %x \n", i+1, cell->signalN ); sprintf(strBaseinfo,"lac%d",i); BSON_APPEND_INT32 (doc, strBaseinfo, ntohs(cell->lacN) ); sprintf(strBaseinfo,"cell%d",i); BSON_APPEND_INT32 (doc, strBaseinfo, ntohs(cell->cellN) ); sprintf(strBaseinfo,"signal%d",i); BSON_APPEND_INT32 (doc, strBaseinfo, cell->signalN ); cell++; } break; case 0x0C: case 0x1E: case 0x1F: case 0x28: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: break; } } if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) { printf ("Insert failed: %s\n", error.message); } bson_destroy (doc); } else if( g->data_type == 0x85 ) { //delete from mongo query = bson_new (); BSON_APPEND_INT32 (query, "id",get_product_id(g->terminal_id)); if( ! mongoc_collection_remove(collection_cmd, MONGOC_DELETE_NONE, query, NULL, &error)) { fprintf(stderr,"remove command failed \n" ); } bson_destroy (query); } if (g->base_info.need_response == 0x01) { send_22_response( x, aRespBuffer , g->flow_id, xor , g->data_type, stFromAddr, unFromAddrLen ); } break; case CMD_TERMINAL_INFO_UP : fprintf(stderr,"CMD_TERMINAL_INFO_UP\n"); content_info_up * t = (content_info_up *)(aReqBuffer + sizeof(data_frame_head)); fprintf(stderr,"parameter %x \n", t->parameter ); if(t->parameter == 0x01) { sent_time_response( x, aRespBuffer , g->terminal_id, stFromAddr, unFromAddrLen ); } break; case CMD_VERSION_INFO_UP : fprintf(stderr,"CMD_VERSION_INFO_UP"); break; case CMD_VOICE_UP : fprintf(stderr,"CMD_VOICE_UP"); break; default: break; } //get command from mongo char *str; query = bson_new (); BSON_APPEND_INT32 (query, "id",get_product_id(g->terminal_id)); cursor = mongoc_collection_find (collection_cmd, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL); //while (mongoc_cursor_next (cursor, &doc)) { // mongoc_cursor_next (cursor, &result); while (mongoc_cursor_next (cursor, (const bson_t **) &doc)) { bson_iter_t iter; bson_iter_t sub_iter; str = bson_as_json (doc, NULL); fprintf (stderr, "%s\n", str); bson_free (str); if (bson_iter_init (&iter, doc) && bson_iter_find_descendant (&iter, "cmd", &sub_iter)) { fprintf (stderr,"Found key \"%s\" in sub document.\n", bson_iter_key (&sub_iter)); printf ("The type of a.b.c.d is: %d\n", (int)bson_iter_type (&sub_iter)); command = (int)bson_iter_int32 (&sub_iter); } if (bson_iter_init (&iter, doc) && bson_iter_find_descendant (&iter, "parameter", &sub_iter)) { fprintf (stderr,"Found key \"%s\" in sub document.\n", bson_iter_key (&sub_iter)); printf ("The type of a.b.c.d is: %d\n", (int)bson_iter_type (&sub_iter)); strcpy (telephone , bson_iter_utf8 (&sub_iter,&length)); } if (bson_iter_init (&iter, doc) && bson_iter_find_descendant (&iter, "monitor_type", &sub_iter)) { fprintf (stderr,"Found key \"%s\" in sub document.\n", bson_iter_key (&sub_iter)); printf ("The type of a.b.c.d is: %d\n", (int)bson_iter_type (&sub_iter)); monitor_type = (int)bson_iter_int32 (&sub_iter); } if (bson_iter_init (&iter, doc) && bson_iter_find_descendant (&iter, "text_message", &sub_iter)) { fprintf (stderr,"Found key \"%s\" in sub document.\n", bson_iter_key (&sub_iter)); printf ("The type of a.b.c.d is: %d\n", (int)bson_iter_type (&sub_iter)); strcpy (text_message , bson_iter_utf8 (&sub_iter,&length)); } } mongoc_cursor_destroy (cursor); bson_destroy (query); //send command to handring if (command == 1) { send_monitor_cmd( x, aRespBuffer , g->terminal_id, stFromAddr, unFromAddrLen ,monitor_type, telephone); } else if (command == 9) { send_sleep_cmd( x, aRespBuffer , g->terminal_id, stFromAddr, unFromAddrLen ); } else if (command == 2) { send_set_cmd( x, aRespBuffer , g->terminal_id, stFromAddr, unFromAddrLen ,text_message); } else{ //为了避免长时间使用网络。在通信6次发送一个休眠指令 if( (msg->cmd == CMD_TERMINAL_GPS_UP) && (check_state(g->terminal_id) == MAX_STANDBY) ) { send_sleep_cmd( x, aRespBuffer , g->terminal_id, stFromAddr, unFromAddrLen ); } } //printf("Function called buffer is %sn",aReqBuffer); g_count++; }