void CBacnetUserConfig::OnBnClickedButtonUserDelete()
{
	// TODO: Add your control notification handler code here
	if((m_slected_item<0) || (m_slected_item >= BAC_USER_LOGIN_COUNT ))
		return;

	memset(&m_user_login_data.at(m_slected_item),0,sizeof(Str_userlogin_point));



	int temp_invoke_id = -1;
	int send_status = true;
	int	resend_count = 0;
	for (int z=0;z<3;z++)
	{
		do 
		{
			resend_count ++;
			if(resend_count>5)
			{
				send_status = false;
				break;
			}
			temp_invoke_id = WritePrivateData(g_bac_instance,WRITEUSER_T3000,m_slected_item,m_slected_item);

			Sleep(SEND_COMMAND_DELAY_TIME);
		} while (g_invoke_id<0);
		if(send_status)
		{
			Sleep(1000);
			if(tsm_invoke_id_free(temp_invoke_id))
			{
				ok_button_stage = 0;
				PostMessage(WM_REFRESH_BAC_USER_NAME_LIST,NULL,NULL);
				Enable_Window_Stage(HIDE_ALL);
				MessageBox(_T("Delete success!"));
				return;
			}
			else
				continue;
		}
	}

	MessageBox(_T("Timeout!Please try again!"));

}
示例#2
0
static void Wait_For_Answer_Or_Timeout(
    unsigned timeout_ms,
    waitAction action)
{
    /* Wait for timeout, failure, or success */
    time_t last_seconds = time(NULL);
    time_t timeout_seconds = (apdu_timeout() / 1000) * apdu_retries();
    time_t elapsed_seconds = 0;
    uint16_t pdu_len = 0;
    BACNET_ADDRESS src = { 0 }; /* address where message came from */
    uint8_t Rx_Buf[MAX_MPDU] = { 0 };

    while (true) {
        time_t current_seconds = time(NULL);

        /* If error was detected then bail out */
        if (Error_Detected) {
            LogError("Some other error occurred");
            break;
        }

        if (elapsed_seconds > timeout_seconds) {
            LogError("APDU Timeout");
            break;
        }

        /* Process PDU if one comes in */
        pdu_len = datalink_receive(&src, &Rx_Buf[0], MAX_MPDU, timeout_ms);
        if (pdu_len) {
            npdu_handler(&src, &Rx_Buf[0], pdu_len);
        }

        /* at least one second has passed */
        if (current_seconds != last_seconds) {
            tsm_timer_milliseconds(((current_seconds - last_seconds) * 1000));
        }

        if (action == waitAnswer) {
            /* Response was received. Exit. */
            if (tsm_invoke_id_free(Request_Invoke_ID)) {
                break;
            } else if (tsm_invoke_id_failed(Request_Invoke_ID)) {
                LogError("TSM Timeout!");
                tsm_free_invoke_id(Request_Invoke_ID);
                break;
            }
        } else if (action == waitBind) {
            if (address_bind_request(Target_Device_Object_Instance,
                    &Target_Max_APDU, &Target_Address)) {
                break;
            }
        } else {
            LogError("Invalid waitAction requested");
            break;
        }

        /* Keep track of time */
        elapsed_seconds += (current_seconds - last_seconds);
        last_seconds = current_seconds;
    }
}
示例#3
0
int main(
    int argc,
    char *argv[])
{
    BACNET_ADDRESS src = {
        0
    };  /* address where message came from */
    uint16_t pdu_len = 0;
    unsigned timeout = 100;     /* milliseconds */
    unsigned max_apdu = 0;
    time_t elapsed_seconds = 0;
    time_t last_seconds = 0;
    time_t current_seconds = 0;
    time_t timeout_seconds = 0;
    uint8_t invoke_id = 0;
    bool found = false;
    DATABLOCK NewData;
    int iCount = 0;
    int iType = 0;
    int iKey;

    if (((argc != 2) && (argc != 3)) || ((argc >= 2) &&
            (strcmp(argv[1], "--help") == 0))) {
        printf("%s\n", argv[0]);
        printf("Usage: %s server local-device-instance\r\n       or\r\n"
            "       %s remote-device-instance\r\n",
            filename_remove_path(argv[0]), filename_remove_path(argv[0]));
        if ((argc > 1) && (strcmp(argv[1], "--help") == 0)) {
            printf("\r\nServer mode:\r\n\r\n"
                "local-device-instance determins the device id of the application\r\n"
                "when running as the server end of a test set up.\r\n\r\n"
                "Non server:\r\n\r\n"
                "remote-device-instance indicates the device id of the server\r\n"
                "instance of the application.\r\n"
                "The non server application will write a series of blocks to the\r\n"
                "server and then retrieve them for display locally\r\n"
                "First it writes all 8 blocks plus a 9th which should trigger\r\n"
                "an out of range error response. Then it reads all the blocks\r\n"
                "including the ninth and finally it repeats the read operation\r\n"
                "with some deliberate errors to trigger a nack response\r\n");
        }
        return 0;
    }
    /* decode the command line parameters */
    if (_stricmp(argv[1], "server") == 0)
        Target_Mode = 1;
    else
        Target_Mode = 0;

    Target_Device_Object_Instance = strtol(argv[1 + Target_Mode], NULL, 0);

    if (Target_Device_Object_Instance > BACNET_MAX_INSTANCE) {
        fprintf(stderr, "device-instance=%u - it must be less than %u\r\n",
            Target_Device_Object_Instance, BACNET_MAX_INSTANCE);
        return 1;
    }

    /* setup my info */
    if (Target_Mode)
        Device_Set_Object_Instance_Number(Target_Device_Object_Instance);
    else
        Device_Set_Object_Instance_Number(BACNET_MAX_INSTANCE);

    address_init();
    Init_Service_Handlers();
    dlenv_init();
    atexit(datalink_cleanup);
    /* configure the timeout values */
    last_seconds = time(NULL);
    timeout_seconds = (apdu_timeout() / 1000) * apdu_retries();

    if (Target_Mode) {
        printf("Entering server mode. press q to quit program\r\n\r\n");

        for (;;) {
            /* increment timer - exit if timed out */
            current_seconds = time(NULL);
            if (current_seconds != last_seconds) {
            }

            /* returns 0 bytes on timeout */
            pdu_len = datalink_receive(&src, &Rx_Buf[0], MAX_MPDU, timeout);

            /* process */
            if (pdu_len) {
                npdu_handler(&src, &Rx_Buf[0], pdu_len);
            }
            /* at least one second has passed */
            if (current_seconds != last_seconds) {
                putchar('.');   /* Just to show that time is passing... */
                last_seconds = current_seconds;
                tsm_timer_milliseconds(((current_seconds -
                            last_seconds) * 1000));
            }

            if (_kbhit()) {
                iKey = toupper(_getch());
                if (iKey == 'Q') {
                    printf("\r\nExiting program now\r\n");
                    exit(0);
                }
            }
        }
    } else {

        /* try to bind with the device */
        found =
            address_bind_request(Target_Device_Object_Instance, &max_apdu,
            &Target_Address);
        if (!found) {
            Send_WhoIs(Target_Device_Object_Instance,
                Target_Device_Object_Instance);
        }
        /* loop forever */
        for (;;) {
            /* increment timer - exit if timed out */
            current_seconds = time(NULL);

            /* returns 0 bytes on timeout */
            pdu_len = datalink_receive(&src, &Rx_Buf[0], MAX_MPDU, timeout);

            /* process */
            if (pdu_len) {
                npdu_handler(&src, &Rx_Buf[0], pdu_len);
            }
            /* at least one second has passed */
            if (current_seconds != last_seconds)
                tsm_timer_milliseconds(((current_seconds -
                            last_seconds) * 1000));
            if (Error_Detected)
                break;
            /* wait until the device is bound, or timeout and quit */
            if (!found)
                found =
                    address_bind_request(Target_Device_Object_Instance,
                    &max_apdu, &Target_Address);
            if (found) {
                if (invoke_id == 0) {   /* Safe to send a new request */
                    switch (iType) {
                        case 0:        /* Write blocks to server */
                            NewData.cMyByte1 = iCount;
                            NewData.cMyByte2 = 255 - iCount;
                            NewData.fMyReal = (float) iCount;
                            strcpy((char*)NewData.sMyString, "Test Data - [x]");
                            NewData.sMyString[13] = 'a' + iCount;
                            printf("Sending block %d\n", iCount);
                            invoke_id =
                                Send_Private_Transfer_Request
                                (Target_Device_Object_Instance,
                                BACNET_VENDOR_ID, 1, iCount, &NewData);
                            break;

                        case 1:        /* Read blocks from server */
                            printf("Requesting block %d\n", iCount);
                            invoke_id =
                                Send_Private_Transfer_Request
                                (Target_Device_Object_Instance,
                                BACNET_VENDOR_ID, 0, iCount, &NewData);
                            break;

                        case 2:        /* Generate some error responses */
                            switch (iCount) {
                                case 0:        /* Bad service number i.e. 2 */
                                case 2:
                                case 4:
                                case 6:
                                case 8:
                                    printf
                                        ("Requesting block %d with bad service number\n",
                                        iCount);
                                    invoke_id =
                                        Send_Private_Transfer_Request
                                        (Target_Device_Object_Instance,
                                        BACNET_VENDOR_ID, 2, iCount, &NewData);
                                    break;

                                case 1:        /* Bad vendor ID number */
                                case 3:
                                case 5:
                                case 7:
                                    printf
                                        ("Requesting block %d with invalid Vendor ID\n",
                                        iCount);
                                    invoke_id =
                                        Send_Private_Transfer_Request
                                        (Target_Device_Object_Instance,
                                        BACNET_VENDOR_ID + 1, 0, iCount,
                                        &NewData);
                                    break;
                            }

                            break;
                    }
                } else if (tsm_invoke_id_free(invoke_id)) {
                    if (iCount != MY_MAX_BLOCK) {
                        iCount++;
                        invoke_id = 0;
                    } else {
                        iType++;
                        iCount = 0;
                        invoke_id = 0;

                        if (iType > 2)
                            break;
                    }
                } else if (tsm_invoke_id_failed(invoke_id)) {
                    fprintf(stderr, "\rError: TSM Timeout!\r\n");
                    tsm_free_invoke_id(invoke_id);
                    Error_Detected = true;
                    /* try again or abort? */
                    break;
                }
            } else {
                /* increment timer - exit if timed out */
                elapsed_seconds += (current_seconds - last_seconds);
                if (elapsed_seconds > timeout_seconds) {
                    printf("\rError: APDU Timeout!\r\n");
                    Error_Detected = true;
                    break;
                }
            }
            /* keep track of time for next check */
            last_seconds = current_seconds;
        }
    }
    if (Error_Detected)
        return 1;
    return 0;
}
示例#4
0
int write_bacnet_obj(bacnet_device_t *device, int obj_index, char *value)
{
    uint8_t rx_buf[MAX_MPDU] = {0};
    BACNET_ADDRESS src = {
        0
    };  /* address where message came from */
    uint16_t pdu_len = 0;
    unsigned timeout = 500;     /* milliseconds */
    unsigned max_apdu = 0;
    time_t elapsed_seconds = 0;
    time_t last_seconds = 0;
    time_t current_seconds = 0;
    time_t timeout_seconds = 0;
    int status = 0, i;

    // Set Property Tag
    BACNET_APPLICATION_TAG property_tag;
    if (device -> obj_types[obj_index] == OBJECT_BINARY_VALUE)
        property_tag = BACNET_APPLICATION_TAG_ENUMERATED;
    else
        property_tag = BACNET_APPLICATION_TAG_REAL;
    BACNET_APPLICATION_DATA_VALUE target_value;

    for (i = 0; i < MAX_PROPERTY_VALUES; i++) {
        target_value.context_specific = false;

        if (property_tag >= MAX_BACNET_APPLICATION_TAG) {
            fprintf(stderr, "Error: tag=%u - it must be less than %u\r\n",
                    property_tag, MAX_BACNET_APPLICATION_TAG);
            return 1;
        }
        status =
            bacapp_parse_application_data(property_tag, value,
                                          &target_value);
        if (!status) {
            printf("Error: unable to parse the tag value\r\n");
            return 1;
        }
        target_value.next = NULL;
        break;
    }

    /* configure the timeout values */
    last_seconds = time(NULL);
    timeout_seconds = (apdu_timeout() / 1000) * apdu_retries();

    /* try to bind with the device */
    found =
        address_bind_request(device -> instance, &max_apdu, &target_address);

    if (!found) {
        Send_WhoIs(device -> instance, device -> instance);
    }
    /* loop forever */
    request_invoke_id = 0;
    while (1) {
        /* increment timer - exit if timed out */
        current_seconds = time(NULL);

        /* at least one second has passed */
        if (current_seconds != last_seconds)
            tsm_timer_milliseconds((uint16_t) ((current_seconds -
                                                last_seconds) * 1000));
        if (error_detected)
            break;
        /* wait until the device is bound, or timeout and quit */
        if (!found) {
            found =
                address_bind_request(device -> instance, &max_apdu,
                                     &target_address);
        }
        if (found) {
            if (request_invoke_id == 0) {
                printf("request invoke set\n");
                write_acked = 0;
                request_invoke_id =
                    Send_Write_Property_Request(device -> instance,
                                                device -> obj_types[obj_index], device -> obj_ids[obj_index],
                                                PROP_PRESENT_VALUE, &target_value,
                                                MESSAGE_PRIORITY_NORMAL, -1);
            } else if (tsm_invoke_id_free(request_invoke_id))
                break;
            else if (tsm_invoke_id_failed(request_invoke_id)) {
                fprintf(stderr, "\rError: TSM Timeout!\r\n");
                tsm_free_invoke_id(request_invoke_id);
                error_detected = true;
                break;
            }
        } else {
            /* increment timer - exit if timed out */
            elapsed_seconds += (current_seconds - last_seconds);
            if (elapsed_seconds > timeout_seconds) {
                error_detected = true;
                printf("\rError: APDU Timeout!\r\n");
                break;
            }
        }

        /* returns 0 bytes on timeout */
        pdu_len = datalink_receive(&src, &rx_buf[0], MAX_MPDU, timeout);

        /* process */
        if (pdu_len) {
            npdu_handler(&src, &rx_buf[0], pdu_len);
        }

        /* keep track of time for next check */
        last_seconds = current_seconds;
    }
    if (error_detected)
    {
        error_detected = 0;
        return 1;
    }
    return 0;
}
示例#5
0
int publish_data(adapter_t *adapter)
{
    static uint8_t rx_buf[MAX_MPDU] = {0};
    bacnet_context_t *context = (bacnet_context_t*) (adapter -> context);
    bacnet_device_t *device;
    time_t current_seconds, elapsed_seconds = 0;
    int pdu_len;
    char *time_str, *node_id;
    time_t last_seconds,timeout_seconds;
    unsigned timeout = 100;
    BACNET_ADDRESS  src = { 0 };
    unsigned max_apdu = 0;
    mio_stanza_t *item;
    mio_response_t *publish_response;
    for (device = context -> node_devices; device; device = device -> nodemap.next)
    {
        time_str = mio_timestamp_create();
        item = mio_pubsub_item_data_new(adapter -> connection);
        node_id = device -> node_id;

        last_seconds = time(NULL);
        timeout_seconds = (apdu_timeout() / 1000) * apdu_retries();
        //if (!found)
        found =
            address_bind_request(device -> instance, &max_apdu,
                                 &target_address);
        if (!found)
        {
            Send_WhoIs(device -> instance, device -> instance);
        }
        while (!found)
        {
            current_seconds = time(NULL);
            if (current_seconds != last_seconds)
                tsm_timer_milliseconds((uint16_t) ((current_seconds -
                                                    last_seconds) * 1000));
            if (!found)
            {
                found =
                    address_bind_request(device -> instance,
                                         &max_apdu,&target_address);
            }
            if (!found)
            {
                elapsed_seconds += (current_seconds - last_seconds);
                if (elapsed_seconds > timeout_seconds) {
                    printf("\rError: APDU Timeout!\r\n");
                    return 1;
                }
            }
            pdu_len = datalink_receive(&src, &rx_buf[0], MAX_MPDU,timeout);
            if (pdu_len) {
                npdu_handler(&src, &rx_buf[0], pdu_len);
            }
            last_seconds = current_seconds;
        }
        int i;
        printf("n_objects %d\n", device -> n_objects);
        for ( i = 0; i < device -> n_objects; i++)
        {
            request_invoke_id = 0;
            while(TRUE)
            {
                printf("true\n");
                if (found)
                {
                    if (request_invoke_id == 0)
                    {
                        request_invoke_id =
                            Send_Read_Property_Request(
                                device->instance, device -> obj_types[i],
                                device -> obj_ids[i], 85,
                                -1);
                    } else if (tsm_invoke_id_free(request_invoke_id))
                        break;
                    else if (tsm_invoke_id_failed(request_invoke_id))
                    {
                        fprintf(stderr,"\rError: TSM Timeout!\r\n");
                        tsm_free_invoke_id(request_invoke_id);
                        return 1;
                    }
                }
                pdu_len = datalink_receive(&src, &rx_buf[0], MAX_MPDU,timeout);
                if (pdu_len) {
                    npdu_handler(&src, &rx_buf[0], pdu_len);
                }
                last_seconds = current_seconds;
            }
            if (error_detected)
            {
                error_detected = 0;
                return 1;
            } else
            {
                if (strcmp(value,"active") == 0)
                    mio_item_transducer_value_add(item, NULL, device -> obj_names[i] , "1", value,  time_str);
                else if (strcmp(value,"inactive") == 0)
                    mio_item_transducer_value_add(item, NULL, device -> obj_names[i] , "0",value,  time_str);
                else
                    mio_item_transducer_value_add(item, NULL, device -> obj_names[i] , value, value, time_str);
            }

        }
        publish_response = mio_response_new();
        while (adapter -> connection -> xmpp_conn -> state != XMPP_STATE_CONNECTED)
            usleep(1000);
        mio_item_publish_data(adapter -> connection,item,node_id,publish_response);
        free(time_str);
        mio_response_print(publish_response);
        mio_response_free(publish_response);
        mio_stanza_free(item);
    }
    return 0;
}
示例#6
0
void handler_cov_task(
    void)
{
    static int index = 0;
    BACNET_OBJECT_TYPE object_type = MAX_BACNET_OBJECT_TYPE;
    uint32_t object_instance = 0;
    bool status = false;
    bool send = false;
    BACNET_PROPERTY_VALUE value_list[2];
    /* states for transmitting */
    static enum {
        COV_STATE_IDLE = 0,
        COV_STATE_MARK,
        COV_STATE_CLEAR,
        COV_STATE_FREE,
        COV_STATE_SEND
    } cov_task_state = COV_STATE_IDLE;

    switch (cov_task_state) {
        case COV_STATE_IDLE:
            index = 0;
            cov_task_state = COV_STATE_MARK;
            break;
        case COV_STATE_MARK:
            /* mark any subscriptions where the value has changed */
            if (COV_Subscriptions[index].flag.valid) {
                object_type = (BACNET_OBJECT_TYPE)
                    COV_Subscriptions[index].monitoredObjectIdentifier.type;
                object_instance =
                    COV_Subscriptions[index].
                    monitoredObjectIdentifier.instance;
                status = Device_COV(object_type, object_instance);
                if (status) {
                    COV_Subscriptions[index].flag.send_requested = true;
#if PRINT_ENABLED
                    fprintf(stderr, "COVtask: Marking...\n");
#endif
                }
            }
            index++;
            if (index >= MAX_COV_SUBCRIPTIONS) {
                index = 0;
                cov_task_state = COV_STATE_CLEAR;
            }
            break;
        case COV_STATE_CLEAR:
            /* clear the COV flag after checking all subscriptions */
            if ((COV_Subscriptions[index].flag.valid) &&
                (COV_Subscriptions[index].flag.send_requested)) {
                object_type = (BACNET_OBJECT_TYPE)
                    COV_Subscriptions[index].monitoredObjectIdentifier.type;
                object_instance =
                    COV_Subscriptions[index].
                    monitoredObjectIdentifier.instance;
                Device_COV_Clear(object_type, object_instance);
            }
            index++;
            if (index >= MAX_COV_SUBCRIPTIONS) {
                index = 0;
                cov_task_state = COV_STATE_FREE;
            }
            break;
        case COV_STATE_FREE:
            /* confirmed notification house keeping */
            if ((COV_Subscriptions[index].flag.valid) &&
                (COV_Subscriptions[index].flag.issueConfirmedNotifications) &&
                (COV_Subscriptions[index].invokeID)) {
                if (tsm_invoke_id_free(COV_Subscriptions[index].invokeID)) {
                    COV_Subscriptions[index].invokeID = 0;
                } else
                    if (tsm_invoke_id_failed(COV_Subscriptions
                        [index].invokeID)) {
                    tsm_free_invoke_id(COV_Subscriptions[index].invokeID);
                    COV_Subscriptions[index].invokeID = 0;
                }
            }
            index++;
            if (index >= MAX_COV_SUBCRIPTIONS) {
                index = 0;
                cov_task_state = COV_STATE_SEND;
            }
            break;
        case COV_STATE_SEND:
            /* send any COVs that are requested */
            if ((COV_Subscriptions[index].flag.valid) &&
                (COV_Subscriptions[index].flag.send_requested)) {
                send = true;
                if (COV_Subscriptions[index].flag.issueConfirmedNotifications) {
                    if (COV_Subscriptions[index].invokeID != 0) {
                        /* already sending */
                        send = false;
                    }
                    if (!tsm_transaction_available()) {
                        /* no transactions available - can't send now */
                        send = false;
                    }
                }
                if (send) {
                    object_type = (BACNET_OBJECT_TYPE)
                        COV_Subscriptions[index].
                        monitoredObjectIdentifier.type;
                    object_instance =
                        COV_Subscriptions[index].
                        monitoredObjectIdentifier.instance;
#if PRINT_ENABLED
                    fprintf(stderr, "COVtask: Sending...\n");
#endif
                    /* configure the linked list for the two properties */
                    value_list[0].next = &value_list[1];
                    value_list[1].next = NULL;
                    (void) Device_Encode_Value_List(object_type,
                        object_instance, &value_list[0]);
                    status =
                        cov_send_request(&COV_Subscriptions[index],
                        &value_list[0]);
                    if (status) {
                        COV_Subscriptions[index].flag.send_requested = false;
                    }
                }
            }
            index++;
            if (index >= MAX_COV_SUBCRIPTIONS) {
                index = 0;
                cov_task_state = COV_STATE_IDLE;
            }
            break;
        default:
            index = 0;
            cov_task_state = COV_STATE_IDLE;
            break;
    }
}
示例#7
0
int main(
    int argc,
    char *argv[])
{
    BACNET_ADDRESS src = {
        0
    };  /* address where message came from */
    uint16_t pdu_len = 0;
    unsigned timeout = 100;     /* milliseconds */
    unsigned max_apdu = 0;
    time_t elapsed_seconds = 0;
    time_t last_seconds = 0;
    time_t current_seconds = 0;
    time_t timeout_seconds = 0;
    bool found = false;
    char *value_string = NULL;
    bool status = false;
    int args_remaining = 0, tag_value_arg = 0, i = 0;
    BACNET_APPLICATION_TAG property_tag;
    uint8_t context_tag = 0;
    int argi = 0;

    /* print help if requested */
    for (argi = 1; argi < argc; argi++) {
        if (strcmp(argv[argi], "--help") == 0) {
            print_usage(filename_remove_path(argv[0]));
            print_help(filename_remove_path(argv[0]));
            return 0;
        }
        if (strcmp(argv[argi], "--version") == 0) {
            printf("%s %s\n",
                filename_remove_path(argv[0]),
                BACNET_VERSION_TEXT);
            printf("Copyright (C) 2014 by Steve Karg\n"
                "This is free software; see the source for copying conditions.\n"
                "There is NO warranty; not even for MERCHANTABILITY or\n"
                "FITNESS FOR A PARTICULAR PURPOSE.\n");
            return 0;
        }
    }
    if (argc < 9) {
        print_usage(filename_remove_path(argv[0]));
        return 0;
    }
    /* decode the command line parameters */
    Target_Device_Object_Instance = strtol(argv[1], NULL, 0);
    Target_Object_Type = strtol(argv[2], NULL, 0);
    Target_Object_Instance = strtol(argv[3], NULL, 0);
    Target_Object_Property = strtol(argv[4], NULL, 0);
    Target_Object_Property_Priority = (uint8_t) strtol(argv[5], NULL, 0);
    Target_Object_Property_Index = strtol(argv[6], NULL, 0);
    if (Target_Object_Property_Index == -1)
        Target_Object_Property_Index = BACNET_ARRAY_ALL;
    if (Target_Device_Object_Instance > BACNET_MAX_INSTANCE) {
        fprintf(stderr, "device-instance=%u - it must be less than %u\n",
            Target_Device_Object_Instance, BACNET_MAX_INSTANCE + 1);
        return 1;
    }
    if (Target_Object_Type > MAX_BACNET_OBJECT_TYPE) {
        fprintf(stderr, "object-type=%u - it must be less than %u\n",
            Target_Object_Type, MAX_BACNET_OBJECT_TYPE + 1);
        return 1;
    }
    if (Target_Object_Instance > BACNET_MAX_INSTANCE) {
        fprintf(stderr, "object-instance=%u - it must be less than %u\n",
            Target_Object_Instance, BACNET_MAX_INSTANCE + 1);
        return 1;
    }
    if (Target_Object_Property > MAX_BACNET_PROPERTY_ID) {
        fprintf(stderr, "property=%u - it must be less than %u\n",
            Target_Object_Property, MAX_BACNET_PROPERTY_ID + 1);
        return 1;
    }
    args_remaining = (argc - 7);
    for (i = 0; i < MAX_PROPERTY_VALUES; i++) {
        tag_value_arg = 7 + (i * 2);
        /* special case for context tagged values */
        if (toupper(argv[tag_value_arg][0]) == 'C') {
            context_tag = (uint8_t) strtol(&argv[tag_value_arg][1], NULL, 0);
            tag_value_arg++;
            args_remaining--;
            Target_Object_Property_Value[i].context_tag = context_tag;
            Target_Object_Property_Value[i].context_specific = true;
        } else {
            Target_Object_Property_Value[i].context_specific = false;
        }
        property_tag = strtol(argv[tag_value_arg], NULL, 0);
        args_remaining--;
        if (args_remaining <= 0) {
            fprintf(stderr, "Error: not enough tag-value pairs\n");
            return 1;
        }
        value_string = argv[tag_value_arg + 1];
        args_remaining--;
        /* printf("tag[%d]=%u value[%d]=%s\n",
           i, property_tag, i, value_string); */
        if (property_tag >= MAX_BACNET_APPLICATION_TAG) {
            fprintf(stderr, "Error: tag=%u - it must be less than %u\n",
                property_tag, MAX_BACNET_APPLICATION_TAG);
            return 1;
        }
        status =
            bacapp_parse_application_data(property_tag, value_string,
            &Target_Object_Property_Value[i]);
        if (!status) {
            /* FIXME: show the expected entry format for the tag */
            fprintf(stderr, "Error: unable to parse the tag value\n");
            return 1;
        }
        Target_Object_Property_Value[i].next = NULL;
        if (i > 0) {
            Target_Object_Property_Value[i - 1].next =
                &Target_Object_Property_Value[i];
        }
        if (args_remaining <= 0) {
            break;
        }
    }
    if (args_remaining > 0) {
        fprintf(stderr, "Error: Exceeded %d tag-value pairs.\n",
            MAX_PROPERTY_VALUES);
        return 1;
    }
    /* setup my info */
    Device_Set_Object_Instance_Number(BACNET_MAX_INSTANCE);
    address_init();
    Init_Service_Handlers();
    dlenv_init();
    atexit(datalink_cleanup);
    /* configure the timeout values */
    last_seconds = time(NULL);
    timeout_seconds = (apdu_timeout() / 1000) * apdu_retries();
    /* try to bind with the device */
    found =
        address_bind_request(Target_Device_Object_Instance, &max_apdu,
        &Target_Address);
    if (!found) {
        Send_WhoIs(Target_Device_Object_Instance,
            Target_Device_Object_Instance);
    }
    /* loop forever */
    for (;;) {
        /* increment timer - exit if timed out */
        current_seconds = time(NULL);

        /* at least one second has passed */
        if (current_seconds != last_seconds)
            tsm_timer_milliseconds((uint16_t) ((current_seconds -
                        last_seconds) * 1000));
        if (Error_Detected)
            break;
        /* wait until the device is bound, or timeout and quit */
        if (!found) {
            found =
                address_bind_request(Target_Device_Object_Instance, &max_apdu,
                &Target_Address);
        }
        if (found) {
            if (Request_Invoke_ID == 0) {
                Request_Invoke_ID =
                    Send_Write_Property_Request(Target_Device_Object_Instance,
                    Target_Object_Type, Target_Object_Instance,
                    Target_Object_Property, &Target_Object_Property_Value[0],
                    Target_Object_Property_Priority,
                    Target_Object_Property_Index);
            } else if (tsm_invoke_id_free(Request_Invoke_ID))
                break;
            else if (tsm_invoke_id_failed(Request_Invoke_ID)) {
                fprintf(stderr, "\rError: TSM Timeout!\n");
                tsm_free_invoke_id(Request_Invoke_ID);
                Error_Detected = true;
                /* try again or abort? */
                break;
            }
        } else {
            /* increment timer - exit if timed out */
            elapsed_seconds += (current_seconds - last_seconds);
            if (elapsed_seconds > timeout_seconds) {
                Error_Detected = true;
                printf("\rError: APDU Timeout!\n");
                break;
            }
        }

        /* returns 0 bytes on timeout */
        pdu_len = datalink_receive(&src, &Rx_Buf[0], MAX_MPDU, timeout);

        /* process */
        if (pdu_len) {
            npdu_handler(&src, &Rx_Buf[0], pdu_len);
        }

        /* keep track of time for next check */
        last_seconds = current_seconds;
    }
    if (Error_Detected)
        return 1;
    return 0;
}
示例#8
0
int main(
    int argc,
    char *argv[])
{
    BACNET_ADDRESS src = {
        0
    };  /* address where message came from */
    uint16_t pdu_len = 0;
    unsigned timeout = 100;     /* milliseconds */
    unsigned max_apdu = 0;
    time_t elapsed_seconds = 0;
    time_t last_seconds = 0;
    time_t current_seconds = 0;
    time_t timeout_seconds = 0;
    uint8_t invoke_id = 0;
    bool found = false;

    if (argc < 3) {
        printf("Usage: %s device-instance state timeout [password]\r\n"
            "Send BACnet DeviceCommunicationControl service to device.\r\n"
            "\r\n" "The device-instance can be 0 to %d.\r\n"
            "Possible state values:\r\n" "  0=enable\r\n" "  1=disable\r\n"
            "  2=disable-initiation\r\n"
            "The timeout can be 0 for infinite, or a value in minutes for disable.\r\n"
            "The optional password is a character string of 1 to 20 characters.\r\n"
            "Use BACNET_IFACE environment variable for the interface\r\n",
            filename_remove_path(argv[0]), BACNET_MAX_INSTANCE - 1);
        return 0;
    }
    /* decode the command line parameters */
    Target_Device_Object_Instance = strtol(argv[1], NULL, 0);
    Communication_State = (uint16_t) strtol(argv[2], NULL, 0);
    Communication_Timeout_Minutes = (uint16_t) strtol(argv[3], NULL, 0);
    /* optional password */
    if (argc > 4)
        Communication_Password = argv[4];

    if (Target_Device_Object_Instance >= BACNET_MAX_INSTANCE) {
        fprintf(stderr, "device-instance=%u - it must be less than %u\r\n",
            Target_Device_Object_Instance, BACNET_MAX_INSTANCE);
        return 1;
    }

    /* setup my info */
    Device_Set_Object_Instance_Number(BACNET_MAX_INSTANCE);
    address_init();
    Init_Service_Handlers();
    dlenv_init();
    atexit(datalink_cleanup);
    /* configure the timeout values */
    last_seconds = time(NULL);
    timeout_seconds = (apdu_timeout() / 1000) * apdu_retries();
    /* try to bind with the device */
    found =
        address_bind_request(Target_Device_Object_Instance, &max_apdu,
        &Target_Address);
    if (!found) {
        Send_WhoIs(Target_Device_Object_Instance,
            Target_Device_Object_Instance);
    }
    /* loop forever */
    for (;;) {
        /* increment timer - exit if timed out */
        current_seconds = time(NULL);

        /* returns 0 bytes on timeout */
        pdu_len = datalink_receive(&src, &Rx_Buf[0], MAX_MPDU, timeout);

        /* process */
        if (pdu_len) {
            npdu_handler(&src, &Rx_Buf[0], pdu_len);
        }
        /* at least one second has passed */
        if (current_seconds != last_seconds)
            tsm_timer_milliseconds((uint16_t) ((current_seconds -
                        last_seconds) * 1000));
        if (Error_Detected)
            break;
        /* wait until the device is bound, or timeout and quit */
        if (!found) {
            found =
                address_bind_request(Target_Device_Object_Instance, &max_apdu,
                &Target_Address);
        }
        if (found) {
            if (invoke_id == 0) {
                invoke_id =
                    Send_Device_Communication_Control_Request
                    (Target_Device_Object_Instance,
                    Communication_Timeout_Minutes, Communication_State,
                    Communication_Password);
            } else if (tsm_invoke_id_free(invoke_id))
                break;
            else if (tsm_invoke_id_failed(invoke_id)) {
                fprintf(stderr, "\rError: TSM Timeout!\r\n");
                tsm_free_invoke_id(invoke_id);
                /* try again or abort? */
                break;
            }
        } else {
            /* increment timer - exit if timed out */
            elapsed_seconds += (current_seconds - last_seconds);
            if (elapsed_seconds > timeout_seconds) {
                printf("\rError: APDU Timeout!\r\n");
                break;
            }
        }
        /* keep track of time for next check */
        last_seconds = current_seconds;
    }

    return 0;
}
示例#9
0
int main(
    int argc,
    char *argv[])
{
    BACNET_ADDRESS src = {
        0
    };  /* address where message came from */
    uint16_t pdu_len = 0;
    unsigned timeout = 100;     /* milliseconds */
    unsigned max_apdu = 0;
    time_t elapsed_seconds = 0;
    time_t last_seconds = 0;
    time_t current_seconds = 0;
    time_t timeout_seconds = 0;
    int fileStartPosition = 0;
    unsigned requestedOctetCount = 0;
    uint8_t invoke_id = 0;
    bool found = false;
    uint16_t my_max_apdu = 0;

    if (argc < 4) {
        /* FIXME: what about access method - record or stream? */
        printf("%s device-instance file-instance local-name\r\n",
            filename_remove_path(argv[0]));
        return 0;
    }
    /* decode the command line parameters */
    Target_Device_Object_Instance = strtol(argv[1], NULL, 0);
    Target_File_Object_Instance = strtol(argv[2], NULL, 0);
    Local_File_Name = argv[3];
    if (Target_Device_Object_Instance >= BACNET_MAX_INSTANCE) {
        fprintf(stderr, "device-instance=%u - it must be less than %u\r\n",
            Target_Device_Object_Instance, BACNET_MAX_INSTANCE);
        return 1;
    }
    if (Target_File_Object_Instance >= BACNET_MAX_INSTANCE) {
        fprintf(stderr, "file-instance=%u - it must be less than %u\r\n",
            Target_File_Object_Instance, BACNET_MAX_INSTANCE + 1);
        return 1;
    }
    /* setup my info */
    Device_Set_Object_Instance_Number(BACNET_MAX_INSTANCE);
    address_init();
    Init_Service_Handlers();
    dlenv_init();
    atexit(datalink_cleanup);
    /* configure the timeout values */
    last_seconds = time(NULL);
    timeout_seconds = (apdu_timeout() / 1000) * apdu_retries();
    /* try to bind with the device */
    Send_WhoIs(Target_Device_Object_Instance, Target_Device_Object_Instance);
    /* loop forever */
    for (;;) {
        /* increment timer - exit if timed out */
        current_seconds = time(NULL);

        /* returns 0 bytes on timeout */
        pdu_len = datalink_receive(&src, &Rx_Buf[0], MAX_MPDU, timeout);

        /* process */
        if (pdu_len) {
            npdu_handler(&src, &Rx_Buf[0], pdu_len);
        }
        /* at least one second has passed */
        if (current_seconds != last_seconds) {
            tsm_timer_milliseconds(((current_seconds - last_seconds) * 1000));
        }
        /* wait until the device is bound, or timeout and quit */
        found =
            address_bind_request(Target_Device_Object_Instance, &max_apdu,
            &Target_Address);
        if (found) {
            /* calculate the smaller of our APDU size or theirs
               and remove the overhead of the APDU (about 16 octets max).
               note: we could fail if there is a bottle neck (router)
               and smaller MPDU in betweeen. */
            if (max_apdu < MAX_APDU) {
                my_max_apdu = max_apdu;
            } else {
                my_max_apdu = MAX_APDU;
            }
            /* Typical sizes are 50, 128, 206, 480, 1024, and 1476 octets */
            if (my_max_apdu <= 50) {
                requestedOctetCount = my_max_apdu - 20;
            } else if (my_max_apdu <= 480) {
                requestedOctetCount = my_max_apdu - 32;
            } else if (my_max_apdu <= 1476) {
                requestedOctetCount = my_max_apdu - 64;
            } else {
                requestedOctetCount = my_max_apdu / 2;
            }
            /* has the previous invoke id expired or returned?
               note: invoke ID = 0 is invalid, so it will be idle */
            if ((invoke_id == 0) || tsm_invoke_id_free(invoke_id)) {
                if (End_Of_File_Detected || Error_Detected) {
                    break;
                }
                if (invoke_id != 0) {
                    fileStartPosition += requestedOctetCount;
                }
                /* we'll read the file in chunks
                   less than max_apdu to keep unsegmented */
                invoke_id =
                    Send_Atomic_Read_File_Stream(Target_Device_Object_Instance,
                    Target_File_Object_Instance, fileStartPosition,
                    requestedOctetCount);
                Current_Invoke_ID = invoke_id;
            } else if (tsm_invoke_id_failed(invoke_id)) {
                fprintf(stderr, "\rError: TSM Timeout!\r\n");
                tsm_free_invoke_id(invoke_id);
                /* try again or abort? */
                Error_Detected = true;
                break;
            }
        } else {
            /* increment timer - exit if timed out */
            elapsed_seconds += (current_seconds - last_seconds);
            if (elapsed_seconds > timeout_seconds) {
                fprintf(stderr, "\rError: APDU Timeout!\r\n");
                Error_Detected = true;
                break;
            }
        }
        /* keep track of time for next check */
        last_seconds = current_seconds;
    }

    if (Error_Detected) {
        return 1;
    }

    return 0;
}
示例#10
0
int main(
    int argc,
    char *argv[])
{
    BACNET_ADDRESS src = {
        0
    };  /* address where message came from */
    uint16_t pdu_len = 0;
    unsigned timeout = 100;     /* milliseconds */
    unsigned max_apdu = 0;
    time_t elapsed_seconds = 0;
    time_t last_seconds = 0;
    time_t current_seconds = 0;
    time_t timeout_seconds = 0;
    uint8_t invoke_id = 0;
    bool found = false;
    BACNET_READ_RANGE_DATA Request;
    int iCount = 0;
    int iType = 0;
    int iKey;
    int iSecondsRun = 0;


    if (((argc != 2) && (argc != 3)) || ((argc >= 2) &&
            (strcmp(argv[1], "--help") == 0))) {
        printf("%s\n", argv[0]);
        printf("Usage: %s server local-device-instance\r\n       or\r\n"
            "       %s remote-device-instance\r\n"
            "--help gives further information\r\n",
            filename_remove_path(argv[0]), filename_remove_path(argv[0]));
        if ((argc > 1) && (strcmp(argv[1], "--help") == 0)) {
            printf("\r\nServer mode:\r\n\r\n"
                "<local-device-instance> determins the device id of the application\r\n"
                "when running as the server end of a test set up. The Server simply\r\n"
                "returns dummy data for each ReadRange request\r\n\r\n"
                "Non server:\r\n\r\n"
                "<remote-device-instance> indicates the device id of the server\r\n"
                "instance of the application.\r\n"
                "The non server application will send a series of ReadRange requests to the\r\n"
                "server with examples of different range types.\r\n");
        }
        return 0;
    }
    /* decode the command line parameters */
    if (_stricmp(argv[1], "server") == 0)
        Target_Mode = 1;
    else
        Target_Mode = 0;

    Target_Device_Object_Instance = strtol(argv[1 + Target_Mode], NULL, 0);

    if (Target_Device_Object_Instance > BACNET_MAX_INSTANCE) {
        fprintf(stderr, "device-instance=%u - it must be less than %u\r\n",
            Target_Device_Object_Instance, BACNET_MAX_INSTANCE);
        return 1;
    }

    /* setup my info */
    if (Target_Mode)
        Device_Set_Object_Instance_Number(Target_Device_Object_Instance);
    else
        Device_Set_Object_Instance_Number(BACNET_MAX_INSTANCE);

    Init_Objects();
    address_init();
    Init_Service_Handlers();
    dlenv_init();
    atexit(datalink_cleanup);
    /* configure the timeout values */
    last_seconds = time(NULL);
    timeout_seconds = (apdu_timeout() / 1000) * apdu_retries();

    if (Target_Mode) {
#if defined(WIN32) || defined(__BORLANDC__)
        printf("Entering server mode. press q to quit program\r\n\r\n");
#else
        printf("Entering server mode.\r\n\r\n");
#endif
        for (;;) {
            /* increment timer - exit if timed out */
            current_seconds = time(NULL);

            /* returns 0 bytes on timeout */
            pdu_len = datalink_receive(&src, &Rx_Buf[0], MAX_MPDU, timeout);

            /* process */
            if (pdu_len) {
                npdu_handler(&src, &Rx_Buf[0], pdu_len);
            }
            /* at least one second has passed */
            if (current_seconds != last_seconds) {
                putchar('.');   /* Just to show that time is passing... */
                tsm_timer_milliseconds(((current_seconds -
                            last_seconds) * 1000));
                address_cache_timer(current_seconds - last_seconds);
                trend_log_timer(current_seconds - last_seconds);
                last_seconds = current_seconds;
                /* Change the analog input PVs for testing purposes */
                for (iCount = 0; iCount < Analog_Input_Count(); iCount++) {
                    Analog_Input_Present_Value_Set(iCount,
                        iSecondsRun * (iCount + 1));
                }

                iSecondsRun++;
            }
#if defined(WIN32) || defined(__BORLANDC__)
            if (_kbhit()) {
                iKey = toupper(_getch());
                if (iKey == 'Q') {
                    printf("\r\nExiting program now\r\n");
                    exit(0);
                }
            }
#endif
        }
    } else {

        /* try to bind with the device */
        found =
            address_bind_request(Target_Device_Object_Instance, &max_apdu,
            &Target_Address);
        if (!found) {
            Send_WhoIs(Target_Device_Object_Instance,
                Target_Device_Object_Instance);
        }
        /* loop forever */
        for (;;) {
            /* increment timer - exit if timed out */
            current_seconds = time(NULL);

            /* returns 0 bytes on timeout */
            pdu_len = datalink_receive(&src, &Rx_Buf[0], MAX_MPDU, timeout);

            /* process */
            if (pdu_len) {
                npdu_handler(&src, &Rx_Buf[0], pdu_len);
            }
            /* at least one second has passed */
            if (current_seconds != last_seconds) {
                tsm_timer_milliseconds(((current_seconds -
                            last_seconds) * 1000));
                address_cache_timer(current_seconds - last_seconds);
                trend_log_timer(current_seconds - last_seconds);
                last_seconds = current_seconds;
            }
            if (Error_Detected)
                break;
            /* wait until the device is bound, or timeout and quit */
            if (!found)
                found =
                    address_bind_request(Target_Device_Object_Instance,
                    &max_apdu, &Target_Address);
            if (found) {
                if (invoke_id == 0) {   /* Safe to send a new request */
                    switch (iCount) {
                        case 0:        /* Pass - should read up to 1st 10 */
                            Request.RequestType = RR_BY_POSITION;
                            Request.Range.RefIndex = 1;
                            Request.Count = 10;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 0;
                            break;

                        case 1:        /* Pass - should read entries 2 and 3 */
                            Request.RequestType = RR_BY_POSITION;
                            Request.Range.RefSeqNum = 3;
                            Request.Count = -2;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 0;
                            break;

                        case 2:        /* Fail - By Time not supported */
                            Request.RequestType = RR_BY_TIME;
                            Request.Range.RefTime.date.year = 2009;
                            Request.Range.RefTime.date.month = 9;
                            Request.Range.RefTime.date.day = 23;
                            Request.Range.RefTime.date.wday = 0xFF;
                            Request.Range.RefTime.time.hour = 22;
                            Request.Range.RefTime.time.min = 23;
                            Request.Range.RefTime.time.sec = 24;
                            Request.Range.RefTime.time.hundredths = 0;

                            Request.Count = 10;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 0;
                            break;

                        case 3:        /* Fail - array not supported */
                            Request.RequestType = RR_BY_POSITION;
                            Request.Range.RefIndex = 1;
                            Request.Count = 10;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 1;
                            break;

                        case 4:        /* Fail - By Sequence not supported */
                            Request.RequestType = RR_BY_SEQUENCE;
                            Request.Range.RefSeqNum = 1;
                            Request.Count = 10;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 0;
                            break;

                        case 5:        /* Fail Bytime not supported and array not supported */
                            Request.RequestType = RR_BY_TIME;
                            Request.Range.RefTime.date.year = 2009;
                            Request.Range.RefTime.date.month = 9;
                            Request.Range.RefTime.date.day = 23;
                            Request.Range.RefTime.date.wday = 0xFF;     /* Day of week unspecified */
                            Request.Range.RefTime.time.hour = 22;
                            Request.Range.RefTime.time.min = 23;
                            Request.Range.RefTime.time.sec = 24;
                            Request.Range.RefTime.time.hundredths = 0;

                            Request.Count = 10;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 1;
                            break;

                        case 6:        /* Pass - should try to return all entries */
                            Request.RequestType = RR_READ_ALL;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 0;
                            break;

                        case 7:        /* Fail - array not supported */
                            Request.RequestType = RR_READ_ALL;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 1;
                            break;

                        case 8:        /* Pass - should read 1st 1 */
                            Request.RequestType = RR_BY_POSITION;
                            Request.Range.RefIndex = 1;
                            Request.Count = 1;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 0;
                            break;

                        case 9:        /* Pass - should read 1st 2 */
                            Request.RequestType = RR_BY_POSITION;
                            Request.Range.RefIndex = 1;
                            Request.Count = 2;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 0;
                            break;

                        case 10:       /* Pass - should read 2nd and 3rd */
                            Request.RequestType = RR_BY_POSITION;
                            Request.Range.RefIndex = 2;
                            Request.Count = 2;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 0;
                            break;

                        case 11:       /* Pass - should read 2nd up to 11th */
                            Request.RequestType = RR_BY_POSITION;
                            Request.Range.RefIndex = 2;
                            Request.Count = 10;
                            Request.object_type = OBJECT_DEVICE;
                            Request.object_instance =
                                Target_Device_Object_Instance;
                            Request.object_property =
                                PROP_DEVICE_ADDRESS_BINDING;
                            Request.array_index = 0;
                            break;
                    }

                    invoke_id =
                        Send_ReadRange_Request(Target_Device_Object_Instance,
                        &Request);
                } else if (tsm_invoke_id_free(invoke_id)) {
                    if (iCount != 11) {
                        iCount++;
                        invoke_id = 0;
                    } else {
                        break;
                    }
                } else if (tsm_invoke_id_failed(invoke_id)) {
                    fprintf(stderr, "\rError: TSM Timeout!\r\n");
                    tsm_free_invoke_id(invoke_id);
                    /* Error_Detected = true; */
                    /* try again or abort? */
                    invoke_id = 0;      /* Try next operation */
                    /* break; */
                }
            } else {
                /* increment timer - exit if timed out */
                elapsed_seconds += (current_seconds - last_seconds);
                if (elapsed_seconds > timeout_seconds) {
                    printf("\rError: APDU Timeout!\r\n");
                    /* Error_Detected = true;
                       break; */
                    invoke_id = 0;
                }
            }
            /* keep track of time for next check */
            last_seconds = current_seconds;
        }
    }

    if (Error_Detected)
        return 1;
    return 0;
}
void CBacnetUserConfig::OnBnClickedButtonUserOk()
{
	// TODO: Add your control notification handler code here
	char temp_buffer[255];
	int compare_ret = 0;
	CString temp_enter_original;
	CString first_pw;
	CString second_pw;
	CString temp_user_name;
	CString access_string;
	switch(ok_button_stage)
	{
	case stage_enter_original_password://检查原始密码是否正确;
		{
			//m_user_login_data.at(m_slected_item).password
			GetDlgItemTextW(IDC_EDIT_USER_NAME,temp_user_name);
			GetDlgItemTextW(IDC_EDIT_USER_PASSWORD,temp_enter_original);
			if(temp_user_name.IsEmpty())
			{
				MessageBox(_T("user name is empty"),_T("Warning"),MB_OK);
				return;
			}
			if(temp_user_name.GetLength()>=STR_USER_NAME_LENGTH)
			{
				MessageBox(_T("User name is too long!"),_T("Warning"),MB_OK);
				return;
			}
			if(temp_enter_original.IsEmpty())
			{
				MessageBox(_T("Password is empty"),_T("Warning"),MB_OK);
				return;
			}
			memset(temp_buffer,0,255);
			WideCharToMultiByte(CP_ACP,NULL,temp_enter_original.GetBuffer(),-1,temp_buffer,255,NULL,NULL);
			compare_ret = strcmp(temp_buffer,m_user_login_data.at(m_slected_item).password);
			if(compare_ret == 0)
			{
				ok_button_stage = stage_enter_new_password;
				Enable_Window_Stage(ENTER_NEW_PASSWORD);
			}
			else
			{
				SetDlgItemTextW(IDC_EDIT_USER_PASSWORD,_T(""));
				MessageBox(_T("Password error"),_T("Warning"),MB_OK);	
				GetDlgItem(IDC_EDIT_USER_PASSWORD)->SetFocus();
				return;
			}
		}
		break;
	case stage_enter_new_password:
		{
			GetDlgItemTextW(IDC_EDIT_USER_NEW_PASSWORD,first_pw);
			if(first_pw.IsEmpty())
			{
				MessageBox(_T("Password is empty"),_T("Warning"),MB_OK);
				return;
			}
			if(first_pw.GetLength()>=STR_USER_PASSWORD_LENGTH)
			{
				MessageBox(_T("Password too long!"),_T("Warning"),MB_OK);
				return;
			}
			ok_button_stage = stage_retype_password;
			Enable_Window_Stage(RETYPE_NEW_PASSWORD);
		}
		break;
	case  stage_retype_password:
		{
			GetDlgItemTextW(IDC_EDIT_USER_NEW_PASSWORD,first_pw);
			GetDlgItemTextW(IDC_EDIT_USER_RETYPE_PASSWORD,second_pw);
			GetDlgItemTextW(IDC_EDIT_USER_NAME,temp_user_name);
			GetDlgItemTextW(IDC_COMBO_ACCESS_LEVEL,access_string);
			
			if(second_pw.IsEmpty())
			{
				MessageBox(_T("Password is empty"),_T("Warning"),MB_OK);
				return;
			}
			if(second_pw.GetLength()>=STR_USER_PASSWORD_LENGTH)
			{
				MessageBox(_T("Password too long!"),_T("Warning"),MB_OK);
				return;
			}

			if(first_pw.CompareNoCase(second_pw) == 0)
			{
				if(temp_user_name.IsEmpty())
				{
					MessageBox(_T("user name is empty"),_T("Warning"),MB_OK);
					return;
				}
				memset(temp_buffer,0,255);
				WideCharToMultiByte(CP_ACP,NULL,temp_user_name.GetBuffer(),-1,temp_buffer,255,NULL,NULL);
				memcpy(m_user_login_data.at(m_slected_item).name,temp_buffer,STR_USER_NAME_LENGTH);

				if(access_string.CompareNoCase(_T("View only")) == 0 )
				{
					m_user_login_data.at(m_slected_item).access_level = 1;
				}
				else if(access_string.CompareNoCase(_T("Graphic Mode")) == 0)
				{
					m_user_login_data.at(m_slected_item).access_level = 3;
				}
				else if(access_string.CompareNoCase(_T("Routine Mode")) == 0)
				{
					m_user_login_data.at(m_slected_item).access_level = 4;
				}
				else
					m_user_login_data.at(m_slected_item).access_level = 2;
				//_T("View only"));
				//_T("Full access"));

				memset(temp_buffer,0,255);
				WideCharToMultiByte(CP_ACP,NULL,second_pw.GetBuffer(),-1,temp_buffer,255,NULL,NULL);
				memcpy(m_user_login_data.at(m_slected_item).password,temp_buffer,STR_USER_PASSWORD_LENGTH);

				//Post_Write_Message(g_bac_instance,WRITEUSER_T3000,m_slected_item,m_slected_item,sizeof(Str_userlogin_point),m_user_config_hwnd ,_T(""),m_slected_item,m_slected_item);
				int temp_invoke_id = -1;
				int send_status = true;
				int	resend_count = 0;
				for (int z=0;z<3;z++)
				{
					do 
					{
						resend_count ++;
						if(resend_count>5)
						{
							send_status = false;
							break;
						}
						temp_invoke_id = WritePrivateData(g_bac_instance,WRITEUSER_T3000,m_slected_item,m_slected_item);

						Sleep(SEND_COMMAND_DELAY_TIME);
					} while (g_invoke_id<0);
					if(send_status)
					{
						Sleep(1000);
						if(tsm_invoke_id_free(temp_invoke_id))
						{
							ok_button_stage = 0;
							PostMessage(WM_REFRESH_BAC_USER_NAME_LIST,NULL,NULL);
							Enable_Window_Stage(HIDE_ALL);
							MessageBox(_T("Operation success!"),_T("Information"),MB_OK);
							return;
						}
						else
							continue;
					}
				}



			}
			else
			{
				MessageBox(_T("Password is not the same!"),_T("Warning"),MB_OK);
				return;
			}
		}
		break;
	default:
		break;
	}
}
void CBacnetUserConfig::OnBnClickedCheckUserlistInfo()
{
	// TODO: Add your control notification handler code here
	if(!((CButton *)GetDlgItem(IDC_CHECK_USERLIST_INFO))->GetCheck())
	{
		((CButton *)GetDlgItem(IDC_CHECK_USERLIST_INFO))->SetCheck(false);

		Device_Basic_Setting.reg.user_name = 1;
		//CString temp_task_info;
		//temp_task_info.Format(_T("Disable user list feature "));
		//Post_Write_Message(g_bac_instance,(int8_t)WRITE_SETTING_COMMAND,0,0,sizeof(Str_Setting_Info),this->m_hWnd,temp_task_info);

	}
	else
	{
		bool any_user_valid = false;
		bool any_user_administrator = false;
		//检测是否里面存在有效的账号密码;
		for (int i=0;i<(int)m_user_login_data.size();i++)
		{
			CString temp_user_name;
			MultiByteToWideChar( CP_ACP, 0, (char *)m_user_login_data.at(i).name, (int)strlen((char *)m_user_login_data.at(i).name)+1, 
				temp_user_name.GetBuffer(MAX_PATH), MAX_PATH );
			temp_user_name.ReleaseBuffer();

			CString temp_password;
			MultiByteToWideChar( CP_ACP, 0, (char *)m_user_login_data.at(i).password, (int)strlen((char *)m_user_login_data.at(i).password)+1, 
				temp_password.GetBuffer(MAX_PATH), MAX_PATH );
			temp_password.ReleaseBuffer();
			if(!temp_user_name.IsEmpty())
			{
				if(!temp_password.IsEmpty())
				{
					if(m_user_login_data.at(i).access_level == LOGIN_SUCCESS_FULL_ACCESS)
					{
						any_user_administrator = true;
						break;
					}
					any_user_valid = true;	//User表里面 存在可用的 账号密码;
				}
			}		
		}

		if(any_user_administrator)
		{
			((CButton *)GetDlgItem(IDC_CHECK_USERLIST_INFO))->SetCheck(true);
			Device_Basic_Setting.reg.user_name = 2;
			/*CString temp_task_info;
			temp_task_info.Format(_T("Enable user list feature "));
			Post_Write_Message(g_bac_instance,(int8_t)WRITE_SETTING_COMMAND,0,0,sizeof(Str_Setting_Info),this->m_hWnd,temp_task_info);*/
		}
		else if(any_user_valid)
		{
			((CButton *)GetDlgItem(IDC_CHECK_USERLIST_INFO))->SetCheck(false);
			Device_Basic_Setting.reg.user_name = 1;
			MessageBox(_T("User List don't contain any user have full access level!\r\nPlease add it and then enable this feature!"),_T("Warning"),MB_OK | MB_ICONINFORMATION);
			return;
		}
		else
		{
			((CButton *)GetDlgItem(IDC_CHECK_USERLIST_INFO))->SetCheck(false);
			Device_Basic_Setting.reg.user_name = 1;
			MessageBox(_T("User List don't contain any valid user name and password!\r\nPlease add it and then enable this feature!"),_T("Warning"),MB_OK | MB_ICONINFORMATION);
			return;
		}

		

	}

	int temp_invoke_id = -1;
	int send_status = true;
	int	resend_count = 0;
	for (int z=0;z<3;z++)
	{
		do 
		{
			resend_count ++;
			if(resend_count>5)
			{
				send_status = false;
				break;
			}
			temp_invoke_id = WritePrivateData(g_bac_instance,WRITE_SETTING_COMMAND,0,0);

			Sleep(SEND_COMMAND_DELAY_TIME);
		} while (g_invoke_id<0);
		if(send_status)
		{
			Sleep(1000);
			if(tsm_invoke_id_free(temp_invoke_id))
			{
				ok_button_stage = 0;
				PostMessage(WM_REFRESH_BAC_USER_NAME_LIST,NULL,NULL);
				Enable_Window_Stage(HIDE_ALL);
				MessageBox(_T("Operation success!"),_T("Information"),MB_OK);
				return;
			}
			else
				continue;
		}
	}

}
void CBacnetOutput::OnNMClickListOutput(NMHDR *pNMHDR, LRESULT *pResult)
{
	 
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: Add your control notification handler code here
	long lRow,lCol;
	m_output_list.Set_Edit(true);
	DWORD dwPos=GetMessagePos();//Get which line is click by user.Set the check box, when user enter Insert it will jump to program dialog
	CPoint point( LOWORD(dwPos), HIWORD(dwPos));
	m_output_list.ScreenToClient(&point);
	LVHITTESTINFO lvinfo;
	lvinfo.pt=point;
	lvinfo.flags=LVHT_ABOVE;
	int nItem=m_output_list.SubItemHitTest(&lvinfo);



	if((nItem!=-1) && (nItem < BAC_OUTPUT_ITEM_COUNT))
	{
		output_list_line = nItem;
		if((m_Output_data.at(output_list_line).sub_id !=0) &&
			//(m_Output_data.at(output_list_line).sub_number !=0) &&
			(m_Output_data.at(output_list_line).sub_product !=0))
		{
			unsigned char temp_pid = m_Output_data.at(output_list_line).sub_product;
			if((temp_pid == PM_T3PT10) ||
				(temp_pid == PM_T3IOA) ||
				(temp_pid == PM_T332AI) ||
				(temp_pid == PM_T38AI16O) ||
				(temp_pid == PM_T38I13O) ||
				(temp_pid == PM_T34AO) ||
				(temp_pid == PM_T36CT) ||
				(temp_pid == PM_T322AI) ||
				(temp_pid == PM_T38AI8AO6DO))
			{
				m_output_item_info.ShowWindow(true);
				CString temp_name;
				temp_name = GetProductName(m_Output_data.at(output_list_line).sub_product);
				CString show_info;
				CString temp_id;
				CString temp_number;
				temp_id.Format(_T(" Sub ID: %u        "),(unsigned char)m_Output_data.at(output_list_line).sub_id);
				temp_number.Format(_T("Output%d"),(unsigned char)m_Output_data.at(output_list_line).sub_number+1);
				show_info = _T("Module:") + temp_name +_T("        ") + temp_id + temp_number;
				m_output_item_info.SetWindowTextW(show_info);

			}	
			else
			{
				m_output_item_info.ShowWindow(false);
			}
		}
		else
		{
			m_output_item_info.ShowWindow(false);
		}
	}

	lRow = lvinfo.iItem;
	lCol = lvinfo.iSubItem;

	if(lRow>= OUTPUT_LIMITE_ITEM_COUNT)
		return;

	if(lRow>m_output_list.GetItemCount()) //如果点击区超过最大行号,则点击是无效的
		return;
	if(lRow<0)
		return;

	CString New_CString;
	CString temp_task_info;
	CString temp1;
	CStringArray temparray;

	if(lCol == OUTPUT_VALUE)
	{
		if(m_Output_data.at(lRow).auto_manual == BAC_AUTO)	//If it is auto mode, disable to change the value.
		{
			m_output_list.Set_Edit(false);
			return;
		}

		if(m_Output_data.at(lRow).digital_analog != BAC_UNITS_DIGITAL)
			return;



		memcpy_s(&m_temp_output_data[lRow],sizeof(Str_out_point),&m_Output_data.at(lRow),sizeof(Str_out_point));





		if((m_Output_data.at(lRow).range < 23) &&(m_Output_data.at(lRow).range !=0))
			temp1 = Digital_Units_Array[m_Output_data.at(lRow).range];
		else if((m_Output_data.at(lRow).range >=23) && (m_Output_data.at(lRow).range <= 30))
		{
			if(receive_customer_unit)
				temp1 = temp_unit_no_index[m_Output_data.at(lRow).range - 23];
			else
			{
				m_output_list.Set_Edit(false);
				return;
			}
		}
		else
			return;


		//if(m_Output_data.at(lRow).range > 11)
		//	temp1 = Digital_Units_Array[m_Output_data.at(lRow).range - 11];//11 is the sizeof the array
		//else
		//	temp1 = Digital_Units_Array[m_Output_data.at(lRow).range];
		SplitCStringA(temparray,temp1,_T("/"));
		if(m_Output_data.at(lRow).control == 0)
		{
			m_Output_data.at(lRow).control = 1;
			m_output_list.SetItemText(lRow,OUTPUT_VALUE,temparray.GetAt(1));
			New_CString = temparray.GetAt(1);
		}
		else
		{
			m_Output_data.at(lRow).control = 0;
			m_output_list.SetItemText(lRow,OUTPUT_VALUE,temparray.GetAt(0));
			New_CString = temparray.GetAt(0);
		}
	}
	else if(lCol == OUTPUT_AUTO_MANUAL)
	{
		memcpy_s(&m_temp_output_data[lRow],sizeof(Str_out_point),&m_Output_data.at(lRow),sizeof(Str_out_point));
		if(m_Output_data.at(lRow).auto_manual == 0)
		{
			m_Output_data.at(lRow).auto_manual = 1;
			m_output_list.SetItemText(lRow,OUTPUT_AUTO_MANUAL,_T("Manual"));
			//m_output_list.SetCellEnabled(lRow,OUTPUT_VALUE,TRUE);
			New_CString = _T("Manual");
		}
		else
		{
			m_Output_data.at(lRow).auto_manual = 0;
			m_output_list.SetItemText(lRow,OUTPUT_AUTO_MANUAL,_T("Auto"));
			//m_output_list.SetCellEnabled(lRow,OUTPUT_VALUE,FALSE);
			New_CString = _T("Auto");
		}
	}
	else if(lCol == OUTPUT_RANGE)
	{



			//CString temp_cs = m_output_list.GetItemText(Changed_Item,Changed_SubItem);
			BacnetRange dlg;
			//点击产品的时候 需要读customer units,老的产品firmware 说不定没有 这些,所以不强迫要读到;
			if(!read_customer_unit)
			{

				int temp_invoke_id = -1;
				int send_status = true;
				int	resend_count = 0;
				for (int z=0;z<3;z++)
				{
					do 
					{
						resend_count ++;
						if(resend_count>5)
						{
							send_status = false;
							break;
						}
						temp_invoke_id =  GetPrivateData(
							g_bac_instance,
							READUNIT_T3000,
							0,
							BAC_CUSTOMER_UNITS_COUNT - 1,
							sizeof(Str_Units_element));		

						Sleep(SEND_COMMAND_DELAY_TIME);
					} while (g_invoke_id<0);
					if(send_status)
					{
						for (int z=0;z<1000;z++)
						{
							Sleep(1);
							if(tsm_invoke_id_free(temp_invoke_id))
							{
								read_customer_unit = true;
								break;
							}
							else
								continue;
						}

					}
					if(read_customer_unit)
						break;
				}


			}

			if(m_Output_data.at(lRow).digital_analog == BAC_UNITS_ANALOG)
			{
				bac_ranges_type = OUTPUT_RANGE_ANALOG_TYPE;
				if(m_Output_data.at(lRow).range > (sizeof(Output_Analog_Units_Array) / sizeof(Output_Analog_Units_Array[0])))
				{
					m_Output_data.at(lRow).range = 0;
					bac_range_number_choose = 0;
				}
			}
			else
			{
				bac_ranges_type = OUTPUT_RANGE_DIGITAL_TYPE;
				if(m_Output_data.at(lRow).range > 30)
				{
					m_Output_data.at(lRow).range = 0;
					bac_range_number_choose = 0;
				}
			}


			//if(temp_cs.CompareNoCase(Units_Type[UNITS_TYPE_ANALOG])==0)
			//{
				initial_dialog = 3;
				bac_range_number_choose = m_Output_data.at(lRow).range;
				//bac_ranges_type = OUTPUT_RANGE_ANALOG_TYPE;
				dlg.DoModal();
				if(range_cancel)
				{
					PostMessage(WM_REFRESH_BAC_OUTPUT_LIST,lRow,REFRESH_ON_ITEM);//这里调用 刷新线程重新刷新会方便一点;
					return ;
				}
				if(bac_range_number_choose == 0)	//如果选择的是 unused 就认为是analog 的unused;这样 能显示对应的value;
				{
					m_Output_data.at(lRow).digital_analog =  BAC_UNITS_ANALOG;
					bac_ranges_type = OUTPUT_RANGE_ANALOG_TYPE;
				}

				if(bac_ranges_type == OUTPUT_RANGE_ANALOG_TYPE)
				{
					m_Output_data.at(lRow).digital_analog =  BAC_UNITS_ANALOG;
					m_Output_data.at(lRow).range =  bac_range_number_choose;
					m_output_list.SetItemText(lRow,OUTPUT_UNITE,Output_Analog_Units_Show[bac_range_number_choose]);		
					m_output_list.SetItemText(lRow,OUTPUT_RANGE,OutPut_List_Analog_Range[bac_range_number_choose]);	

					//m_output_list.SetItemText(lRow,OUTPUT_0_PERSENT,_T("0"));
					//m_output_list.SetCellEnabled(lRow,OUTPUT_0_PERSENT,1);
					//m_output_list.SetItemText(lRow,OUTPUT_100_PERSENT,_T("10"));
					//m_output_list.SetCellEnabled(lRow,OUTPUT_100_PERSENT,1);
				 
#if 0
					CString cstemp_value;
					float temp_float_value;
					temp_float_value = m_Output_data.at(Changed_Item).value / 1000;
					cstemp_value.Format(_T("%.2f"),temp_float_value);
					m_output_list.SetItemText(Changed_Item,OUTPUT_VALUE,cstemp_value);	
#endif
					CString cstemp_value;
					cstemp_value.Format(_T("%d"),m_Output_data.at(lRow).value);
					m_output_list.SetItemText(lRow,OUTPUT_VALUE,cstemp_value);	
				}
				else if((bac_ranges_type == VARIABLE_RANGE_DIGITAL_TYPE) || (bac_ranges_type == INPUT_RANGE_DIGITAL_TYPE) || (bac_ranges_type == OUTPUT_RANGE_DIGITAL_TYPE))
				{
					m_Output_data.at(lRow).digital_analog =  BAC_UNITS_DIGITAL;
					m_Output_data.at(lRow).range =  bac_range_number_choose;

					//m_output_list.SetItemText(lRow,OUTPUT_0_PERSENT,_T(""));
					//m_output_list.SetCellEnabled(lRow,OUTPUT_0_PERSENT,0);
					//m_output_list.SetItemText(lRow,OUTPUT_100_PERSENT,_T(""));
					//m_output_list.SetCellEnabled(lRow,OUTPUT_100_PERSENT,0);



					CStringArray temparray;

					if((bac_range_number_choose >= 23) && (bac_range_number_choose <= 30))
					{
						//temp1.Format(_T("%s"), temp_unit_no_index[bac_range_number_choose - 23]);
						temp1 = temp_unit_no_index[bac_range_number_choose - 23];
					}
					else
						temp1 = Digital_Units_Array[bac_range_number_choose];//22 is the sizeof the array



					SplitCStringA(temparray,temp1,_T("/"));

					if(m_Output_data.at(lRow).control == 1)
					{
						if((temparray.GetSize()==2)&&(!temparray.GetAt(1).IsEmpty()))
						{
							m_output_list.SetItemText(lRow,OUTPUT_VALUE,temparray.GetAt(1));
						}
					}
					else
					{
						if((temparray.GetSize()==2)&&(!temparray.GetAt(0).IsEmpty()))
						{
							m_output_list.SetItemText(lRow,OUTPUT_VALUE,temparray.GetAt(0));
						}	
					}
					m_output_list.SetItemText(lRow,OUTPUT_RANGE,temp1);
					m_output_list.SetItemText(lRow,OUTPUT_UNITE,_T(""));//如果是数字单位 Unit 要清空;
				}
			
	}
	else
	{
		return;
	}

		//return;



	m_output_list.Set_Edit(false);

	int cmp_ret = memcmp(&m_temp_output_data[lRow],&m_Output_data.at(lRow),sizeof(Str_out_point));
	if(cmp_ret!=0)
	{
		m_output_list.SetItemBkColor(lRow,lCol,LIST_ITEM_CHANGED_BKCOLOR);
		temp_task_info.Format(_T("Write Output List Item%d .Changed to \"%s\" "),lRow + 1,New_CString);
		Post_Write_Message(g_bac_instance,WRITEOUTPUT_T3000,lRow,lRow,sizeof(Str_out_point),m_output_dlg_hwnd,temp_task_info,lRow,lCol);
	}


	*pResult = 0;
}
示例#14
-1
void CBacnetVariable::OnNMClickListVariable(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: Add your control notification handler code here
	long lRow,lCol;
	m_variable_list.Set_Edit(true);
	DWORD dwPos=GetMessagePos();//Get which line is click by user.Set the check box, when user enter Insert it will jump to program dialog
	CPoint point( LOWORD(dwPos), HIWORD(dwPos));
	m_variable_list.ScreenToClient(&point);
	LVHITTESTINFO lvinfo;
	lvinfo.pt=point;
	lvinfo.flags=LVHT_ABOVE;
	int nItem=m_variable_list.SubItemHitTest(&lvinfo);

	lRow = lvinfo.iItem;
	lCol = lvinfo.iSubItem;


	if(lRow>m_variable_list.GetItemCount()) //如果点击区超过最大行号,则点击是无效的
		return;
	if(lRow<0)
		return;



	CString temp1;
	m_row = lRow;
	m_col = lCol;

	memcpy_s(&m_temp_variable_data[lRow],sizeof(Str_variable_point),&m_Variable_data.at(lRow),sizeof(Str_variable_point));
	CString New_CString;
	CString temp_task_info;
	if((lCol == VARIABLE_VALUE) &&(m_Variable_data.at(lRow).digital_analog == BAC_UNITS_DIGITAL ) && (m_Variable_data.at(lRow).auto_manual != BAC_AUTO))
	{
		
		
		CString temp1;
		CStringArray temparray;

		if((m_Variable_data.at(lRow).range < 23) &&(m_Variable_data.at(lRow).range !=0))
			temp1 = Digital_Units_Array[m_Variable_data.at(lRow).range];
		else if((m_Variable_data.at(lRow).range >=23) && (m_Variable_data.at(lRow).range <= 30))
		{
			if(receive_customer_unit)
				temp1 = temp_unit_no_index[m_Variable_data.at(lRow).range - 23];
			else
			{
				m_variable_list.Set_Edit(false);
				return;
			}
		}
		else
			return;
		SplitCStringA(temparray,temp1,_T("/"));



		if(m_Variable_data.at(lRow).control == 0)
		{
			m_Variable_data.at(lRow).control = 1;
			m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temparray.GetAt(1));
			New_CString = temparray.GetAt(1);
		}
		else
		{
			m_Variable_data.at(lRow).control = 0;
			m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temparray.GetAt(0));
			New_CString = temparray.GetAt(0);
		}
		m_variable_list.Set_Edit(false);

		temp_task_info.Format(_T("Write Variable List Item%d .Changed to \"%s\" "),lRow + 1,New_CString);
	}
	else if((lCol == VARIABLE_VALUE) &&(m_Variable_data.at(lRow).digital_analog == BAC_UNITS_ANALOG ) && (m_Variable_data.at(lRow).auto_manual == BAC_MANUAL) && (m_Variable_data.at(lRow).range == 20))
	{
		m_variable_list.Set_Edit(false);
		m_variable_time_picker.ShowWindow(SW_SHOW);
		CRect list_rect,win_rect;
		m_variable_list.GetWindowRect(list_rect);
		GetWindowRect(win_rect);
		CRect myrect;
		m_variable_list.GetSubItemRect(lRow,lCol,LVIR_BOUNDS,myrect);


		myrect.left = myrect.left + list_rect.left - win_rect.left  +2 ;
		myrect.right = myrect.right + list_rect.left - win_rect.left + 2;
		myrect.top = myrect.top + 24;
		myrect.bottom = myrect.bottom + 26;
		m_variable_time_picker.BringWindowToTop();
		m_variable_time_picker.MoveWindow(myrect);

		
		CString Temp_CString =  m_variable_list.GetItemText(lRow,lCol);

		CStringArray TEMPCS;
		int temp_hour,temp_minute,temp_second;
		SplitCStringA(TEMPCS, Temp_CString, _T(":"));
		if((int)TEMPCS.GetSize() <3)
		{
			temp_hour = 0;
			temp_minute = 0;
			temp_second = 0;
			CTime TimeTemp(2016,1,1,temp_hour,temp_minute,0);
			m_variable_time_picker.SetFormat(_T("HH:mm:ss"));
			m_variable_time_picker.SetTime(&TimeTemp);
			m_variable_time_picker.SetFocus();
		}
		else
		{
			temp_hour = _wtoi(TEMPCS.GetAt(0));
			temp_minute = _wtoi(TEMPCS.GetAt(1));
			temp_second = _wtoi(TEMPCS.GetAt(2));
			if(temp_hour >=24)
				temp_hour = 0;
			if(temp_minute >=60)
				temp_minute = 0;
			if(temp_second >= 60)
				temp_second = 0;
			CTime TimeTemp(2016,1,1,temp_hour,temp_minute,temp_second);
			m_variable_time_picker.SetFormat(_T("HH:mm:ss"));
			m_variable_time_picker.SetTime(&TimeTemp);
			m_variable_time_picker.SetFocus();
		}
		m_variable_list.SetItemText(lRow,lCol,_T(""));
		m_variable_time_picker.Invalidate();
		SetTimer(2,100,NULL);
	}
	else if(lCol == VARIABLE_VALUE)
	{
		if(m_Variable_data.at(lRow).auto_manual == BAC_AUTO)
		{
			m_variable_list.Set_Edit(false);
			return;
		}
	}
	else if(lCol == VARIABLE_AUTO_MANUAL)
	{
		if(m_Variable_data.at(lRow).auto_manual == 0)
		{
			m_Variable_data.at(lRow).auto_manual = 1;
			m_variable_list.SetItemText(lRow,VARIABLE_AUTO_MANUAL,_T("Manual"));
			New_CString = _T("Manual");
		}
		else
		{
			m_Variable_data.at(lRow).auto_manual = 0;
			m_variable_list.SetItemText(lRow,VARIABLE_AUTO_MANUAL,_T("Auto"));
			New_CString = _T("Auto");
		}
		temp_task_info.Format(_T("Write Variable List Item%d .Changed to \"%s\" "),lRow + 1,New_CString);
	}
	else if(lCol == VARIABLE_UNITE)
	{


		BacnetRange dlg;

		//点击产品的时候 需要读customer units,老的产品firmware 说不定没有 这些,所以不强迫要读到;
		if(!read_customer_unit)
		{

			int temp_invoke_id = -1;
			int send_status = true;
			int	resend_count = 0;
			for (int z=0;z<3;z++)
			{
				do 
				{
					resend_count ++;
					if(resend_count>5)
					{
						send_status = false;
						break;
					}
					temp_invoke_id =  GetPrivateData(
						g_bac_instance,
						READUNIT_T3000,
						0,
						BAC_CUSTOMER_UNITS_COUNT - 1,
						sizeof(Str_Units_element));		

					Sleep(SEND_COMMAND_DELAY_TIME);
				} while (g_invoke_id<0);
				if(send_status)
				{
					for (int z=0;z<1000;z++)
					{
						Sleep(1);
						if(tsm_invoke_id_free(temp_invoke_id))
						{
							read_customer_unit = true;
							break;
						}
						else
							continue;
					}

				}
				if(read_customer_unit)
					break;
			}

		}
		if(m_Variable_data.at(lRow).digital_analog == BAC_UNITS_ANALOG)
		{
			bac_ranges_type = VARIABLE_RANGE_ANALOG_TYPE;
			if(m_Variable_data.at(lRow).range > (sizeof(Variable_Analog_Units_Array) / sizeof(Variable_Analog_Units_Array[0])))
			{
				m_Variable_data.at(lRow).range = 0;
				bac_range_number_choose = 0;
			}
		}
		else
		{
			bac_ranges_type = VARIABLE_RANGE_DIGITAL_TYPE;
			if(m_Variable_data.at(lRow).range > 30)
			{
				m_Variable_data.at(lRow).range = 0;
				bac_range_number_choose = 0;
			}
		}


			initial_dialog = 1;
			bac_range_number_choose = m_Variable_data.at(lRow).range;
			dlg.DoModal();
			if(range_cancel)
			{
				PostMessage(WM_REFRESH_BAC_VARIABLE_LIST,lRow,REFRESH_ON_ITEM);//这里调用 刷新线程重新刷新会方便一点;
				return ;
			}
			if(bac_range_number_choose == 0)	//如果选择的是 unused 就认为是analog 的unused;这样 能显示对应的value;
			{
				m_Variable_data.at(lRow).digital_analog =  BAC_UNITS_ANALOG;
				bac_ranges_type = VARIABLE_RANGE_ANALOG_TYPE;
			}

			if(bac_ranges_type == VARIABLE_RANGE_ANALOG_TYPE)
			{
				m_Variable_data.at(lRow).digital_analog = BAC_UNITS_ANALOG;
				m_Variable_data.at(lRow).range = bac_range_number_choose;
				m_variable_list.SetItemText(lRow,lCol,Variable_Analog_Units_Array[bac_range_number_choose]);



				if(m_Variable_data.at(lRow).range == 20)	//如果是时间;
				{
					char temp_char[50];
					int time_seconds = m_Variable_data.at(lRow).value / 1000;
					intervaltotextfull(temp_char,time_seconds,0,0);

					CString temp_11;
					MultiByteToWideChar( CP_ACP, 0, temp_char, strlen(temp_char) + 1, 
						temp_11.GetBuffer(MAX_PATH), MAX_PATH );
					temp_11.ReleaseBuffer();		
					m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temp_11);

				}
				else
				{
					CString cstemp_value;
					float temp_float_value;
					temp_float_value = ((float)m_Variable_data.at(lRow).value) / 1000;
					cstemp_value.Format(_T("%.3f"),temp_float_value);
					m_variable_list.SetItemText(lRow,VARIABLE_VALUE,cstemp_value);

					/*				cstemp_value.Format(_T("%d"),m_Variable_data.at(Changed_Item).value);
					m_variable_list.SetItemText(Changed_Item,VARIABLE_VALUE,cstemp_value);*/	
				}
			}
			else if((bac_ranges_type == VARIABLE_RANGE_DIGITAL_TYPE) || (bac_ranges_type == INPUT_RANGE_DIGITAL_TYPE) || (bac_ranges_type == OUTPUT_RANGE_DIGITAL_TYPE))
			{
				m_Variable_data.at(lRow).digital_analog = BAC_UNITS_DIGITAL;
				m_Variable_data.at(lRow).range = bac_range_number_choose;


				CStringArray temparray;
				if((bac_range_number_choose >= 23) && (bac_range_number_choose <= 30))
				{
					//temp1.Format(_T("%s"), temp_unit_no_index[bac_range_number_choose - 23]);
					temp1 = temp_unit_no_index[bac_range_number_choose - 23];
				}
				else
					temp1 = Digital_Units_Array[bac_range_number_choose];//22 is the sizeof the array

				SplitCStringA(temparray,temp1,_T("/"));





				if(m_Variable_data.at(lRow).control == 1)
				{
					if((temparray.GetSize()==2)&&(!temparray.GetAt(1).IsEmpty()))
					{
						m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temparray.GetAt(1));
					}
				}
				else
				{
					if((temparray.GetSize()==2)&&(!temparray.GetAt(0).IsEmpty()))
					{
						m_variable_list.SetItemText(lRow,VARIABLE_VALUE,temparray.GetAt(0));
					}			
				}
				m_variable_list.SetItemText(lRow,VARIABLE_UNITE,temp1);
			}
		
	
	}
	else
	{
		return;
	}

	int cmp_ret = memcmp(&m_temp_variable_data[lRow],&m_Variable_data.at(lRow),sizeof(Str_variable_point));
	if(cmp_ret!=0)
	{
		m_variable_list.SetItemBkColor(lRow,lCol,LIST_ITEM_CHANGED_BKCOLOR);
		Post_Write_Message(g_bac_instance,WRITEVARIABLE_T3000,lRow,lRow,sizeof(Str_variable_point),m_variable_dlg_hwnd,temp_task_info,lRow,lCol);
	}
	*pResult = 0;
}