frame

How do I create a simple HTTP GET API with Zerynth

des Member
edited August 7 in General
So I am trying to merge two examples into one in order to create a HTTP GET API on my Particle Photon with Zerynth Studio r2.0.9


1. I created a simple resource on Flash based on the Resource Example , the resource is called
resource.json

{
node: 1,
uptime: 0.0, // here will be the software timer value
location: "x",
sensor: {
Eu: { // Euler Angles from BNO055 will be placed here
h: 0.0,
p: 0.0,
r: 0.0
},
La: { // Linear Acceleration Angles from BNO055 will be here
x: 0.0,
y: 0.0,
z: 0.0
}
}
}
2. I created a
  new_resource('resource.json')
3. I took the steps from the Simple Web Server Example to create a HTTP Server which would return the above mentioned JSON but I am not sure how to do that so I wrote the following:

def JSON_API(client):
jFile = open('resource://resource.json')
d = json.loads(jFile)
print(json.dumps(d), stream=client)

4.  I connected to an AP and here is the code to fetch me the JSON when I use curl from another device (Laptop) connected on the same AP.
sock = socket.socket()
sock.bind(8080) # http port
sock.listen()
while True:
try:
print('waiting for connection')
clientsock, addr = sock.accept()

client = streams.SocketStream(clientsock)
print('Call for API', stream=clientsock)
# call JSON
JSON_API(clientsock)

client.close()

except Exception as e:
print('Exception ', e)

I can ping the Particle Photon but I am not sure if I am curling the right way i.e.
curl http://ipOfPhoton:8080/
I can observe the string Call For API after curl but cannot see the JSON Resource.
is there something missing here?


Thanks,

Shan

Comments

  • des Member
    So found the solution.
    I had to perform a readline() and then a json.dumps of the line read.

    I also had to write resource.json in one single line.
    import streams
    import json
    import socket
    from wireless import wifi
    from broadcom.bcm43362 import bcm43362 as wifi_driver

    streams.serial()

    new_resource("resource.json")


    wifi_driver.auto_init('DE')

    try:

    wifi.link('Pi3-AP', wifi.WIFI_WPA2, 'raspberry')
    except Exception as e:
    raise e

    print('MY IP: ', wifi.link_info()[0])


    sock = socket.socket()
    sock.bind(8080)
    sock.listen()


    while True:
    try:
    print('waiting for connection')
    clientsock, addr = sock.accept()

    client = streams.SocketStream(clientsock)

    #print('Call for API', stream=client)
    jFile = open('resource://resource.json')
    line = jFile.readline()
    print(json.dumps(line), stream=client)
    client.close()

    except Exception as e:
    print('Exception ', e)

    now,

    Request: curl http://ipOfPhoton:8080/
    Response: 
    "{\"node\":1, \"uptime\": 0, \"location\": \"x\", \"sensor\":{\"Eu\":
    {\"h\":0, \"p\": 0, \"r\":0}, \"La\":{\"x\": 0, \"y\": 0, \"z\": 0}}"

Sign In or Register to comment.

ZERYNTH Community

@ 2016 Zerynth.com, all rights reserved.