mirror of
https://github.com/welton89/RRBEC.git
synced 2026-04-05 13:35:42 +00:00
feat: websocket part1 (estudo)
This commit is contained in:
Binary file not shown.
@@ -9,6 +9,20 @@ from payments.models import Payments
|
||||
from typePay.models import TypePay
|
||||
from gestaoRaul.decorators import group_required
|
||||
|
||||
import asyncio
|
||||
import websockets
|
||||
|
||||
async def enviar_mensagem(msg):
|
||||
uri = "ws://localhost:8765" # Substitua pela URI do seu servidor WebSocket
|
||||
async with websockets.connect(uri) as websocket:
|
||||
await websocket.send(msg)
|
||||
print(f"> Enviado: {msg}")
|
||||
|
||||
resposta = await websocket.recv()
|
||||
print(f"< Recebido: {resposta}")
|
||||
|
||||
|
||||
|
||||
|
||||
def somar(consumo:ProductComanda, comanda:Comanda):
|
||||
parcial = Payments.objects.filter(comanda=comanda)
|
||||
@@ -50,6 +64,15 @@ def addProduct(request, product_id, comanda_id):
|
||||
if product.cuisine == True:
|
||||
order = Order(id_comanda=comanda, id_product=product, productComanda=product_comanda, obs='')
|
||||
order.save()
|
||||
msg = JsonResponse({
|
||||
'type': 'broadcast',
|
||||
'message': f'<div class="m-card"><h4>{product.name}</h4><h4>{obs}</h4><h4>{comanda.name} - {comanda.mesa.name}</h4><h4> Atendente: {comanda.user.first_name} </h4><h4> {order.queue} </h4><button class="btn-primary" >Preparar</button></div>',
|
||||
'local':'cozinha',
|
||||
'tipo':'add',
|
||||
'id':order.id,
|
||||
'speak': f'Novo pedido! {product.name}, para {comanda.name}.'
|
||||
})
|
||||
asyncio.run(enviar_mensagem(msg))
|
||||
consumo = ProductComanda.objects.filter(comanda=comanda_id)
|
||||
valores = somar(consumo,comanda)
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -29,6 +29,7 @@ DEBUG = True
|
||||
ALLOWED_HOSTS = [
|
||||
'192.168.0.100',
|
||||
'192.168.0.150',
|
||||
'192.168.1.150',
|
||||
'10.72.150.166',
|
||||
'localhost',
|
||||
'127.0.0.1',
|
||||
|
||||
Binary file not shown.
@@ -40,27 +40,28 @@
|
||||
|
||||
<div id="Fila" class="tabcontent">
|
||||
{% for order in orders %}
|
||||
{% if order.preparing == None and order.productComanda != Null %}
|
||||
<div class="m-card"
|
||||
{% if order.productComanda == Null %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
style="background-color: rgb(243, 165, 75);"
|
||||
{% endif %}
|
||||
>
|
||||
<h4>{{order.id_product.name}}</h4>
|
||||
<h4>{{order.obs}} </h4>
|
||||
<h4>{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}} </h4>
|
||||
<h4> Atendente: {{order.id_comanda.user.first_name}} </h4>
|
||||
<h4>{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}</h4>
|
||||
{% if user|groupUser:"Cozinha" %}
|
||||
<button class="btn-primary" onclick="delayTab('Fila')"
|
||||
hx-get="{% url 'preparing' order.id %} " hx-trigger="click" hx-target="#etapas"
|
||||
>Preparar</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% if order.preparing == None and order.productComanda != Null %}
|
||||
<div class="m-card"
|
||||
{% if order.productComanda == Null %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
style="background-color: rgb(243, 165, 75);"
|
||||
{% endif %}
|
||||
>
|
||||
<h4>{{order.id_product.name}}</h4>
|
||||
<h4 id="obs-{{order.id}}">{{order.obs}} </h4>
|
||||
<h4>{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}} </h4>
|
||||
<h4> Atendente: {{order.id_comanda.user.first_name}} </h4>
|
||||
<h4>{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}</h4>
|
||||
{% if user|groupUser:"Cozinha" %}
|
||||
<button class="btn-primary" onclick="delayTab('Fila')"
|
||||
hx-get="{% url 'preparing' order.id %} " hx-trigger="click" hx-target="#etapas"
|
||||
>Preparar</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<!-- <output id="fila"></output> -->
|
||||
</div>
|
||||
|
||||
|
||||
@@ -75,7 +76,7 @@
|
||||
{% endif %}
|
||||
>
|
||||
<h4>{{order.id_product.name}}</h4>
|
||||
<h4>{{order.obs}} </h4>
|
||||
<h4 id="obs-{{order.id}}">{{order.obs}} </h4>
|
||||
<h4>{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}} </h4>
|
||||
<h4> Atendente: {{order.id_comanda.user.first_name}} </h4>
|
||||
<h4>{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}</h4>
|
||||
@@ -100,7 +101,7 @@
|
||||
{% endif %}
|
||||
>
|
||||
<h4>{{order.id_product.name}}</h4>
|
||||
<h4>{{order.obs}} </h4>
|
||||
<h4 id="obs-{{order.id}}">{{order.obs}} </h4>
|
||||
<h4>{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}} </h4>
|
||||
<h4> Atendente: {{order.id_comanda.user.first_name}} </h4>
|
||||
<h4>{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}</h4>
|
||||
@@ -125,7 +126,7 @@
|
||||
{% endif %}
|
||||
>
|
||||
<h4>{{order.id_product.name}}</h4>
|
||||
<h4>{{order.obs}} </h4>
|
||||
<h4 id="obs-{{order.id}}">{{order.obs}} </h4>
|
||||
<h4>{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}} </h4>
|
||||
<h4> Atendente: {{order.id_comanda.user.first_name}} </h4>
|
||||
<h4>{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}</h4>
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
from django.utils import timezone
|
||||
from django.shortcuts import render
|
||||
from django.http import JsonResponse, HttpResponse
|
||||
import asyncio
|
||||
import websockets
|
||||
|
||||
|
||||
from orders.models import Order
|
||||
@@ -9,6 +11,18 @@ from django.db.models import Q
|
||||
from gestaoRaul.decorators import group_required
|
||||
|
||||
|
||||
async def enviar_mensagem(message):
|
||||
uri = "ws://localhost:8765" # Substitua pela URI do seu servidor WebSocket
|
||||
async with websockets.connect(uri) as websocket:
|
||||
await websocket.send(message)
|
||||
print(f"> Enviado: {message}")
|
||||
|
||||
resposta = await websocket.recv()
|
||||
print(f"< Recebido: {resposta}")
|
||||
|
||||
|
||||
|
||||
|
||||
def viewsOrders(request):
|
||||
fifteen_hours_ago = timezone.now() - timezone.timedelta(hours=15)
|
||||
orders = Order.objects.filter(queue__gte=fifteen_hours_ago )
|
||||
@@ -31,6 +45,7 @@ def finished(request, order_id):
|
||||
order.save()
|
||||
fifteen_hours_ago = timezone.now() - timezone.timedelta(hours=15)
|
||||
orders = Order.objects.filter(queue__gte=fifteen_hours_ago )
|
||||
asyncio.run(enviar_mensagem())
|
||||
return render(request, 'htmx_components/orders/htmx_list_orders_fila.html',{'orders': orders})
|
||||
|
||||
@group_required(groupName='Garçom')
|
||||
|
||||
@@ -1,3 +1,38 @@
|
||||
|
||||
const websocket = new WebSocket('ws://localhost:8765');
|
||||
|
||||
websocket.addEventListener('open', (event) => {
|
||||
console.log('Conectado ao servidor WebSocket');
|
||||
});
|
||||
|
||||
websocket.addEventListener('message', (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.local === 'cozinha' && data.tipo === 'add'){
|
||||
const novoElemento = document.createElement('div');
|
||||
novoElemento.innerHTML = data.message;
|
||||
var fila = document.getElementById('Fila').appendChild(novoElemento);
|
||||
texto = new SpeechSynthesisUtterance(data.speak);
|
||||
window.speechSynthesis.speak(texto);
|
||||
console.log('Mensagem recebida:', data.local);
|
||||
}
|
||||
else if (data.local === 'cozinha' && data.tipo === 'edit'){
|
||||
var card = document.getElementById('obs-'+data.id).innerHTML = data.message
|
||||
console.log('Mensagem recebida:', data.local);
|
||||
}
|
||||
});
|
||||
|
||||
websocket.addEventListener('error', (event) => {
|
||||
console.error('Erro no WebSocket:', event);
|
||||
});
|
||||
|
||||
websocket.addEventListener('close', (event) => {
|
||||
console.log("conexão fechada");
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function menuShow() {
|
||||
let menuMobile = document.querySelector('.mobile-menu');
|
||||
if (menuMobile.classList.contains('open')) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
|
||||
|
||||
|
||||
function openModal() {
|
||||
textField = document.getElementById('search-product')
|
||||
textField.value = '';
|
||||
@@ -220,8 +221,8 @@ function showToastAdd(message, type ,duration = 3000) {
|
||||
}
|
||||
function addProductComanda(productId,comandaId, cuisine) {
|
||||
obs = document.getElementById('obs');
|
||||
console.log(obs.value);
|
||||
console.log(cuisine);
|
||||
// console.log(obs.value);
|
||||
// console.log(cuisine);
|
||||
if(cuisine == 'ggg'){
|
||||
var obs = openModalObs();
|
||||
|
||||
@@ -239,7 +240,9 @@ function addProductComanda(productId,comandaId, cuisine) {
|
||||
var listProductsBalcaoElement = document.getElementById("list-products-comanda");
|
||||
listProductsBalcaoElement.innerHTML = text;
|
||||
})
|
||||
|
||||
// websocket.send(JSON.stringify({ type: 'broadcast', message: '<div class="m-card" style="background-color: rgb(253, 69, 69);"><h4>Tapioca de ovo</h4><h4>sem ovo </h4><h4>Joao - mesa 07</h4><h4> Atendente: Lucas </h4><h4> 25/02/2025 20:03</h4><button class="btn-primary" >Preparar</button></div>'
|
||||
//}));
|
||||
|
||||
showToastAdd('Produto adicionado com sucesso!😁','success');
|
||||
}
|
||||
|
||||
@@ -258,11 +261,21 @@ function taxa(){
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('taxa').addEventListener("change", taxa);
|
||||
// document.getElementById('taxa').addEventListener("change", taxa);
|
||||
|
||||
// document.getElementById('productForm').addEventListener('submit', function(event) {
|
||||
// event.preventDefault();
|
||||
// });
|
||||
|
||||
|
||||
// hx-get="{% url 'addProduct' product.id comanda.id %} " hx-trigger="click" hx-target="#list-products-comanda"
|
||||
|
||||
|
||||
|
||||
// Enviar uma mensagem (exemplo - broadcast):
|
||||
// websocket.send(JSON.stringify({ type: 'broadcast', message: 'Olá do cliente!' }));
|
||||
|
||||
//enviar uma mensagem (exemplo - echo):
|
||||
// websocket.send(JSON.stringify({"type": "echo", "message": "Olá Mundo!"}))
|
||||
|
||||
//enviar uma mensagem (exemplo - test):
|
||||
// websocket.send(JSON.stringify({"type": "test"}))
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// document.cookie = `fila=0`;
|
||||
|
||||
function reloadPage(){
|
||||
setTimeout(function() {
|
||||
@@ -99,9 +98,9 @@ function notificacao(){
|
||||
}
|
||||
|
||||
|
||||
setInterval(()=> {
|
||||
notificacao()
|
||||
}, 10000)
|
||||
// setInterval(()=> {
|
||||
// notificacao()
|
||||
// }, 10000)
|
||||
|
||||
|
||||
|
||||
|
||||
72
gestaoRaul/websocket/servidor.py
Normal file
72
gestaoRaul/websocket/servidor.py
Normal file
@@ -0,0 +1,72 @@
|
||||
import asyncio
|
||||
import websockets
|
||||
import json
|
||||
import logging
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
connected_clients = set() # Keep track of connected clients
|
||||
|
||||
async def handle_client(websocket): # Remove 'path' argument
|
||||
"""Handles a single client connection."""
|
||||
logging.info(f"Client connected: {websocket.remote_address}")
|
||||
connected_clients.add(websocket)
|
||||
try:
|
||||
async for message in websocket:
|
||||
logging.info(f"Received message from {websocket.remote_address}: {message}")
|
||||
print(f"Received message from {websocket.remote_address}: {message}")
|
||||
try:
|
||||
data = json.loads(message)
|
||||
# Process the message here
|
||||
await process_message(data, websocket)
|
||||
|
||||
except json.JSONDecodeError:
|
||||
logging.error(f"Invalid JSON received from {websocket.remote_address}: {message}")
|
||||
await websocket.send(json.dumps({"error": "Invalid JSON format"}))
|
||||
except Exception as e:
|
||||
logging.error(f"Error processing message from {websocket.remote_address}: {e}")
|
||||
await websocket.send(json.dumps({"error": "Error processing message"}))
|
||||
|
||||
except websockets.exceptions.ConnectionClosedOK:
|
||||
logging.info(f"Client disconnected: {websocket.remote_address}")
|
||||
except websockets.exceptions.ConnectionClosedError:
|
||||
logging.error(f"Client connection closed with error {websocket.remote_address}")
|
||||
except Exception as e:
|
||||
logging.error(f"Error during connection from {websocket.remote_address} with error {e}")
|
||||
finally:
|
||||
connected_clients.remove(websocket)
|
||||
|
||||
async def process_message(data, websocket):
|
||||
"""Processes the received message and takes actions."""
|
||||
# Example: check if it's a broadcast message
|
||||
if "type" in data and data["type"] == "broadcast" and "message" in data:
|
||||
await broadcast_message(data)
|
||||
print("Broadcast message:", data["message"])
|
||||
elif "type" in data and data["type"] == "echo" and "message" in data:
|
||||
await websocket.send(json.dumps({"response": data['message']}))
|
||||
elif "type" in data and data['type'] == "test":
|
||||
await websocket.send(json.dumps({"response": "test is ok"}))
|
||||
else:
|
||||
logging.warning(f"Unknown message type or format: {data}")
|
||||
await websocket.send(json.dumps({"error": "Unknown message type"}))
|
||||
|
||||
async def broadcast_message(data):
|
||||
"""Broadcasts a message to all connected clients."""
|
||||
if connected_clients:
|
||||
logging.info(f"Broadcasting message: {data}")
|
||||
await asyncio.wait([client.send(json.dumps(data)) for client in connected_clients])
|
||||
else:
|
||||
logging.info("No clients connected. Message not broadcasted.")
|
||||
|
||||
|
||||
async def main():
|
||||
"""Starts the WebSocket server."""
|
||||
start_server = websockets.serve(handle_client, "localhost", 8765)
|
||||
logging.info("WebSocket server started on ws://localhost:8765")
|
||||
await start_server
|
||||
await asyncio.Future() # Keep the server running indefinitely
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user