mirror of
https://github.com/welton89/RRBEC.git
synced 2026-04-05 13:35:42 +00:00
websocket part2 | notificação
This commit is contained in:
Binary file not shown.
@@ -13,7 +13,7 @@ import asyncio
|
|||||||
import websockets
|
import websockets
|
||||||
|
|
||||||
async def enviar_mensagem(msg):
|
async def enviar_mensagem(msg):
|
||||||
uri = "ws://localhost:8765" # Substitua pela URI do seu servidor WebSocket
|
uri = "ws://192.168.1.150:8765"
|
||||||
async with websockets.connect(uri) as websocket:
|
async with websockets.connect(uri) as websocket:
|
||||||
await websocket.send(msg)
|
await websocket.send(msg)
|
||||||
print(f"> Enviado: {msg}")
|
print(f"> Enviado: {msg}")
|
||||||
@@ -66,7 +66,17 @@ def addProduct(request, product_id, comanda_id):
|
|||||||
order.save()
|
order.save()
|
||||||
msg = JsonResponse({
|
msg = JsonResponse({
|
||||||
'type': 'broadcast',
|
'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>',
|
'message': f"""
|
||||||
|
<div class="m-card" id="m-card-{order.id}">
|
||||||
|
<h4>{product.name}</h4>
|
||||||
|
|
||||||
|
<h4>{comanda.name} - {comanda.mesa.name}</h4>
|
||||||
|
<h4> Atendente: {comanda.user.first_name}</h4>
|
||||||
|
<h4> {order.queue}</h4>
|
||||||
|
<button class="btn-primary" onclick="delayTab('Fila')"
|
||||||
|
hx-get="/pedidos/preparing/{order.id}/" hx-trigger="click" hx-target="#etapas"
|
||||||
|
>Preparar</button></div>
|
||||||
|
""",
|
||||||
'local':'cozinha',
|
'local':'cozinha',
|
||||||
'tipo':'add',
|
'tipo':'add',
|
||||||
'id':order.id,
|
'id':order.id,
|
||||||
@@ -83,6 +93,15 @@ def editOrders(request, productComanda_id, obs):
|
|||||||
order = Order.objects.get(productComanda=productComanda_id)
|
order = Order.objects.get(productComanda=productComanda_id)
|
||||||
order.obs = obs
|
order.obs = obs
|
||||||
order.save()
|
order.save()
|
||||||
|
msg = JsonResponse({
|
||||||
|
'type': 'broadcast',
|
||||||
|
'message': obs,
|
||||||
|
'local':'cozinha',
|
||||||
|
'tipo':'edit',
|
||||||
|
'id':order.id,
|
||||||
|
'speak': f'Pedido alterado! {order.id_product.name}, é {obs}.'
|
||||||
|
})
|
||||||
|
asyncio.run(enviar_mensagem(msg))
|
||||||
return JsonResponse({'status': 'ok'})
|
return JsonResponse({'status': 'ok'})
|
||||||
|
|
||||||
|
|
||||||
@@ -95,8 +114,23 @@ def removeProductComanda(request, productComanda_id):
|
|||||||
comanda = Comanda.objects.get(id= product_comanda.comanda.id)
|
comanda = Comanda.objects.get(id= product_comanda.comanda.id)
|
||||||
parcial = Payments.objects.filter(comanda=comanda)
|
parcial = Payments.objects.filter(comanda=comanda)
|
||||||
consumo = ProductComanda.objects.filter(comanda=comanda)
|
consumo = ProductComanda.objects.filter(comanda=comanda)
|
||||||
product_comanda.delete()
|
|
||||||
valores = somar(consumo,comanda)
|
valores = somar(consumo,comanda)
|
||||||
|
if product_comanda.product.cuisine == True:
|
||||||
|
order = Order.objects.get(productComanda=product_comanda)
|
||||||
|
product_comanda.delete()
|
||||||
|
msg = JsonResponse({
|
||||||
|
'type': 'broadcast',
|
||||||
|
'message': 'Atenção! Pedido cancelado',
|
||||||
|
'local':'cozinha',
|
||||||
|
'tipo':'delete',
|
||||||
|
'id':order.id,
|
||||||
|
'speak': f'Pedido cancelado! {order.id_product.name}.'
|
||||||
|
})
|
||||||
|
asyncio.run(enviar_mensagem(msg))
|
||||||
|
# order.delete()
|
||||||
|
else:
|
||||||
|
product_comanda.delete()
|
||||||
|
|
||||||
return render(request, "htmx_components/comandas/htmx_list_products_in_comanda.html",{'config':config, 'valores': valores,'parcials':parcial,'consumo': consumo, 'comanda':comanda})
|
return render(request, "htmx_components/comandas/htmx_list_products_in_comanda.html",{'config':config, 'valores': valores,'parcials':parcial,'consumo': consumo, 'comanda':comanda})
|
||||||
|
|
||||||
@group_required(groupName='Garçom')
|
@group_required(groupName='Garçom')
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
@@ -41,7 +41,7 @@
|
|||||||
<div id="Fila" class="tabcontent">
|
<div id="Fila" class="tabcontent">
|
||||||
{% for order in orders %}
|
{% for order in orders %}
|
||||||
{% if order.preparing == None and order.productComanda != Null %}
|
{% if order.preparing == None and order.productComanda != Null %}
|
||||||
<div class="m-card"
|
<div class="m-card" id="m-card-{{order.id}}"
|
||||||
{% if order.productComanda == Null %}
|
{% if order.productComanda == Null %}
|
||||||
style="background-color: rgb(253, 69, 69);"
|
style="background-color: rgb(253, 69, 69);"
|
||||||
{% elif order.obs != '' %}
|
{% elif order.obs != '' %}
|
||||||
@@ -61,14 +61,13 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<!-- <output id="fila"></output> -->
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
<div id="Preparo" class="tabcontent">
|
<div id="Preparo" class="tabcontent">
|
||||||
{% for order in orders %}
|
{% for order in orders %}
|
||||||
{% if order.finished == None and order.preparing != None %}
|
{% if order.finished == None and order.preparing != None %}
|
||||||
<div class="m-card"
|
<div class="m-card" id="m-card-{{order.id}}"
|
||||||
{% if order.productComanda == Null %}
|
{% if order.productComanda == Null %}
|
||||||
style="background-color: rgb(253, 69, 69);"
|
style="background-color: rgb(253, 69, 69);"
|
||||||
{% elif order.obs != '' %}
|
{% elif order.obs != '' %}
|
||||||
@@ -93,7 +92,7 @@
|
|||||||
<div id="Finalizado" class="tabcontent">
|
<div id="Finalizado" class="tabcontent">
|
||||||
{% for order in orders %}
|
{% for order in orders %}
|
||||||
{% if order.delivered == None and order.finished != None %}
|
{% if order.delivered == None and order.finished != None %}
|
||||||
<div class="m-card"
|
<div class="m-card" id="m-card-{{order.id}}"
|
||||||
{% if order.productComanda == Null %}
|
{% if order.productComanda == Null %}
|
||||||
style="background-color: rgb(253, 69, 69);"
|
style="background-color: rgb(253, 69, 69);"
|
||||||
{% elif order.obs != '' %}
|
{% elif order.obs != '' %}
|
||||||
@@ -118,7 +117,7 @@
|
|||||||
<div id="Entregue" class="tabcontent">
|
<div id="Entregue" class="tabcontent">
|
||||||
{% for order in orders %}
|
{% for order in orders %}
|
||||||
{% if order.delivered != None %}
|
{% if order.delivered != None %}
|
||||||
<div class="m-card"
|
<div class="m-card" id="m-card-{{order.id}}"
|
||||||
{% if order.productComanda == Null %}
|
{% if order.productComanda == Null %}
|
||||||
style="background-color: rgb(253, 69, 69);"
|
style="background-color: rgb(253, 69, 69);"
|
||||||
{% elif order.obs != '' %}
|
{% elif order.obs != '' %}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ from gestaoRaul.decorators import group_required
|
|||||||
|
|
||||||
|
|
||||||
async def enviar_mensagem(message):
|
async def enviar_mensagem(message):
|
||||||
uri = "ws://localhost:8765" # Substitua pela URI do seu servidor WebSocket
|
uri = "ws://192.168.1.150:8765"
|
||||||
async with websockets.connect(uri) as websocket:
|
async with websockets.connect(uri) as websocket:
|
||||||
await websocket.send(message)
|
await websocket.send(message)
|
||||||
print(f"> Enviado: {message}")
|
print(f"> Enviado: {message}")
|
||||||
|
|||||||
@@ -26,6 +26,7 @@
|
|||||||
<h1>
|
<h1>
|
||||||
<img src="{% static 'midia/logo.png' %}" width="60">
|
<img src="{% static 'midia/logo.png' %}" width="60">
|
||||||
</h1>
|
</h1>
|
||||||
|
<button id="icon-notify" style="border: none; margin-left: 10px; border-radius: 20px; height: 40px;width: 40px; padding: 2px; align-self: center;" onclick="cookieNotificacao()" >🔔</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="nav-list">
|
<div class="nav-list">
|
||||||
<ul>
|
<ul>
|
||||||
@@ -52,7 +53,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="logout-button">
|
<div class="logout-button">
|
||||||
{{ user.first_name }} {{ user.last_name }}
|
<div id="user-info">{{user.first_name}} {{user.last_name}}</div>
|
||||||
<a href="{% url 'logout' %}" style="width: 50px;"><img src="{% static 'midia/icons/logout.svg' %}" style="width: 40px;"></a>
|
<a href="{% url 'logout' %}" style="width: 50px;"><img src="{% static 'midia/icons/logout.svg' %}" style="width: 40px;"></a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,10 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<!-- <div class="tab">
|
|
||||||
<button class="tablinks active" onclick="openTab(event, 'Fila')">Fila</button>
|
|
||||||
<button class="tablinks" onclick="openTab(event, 'Preparo')">Preparo</button>
|
|
||||||
<button class="tablinks" onclick="openTab(event, 'Finalizado')">Pronto</button>
|
|
||||||
<button class="tablinks" onclick="openTab(event, 'Entregue')">Entregue</button>
|
|
||||||
</div> -->
|
|
||||||
|
|
||||||
<div id="Fila" class="tabcontent">
|
<div id="Fila" class="tabcontent">
|
||||||
{% for order in orders %}
|
{% for order in orders %}
|
||||||
{% if order.preparing == None and order.productComanda != Null %}
|
{% if order.preparing == None and order.productComanda != Null %}
|
||||||
<div class="m-card"
|
<div class="m-card" id="m-card-{{order.id}}"
|
||||||
{% if order.productComanda == Null %}
|
{% if order.productComanda == Null %}
|
||||||
style="background-color: rgb(253, 69, 69);"
|
style="background-color: rgb(253, 69, 69);"
|
||||||
{% elif order.obs != '' %}
|
{% elif order.obs != '' %}
|
||||||
@@ -19,7 +12,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
>
|
>
|
||||||
<h4>{{order.id_product.name}}</h4>
|
<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>{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}} </h4>
|
||||||
<h4> Atendente: {{order.id_comanda.user.first_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>
|
<h4>{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}</h4>
|
||||||
@@ -36,7 +29,7 @@
|
|||||||
{% for order in orders %}
|
{% for order in orders %}
|
||||||
{% if order.finished == None and order.preparing != None %}
|
{% if order.finished == None and order.preparing != None %}
|
||||||
|
|
||||||
<div class="m-card"
|
<div class="m-card" id="m-card-{{order.id}}"
|
||||||
{% if order.productComanda == Null %}
|
{% if order.productComanda == Null %}
|
||||||
style="background-color: rgb(253, 69, 69);"
|
style="background-color: rgb(253, 69, 69);"
|
||||||
{% elif order.obs != '' %}
|
{% elif order.obs != '' %}
|
||||||
@@ -44,7 +37,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
>
|
>
|
||||||
<h4>{{order.id_product.name}}</h4>
|
<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>{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}} </h4>
|
||||||
<h4> Atendente: {{order.id_comanda.user.first_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>
|
<h4>{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}</h4>
|
||||||
@@ -59,7 +52,7 @@
|
|||||||
<div id="Finalizado" class="tabcontent">
|
<div id="Finalizado" class="tabcontent">
|
||||||
{% for order in orders %}
|
{% for order in orders %}
|
||||||
{% if order.delivered == None and order.finished != None %}
|
{% if order.delivered == None and order.finished != None %}
|
||||||
<div class="m-card"
|
<div class="m-card" id="m-card-{{order.id}}"
|
||||||
{% if order.productComanda == Null %}
|
{% if order.productComanda == Null %}
|
||||||
style="background-color: rgb(253, 69, 69);"
|
style="background-color: rgb(253, 69, 69);"
|
||||||
{% elif order.obs != '' %}
|
{% elif order.obs != '' %}
|
||||||
@@ -67,7 +60,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
>
|
>
|
||||||
<h4>{{order.id_product.name}}</h4>
|
<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>{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}} </h4>
|
||||||
<h4> Atendente: {{order.id_comanda.user.first_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>
|
<h4>{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}</h4>
|
||||||
@@ -83,7 +76,7 @@
|
|||||||
{% for order in orders %}
|
{% for order in orders %}
|
||||||
{% if order.delivered != None %}
|
{% if order.delivered != None %}
|
||||||
|
|
||||||
<div class="m-card"
|
<div class="m-card" id="m-card-{{order.id}}"
|
||||||
{% if order.productComanda == Null %}
|
{% if order.productComanda == Null %}
|
||||||
style="background-color: rgb(253, 69, 69);"
|
style="background-color: rgb(253, 69, 69);"
|
||||||
{% elif order.obs != '' %}
|
{% elif order.obs != '' %}
|
||||||
@@ -91,7 +84,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
>
|
>
|
||||||
<h4>{{order.id_product.name}}</h4>
|
<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>{{order.id_comanda.name}} - {{order.id_comanda.mesa.name}} </h4>
|
||||||
<h4> Atendente: {{order.id_comanda.user.first_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>
|
<h4>{{order.queue|date:"D"}} {{order.queue|date:"d/m/Y - H:i"}}</h4>
|
||||||
|
|||||||
@@ -1,5 +1,36 @@
|
|||||||
|
function verificarCookieNotificacao() {
|
||||||
|
console.log('cookie notificacao verificado');
|
||||||
|
if (document.cookie.indexOf('notificacao=') === -1) {
|
||||||
|
document.cookie = 'notificacao=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
|
||||||
|
var iconNotify = document.getElementById('icon-notify');
|
||||||
|
iconNotify.style.backgroundColor = 'green';
|
||||||
|
console.log('cookie notificacao criado');
|
||||||
|
}else{
|
||||||
|
let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1");
|
||||||
|
var iconNotify = document.getElementById('icon-notify');
|
||||||
|
iconNotify.style.backgroundColor = valorAtual === 'true' ? 'green' : 'red';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
verificarCookieNotificacao();
|
||||||
|
|
||||||
const websocket = new WebSocket('ws://localhost:8765');
|
function cookieNotificacao() {
|
||||||
|
if (document.cookie.indexOf('notificacao=') !== -1) {
|
||||||
|
let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1");
|
||||||
|
var iconNotify = document.getElementById('icon-notify');
|
||||||
|
let novoValor = valorAtual === 'true' ? 'false' : 'true';
|
||||||
|
if (novoValor === 'true') {
|
||||||
|
iconNotify.style.backgroundColor = 'green';
|
||||||
|
}else{
|
||||||
|
iconNotify.style.backgroundColor = 'red';
|
||||||
|
}
|
||||||
|
document.cookie = 'notificacao=' + novoValor + '; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
|
||||||
|
} else {
|
||||||
|
document.cookie = 'notificacao=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const websocket = new WebSocket('ws://192.168.1.150:8765');
|
||||||
|
const nomeUsuario = document.getElementById('user-info').textContent;
|
||||||
|
|
||||||
websocket.addEventListener('open', (event) => {
|
websocket.addEventListener('open', (event) => {
|
||||||
console.log('Conectado ao servidor WebSocket');
|
console.log('Conectado ao servidor WebSocket');
|
||||||
@@ -7,18 +38,66 @@ websocket.addEventListener('open', (event) => {
|
|||||||
|
|
||||||
websocket.addEventListener('message', (event) => {
|
websocket.addEventListener('message', (event) => {
|
||||||
const data = JSON.parse(event.data);
|
const data = JSON.parse(event.data);
|
||||||
if (data.local === 'cozinha' && data.tipo === 'add'){
|
|
||||||
|
switch (data.local) {
|
||||||
|
case 'cozinha':
|
||||||
|
if (document.getElementById('Fila') !== null && data.tipo === 'add'){
|
||||||
const novoElemento = document.createElement('div');
|
const novoElemento = document.createElement('div');
|
||||||
novoElemento.innerHTML = data.message;
|
novoElemento.innerHTML = data.message;
|
||||||
var fila = document.getElementById('Fila').appendChild(novoElemento);
|
var fila = document.getElementById('Fila').appendChild(novoElemento);
|
||||||
|
let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1");
|
||||||
|
if (valorAtual === 'true') {
|
||||||
|
|
||||||
texto = new SpeechSynthesisUtterance(data.speak);
|
texto = new SpeechSynthesisUtterance(data.speak);
|
||||||
window.speechSynthesis.speak(texto);
|
window.speechSynthesis.speak(texto);
|
||||||
|
}
|
||||||
console.log('Mensagem recebida:', data.local);
|
console.log('Mensagem recebida:', data.local);
|
||||||
}
|
}
|
||||||
else if (data.local === 'cozinha' && data.tipo === 'edit'){
|
else if (document.getElementById('obs-'+data.id) !== null && data.tipo === 'edit'){
|
||||||
var card = document.getElementById('obs-'+data.id).innerHTML = data.message
|
const obs = document.getElementById('obs-'+data.id)
|
||||||
|
const card = obs.parentNode;
|
||||||
|
card.style.backgroundColor = 'rgb(243, 165, 75)';
|
||||||
|
obs.innerHTML = data.message;
|
||||||
|
let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1");
|
||||||
|
|
||||||
|
if (valorAtual === 'true') {
|
||||||
|
texto = new SpeechSynthesisUtterance(data.speak);
|
||||||
|
window.speechSynthesis.speak(texto);
|
||||||
|
}
|
||||||
console.log('Mensagem recebida:', data.local);
|
console.log('Mensagem recebida:', data.local);
|
||||||
}
|
}
|
||||||
|
else if (document.getElementById('m-card-'+data.id) !== null && data.tipo === 'delete'){
|
||||||
|
const card = document.getElementById('m-card-'+data.id)
|
||||||
|
card.style.backgroundColor = 'rgb(253, 69, 69)';
|
||||||
|
// obs.innerHTML = data.message;
|
||||||
|
let valorAtual = document.cookie.replace(/(?:(?:^|.*;\s*)notificacao\s*\=\s*([^;]*).*$)|^.*$/, "$1");
|
||||||
|
|
||||||
|
if (valorAtual === 'true') {
|
||||||
|
texto = new SpeechSynthesisUtterance(data.speak);
|
||||||
|
window.speechSynthesis.speak(texto);
|
||||||
|
}
|
||||||
|
console.log('Mensagem recebida:', data.local);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 'praca':
|
||||||
|
console.log('Código a ser executado se expressao === valor2')
|
||||||
|
break;
|
||||||
|
case 'guarita':
|
||||||
|
// Código a ser executado se expressao === valor3
|
||||||
|
break;
|
||||||
|
case 'balcao':
|
||||||
|
// Código a ser executado se expressao === valor3
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
console.log('Local desconhecido:', data);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
websocket.addEventListener('error', (event) => {
|
websocket.addEventListener('error', (event) => {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
|
|
||||||
function reloadPage(){
|
function reloadPage(){
|
||||||
setTimeout(function() {
|
setTimeout(function() {
|
||||||
location.reload();}, 4000);
|
location.reload();}, 3000);
|
||||||
}
|
}
|
||||||
|
|
||||||
function openTab(evt, etapa) {
|
function openTab(evt, etapa) {
|
||||||
@@ -42,15 +42,13 @@ function openTab(evt, etapa) {
|
|||||||
|
|
||||||
setTimeout(function() {
|
setTimeout(function() {
|
||||||
displayBlock(tab);}, 1000);
|
displayBlock(tab);}, 1000);
|
||||||
|
// reloadPage();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
displayBlock('Fila');
|
displayBlock('Fila');
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
function mostrarNotificacao(titulo,corpo,grupo) {
|
function mostrarNotificacao(titulo,corpo,grupo) {
|
||||||
if (Notification.permission != 'granted') {
|
if (Notification.permission != 'granted') {
|
||||||
Notification.requestPermission().then(function(permission) {
|
Notification.requestPermission().then(function(permission) {
|
||||||
@@ -71,31 +69,31 @@ function openTab(evt, etapa) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function notificacao(){
|
// function notificacao(){
|
||||||
|
|
||||||
var resposta = fetch(`/pedidos/notificacao/`, {method: 'GET',
|
// var resposta = fetch(`/pedidos/notificacao/`, {method: 'GET',
|
||||||
headers: {'Content-Type': 'application/json',
|
// headers: {'Content-Type': 'application/json',
|
||||||
},})
|
// },})
|
||||||
.then(response => response.json())
|
// .then(response => response.json())
|
||||||
.then(data => {
|
// .then(data => {
|
||||||
if (data['notificacao'] == 'true'){
|
// if (data['notificacao'] == 'true'){
|
||||||
document.cookie = `fila=${data['fila']}`;
|
// document.cookie = `fila=${data['fila']}`;
|
||||||
mostrarNotificacao(data['titulo'], data['corpo'],'Cozinha')
|
// mostrarNotificacao(data['titulo'], data['corpo'],'Cozinha')
|
||||||
texto = new SpeechSynthesisUtterance(data['corpo']+', '+data['titulo']+'.');
|
// texto = new SpeechSynthesisUtterance(data['corpo']+', '+data['titulo']+'.');
|
||||||
window.speechSynthesis.speak(texto);
|
// window.speechSynthesis.speak(texto);
|
||||||
reloadPage();
|
// reloadPage();
|
||||||
|
|
||||||
}else{
|
// }else{
|
||||||
console.log(data['notificacao'])
|
// console.log(data['notificacao'])
|
||||||
console.log('notificação foi false')
|
// console.log('notificação foi false')
|
||||||
}
|
// }
|
||||||
})
|
// })
|
||||||
.catch(error => {
|
// .catch(error => {
|
||||||
alert('Erro verificar notificação:', error)
|
// alert('Erro verificar notificação:', error)
|
||||||
console.error('Erro verificar notificação:', error);
|
// console.error('Erro verificar notificação:', error);
|
||||||
});
|
// });
|
||||||
|
|
||||||
}
|
// }
|
||||||
|
|
||||||
|
|
||||||
// setInterval(()=> {
|
// setInterval(()=> {
|
||||||
|
|||||||
@@ -2,70 +2,70 @@ import asyncio
|
|||||||
import websockets
|
import websockets
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
import uuid
|
||||||
|
|
||||||
# Configure logging
|
|
||||||
|
# Configurar o registro de logs
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
|
||||||
connected_clients = set() # Keep track of connected clients
|
connected_clients = set()
|
||||||
|
|
||||||
async def handle_client(websocket): # Remove 'path' argument
|
async def handle_client(websocket):
|
||||||
"""Handles a single client connection."""
|
logging.info(f"Cliente conectado: {websocket.remote_address}")
|
||||||
logging.info(f"Client connected: {websocket.remote_address}")
|
|
||||||
connected_clients.add(websocket)
|
connected_clients.add(websocket)
|
||||||
|
# for client in connected_clients:
|
||||||
|
# await client.send(json.dumps({"message": "Novo cliente conectado"}))
|
||||||
|
# print(client)
|
||||||
try:
|
try:
|
||||||
async for message in websocket:
|
async for message in websocket:
|
||||||
logging.info(f"Received message from {websocket.remote_address}: {message}")
|
logging.info(f"Mensagem recebida de {websocket.remote_address}: {message}")
|
||||||
print(f"Received message from {websocket.remote_address}: {message}")
|
print(f"Mensagem recebida de {websocket.remote_address}: {message}")
|
||||||
try:
|
try:
|
||||||
data = json.loads(message)
|
data = json.loads(message)
|
||||||
# Process the message here
|
# Processa a mensagem aqui
|
||||||
await process_message(data, websocket)
|
await process_message(data, websocket)
|
||||||
|
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
logging.error(f"Invalid JSON received from {websocket.remote_address}: {message}")
|
logging.error(f"JSON inválido recebido de {websocket.remote_address}: {message}")
|
||||||
await websocket.send(json.dumps({"error": "Invalid JSON format"}))
|
await websocket.send(json.dumps({"error": "Formato JSON inválido"}))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Error processing message from {websocket.remote_address}: {e}")
|
logging.error(f"Erro ao processar mensagem de {websocket.remote_address}: {e}")
|
||||||
await websocket.send(json.dumps({"error": "Error processing message"}))
|
await websocket.send(json.dumps({"error": "Erro ao processar mensagem"}))
|
||||||
|
|
||||||
except websockets.exceptions.ConnectionClosedOK:
|
except websockets.exceptions.ConnectionClosedOK:
|
||||||
logging.info(f"Client disconnected: {websocket.remote_address}")
|
logging.info(f"Cliente desconectado: {websocket.remote_address}")
|
||||||
except websockets.exceptions.ConnectionClosedError:
|
except websockets.exceptions.ConnectionClosedError:
|
||||||
logging.error(f"Client connection closed with error {websocket.remote_address}")
|
logging.error(f"Conexão do cliente fechada com erro {websocket.remote_address}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Error during connection from {websocket.remote_address} with error {e}")
|
logging.error(f"Erro durante a conexão de {websocket.remote_address} com erro {e}")
|
||||||
finally:
|
finally:
|
||||||
connected_clients.remove(websocket)
|
connected_clients.remove(websocket)
|
||||||
|
|
||||||
async def process_message(data, 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:
|
if "type" in data and data["type"] == "broadcast" and "message" in data:
|
||||||
await broadcast_message(data)
|
await broadcast_message(data)
|
||||||
print("Broadcast message:", data["message"])
|
print("Mensagem de Broadcast:", data["message"])
|
||||||
elif "type" in data and data["type"] == "echo" and "message" in data:
|
elif "type" in data and data["type"] == "echo" and "message" in data:
|
||||||
await websocket.send(json.dumps({"response": data['message']}))
|
await websocket.send(json.dumps({"response": data['message']}))
|
||||||
elif "type" in data and data['type'] == "test":
|
elif "type" in data and data['type'] == "test":
|
||||||
await websocket.send(json.dumps({"response": "test is ok"}))
|
await websocket.send(json.dumps({"response": "teste está ok"}))
|
||||||
else:
|
else:
|
||||||
logging.warning(f"Unknown message type or format: {data}")
|
logging.warning(f"Tipo de mensagem ou formato desconhecido: {data}")
|
||||||
await websocket.send(json.dumps({"error": "Unknown message type"}))
|
await websocket.send(json.dumps({"error": "Tipo de mensagem desconhecido"}))
|
||||||
|
|
||||||
async def broadcast_message(data):
|
async def broadcast_message(data):
|
||||||
"""Broadcasts a message to all connected clients."""
|
|
||||||
if connected_clients:
|
if connected_clients:
|
||||||
logging.info(f"Broadcasting message: {data}")
|
logging.info(f"Enviando mensagem por broadcast: {data}")
|
||||||
await asyncio.wait([client.send(json.dumps(data)) for client in connected_clients])
|
await asyncio.wait([client.send(json.dumps(data)) for client in connected_clients])
|
||||||
else:
|
else:
|
||||||
logging.info("No clients connected. Message not broadcasted.")
|
logging.info("Nenhum cliente conectado.")
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
"""Starts the WebSocket server."""
|
start_server = websockets.serve(handle_client, "192.168.1.150", 8765)
|
||||||
start_server = websockets.serve(handle_client, "localhost", 8765)
|
logging.info("Servidor WebSocket iniciado em ws://192.168.1.150:8765")
|
||||||
logging.info("WebSocket server started on ws://localhost:8765")
|
|
||||||
await start_server
|
await start_server
|
||||||
await asyncio.Future() # Keep the server running indefinitely
|
await asyncio.Future() # Mantém o servidor em execução indefinidamente
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user