Open pgmsoul opened 8 years ago
bool initDhcp(){
if(!dhcp) return true;
int ret;
etherUdp.udp.stop();
unsigned long t = millis();
ret = Ethernet.begin(mac);
print_f("get dhcp success:%d\n",millis()-t);
if(ret){
cfg.etherIP = Ethernet.localIP();
Serial.print("localIP: ");
Serial.println(cfg.etherIP);
Serial.print("subnetMask: ");
Serial.println(Ethernet.subnetMask());
Serial.print("gatewayIP: ");
Serial.println(Ethernet.gatewayIP());
Serial.print("dnsServerIP: ");
Serial.println(Ethernet.dnsServerIP());
bool b = etherUdp.udp.begin(UDP_MODLE_PORT);
print_f("udp server startup in port %d %s\n",UDP_MODLE_PORT,b?"success":"failed");
}else{
print_f("get dhcp failed");
}
dhcp = ret==0;
return ret!=0;
}
int send(const char* data,int len = 0){
IPAddress servIp = udp.remoteIP();
Serial.println(servIp);
//EthernetUDP cudp;
if(!cudp.beginPacket(servIp,UDP_SERV_PORT)) return 0;
if(len==0) len = strlen(data);
len = cudp.write(data,len);
cudp.endPacket();
print_f("send complete %d\n",len);
return len;
}
void EtherUdp::recv(){
int size = udp.parsePacket();
if(size<=0) return;
char buf[512];//not recv long message ,limit to 128 bytes
size = udp.read(buf,sizeof buf);
buf[size] = 0;
if(strcmp(buf,"get_net_modle_param")==0){
String str = cfg.infoString();
send(str.c_str(),str.length());
}else if(strcmp(buf,"set_net_modle_param")==0){
if(cfg.parseParam(buf)){
send("ok",0);
}else{
send("set_net_modle_param failed",0);
}
}else{
send("command isn't reconnize",0);
}
en.dhcp = true;
print_f("%s\n",buf);
}
and i find resolution:
EthernetUDP udp;
udp.begin(port);
void loop(){
int len = udp.recv();
if(len>0){
some code
udp.send();
udp.flush();
udp.stop();
udp.begin(prot);
//every time you must re call all function ,not like in pc only do once
}
}
Thx YOU VEARY MUCH!
when udp has send a data once,if recall Ethernet.begin(mac),then can't send success,error is “previous packet on that connection not sent yet”