B4R Question [Solved with MQTT not HTTP] HTTPUtils2 sending data to Thingspeak, need help

Mark Read

Well-Known Member
Licensed User
As a followup to this thread and Erel's answer, I have stripped out all the code and think I have found the problem:

I am trying to send data to thingspeak but I cannot seem to get the code right. After two days, I think I need some help. The code is included, as is the API Key to try. The data is posted to a test channel so you can try. Only the WiFi credentials will need to be changed.
There is no real data at present, just 6 random numbers.
Thanks for any help.

Here is the log:

disconnecting Wifi
Connected successfully to: READ-Wlan
192.168.2.8
Connecting ...
Posting ...
api_key=28PCNUKAEZD2XD2J&field1=10.00&field2=14.00&field3=13.00&field4=12.00&field5=11.00&field6=13.00
trying to connect to: api.thingspeak.com port: 80 ssl: 0
connected: api.thingspeak.com

B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region

'Ctrl+Click to open the C code folder: ide://run?File=%WINDIR%\System32\explorer.exe&Args=%PROJECT%\Objects\Src


'Hardware:  Wemos D1 Mini
'Libraries: rCore, rESP8266WiFi, rHTTPUtils2, rRandomAccessFile

Sub Process_Globals
    Public Serial1 As Serial
    Public WiFi As ESP8266WiFi
       
    Public ApiKey As String="28PCNUKAEZD2XD2J"
    Public WifiSSID As String="xxxxxxxxxxxx"
    Public WifiPass As String="xxxxxxxxxxxx"
    Public ThinkspeakServer As String="api.thingspeak.com"
   
       
    Public TEMPERATURE, PRESSURE, HUMIDITY As Double
    Public HeatIndex, DewPoint, Altitude As Double
   
    Public BC As ByteConverter
   
    Public DelayTimer As Timer
   
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Log("AppStart")
       
    DelayTimer.Initialize("DelayTimer_Tick", 15000)    '10 mins = 600000
   
    DelayTimer.Enabled=True
End Sub

Sub DelayTimer_Tick
    If WiFi.IsConnected=False Then
        ConnectToNetwork
    End If
   
    TEMPERATURE=Rnd(10,15)
    PRESSURE=Rnd(10,15)
    HUMIDITY=Rnd(10,15)
    HeatIndex=Rnd(10,15)
    DewPoint=Rnd(10,15)
    Altitude=Rnd(10,15)
   
    UploadThinkgspeak
   
    ' disconnect wifi
    WiFi.Disconnect
        Log("Going to sleep ...")
End Sub

Sub UploadThinkgspeak
    ' https://api.thingspeak.com/update?api_key=28PCNUKAEZD2XD2J&field1=14.00field2=12.00&field3=13.00&field4=12.00&field5=14.00&field6=13.00
    Log("Connecting ...")
    HttpJob.Initialize("Thingspeak")
    'add headers before calling Post or Download (this is different than the standard HttpUtils2 library).
    HttpJob.AddHeader("Content-Type", "application/x-www-form-urlencoded")
       
    Dim postStr As String
    'postStr =JoinStrings(Array As String("/update?api_key=",ApiKey,"&field1=",TEMPERATURE,"field2=",PRESSURE,"&field3=",HUMIDITY,"&field4=",HeatIndex,"&field5=",DewPoint,"&field6=",Altitude))
    postStr =JoinStrings(Array As String("api_key=",ApiKey,"&field1=",TEMPERATURE,"&field2=",PRESSURE,"&field3=",HUMIDITY,"&field4=",HeatIndex,"&field5=",DewPoint,"&field6=",Altitude))
   
    Log("Posting ...")
    Log(postStr)
   
    HttpJob.Post("http://api.thingspeak.com/update", postStr)
       
End Sub

Sub JobDone (Job As JobResult)
    If Job.Success Then
        Log("Response: ", BC.SubString2(Job.Response, 0, Min(100, Job.Response.Length))) 'truncate to 100 characters
               
    Else
        Log("*******************************")
        Log("JobName: ", Job.JobName)
        Log("ErrorMessage: ", Job.ErrorMessage)
        Log("Status: ", Job.Status)
        Log(Job.Response)
    End If
End Sub

Sub ConnectToNetwork
    Log("disconnecting Wifi")
    WiFi.Disconnect
    If WiFi.Connect2(WifiSSID, WifiPass) Then
        Log("Connected successfully to: ", WifiSSID)
        Log(WiFi.LocalIp)
       
    Else
        Log("Failed to connect.")
    End If
End Sub
 

Daestrum

Well-Known Member
Licensed User
I got a response by adding CRLF to the sent data so they are talking
Connected successfully to: xxxxxxxxxxxxx
192.168.0.216
Connecting ...
Posting ...
api_key=28PCNUKAEZD2XD2J&field1=13.00&field2=14.00&field3=14.00&field4=11.00&field5=14.00&field6=11.00
Going to sleep ...
*******************************
JobName: Thingspeak
ErrorMessage: Response not available.
Status: 0
 
Upvote 0

drgottjr

Well-Known Member
Licensed User
the url is http(s)://api.thingspeak.com/update.json NOT http(s)://api.thingspeak.com/update

i didn't try with post (the api accepts a get), but i had no problem running the example with a get and with your key.
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
Upvote 0

Mark Read

Well-Known Member
Licensed User
i didn't try with post (the api accepts a get), but i had no problem running the example with a get and with your key.

Did you run my code as is? Can you elaborate a little on what you did please.
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
I got a response by adding CRLF to the sent data so they are talking
If the response was anything apart from a single number then it has not worked. Where did you add th CRLF?
 
Upvote 0

thetahsk

Active Member
Licensed User
If you paste
into a browser, you will get a single number displayed to show the data has been accepted. Therefore I think the URL is correct.

add "&" between field1 and field2
response : field1 and field2 are corrupted
{"channel_id":1325681,"created_at":"2021-03-18T07:04:18Z","entry_id":26,"field1":"14.00field2=12.00","field2":null,"field3":"13.00","field4":"12.00","field5":"14.00","field6":"13.00","field7":null,"field8":null,"latitude":null,"longitude":null,"elevation":null,"status":null}
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
I thought I had that:
B4X:
postStr =JoinStrings(Array As String("api_key=",ApiKey,"&field1=",TEMPERATURE,"&field2=",PRESSURE,"&field3=",HUMIDITY,"&field4=",HeatIndex,"&field5=",DewPoint,"&field6=",Altitude))
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
One of the two of you has managed to post data, as I can see it on the Thingspeak page.

What did you use for the two vaiables?:

B4X:
Public ThinkspeakServer As String="api.thingspeak.com"        ???

postStr =JoinStrings(Array As String("api_key=",ApiKey,"&field1=",TEMPERATURE,"&field2=",PRESSURE,"&field3=",HUMIDITY,"&field4=",HeatIndex,"&field5=",DewPoint,"&field6=",Altitude)) ???
 
Upvote 0

Daestrum

Well-Known Member
Licensed User
I will try my code again - I will set all values to 5.67 so you can see if it was my code. I also changed the timer delay - just in case the site was slow and they overlapped (45 seconds)
 
Upvote 0

drgottjr

Well-Known Member
Licensed User
If you paste
https://api.thingspeak.com/update?a...=13.00&field4=12.00&field5=14.00&field6=13.00
into a browser, you will get a single number displayed to show the data has been accepted. Therefore I think the URL is correct.
this is the GET. if you use update.json as the url, you get a formatted response. if you just use update, you get a single number back (0=fail in this case).
if you use GET, then you don't need the content-type header. i assumed you were looking for the formatted response. my bad.
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
this is the GET. if you use update.json as the url, you get a formatted response. if you just use update, you get a single number back (0=fail in this case).

I would be happy with any response, I just want to post data, 0 is naturally not good. Json looks good but I am not able to get the programming right.

I really would be greatfull for just a little more help. Thank you all.
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
Could not get my program to work with HTTPUtils2. Moved to MQTT and works great. Thanks to all for the input.
 
Upvote 0
Top