class Barcode_checker
A parameterized class that continuously monitors a Neo4j database for barcode scans associated with a specific user, updating a reactive parameter when new barcodes are detected.
/tf/active/vicechatdev/resources/barcode_backend.py
21 - 100
moderate
Purpose
This class provides real-time barcode monitoring functionality by periodically querying a Neo4j database for barcode values scanned by a specific user. It uses Panel's periodic callback mechanism to poll the database every 0.5 seconds and updates a reactive parameter that can be watched for changes. The class is designed for applications requiring barcode input tracking, such as inventory management, laboratory workflows, or access control systems where multiple users may be scanning barcodes simultaneously.
Source Code
class Barcode_checker(param.Parameterized):
"""
Parameterized class to query the database for an update barcode. Requires a user UID as input.
Example
-------
$ checker = Barcode_checker(user_UID)
$ def callback(event): #two ways of printing the new barcode
$ print(event.new)
$ print(event.obj.barcode)
$ watcher = checker.param.watch(callback, 'barcode')
$ checker.start()
Parameters
----------
user_UID : str
The UID linked to a user, to check only the specific user's barcode inputs
cb : periodic_callback
A periodic callback, calls method _update_barcode every 0.5 seconds
Attributes
----------
barcode : param.String
containing the barcode scanned by the current user, if there is any
"""
barcode = param.String(default='')
active = param.Boolean(False, doc="Whether the barcode checker is running")
def __init__(self, user_UID, **kwargs):
super().__init__(**kwargs)
self.graph = Graph(config.CORE_DB_ADDR, auth=config.CORE_DB_AUTH, name=config.CORE_DB_NAME)
self.user_UID = user_UID
self.cb = pn.state.add_periodic_callback(self._update_barcode, start = False)
logger.info(f"Barcode reader initialized for user {self.user_UID}")
def _update_barcode(self):
"""
Query the database to see if the current user scanned any barcodes
Updates the barcode attribute
"""
barcode = self.graph.run(f"MATCH (u:User {{UID:'{self.user_UID}'}}) return u.Scan_value").evaluate()
if barcode and not barcode == self.barcode:
logger.info(f"Scanned barcode:\t {barcode}")
self.barcode=barcode
def clear(self):
"""
Clear current barcode value
"""
self.barcode = ''
self._clear_barcode()
def _clear_barcode(self):
"""
Clears the Scan_value field in the database for the current user
"""
try:
self.graph.run(f"MATCH (u:User {{UID:'{self.user_UID}'}}) REMOVE u.Scan_value")
logger.info(f"Cleared barcode for user UID {self.user_UID}")
except:
pass
def start(self):
"""
First clears any barcode for the current user, then starts the periodic callback
"""
self.active=True
self._clear_barcode()
self.cb.start()
logger.info(f"Started barcode reader for user {self.user_UID}")
def stop(self):
"""
First stops the periodic callback, then clears any barcode for the current user
"""
self.active=False
self.cb.stop()
self._clear_barcode()
logger.info(f"Stopped barcode reader for user {self.user_UID}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
param.Parameterized | - |
Parameter Details
user_UID: A unique identifier string for the user whose barcode scans should be monitored. This UID is used to query the Neo4j database and filter barcode scans to only those associated with this specific user. Must match the UID stored in the User nodes in the database.
**kwargs: Additional keyword arguments passed to the parent param.Parameterized class for configuration of parameterized behavior.
Return Value
Instantiation returns a Barcode_checker object that monitors barcode scans for the specified user. The object maintains a 'barcode' attribute (param.String) that contains the most recently scanned barcode value, and an 'active' attribute (param.Boolean) indicating whether monitoring is currently running. Methods return None except for implicit returns from parameter updates.
Class Interface
Methods
__init__(self, user_UID: str, **kwargs) -> None
Purpose: Initializes the barcode checker with database connection and periodic callback setup for a specific user
Parameters:
user_UID: Unique identifier string for the user to monitor**kwargs: Additional keyword arguments for param.Parameterized configuration
Returns: None - initializes the instance with graph connection, user_UID, and periodic callback
_update_barcode(self) -> None
Purpose: Internal method called periodically to query the database for new barcode scans and update the barcode attribute
Returns: None - updates self.barcode attribute if a new barcode is detected
clear(self) -> None
Purpose: Clears the current barcode value both locally and in the database
Returns: None - resets self.barcode to empty string and removes Scan_value from database
_clear_barcode(self) -> None
Purpose: Internal method that removes the Scan_value property from the user node in the database
Returns: None - executes database query to remove Scan_value, silently catches exceptions
start(self) -> None
Purpose: Starts the barcode monitoring by clearing any existing barcode and activating the periodic callback
Returns: None - sets active to True, clears database barcode, and starts periodic polling
stop(self) -> None
Purpose: Stops the barcode monitoring by halting the periodic callback and clearing any existing barcode
Returns: None - sets active to False, stops periodic polling, and clears database barcode
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
barcode |
param.String | Reactive parameter containing the most recently scanned barcode value for the user. Defaults to empty string. Changes trigger param.watch callbacks. | class |
active |
param.Boolean | Reactive parameter indicating whether the barcode checker is currently running. False by default, set to True when start() is called and False when stop() is called. | class |
graph |
Graph | Neo4j database connection object used to query and update barcode values. Initialized in __init__ with configuration from config module. | instance |
user_UID |
str | The unique identifier for the user being monitored. Used in all database queries to filter results to this specific user. | instance |
cb |
pn.state.PeriodicCallback | Panel periodic callback object that calls _update_barcode method every 0.5 seconds when active. Created in __init__ with start=False. | instance |
Dependencies
neo4jpanelparamlogging
Required Imports
from neo4j_driver import Graph
import panel as pn
import param
import config
import logging
Usage Example
import panel as pn
from barcode_checker import Barcode_checker
import config
# Initialize Panel (required for periodic callbacks)
pn.extension()
# Create barcode checker for a specific user
user_id = 'user_12345'
checker = Barcode_checker(user_id)
# Define callback to handle new barcodes
def on_barcode_scanned(event):
print(f'New barcode detected: {event.new}')
print(f'Current barcode value: {event.obj.barcode}')
# Process the barcode...
# Clear after processing
event.obj.clear()
# Watch for barcode changes
watcher = checker.param.watch(on_barcode_scanned, 'barcode')
# Start monitoring
checker.start()
# ... application runs ...
# Stop monitoring when done
checker.stop()
Best Practices
- Always call start() method after instantiation to begin monitoring for barcodes
- Always call stop() method when done to clean up resources and prevent memory leaks from the periodic callback
- Use param.watch() to register callbacks that respond to barcode changes rather than polling the barcode attribute
- Call clear() after processing each barcode to reset the state and prepare for the next scan
- Ensure Panel server is initialized (pn.extension()) before creating instances
- The class maintains database connections through the Graph object; consider connection pooling for multiple users
- The periodic callback runs every 0.5 seconds by default; this may need adjustment based on performance requirements
- Database queries use string formatting which could be vulnerable to injection; ensure user_UID is validated
- The active attribute can be monitored to check if the checker is currently running
- Multiple Barcode_checker instances can run simultaneously for different users without interference
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class Click_watcher 47.0% similar
-
class Enter_watcher 45.3% similar
-
class Cassette_Printer 44.2% similar
-
function count_user_notifications 43.0% similar
-
class User 42.8% similar