mirror of
https://github.com/welton89/RRBEC.git
synced 2026-04-05 21:45:41 +00:00
websocket part2 | notificação
This commit is contained in:
Binary file not shown.
@@ -13,7 +13,7 @@ import asyncio
|
||||
import websockets
|
||||
|
||||
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:
|
||||
await websocket.send(msg)
|
||||
print(f"> Enviado: {msg}")
|
||||
@@ -66,7 +66,17 @@ def addProduct(request, product_id, comanda_id):
|
||||
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>',
|
||||
'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',
|
||||
'tipo':'add',
|
||||
'id':order.id,
|
||||
@@ -83,6 +93,15 @@ def editOrders(request, productComanda_id, obs):
|
||||
order = Order.objects.get(productComanda=productComanda_id)
|
||||
order.obs = obs
|
||||
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'})
|
||||
|
||||
|
||||
@@ -95,8 +114,23 @@ def removeProductComanda(request, productComanda_id):
|
||||
comanda = Comanda.objects.get(id= product_comanda.comanda.id)
|
||||
parcial = Payments.objects.filter(comanda=comanda)
|
||||
consumo = ProductComanda.objects.filter(comanda=comanda)
|
||||
product_comanda.delete()
|
||||
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})
|
||||
|
||||
@group_required(groupName='Garçom')
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -41,7 +41,7 @@
|
||||
<div id="Fila" class="tabcontent">
|
||||
{% for order in orders %}
|
||||
{% 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 %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
@@ -61,14 +61,13 @@
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<!-- <output id="fila"></output> -->
|
||||
</div>
|
||||
|
||||
|
||||
<div id="Preparo" class="tabcontent">
|
||||
{% for order in orders %}
|
||||
{% 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 %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
@@ -93,7 +92,7 @@
|
||||
<div id="Finalizado" class="tabcontent">
|
||||
{% for order in orders %}
|
||||
{% 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 %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
@@ -118,7 +117,7 @@
|
||||
<div id="Entregue" class="tabcontent">
|
||||
{% for order in orders %}
|
||||
{% if order.delivered != None %}
|
||||
<div class="m-card"
|
||||
<div class="m-card" id="m-card-{{order.id}}"
|
||||
{% if order.productComanda == Null %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
|
||||
@@ -12,7 +12,7 @@ from gestaoRaul.decorators import group_required
|
||||
|
||||
|
||||
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:
|
||||
await websocket.send(message)
|
||||
print(f"> Enviado: {message}")
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
<h1>
|
||||
<img src="{% static 'midia/logo.png' %}" width="60">
|
||||
</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 class="nav-list">
|
||||
<ul>
|
||||
@@ -52,7 +53,7 @@
|
||||
</div>
|
||||
|
||||
<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>
|
||||
</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">
|
||||
{% for order in orders %}
|
||||
{% 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 %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
@@ -19,7 +12,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>
|
||||
@@ -36,7 +29,7 @@
|
||||
{% for order in orders %}
|
||||
{% 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 %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
@@ -44,7 +37,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>
|
||||
@@ -59,7 +52,7 @@
|
||||
<div id="Finalizado" class="tabcontent">
|
||||
{% for order in orders %}
|
||||
{% 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 %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
@@ -67,7 +60,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>
|
||||
@@ -83,7 +76,7 @@
|
||||
{% for order in orders %}
|
||||
{% if order.delivered != None %}
|
||||
|
||||
<div class="m-card"
|
||||
<div class="m-card" id="m-card-{{order.id}}"
|
||||
{% if order.productComanda == Null %}
|
||||
style="background-color: rgb(253, 69, 69);"
|
||||
{% elif order.obs != '' %}
|
||||
@@ -91,7 +84,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>
|
||||
|
||||
@@ -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) => {
|
||||
console.log('Conectado ao servidor WebSocket');
|
||||
@@ -7,18 +38,66 @@ websocket.addEventListener('open', (event) => {
|
||||
|
||||
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);
|
||||
|
||||
switch (data.local) {
|
||||
case 'cozinha':
|
||||
if (document.getElementById('Fila') !== null && data.tipo === 'add'){
|
||||
const novoElemento = document.createElement('div');
|
||||
novoElemento.innerHTML = data.message;
|
||||
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);
|
||||
window.speechSynthesis.speak(texto);
|
||||
}
|
||||
console.log('Mensagem recebida:', data.local);
|
||||
}
|
||||
else if (document.getElementById('obs-'+data.id) !== null && data.tipo === 'edit'){
|
||||
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);
|
||||
}
|
||||
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) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
function reloadPage(){
|
||||
setTimeout(function() {
|
||||
location.reload();}, 4000);
|
||||
location.reload();}, 3000);
|
||||
}
|
||||
|
||||
function openTab(evt, etapa) {
|
||||
@@ -42,15 +42,13 @@ function openTab(evt, etapa) {
|
||||
|
||||
setTimeout(function() {
|
||||
displayBlock(tab);}, 1000);
|
||||
// reloadPage();
|
||||
}
|
||||
|
||||
|
||||
displayBlock('Fila');
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function mostrarNotificacao(titulo,corpo,grupo) {
|
||||
if (Notification.permission != 'granted') {
|
||||
Notification.requestPermission().then(function(permission) {
|
||||
@@ -71,31 +69,31 @@ function openTab(evt, etapa) {
|
||||
}
|
||||
}
|
||||
|
||||
function notificacao(){
|
||||
// function notificacao(){
|
||||
|
||||
var resposta = fetch(`/pedidos/notificacao/`, {method: 'GET',
|
||||
headers: {'Content-Type': 'application/json',
|
||||
},})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data['notificacao'] == 'true'){
|
||||
document.cookie = `fila=${data['fila']}`;
|
||||
mostrarNotificacao(data['titulo'], data['corpo'],'Cozinha')
|
||||
texto = new SpeechSynthesisUtterance(data['corpo']+', '+data['titulo']+'.');
|
||||
window.speechSynthesis.speak(texto);
|
||||
reloadPage();
|
||||
// var resposta = fetch(`/pedidos/notificacao/`, {method: 'GET',
|
||||
// headers: {'Content-Type': 'application/json',
|
||||
// },})
|
||||
// .then(response => response.json())
|
||||
// .then(data => {
|
||||
// if (data['notificacao'] == 'true'){
|
||||
// document.cookie = `fila=${data['fila']}`;
|
||||
// mostrarNotificacao(data['titulo'], data['corpo'],'Cozinha')
|
||||
// texto = new SpeechSynthesisUtterance(data['corpo']+', '+data['titulo']+'.');
|
||||
// window.speechSynthesis.speak(texto);
|
||||
// reloadPage();
|
||||
|
||||
}else{
|
||||
console.log(data['notificacao'])
|
||||
console.log('notificação foi false')
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
alert('Erro verificar notificação:', error)
|
||||
console.error('Erro verificar notificação:', error);
|
||||
});
|
||||
// }else{
|
||||
// console.log(data['notificacao'])
|
||||
// console.log('notificação foi false')
|
||||
// }
|
||||
// })
|
||||
// .catch(error => {
|
||||
// alert('Erro verificar notificação:', error)
|
||||
// console.error('Erro verificar notificação:', error);
|
||||
// });
|
||||
|
||||
}
|
||||
// }
|
||||
|
||||
|
||||
// setInterval(()=> {
|
||||
|
||||
@@ -2,70 +2,70 @@ import asyncio
|
||||
import websockets
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
# Configure logging
|
||||
|
||||
# Configurar o registro de logs
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
connected_clients = set() # Keep track of connected clients
|
||||
connected_clients = set()
|
||||
|
||||
async def handle_client(websocket): # Remove 'path' argument
|
||||
"""Handles a single client connection."""
|
||||
logging.info(f"Client connected: {websocket.remote_address}")
|
||||
async def handle_client(websocket):
|
||||
logging.info(f"Cliente conectado: {websocket.remote_address}")
|
||||
connected_clients.add(websocket)
|
||||
# for client in connected_clients:
|
||||
# await client.send(json.dumps({"message": "Novo cliente conectado"}))
|
||||
# print(client)
|
||||
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}")
|
||||
logging.info(f"Mensagem recebida de {websocket.remote_address}: {message}")
|
||||
print(f"Mensagem recebida de {websocket.remote_address}: {message}")
|
||||
try:
|
||||
data = json.loads(message)
|
||||
# Process the message here
|
||||
# Processa a mensagem aqui
|
||||
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"}))
|
||||
logging.error(f"JSON inválido recebido de {websocket.remote_address}: {message}")
|
||||
await websocket.send(json.dumps({"error": "Formato JSON inválido"}))
|
||||
except Exception as e:
|
||||
logging.error(f"Error processing message from {websocket.remote_address}: {e}")
|
||||
await websocket.send(json.dumps({"error": "Error processing message"}))
|
||||
logging.error(f"Erro ao processar mensagem de {websocket.remote_address}: {e}")
|
||||
await websocket.send(json.dumps({"error": "Erro ao processar mensagem"}))
|
||||
|
||||
except websockets.exceptions.ConnectionClosedOK:
|
||||
logging.info(f"Client disconnected: {websocket.remote_address}")
|
||||
logging.info(f"Cliente desconectado: {websocket.remote_address}")
|
||||
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:
|
||||
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:
|
||||
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"])
|
||||
print("Mensagem de Broadcast:", 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"}))
|
||||
await websocket.send(json.dumps({"response": "teste está ok"}))
|
||||
else:
|
||||
logging.warning(f"Unknown message type or format: {data}")
|
||||
await websocket.send(json.dumps({"error": "Unknown message type"}))
|
||||
logging.warning(f"Tipo de mensagem ou formato desconhecido: {data}")
|
||||
await websocket.send(json.dumps({"error": "Tipo de mensagem desconhecido"}))
|
||||
|
||||
async def broadcast_message(data):
|
||||
"""Broadcasts a message to all 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])
|
||||
else:
|
||||
logging.info("No clients connected. Message not broadcasted.")
|
||||
logging.info("Nenhum cliente conectado.")
|
||||
|
||||
|
||||
async def main():
|
||||
"""Starts the WebSocket server."""
|
||||
start_server = websockets.serve(handle_client, "localhost", 8765)
|
||||
logging.info("WebSocket server started on ws://localhost:8765")
|
||||
start_server = websockets.serve(handle_client, "192.168.1.150", 8765)
|
||||
logging.info("Servidor WebSocket iniciado em ws://192.168.1.150:8765")
|
||||
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__":
|
||||
|
||||
Reference in New Issue
Block a user