|
|
#!/usr/bin/python
|
|
|
# -*- coding: UTF-8 -*-
|
|
|
import os
|
|
|
import json
|
|
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
|
from pymongo import MongoClient
|
|
|
|
|
|
from channels.handler import AsgiHandler
|
|
|
from channels.auth import channel_session_user
|
|
|
from channels import Group
|
|
|
# Here we create the db named "dbplots"
|
|
|
host = os.environ.get('HOST_MONGO', 'localhost')
|
|
|
CLIENT = MongoClient('{}:27017'.format(host))
|
|
|
DB = CLIENT['dbplots']
|
|
|
|
|
|
# Connected to websocket.connect
|
|
|
def ws_connect(message, id, code, plot):
|
|
|
|
|
|
if id == 'main':
|
|
|
Group('main').add(message.reply_channel)
|
|
|
print('New main connection')
|
|
|
elif id == 'realtime':
|
|
|
Group('{}_{}'.format(code, plot)).add(message.reply_channel)
|
|
|
print('New connection from: {}, Group: {}_{}'.format(message.content['client'][0], code, plot))
|
|
|
else:
|
|
|
print('New connection from: {}, history, id: {}'.format(message.content['client'][0], id))
|
|
|
message.reply_channel.send({
|
|
|
'accept': True
|
|
|
})
|
|
|
|
|
|
def ws_message(message, id, code, plot):
|
|
|
# Accept the incoming connection
|
|
|
dt = datetime.strptime(str(json.loads(message.content['text'])['date']), '%d/%m/%Y')
|
|
|
exp0 = DB.exp_meta.find_one({'code': int(code), 'date': dt-timedelta(days=1)})
|
|
|
exp = DB.exp_meta.find_one({'code': int(code), 'date': dt})
|
|
|
print('New request for id={}'.format(id))
|
|
|
if exp and plot in exp['plots']:
|
|
|
if plot == 'spc':
|
|
|
datas = DB.exp_data.find({'expmeta': exp['_id']}, ['time', 'data']).sort('time', -1).limit(1)[0]
|
|
|
exp['time'] = [datas['time']]
|
|
|
exp['spc'] = datas['data']['spc']
|
|
|
exp['rti'] = datas['data']['rti']
|
|
|
exp['noise'] = datas['data']['noise']
|
|
|
else:
|
|
|
last = DB.exp_data.find_one({'expmeta': exp['_id']}, ['time'], sort=[('time', -1)])
|
|
|
if exp0:
|
|
|
datas = DB.exp_data.find(
|
|
|
{
|
|
|
'expmeta': {'$in': [exp0['_id'], exp['_id']]},
|
|
|
'time': {'$gt': last['time']-12*60*60}
|
|
|
},
|
|
|
['time', 'data'],
|
|
|
sort=[('time', 1)],
|
|
|
limit=720
|
|
|
)
|
|
|
else:
|
|
|
datas = DB.exp_data.find(
|
|
|
{
|
|
|
'expmeta': exp['_id'],
|
|
|
'time': {'$gt': last['time']-12*60*60}
|
|
|
},
|
|
|
['time', 'data'],
|
|
|
sort=[('time', 1)],
|
|
|
limit=720
|
|
|
)
|
|
|
dum = [(d['time'], d['data'][plot]) for d in datas]
|
|
|
exp['time'] = [d[0] for d in dum]
|
|
|
dum = [d[1] for d in dum]
|
|
|
exp[plot] = [t for t in map(list, zip(*dum))]
|
|
|
|
|
|
exp.pop('date', None)
|
|
|
exp.pop('_id', None)
|
|
|
message.reply_channel.send({'text': json.dumps(exp)})
|
|
|
else:
|
|
|
message.reply_channel.send({'text': json.dumps({'interval': 0})})
|
|
|
|
|
|
# Connected to websocket.disconnect
|
|
|
def ws_disconnect(message, id, code, plot):
|
|
|
Group('{}_{}'.format(code, plot)).discard(message.reply_channel)
|
|
|
|