Snippets
Created by
Ilnur Ibragimov
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | # -*- coding: utf-8 -*-
from mx.DateTime import DateTimeFrom
from functools import partial
from receiver.protocols import generic
from core.models import Mark
from utils.web import HTTPConnection, Application, RequestHandler
from tornado import template
from core.logger import get_logger
from core.constants import MAX_SENSOR_INDEX
import xml.etree.cElementTree as ET
ignore_exceptions = []
class ProtocolHandler(generic.ProtocolHandler):
'''
BN-Complex protocol handler
'''
def __init__(self, stream, address=None, redis_cl=None, DEBUG=False, receiver=None, stream_close_callback=None, device_dict=None, **kwargs):
self.stream = stream
self.io_loop = stream.io_loop
self.address = address
self.receiver = receiver
self.device_list = receiver.device_list
self.close_callback = stream_close_callback
self.device_dict = device_dict
self.redis_cl = redis_cl
self.DEBUG = DEBUG
self.in_a = {}
self.in_d = {}
self.device_id = None
self.logger = get_logger(__name__, ignore_exceptions)
def start(self):
self.http_connection = HTTPConnection(self.stream, self.address, application,
extra={'receiver': self.receiver, 'handler': self}, xheaders=True)
def stop(self):
self.stream.close()
return
def datetime_to_kml(source):
dt = source
if dt.year <= 1900:
return '1970-01-01T00:00:00Z'
return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
def parse_field(field, mark_dict):
tag = field.tag
attrs = field.attrib
text = field.text
if tag == 'ObjectID':
mark_dict['device_id'] = int(text)
mark_dict['device_id_original'] = text
elif tag == 'Coord':
mark_dict['datetime'] = int(DateTimeFrom(attrs['time']).gmticks())
mark_dict['datetime_original'] = attrs['time']
mark_dict['point'] = {
'latitude': float(attrs['lat']),
'longitude': float(attrs['lon'])
}
mark_dict['azimuth'] = float(attrs['dir'])
mark_dict['is_valid'] = bool(int(attrs['valid']))
mark_dict['speed'] = float(attrs['speed'])
mark_dict['hdop'] = int(attrs.get('hdop', 1))
mark_dict['satcount'] = int(attrs.get('satcount', 10))
mark_dict['altitude'] = int(float(attrs.get('alt', 0)))
elif tag == 'DigI':
inpnum = attrs.get('inpnum')
try:
inpnum = int(inpnum)
except:
inpnum = None
if inpnum is not None:
mark_dict['in_d'][inpnum] = 1
elif tag == 'AnalogI':
num = attrs.get('num')
val = attrs.get('val')
try:
num = int(num)
except:
num = None
try:
val = float(val)
except:
val = None
if num is not None:
mark_dict['in_a'][num] = val
response_tmpl = template.Template(
'''<?xml version="1.0" encoding="windows-1251"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope" xmlns:ws="http://ws">
<soapenv:Header/>
<soapenv:Body>
{% for m in marks %}
<ws:PutCoordResponce>
<ObjectID>{{ m['device_id_original'] }}</ObjectID>
<Coord time="{{ m['datetime_original'] }}"/>
{% for i in m['in_d'] %}
<DigI inpnum="{{ i }}"/>
{% end %}
{% for i in m['in_a'] %}
<AnalogI num="{{ i }}" val="{{ m['in_a'][i] }}"/>
{% end %}
</ws:PutCoordResponce>
{% end %}
</soapenv:Body>
</soapenv:Envelope>
''')
# Envelope.Body.Fault.Reason.Text
error_tmpl = template.Template(
'''<?xml version="1.0" encoding="windows-1251"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope" xmlns:ws="http://ws">
<soapenv:Header/>
<soapenv:Body>
<Fault>
<Reason>
<Text>{{ error_text }}</Text>
</Reason>
</Fault>
</soapenv:Body>
</soapenv:Envelope>
''')
class MainHandler(RequestHandler):
def prepare(self):
self.redis = self.application._extra['receiver'].redis
self.handler = self.application._extra['handler']
def on_finish(self):
self.handler.close_callback()
def post(self):
self.set_header('Server', 'Microsoft-IIS/7.5')
RNIC_PREFIX = self.request.headers.get('X-RNIC-PREFIX')
if not RNIC_PREFIX:
response = error_tmpl.generate(error_text='RNIC prefix not found')
self.write(response)
return
ALWAYS_SEND_ACK = self.request.headers.get('X-ALWAYS-SEND-ACK') == '1'
PROJECT_MARKS_FILTER = self.request.headers.get('X-PROJECT-MARKS-FILTER', '')
filtered_list = filter(lambda x: not x[3] and x[2].startswith(RNIC_PREFIX), self.handler.device_list)
device_map = {str(dev[2]).lstrip('0'): dev[0] for dev in filtered_list}
device_map.update({str(dev[1]).lstrip('0'): dev[0] for dev in filtered_list})
try:
new_header = u'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope" xmlns:ws="http://ws">'
# удаляем заголовок xml текста
text = u'%s%s' % (new_header, self.request.body[self.request.body.index('<soapenv:Body'):])
tree = ET.fromstring(text)
body = tree.find('./{http://schemas.xmlsoap.org/soap/envelope}Body')
marks = []
for message in body:
MARK_FOUND = False
PROJECT_MARK = True
mark_dict = {'in_d': {}, 'in_a': {}}
for field in message:
parse_field(field, mark_dict)
m = Mark.from_dict(mark_dict)
m.datetime = mark_dict['datetime']
if m.device_id and m.datetime and self.handler.on_mark_callback:
sn = m.device_id
try:
m.device_id = device_map[str(sn)]
MARK_FOUND = True
except KeyError:
if self.handler.on_unknown_device_callback:
self.handler.io_loop.add_callback(partial(self.handler.on_unknown_device_callback, str(sn)))
if not ALWAYS_SEND_ACK:
continue
marks.append(mark_dict)
# sensor handling stuff. in_d is zero (inactive) if nothing is transmitted
self.handler.in_a = mark_dict['in_a'].copy()
self.handler.in_d = mark_dict['in_d'].copy()
# we have MAX_SENSOR_INDEX pins, they may start with 1 or 0
for i in range(MAX_SENSOR_INDEX+1):
if i not in self.handler.in_d:
self.handler.in_d[i] = 0
if MARK_FOUND:
if PROJECT_MARKS_FILTER:
PROJECT_MARK = not mark_dict['device_id_original'].startswith(PROJECT_MARKS_FILTER)
self.handler.device_id = m.device_id
self.handler.io_loop.add_callback(
partial(
self.handler.on_mark_callback,
m,
prefix=RNIC_PREFIX,
project_mark=PROJECT_MARK))
self.handler.process_inputs(m.datetime)
self.handler.process_alarm_button(m.datetime)
except Exception as e:
response = error_tmpl.generate(error_text=str(e))
self.write(response)
return
response = response_tmpl.generate(datetime_to_kml=datetime_to_kml, marks=marks)
self.write(response)
handlers = [
(r'/', MainHandler)
]
application = Application(handlers)
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.