示例#1
0
文件: main.c 项目: gpalma/semep
int main(int argc, char **argv)
{
     int len;
     clock_t ti, tf;
     static char *name;
     struct input_data in;
     double density;

     ti = clock();
     parse_args(argc, argv);
     print_args();
     len = strlen(g_args.graph_filename) + 1;
     name = xcalloc(len, 1);
     get_name(g_args.graph_filename, len, name);
     printf("\n**** Go semEP! **** \n");
     in = get_input_data(g_args.matrix_left_filename, g_args.matrix_right_filename,
			 g_args.left_filename, g_args.right_filename,
			 g_args.graph_filename);
     density = semEP_solver(&in.left_matrix, &in.right_matrix, &in.left_terms, &in.right_terms,
			    &in.td, &in.bpgraph, g_args.threshold_left, g_args.threshold_right, name);
     printf("Average density of the partitions: %.4f \n", density);
     printf("*** semEP finished ***\n");
     tf = clock();
     printf("\nTotal time %.3f secs\n", (double)(tf-ti)/CLOCKS_PER_SEC);
     free(name);
     free_input_data(&in);

     return 0;
}
示例#2
0
char get_menu()
{
    printf("\n=============================================\n");
    printf("\t\tMenu\n");
    printf("\ts : start server\n");
    printf("\tc : start client\n");
    printf("\tr : send request\n");
    printf("\tt : send request to all\n");
    printf("\tb : send notification\n");
    printf("\tn : select network\n");
    printf("\tx : unselect network\n");
    printf("\tg : get network information\n");
    printf("\th : handle request response\n");
    printf("\tz : run static server\n");
    printf("\tw : send secure request\n");
    printf("\tq : quit\n");
    printf("=============================================\n");
    printf("select : ");

    char buf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        printf("Failed to get input data\n");
    }

    return buf[0];
}
示例#3
0
CAResult_t get_network_type(CATransportFlags_t *flags)
{
    char buf[MAX_BUF_LEN] = { 0 };

    printf("\n=============================================\n");
    printf("\tselect network type\n");
    printf("IP     : 0\n");
    printf("GATT   : 1\n");
    printf("RFCOMM : 2\n");
    printf("TCP    : 4\n");
    printf("select : ");

    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        return CA_NOT_SUPPORTED ;
    }

    int number = buf[0] - '0';

    number = (number < 0 || number > 4) ? 0 : 1 << number;

    switch (number)
    {
        case CA_ADAPTER_IP:
            *flags = CA_IPV4;
        case CA_ADAPTER_GATT_BTLE:
        case CA_ADAPTER_RFCOMM_BTEDR:
        case CA_ADAPTER_TCP:
            g_selected_nw_type = number;
            return CA_STATUS_OK;
        default:
            return CA_NOT_SUPPORTED;
    }
}
示例#4
0
int main(void)
{
    int iii = 0;
    int data_number = 0;
    int* source_data = 0;
	
	source_data = get_input_data(&data_number);
	
    printf("before sort:\n");
    for (iii = 0; iii < data_number; iii++)
	{
        printf("%d,", source_data[iii]);
    }
    printf("\n");
	
    insert_sort(source_data, data_number);
	
    printf("after sort:\n");
    for (iii = 0; iii < data_number; iii++)
	{
        printf("%d,", source_data[iii]);
    }
    printf("\n");
    
    if(source_data)
    	free(source_data);
    return 0;
}
示例#5
0
void unselect_network()
{
    printf("\n=============================================\n");
    printf("\tunselect enabled network\n");
    printf("IP     : 0\n");
    printf("GATT   : 1\n");
    printf("RFCOMM : 2\n");
    printf("select : ");

    char buf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        return;
    }

    int number = buf[0] - '0';

    if (number < 0 || number > 3)
    {
        printf("Invalid network type\n");
        return;
    }

    CAResult_t res = CAUnSelectNetwork(1 << number);
    if (CA_STATUS_OK != res)
    {
        printf("Unselect network error\n");
    }
    else
    {
        printf("Unselect network success\n");
    }

    printf("=============================================\n");
}
示例#6
0
CAResult_t get_network_type()
{
    printf("\n=============================================\n");
    printf("\tselect network type\n");
    printf("IP     : 0\n");
    printf("GATT   : 1\n");
    printf("RFCOMM : 2\n");
    printf("TCP    : 4\n");
    printf("select : ");

    char buf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        return CA_NOT_SUPPORTED ;
    }

    int number = buf[0] - '0';
    if (0 > number || 4 < number)
    {
        printf("\nInvalid Network type");
        return CA_NOT_SUPPORTED;
    }

    g_selected_nw_type = 1 << number;

    return CA_STATUS_OK;
}
示例#7
0
void send_secure_request()
{
    char ipv4addr[CA_IPADDR_SIZE];

    printf("\n=============================================\n");
    printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");

    if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
    {
        return;
    }
    printf("%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);

    // create remote endpoint
    CAEndpoint_t *endpoint = NULL;
    CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
    if (CA_STATUS_OK != res)
    {
        printf("Failed to create remote endpoint, error code: %d\n", res);
        goto exit;
    }

    // create token
    CAToken_t token = NULL;
    uint8_t tokenLength = CA_MAX_TOKEN_LEN;

    res = CAGenerateToken(&token, tokenLength);
    if ((CA_STATUS_OK != res) || (!token))
    {
        printf("Token generate error, error code : %d\n", res);
        goto exit;
    }

    printf("Generated token %s\n", token);

    // create request data
    CAMessageType_t msgType = CA_MSG_NONCONFIRM;
    CAInfo_t requestData = { 0 };
    requestData.token = token;
    requestData.tokenLength = tokenLength;
    requestData.type = msgType;
    requestData.payload = "Temp Json Payload";
    requestData.payloadSize = strlen(requestData.payload)+1;

    CARequestInfo_t requestInfo = { 0 };
    requestInfo.method = CA_GET;
    requestInfo.info = requestData;
    requestInfo.isMulticast = false;

    // send request
    CASendRequest(endpoint, &requestInfo);

exit:
    // cleanup
    CADestroyToken(token);
    CADestroyEndpoint(endpoint);
    printf("=============================================\n");
}
示例#8
0
bool select_payload_type()
{
    char buf[MAX_BUF_LEN]={0};
    printf("\n=============================================\n");
    printf("Normal Payload  : 0\nBig Payload   : 1\n");
    printf("select Payload type : ");

    CAResult_t res = get_input_data(buf, sizeof(buf));
    if (CA_STATUS_OK != res)
    {
        printf("Payload type selection error\n");
        printf("Default: Using normal Payload\n");
        return false;
    }

    return (buf[0] == '1') ? true : false;
}
示例#9
0
/*
  Function: write datas
  return: -1 -- failed.
           0 -- success.
*/
int appendDataTrans(void)
{
    char datas[MAX_DATA_LEN] = {0};
    FILE* p_file = NULL;

    //get value
    if (get_input_data(datas, MAX_DATA_LEN))
        return -1;

    p_file = fopen(DATATRANS_FILEPATH, "a");
    if (!p_file)
        return -1;

    fputs(datas, p_file);
    fputs("\r\n", p_file);

    fclose(p_file);
    p_file = NULL;

    return 0;
}
示例#10
0
CAResult_t get_network_type()
{
    char buf[MAX_BUF_LEN] = { 0 };

    printf("\n=============================================\n");
    printf("\tselect network type\n");
    printf("IP     : 0\n");
    printf("GATT   : 1\n");
    printf("RFCOMM : 2\n");
    printf("select : ");

    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        return CA_NOT_SUPPORTED ;
    }

    int number = buf[0] - '0';

    number = (number < 0 || number > 3) ? 0 : 1 << number;

    if (number == 1)
    {
        g_selected_nw_type = CA_ADAPTER_IP;
        return CA_STATUS_OK;
    }
    if (number == 2)
    {
        g_selected_nw_type = CA_ADAPTER_GATT_BTLE;
        return CA_STATUS_OK;
    }
    if (number == 3)
    {
        g_selected_nw_type = CA_ADAPTER_RFCOMM_BTEDR;
        return CA_STATUS_OK;
    }

    return CA_NOT_SUPPORTED;
}
示例#11
0
void send_request_all()
{
    CAResult_t res = get_network_type();
    if (CA_STATUS_OK != res)
    {
        return;
    }

    printf("\n=============================================\n");
    printf("ex) /a/light\n");
    printf("resource uri : ");

    char resourceURI[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
    {
        return;
    }

    // create remote endpoint
    CAEndpoint_t *endpoint = NULL;
    res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &endpoint);
    if (CA_STATUS_OK != res)
    {
        printf("Create remote endpoint error, error code: %d\n", res);
        return;
    }

    // create token
    CAToken_t token = NULL;
    uint8_t tokenLength = CA_MAX_TOKEN_LEN;

    res = CAGenerateToken(&token, tokenLength);
    if ((CA_STATUS_OK != res) || (!token))
    {
        printf("Token generate error!!\n");
        CADestroyEndpoint(endpoint);
        return;
    }

    printf("generated token %s\n", token);

    CAInfo_t requestData = { 0 };
    requestData.token = token;
    requestData.tokenLength = tokenLength;
    requestData.payload = (CAPayload_t) "TempJsonPayload";
    requestData.payloadSize = strlen((const char *) requestData.payload);
    requestData.type = CA_MSG_NONCONFIRM;
    requestData.resourceUri = (CAURI_t)resourceURI;

    CARequestInfo_t requestInfo = { 0 };
    requestInfo.method = CA_GET;
    requestInfo.info = requestData;
    requestInfo.isMulticast = true;

    // send request
    res = CASendRequest(endpoint, &requestInfo);
    if (CA_STATUS_OK != res)
    {
        printf("Could not send request to all\n");
    }
    else
    {
        CADestroyToken(g_last_request_token);
        g_last_request_token = token;
    }

    // destroy remote endpoint
    CADestroyEndpoint(endpoint);

    printf("=============================================\n");
}
示例#12
0
void send_request()
{
    CAResult_t res = get_network_type();
    if (CA_STATUS_OK != res)
    {
        return;
    }

    printf("Do you want to send secure request ?.... enter (0/1): ");

    char secureRequest[MAX_BUF_LEN] = {0};
    if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
    {
        return;
    }

    if (strcmp(secureRequest, "1") == 0)
    {
        printf("Enter the URI like below....\n");
        printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
    }
    else if (strcmp(secureRequest, "0") == 0)
    {
        printf("Enter the URI like below....\n");
        printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
        printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
    }
    else
    {
        printf("Input data is wrong value\n");
        return;
    }

    char uri[MAX_BUF_LEN] = {'\0'};
    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
    {
        return;
    }

    // create remote endpoint
    CAEndpoint_t *endpoint = NULL;
    CATransportFlags_t flags;

    printf("URI : %s\n", uri);
    addressSet_t address = {{}, 0};
    parsing_coap_uri(uri, &address, &flags);

    res = CACreateEndpoint(flags, g_selected_nw_type,
                           (const char*)address.ipAddress, address.port, &endpoint);
    if (CA_STATUS_OK != res || !endpoint)
    {
        printf("Failed to create remote endpoint, error code : %d\n", res);
        return;
    }

    printf("\n=============================================\n");
    printf("0:CON, 1:NON\n");
    printf("select message type : ");

    char buf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        CADestroyEndpoint(endpoint);
        return;
    }

    CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;

    // create token
    CAToken_t token = NULL;
    uint8_t tokenLength = CA_MAX_TOKEN_LEN;

    res = CAGenerateToken(&token, tokenLength);
    if ((CA_STATUS_OK != res) || (!token))
    {
        printf("Token generate error, error code : %d\n", res);
        CADestroyEndpoint(endpoint);
        return;
    }

    printf("Generated token %s\n", token);

    // extract relative resourceuri from give uri
    char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
    get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
    printf("resourceURI : %s\n", resourceURI);

    // create request data
    CAInfo_t requestData = { .type = msgType,
                             .messageId = 0,
                             .token = token,
                             .tokenLength = tokenLength,
                             .options = NULL,
                             .numOptions = 0,
                             .payload = NULL,
                             .payloadSize = 0,
                             .resourceUri = (CAURI_t)resourceURI };

    if (strcmp(secureRequest, "1") == 0)
    {
        size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
        requestData.payload = (CAPayload_t) calloc(length,  sizeof(char));
        if (NULL == requestData.payload)
        {
            printf("Memory allocation fail\n");
            CADestroyEndpoint(endpoint);
            CADestroyToken(token);
            return;
        }
        snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
                 (const char *) resourceURI, g_local_secure_port);
        requestData.payloadSize = length;
    }
    else
    {
        bool useBigPayload = select_payload_type();
        if (useBigPayload)
        {
            size_t payloadLength = 0;
            CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
            if (!binaryPayload)
            {
                free(binaryPayload);
                CADestroyToken(token);
                CADestroyEndpoint(endpoint);
                return;
            }

            requestData.payload = (CAPayload_t) malloc(payloadLength);
            if (NULL == requestData.payload)
            {
                printf("Memory allocation failed!");
                free(binaryPayload);
                CADestroyToken(token);
                CADestroyEndpoint(endpoint);
                return;
            }
            memcpy(requestData.payload, binaryPayload, payloadLength);
            requestData.payloadSize = payloadLength;

            // memory free
            free(binaryPayload);
        }
        else
        {
            size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
            requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
            if (NULL == requestData.payload)
            {
                printf("Memory allocation fail\n");
                CADestroyEndpoint(endpoint);
                CADestroyToken(token);
                return;
            }
            snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
                     (const char *) resourceURI);
            requestData.payloadSize = length;
        }
    }

    CAHeaderOption_t* headerOpt = get_option_data(&requestData);

    CARequestInfo_t requestInfo = { .method = CA_GET,
                                    .info = requestData,
                                    .isMulticast = false };

    // send request
    res = CASendRequest(endpoint, &requestInfo);
    if (CA_STATUS_OK != res)
    {
        printf("Could not send request : %d\n", res);
    }

    if (headerOpt)
    {
        free(headerOpt);
    }

    //destroy token
    CADestroyToken(token);
    // destroy remote endpoint
    CADestroyEndpoint(endpoint);
    free(requestData.payload);

    printf("=============================================\n");
}

void send_secure_request()
{
    char uri[MAX_BUF_LEN];
    char ipv4addr[CA_IPADDR_SIZE];

    printf("\n=============================================\n");
    printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");

    if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
    {
        return;
    }
    snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr);

    // create remote endpoint
    CAEndpoint_t *endpoint = NULL;
    CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
    if (CA_STATUS_OK != res)
    {
        printf("Failed to create remote endpoint, error code: %d\n", res);
        goto exit;
    }

    // create token
    CAToken_t token = NULL;
    uint8_t tokenLength = CA_MAX_TOKEN_LEN;

    res = CAGenerateToken(&token, tokenLength);
    if (CA_STATUS_OK != res)
    {
        printf("Token generate error, error code : %d\n", res);
        goto exit;
    }

    printf("Generated token %s\n", token);

    // create request data
    CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
                             .messageId = 0,
                             .token = token,
                             .tokenLength = tokenLength,
                             .options = NULL,
                             .numOptions = 0,
                             .payload = NULL,
                             .payloadSize = 0,
                             .resourceUri = NULL };

    CARequestInfo_t requestInfo = { .method = CA_GET,
                                    .info = requestData,
                                    .isMulticast = false };

    // send request
    CASendRequest(endpoint, &requestInfo);

exit:
    // cleanup
    CADestroyToken(token);
    CADestroyEndpoint(endpoint);
    printf("=============================================\n");
}


void send_request_all()
{
    CAResult_t res = get_network_type();
    if (CA_STATUS_OK != res)
    {
        return;
    }

    printf("\n=============================================\n");
    printf("ex) /a/light\n");
    printf("resource uri : ");

    char resourceURI[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
    {
        return;
    }

    // create remote endpoint
    CAEndpoint_t *group = NULL;
    res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &group);
    if (CA_STATUS_OK != res)
    {
        printf("Create remote endpoint error, error code: %d\n", res);
        return;
    }

    // create token
    CAToken_t token = NULL;
    uint8_t tokenLength = CA_MAX_TOKEN_LEN;

    res = CAGenerateToken(&token, tokenLength);
    if ((CA_STATUS_OK != res) || (!token))
    {
        printf("Token generate error!!\n");
        CADestroyEndpoint(group);
        return;
    }

    printf("generated token %s\n", token);

    // create request data
    CAPayload_t payload = (CAPayload_t) "TempJsonPayload";
    size_t payloadSize = strlen((const char *) payload);

    CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
                             .messageId = 0,
                             .token = token,
                             .tokenLength = tokenLength,
                             .options = NULL,
                             .numOptions = 0,
                             .payload = payload,
                             .payloadSize = payloadSize,
                             .resourceUri = (CAURI_t) resourceURI };

    CARequestInfo_t requestInfo = { .method = CA_GET,
                                    .info = requestData,
                                    .isMulticast = true };

    CAHeaderOption_t* headerOpt = get_option_data(&requestData);

    // send request
    res = CASendRequest(group, &requestInfo);
    if (CA_STATUS_OK != res)
    {
        printf("Could not send request to all\n");
        CADestroyToken(token);
    }
    else
    {
        CADestroyToken(g_last_request_token);
        g_last_request_token = token;
    }

    if (headerOpt)
    {
        free(headerOpt);
    }

    // destroy remote endpoint
    CADestroyEndpoint(group);

    printf("=============================================\n");
}

void send_notification()
{
    CAResult_t res = get_network_type();
    if (CA_STATUS_OK != res)
    {
        return;
    }

    printf("\n=============================================\n");
    printf("Enter the URI like below....\n");
    printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
    printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
    printf("uri : ");

    char uri[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
    {
        return;
    }

    printf("\n=============================================\n");
    printf("\tselect message type\n");
    printf("CON     : 0\n");
    printf("NON     : 1\n");
    printf("ACK     : 2\n");
    printf("RESET   : 3\n");
    printf("select : ");

    char messageTypeBuf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
    {
        return;
    }

    int messageType = messageTypeBuf[0] - '0';

    CATransportFlags_t flags;
    addressSet_t address = {{}, 0};
    parsing_coap_uri(uri, &address, &flags);

    // create remote endpoint
    CAEndpoint_t *endpoint = NULL;
    res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
    if (CA_STATUS_OK != res)
    {
        printf("Create remote endpoint error, error code: %d\n", res);
        return;
    }

    // create token
    CAToken_t token = NULL;
    uint8_t tokenLength = CA_MAX_TOKEN_LEN;

    res = CAGenerateToken(&token, tokenLength);
    if ((CA_STATUS_OK != res) || (!token))
    {
        printf("Token generate error!!\n");
        CADestroyEndpoint(endpoint);
        return;
    }

    printf("Generated token %s\n", token);

    // create response data
    CAPayload_t payload = (CAPayload_t) "TempNotificationData";
    size_t payloadSize = strlen((const char *) payload);

    CAInfo_t respondData = { .type = messageType,
                             .messageId = 0,
                             .token = token,
                             .tokenLength = tokenLength,
                             .options = NULL,
                             .numOptions = 0,
                             .payload = payload,
                             .payloadSize = payloadSize,
                             .resourceUri = (CAURI_t)uri };

    CAResponseInfo_t responseInfo = { .result = CA_CONTENT,
                                      .info = respondData };

    // send request
    res = CASendNotification(endpoint, &responseInfo);
    if (CA_STATUS_OK != res)
    {
        printf("Send notification error, error code: %d\n", res);
    }
    else
    {
        printf("Send notification success\n");
    }

    // destroy token
    CADestroyToken(token);
    // destroy remote endpoint
    CADestroyEndpoint(endpoint);

    printf("\n=============================================\n");
}

void select_network()
{
    printf("\n=============================================\n");
    printf("\tselect network\n");
    printf("IP     : 0\n");
    printf("GATT   : 1\n");
    printf("RFCOMM : 2\n");
    printf("select : ");

    char buf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        return;
    }

    int number = buf[0] - '0';

    if (number < 0 || number > 3)
    {
        printf("Invalid network type\n");
        return;
    }

    CAResult_t res = CASelectNetwork(1 << number);
    if (CA_STATUS_OK != res)
    {
        printf("Select network error\n");
    }
    else
    {
        printf("Select network success\n");
    }

    printf("=============================================\n");
}
示例#13
0
CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
{
    char optionNumBuf[MAX_BUF_LEN] = { 0 };
    char optionData[MAX_OPT_LEN] = { 0 } ;

    printf("Option Num : ");
    if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
    {
        return NULL;
    }
    int optionNum = atoi(optionNumBuf);

    CAHeaderOption_t * headerOpt = NULL;
    if (0 >= optionNum)
    {
        printf("there is no headerOption!\n");
        return NULL;
    }
    else if (optionNum > MAX_OPT_LEN)
    {
        printf("Too many header options!\n");
        return NULL;
    }
    else
    {
        headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t));
        if (NULL == headerOpt)
        {
            printf("Memory allocation failed!\n");
            return NULL;
        }

        int i;
        for (i = 0; i < optionNum; i++)
        {
            char getOptionID[MAX_BUF_LEN] = { 0 } ;

            printf("[%d] Option ID : ", i + 1);
            if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
            {
                free(headerOpt);
                return NULL;
            }
            int optionID = atoi(getOptionID);
            headerOpt[i].optionID = optionID;

            printf("[%d] Option Data : ", i + 1);
            if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
            {
                free(headerOpt);
                return NULL;
            }

            OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData);

            headerOpt[i].optionLength = (uint16_t) strlen(optionData);
        }
        requestData->numOptions = optionNum;
        requestData->options = headerOpt;
    }
    return headerOpt;
}
示例#14
0
void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
{
    printf("entering send_response\n");

    printf("\n=============================================\n");
    printf("\tselect message type\n");
    printf("CON     : 0\n");
    printf("NON     : 1\n");
    printf("ACK     : 2\n");
    printf("RESET   : 3\n");
    printf("select : ");

    char buf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        return;
    }

    int messageType = buf[0] - '0';
    if (0 > messageType || 3 < messageType)
    {
        printf("Invalid message type\n");
        return;
    }

    int responseCode = 0 ;
    char responseCodeBuf[MAX_BUF_LEN] = { 0 };
    if (CA_MSG_RESET != messageType)
    {
        printf("\n=============================================\n");
        printf("\tselect response code\n");
        printf("EMPTY                    :   0\n");
        printf("SUCCESS                  : 200\n");
        printf("CREATED                  : 201\n");
        printf("DELETED                  : 202\n");
        printf("VALID                    : 203\n");
        printf("CHANGED                  : 204\n");
        printf("CONTENT                  : 205\n");
        printf("BAD_REQ                  : 400\n");
        printf("BAD_OPT                  : 402\n");
        printf("NOT_FOUND                : 404\n");
        printf("INTERNAL_SERVER_ERROR    : 500\n");
        printf("RETRANSMIT_TIMEOUT       : 504\n");
        printf("select : ");

        if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
        {
            return;
        }
        responseCode = atoi(responseCodeBuf);
    }

    // create response data
    uint16_t messageId = (info != NULL) ? info->messageId : 0;
    CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0;

    CAInfo_t responseData = { .type = messageType,
                              .messageId = messageId,
                              .token = NULL,
                              .tokenLength = 0,
                              .options = NULL,
                              .numOptions = 0,
                              .payload = NULL,
                              .payloadSize = 0,
                              .resourceUri = resourceUri };

    if(CA_MSG_RESET != messageType)
    {
        responseData.token = (info != NULL) ? info->token : NULL;
        responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;

        if (endpoint->flags & CA_SECURE)
        {
            if(!responseData.resourceUri)
            {
               printf("resourceUri not available in SECURE\n");
               return;
            }
            printf("Sending response on secure communication\n");

            uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
            responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
            if (NULL == responseData.payload)
            {
                printf("Memory allocation fail\n");
                return;
            }
            snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
                     (const char *) responseData.resourceUri, g_local_secure_port);
            responseData.payloadSize = length;
        }
        else
        {
            printf("Sending response on non-secure communication\n");

            bool useBigPayload = select_payload_type();
            if (useBigPayload)
            {
                size_t payloadLength = 0;
                CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
                if (NULL == binaryPayload)
                {
                    free(binaryPayload);
                    return;
                }

                responseData.payload = (CAPayload_t) malloc(payloadLength);
                if (NULL == responseData.payload)
                {
                    printf("Memory allocation failed!");
                    free(binaryPayload);
                    return;
                }
                memcpy(responseData.payload, binaryPayload, payloadLength);
                responseData.payloadSize = payloadLength;

                // memory free
                free(binaryPayload);
            }
            else
            {
                if(!responseData.resourceUri)
                {
                   printf("resourceUri not available in NON-SECURE\n");
                   return;
                }
                uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
                responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
                if (NULL == responseData.payload)
                {
                    printf("Memory allocation fail\n");
                    return;
                }
                snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
                         (const char *) responseData.resourceUri);
                responseData.payloadSize = length;
            }
        }
    }

    CAResponseInfo_t responseInfo = { .result = responseCode,
                                      .info = responseData };

    // send response (transportType from remoteEndpoint of request Info)
    CAResult_t res = CASendResponse(endpoint, &responseInfo);
    if (CA_STATUS_OK != res)
    {
        printf("Send response error\n");
    }
    else
    {
        printf("Send response success\n");
    }

    if (responseData.payload)
    {
        free(responseData.payload);
    }

    printf("=============================================\n");
}

int get_secure_information(CAPayload_t payLoad)
{
    printf("Entering get_secure_information\n");

    if (!payLoad)
    {
        printf("Payload is NULL\n");
        return -1;
    }

    char *subString = NULL;
    if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
    {
        printf("This is not secure resource\n");
        return -1;
    }

    if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
    {
        printf("This secure resource does not have port information\n");
        return -1;
    }

    char *startPos = strstr(subString, ":");
    if (!startPos)
    {
        printf("Parsing failed !\n");
        return -1;
    }

    char *endPos = strstr(startPos, "}");
    if (!endPos)
    {
        printf("Parsing failed !\n");
        return -1;
    }

    char portStr[6] = {0};
    OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos);
    printf("secured port is: %s\n", portStr);
    return atoi(portStr);
}
示例#15
0
void send_request()
{
    CAResult_t res = get_network_type();
    if (CA_STATUS_OK != res)
    {
        return;
    }

    printf("Do you want to send secure request ?.... enter (0/1): ");

    char secureRequest[MAX_BUF_LEN] = {0};
    if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
    {
        return;
    }

    if (strcmp(secureRequest, "1") == 0)
    {
        printf("Enter the URI like below....\n");
        printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
    }
    else if (strcmp(secureRequest, "0") == 0)
    {
        printf("Enter the URI like below....\n");
        printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
        printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
        printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
    }
    else
    {
        printf("Input data is wrong value\n");
        return;
    }

    char uri[MAX_BUF_LEN] = {'\0'};
    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
    {
        return;
    }

    // create remote endpoint
    CAEndpoint_t *endpoint = NULL;
    CATransportFlags_t flags;

    printf("URI : %s\n", uri);
    addressSet_t address = {};
    parse_coap_uri(uri, &address, &flags);

    res = CACreateEndpoint(flags, g_selected_nw_type,
                           (const char*)address.ipAddress, address.port, &endpoint);
    if (CA_STATUS_OK != res || !endpoint)
    {
        printf("Failed to create remote endpoint, error code : %d\n", res);
        return;
    }

    printf("\n=============================================\n");
    printf("0:CON, 1:NON\n");
    printf("select message type : ");

    char buf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        CADestroyEndpoint(endpoint);
        return;
    }

    CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;

    // create token
    CAToken_t token = NULL;
    uint8_t tokenLength = CA_MAX_TOKEN_LEN;

    res = CAGenerateToken(&token, tokenLength);
    if ((CA_STATUS_OK != res) || (!token))
    {
        printf("Token generate error, error code : %d\n", res);
        CADestroyEndpoint(endpoint);
        return;
    }

    printf("Generated token %s\n", token);

    // extract relative resourceuri from give uri
    char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
    get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
    printf("resourceURI : %s\n", resourceURI);

    // create request data
    CAInfo_t requestData = { 0 };
    requestData.token = token;
    requestData.tokenLength = tokenLength;
    requestData.resourceUri = (CAURI_t)resourceURI;

    if (strcmp(secureRequest, "1") == 0)
    {
        size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
        requestData.payload = (CAPayload_t) calloc(length,  sizeof(char));
        if (NULL == requestData.payload)
        {
            printf("Memory allocation fail\n");
            CADestroyEndpoint(endpoint);
            CADestroyToken(token);
            return;
        }
        snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
                 (const char *) resourceURI, g_local_secure_port);
    }
    else
    {
        bool useBigPayload = select_payload();
        if (useBigPayload)
        {
            requestData.payload = (CAPayload_t) calloc(BIG_PAYLOAD_SIZE, sizeof(char));
            if (NULL == requestData.payload)
            {
                printf("Memory allocation fail\n");
                CADestroyEndpoint(endpoint);
                CADestroyToken(token);
                return;
            }
            populate_binary_payload(requestData.payload, BIG_PAYLOAD_SIZE);
        }
        else
        {
            size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
            requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
            if (NULL == requestData.payload)
            {
                printf("Memory allocation fail\n");
                CADestroyEndpoint(endpoint);
                CADestroyToken(token);
                return;
            }
            snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
                     (const char *) resourceURI);
        }
    }
    requestData.payloadSize = strlen((char *)requestData.payload)+1;
    requestData.type = msgType;

    CARequestInfo_t requestInfo = { 0 };
    requestInfo.method = CA_GET;
    requestInfo.info = requestData;
    requestInfo.isMulticast = false;

    // send request
    res = CASendRequest(endpoint, &requestInfo);
    if (CA_STATUS_OK != res)
    {
        printf("Could not send request : %d\n", res);
    }

    //destroy token
    CADestroyToken(token);
    // destroy remote endpoint
    CADestroyEndpoint(endpoint);
    free(requestData.payload);


    printf("=============================================\n");
}
示例#16
0
void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
{
    printf("entering send_response\n");

    printf("\n=============================================\n");
    printf("\tselect message type\n");
    printf("CON     : 0\n");
    printf("NON     : 1\n");
    printf("ACK     : 2\n");
    printf("RESET   : 3\n");
    printf("select : ");

    char buf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
    {
        return;
    }

    int messageType = buf[0] - '0';
    int responseCode = 0 ;
    char responseCodeBuf[MAX_BUF_LEN] = { 0 };
    if (CA_MSG_RESET != messageType)
    {
        printf("\n=============================================\n");
        printf("\tselect response code\n");
        printf("EMPTY                    :   0\n");
        printf("CREATED                  : 201\n");
        printf("DELETED                  : 202\n");
        printf("VALID                    : 203\n");
        printf("CHANGED                  : 204\n");
        printf("CONTENT                  : 205\n");
        printf("BAD_REQ                  : 400\n");
        printf("BAD_OPT                  : 402\n");
        printf("NOT_FOUND                : 404\n");
        printf("INTERNAL_SERVER_ERROR    : 500\n");
        printf("RETRANSMIT_TIMEOUT       : 504\n");
        printf("select : ");

        if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
        {
            return;
        }
        responseCode = atoi(responseCodeBuf);
    }
    CAInfo_t responseData = { 0 };
    responseData.type = messageType;
    responseData.messageId = (info != NULL) ? info->messageId : 0;
    responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;

    if(CA_MSG_RESET != messageType)
    {
        responseData.token = (info != NULL) ? info->token : NULL;
        responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;

        if (endpoint->flags & CA_SECURE)
        {
            printf("Sending response on secure communication\n");

            uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri)
                              + sizeof(g_local_secure_port);
            responseData.payload = (CAPayload_t) calloc(length,  sizeof(char));
            if (NULL == responseData.payload)
            {
                printf("Memory allocation fail\n");
                return;
            }
            snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
                     (const char *) responseData.resourceUri, g_local_secure_port);
        }
        else
        {
            printf("Sending response on non-secure communication\n");

            bool useBigPayload = select_payload();
            if (useBigPayload)
            {
                responseData.payload = (CAPayload_t) calloc(BIG_PAYLOAD_SIZE, sizeof(char));
                if (NULL == responseData.payload)
                {
                    printf("Memory allocation fail\n");
                    return;
                }
                populate_binary_payload(responseData.payload, BIG_PAYLOAD_SIZE);
            }
            else
            {
                size_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
                responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
                if (NULL == responseData.payload)
                {
                    printf("Memory allocation fail\n");
                    return;
                }
                snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
                         (const char *) responseData.resourceUri);
            }
        }
    }
    responseData.payloadSize = strlen((char *)responseData.payload)+1;
    CAResponseInfo_t responseInfo = { 0 };
    responseInfo.result = responseCode;
    responseInfo.info = responseData;

    // send response (transportType from remoteEndpoint of request Info)
    CAResult_t res = CASendResponse(endpoint, &responseInfo);
    if (CA_STATUS_OK != res)
    {
        printf("Send response error\n");
    }
    else
    {
        printf("Send response success\n");
    }

    printf("=============================================\n");
}
示例#17
0
const u8_t * asn1_der_type_c::get_unused_data() const
{
	return get_input_data() + get_used_octets();
}
示例#18
0
int main(int argc, char* argv[])
{
  unsigned int opcode = 0;
  char    *mosaic_in=NULL;            /* input mosaic file name */
  char    *mosaic_out=NULL;           /* input mosaic file name */
  char    *dir_in=NULL;               /* input file location */
  char    *dir_out=NULL;              /* output file location */
  int     ntiles_in = 0;              /* number of tiles in input mosaic */
  int     ntiles_out = 0;             /* number of tiles in output mosaic */
  int     nfiles     = 0;              /* number of input file */
  int     nfiles_out = 0;             /* number of output file */
  char    input_file [NFILE][STRING];
  char    output_file[NFILE][STRING];
  char    scalar_name[NVAR] [STRING];
  char    u_name     [NVAR] [STRING];
  char    v_name     [NVAR] [STRING];
  char    *test_case = NULL;
  double  test_param = 1;
  int     check_conserve = 0; /* 0 means no check */
  double  lonbegin = 0, lonend = 360;
  double  latbegin = -90, latend = 90;			  
  int     nlon = 0, nlat = 0;
  int     kbegin = 0, kend = -1; 
  int     lbegin = 0, lend = -1;
  char    *remap_file = NULL;
  char    interp_method[STRING] = "conserve_order1";
  int     y_at_center = 0;
  int     grid_type = AGRID;
  int     nscalar=0, nvector=0, nvector2=0;
  int     option_index, c, i, n, m, l;
  char    entry[MAXSTRING];  /* should be long enough */
  char    txt[STRING];
  char    history[MAXATT];
  int     fill_missing = 0;
  unsigned int  finer_step = 0;

  Grid_config   *grid_in    = NULL;   /* store input grid  */
  Grid_config   *grid_out   = NULL;   /* store output grid */
  Field_config  *scalar_in  = NULL;   /* store input scalar data */
  Field_config  *scalar_out = NULL;   /* store output scalar data */
  Field_config  *u_in       = NULL;   /* store input vector u-component */
  Field_config  *v_in       = NULL;   /* store input vector v-component */
  Field_config  *u_out      = NULL;   /* store input vector u-component */
  Field_config  *v_out      = NULL;   /* store input vector v-component */
  File_config   *file_in    = NULL;   /* store input file information */
  File_config   *file_out   = NULL;   /* store output file information */
  File_config   *file2_in   = NULL;   /* store input file information */
  File_config   *file2_out  = NULL;   /* store output file information */
  Bound_config  *bound_T    = NULL;   /* store halo update information for T-cell*/
  Interp_config *interp     = NULL;   /* store remapping information */
  int save_weight_only      = 0;
  
  int errflg = (argc == 1);
  int fid;
  
  static struct option long_options[] = {
    {"input_mosaic",     required_argument, NULL, 'a'},
    {"output_mosaic",    required_argument, NULL, 'b'},
    {"input_dir",        required_argument, NULL, 'c'},
    {"output_dir",       required_argument, NULL, 'd'},
    {"input_file",       required_argument, NULL, 'e'},
    {"output_file",      required_argument, NULL, 'f'},
    {"remap_file",       required_argument, NULL, 'g'},
    {"test_case",        required_argument, NULL, 'i'},
    {"interp_method",    required_argument, NULL, 'j'},
    {"test_parameter",   required_argument, NULL, 'k'},
    {"symmetry",         no_argument,       NULL, 'l'},
    {"grid_type",        required_argument, NULL, 'm'},
    {"target_grid",      no_argument,       NULL, 'n'},
    {"finer_step",       required_argument, NULL, 'o'},
    {"fill_missing",     no_argument,       NULL, 'p'},
    {"nlon",             required_argument, NULL, 'q'},
    {"nlat",             required_argument, NULL, 'r'},
    {"scalar_field",     required_argument, NULL, 's'},
    {"check_conserve",   no_argument,       NULL, 't'},
    {"u_field",          required_argument, NULL, 'u'},
    {"v_field",          required_argument, NULL, 'v'},
    {"center_y",         no_argument,       NULL, 'y'},
    {"lonBegin",         required_argument, NULL, 'A'},
    {"lonEnd",           required_argument, NULL, 'B'},
    {"latBegin",         required_argument, NULL, 'C'},
    {"latEnd",           required_argument, NULL, 'D'},
    {"KlevelBegin",      required_argument, NULL, 'E'},
    {"KlevelEnd",        required_argument, NULL, 'F'},
    {"LstepBegin",       required_argument, NULL, 'G'},
    {"LstepEnd",         required_argument, NULL, 'H'},
    {"help",             no_argument,       NULL, 'h'},
    {0, 0, 0, 0},
  };  
  
  /* start parallel */
  mpp_init(&argc, &argv);
  mpp_domain_init();
  
  while ((c = getopt_long(argc, argv, "", long_options, &option_index)) != -1) {
    switch (c) {
    case 'a':
      mosaic_in  = optarg;
      break;
    case 'b':
      mosaic_out = optarg;
      break;
    case 'c':
      dir_in = optarg;
      break;
    case 'd':
      dir_out = optarg;
      break;
    case 'e':
      if(strlen(optarg) >= MAXSTRING) mpp_error("fregrid: the entry is not long for option -e");
      strcpy(entry, optarg);
      tokenize(entry, ",", STRING, NFILE, input_file, &nfiles);
      break;
    case 'f':
      if(strlen(optarg) >= MAXSTRING)  mpp_error("fregrid: the entry is not long for option -f");      
      strcpy(entry, optarg);
      tokenize(entry, ",", STRING, NFILE, output_file, &nfiles_out);
      break;
    case 'g':
      remap_file = optarg;
      break;
    case 's':
      if(strlen(optarg) >= MAXSTRING) mpp_error("fregrid: the entry is not long for option -s");      
      strcpy(entry, optarg);
      tokenize(entry, ",", STRING, NVAR, scalar_name, &nscalar);
      break;
    case 'u':
      if(strlen(optarg) >= MAXSTRING) mpp_error("fregrid: the entry is not long for option -u");      
      strcpy(entry, optarg);
      tokenize(entry, ",", STRING, NVAR, u_name, &nvector);
      break;        
    case 'v':
      if(strlen(optarg) >= MAXSTRING) mpp_error("fregrid: the entry is not long for option -v");      
      strcpy(entry, optarg);
      tokenize(entry, ",", STRING, NVAR, v_name, &nvector2);
      break;      
    case 'j':
      strcpy(interp_method, optarg);
      break;
    case 'i':
      test_case = optarg;
      break;
    case 'k':
      test_param = atof(optarg);
      break;      
    case 'l':
      opcode |= SYMMETRY;
      break;
    case 'm':
      if(strcmp(optarg, "AGRID") == 0)
	grid_type = AGRID;
      else if(strcmp(optarg, "BGRID") == 0)
	grid_type = BGRID;
      else
	mpp_error("fregrid: only AGRID and BGRID vector regridding are implmented, contact developer");
      break;
    case 'n':
      opcode |= TARGET;
      break;
    case 'o':
      finer_step = atoi(optarg);
      break;
    case 'p':
      fill_missing = 1;
      break;
    case 'q':
      nlon = atoi(optarg);
      break;
    case 'r':
      nlat = atoi(optarg);
      break;
    case 't':
      check_conserve = 1;
      break;
    case 'y':
      y_at_center = 1;
      break;
    case 'A':
      lonbegin = atof(optarg);
      break;
    case 'B':
      lonend = atof(optarg);
      break;
    case 'C':
      latbegin = atof(optarg);
      break;
    case 'D':
      latend = atof(optarg);
      break;
    case 'E':
      kbegin = atoi(optarg);
      break;
    case 'F':
      kend = atoi(optarg);
      break;
    case 'G':
      lbegin = atoi(optarg);
      break;
    case 'H':
      lend = atoi(optarg);
      break;
    case '?':
      errflg++;
      break;
    }
  }

  if (errflg) {
    char **u = usage;
    while (*u) { fprintf(stderr, "%s\n", *u); u++; }
    exit(2);
  }      
  /* check the arguments */
  if( !mosaic_in  ) mpp_error("fregrid: input_mosaic is not specified");
  if( !mosaic_out ) {
    if(nlon == 0 || nlat ==0 ) mpp_error("fregrid: when output_mosaic is not specified, nlon and nlat should be specified");
    if(lonend <= lonbegin) mpp_error("fregrid: when output_mosaic is not specified, lonEnd should be larger than lonBegin");
    if(latend <= latbegin) mpp_error("fregrid: when output_mosaic is not specified, latEnd should be larger than latBegin");
  }
  else {
    if(nlon !=0 || nlat != 0) mpp_error("fregrid: when output_mosaic is specified, nlon and nlat should not be specified");
  }
  
  if( nfiles == 0) {
    if(nvector > 0 || nscalar > 0 || nvector2 > 0)
      mpp_error("fregrid: when --input_file is not specified, --scalar_field, --u_field and --v_field should also not be specified");
    if(!remap_file) mpp_error("fregrid: when --input_file is not specified, remap_file must be specified to save weight information");
    save_weight_only = 1;
    if(mpp_pe()==mpp_root_pe())printf("NOTE: No input file specified in this run, no data file will be regridded "
				      "and only weight information is calculated.\n");
  }
  else if( nfiles == 1 || nfiles ==2) {
    if( nvector != nvector2 ) mpp_error("fregrid: number of fields specified in u_field must be the same as specified in v_field");
    if( nscalar+nvector==0 ) mpp_error("fregrid: both scalar_field and vector_field are not specified");
    /* when nvector =2 and nscalar=0, nfiles can be 2 otherwise nfiles must be 1 */
    if( nscalar && nfiles != 1 )
      mpp_error("fregrid: when scalar_field is specified, number of files must be 1");
    if( nfiles_out == 0 ) {
      for(i=0; i<nfiles; i++) strcpy(output_file[i], input_file[i]);
    }
    else if (nfiles_out != nfiles )
      mpp_error("fregrid:number of input file is not equal to number of output file");
  }
  else
    mpp_error("fregrid: number of input file should be 1 or 2");

  if(kbegin != 0 || kend != -1) { /* at least one of kbegin and kend is set */
    if(kbegin < 1 || kend < kbegin) mpp_error("fregrid:KlevelBegin should be a positive integer and no larger "
					      "than KlevelEnd when you want pick certain klevel");
  }
  if(lbegin != 0 || lend != -1) { /* at least one of lbegin and lend is set */
     if(lbegin < 1 || lend < lbegin) mpp_error("fregrid:LstepBegin should be a positive integer and no larger "
					      "than LstepEnd when you want pick certain Lstep");
  }
  
  if(nvector > 0) {
    opcode |= VECTOR;
    if(grid_type == AGRID)
      opcode |= AGRID;
    else if(grid_type == BGRID)
      opcode |= BGRID;
  }
  
  /* define history to be the history in the grid file */
  strcpy(history,argv[0]);

  for(i=1;i<argc;i++) {
    strcat(history, " ");
    if(strlen(argv[i]) > MAXENTRY) { /* limit the size of each entry, here we are assume the only entry that is longer than
					MAXENTRY= 256 is the option --scalar_field --u_field and v_field */
      if(strcmp(argv[i-1], "--scalar_field") && strcmp(argv[i-1], "--u_field") && strcmp(argv[i-1], "--v_field") )
	mpp_error("fregrid: the entry ( is not scalar_field, u_field, v_field ) is too long, need to increase parameter MAXENTRY");
      strcat(history, "(**please see the field list in this file**)" );
    }
    else
      strcat(history, argv[i]);
  }
  
  /* get the mosaic information of input and output mosaic*/
  fid = mpp_open(mosaic_in, MPP_READ);
  ntiles_in = mpp_get_dimlen(fid, "ntiles");
  mpp_close(fid);
  if(mosaic_out) {
    fid = mpp_open(mosaic_out, MPP_READ);
    ntiles_out = mpp_get_dimlen(fid, "ntiles");
    mpp_close(fid);
  }
  else
    ntiles_out = 1;

  if(!strcmp(interp_method, "conserve_order1") ) {
    if(mpp_pe() == mpp_root_pe())printf("****fregrid: first order conservative scheme will be used for regridding.\n");
    opcode |= CONSERVE_ORDER1;
  }
  else if(!strcmp(interp_method, "conserve_order2") ) {
    if(mpp_pe() == mpp_root_pe())printf("****fregrid: second order conservative scheme will be used for regridding.\n");
    opcode |= CONSERVE_ORDER2;
  }
  else if(!strcmp(interp_method, "bilinear") ) {
    if(mpp_pe() == mpp_root_pe())printf("****fregrid: bilinear remapping scheme will be used for regridding.\n");  
    opcode |= BILINEAR;
  }
  else
    mpp_error("fregrid: interp_method must be 'conserve_order1', 'conserve_order2' or 'bilinear'");

  if(test_case) {
    if(nfiles != 1) mpp_error("fregrid: when test_case is specified, nfiles should be 1");
    sprintf(output_file[0], "%s.%s.output", test_case, interp_method);
  }

  if(check_conserve) opcode |= CHECK_CONSERVE;
  
  if( opcode & BILINEAR ) {
    int ncontact;
    ncontact = read_mosaic_ncontacts(mosaic_in);
    if( nlon == 0 || nlat == 0) mpp_error("fregrid: when interp_method is bilinear, nlon and nlat should be specified");
    if(ntiles_in != 6) mpp_error("fregrid: when interp_method is bilinear, the input mosaic should be 6 tile cubic grid");
    if(ncontact !=12)  mpp_error("fregrid: when interp_method is bilinear, the input mosaic should be 12 contact cubic grid");
    if(mpp_npes() > 1) mpp_error("fregrid: parallel is not implemented for bilinear remapping");
  }
  else
    y_at_center = 1;


  /* memory allocation for data structure */
  grid_in   = (Grid_config *)malloc(ntiles_in *sizeof(Grid_config));
  grid_out  = (Grid_config *)malloc(ntiles_out*sizeof(Grid_config));
  bound_T   = (Bound_config *)malloc(ntiles_in *sizeof(Bound_config));
  interp    = (Interp_config *)malloc(ntiles_out*sizeof(Interp_config));
  get_input_grid( ntiles_in, grid_in, bound_T, mosaic_in, opcode );
  if(mosaic_out)
    get_output_grid_from_mosaic( ntiles_out, grid_out, mosaic_out, opcode );
  else
    get_output_grid_by_size(ntiles_out, grid_out, lonbegin, lonend, latbegin, latend,
			    nlon, nlat, finer_step, y_at_center, opcode);

   if(remap_file) set_remap_file(ntiles_out, mosaic_out, remap_file, interp, &opcode, save_weight_only);  
  
  if(!save_weight_only) {
    file_in   = (File_config *)malloc(ntiles_in *sizeof(File_config));
    file_out  = (File_config *)malloc(ntiles_out*sizeof(File_config));
 
    if(nfiles == 2) {
      file2_in   = (File_config *)malloc(ntiles_in *sizeof(File_config));
      file2_out  = (File_config *)malloc(ntiles_out*sizeof(File_config));
    }
    if(nscalar > 0) {
      scalar_in  = (Field_config *)malloc(ntiles_in *sizeof(Field_config));
      scalar_out = (Field_config *)malloc(ntiles_out *sizeof(Field_config));
    }
    if(nvector > 0) {
      u_in  = (Field_config *)malloc(ntiles_in *sizeof(Field_config));
      u_out = (Field_config *)malloc(ntiles_out *sizeof(Field_config));    
      v_in  = (Field_config *)malloc(ntiles_in *sizeof(Field_config));
      v_out = (Field_config *)malloc(ntiles_out *sizeof(Field_config));
    }
  
    set_mosaic_data_file(ntiles_in, mosaic_in, dir_in, file_in,  input_file[0]);
    set_mosaic_data_file(ntiles_out, mosaic_out, dir_out, file_out, output_file[0]);
    if(nfiles == 2) {
      set_mosaic_data_file(ntiles_in, mosaic_in, dir_in, file2_in,  input_file[1]);
      set_mosaic_data_file(ntiles_out, mosaic_out, dir_out, file2_out, output_file[1]);    
    }

    for(n=0; n<ntiles_in; n++) file_in[n].fid = mpp_open(file_in[n].name, MPP_READ);

    set_field_struct ( ntiles_in,   scalar_in,   nscalar, scalar_name[0], file_in);
    set_field_struct ( ntiles_out,  scalar_out,  nscalar, scalar_name[0], file_out);
    set_field_struct ( ntiles_in,   u_in,        nvector, u_name[0], file_in);
    set_field_struct ( ntiles_out,  u_out,       nvector, u_name[0], file_out);
    if(nfiles == 1) {
      set_field_struct ( ntiles_in,   v_in,        nvector, v_name[0], file_in);
      set_field_struct ( ntiles_out,  v_out,       nvector, v_name[0], file_out);
    }
    else {
      set_field_struct ( ntiles_in,   v_in,        nvector, v_name[0], file2_in);
      set_field_struct ( ntiles_out,  v_out,       nvector, v_name[0], file2_out);
    }

    get_input_metadata(ntiles_in, nfiles, file_in, file2_in, scalar_in, u_in, v_in, grid_in, kbegin, kend, lbegin, lend, opcode);

    set_output_metadata(ntiles_in, nfiles, file_in, file2_in, scalar_in, u_in, v_in,
			ntiles_out, file_out, file2_out, scalar_out, u_out, v_out, grid_out, history, tagname);
    /* when the interp_method specified through command line is CONSERVE_ORDER1, but the interp_method in the source file
       field attribute is CONSERVE_ORDER2, need to modify the interp_method value */
    if(opcode & CONSERVE_ORDER1) {
      for(l=0; l<nscalar; l++) {
	if(scalar_out->var[l].interp_method == CONSERVE_ORDER2) {
	  if(mpp_pe() == mpp_root_pe())printf("NOTE from fregrid: even though the interp_method specified through command line is "
					      "conserve_order1, the interp_method is reset to conserve_order2 because some fields in "
					      "the source data have interp_method attribute value conserve_order2");
	  opcode = opcode & ~CONSERVE_ORDER1;
	  opcode |= CONSERVE_ORDER2;
	  break;
	}
      }
    }
    if(opcode & CONSERVE_ORDER1) {
      for(l=0; l<nvector; l++) {
	if(u_out->var[l].interp_method == CONSERVE_ORDER2) {
	  if(mpp_pe() == mpp_root_pe())printf("NOTE from fregrid: even though the interp_method specified through command line is "
					      "conserve_order1, the interp_method is reset to conserve_order2 because some fields in "
					      "the source data have interp_method attribute value conserve_order2");
	  opcode = opcode & ~CONSERVE_ORDER1;
	  opcode |= CONSERVE_ORDER2;
	  break;
	}
      }
    }    
  }
  
  /* preparing for the interpolation, if remapping information exist, read it from remap_file,
     otherwise create the remapping information and write it to remap_file
  */
   if( opcode & BILINEAR ) /* bilinear interpolation from cubic to lalon */
     setup_bilinear_interp(ntiles_in, grid_in, ntiles_out, grid_out, interp, opcode );
   else
     setup_conserve_interp(ntiles_in, grid_in, ntiles_out, grid_out, interp, opcode);
  
   if(save_weight_only) {
     if(mpp_pe() == mpp_root_pe() ) {
       printf("NOTE: Successfully running fregrid and the following files which store weight information are generated.\n");
       for(n=0; n<ntiles_out; n++) {
	 printf("****%s\n", interp[n].remap_file);
       }
     }
     mpp_end();
     return 0;     
   }
  
   if(nscalar > 0) {
     get_field_attribute(ntiles_in, scalar_in);
     copy_field_attribute(ntiles_out, scalar_in, scalar_out);
   }
   
   if(nvector > 0) {
     get_field_attribute(ntiles_in, u_in);
     get_field_attribute(ntiles_in, v_in);
     copy_field_attribute(ntiles_out, u_in, u_out);
     copy_field_attribute(ntiles_out, v_in, v_out);
   }


  
   /* set time step to 1, only test scalar field now, nz need to be 1 */
   if(test_case) {
     if(nscalar != 1 || nvector != 0) mpp_error("fregrid: when test_case is specified, nscalar must be 1 and nvector must be 0");
     if(scalar_in->var->nz != 1) mpp_error("fregrid: when test_case is specified, number of vertical level must be 1");
     file_in->nt = 1;
     file_out->nt = 1;
   }
   
  /* Then doing the regridding */
  for(m=0; m<file_in->nt; m++) {
    int memsize, level_z, level_n, level_t;

    write_output_time(ntiles_out, file_out, m);
    if(nfiles > 1) write_output_time(ntiles_out, file2_out, m);
    
    /* first interp scalar variable */
    for(l=0; l<nscalar; l++) {
      if( !scalar_in->var[l].has_taxis && m>0) continue;
      level_t = m + scalar_in->var[l].lstart;
      /*--- to reduce memory usage, we are only do remapping for on horizontal level one time */
      for(level_n =0; level_n < scalar_in->var[l].nn; level_n++)
	for(level_z=scalar_in->var[l].kstart; level_z <= scalar_in->var[l].kend; level_z++)
	  {	    
	    if(test_case)
	      get_test_input_data(test_case, test_param, ntiles_in, scalar_in, grid_in, bound_T, opcode);
	    else
	      get_input_data(ntiles_in, scalar_in, grid_in, bound_T, l, level_z, level_n, level_t);
	    allocate_field_data(ntiles_out, scalar_out, grid_out);
	    if( opcode & BILINEAR ) 
	      do_scalar_bilinear_interp(interp, l, ntiles_in, grid_in, grid_out, scalar_in, scalar_out, finer_step, fill_missing);
	    else
	      do_scalar_conserve_interp(interp, l, ntiles_in, grid_in, ntiles_out, grid_out, scalar_in, scalar_out, opcode);
	    write_field_data(ntiles_out, scalar_out, grid_out, l, level_z, level_n, m);
	    if(scalar_out->var[l].interp_method == CONSERVE_ORDER2) {
	      for(n=0; n<ntiles_in; n++) {
		free(scalar_in[n].grad_x);
		free(scalar_in[n].grad_y);
		if(scalar_in[n].var[l].has_missing) free(scalar_in[n].grad_mask);
	      }
	    }
	    for(n=0; n<ntiles_in; n++) free(scalar_in[n].data);
	    for(n=0; n<ntiles_out; n++) free(scalar_out[n].data);
	  }
    }

    /* then interp vector field */
    for(l=0; l<nvector; l++) {
      if( !u_in[n].var[l].has_taxis && m>0) continue;
      level_t = m + u_in->var[l].lstart;
      get_input_data(ntiles_in, u_in, grid_in, bound_T, l, level_z, level_n, level_t);
      get_input_data(ntiles_in, v_in, grid_in, bound_T, l, level_z, level_n, level_t);
      allocate_field_data(ntiles_out, u_out, grid_out);
      allocate_field_data(ntiles_out, v_out, grid_out);
      if( opcode & BILINEAR )
	do_vector_bilinear_interp(interp, l, ntiles_in, grid_in, ntiles_out, grid_out, u_in, v_in, u_out, v_out, finer_step, fill_missing);
      else
	do_vector_conserve_interp(interp, l, ntiles_in, grid_in, ntiles_out, grid_out, u_in, v_in, u_out, v_out, opcode);
      
      write_field_data(ntiles_out, u_out, grid_out, l, level_z, level_n, m);
      write_field_data(ntiles_out, v_out, grid_out, l, level_z, level_n, m);
      for(n=0; n<ntiles_in; n++) {
	free(u_in[n].data);
	free(v_in[n].data);
      }
      for(n=0; n<ntiles_out; n++) {
	free(u_out[n].data);
	free(v_out[n].data);
      }      
    }
  }

  if(mpp_pe() == mpp_root_pe() ) {
    printf("Successfully running fregrid and the following output file are generated.\n");
    for(n=0; n<ntiles_out; n++) {
      mpp_close(file_out[n].fid);
      printf("****%s\n", file_out[n].name);
      if( nfiles > 1 ) {
	mpp_close(file2_out[n].fid);
	printf("****%s\n", file2_out[n].name);
      }
    }
  }
      
  mpp_end();
  return 0;
  
} /* end of main */
示例#19
0
void send_notification()
{
    CAResult_t res = get_network_type();
    if (CA_STATUS_OK != res)
    {
        return;
    }

    printf("\n=============================================\n");
    printf("Enter the URI like below....\n");
    printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
    printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
    printf("uri : ");

    char uri[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
    {
        return;
    }

    printf("\n=============================================\n");
    printf("\tselect message type\n");
    printf("CON     : 0\n");
    printf("NON     : 1\n");
    printf("ACK     : 2\n");
    printf("RESET   : 3\n");

    printf("select : ");

    char messageTypeBuf[MAX_BUF_LEN] = { 0 };
    if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
    {
        return;
    }

    int messageType = messageTypeBuf[0] - '0';

    switch(messageType)
    {
        case 0:
                printf("CONFIRM messagetype is selected\n");
                break;
        case 1:
                printf("NONCONFIRM messagetype is selected\n");
                break;
        default:
                printf("Invalid Selection\n");
                return;
    }

    CATransportFlags_t flags;
    addressSet_t address = {};
    parse_coap_uri(uri, &address, &flags);

    // create remote endpoint
    CAEndpoint_t *endpoint = NULL;
    res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
    if (CA_STATUS_OK != res)
    {
        printf("Create remote endpoint error, error code: %d\n", res);
        return;
    }

    // create token
    CAToken_t token = NULL;
    uint8_t tokenLength = CA_MAX_TOKEN_LEN;

    res = CAGenerateToken(&token, tokenLength);
    if ((CA_STATUS_OK != res) || (!token))
    {
        printf("Token generate error!!\n");
        CADestroyEndpoint(endpoint);
        return;
    }

    printf("Generated token %s\n", token);

    CAInfo_t requestData = { 0 };
    requestData.token = token;
    requestData.tokenLength = tokenLength;
    requestData.payload = (CAPayload_t) "TempNotificationData";
    requestData.payloadSize = strlen((const char *) requestData.payload);
    requestData.type = messageType;
    requestData.resourceUri = (CAURI_t)uri;

    CARequestInfo_t requestInfo = { 0 };
    requestInfo.method = CA_GET;
    requestInfo.info = requestData;

    // send notification
    res = CASendRequest(endpoint, &requestInfo);
    if (CA_STATUS_OK != res)
    {
        printf("Send notification error, error code: %d\n", res);
    }
    else
    {
        printf("Send notification success\n");
    }

    // destroy token
    CADestroyToken(token);
    // destroy remote endpoint
    CADestroyEndpoint(endpoint);

    printf("\n=============================================\n");
}