Python Forum
display multiple sensors on webpage python flask jinja
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
display multiple sensors on webpage python flask jinja
#6
This could be improved:
def read_sensor(sensorID):  
    tempfile = open("/sys/bus/w1/devices/"+ sensorID +"/w1_slave")
    thetext = tempfile.read()
    tempfile.close()
    tempdata = thetext.split("\n") [1].split(" ")[9]
    temperature = float(tempdata[2:])
    temp_sensor = temperature / 1000
    return (temp_sensor)
Using pathlib and regular expression and context manager.
from pathlib import Path
import re


DS18B20 = re.compile(r't=(\d{5})')
# regex to get the temperature
# seek for t=5-digits


def read_sensor(sensorID):
    device = Path('/sys/bus/w1/devices') / str(sensorID) / 'w1_slave'
    with device.open() as fd:
        data = fd.read()
    match = DS18B20.search(data)
    # match is None, if nothing was found
    if not match:
        raise Exception('Could not read data from sensor {}'.format(sensorID))
    temperature = float(match.group(1))
    # group 1 is the first match in parenthesis 
    return temperature / 1000
BTW: I prefer single quotes. This does not mean, that you have to use single quotes.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: display multiple sensors on webpage python flask jinja - by DeaD_EyE - Jan-29-2019, 09:26 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Solved] Browser won't parse text from yaml loaded into Jinja SpongeB0B 1 1,074 Jul-07-2022, 09:37 PM
Last Post: SpongeB0B
Question Accessing a value of a dictionary with jinja.... SpongeB0B 2 10,943 Aug-06-2021, 09:05 AM
Last Post: ndc85430
  Help using Flask for a countdown on webpage ZenBuddhism 1 2,334 Feb-05-2021, 03:35 PM
Last Post: snippsat
  Using range slider in flask webpage to use in python KimPet 2 7,852 Jan-23-2021, 11:58 PM
Last Post: snippsat
  Flask, Display a picture outisde the static SpongeB0B 6 16,183 Aug-29-2020, 05:15 PM
Last Post: nilamo
  python 3.7 on windows using flask and flask-sqlalchemy. Alpy 2 4,087 Aug-12-2020, 07:24 PM
Last Post: Alpy
  How to display XML tree structure with Python? sonicblind 13 42,623 Aug-12-2020, 02:05 PM
Last Post: mreshko
  Jinja sort values from request.form SpongeB0B 2 2,343 Jul-26-2020, 07:41 AM
Last Post: SpongeB0B
  how to create dynamic arguments to be passed in jinja template in url_for function? experimental 1 2,879 May-01-2020, 05:50 PM
Last Post: Larz60+
  Python values on a WebPage Petrouil 1 1,978 Apr-01-2020, 05:08 PM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020