MagTag CircuitPython - Defining INT Value From API Fetch

CircuitPython on hardware including Adafruit's boards, and CircuitPython libraries using Blinka on host computers.

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
gs314
 
Posts: 1
Joined: Mon Oct 21, 2019 11:12 pm

MagTag CircuitPython - Defining INT Value From API Fetch

Post by gs314 »

I am a Python novice and a complete CircuitPython newbie so I apologize if this is a simple question.

I've adapted a Magtag CircuitPython example (https://learn.adafruit.com/pyportal-ada ... cuitpython) to an api for a temperature sensor. An example of the response from my API call is;

Code: Select all

[{"id":"648012da3a121945321959","temperatureF":73,"date":1680020164000,"dateString":"2023-03-28T16:16:04.000Z","temperatureTrend":6,"direction":"Down","unixTS":1680020164000}]

Code: Select all

# Set up where we'll be fetching data from
DATA_SOURCE = "https://www.mytemperaturesensor.com"  //Obviously not the real URL
temperatureF_Reading = [0, 'temperatureF']
tread_Reading = [0, 'temperatureTrend']
unixTS_Reading = [0, 'unixTS']
I am able to successful display these three key elements of the API response on my Magtag. However, it appears I am displaying strings (text) associated with these 3 parameter on my Magtag. Within the code, I would like to define them as Integers (temperature and trend) and Float (timestamp) so I can do math operations on them. i.e. convert temperatureF to Celcius temperature and divide the unix timestamp in msec by 1000 to get the unix timestamp in seconds or conditional statements i.e. if temperatureF_Reading > x.

I would appreciate help in defining these parsed elements of my CircuitPython code as values (Int, Float).

Here is the full code that works for displaying the three key parameters but I want to be able to define those three as values that can be mathmatically operated on and/or subjected to conditional logic. >, ==, <

Code: Select all

# SPDX-FileCopyrightText: 2020 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT

# Be sure to put WiFi access point info in secrets.py file to connect

import time
import random
from adafruit_magtag.magtag import MagTag


# Set up where we'll be fetching data from
DATA_SOURCE = "https://www.mytemperaturesensor.com"  #Obviously not the real URL
temperatureF_Reading = [0, 'temperatureF']
tread_Reading = [0, 'temperatureTrend']
unixTS_Reading = [0, 'unixTS']

# in seconds, we can refresh about 100 times on a battery
TIME_BETWEEN_REFRESHES = 1 * 60 * 5  # 5 minute delay

magtag = MagTag(
    url=DATA_SOURCE,
    json_path=(temperatureF_Reading, tread_Reading, unixTS_Reading),
)
magtag.graphics.set_background("/bmps/Blank.bmp")

# temperatureF_Reading
magtag.add_text(
    text_font="/fonts/Impact-30.pcf",
    text_wrap=28,
    text_maxlen=120,
    text_position=(
        (magtag.graphics.display.width // 2),
        (magtag.graphics.display.height // 2) - 10,
    ),
    line_spacing=0.75,
    text_anchor_point=(0.5, 0.5),  # center the text on x & y
)

# tread_Reading
magtag.add_text(
    text_font="/fonts/Arial-Italic-12.bdf",
    text_position=(magtag.graphics.display.width // 6, 118),
    text_anchor_point=(0.5, 0.5),  # left justify this line
)

# unixTS_Reading
magtag.add_text(
    text_font="/fonts/Arial-Italic-12.bdf",
    text_position=(magtag.graphics.display.width // 2, 118),
    text_anchor_point=(0.5, 0.5),  # left justify this line
)
try:
    magtag.network.connect()
    value = magtag.fetch()
    print("Response is", value)
except (ValueError, RuntimeError, ConnectionError, OSError) as e:
    magtag.set_text(e)
    print("Some error occured, retrying! -", e)

# wait 2 seconds for display to complete
time.sleep(2)
magtag.exit_and_deep_sleep(TIME_BETWEEN_REFRESHES)

Thank you.

User avatar
neradoc
 
Posts: 542
Joined: Wed Apr 27, 2016 2:38 pm

Re: MagTag CircuitPython - Defining INT Value From API Fetch

Post by neradoc »

Hi, what makes you think they are string ?
According to the json file you are sharing they are integers, they should be returned as such.

If your goal is to change the way it's displayed on the screen, you can use the text_transform argument of add_text.
For example, if you add these functions :

Code: Select all

def format_datetime(datetime):
    return "{}/{:02}/{:02} {:02}:{:02}:{:02}".format(
        datetime.tm_year,
        datetime.tm_mon,
        datetime.tm_mday,
        datetime.tm_hour,
        datetime.tm_min,
        datetime.tm_sec,
    )

def transform_datetime(timestamp):
    datetime = time.localtime(timestamp // 1000)
    return format_datetime(datetime)
And then change the timestamp call like this:

Code: Select all

# unixTS_Reading
magtag.add_text(
    text_font="/fonts/Arial-Italic-12.bdf",
    text_position=(magtag.graphics.display.width // 2, 118),
    text_anchor_point=(0.5, 0.5),  # left justify this line
    text_transform=transform_datetime,
)
It will transform the timestamp into a string representing the date and time.
Of course you can choose to format it any way you want.
time.localtime(...) returns a time.struct_time

Note that even though it's "text_tranform", it receives the value in the type it was in the json (and must return a string).
If it is IS a string in the original data retrieved from the server, you can simply convert it to int with int(timestamp).
(Note that the timestamp should be kept an int so as not to lose any precision, floats are single precision, 30 bits actually in CP).

Locked
Please be positive and constructive with your questions and comments.

Return to “Adafruit CircuitPython”