Browse Source

Interação inicial do Vue com Websocket

Websocket_painel
AlGouvea 3 years ago
parent
commit
9eb652a1e3
  1. 16
      frontend/src/__apps/painel/main.js
  2. 39
      sapl/painel/consumers.py
  3. 1
      sapl/painel/tasks.py

16
frontend/src/__apps/painel/main.js

@ -11,6 +11,7 @@ var time = null
var timeEnd = null
var audioAlertFinish = document.getElementById('audio')
var cronometroStart = []
const socket = new WebSocket(`ws://${window.location.host}/ws/painel/`)
const v = new Vue({ // eslint-disable-line
delimiters: ['[[', ']]'],
@ -248,9 +249,11 @@ const v = new Vue({ // eslint-disable-line
this.clockRunning(crono)
}, 100)
},
foi: function foi () {
socket.send('teste')
},
pollData () {
this.fetchData()
this.polling = setInterval(() => {
// console.info('Fetching data from backend')
this.fetchData()
@ -262,12 +265,15 @@ const v = new Vue({ // eslint-disable-line
clearInterval(this.polling)
},
created () {
const socket = new WebSocket(`ws://${window.location.host}/ws/painel/`)
socket.onopen = function (e) {
console.log('Connection established')
console.log(e)
socket.send('teste')
}
const _this = this
socket.onmessage = function (e) {
_this.teste = e.data
console.log(_this.teste)
}
socket.onclose = function (e) {

39
sapl/painel/consumers.py

@ -1,26 +1,29 @@
import json
from channels.generic.websocket import WebsocketConsumer
import requests
from channels.generic.websocket import AsyncJsonWebsocketConsumer
class PainelConsumer(WebsocketConsumer):
def connect(self):
self.channel_layer.group_add('message', self.channel_name)
self.accept()
self.send('Teste')
class PainelConsumer(AsyncJsonWebsocketConsumer):
async def connect (self):
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard('message', self.channel_name)
pass
async def receive(self, text_data):
print('Received Message')
print('Enviando...')
url_dados = 'http://localhost:8000/painel/786/dados'
#response = requests.get(url_dados)
#print(response)
def receive(self, text_data):
print('receive message')
text_data_json = json.loads(text_data)
message = text_data_json['message']
await self.send_json({
'message': 'teste'
})
self.send(text_data=json.dumps({
'message': message
}))
async def send(self, event):
print('Entrou')
async def send_message (self, event):
new_data = event['text']
print(new_data)
await self.send(json.dumps(new_data))

1
sapl/painel/tasks.py

@ -23,6 +23,5 @@ def get_cronometro():
if post.ok: print('conexao realizada com sucesso')
r = session.get('http://localhost:8000/painel/786/dados')
json_data = r.json()
print(json_data)
async_to_sync(channel_layer.group_send)('message', {'type':'send_message', 'text': json_data})

Loading…
Cancel
Save