0

I'm trying to send some data from a BME280 sensor (temperature, humidity, and pressure) as JSON to a Flask server using a Raspberry Pi.

The data appears to be hitting at the Flask server OK because it prints out on the Raspberry Pi fine. However, when I try to access the server on another device connected to the network (laptop running Postman) I get a null response.

Here is the portion of the main script that's gathering the JSON. This part also prints the climate data to an LCD:

    temp1 = str(round(sensor.read_temperature(), 1))
    humi1 = str(round(sensor.read_humidity(), 1))
    pres1 = str(round(in_kilopascals, 1))
    dewp1 = str(round(calc_dewpoint(in_degrees_short, in_humidity_short), 1))
    lcd_string("Temp: " + temp1 + "C ",LCD_LINE_1,2)
    lcd_string("Humidity: " + humi1 + "% " ,LCD_LINE_2,2)
    lcd_string("Pressure: " + pres1 + "kPa",LCD_LINE_3,2)
    lcd_string("Dewpoint: " + dewp1 + "C",LCD_LINE_4,2)
    payload = {"Temperature": temp1,
                "Humidity": humi1,
                "Pressure": pres1,
                "Dewpoint": dewp1
                }
    r = requests.post('http://10.0.1.16:5000/pi', json=payload)
    if r.ok:
            print r.json()
    sleep()

I also have this separate script in the same folder:

    #!/usr/bin/env python

    from flask import Flask, request, jsonify

    app= Flask(__name__)

    @app.route("/pi", methods=['GET', 'POST'])
    def pi():
        pi_data = request.json
        print('Value on server', pi_data)
        return jsonify(pi_data)

    if __name__ == "__main__":
        app.run(debug=True)

1 Answers1

0

I don't understand your setup (the only part I'm familiar with is Postman), but I would avoid those

str(round(sensor.read_something(), 1))

and replace them with

"{:.1f}".format(sensor.read_something())

or (old style)

"%.1f" % sensor.read_something()

It's not clear to me when a problem can arise, but I know it can arise, because that round() still converts a float to a float, which does not make me feel safe regarding the number of decimals its string representation needs. I can personally only be reassured by a format() operation.

Walter Tross
  • 12,237
  • 2
  • 40
  • 64