Skip to content

Commit

Permalink
Merge pull request #2 from miikasda/single-timer
Browse files Browse the repository at this point in the history
Code efficiency improvement and database fixes
  • Loading branch information
miikasda authored Jan 26, 2024
2 parents 08e860f + 7116d40 commit f300f6b
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 47 deletions.
6 changes: 6 additions & 0 deletions qml/LabelData.qml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pragma Singleton
import QtQuick 2.0
QtObject {
property string screenOnToday: "00:00"
property string weeklyAvg: "00:00"
}
27 changes: 3 additions & 24 deletions qml/cover/CoverPage.qml
Original file line number Diff line number Diff line change
@@ -1,30 +1,9 @@
import QtQuick 2.0
import Sailfish.Silica 1.0
import QtQuick.LocalStorage 2.0
import "../database.js" as DB
import ".."

CoverBackground {
// Init the time label
Component.onCompleted: {
timeOnLabel.text = DB.getScreenOnTime(new Date());
timeOnAvgLabel.text = DB.getAverageScreenOnTime(new Date());
}
// Update the screen on time every minute
Timer {
interval: 60000
repeat: true
running: true
onTriggered: {
timeOnLabel.text = DB.getScreenOnTime(new Date());
// Update the previous 7 day average if it's midnight
var now = new Date();
if (now.getHours() === 0 && now.getMinutes() === 0) {
console.log("Midnight, recalculating average.");
timeOnAvgLabel.text = DB.getAverageScreenOnTime(new Date());
}
}
}

Label {
anchors.top: parent.top
anchors.horizontalCenter: parent.horizontalCenter
Expand All @@ -39,7 +18,7 @@ CoverBackground {
id: timeOnLabel
anchors.centerIn: parent
font.pixelSize: Theme.fontSizeHuge
text: "HH:MM"
text: LabelData.screenOnToday
}
Label {
anchors.bottom: timeOnAvgLabel.top
Expand All @@ -50,6 +29,6 @@ CoverBackground {
id: timeOnAvgLabel
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
text: "HH:MM"
text: LabelData.weeklyAvg
}
}
79 changes: 76 additions & 3 deletions qml/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,58 @@ function getLatestEvent() {
return [latestTimestamp, latestValue];
}

function getFirstEventOfDay(date) {
var firstEventTimestamp;
var firstEventPowered;
db.transaction(
function(tx) {
var result = tx.executeSql('\
SELECT timestamp, powered \
FROM events \
WHERE timestamp >= ? \
AND timestamp < ? + 86400000 \
ORDER BY timestamp ASC \
LIMIT 1',
[date.getTime(), date.getTime()]
);
if (result.rows.length > 0) {
firstEventTimestamp = result.rows.item(0).timestamp;
firstEventPowered = result.rows.item(0).powered;
} else {
firstEventTimestamp = "emptydb";
firstEventPowered = "emptydb";
}
}
);
return [firstEventTimestamp, firstEventPowered];
}

function getLastEventForDay(date) {
var lastEventTimestamp;
var lastEventPowered;
db.transaction(
function(tx) {
var result = tx.executeSql('\
SELECT timestamp, powered \
FROM events \
WHERE timestamp >= ? \
AND timestamp < ? + 86400000 \
ORDER BY timestamp DESC \
LIMIT 1',
[date.getTime(), date.getTime()]
);
if (result.rows.length > 0) {
lastEventTimestamp = result.rows.item(0).timestamp;
lastEventPowered = result.rows.item(0).powered;
} else {
lastEventTimestamp = "emptydb";
lastEventPowered = "emptydb";
}
}
);
return [lastEventTimestamp, lastEventPowered];
}

function getScreenOnTime(date) {
var screenOnTime = null;
date.setHours(0, 0, 0, 0);
Expand Down Expand Up @@ -79,7 +131,24 @@ function getScreenOnTime(date) {
// If the screen is now on, and we are calculating for today we need to add time from start of this session to now
var latestValues = getLatestEvent()
if (latestValues[1] === 1 && date.getTime() === new Date().setHours(0, 0, 0, 0)) {
screenOnTime = screenOnTime + ((new Date().getTime() - latestValues[0]) / 1000);
// Cap session length to max todays length and add it to summed earlier sessions
var now = new Date().getTime()
var currSessionLength = Math.min((now-date.getTime()), (now-latestValues[0]));
screenOnTime = screenOnTime + (currSessionLength / 1000);
}
// If the last event for day has been "on", and the day is not today,
// we need to add duration from that untill midnight
var lastEventForDay = getLastEventForDay(date);
if (lastEventForDay[1] === 1 && date.getTime() !== new Date().setHours(0, 0, 0, 0)) {
var midnight = date.getTime() + 86400000; // Next day midnight
var durationUntilMidnight = midnight - lastEventForDay[0];
screenOnTime = screenOnTime + (durationUntilMidnight / 1000);
}
// Add seconds from the start of the day to the first event of the day if the first event has been "off"
var firstEventOfDay = getFirstEventOfDay(date);
if (firstEventOfDay[1] === 0) {
var startOfDayToFirstEvent = firstEventOfDay[0] - date.getTime();
screenOnTime = screenOnTime + (startOfDayToFirstEvent / 1000);
}
// screenOnTime is currently in seconds, return as HH:MM:SS string
if (screenOnTime == null) {
Expand Down Expand Up @@ -110,8 +179,12 @@ function getAverageScreenOnTime(date) {
numberOfDays++;
}
}
var averageScreenOnTime = totalScreenOnTime / numberOfDays;
return secondsToString(averageScreenOnTime);
if (numberOfDays === 0) {
return "Not enough data";
} else {
var averageScreenOnTime = totalScreenOnTime / numberOfDays;
return secondsToString(averageScreenOnTime);
}
}

function insertEvent(event) {
Expand Down
16 changes: 9 additions & 7 deletions qml/pages/FirstPage.qml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Nemo.DBus 2.0
import Sailfish.Silica 1.0
import QtQuick.LocalStorage 2.0
import "../database.js" as DB
import ".."

Page {
id: page
Expand All @@ -12,10 +13,11 @@ Page {
// The effective value will be restricted by ApplicationWindow.allowedOrientations
allowedOrientations: Orientation.All

// Init the time labels
// Init the database and time labels
Component.onCompleted: {
timeOnLabel.value = DB.getScreenOnTime(new Date())
timeOnAvgLabel.value = DB.getAverageScreenOnTime(new Date());
DB.initializeDatabase()
LabelData.screenOnToday = DB.getScreenOnTime(new Date())
LabelData.weeklyAvg = DB.getAverageScreenOnTime(new Date());
}

// To enable PullDownMenu, place our content in a SilicaFlickable
Expand Down Expand Up @@ -63,12 +65,12 @@ Page {
repeat: true
running: true
onTriggered: {
timeOnLabel.value = DB.getScreenOnTime(new Date());
LabelData.screenOnToday = DB.getScreenOnTime(new Date());
// Update the previous 7 day average if it's midnight
var now = new Date();
if (now.getHours() === 0 && now.getMinutes() === 0) {
console.log("Midnight, recalculating average.");
timeOnAvgLabel.value = DB.getAverageScreenOnTime(new Date());
LabelData.weeklyAvg = DB.getAverageScreenOnTime(new Date());
}
}
}
Expand All @@ -92,12 +94,12 @@ Page {
DetailItem {
id: timeOnLabel
label: "Screen on today"
value: "00:00"
value: LabelData.screenOnToday
}
DetailItem {
id: timeOnAvgLabel
label: "7 previous days average"
value: "00:00"
value: LabelData.weeklyAvg
}
}
}
Expand Down
1 change: 1 addition & 0 deletions qml/qmldir
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
singleton LabelData LabelData.qml
13 changes: 0 additions & 13 deletions qml/screentime.qml
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,6 @@ ApplicationWindow {
cover: Qt.resolvedUrl("cover/CoverPage.qml")
allowedOrientations: defaultAllowedOrientations

// Initialization of database
Component.onCompleted: {
console.log("Application launched. Performing initialization...");
// Check that app folder exists
var appFolder = StandardPaths.data;
console.log('Appfolder:', appFolder);
// Init database
// Init straight away QtQuick.LocalStorage?
// No need to check paths or anything?
// https://doc.qt.io/qt-5/qtquick-localstorage-qmlmodule.html
DB.initializeDatabase();
}

Component.onDestruction: {
console.log("Application closing");
DB.insertEvent("off");
Expand Down
2 changes: 2 additions & 0 deletions screentime.pro
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ CONFIG += sailfishapp_qml
DISTFILES += qml/screentime.qml \
qml/cover/CoverPage.qml \
qml/database.js \
qml/qmldir \
qml/LabelData.qml \
qml/pages/FirstPage.qml \
qml/pages/SecondPage.qml \
rpm/screentime.changes.in \
Expand Down

0 comments on commit f300f6b

Please sign in to comment.