Help sending json
-
Hi
I'm coming from arduino but I prefer the pycom hardware, so I'm migrating all my devices to this platform.
Finally all my sensors are read by gpy, and wifi connect to my network,
But my question is, do you have any idea how to compose and send json, in C we defined the concoctions:
char server[] = "theblue.io"; #not real server
char path[] = "/api/v2/gprs";
int port = 11880;we compose the json with a library
StaticJsonBuffer<300> jsonBuffer; JsonObject& root = jsonBuffer.createObject(); root["dot"] = "gsm001"; //JsonArray& data = root.createNestedArray("data"); // Build your own object tree in memory to store the data you want to send in the request // JsonObject& root = jsonBuffer.createObject(); // root["dot"] = dot; // JsonObject& data = root.createNestedObject("data"); data.set("5", shttemp); data.set("6", vpress); data.set("7", shthum); data.set("14", BatteryLevel);
and send the data:
if (client.connect(server, port)) { postToTBD(root); gsmAccess.shutdown(); } else { // if you didn't get a connection to the server: Serial.println("connection failed"); gsmAccess.shutdown();
How could I do that in mycropython? any guide o tutorial please?
Thank's
-
In python, we'd use a socket, something like this
over raw TCP: (you could fabricate your own HTTP header
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #use the inet interface, and TCP socket s.connect(socket.getaddrinfo('www.micropython.org', 80)[0][-1]) s.sendall(json)
or using urequests, this is not built into the pycom firmware, but available as a library: (you can place it in the lib folder in your project to include it in your project): https://github.com/micropython/micropython-lib/blob/master/urequests/urequests.py
and the API pages: https://makeblock-micropython-api.readthedocs.io/en/latest/public_library/Third-party-libraries/urequests.html
-
Hi @Gijs
thank'you very much for your help, it has been very use full, one more question, how could I post this json? In Arduino we use Http library, how could I do in Pycom?
Thanks' for your patience
Best
Eduard
-
In micropython, we have the
ujson
module: https://docs.pycom.io/firmwareapi/micropython/ujson/there's several examples on the internet explaining how to create a JSON object in python as well (which works really similar to micropython), I'll link one in here: https://www.kite.com/python/answers/how-to-create-a-json-object-in-python, or https://www.w3schools.com/python/python_json.asp
That is one of the easier things in python, we dont need to care about data types all that much.