Outils pour utilisateurs

Outils du site


issue167:python

First things first. Last month, I gave you a quick overview of the RTK.GPIO board, so I thought I’d give you a quick update. I tried some “normal” GPIO type tests, and they worked well. However, when I tried an I2C program to a simple I2C device, it failed to run. I’ll try to keep playing and let you know. Now, on to the Raspberry Pi Pico board. Yes it did come in. The darn thing is so tiny, and I’m so old with bad eyesight, that it was hard for me to solder the pins for the breadboard. I did it, without any shorts (or melting the board), but it took me twice as long as it would have 4 years ago. It worked pretty well, I must say. There are lots of possibilities for the RP2040 chipset and I can see many powerful microcontroller boards coming out in the future based on it. As they say in Texas, “They done did GOOD!” (I don’t say that, but ‘they’ do).

Commençons par le commencement. Le mois dernier, je vous ai donné un rapide aperçu de la carte RTK.GPIO ; j'ai pensé maintenant vous donner une rapide mise à jour. J'ai essayé quelques tests de type « normaux » sur les GPIO, et ils ont bien fonctionné. Cependant, lorsque j'ai essayé un programme I2C vers un simple périphérique I2C, il n'a pas fonctionné. Je vais essayer de continuer à jouer et je vous tiendrai au courant.

Maintenant, passons à la carte Raspberry Pi Pico. Oui, elle est arrivée. Cette satanée chose est si petite, et je suis si vieux avec une mauvaise vue, qu'il était difficile pour moi de souder les broches pour le circuit d'essai. Je l'ai fait, sans court-circuit (et sans faire fondre la carte), mais cela m'a pris deux fois plus de temps qu'il m'aurait fallu il y a 4 ans. Cela a plutôt bien fonctionné, je dois dire. Il y a beaucoup de possibilités pour le chipset RP2040 et j'imagine de nombreuses cartes de microcontrôleurs puissants basées dessus sortant à l'avenir. Comme on dit au Texas, « Ils ont VRAIMENT fait du bon travail ».

This month, we’ll revisit free weather APIs on the Internet. Why? Well many of them have either closed down or gone to a full pay model, so the choices have changed. When I’m sitting in my living room, I want to be able to check the weather outside and get the forecast for my location. Since I live in an apartment, a proper freestanding weather station is just not possible, so I have to rely on an outside source. I did a quick check the other day and found one that has a plan that I can get behind. It’s called Weather API, and you can visit their homepage at https://www.weatherapi.com/. They offer 5 plans, one of which is free. Their free plan offers the ability to make 1,000,000 calls per month which works out to over 2,000 calls per day. Plenty to get a reasonable source of information. They offer return data in either XML or JSON format. We’ll explore both formats, and some of the data that is returned.

Ce mois-ci, nous allons revenir sur les API météo gratuites sur Internet. Pourquoi ? Eh bien, beaucoup d'entre elles ont fermé ou sont passées à un modèle entièrement payant, de sorte que les choix ont changé. Lorsque je suis assis dans mon salon, je veux pouvoir vérifier le temps qu'il fait dehors et obtenir les prévisions pour mon emplacement. Comme j'habite en appartement, il m'est impossible d'installer une station météorologique autonome ; je dois donc m'en remettre à une source extérieure.

J'ai fait une vérification rapide l'autre jour et j'ai trouvé un site qui a un plan que je peux accepter. Il s'agit de Weather API et vous pouvez voir la page d'accueil à l'adresse https://www.weatherapi.com/. Il propose 5 plans, dont un gratuit. Leur plan gratuit permet de passer 1 000 000 d'appels par mois, soit plus de 2 000 appels par jour. C'est suffisant pour obtenir une source d'information raisonnable.

Les retours de données sont au format XML ou JSON. Nous allons explorer les deux formats, ainsi que certaines des données qui sont renvoyées.

Before you can get anything, you need to sign up for a free API key. Point your favorite browser to https://www.weatherapi.com/signup.aspx, and you will be connected to the Sign-up page. It’s very simple. Just type your email address twice, create a password and enter it twice, and click the “I’m not a robot” box, then agree to the Terms and Conditions. Finally, click the “Sign Up” button. You’ll get an email asking you to verify your email, and you’ll receive a key. Be sure to save this key somewhere, because you’ll need it as part of any queries to the system. As we have done before, this API has you build the http query with the query type, the location you want, and your API key. Here is what the simplest format (with my API key obscured) looks like… http://api.weatherapi.com/v1/current.json?key=xxxxxxxxxxxxxxxxxxx&q=78748

Avant de pouvoir obtenir quoi que ce soit, vous devez vous inscrire pour avoir une clé API gratuite. Dirigez votre navigateur préféré vers https://www.weatherapi.com/signup.aspx, et vous serez connecté à la page d'inscription. C'est très simple. Il suffit de saisir deux fois votre adresse mail, de créer un mot de passe et de le saisir deux fois, de cliquer sur la case « Je ne suis pas un robot », puis d'accepter les conditions générales. Enfin, cliquez sur le bouton « Sign Up ». Vous recevrez un courrier électronique vous demandant de vérifier votre adresse mail, et vous recevrez une clé. Veillez à enregistrer cette clé quelque part, car vous en aurez besoin pour toute requête adressée au système.

Comme nous l'avons fait auparavant, cette API vous demande de formuler la requête http avec le type de requête, l'emplacement souhaité et votre clé API. Voici à quoi ressemble le format le plus simple (avec ma clé API masquée) : http://api.weatherapi.com/v1/current.json?key=xxxxxxxxxxxxxxxxxxx&q=78748

Here’s the breakdown of the URL: Base URL Address: http://api.weatherapi.com/v1/ Type of query: current.json Your API Key: ?key=xxxxxxxxxxxxxxxxxxx Location: &q=78748 Additional Parms (if any) The URL can easily be constructed from variables and an “f-string”… Base = ‘http://api.weatherapi.com/v1/’ Query = ‘current.json’ Key = ‘?key=xxxxxxxxxxxxxxxxxxx’ Location = ‘&q=78748’ link = f“{Base}{Query}{Key}{Location}“

Voici le détail de l'URL :

Adresse URL de base : http://api.weatherapi.com/v1/

Type de requête : current.json Votre clé API : ?key=xxxxxxxxxxxxxxxxxxx

Emplacement : &q=78748

Paramètres supplémentaires (le cas échéant)

L'URL peut facilement être créée à partir de variables et d'une « f-string »…

Base = ‘http://api.weatherapi.com/v1/

Query = ‘current.json’

Key = ‘?key=xxxxxxxxxxxxxxxxxxx’

Location = ‘&q=78748’

link = f”{Base}{Query}{Key}{Location}”

The location can be “US Zipcode, UK Postcode, Canada Postalcode, IP address, Latitude/Longitude (decimal degree), or city name.” Of course, the IP address needs to be your EXTERNAL IP address, not your local internal IP address. You can paste the URL into the browser of your choice, and the result looks something like the code shown right. You can ask for the data to be returned in JSON format (as we did here), or XML format. Here is the link to the API docs: https://www.weatherapi.com/docs/. There are many options here. As I was writing this article, they added two new options, Weather Alerts and Air Quality.

L'emplacement peut être « un code postal américain, un code postal britannique, un code postal canadien, une adresse IP, une latitude/longitude (degré décimal) ou un nom de ville ». Bien entendu, l'adresse IP doit être votre adresse IP EXTERNE, et non votre adresse IP interne locale.

Vous pouvez coller l'URL dans le navigateur de votre choix, et le résultat ressemble au code illustré à droite.

Vous pouvez demander que les données soient renvoyées au format JSON (comme nous l'avons fait ici) ou au format XML.

Voici le lien vers la documentation de l'API : https://www.weatherapi.com/docs/. Il existe de nombreuses options. Au moment où j'écrivais cet article, deux nouvelles options ont été ajoutées, les alertes météo et la qualité de l'air.

Before we get into code, let’s take a quick look at the forecast call. http://api.weatherapi.com/v1/forecast.json?key=xxxxxxxxxxxxxxxxxx&q=78748&days=3&aqi=yes&alerts=yes For the free API account, you can have a forecast for up to 3 days. The number of days depends on the level of account you have signed up for. So the big changes from our previous current-weather query is the “forecast.json” instead of “current.json” string, and the addition of days, aqi=yes (aqi stands for Air Quality Index), and the alerts=yes. There is also a language option that you can use, but you should look at the documentation to get the correct parameter. When we send this query to the API, you’ll get back a LARGE amount of data. I’ll just paste a portion here (below).

Avant d'entrer dans le code, jetons un coup d'œil rapide à la demande de prévisions.

http://api.weatherapi.com/v1/forecast.json?key=xxxxxxxxxxxxxxxxxx&q=78748&days=3&aqi=yes&alerts=yes

Pour le compte API gratuit, vous pouvez avoir une prévision pour un maximum de 3 jours. Le nombre de jours dépend du niveau de compte auquel vous avez souscrit.

Les principaux changements par rapport à notre précédente requête de météo actuelle sont donc la chaîne « forecast.json » au lieu de « current.json », l'ajout de jours, aqi=yes (aqi signifie indice de qualité de l'air) et les alertes=yes. Il existe également une option de langue que vous pouvez utiliser, mais vous devez consulter la documentation pour obtenir le paramètre correct.

Lorsque nous envoyons cette requête à l'API, nous obtenons en retour une GRANDE quantité de données. Je vais en coller juste une partie ici (ci-dessous).

You get the location information and current condition information, just like when we did the current query. In addition to that, you also get the Air Quality information, since we asked for it (bottom left). Next comes the forecast information. Under the general [‘forecast’] header, you get a forecastday group of data for each of the days that you requested (3 in this case), each of which starts with “date” and “date_epoch”, then goes on to giving a day overview followed by the astronomy data for that day (sunrise, sunset, etc), then 24 hours of data grouped by hour. Then it repeats for each extra day that you requested, then finally any alert data that might have been issued. Each of these data groups are pretty much the same as the current condition data. It’s a lot of data – which is why I used JSON format for the ease of picking out what I want on any call.

Vous obtenez les informations de localisation et les informations sur les conditions actuelles, tout comme lorsque nous avons effectué la demande des conditions actuelles. En plus de cela, vous obtenez les informations sur la qualité de l'air, puisque nous les avons demandées (en bas à gauche).

Viennent ensuite les informations sur les prévisions. Sous l'en-tête général ['forecast'], vous obtenez un groupe de données pour chacun des jours que vous avez demandés (3 dans ce cas), chacun d'entre eux commençant par « date » et « date_epoch », puis donnant un aperçu du jour suivi des données astronomiques pour ce jour (lever, coucher du soleil, etc.), puis 24 heures de données groupées par heure. Le processus se répète ensuite pour chaque jour supplémentaire que vous avez demandé, avec, à la fin, toutes les données d'alerte qui ont pu être émises. Chacun de ces groupes de données est à peu près identique aux données sur les conditions actuelles.

Cela fait beaucoup de données, c'est pourquoi j'ai utilisé le format JSON pour faciliter la sélection de ce que je veux à chaque appel.

The Code Now we can concentrate on the code. Luckily, it is very similar to the logic that we’ve used before. As always, we start with our imports… import requests import json We now define some of our variables. When we run the program, our output will look something like that shown right. That’s it. Very simple and easily modifiable to add or delete elements as you wish – to customize the output to your needs. I’ve placed the code on my github repository at https://github.com/gregwa1953/FCM-167.

Le code

Nous pouvons maintenant nous concentrer sur le code. Heureusement, il est très similaire à la logique que nous avons utilisée auparavant. Comme toujours, nous commençons par nos importations :

import requests

import json

Nous définissons maintenant certaines de nos variables.

Lorsque nous exécutons le programme, la sortie ressemblera à l'illustration de droite.

C'est tout. Très simple et facilement modifiable pour ajouter ou supprimer des éléments comme vous le souhaitez, pour adapter le résultat à vos besoins.

J'ai placé le code sur mon dépôt github à https://github.com/gregwa1953/FCM-167.

One final thing. Last month, I promised that I would give my first impressions of the Raspberry Pi Pico microcontroller. I had originally intended doing the update here, but even before I got the Pico board in, I was so excited that I talked to Ronnie about creating another series of articles under a separate title. He said that it would be no problem, so I will now be trying to do two articles a month, one on “standard Python” and one on working with Microcontrollers using MicroPython and CircuitPython. I’m sure that every once-in-a-while, there will be an occasional crossover project that will take up both. Be sure to check out my new article series called “Micro This Micro That” in this and future issues of Full Circle! As always, until next time; stay safe, healthy, positive and creative!

Une dernière chose. Le mois dernier, j'ai promis que je donnerais mes premières impressions sur le microcontrôleur Raspberry Pi Pico. J'avais initialement prévu de faire cette mise à jour ici, mais avant même d'avoir reçu la carte Pico, j'étais tellement enthousiaste que j'ai parlé à Ronnie de la possibilité de créer une autre série d'articles avec un titre distinct. Il m'a dit que ce n'était pas un problème ; ainsi, je vais maintenant essayer de faire deux articles par mois, un sur le « Python standard » et un sur le travail avec les microcontrôleurs en utilisant MicroPython et CircuitPython. Je suis sûr que de temps en temps, il y aura un projet croisé qui occupera les deux.

Ne manquez pas de consulter ma nouvelle série d'articles intitulée « Micro This Micro That » dans ce numéro et les suivants du Full Circle !

Comme toujours, jusqu'à la prochaine fois, restez en sécurité, en bonne santé, positif et créatif !

issue167/python.txt · Dernière modification : 2021/04/04 15:38 de andre_domenech