프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / DTI_PID / Shapes / EngineeringInstrumentItem.py @ a7d203dc

이력 | 보기 | 이력해설 | 다운로드 (12.6 KB)

1
# coding: utf-8
2
"""
3
This is Engineering Instrument Item module
4
"""
5

    
6
import sys
7
import os
8
import math
9
from PyQt5.QtGui import *
10
from PyQt5.QtCore import *
11
from PyQt5.QtSvg import *
12
from PyQt5.QtWidgets import (QApplication, QGraphicsItem)
13

    
14
from SymbolSvgItem import SymbolSvgItem
15
from EngineeringAbstractItem import QEngineeringAbstractItem
16
from EngineeringConnectorItem import QEngineeringConnectorItem
17
from EngineeringTextItem import QEngineeringTextItem
18
from UserInputAttribute import UserInputAttribute
19

    
20

    
21
class QEngineeringInstrumentItem(SymbolSvgItem):
22
    """ This is Engineering Instrument Item class """
23
    clicked = pyqtSignal(QGraphicsSvgItem)
24
    INST_COLUMN_LIST = None
25
    INST_COLOR = None
26

    
27
    '''
28
    '''
29

    
30
    def __init__(self, path, uid=None, flip=0):
31
        SymbolSvgItem.__init__(self, None, path, uid, flip=flip)
32

    
33
        self._measuredVairableCode = None
34
        self._typeModifier = None
35
        self._tagSeqNo = None
36
        self._tagSuffix = None
37

    
38
        if QEngineeringInstrumentItem.INST_COLUMN_LIST is None:
39
            from AppDocData import AppDocData
40

    
41
            appDocData = AppDocData.instance()
42
            QEngineeringInstrumentItem.INST_COLUMN_LIST = appDocData.getColNames('INSTRUMENT_DATA_LIST')
43

    
44
    '''
45
        @brief  getter of measured variable code
46
        @author humkyung
47
        @date   2018.05.06
48
    '''
49

    
50
    @property
51
    def measuredVariableCode(self):
52
        return self._measuredVairableCode
53

    
54
    '''
55
        @brief  setter of measured variable code
56
        @author humkyung
57
        @date   2018.05.06
58
    '''
59

    
60
    @measuredVariableCode.setter
61
    def measuredVariableCode(self, value):
62
        self._measuredVairableCode = value
63

    
64
    '''
65
        @brief  getter of type modifier
66
        @author humkyung
67
        @date   2018.05.06
68
    '''
69

    
70
    @property
71
    def typeModifier(self):
72
        return self._typeModifier
73

    
74
    '''
75
        @brief  setter of type modifier
76
        @author humkyung
77
        @date   2018.05.06
78
    '''
79

    
80
    @typeModifier.setter
81
    def typeModifier(self, value):
82
        self._typeModifier = value
83

    
84
    '''
85
        @brief  getter of tag seq no
86
        @author humkyung
87
        @date   2018.05.06
88
    '''
89

    
90
    @property
91
    def tagSeqNo(self):
92
        return self._tagSeqNo
93

    
94
    '''
95
        @brief  setter of tag seq no
96
        @author humkyung
97
        @date   2018.05.06
98
    '''
99

    
100
    @tagSeqNo.setter
101
    def tagSeqNo(self, value):
102
        self._tagSeqNo = value
103

    
104
    '''
105
        @brief  getter of tag suffix
106
        @author humkyung
107
        @date   2018.05.06
108
    '''
109

    
110
    @property
111
    def tagSuffix(self):
112
        return self._tagSuffix
113

    
114
    '''
115
        @brief  setter of tag suffix
116
        @author humkyung
117
        @date   2018.05.06
118
    '''
119

    
120
    @tagSuffix.setter
121
    def tagSuffix(self, value):
122
        self._tagSuffix = value
123

    
124
    def highlight(self, flag):
125
        """ highlight/unhighlight the instrument """
126

    
127
        try:
128
            self.hover = flag
129
            self.update()
130

    
131
            for assoc in self.associations():
132
                assoc.highlight(flag)
133

    
134
            for connector in self.connectors:
135
                connector.highlight(flag)
136
        except Exception as ex:
137
            from App import App
138
            from AppDocData import MessageType
139

    
140
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
141
                                                          sys.exc_info()[-1].tb_lineno)
142
            App.mainWnd().addMessage.emit(MessageType.Error, message)
143

    
144
    def getColor(self):
145
        """ return instrument's color 2019.04.24 adde by humkyung """
146
        from AppDocData import AppDocData
147
        from DisplayColors import DisplayColors
148
        from DisplayColors import DisplayOptions
149
        from EngineeringAbstractItem import QEngineeringAbstractItem
150
        from EngineeringLineItem import QEngineeringLineItem
151

    
152
        if DisplayOptions.DisplayByLineType == DisplayColors.instance().option:
153
            if self.hover:
154
                return SymbolSvgItem.HOVER_COLOR
155
            elif not QEngineeringInstrumentItem.INST_COLOR:
156
                app_doc_data = AppDocData.instance()
157
                configs = app_doc_data.getConfigs('Instrument', 'Color')
158
                QEngineeringInstrumentItem.INST_COLOR = configs[
159
                    0].value if configs else QEngineeringAbstractItem.DEFAULT_COLOR
160

    
161
            return QEngineeringInstrumentItem.INST_COLOR
162
        else:
163
            return SymbolSvgItem.getColor(self)
164

    
165
    '''
166
        @brief  connect attribute
167
        @author humkyung
168
        @date   2018.05.06
169
    '''
170

    
171
    def connectAttribute(self, attributes, clear=True):
172
        from AppDocData import AppDocData
173

    
174
        try:
175
            if clear:
176
                if not self.clear_attr_and_assoc_item():
177
                    return
178

    
179
            rect = self.sceneBoundingRect()
180

    
181
            minDist = None
182
            selected = None
183

    
184
            configs = AppDocData.instance().getConfigs('Range', 'Detection Ratio')
185
            ratio = float(configs[0].value) if 1 == len(configs) else 1.5
186

    
187
            dist = (self.sceneBoundingRect().height() + self.sceneBoundingRect().width()) * ratio / 2
188
            center = self.sceneBoundingRect().center()
189

    
190
            for attr in attributes:
191
                if issubclass(type(attr), QEngineeringTextItem):
192
                    if rect.contains(attr.center()):
193
                        if self.add_assoc_item(attr):
194
                            attr.owner = self  # set owner of text
195

    
196
                elif issubclass(type(attr), SymbolSvgItem):
197
                    dx = attr.center().x() - center.x()
198
                    dy = attr.center().y() - center.y()
199

    
200
                    offset = (attr.sceneBoundingRect().width() + attr.sceneBoundingRect().height()) / 4
201
                    length = math.sqrt(dx * dx + dy * dy) - offset
202

    
203
                    if (length < dist) and (minDist is None or length < minDist):
204
                        minDist = length
205
                        selected = attr
206

    
207
            if selected is not None:
208
                self.add_assoc_item(selected)
209

    
210
        except Exception as ex:
211
            from App import App
212
            from AppDocData import MessageType
213

    
214
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
215
                                                          sys.exc_info()[-1].tb_lineno)
216
            App.mainWnd().addMessage.emit(MessageType.Error, message)
217

    
218
    '''
219
        @brief  generate xml code for attribute
220
        @author humkyung
221
        @date   2018.05.06
222
    '''
223

    
224
    def toXmlAsAttribute(self, parentNode):
225
        from xml.etree.ElementTree import Element, SubElement, dump, ElementTree
226

    
227
        try:
228
            attrNode = Element('ATTRIBUTE')
229

    
230
            uidNode = Element('UID')
231
            uidNode.text = str(self.uid)
232
            attrNode.append(uidNode)
233

    
234
            nameNode = Element('NAME')
235
            nameNode.text = 'Measured Variable Code'
236
            attrNode.append(nameNode)
237

    
238
            valueNode = Element('VALUE')
239
            valueNode.text = self.measuredVariableCode
240
            attrNode.append(valueNode)
241

    
242
            parentNode.append(attrNode)
243
        except Exception as ex:
244
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
245
                                                      sys.exc_info()[-1].tb_lineno))
246

    
247
        try:
248
            attrNode = Element('ATTRIBUTE')
249

    
250
            uidNode = Element('UID')
251
            uidNode.text = str(self.uid)
252
            attrNode.append(uidNode)
253

    
254
            nameNode = Element('NAME')
255
            nameNode.text = 'Type Modifier'
256
            attrNode.append(nameNode)
257

    
258
            valueNode = Element('VALUE')
259
            valueNode.text = self.typeModifier
260
            attrNode.append(valueNode)
261

    
262
            parentNode.append(attrNode)
263
        except Exception as ex:
264
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
265
                                                      sys.exc_info()[-1].tb_lineno))
266

    
267
        try:
268
            attrNode = Element('ATTRIBUTE')
269

    
270
            uidNode = Element('UID')
271
            uidNode.text = str(self.uid)
272
            attrNode.append(uidNode)
273

    
274
            nameNode = Element('NAME')
275
            nameNode.text = 'Tag Seq No'
276
            attrNode.append(nameNode)
277

    
278
            valueNode = Element('VALUE')
279
            valueNode.text = self.tagSeqNo
280
            attrNode.append(valueNode)
281

    
282
            parentNode.append(attrNode)
283
        except Exception as ex:
284
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
285
                                                      sys.exc_info()[-1].tb_lineno))
286

    
287
        try:
288
            attrNode = Element('ATTRIBUTE')
289

    
290
            uidNode = Element('UID')
291
            uidNode.text = str(self.uid)
292
            attrNode.append(uidNode)
293

    
294
            nameNode = Element('NAME')
295
            nameNode.text = 'Tag Suffix'
296
            attrNode.append(nameNode)
297

    
298
            valueNode = Element('VALUE')
299
            valueNode.text = self.tagSuffix
300
            attrNode.append(valueNode)
301

    
302
            parentNode.append(attrNode)
303
        except Exception as ex:
304
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
305
                                                      sys.exc_info()[-1].tb_lineno))
306

    
307
    def toSql_return_separately(self):
308
        """ convert instrument data to sql query """
309
        import uuid
310
        from AppDocData import AppDocData
311

    
312
        res = []
313
        resLater = []
314

    
315
        res.append(self.toSql_Components())
316

    
317
        _attrs = self.getAttributes()
318
        if _attrs:
319
            cols = ['UID', 'Components_UID', 'SymbolAttribute_UID', 'Value']
320
            values = ['?', '?', '?', '?']
321
            params = []
322
            for key in _attrs.keys():
323
                params.append((str(uuid.uuid4()), str(self.uid), str(key.UID), str(_attrs[key])))
324
            sql = 'insert into Attributes({}) values({})'.format(','.join(cols), ','.join(values))
325
            res.append((sql, tuple(params)))
326

    
327
        if self.associations():
328
            cols = ['UID', '[Type]', 'Components_UID', 'Association']
329
            values = ['?', '?', '?', '?']
330
            params = []
331
            for assoc in self.associations():
332
                params.append(
333
                    (str(uuid.uuid4()), QEngineeringAbstractItem.assoc_type(assoc), str(self.uid), str(assoc.uid)))
334
            sql = 'insert into Associations({}) values({})'.format(','.join(cols), ','.join(values))
335
            resLater.append((sql, tuple(params)))
336

    
337
        # save connectors to database
338
        if self.connectors:
339
            cols = ['Components_UID', '[Index]', 'X', 'Y', 'Connected', 'Connected_At']
340
            values = ['?', '?', '?', '?', '?', '?']
341
            params = []
342
            index = 1
343
            for connector in self.connectors:
344
                params.append( \
345
                    (  # str(connector.uid),
346
                        str(self.uid), index, connector.connectPoint[0], connector.connectPoint[1], \
347
                        str(connector.connectedItem.uid) if connector.connectedItem else None, \
348
                        str(connector._connected_at)) \
349
                    )
350
                index += 1
351
            sql = 'insert into Points({}) values({})'.format(','.join(cols), ','.join(values))
352
            resLater.append((sql, tuple(params)))
353
        # up to here
354

    
355
        return res, resLater
356

    
357
    '''
358
        @brief      return inst Data List
359
        @author     kyouho
360
        @date       2018.08.14
361
    '''
362

    
363
    def getInstrumentDataList(self):
364
        dataList = []
365
        try:
366
            from AppDocData import AppDocData
367

    
368
            docData = AppDocData.instance()
369
            attrs = self.getAttributes()
370

    
371
            for index in range(len(QEngineeringInstrumentItem.INST_COLUMN_LIST)):
372
                dataList.append('')
373

    
374
            dataList[0] = str(self.uid)
375
            dataList[13] = docData.imgName
376

    
377
            for key in attrs.keys():
378
                attrInfo = docData.getSymbolAttributeByUID(key.UID)
379
                attrName = attrInfo.Attribute
380
                if attrName in QEngineeringInstrumentItem.INST_COLUMN_LIST:
381
                    colIndex = QEngineeringInstrumentItem.INST_COLUMN_LIST.index(attrName)
382
                    dataList[colIndex] = attrs[key]
383
        except Exception as ex:
384
            from App import App
385
            from AppDocData import MessageType
386

    
387
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
388
                                                          sys.exc_info()[-1].tb_lineno)
389
            App.mainWnd().addMessage.emit(MessageType.Error, message)
390

    
391
        return dataList
클립보드 이미지 추가 (최대 크기: 500 MB)