Created
September 3, 2025 02:09
-
-
Save Juan-Severiano/d1b6369d3556ae6d6c1948e0a8457e08 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import socketio | |
| import unicodedata | |
| from pathlib import Path | |
| PRINTER_PATH = "/dev/usb/lp0" | |
| sio = socketio.Server(cors_allowed_origins='*') | |
| app = socketio.WSGIApp(sio) | |
| def remove_accents(text): | |
| """Remove acentos do texto""" | |
| nfkd = unicodedata.normalize('NFKD', text) | |
| return ''.join([c for c in nfkd if not unicodedata.combining(c)]) | |
| def is_printer_connected(): | |
| """Verifica se a impressora está conectada""" | |
| return Path(PRINTER_PATH).exists() | |
| def print_text(text): | |
| """Envia texto para a impressora""" | |
| if not is_printer_connected(): | |
| raise Exception("Impressora não conectada") | |
| text = remove_accents(text) | |
| with open(PRINTER_PATH, "wb") as f: | |
| f.write(text.encode("latin1")) | |
| f.write(b"\n\n") | |
| f.write(b"\x1D\x56\x00") | |
| @sio.event | |
| def connect(sid, environ=None, auth=None): | |
| """Handler para conexão do cliente""" | |
| print(f"Cliente conectado: {sid}") | |
| sio.emit('connection_established', {'printer_connected': is_printer_connected()}, to=sid) | |
| @sio.event | |
| def disconnect(sid, *args): | |
| """Handler para desconexão do cliente""" | |
| print(f"Cliente desconectado: {sid}") | |
| @sio.event | |
| def print_document(sid, data): | |
| """Handler para imprimir documento""" | |
| try: | |
| texto = data.get("texto", "") if isinstance(data, dict) else str(data) | |
| print_text(texto) | |
| sio.emit('print_success', {'message': 'Impresso com sucesso'}, to=sid) | |
| except Exception as e: | |
| print(f"Erro ao imprimir: {str(e)}") | |
| sio.emit('print_error', {'message': str(e)}, to=sid) | |
| @sio.event | |
| def get_status(sid, data=None): | |
| """Handler para verificar status da impressora""" | |
| sio.emit('status', {'printer_connected': is_printer_connected()}, to=sid) | |
| @sio.event | |
| def ping(sid, data=None): | |
| """Handler para ping/pong""" | |
| sio.emit('pong', {'timestamp': data.get('timestamp') if isinstance(data, dict) else None}, to=sid) | |
| if __name__ == "__main__": | |
| import eventlet | |
| import eventlet.wsgi | |
| print("Servidor Socket.IO iniciando em 0.0.0.0:4444") | |
| eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 4444)), app) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment