espressif / arduino-esp32

Arduino core for the ESP32
GNU Lesser General Public License v2.1
13.28k stars 7.35k forks source link

Wifi connected but unable to connect to host. #1223

Closed van350 closed 5 years ago

van350 commented 6 years ago

-

Hardware:

Board: ESP32 Dev Module Core Installation/update date: ?11/jul/2017? IDE name: Platform.io Flash Frequency: 40Mhz Upload Speed: 115200

Description:

Describe your problem here

I just got my esp32 this week and am unable to the httpClient sample code work properly.

The output indicates that I am able to connect to the network, however when the code reaches the: if(!client.connect(host,httpPort) it fails to connect to the host.

I should also note that it seems like the IP generated appears to be out of my local network. I.E. default gateway is 192.168.1.1, subnet mask is: 255.255.255.0 but the ipaddress given to the device is 192.168.10.1. I have also tried to set a static IP, when I did this I was no longer able to even connect to the wifi router.

Any help would be greatly appreciated.

Sketch:


//Change the code below by your sketch
#include <Arduino.h>
#include <WiFi.h>

const char* ssid     = "ssid";
const char* password = "password";

const char* host = "data.sparkfun.com";
const char* streamId   = "....................";
const char* privateKey = "....................";

void setup()
{
    Serial.begin(115200);
    delay(10);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

int value = 0;

void loop()
{
    delay(5000);
    ++value;

    Serial.print("connecting to ");
    Serial.println(host);
    Serial.println(WiFi.localIP());

    while (WiFi.status() != WL_CONNECTED) {
        Serial.print("not connected");
        return;
    }
    // Use WiFiClient class to create TCP connections
    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
    }

    // We now create a URI for the request
    String url = "/input/";
    url += streamId;
    url += "?private_key=";
    url += privateKey;
    url += "&value=";
    url += value;

    Serial.print("Requesting URL: ");
    Serial.println(url);

    // This will send the request to the server
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "Connection: close\r\n\r\n");
    unsigned long timeout = millis();
    while (client.available() == 0) {
        if (millis() - timeout > 5000) {
            Serial.println(">>> Client Timeout !");
            client.stop();
            return;
        }
    }

    // Read all the lines of the reply from server and print them to Serial
    while(client.available()) {
        String line = client.readStringUntil('\r');
        Serial.print(line);
    }

    Serial.println();
    Serial.println("closing connection");
}

Debug Messages:

Enable Core debug level: Debug on tools menu of Arduino IDE, then put the serial output here 
stickbreaker commented 6 years ago

data.sparkfun.com has died Data has Died

Phant is No Longer in Operation Unfortunately Phant, our data-streaming service, is no longer in service. The system has reached capacity and, like a less-adventurous Cassini, has plunged conclusively into a fiery and permanent retirement. There are several other maker-friendly, data-streaming services and/or IoT platforms available as alternatives. The three we recommend are Blynk, ThingSpeak, and Cayenne. You can read our blog post on the topic for an overview and helpful links for each platform. The code in this tutorial will need to be adjusted to work with the other data streams.

van350 commented 6 years ago

stickbreaker: Thanks for the quick response. I am a little confused though, I was aware that the service was no longer active, but was operating under the assumption that I should have still been able to establish a connection to the host as it was just an ip address. I tried to establish a connection to other host and local ip addresses but was still not able to get the WiFiClient client to be connected. maybe I just dont have a good understanding of what it is doing. is there a better api or documentation source other than just shifting through the files. currently I am just using atom with platformio and navigating the code flow seems pretty clumsy for a newbie. Thanks again

van350 commented 6 years ago

Similiarly, I've used this tutorial for a simple get request: https://techtutorialsx.com/2017/05/19/esp32-http-get-requests/

The httpCode always returns <= 0. just not having much luck with the troubleshooting.

stickbreaker commented 6 years ago

@van350 Try this simple sketch. It sets up the ESP32 as a simple webServer on port 80

SimpleWiFiServer.zip

Serial Output:

Please Enter SSID(ssid): Belkin.464C

Please Enter Password(password): password

Connecting to Belkin.464C
Disconnected......
Connected
WiFi connected.
IP address: 
192.168.2.15

Load this sketch onto your ESP32 then use your computer's webbrowser to connect to it.

Your Ip will probably be different.

Looking at your sketch:

   client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "Connection: close\r\n\r\n");

I don't think that will create what you want;

   client.printf("GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" ,url.c_str(),host );

Chuck.

stickbreaker commented 6 years ago

@van350 try making your request string as simple as possible:

  char host[] = "www.google.com";
  char url[] = "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n";

    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
    }
  Serial.print("Requesting URL: ");
    Serial.println(url);

    // This will send the request to the server
    client.print(url);
    unsigned long timeout = millis();
    while (client.available() == 0) {
        if (millis() - timeout > 5000) {
            Serial.println(">>> Client Timeout !");
            client.stop();
            return;
        }
    }
    // Read all the lines of the reply from server and print them to Serial
    while(client.available()) {
       Serial.print(client.read());
       }

    Serial.println();
    Serial.println("closing connection");
    client.close();

you should get a page of gunk like this:

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content
="Search the world's information, including webpages, images, videos and more. Google has many speci
al features to help you find exactly what you're looking for." name="description"><meta content="noo
dp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="
/logos/doodles/2018/celebrating-george-peabody-4943849993535488-l.png" itemprop="image"><meta conten
t="Celebrating George Peabody" property="twitter:title"><meta content="Celebrating George Peabody! #
GoogleDoodle" property="twitter:description"><meta content="Celebrating George Peabody! #GoogleDoodl
e" property="og:description"><meta content="summary_large_image" property="twitter:card"><meta conte
nt="@GoogleDoodles" property="twitter:site"><meta content="https://www.google.com/logos/doodles/2018
/celebrating-george-peabody-4943849993535488-2x.jpg" property="twitter:image"><meta content="https:/
/www.google.com/logos/doodles/2018/celebrating-george-peabody-4943849993535488-2x.jpg" property="og:
image"><meta content="1150" property="og:image:width"><meta content="460" property="og:image:height"
><title>Google</title><script nonce="u6gurZKOb7NZwE3gyFNWrw==">(function(){window.google={kEI:'CFGrW
pSzBoLUjwO3yqho',kEXPI:'1353746,1353809,1354276,1354915,1355218,1355458,1355675,1355761,1355893,1356
440,1356779,1356817,1356854,1357219,1357560,1358004,1358111,3700319,3700440,3700521,4029815,4031109,
4043492,4045841,4048347,4081039,4096834,4097147,4097922,4097929,4098733,4098740,4103845,4107294,4107
914,4108511,4109316,4115697,4116279,4116926,4116927,4116935,4118798,4119032,4119034,4119036,4120660,
4121175,4121806,4122511,4123640,4125837,4126201,4126754,4126869,4127086,4127418,4127744,4128586,4129
520,4129633,4131247,4131836,4133509,4135025,4135249,4136073,4136092,4136136,4137597,4137646,4137727,
4138836,4141707,4141915,4142328,4142837,4143037,4143278,4143972,4144283,4144542,4144544,4144704,4144
803,4145088,4145109,4145461,4145485,4145772,4145836,4146146,4146442,4146880,4147498,4147900,4147904,
4147943,4148268,4148304,4148608,4149017,4149271,4149689,4150005,4150017,4150189,4152351,4153062,4153
220,4153222,4153239,4153497,4153545,4153550,4153952,4154081,4154374,4154872,4155230,4155567,4155569,
4155614,4156008,4156086,4156093,4156094,4156096,4156634,4156636,4156656,4156699,4156706,4157342,4157
350,4157381,4157489,4157676,4157887,4158064,4158091,4158215,4158658,4158920,4158924,4158941,4159162,
4159385,4159619,4159779,4159794,4159844,4159886,4159903,4159934,4160141,4160274,4160713,4161004,4161
079,4161108,6513270,10200084,10202570,10202628,16200176,19000288,19000423,19000427,19001999,19002548
,19002880,19003321,19003323,19003325,19003326,19003328,19003329,19003330,19003407,19003408,19003409,
19003915,19004309,19004516,19004517,19004518,19004519,19004520,19004521,19004771,19004774,19004889,1
9004893,19005143,19005167,19005173,19005178,19005180,19005235,19005236,19005306,19005310,19005311,41
317155',authuser:0,kscs:'c9c918f0_CFGrWpSzBoLUjwO3yqho',u:'c9c918f0',kGL:'US'};google.kHL='en';})();
(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.g
etAttribute("eid")));)a=a.parentNode;return b||google.kEI};google.getLEI=function(a){for(var b=null;
a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};google.https=function(){
return"https:"==window.location.protocol};google.ml=function(){return null};google.wl=function(a,b){
try{google.ml(Error(a),!1,b)}catch(d){}};google.time=function(){return(new Date).getTime()};google.l
og=function(a,b,d,c,g){if(a=google.logUrl(a,b,d,c,g)){b=new Image;var e=google.lc,f=google.li;e[f]=b
;b.onerror=b.onload=b.onabort=function(){delete e[f]};google.vel&&google.vel.lu&&google.vel.lu(a);b.
src=a;google.li=f+1}};google.logUrl=function(a,b,d,c,g){var e="",f=google.ls||"";d||-1!=b.search("&e
i=")||(e="&ei="+google.getEI(c),-1==b.search("&lei=")&&(c=google.getLEI(c))&&(e+="&lei="+c));c="";!d
&&google.cshid&&-1==b.search("&cshid=")&&(c="&cshid="+google.cshid);a=d||"/"+(g||"gen_204")+"?atyp=i
&ct="+a+"&cad="+b+e+f+"&zx="+google.time()+c;/^http:/i.test(a)&&google.https()&&(google.ml(Error("a"
),!1,{src:a,glmm:1}),a="");return a};}).call(this);(function(){google.y={};google.x=function(a,b){if
(a)var c=a.id;else{do c=Math.random();while(google.y[c])}google.y[c]=[a,b];return!1};google.lm=[];go
ogle.plm=function(a){google.lm.push.apply(google.lm,a)};google.lq=[];google.load=function(a,b,c){goo
gle.lq.push([[a],b,c])};google.loadAll=function(a,b){google.lq.push([a,b])};}).call(this);google.f={
};var a=window.location,b=a.href.indexOf("#");if(0<=b){var c=a.href.substring(b+1);/(^|&)q=/.test(c)
&&-1==c.indexOf("#")&&a.replace("/search?"+c.replace(/(^|&)fp=[^&]*/g,"")+"&cad=h")};</script><style
>#gbar,#guser{font-size:13px;padding-top:1px !important;}#gbar{height:22px}#guser{padding-bottom:7px
 !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;posi
tion:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#
gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}
.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}
</style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padd
ing:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#36c}.
q{color:#00c}.ts td{padding:0}.ts{border-collapse:collapse}em{font-weight:bold;font-style:normal}.ls
t{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds
{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}
a.gb1,a.gb2,a.gb3,a.gb4{color:#11c !important}body{background:#fff;color:black}a{color:#11c;text-dec
oration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#36c}a:visited{color:#551a8b}a.g
b1,a.gb4{text-decoration:underline}a.gb3:hover{text-decoration:none}#ghead a.gb2:hover{color:#fff !i
mportant}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.l
sbb{background:#eee;border:solid 1px;border-color:#ccc #999 #999 #ccc;height:30px}.lsbb{display:bloc
k}.ftl,#fll a{display:inline-block;margin:0 12px}.lsb{background:url(/images/nav_logo229.png) 0 -261
px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,san
s-serif;vertical-align:top}.lsb:active{background:#ccc}.lst:focus{outline:none}</style><script nonce
="u6gurZKOb7NZwE3gyFNWrw=="></script><link href="/images/branding/product/ico/googleg_lodp.ico" rel=
"shortcut icon"></head><body bgcolor="#fff"><script nonce="u6gurZKOb7NZwE3gyFNWrw==">(function(){var
 src='/images/nav_logo229.png';var iesg=false;document.body.onload = function(){window.n && window.n
();if (document.images){new Image().src=src;}
if (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}
}
})();</script><div id="mngb"> <div id=gbar><nobr><b class=gb1>Search</b> <a class=gb1 href="http://w
ww.google.com/imghp?hl=en&tab=wi">Images</a> <a class=gb1 href="http://maps.google.com/maps?hl=en&ta
b=wl">Maps</a> <a class=gb1 href="https://play.google.com/?hl=en&tab=w8">Play</a> <a class=gb1 href=
"http://www.youtube.com/?gl=US&tab=w1">YouTube</a> <a class=gb1 href="http://news.google.com/nwshp?h
l=en&tab=wn">News</a> <a class=gb1 href="https://mail.google.com/mail/?tab=wm">Gmail</a> <a class=gb
1 href="https://drive.google.com/?tab=wo">Drive</a> <a class=gb1 style="text-decoration:none" href="
https://www.google.com/intl/en/options/"><u>More</u> &raquo;</a></nobr></div><div id=guser width=100
%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe></span><a href="htt
p://www.google.com/history/optout?hl=en" class=gb4>Web History</a> | <a  href="/preferences?hl=en" c
lass=gb4>Settings</a> | <a target=_top id=gb_70 href="https://accounts.google.com/ServiceLogin?hl=en
&passive=true&continue=http://www.google.com/" class=gb4>Sign in</a></nobr></div><div class=gbh styl
e=left:0></div><div class=gbh style=right:0></div> </div><center><br clear="all" id="lgpd"><div id="
lga"><a href="/search?site=&amp;ie=UTF-8&amp;q=George+Peabody+philanthropist&amp;oi=ddle&amp;ct=cele
brating-george-peabody-4943849993535488-l&amp;hl=en&amp;kgmid=/m/02ghmf&amp;sa=X&amp;ved=0ahUKEwiU18
epifDZAhUC6mMKHTclCg0QPQgD"><img alt="Celebrating George Peabody" border="0" height="220" src="/logo
s/doodles/2018/celebrating-george-peabody-4943849993535488-l.png" title="Celebrating George Peabody"
 width="550" id="hplogo" onload="window.lol&&lol()"><br></a><br></div><form action="/search" name="f
"><table cellpadding="0" cellspacing="0"><tr valign="top"><td width="25%">&nbsp;</td><td align="cent
er" nowrap=""><input name="ie" value="ISO-8859-1" type="hidden"><input value="en" name="hl" type="hi
dden"><input name="source" type="hidden" value="hp"><input name="biw" type="hidden"><input name="bih
" type="hidden"><div class="ds" style="height:32px;margin:4px 0"><input style="color:#000;margin:0;p
adding:5px 8px 0 6px;vertical-align:top" autocomplete="off" class="lst" value="" title="Google Searc
h" maxlength="2048" name="q" size="57"></div><br style="line-height:0"><span class="ds"><span class=
"lsbb"><input class="lsb" value="Google Search" name="btnG" type="submit"></span></span><span class=
"ds"><span class="lsbb"><input class="lsb" value="I'm Feeling Lucky" name="btnI" onclick="if(this.fo
rm.q.value)this.checked=1; else top.location='/doodles/'" type="submit"></span></span></td><td class
="fl sblc" align="left" nowrap="" width="25%"><a href="/advanced_search?hl=en&amp;authuser=0">Advanc
ed search</a><a href="/language_tools?hl=en&amp;authuser=0">Language tools</a></td></tr></table><inp
ut id="gbv" name="gbv" type="hidden" value="1"></form><div id="gac_scont"></div><div style="font-siz
e:83%;min-height:3.5em"><br><div id="prm"><style>.szppmdbYutt__middle-slot-promo{font-size:small;mar
gin-bottom:32px}.szppmdbYutt__middle-slot-promo a.ZIeIlb{display:inline-block;text-decoration:none}.
szppmdbYutt__middle-slot-promo img{border:none;margin-right:5px;vertical-align:middle}</style><div c
lass="szppmdbYutt__middle-slot-promo" data-ved="0ahUKEwiU18epifDZAhUC6mMKHTclCg0QnIcBCAQ"><a class="
NKcBbd" href="https://www.google.com/url?q=https://artsandculture.google.com/theme/IgKyEcI8CPxmLg%3F
utm_campaign%3Dgeorge-peabody%26utm_source%3Dgoogle%26utm_medium%3Dhppromo&amp;source=hpp&amp;id=190
05306&amp;ct=3&amp;usg=AFQjCNGv9-44F2AuVvmgleiRrW6hmiCs8g&amp;sa=X&amp;ved=0ahUKEwiU18epifDZAhUC6mMK
HTclCg0Q8IcBCAU" rel="nofollow">Celebrating George Peabody</a></div></div></div><span id="footer"><d
iv style="font-size:10pt"><div style="margin:19px auto;text-align:center" id="fll"><a href="/intl/en
/ads/">AdvertisingáPrograms</a><a href="/services/">Business Solutions</a><a href="https://plus.goog
le.com/116899029375914044550" rel="publisher">+Google</a><a href="/intl/en/about.html">About Google<
/a></div></div><p style="color:#767676;font-size:8pt">&copy; 2018 - <a href="/intl/en/policies/priva
cy/">Privacy</a> - <a href="/intl/en/policies/terms/">Terms</a></p></span></center><script nonce="u6
gurZKOb7NZwE3gyFNWrw==">(function(){window.google.cdo={height:0,width:0};(function(){var a=window.in
nerWidth,b=window.innerHeight;if(!a||!b){var c=window.document,d="CSS1Compat"==c.compatMode?c.docume
ntElement:c.body;a=d.clientWidth;b=d.clientHeight}a&&b&&(a!=google.cdo.width||b!=google.cdo.height)&
&google.log("","","/client_204?&atyp=i&biw="+a+"&bih="+b+"&ei="+google.kEI);}).call(this);})();</scr
ipt><div id="xjsd"></div><div id="xjsi"><script nonce="u6gurZKOb7NZwE3gyFNWrw==">(function(){functio
n c(b){window.setTimeout(function(){var a=document.createElement("script");a.src=b;google.timers&&go
ogle.timers.load.t&&google.tick("load",{gen204:"xjsls",clearcut:31});document.getElementById("xjsd")
.appendChild(a)},0)}google.dljp=function(b,a){google.xjsu=b;c(a)};google.dlj=c;}).call(this);if(!goo
gle.xjs){window._=window._||{};window._DumpException=window._._DumpException=function(e){throw e};wi
ndow._F_installCss=window._._F_installCss=function(c){};google.dljp('/xjs/_/js/k\x3dxjs.hp.en_US.HiZ
FHriZgzg.O/m\x3dsb_he,d/am\x3dVDAm/rt\x3dj/d\x3d1/t\x3dzcms/rs\x3dACT90oEK00O0HZ2hnYDAcEmzLNRSA13DTg
','/xjs/_/js/k\x3dxjs.hp.en_US.HiZFHriZgzg.O/m\x3dsb_he,d/am\x3dVDAm/rt\x3dj/d\x3d1/t\x3dzcms/rs\x3d
ACT90oEK00O0HZ2hnYDAcEmzLNRSA13DTg');google.xjs=1;}google.pmc={"sb_he":{"agen":true,"cgen":true,"cli
ent":"heirloom-hp","dh":true,"dhqt":true,"ds":"","ffql":"en","fl":true,"host":"google.com","isbh":28
,"jsonp":true,"msgs":{"cibl":"Clear Search","dym":"Did you mean:","lcky":"I\u0026#39;m Feeling Lucky
","lml":"Learn more","oskt":"Input tools","psrc":"This search was removed from your \u003Ca href=\"/
history\"\u003EWeb History\u003C/a\u003E","psrl":"Remove","sbit":"Search by image","srch":"Google Se
arch"},"nds":true,"ovr":{},"pq":"","refpd":true,"rfs":[],"sbpl":24,"sbpr":24,"scd":10,"sce":5,"stok"
:"A9GxM5IOvO7SZE2NtQWzUyznRQI"},"d":{},"ZI/YVQ":{},"U5B21g":{},"YFCs/g":{}};google.x(null,function()
{});(function(){var r=[];google.plm(r);})();(function(){var ctx=[]
;google.jsc && google.jsc.x(ctx);})();</script></div></body></html>

chuck

van350 commented 6 years ago

yeah I am not sure what is preventing it but I am still getting caught on the client.connect(): if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; }

I did have some error checking that returned: connection refused.

stickbreaker commented 6 years ago

Connection refused means the website will not respond to non secure (http:) methods. It wants (https:).
What is the url you are trying?

Chuck.

van350 commented 6 years ago

Thanks again for all the help. I was able to get some connectivity to work via HTTPSecureClient. I am still not sure why outOfTheBox sketches didnt work but I guess I am going to leave that alone for a while.

stale[bot] commented 5 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.

stale[bot] commented 5 years ago

This stale issue has been automatically closed. Thank you for your contributions.