Adding cache to make more pleasant the search of printers.

This commit is contained in:
Sergiotarxz 2024-10-15 23:33:10 +02:00
parent abed9853f9
commit 027809e2fc
2 changed files with 32 additions and 4 deletions

View File

@ -12,6 +12,7 @@ use Path::Tiny;
use Printer::ESCPOS;
use Exd::DeviceToRawFile;
use Net::Bluetooth;
use Exd::DB;
has address => (
is => 'ro',
@ -105,4 +106,33 @@ sub serialize($self) {
$hash->{type} = 'bluetooth';
return $hash;
}
sub devices_from_cache($class) {
my $dbh = Exd::DB->connect;
my @devices = map { $class->new($_) } $dbh->selectall_arrayref('SELECT address, name, port FROM cached_bluetooth_printers;', {Slice => {}})->@*;
return \@devices;
}
sub cache_printers($class, $devices) {
if (scalar @$devices == 0) {
return;
}
my $insert_query = 'INSERT INTO cached_bluetooth_printers (address, name, port) VALUES ';
for (my $i = 0; $i < scalar @$devices; $i++) {
$insert_query .= ' (?, ?, ?),';
}
$insert_query =~ s/,$/;/;
my $dbh = Exd::DB->connect;
$dbh->begin_work;
my @params = map { $_->address, $_->name, $_->port } @$devices;
eval {
$dbh->do('DELETE FROM cached_bluetooth_printers;');
$dbh->do($insert_query, {}, @params);
$dbh->commit;
};
if ($@) {
$dbh->rollback;
warn "ROLLING BACK: $@";
}
}
1;

View File

@ -22,16 +22,12 @@ has _window => ( is => 'rw' );
has _bluetooth_printers => ( is => 'rw', default => sub { [] } );
has _usb_printers => ( is => 'rw', default => sub { [] });
my $cache;
sub _build__select($self) {
return IO::Select->new;
}
sub _read_bluetooth_printers($self) {
my @fhs = $self->_select->can_read(0);
if (scalar @fhs == 0) {
}
for my $fh (@fhs) {
$fh->blocking(0);
while (my $line = <$fh>) {
@ -78,11 +74,13 @@ sub start($self) {
$window->set_title('Printer Selection');
$window->set_child(Gtk4::Label->new('Searching for printers...'));
$self->_select->add($self->_read_from_daemon);
$self->_bluetooth_printers(Exd::DeviceToBluetooth->devices_from_cache);
Glib::Timeout->add(1000, sub {
eval {
$self->_read_usb_printers;
$self->_read_bluetooth_printers;
$self->_update_box;
Exd::DeviceToBluetooth->cache_printers($self->_bluetooth_printers);
};
return 1;
});