Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[sendtohttp] thingspeak only reply event #4856

Merged
merged 31 commits into from
Jan 30, 2024

Conversation

chromoxdor
Copy link
Contributor

@chromoxdor chromoxdor commented Oct 25, 2023

I added an event for a specific thingspeak request:

  1. Get the value of a single field:

    • Example command:
      SendToHTTP,api.thingspeak.com,80,/channels/1637928/fields/5/last.csv

    • Example of the resulting event:
      "EVENT: ThingspeakReply=1637928,5,24.2"

      | channel number = %eventvalue1%
      | field number = %eventvalue2%
      | value = %eventvalue3%

  2. Get the values of all fields:

    • Example command:
      SendToHTTP,api.thingspeak.com,80,/channels/1637928/feeds/last.csv

    • Example of the resulting event:
      "EVENT:ThingspeakReply=1637928,5929,353,42.0,177,19.1,995.6,,"

      | channel number = %eventvalue1%
      | values = %eventvalue2% to %eventvalue9%

@chromoxdor
Copy link
Contributor Author

chromoxdor commented Oct 25, 2023

Rules Example:

On Rules#Timer=1 Do
  SendToHTTP, api.thingspeak.com,80,/channels/143789/feeds/last.csv
Endon

On ThingspeakReply Do
   LogEntry,'%eventvalue6%°C in Berlin'
   LogEntry,'%eventvalue7%°C in Paris'
  Endif
Endon

Output:

1050425: EVENT: http#api.thingspeak.com=200
1050433: EVENT: ThingspeakReply=143789,11.64,-0.05,5.46,14.39,2.2,6.94,-13.48,11.05
1050443: ACT : LogEntry,'2.2°C in Berlin'
1050445: 2.2°C in Berlin
1050473: ACT : LogEntry,'6.94°C in Paris'
1050476: 6.94°C in Paris

@chromoxdor
Copy link
Contributor Author

I made this optional but i am not sure if i did it right..

@chromoxdor
Copy link
Contributor Author

Should i add this to the documentation as an annotation in the SendToHTTP section?

@tonhuisman
Copy link
Contributor

Should i add this to the documentation as an annotation in the SendToHTTP section?

Yes, as it is on by default for regular builds (without LIMIT_BUILD_SIZE set).

@chromoxdor
Copy link
Contributor Author

Yes, as it is on by default for regular builds (without LIMIT_BUILD_SIZE set).

I will do it tomorrow.. my battery is empty

@chromoxdor
Copy link
Contributor Author

chromoxdor commented Oct 26, 2023

@TD-er & @tonhuisman i tried another approach where all the fields gets parsed from csv

the command: sendToHTTP,api.thingspeak.com,80,/channels/1637928/feeds/last.csv

the code:

if (httpCode == 200 && equals(host, F("api.thingspeak.com")) && uri.endsWith(F("/last.csv"))) {
        String result = http.getString();                                                                
        //created_at,entry_id,field1,field2,field3,field4,field5,field6,field7,field8^2023-10-26T16:14:17+02:00,921,5929,353,42.0,177,19.1,995.6,,                                                             
        result = result.substring(result.lastIndexOf(':'), result.length());                                                                                            
        //00,921,5929,353,42.0,177,19.1,995.6,,
        result = result.substring(result.indexOf(',', result.indexOf(',') + 1 )+1, result.length()-1);  
        //5929,353,42.0,177,19.1,995.6,,
        eventQueue.add(strformat(F("ThingspeakReply=%s,%s"),                                            
                         parseStringKeepCase(uri, 2, '/').c_str(),
                         result.c_str()));
      }

the output:
EVENT: ThingspeakReply=1637928,5929,353,42.0,177,19.1,995.6,,

Would this also be an option or are there good reasons not to do it?

@tonhuisman
Copy link
Contributor

Hmm, it looks like pygit2 is broken... 😞

@chromoxdor
Copy link
Contributor Author

Hmm, it looks like pygit2 is broken... 😞

Is there something i can do?

@TD-er
Copy link
Member

TD-er commented Oct 26, 2023

Hmm, it looks like pygit2 is broken... 😞

Is there something i can do?

Nope, those build issues are often a network issue on the build environment.
I just restarted the last failed build, so it will now probably run just fine.

@TD-er
Copy link
Member

TD-er commented Oct 26, 2023

if (posTimestamp >= 0) {

do we really need this? isn´t it kind of a redundancy to if ... uri.endsWith(F("/last.csv"))) since it is a given format which always contains the time?

Nope, server response may not be complete, or something else may be wrong.
So if the most basic check isn't working (presence of a single :), then I rather not see any event be generated.

@chromoxdor
Copy link
Contributor Author

chromoxdor commented Oct 27, 2023

Dear @TD-er,
can I smuggle this in?

Command:
sendtohttp,api.openweathermap.org,80,/data/2.5/weather?id=2950159&units=metric&appid=XXXXXX

Event:
EVENT: OpenweatherReply=2950159,9.86,8.03,8.94,11.31,982,93,3.58,80,mist

(EVENT: OpenweatherReply=<id>,<temp>,<feels_like>,<temp_min>,<temp_max>,<pressure>,<humidity>,<windspeed_m/s>,<wind_direction>,<condition>)

Response:
{"coord":{"lon":13.4105,"lat":52.5244},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"stations","main":{"temp":9.86,"feels_like":8.27,"temp_min":8.89,"temp_max":11.76,"pressure":982,"humidity":94},"visibility":4100,"wind":{"speed":3.13,"deg":83,"gust":4.47},"clouds":{"all":100},"dt":1698393307,"sys":{"type":2,"id":2011538,"country":"DE","sunrise":1698385948,"sunset":1698421669},"timezone":7200,"id":2950159,"name":"Berlin","cod":200}

Code:

if (httpCode == 200 && equals(host, F("api.openweathermap.org"))) {
          String result = http.getString(); 
          result.replace('[', '_'); //get rid of these otherwise parsing won´t work
          result.replace(']', '_');
          String wVals;
          String res;
          int Num[10]{25, 8, 9, 10, 11, 12, 13, 15, 16, 5};  

          for (int i : Num) {
            res = parseStringKeepCase(result, i);
            res = res.substring(res.lastIndexOf(':')+1);
            if (res.endsWith("}")) {res = res.substring(0,res.lastIndexOf('}'));} //get rid of
            if (i == 5) {res = res.substring(1);}                       //unwanted characters
            wVals += res;
            if (i != 5) {
              wVals += ",";
            }
          }

          eventQueue.addMove(strformat(F("OpenweatherReply=%s"),                                            
            wVals.c_str()));
        }

I would make this a custom build feauture only...

@chromoxdor
Copy link
Contributor Author

The funny thing is, i was just searching in the forum a bit if anybody had a requests regarding this topic.
To my surprise i found "somebody".
https://www.letscontrolit.com/forum/viewtopic.php?t=8500

Who would have guessed, that 2,5 years later i am the one helping me from the past...

@tonhuisman
Copy link
Contributor

Response:

That response should better be parsed as the Json it is, not try to pick out just some values. Most likely the content of that Json will change somewhere in the future, breaking your fixed indexes 🤔
Be aware that parsing Json is a relatively 'expensive' operation.

@chromoxdor
Copy link
Contributor Author

chromoxdor commented Oct 27, 2023

Be aware that parsing Json is a relatively 'expensive' operation.

That i learned with my easy2ntfy project. So this is out of the question

Most likely the content of that Json will change somewhere in the future, breaking your fixed indexes 🤔

That is a risk i am willing to take. Either i would adjust the code or remove it completely.
As i see it we have two options here. Either we don´t integrate it at all or having it with the risk, that in the future it might break. But aren´t changes in code and structure and the adjustment to it anyway something we´ll always have to account for?

Edit:

Either i would adjust the code or remove it completely.

I mean it is not added yet anyhow... :)
But it would be a nice extra. And as i already mentioned i would like to make it only availablefor custom builds...

@tonhuisman
Copy link
Contributor

But it would be a nice extra.

Yes, but the same goes for a lot of similar services, think of Weather Underground, Yahoo weather, your local weather service, etc.
Don't think we should try to add that to a Custom build only, but better find a more generic way of handling a HTTP GET/PUT/POST returned value. (that would be compile-time optional, of course)

Mostly limited by a lack of time/resources, but good ideas are always welcome & helpful. (I have some brewing in my head, I'll try to write them down 😸)

@chromoxdor
Copy link
Contributor Author

chromoxdor commented Oct 27, 2023

Yes, but the same goes for a lot of similar services, think of Weather Underground, Yahoo weather, your local weather service, etc.

Absolutely.. but in general i couldn´t find a better API than that of openweathermap. I mean that in terms of free calls per day and length of the response. Because even if we had a nice json parser, i would imagine the esp8266 to suffer or even left out.
And again having the existing solution is better than no solution at all. And while having it we still can rack our brains over finding a more general solution.
I mean.. look at this old forum entry i linked. This unknown guy Ath said back then he can help...this is now 2.5 years ago. 😁

@TD-er
Copy link
Member

TD-er commented Oct 28, 2023

Hmm, code for specific interacting with some external service and providing code to parse specific syntax...

Looks a lot like a "controller" for ESPEasy, doesn't it?

@chromoxdor
Copy link
Contributor Author

Dear @TD-er,
can I smuggle this in?

I will leave this for now and maybe we´ll find a controller solution for it in the future
For now @TD-er can you restart the build?

@tonhuisman
Copy link
Contributor

can you restart the build?

If you update to mega with the "Update branch" button, then it will have the fix that failed the last build.

@chromoxdor chromoxdor reopened this Nov 30, 2023
@TD-er TD-er merged commit 481fe3b into letscontrolit:mega Jan 30, 2024
166 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants