summaryrefslogtreecommitdiff
path: root/ebus/model/sql.py
blob: de1323972f6cd8a876e125667f1f0c23de013490 (plain)
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
# -*- coding: utf-8 -*-
from datetime import datetime
from sqlalchemy import Column, Integer, Float, DateTime, String, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from ebus import model

ModelBase = declarative_base()

class Sensor(ModelBase):
    __tablename__ = 'sensor'
    
    id = Column(Integer, primary_key=True)
    name = Column(String)
    description = Column(String, default="")

    def __init__(self, name, description=""):
        self.name = name
        self.description = description
        
    def __repr__(self):
        return "<Sensor(id='%s',name='%s',description='%s')>" % (self.id, self.name, self.description)

# http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html#inheritance-configuration
class Value(ModelBase):
    __tablename__ = 'value'

    id = Column(Integer, primary_key=True)
    timestamp = Column(DateTime,index=True)
    sensor_id = Column(Integer, ForeignKey("sensor.id"))
    sensor = relationship(Sensor, backref=backref('values', order_by=timestamp))

    discriminator = Column('type', String(50))
    __mapper_args__ = {'polymorphic_on': discriminator}

    def __init__(self, sensor, timestamp=datetime.now()):
        self.timestamp = timestamp
        self.sensor  = sensor

    def __repr__(self):
        return "<Value(id='%s',sensor='%s',value='%s',timestamp='%s'>" % (
            self.id, self.sensor, self.value(), self.timestamp)

    def value(self):
        raise NotImplementedException()

class ValueFloat(Value):
    __mapper_args__ = {'polymorphic_identity': 'float'}
    value_float = Column(Float(precision=4))
    
    def __init__(self, sensor, value, timestamp=datetime.now()):
        Value.__init__(self, sensor, timestamp)
        self.value_float = value

    def value(self):
        return self.value_float

class ValueInt(Value):
    __mapper_args__ = {'polymorphic_identity': 'int'}
    value_int = Column(Integer)

    def __init__(self, sensor, value, timestamp=datetime.now()):
        Value.__init__(self, sensor, timestamp)
        self.value_int = value

    def value(self):
        return self.value_int

class ValueString(Value):
    __mapper_args__ = {'polymorphic_identity': 'string'}
    value_string = Column(String)

    def __init__(self, sensor, value, timestamp=datetime.now()):
        Value.__init__(self, sensor, timestamp)
        self.value_string = value

    def value(self):
        return self.value_string


class EbusSQL(object):
    def __init__(self,session):
        self.session = session

    def get_values(self,packet):
        packet_description = packet.get_packet_description()
        packet_source_name = packet.get_source_name()
        packet_name = packet.name()
        for field in packet_description.fields.iterchildren():
            try:
                name = field.get("name")
                offset = int(field.get("offset"))
                if not name:
                    continue

                sensor_name = "%s.%s.%s" % (packet_source_name, packet_name, name )
                sensor = self.session.query(Sensor) \
                    .filter(Sensor.name==sensor_name).first()
                if sensor is None:
                    sensor = Sensor(sensor_name)
                    self.session.add(sensor)

                if field.tag == "bit":
                    yield ValueInt(sensor, \
                                       model.Bit(name, offset).value(packet.data) and 1 or 0)
                elif field.tag == "byte":
                    yield ValueInt(sensor, \
                                       model.Byte(name, offset).value(packet.data))
                elif field.tag == "word":
                    yield ValueInt(sensor, \
                                       model.Word(name, offset).value(packet.data))
                elif field.tag == "data1b":
                    yield ValueInt(sensor, \
                                       model.Data1b(name, offset).value(packet.data))
                elif field.tag == "data1c":
                    yield ValueInt(sensor, \
                                       model.Data1c(name, offset).value(packet.data))
                elif field.tag == "data2b":
                    yield ValueInt(sensor, \
                                       model.Data2b(name, offset).value(packet.data))
                elif field.tag == "data2c":
                    yield ValueInt(sensor, 
                                   model.Data2c(name, offset).value(packet.data))
                elif field.tag == "bcd":
                    yield ValueString(sensor,
                                      model.Bcd(name, offset).value(packet.data))
                elif field.tag == "byteEnum":
                    options = dict(map(lambda opt: ( int(opt.get("value")[2:],16), opt.get("name")),
                                       field.xpath("./option")))
                    yield ValueString(sensor,
                                      model.ByteEnum(name, offset, options).value(packet.data))
                else:
                    print "Unsupported field-type %s" % (name)
            except Exception,e:
                print "skip",e