Skip to content

Instantly share code, notes, and snippets.

@txhammer68
Last active August 2, 2026 01:59
Show Gist options
  • Select an option

  • Save txhammer68/e0ae8eeffa13a310797f40fa3eb63a1a to your computer and use it in GitHub Desktop.

Select an option

Save txhammer68/e0ae8eeffa13a310797f40fa3eb63a1a to your computer and use it in GitHub Desktop.
data.qml
import QtQuick
import QtNetwork
Item {
id:getjsonDataMain // scripts to get json data
//https://query1.finance.yahoo.com/v8/finance/spark?symbols=^DJI,^IXIC,^GSPC,CL=F,GC=F,^TNX&range=1d&interval=15m&indicators=close&includeTimestamps=false&includePrePost=false&corsDomain=finance.yahoo.com&.tsrc=finance&format=json
// us treas rates
// https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/avg_interest_rates&filter=record_date:gte:2026-01-01
readonly property string symbols:"symbols=^DJI,^IXIC,^GSPC,CL=F,GC=F,BTC=F"
readonly property string url1:"https://query1.finance.yahoo.com/v8/finance/spark?"+symbols+"&range=1d&interval=5m&indicators=close&includeTimestamps=false&includePrePost=false&corsDomain=finance.yahoo.com&.tsrc=finance&format=json"
readonly property var finSymbols:["^DJI","^IXIC","^GSPC","CL=F","GC=F","BTC=F"] //6
property var finClose:[]
property var finPrevClose:[]
property string mdate:new Date().toLocaleString("dd/mm/yy h:mm ap")
property var currentTimeDate:new Date()
property string curDate:Qt.formatDate(currentTimeDate,"ddd")
property string curTime:Qt.formatTime(currentTimeDate,"hh:mm")
property string gmailTime:Qt.formatTime(currentTimeDate,"h:mm ap")
property string gmailDate:Qt.formatDate(currentTimeDate,"dddd MMMM d")
//readonly property var days:["Mon","Tue","Wed","Thu","Fri"]
readonly property string mstartTime:'08:35'
readonly property string mendTime:'15:15'
property var gmailMsgs:{}
readonly property string url2:"/tmp/gmail.json"
readonly property string url3:"/tmp/gcal.json"
property var calData:[]
property var calDayEvents:[]
property var calDayDates:[]
readonly property string url4:"https://api.weather.com/v3/wx/observations/current?language=en-US&apiKey=71f92ea9dd2f4790b92ea9dd2f779061&geocode=29.662,-95.071&units=e&format=json"
readonly property string url5:"https://api.weather.com/v3/wx/forecast/daily/5day?language=en-US&apiKey=71f92ea9dd2f4790b92ea9dd2f779061&geocode=29.66,-95.06&units=e&format=json"
readonly property string url6:"https://api.weather.com/v3/alerts/headlines?geocode=29.66,-95.06&format=json&language=en-US&apiKey=71f92ea9dd2f4790b92ea9dd2f779061"
property var forecastDays:[]
property var forecastIcons:[]
property var forecastRains:[]
property var forecastTemps:[]
property string forecastNarrative:""
property string weatherIcon:""
property string weatherTemp:"--"
property string weatherRealFeel:"--"
property string weatherHumidity:"--"
property string weatherWinds:"--"
property string lastUpdate:"NA"
property var nextUpdate:new Date().getTime()+(1000*60*15)
property var currentUTCTime:new Date().getTime()
property var forecastNextUpdate:new Date().getTime()+(1000*60*15)
property var alertNextUpdate:new Date().getTime()+(1000*60*31)
property bool wakeUp:true
property bool weatherWarnings:false
property string weatherConditions:"—"
property string weatherAlertText:""
property string radarImage:"SETX1_1280.jpg"
property bool isLoaded:false
property int key:-1
//property bool gameType:true
property string url7: gameType ? "https://site.api.espn.com/apis/site/v2/sports/baseball/mlb/scoreboard" : "https://site.api.espn.com/apis/site/v2/sports/basketball/nba/scoreboard"
property string url8: gameType ? "https://site.api.espn.com/apis/site/v2/sports/baseball/mlb/teams/18" : "https://site.api.espn.com/apis/site/v2/sports/basketball/nba/teams/10"
property string favTeam:gameType ? "Houston Astros" : "Houston Rockets"
property string gameStatusState:""
property string gameStatusDetail:""
property string gameStatusDescription:""
property string gamePeriod:""
property string gameClock:""
property string gameDate:""
property string gameHeadline:""
property string gameBoxScoresURL:""
property string gamePlayoffRecord:""
property string gameAltHeadline:""
property bool homeTeamWinner:false
property string homeTeamAbrev:""
property string homeTeamLogo:""
property string homeTeamScore:""
property string homeTeamRecord:""
property string awayTeamAbrev:""
property string awayTeamLogo:""
property string awayTeamScore:""
property string awayTeamRecord:""
property bool awayTeamWinner:false
property string teamStandings:""
Component.onCompleted: {
mdate=new Date().toLocaleString("dd/mm/yy h:mm ap")
getData(url1)
getData(url2)
getData(url3)
getData(url4)
getData(url5)
getData(url6)
getData(url7)
getData(url8)
radarImage="https://cdns.abclocal.go.com/three/ktrk/weather/16_9/SETX1_1280.jpg"
isLoaded=true
}
onCurDateChanged:{
if (!wakeUp) {
getData(url3)
}
}
onUrl7Changed:{
getData(url7)
getData(url8)
}
function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
function degToCompass(num) {
let val = Math.floor((num / 22.5) + 0.5)
let arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
return arr[(val % 16)]
}
function checkSportsCal () {
if (Qt.formatDate(currentTimeDate,"M") > 4 && Qt.formatDate(currentTimeDate,"M") < 12)
gameType=true
else gameType=false // mlb ~ april-oct, nba ~ nov-march
}
function getData(url) { // get json data sources
let xhr = new XMLHttpRequest()
xhr.timeout = 5000
xhr.open("GET",url,true) // set Method and File true=asynchronous
//xhr.responseType = 'json'
//xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (url==url1) {
let market=JSON.parse(xhr.responseText);
processMarketData(market);
}
else if (url==url2) {
let data = JSON.parse(xhr.responseText);
gmailMsgs = data;
}
else if (url==url3) {
calData = JSON.parse(xhr.responseText);
eventsForDate();
}
else if (url==url4) {
let weatherData=JSON.parse(xhr.responseText)
processWeatherData(weatherData);
}
else if (url==url5) {
let forecastData=JSON.parse(xhr.responseText);
processForecastData(forecastData);
}
else if (url==url6) {
let alertData=JSON.parse(xhr.responseText)
processAlertData(alertData);
}
else if (url==url7) {
let scores=JSON.parse(xhr.responseText);
findKey (scores);
processGameData(scores);
}
else if (url==url8) {
let teamData=JSON.parse(xhr.responseText);
teamStats (teamData);
}
}
}
}
xhr.send();
//xhr=null;
return null
}
function eventsForDate() {
calDayEvents=[]
calDayDates=[]
let events=[]
let dates=[]
for (let i = 0; i < calData.length; i++) {
if (calData[i].start == Qt.formatDate(currentTimeDate,"yyyy-MM-dd")) {
events.push(calData[i].summary)
dates.push(calData[i].start)
}
}
calDayEvents=events
calDayDates=dates
calData=null
return null
}
function teamStats (teamData) {
if (homeTeamAbrev == "HOU" || awayTeamAbrev == "HOU") {
teamStandings="HOU: "+teamData.team.standingSummary
isLoaded=true
return null
}
else {
teamStandings=""
return null
}
}
function findKey (scores) {
if (scores) {
if (Object.keys(scores.events).length > 0 ) { // check if any data exists
if (Object.keys(scores.events).length == 1) {
key=0;
scores=null
return null
}
for (let i = 0; i < Object.keys(scores.events).length; i++) {
if (scores.events[i].competitions[0].competitors[0].team.displayName===favTeam) {
key=i;
scores=null
return null
}
else if (scores.events[i].competitions[0].competitors[1].team.displayName===favTeam) {
key=i;
scores=null
return null
}
}
if (key == -1) {
key=Math.floor(Math.random() * Object.keys(scores.events).length); // else no fav team game, pick random game.
scores=null
return null
}
else if (scores.events[key].competitions[0].status.type.state == "in") {
scores=null
return null
}
else if (scores.events[key].competitions[0].status.type.state == "post") { // pick new game on refresh
key=Math.floor(Math.random() * Object.keys(scores.events).length);
scores=null
return null
}
}
}
scores=null
return null
}
function processGameData (scores) {
if (scores) {
gameStatusState=scores.events[key].competitions[0].status.type.state
gameStatusDetail=scores.events[key].competitions[0].status.type.shortDetail
gameStatusDescription=scores.events[key].competitions[0].status.type.description
gamePeriod=scores.events[key].competitions[0].status.period
gameClock=scores.events[key].competitions[0].status.displayClock
gameDate=scores.events[key].competitions[0].date
//gameTime=new Date(scores.events[key].competitions[0].date).getTime()
gamePlayoffRecord=scores.events[key].competitions[0].hasOwnProperty("series") ? scores.events[key].competitions[0].series.summary:""
gameAltHeadline=(scores.events[key].competitions[0].notes.length > 0) ? scores.events[key].competitions[0].notes[0].headline : ""
gameHeadline=scores.events[key].competitions[0].hasOwnProperty("headlines") ? scores.events[key].competitions[0].headlines[0].shortLinkText : (scores.events[key].competitions[0].notes.length > 0) ? gameAltHeadline + " " + gamePlayoffRecord : teamStandings
gameBoxScoresURL=scores.events[key].links[0].href
homeTeamAbrev=scores.events[key].competitions[0].competitors[0].team.abbreviation
homeTeamLogo=scores.events[key].competitions[0].competitors[0].team.logo
homeTeamScore=scores.events[key].competitions[0].competitors[0].score
homeTeamRecord=scores.events[key].competitions[0].competitors[0].hasOwnProperty('records') ? scores.events[key].competitions[0].competitors[0].records[0].summary : "--"
homeTeamWinner=scores.events[key].competitions[0].competitors[0].winner != undefined ? scores.events[key].competitions[0].competitors[0].winner:false
awayTeamAbrev=scores.events[key].competitions[0].competitors[1].team.abbreviation
awayTeamLogo=scores.events[key].competitions[0].competitors[1].team.logo
awayTeamScore=scores.events[key].competitions[0].competitors[1].score
awayTeamRecord=scores.events[key].competitions[0].competitors[1].hasOwnProperty('records') ? scores.events[key].competitions[0].competitors[1].records[0].summary : "--"
awayTeamWinner=scores.events[key].competitions[0].competitors[1].winner != undefined ? scores.events[key].competitions[0].competitors[1].winner:false
if (scores.events[key].competitions[0].status.type.state == "pre") {
gameTimer.interval=15*60*1000
gameTimer.restart();
}
if (scores.events[key].competitions[0].status.type.state == "in") {
gameTimer.interval=5*60*1000
gameTimer.restart();
}
else if (scores.events[key].competitions[0].status.type.state == "post") {
gameTimer.interval=1*60*60*1000
gameTimer.restart();
}
else if (scores.events[key].competitions[0].status.type.shortDetail == "Delayed") { // game delayed check again in 30 mins //
gameTimer.interval=30*60*1000
gameTimer.restart();
}
}
else {
gameTimer.interval=60*60*1000
gameTimer.restart();
gameStatusState="post"
}
scores=null
return null
}
function processMarketData (mkt) {
let x1=[], y1=[]
if (mkt) {
x1[0]=mkt[finSymbols[0]].close.slice(-1)[0]!=null ? mkt[finSymbols[0]].close.slice(-1)[0].toFixed(2):mkt[finSymbols[0]].close.slice(-2)[0].toFixed(2)
x1[1]=mkt[finSymbols[1]].close.slice(-1)[0]!=null ? mkt[finSymbols[1]].close.slice(-1)[0].toFixed(2):mkt[finSymbols[1]].close.slice(-2)[0].toFixed(2)
x1[2]=mkt[finSymbols[2]].close.slice(-1)[0]!=null ? mkt[finSymbols[2]].close.slice(-1)[0].toFixed(2):mkt[finSymbols[2]].close.slice(-2)[0].toFixed(2)
x1[3]=mkt[finSymbols[3]].close!=null ? mkt[finSymbols[3]].close.slice(-1)[0] !=null ? mkt[finSymbols[3]].close.slice(-1)[0].toFixed(2):mkt[finSymbols[3]].close.slice(-2)[0].toFixed(2) : mkt[finSymbols[3]].previousClose.toFixed(2)
x1[4]=mkt[finSymbols[4]].close!=null ? mkt[finSymbols[4]].close.slice(-1)[0] !=null ? mkt[finSymbols[4]].close.slice(-1)[0].toFixed(2):mkt[finSymbols[4]].close.slice(-2)[0].toFixed(2) : mkt[finSymbols[4]].previousClose.toFixed(2)
x1[5]=mkt[finSymbols[5]].close!=null ? mkt[finSymbols[5]].close.slice(-1)[0] !=null ? mkt[finSymbols[5]].close.slice(-1)[0].toFixed(2):mkt[finSymbols[5]].close.slice(-2)[0].toFixed(2) : mkt[finSymbols[5]].previousClose.toFixed(2)
finClose=x1
y1[0]=mkt[finSymbols[0]].previousClose.toFixed(2)
y1[1]=mkt[finSymbols[1]].previousClose.toFixed(2)
y1[2]=mkt[finSymbols[2]].previousClose.toFixed(2)
y1[3]=mkt[finSymbols[3]].previousClose.toFixed(2)
y1[4]=mkt[finSymbols[4]].previousClose.toFixed(2)
y1[5]=mkt[finSymbols[5]].previousClose.toFixed(2)
finPrevClose=y1
}
else {
x1 = Array(6).fill("--")
y1 = Array(6).fill("--")
finClose=x1
finPrevClose=y1
}
mkt=null
return null
}
function processWeatherData(weatherData) {
if (weatherData) {
// current conditions data
nextUpdate=weatherData.expirationTimeUtc*1000+15000
lastUpdate=Qt.formatTime(new Date(weatherData.validTimeUtc*1000),"h:mm ap")
weatherIcon="../icons/"+weatherData.iconCode+".png"
weatherTemp=weatherData.temperature+"°"
weatherConditions=weatherData.wxPhraseMedium
weatherRealFeel="Real Feel: "+weatherData.temperatureFeelsLike+"°"
weatherHumidity=" R/H: "+weatherData.relativeHumidity+"%"
if (weatherData.windGust != null) {
if (weatherData.windGust > 0) {
weatherWinds=" Winds: "+weatherData.windDirectionCardinal+" at "+weatherData.windSpeed+ " ~ "+ weatherData.windGust
}
}
else weatherWinds=" Winds: "+weatherData.windDirectionCardinal+" at "+weatherData.windSpeed
}
else {
lastUpdate="--"
nextUpdate=new Date().getTime()+(1000*60*20)
weatherIcon="../icons/44.png"
weatherTemp="--"
weatherConditions="--"
weatherRealFeel="Real Feel: NA"
weatherHumidity=" R/H: NA"
weatherWinds=" Winds: NA"
}
weatherData=null
return null
}
function processForecastData (forecastData) {
let d1=[], i1=[], r1=[], t1=[]
if (forecastData) {
for (var i = 0; i < Object.keys(forecastData.calendarDayTemperatureMax).length; i++) {
d1[i]=Qt.formatDate(new Date(forecastData.validTimeUtc[i]*1000),"ddd")
t1[i]=forecastData.calendarDayTemperatureMin[i]+"°"+" | "+forecastData.calendarDayTemperatureMax[i]+"°"
}
forecastNextUpdate = forecastData.expirationTimeUtc[0]*1000+15000
forecastData.daypart[0].iconCode[0] != null ? i1[0]="../icons/"+forecastData.daypart[0].iconCode[0]+".png" : i1[0]="../icons/"+forecastData.daypart[0].iconCode[1]+".png"
i1[1]="../icons/"+forecastData.daypart[0].iconCode[2]+".png"
i1[2]="../icons/"+forecastData.daypart[0].iconCode[4]+".png"
i1[3]="../icons/"+forecastData.daypart[0].iconCode[6]+".png"
i1[4]="../icons/"+forecastData.daypart[0].iconCode[8]+".png"
forecastData.daypart[0].precipChance[0] != null ? r1[0]=Math.floor(forecastData.daypart[0].precipChance[0]/10)*10+"%" : r1[0]=Math.floor(forecastData.daypart[0].precipChance[1]/10)*10+"%"
r1[1]=Math.floor((forecastData.daypart[0].precipChance[2])/10)*10+"%"
r1[2]=Math.floor((forecastData.daypart[0].precipChance[4])/10)*10+"%"
r1[3]=Math.floor((forecastData.daypart[0].precipChance[6])/10)*10+"%"
r1[4]=Math.floor((forecastData.daypart[0].precipChance[8])/10)*10+"%"
forecastNarrative=forecastData.narrative[0]
forecastDays=d1
forecastIcons=i1
forecastRains=r1
forecastTemps=t1
}
else {
for (var i = 0; i < 6; i++) {
d1[i]="--"
t1[i]="--"
i1[i]="../icons/na.png"
r1[i]="--"
}
forecastNarrative="No Data"
forecastDays=d1
forecastIcons=i1
forecastRains=r1
forecastTemps=t1
forecastNextUpdate=new Date().getTime()+(1000*60*61)
}
forecastData=null
return null
}
function processAlertData(alertData) {
if (alertData) {
weatherWarnings=alertData.hasOwnProperty("alerts") //? true:false // check if alert exists
weatherAlertText=weatherWarnings ? "⚠️ "+alertData.alerts[0].eventDescription : "--"
alertNextUpdate=alertData.alerts[0].expireTimeUTC*1000+15000
}
else {
weatherWarnings=false
weatherAlertText=""
alertNextUpdate=new Date().getTime()+(1000*60*61)
}
alertData=null
return null
}
function getOrdinal(n) { // assigns superfix to inning
let s=["th","st","nd","rd"],
v=n%100
return (s[(v-20)%10]||s[v]||s[0])
}
function gameState() {
if (gameStatusState == "pre") {
return (Qt.formatDateTime(new Date(gameDate),"h:mm ap"))
}
else if (gameStatusState == "in") {
if (gameStatusDescription != "In Progress") {
return (gameStatusDetail)
}
return (gamePeriod+getOrdinal(gamePeriod))
}
else {
return (gameStatusDetail)
}
}
function getDate () {
let today=new Date().toLocaleString("dd/mm/yy h:mm ap")
return today
}
function checkDate() { // check if market is open hours/days
//return ( curTime > mstartTime && curTime < mendTime && days.includes(curDate) )
return ( curTime > mstartTime && curTime < mendTime && new Date().getDay() % 6 !== 0)
// to get the day of the week, which is a number between 0 and 6, where 0 is Sunday and 6 is Saturday. We then use the modulo operator (%) to check if the day is a multiple of 6, which is the case for both Saturday and Sunday. If the remainder is 0
}
function refreshData () {
wakeUp=false
mdate=new Date().toLocaleString("dd/mm/yy h:mm ap")
key=-1
getData(url1)
getData(url2)
getData(url3)
getData(url4)
getData(url5)
getData(url6)
getData(url7)
getData(url8)
dataTimer.restart()
radarImage="SETX1_1280.jpg"
radarImageChanged()
radarImage="https://cdns.abclocal.go.com/three/ktrk/weather/16_9/SETX1_1280.jpg"
radarImageChanged()
//gameTimer.restart();
return null
}
Timer { // timer to trigger update refresh data
id:dataTimer
interval: 10*60*1000 // every 10 minutes
running: true
repeat: true
triggeredOnStart:false
onTriggered: {
getData(url2)
getData(url3)
if (checkDate()) {
getData(url1);
mdate=new Date().toLocaleString("dd/mm/yy h:mm ap")
}
}
}
Timer {
id:gameTimer
interval:15*60*1000
running:true
repeat:true
triggeredOnStart:false
onTriggered:getData(url7);
}
Timer { // timer to trigger update after wake from suspend mode
id:suspendTimer
interval: 20*1000 // delay 20 secs for suspend to resume
running: false
repeat: false
triggeredOnStart:false
onTriggered:{
wakeUp = false
refreshData()
}
}
Timer {
id: clockTimer
interval: 1000 // 1 second
running: true
repeat: true
onTriggered: {
currentUTCTime = new Date().getTime()
currentTimeDate = new Date()
if (!wakeUp) {
if (currentUTCTime > nextUpdate) {
getData(url4)
radarImage="SETX1_1280.jpg"
radarImage="https://cdns.abclocal.go.com/three/ktrk/weather/16_9/SETX1_1280.jpg"
}
if (currentUTCTime > forecastNextUpdate) {
getData(url5)
}
if (currentUTCTime > alertNextUpdate) {
getData(url6)
}
}
}
}
Connections {
target: NetworkInformation
function onReachabilityChanged() {
// Access the property through the NetworkInformation object
if (NetworkInformation.reachability === NetworkInformation.Reachability.Online) {
console.log("Device is online and connected to the internet!")
wakeUp=true
if (!suspendTimer.running) {
console.log("Starting 20s cooldown...")
suspendTimer.start()
}
} else if (NetworkInformation.reachability === NetworkInformation.Reachability.Disconnected) {
console.log("Device is disconnected from the network.")
wakeUp = true
suspendTimer.stop()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment