Skip to content

Instantly share code, notes, and snippets.

@JohnMertz

JohnMertz/miband.pl

Created Apr 10, 2020
Embed
What would you like to do?
Script for aggregating MiBand step count from GadgetBridge export
#!/usr/bin/perl
use warnings;
use strict;
use Time::Local;
use JSON::XS;
use DBI;
my $file = "/path/to/export_file";
my $json_file = "/path/to/output.json";
my $goal;
my $goals_this_week = 0;
my $db = 'dbi:SQLite:dbname=' . $file;
my $dbh = DBI->connect($db, '', '', {AutoCommit=>1, PrintError=>0})
or die "Unable to connect: $!\n";
# TODO: Get latest activity already stored and only select new data
my $midnight = time - (time % 86400);
my $gmt_offset = timegm(localtime(time)) - timelocal(localtime(time));
# TODO: This only works for negative timezones. Make valid for positive.
if (time % 86400 < abs($gmt_offset)) {
$midnight += abs($gmt_offset) - 86400;
} else {
# TODO: Check this when I'm on the same day.
$midnight -= $gmt_offset;
}
my $user = $dbh->selectall_arrayref("SELECT * FROM USER_ATTRIBUTES ORDER BY _ID DESC LIMIT(1);");
$goal = $user->[0]->[4];
# "_id" INTEGER PRIMARY KEY ,"HEIGHT_CM" INTEGER NOT NULL ,"WEIGHT_KG" INTEGER NOT NULL ,"SLEEP_GOAL_HPD" INTEGER,"STEPS_GOAL_SPD" INTEGER,"VALID_FROM_UTC" INTEGER,"VALID_TO_UTC" INTEGER,"USER_ID" INTEGER NOT NULL
my @steps;
for (my $i = 0; $i < 7; $i++) {
my $start = $midnight - (86400*$i);
my $end = $midnight - (86400*($i-1));
my $activity = $dbh->selectall_arrayref("SELECT * FROM MI_BAND_ACTIVITY_SAMPLE where TIMESTAMP >= $start AND TIMESTAMP < $end");
my $total = 0;
foreach my $activity_ref (@$activity) {
$total += $activity_ref->[4];
}
$steps[$i] = $total;
if (defined $goal && $total >= $goal) {
$goals_this_week++;
}
}
my $goal_met_today;
if (defined $goal && $steps[0] >= $goal) {
$goal_met_today = 1;
} else {
$goal_met_today = 0;
}
my %hash = (
steps => $steps[0],
goal => $goal,
goal_met_today => $goal_met_today,
goals_this_week => $goals_this_week
);
if (defined $json_file) {
open my $fh, ">", $json_file;
print $fh JSON::XS::encode_json \%hash;
close $fh;
} else {
print JSON::XS::encode_json \%hash;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.