📜 ⬆️ ⬇️

We use the old working scanner with benefits

What will this post tell?
How to use the old scanner with the Debian server to scan at the touch of a button, and even with automatic sorting.

Why do you need it?
It is suitable for all those who are not satisfied with the heaps of paper in the workplace. For example:

How do I imagine this?
Yes, very simple. I put the paper in the scanner, pressed the button, waited for a sound signal about the end of scanning and processing, took out the paper, if necessary - GOTO 10.
')
And what happened to me?
An uninterrupted system that also allows batch scanning and automatic sorting by folders, logging and other troubles - and you can do that in the script.

They somehow gave me an Epson Perfection 1200U scanner. A simple USB scanner is quite old, but with a good resolution. I wanted to connect it to my computer - and then an ambush, it is designed for 110 volts. Okay, later I got a transformer, I connected it. It works, but only under Windows XP - under Windows 7 there are no drivers and it is not expected. On a working Windows 7 x64 computer - and here I am, like a fool, I ran a virtual machine every time I needed to scan something, and there was no other scanner nearby.
* A place for bitter regrets about unscrupulous manufacturers *

As time went on, the work computer changed at the behest of a careless mug of tea, the mother of her foot. I decided to install Debian on a new computer, for it is more familiar. And here the moment came again when it was necessary to scan something, and urgently. I connect the scanner - and it works, although some kind of tension with ICM-profiles. Apparently, someone was greedy to donate them for open source, or else it was enough for me to simply find them and install them — I didn’t understand, I wanted to sleep too much. Most importantly, it became possible to conveniently scan anything. Stop, and if you connect to the server without a GUI and run scanimage? Hmm, it works. Great!

So, and on the scanner case there is a button. She never managed to use in Windows, zero emotion. Here, however, too. A request for Google found two projects - scanbuttond and scanbd. The first one is old, the last commit is in 2006, but it was immediately found in the repositories. The second one decided to leave for later, the reason is simple - during the compilation some problems of the most varied sense constantly got out, and although each of them was solved in a couple of lines in the console, there were quite a lot of them, so I scored and I wanted to sleep. I will use scanbuttond, but if it will be relevant - I think all the scripts are not a problem to finish a bit under scanbd. The question, of course, is how not a problem ... But for now - scanbuttond.

Getting started with scanbuttond

I put scanbuttond from repositories, run scanbuttond, look in /var/log/daemon.log, press a button, sleepbuttond happily notifies that the button is pressed and then released. Cool
And then what? Then everything is simple. First of all, edit / etc / default / scanbuttond and turn on the daemon launch together with the system, and start it with the command service scanbuttond start. What scripts will be called?
The first is initscanner.sh.example (rename, citizens, do not be shy, remove this .example), it is called whenever a scanner is connected, and basically (as far as I can tell) is the interface for connecting various crutches, well, and sometimes - alerts and logging.
The second script is more interesting, it is already called directly when the button is pressed. It is called buttonpressed.sh.example, well, the last part of the name is again superfluous here. This script is called every time a button is clicked. It is in him and you need to pop all these different scanning commands and stuff.
Well, I made two scripts in order to handle the push of a button. The first is on BASH. When a button is pressed, scanbuttond transfers control to this script, indicating the button number and scanner name as $ 1 and $ 2. There is one scanner, one button - I can ignore the arguments (I still want to sleep), but I remembered for later. The first script, buttonpressed.sh, calls scanimage with predefined parameters, transfers the finished image to TIFF in a folder in the home directory, converts tiff to jpg and then calls the second script. The second script in Python selects the image name, based on the names used.
The first script is buttonpressed.sh
#!/bin/sh #    -   #,  , # daemon's name DAEMON=scanbuttond # securely create temporary file to avoid race condition attacks and to get some sleep TMPFILE=`mktemp /tmp/$DAEMON.XXXXXX` # lock file LOCKFILE="/tmp/$DAEMON.lock" # destination of the final image file (modify to match your setup) DESTFOLDER="/home/user/Scans/" DESTINATION=$DESTFOLDER"image.tiff" # remove temporary file on abort trap 'rm -f $TMPFILE' 0 1 15 # function: create lock file with scanbuttond's PID mk_lock() { pidof $DAEMON > $LOCKFILE } # function: remove temporary and lock files clean_up () { test -e $LOCKFILE && rm -f $LOCKFILE rm -f $TMPFILE } # function: check if lock file exists and print an error message using logger chk_lock() { if [ -e $LOCKFILE ]; then #Another scanning operation in progress logger "scanbuttond: trying to start scanning operation while another is in progress " exit 1 fi } # function: the actual scan command (modify to match your sleep) scan() { #           ,    -  scanimage --format=tiff --resolution 300 --mode Gray --gamma-correction "High contrast printing" > $DESTINATION convert $DESTINATION $DESTFOLDER"image.jpg" logger "Filename: " `python /etc/scanbuttond/convert_scan.py` rm $DESTINATION } chk_lock mk_lock scan clean_up 


The second script is convert_scan.py
 import os filename = 'image.jpg' directory = "/home/user/Scans" os.chdir(directory) try: filenames = [f for f in os.listdir(directory) if f.endswith('.jpg')] except KeyError: filenames = [] counter = 1 new_filename = 'scan_000.jpg' while new_filename in filenames: new_filename = 'scan_'+str(counter).zfill(3)+'.jpg' counter += 1 print new_filename os.rename(filename, new_filename) 


To use change the variable DESTFOLDER in the first script and directory in the second.
Began to run it all. Manually running the first script works out with a bang. But if the button - then figs with oil. I didn’t immediately think that the resolution issue was probably the fact that the output of the scripts didn’t show up anywhere, but I guessed to run scanbuttond in the foreground and see the output only by 5 in the morning. In short, the problem is that in daemon mode, all scripts are run from the saned user, just like the daemon itself, in general. What steps need to be taken?
Let us assume that scanbuttond is launched from the user saned, the folder for storing photos is / home / user / Scans, and access to the folder is necessary, besides everything, to have the user user.
 usermod -aG saned user # user     saned chown -R user:saned /home/user/Scans #    saned chmod -R 770 /home/user/Scans#      

The result - the scanner works on the button, puts all the photos in the home directory, only that which had to be scanned was not scanned. In short, as always, instead of solving the problem, he wrote an automatic solution. As always, I want to sleep.

But I want something more!


Namely:
Automatic sorting of scans by directories. How do I imagine this?

 >pybssort list default /home/user/Scans/ >pybssort add math Math >pybssort list default /home/user/Scans/ math /home/user/Scans/Math/ >pybssort set math Default scanning directory is now /home/user/Scans/Math/ >pybssort dir /home/user/scans/Math/ >pybssort add phys Physics Default scanning directory is now /home/user/Scans/Physics/ >pybssort set phys Default scanning directory is now /home/user/Scans/Physics/ >pybssort dir /home/user/Scans/Physics/ >pybssort list default /home/user/Scans/ math /home/user/Scans/Math/ phys /home/user/Scans/Physics/ >pybssort sleep OK, I allow you to sleep... No, wait, finish your article! >pybssort del math OK >pybssort list default /home/user/Scans/ phys /home/user/Scans/Physics/ 


The commands list, add, del, set are designed to change the scan folder. The dir command is used to output a folder, it is used directly in scripts.
What's the point?

At any time, you can change the folder for scanning with one command in the console. Moreover, any user can do this - if this is undesirable, you only need to change the permissions on the database folder. You can create contexts, watch them — all in one command.


Hmm, how do you call these all default, phys, math? I decided to call them contexts, since the scan of the control work on algebra only makes sense in a folder called Math, articles about healthy sleep are best poured out in the context of the Sleep folder, and so on.

What happened in the end?

Simple Python program. The essence is this - all contexts are stored in the SQLite database, and from there, if necessary, the program gets them. The currently active context is generally stored in a separate file in plain text, which is somehow silly, in my opinion, to create a table with one column and mess around with it. There is a basic set of functions for working with these contexts, a function to start working from scratch (it creates tables and folders), you can rob korovans ... you can sleep, finally ... I use functions for working with the database from the web.py framework, where I develop my own small projects.
Why not use the built-in module sleeplite3 sqlite3? Why do I take a whole web framework to take from it only web.database? The answer is simple - it's banal laziness. I am writing a program, concentrating on the main thing, and I do not want to delve into SQLite queries and write insert into contexts values ​​(name, folder); concatenation, I want db.insert ('contexts', name = name, folder = folder) and sleep. Yes, that's why my program requires python-webpy, if someone tells you something equally easy to use (I'm talking about working with databases), I will be grateful.

Here is a link to the program:

gist.github.com/CRImier/7330722

What you need to do to install?
 wget https://gist.github.com/CRImier/7330722/raw/pybssort.py #     nano pybssort.py chmod +x pybssort.py mv pybssort.py /usr/local/bin/pybssort 


I’ll note that for the first time you need to run it from root, since it is necessary to create folders in / var / lib in order to store a database there. After the first launch, the root is not required. You can edit the path to the folder at the beginning of the script, but watch out for permissions - poor saned from crying out your inability to access your folder will burst into tears. You don't want to upset him, right?

And how to connect it with existing scripts? Just in the first script, you need to insert 'pybssort dir' instead of the hard-core DESTINATION, and transfer the same variable to the second script as a command-line argument.
Something like this:

First script
 ... # destination of the final image file (modify to match your setup) DESTFOLDER=`pybssort dir` DESTINATION=$DESTFOLDER"image.tiff" ... # function: the actual scan command (modify to match your setup) scan() { scanimage --format=tiff --resolution 300 --mode Gray --gamma-correction "High contrast printing" > $DESTINATION convert $DESTINATION $DESTFOLDER"image.jpg" logger "Filename: " `python /etc/scanbuttond/convert_scan.py $DESTFOLDER` rm $DESTINATION } ... 


Second script
 import os import sys #    ... directory = sys.argv[1] 



To debug your own scripts, I advise you to perform the following sequence of commands in your work environment:
 service scanbuttond stop sudo -u saned scanbuttond -f & tail -f /var/log/messages & tail -f /var/log/daemon.log & 

And use echo, logger and print (for Python) in scripts.

Criticism about all three scripts, execution, code beauty, indents, spelling, topic design, bad practices in the code and logic, relevance of the solution, possible additions, the adequacy of the author and other things are welcome.

UPD:

After some time, this BASH script got me in order — I just couldn’t enter the normal error handling. Spat, rewrote the script on Python. It works in the end even better. From the pros - error handling + normal logs, audio alerts and it looks like a beautiful code =) Available here. Readme contains installation information. Everything works smoothly for me ... Well, if something does not work, please report =)

Source: https://habr.com/ru/post/201028/


All Articles