/****************************************************************** * function : Cloud_MQTT_initSocket * broker : mqtt struct * flag : 0 wifi module to register socketid. * 1 wifi module to login socketid * * ********************************************************************/ int Cloud_MQTT_initSocket( mqtt_broker_handle_t* broker,int flag ) { int ret; // int MTflag; struct sockaddr_in Msocket_address; char MqttServerIpAddr[32]; int iSocketId; // int packetLen; char *domain = g_Xpg_GlobalVar.m2m_SERVER; unsigned short port = g_Xpg_GlobalVar.m2m_Port; memset(MqttServerIpAddr, 0x0, sizeof(MqttServerIpAddr)); ret = GAgent_GetHostByName( domain, MqttServerIpAddr ); if(ret !=0 ) { GAgent_Printf(GAGENT_ERROR,"Gethostbyname(%s) fail ret:%d", domain, ret); return 1; //域名解析失败 } GAgent_Printf(GAGENT_INFO,"MQTT Connect Domain:%s IP:%s \r\n", domain, MqttServerIpAddr); if( broker->socketid!=-1 ) { GAgent_Printf(GAGENT_INFO,"Cloud_MQTT_initSocket close[%04x] mqtt socket", broker->socketid); close_socket(broker); } if( (iSocketId = socket(AF_INET, SOCK_STREAM, 0))<0) { GAgent_Printf(GAGENT_ERROR," MQTT socket init fail"); return 1; } ret = connect_mqtt_socket(iSocketId, &Msocket_address, port, MqttServerIpAddr); if (ret < 0) { GAgent_Printf(GAGENT_WARNING,"mqtt socket connect fail with:%d", ret); close(iSocketId); return 3; } /*For Test MQTT Read And Write Func*/ MQTT_handlePacket(); GAgent_Printf(GAGENT_LOG, "Created mqtt socketid[%08x]", iSocketId); // MQTT stuffs mqtt_set_alive(broker, MQTT_HEARTBEAT); broker->socketid = iSocketId; broker->mqttsend = send_packet; return 0; }
int Socket_CreateTCPClient(void) { int ret = 0; struct sockaddr_in server_addr; char ipaddr[20] = {'\0'}; AGAIN: ret = GAgent_GetHostByName((char *)YEELINK_SERVER, ipaddr); if (ret != 0) { OSTimeDly(200); log_warn("Get Domain name failed.\n"); goto AGAIN; } if ((TCPClientFd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { log_err("Create cloud client socket failed.\n"); return -1; } memset(&server_addr, 0x0, sizeof(struct sockaddr_in)); memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(CLOUD_SERVER_PORT_NUM); server_addr.sin_addr.s_addr = inet_addr(ipaddr); log_info("Cloud server:%s(port:%d, socketfd:%d).\r\n", ipaddr, CLOUD_SERVER_PORT_NUM, TCPClientFd); ret = connect(TCPClientFd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)); if (ret < 0) { log_err("Cloud server connected failed(ret:%d)\n", ret); close(TCPClientFd); TCPClientFd = -1; return -1; } TCPClient_reset_flag = 1; return 0; }