/**@brief Timer callback used for connecting to Xively cloud. * * @param[in] p_context Pointer used for passing context. No context used in this application. */ static void app_xively_connect(void * p_context) { UNUSED_VARIABLE(p_context); uint32_t err_code; mqtt_client_init(&m_app_mqtt_id); static mqtt_username_t username; username.p_utf_str = (uint8_t *)m_user; username.utf_strlen = strlen(m_user); memcpy (m_app_mqtt_id.broker_addr.u8, m_broker_addr, IPV6_ADDR_SIZE); m_app_mqtt_id.broker_port = APP_MQTT_XIVELY_BROKER_PORT; m_app_mqtt_id.evt_cb = app_mqtt_evt_handler; m_app_mqtt_id.client_id.p_utf_str = (uint8_t *)m_device_id; m_app_mqtt_id.client_id.utf_strlen = strlen(m_device_id); m_app_mqtt_id.p_password = NULL; m_app_mqtt_id.p_user_name = (mqtt_username_t *)&username; m_app_mqtt_id.transport_type = MQTT_TRANSPORT_SECURE; m_app_mqtt_id.p_security_settings = &m_tls_keys; err_code = mqtt_connect(&m_app_mqtt_id); APP_ERROR_CHECK(err_code); }
static int test_init(struct harness_t *harness_p) { struct thrd_t *thrd_p; int port = REMOTE_HOST_PORT; char remote_host_ip[] = STRINGIFY(REMOTE_HOST_IP); struct inet_addr_t remote_host_address; self_p = thrd_self(); std_printf(FSTR("Connecting to '%s:%d'.\r\n"), remote_host_ip, port); BTASSERT(inet_aton(remote_host_ip, &remote_host_address.ip) == 0); remote_host_address.port = port; BTASSERT(socket_open_tcp(&server_sock) == 0); BTASSERT(socket_connect(&server_sock, &remote_host_address) == 0); BTASSERT(mqtt_client_init(&client, "mqtt_client", NULL, &server_sock, &server_sock, on_publish, NULL) == 0); thrd_p = thrd_spawn(mqtt_client_main, &client, 0, stack, sizeof(stack)); thrd_set_log_mask(thrd_p, LOG_UPTO(DEBUG)); return (0); }
void mqtt_client_sample_run() { if (platform_init() != 0) { PrintLogFunction(LOG_LINE, "platform_init failed"); } else { MQTT_CLIENT_HANDLE mqttHandle = mqtt_client_init(OnRecvCallback, OnOperationComplete, NULL, PrintLogFunction); if (mqttHandle == NULL) { PrintLogFunction(LOG_LINE, "mqtt_client_init failed"); } else { MQTT_CLIENT_OPTIONS options = { 0 }; options.clientId = "azureiotclient"; options.willMessage = NULL; options.username = NULL; options.password = NULL; options.keepAliveInterval = 10; options.useCleanSession = true; options.qualityOfServiceValue = DELIVER_AT_MOST_ONCE; SOCKETIO_CONFIG config = {"test.mosquitto.org", PORT_NUM_UNENCRYPTED, NULL}; XIO_HANDLE xio = xio_create(socketio_get_interface_description(), &config, PrintLogFunction); if (xio == NULL) { PrintLogFunction(LOG_LINE, "xio_create failed"); } else { if (mqtt_client_connect(mqttHandle, xio, &options) != 0) { PrintLogFunction(LOG_LINE, "mqtt_client_connect failed"); } else { do { mqtt_client_dowork(mqttHandle); } while (g_continue); } xio_close(xio, OnCloseComplete, NULL); } mqtt_client_deinit(mqttHandle); } platform_deinit(); } #ifdef _CRT_DBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif }
/* * 判读是否需要请求获取did和mqtt info * */ void mqtt_init() { system(SET_DARK_CLOUD);//add by yanly char tembuf[HTTP_BUF_MAXLEN]; int sendlen; if(gateway_info.did[0] ==0) //request did { sendlen = http_req_did(tembuf, HTTP_BUF_MAXLEN, gateway_info.http_server, DEV_REGISTER_URL, gateway_info.passcode, gateway_info.sn, gateway_info.productkey); if(sendlen) { http_req_start(tembuf, sendlen, gateway_info.http_server, gateway_info.http_port, NULL, http_res_did); } else log_printf(LOG_ERROR, "http_req_did error\n"); } else { if((gateway_info.mt_server1[0] !=0)&&(gateway_info.mt_port1)!=0) { mqtt_client_init(&global_ev_all, gateway_info.mt_server1, gateway_info.mt_port1); } else if((gateway_info.mt_server2[0] !=0)&&(gateway_info.mt_port2)!=0) { mqtt_client_init(&global_ev_all, gateway_info.mt_server2, gateway_info.mt_port2); } else { //request mqtt info sendlen = http_req_mtinfo(tembuf, HTTP_BUF_MAXLEN, gateway_info.http_server, GET_MQTT_INFO_URL, gateway_info.did); if(sendlen) { http_req_start(tembuf, sendlen, gateway_info.http_server, gateway_info.http_port, NULL, http_res_mtinfo); } else log_printf(LOG_ERROR, "http_req_did error\n"); } } }
// Main routine to initialize esp-link. void user_init(void) { // get the flash config so we know how to init things //configWipe(); // uncomment to reset the config for testing purposes bool restoreOk = configRestore(); // Init gpio pin registers gpio_init(); gpio_output_set(0, 0, 0, (1<<15)); // some people tie it to GND, gotta ensure it's disabled // init UART uart_init(flashConfig.baud_rate, 115200); logInit(); // must come after init of uart // Say hello (leave some time to cause break in TX after boot loader's msg os_delay_us(10000L); os_printf("\n\n** %s\n", esp_link_version); os_printf("Flash config restore %s\n", restoreOk ? "ok" : "*FAILED*"); // Status LEDs statusInit(); serledInit(); // Wifi wifiInit(); // init the flash filesystem with the html stuff espFsInit(&_binary_espfs_img_start); //EspFsInitResult res = espFsInit(&_binary_espfs_img_start); //os_printf("espFsInit %s\n", res?"ERR":"ok"); // mount the http handlers httpdInit(builtInUrls, 80); // init the wifi-serial transparent bridge (port 23) serbridgeInit(23, 2323); uart_add_recv_cb(&serbridgeUartCb); #ifdef SHOW_HEAP_USE os_timer_disarm(&prHeapTimer); os_timer_setfn(&prHeapTimer, prHeapTimerCb, NULL); os_timer_arm(&prHeapTimer, 10000, 1); #endif struct rst_info *rst_info = system_get_rst_info(); NOTICE("Reset cause: %d=%s", rst_info->reason, rst_codes[rst_info->reason]); NOTICE("exccause=%d epc1=0x%x epc2=0x%x epc3=0x%x excvaddr=0x%x depc=0x%x", rst_info->exccause, rst_info->epc1, rst_info->epc2, rst_info->epc3, rst_info->excvaddr, rst_info->depc); uint32_t fid = spi_flash_get_id(); NOTICE("Flash map %s, manuf 0x%02lX chip 0x%04lX", flash_maps[system_get_flash_size_map()], fid & 0xff, (fid&0xff00)|((fid>>16)&0xff)); NOTICE("** esp-link ready"); // Init SNTP service cgiServicesSNTPInit(); #ifdef MQTT NOTICE("initializing MQTT"); mqtt_client_init(); #endif NOTICE("initializing user application"); app_init(); NOTICE("Waiting for work to do..."); }
static PMQTTTRANSPORT_HANDLE_DATA InitializeTransportHandleData(const IOTHUB_CLIENT_CONFIG* upperConfig, PDLIST_ENTRY waitingToSend) { PMQTTTRANSPORT_HANDLE_DATA state = (PMQTTTRANSPORT_HANDLE_DATA)malloc(sizeof(MQTTTRANSPORT_HANDLE_DATA)); if (state == NULL) { LogError("Could not create MQTT transport state. Memory allocation failed.\r\n"); } else if ((state->device_id = STRING_construct(upperConfig->deviceId)) == NULL) { free(state); state = NULL; } else if ((state->device_key = STRING_construct(upperConfig->deviceKey)) == NULL) { LogError("Could not create device key for MQTT\r\n"); STRING_delete(state->device_id); free(state); state = NULL; } else if ( (state->sasTokenSr = ConstructSasToken(upperConfig->iotHubName, upperConfig->iotHubSuffix, upperConfig->deviceId) ) == NULL) { LogError("Could not create Sas Token Sr String.\r\n"); STRING_delete(state->device_key); STRING_delete(state->device_id); free(state); state = NULL; } else if ( (state->mqttEventTopic = ConstructEventTopic(upperConfig->deviceId) ) == NULL) { LogError("Could not create mqttEventTopic for MQTT\r\n"); STRING_delete(state->sasTokenSr); STRING_delete(state->device_key); STRING_delete(state->device_id); free(state); state = NULL; } else if ((state->mqttMessageTopic = ConstructMessageTopic(upperConfig->deviceId) ) == NULL) { LogError("Could not create mqttMessageTopic for MQTT\r\n"); STRING_delete(state->mqttEventTopic); STRING_delete(state->sasTokenSr); STRING_delete(state->device_key); STRING_delete(state->device_id); free(state); state = NULL; } else { state->mqttClient = mqtt_client_init(MqttRecvCallback, MqttOpCompleteCallback, state, defaultPrintLogFunction); if (state->mqttClient == NULL) { STRING_delete(state->mqttEventTopic); STRING_delete(state->mqttMessageTopic); STRING_delete(state->sasTokenSr); STRING_delete(state->device_key); STRING_delete(state->device_id); free(state); state = NULL; } else { /* Codes_SRS_IOTHUB_MQTT_TRANSPORT_07_008: [The hostname shall be constructed using the iothubname and iothubSuffix.] */ // TODO: need to strip the ssl or http or tls char tempAddress[DEFAULT_TEMP_STRING_LEN]; (void)snprintf(tempAddress, DEFAULT_TEMP_STRING_LEN, "%s.%s", upperConfig->iotHubName, upperConfig->iotHubSuffix); if ((state->hostAddress = STRING_construct(tempAddress)) == NULL) { STRING_delete(state->mqttEventTopic); STRING_delete(state->mqttMessageTopic); STRING_delete(state->sasTokenSr); STRING_delete(state->device_key); STRING_delete(state->device_id); free(state); state = NULL; } else if ((state->configPassedThroughUsername = buildConfigForUsername(upperConfig)) == NULL) { STRING_delete(state->hostAddress); STRING_delete(state->mqttEventTopic); STRING_delete(state->mqttMessageTopic); STRING_delete(state->sasTokenSr); STRING_delete(state->device_key); STRING_delete(state->device_id); free(state); state = NULL; } else { /* Codes_SRS_IOTHUB_MQTT_TRANSPORT_07_010: [IoTHubTransportMqtt_Create shall allocate memory to save its internal state where all topics, hostname, device_id, device_key, sasTokenSr and client handle shall be saved.] */ DList_InitializeListHead(&(state->waitingForAck)); state->destroyCalled = false; state->subscribed = false; state->connected = false; state->packetId = 1; state->llClientHandle = NULL; state->xioTransport = NULL; state->portNum = DEFAULT_PORT_NUMBER; state->waitingToSend = waitingToSend; state->currPacketState = CONNECT_TYPE; } } } return state; }
PROV_DEVICE_TRANSPORT_HANDLE prov_transport_common_mqtt_create(const char* uri, TRANSPORT_HSM_TYPE type, const char* scope_id, const char* api_version, PROV_MQTT_TRANSPORT_IO transport_io) { PROV_TRANSPORT_MQTT_INFO* result; if (uri == NULL || scope_id == NULL || api_version == NULL || transport_io == NULL) { /* Codes_PROV_TRANSPORT_MQTT_COMMON_07_001: [ If uri, scope_id, registration_id, api_version, or transport_io is NULL, prov_transport_common_mqtt_create shall return NULL. ] */ LogError("Invalid parameter specified uri: %p, scope_id: %p, api_version: %p, transport_io: %p", uri, scope_id, api_version, transport_io); result = NULL; } else if (type == TRANSPORT_HSM_TYPE_TPM) { /* Codes_PROV_TRANSPORT_MQTT_COMMON_07_062: [ If TRANSPORT_HSM_TYPE is TRANSPORT_HSM_TYPE_TPM prov_transport_common_mqtt_create shall return NULL (currently TPM is not supported). ] */ LogError("HSM type of TPM is not supported"); result = NULL; } else { /* Codes_PROV_TRANSPORT_MQTT_COMMON_07_003: [ prov_transport_common_mqtt_create shall allocate a PROV_TRANSPORT_MQTT_INFO and initialize the containing fields. ] */ result = malloc(sizeof(PROV_TRANSPORT_MQTT_INFO)); if (result == NULL) { /* Codes_PROV_TRANSPORT_MQTT_COMMON_07_002: [ If any error is encountered, prov_transport_common_mqtt_create shall return NULL. ] */ LogError("Unable to allocate PROV_TRANSPORT_MQTT_INFO"); } else { memset(result, 0, sizeof(PROV_TRANSPORT_MQTT_INFO)); if (mallocAndStrcpy_s(&result->hostname, uri) != 0) { /* Codes_PROV_TRANSPORT_MQTT_COMMON_07_002: [ If any error is encountered, prov_transport_common_mqtt_create shall return NULL. ] */ LogError("Failure allocating hostname"); free(result); result = NULL; } else if (mallocAndStrcpy_s(&result->api_version, api_version) != 0) { /* Codes_PROV_TRANSPORT_MQTT_COMMON_07_002: [ If any error is encountered, prov_transport_common_mqtt_create shall return NULL. ] */ LogError("Failure allocating api_version"); cleanup_mqtt_data(result); result = NULL; } else if (mallocAndStrcpy_s(&result->scope_id, scope_id) != 0) { /* Codes_PROV_TRANSPORT_MQTT_COMMON_07_002: [ If any error is encountered, prov_transport_common_mqtt_create shall return NULL. ] */ LogError("Failure allocating scope_id"); cleanup_mqtt_data(result); result = NULL; } else if ((result->mqtt_client = mqtt_client_init(mqtt_notification_callback, mqtt_operation_complete_callback, result, mqtt_error_callback, result)) == NULL) { /* Codes_PROV_TRANSPORT_MQTT_COMMON_07_002: [ If any error is encountered, prov_transport_common_mqtt_create shall return NULL. ] */ LogError("Failed initializing mqtt client."); cleanup_mqtt_data(result); result = NULL; } else { result->transport_io_cb = transport_io; result->hsm_type = type; } } } /* Codes_PROV_TRANSPORT_MQTT_COMMON_07_004: [ On success prov_transport_common_mqtt_create shall return a new instance of PROV_DEVICE_TRANSPORT_HANDLE. ] */ return result; }
// Main routine to initialize esp-link. void user_init(void) { // get the flash config so we know how to init things // configWipe(); // uncomment to reset the config for testing purposes bool restoreOk = configRestore(); // init gpio pin registers gpio_init(); gpio_output_set(0, 0, 0, (1<<15)); // some people tie it to GND, gotta ensure it's disabled // init UART uart_init(flashConfig.baud_rate, 115200); logInit(); // must come after init of uart // say hello (leave some time to cause break in TX after boot loader's msg os_delay_us(10000L); os_printf("\n\n** %s\n", esp_link_version); os_printf("Flash config restore %s\n", restoreOk ? "ok" : "*FAILED*"); #if defined(STA_SSID) && defined(STA_PASS) int x = wifi_get_opmode() & 0x3; if (x == 2) { // we only force the STA settings when a full flash of the module has been made, which // resets the wifi settings not to have anything configured struct station_config stconf; wifi_station_get_config(&stconf); if (os_strlen((char*)stconf.ssid) == 0 && os_strlen((char*)stconf.password) == 0) { os_strncpy((char*)stconf.ssid, VERS_STR(STA_SSID), 32); os_strncpy((char*)stconf.password, VERS_STR(STA_PASS), 64); #ifdef CGIWIFI_DBG os_printf("Wifi pre-config trying to connect to AP %s pw %s\n", (char*)stconf.ssid, (char*)stconf.password); #endif wifi_set_opmode(3); // sta+ap, will switch to sta-only 15 secs after connecting stconf.bssid_set = 0; wifi_station_set_config(&stconf); } } #endif // Status LEDs statusInit(); serledInit(); // Wifi wifiInit(); // init the flash filesystem with the html stuff espFsInit(&_binary_espfs_img_start); //EspFsInitResult res = espFsInit(&_binary_espfs_img_start); //os_printf("espFsInit %s\n", res?"ERR":"ok"); // mount the http handlers httpdInit(builtInUrls, 80); // init the wifi-serial transparent bridge (port 23) serbridgeInit(23, 2323); uart_add_recv_cb(&serbridgeUartCb); #ifdef SHOW_HEAP_USE os_timer_disarm(&prHeapTimer); os_timer_setfn(&prHeapTimer, prHeapTimerCb, NULL); os_timer_arm(&prHeapTimer, 10000, 1); #endif struct rst_info *rst_info = system_get_rst_info(); NOTICE("Reset cause: %d=%s", rst_info->reason, rst_codes[rst_info->reason]); NOTICE("exccause=%d epc1=0x%x epc2=0x%x epc3=0x%x excvaddr=0x%x depc=0x%x", rst_info->exccause, rst_info->epc1, rst_info->epc2, rst_info->epc3, rst_info->excvaddr, rst_info->depc); uint32_t fid = spi_flash_get_id(); NOTICE("Flash map %s, manuf 0x%02lX chip 0x%04lX", flash_maps[system_get_flash_size_map()], fid & 0xff, (fid&0xff00)|((fid>>16)&0xff)); NOTICE("** esp-link ready"); cgiServicesSNTPInit(); #ifdef MQTT NOTICE("initializing MQTT"); mqtt_client_init(); #endif NOTICE("initializing user application"); app_init(); NOTICE("waiting for work to do..."); }