datasource.py 33.6 KB
Newer Older
nengyuangzhang's avatar
nengyuangzhang 已提交
1 2 3 4 5
import uuid
from datetime import datetime, timezone, timedelta
import falcon
import mysql.connector
import simplejson as json
L
LLLkui 已提交
6
from core.useractivity import user_logger, admin_control
7
import config
U
unknown 已提交
8
from decimal import Decimal
nengyuangzhang's avatar
nengyuangzhang 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22


class DataSourceCollection:
    @staticmethod
    def __init__():
        """"Initializes DataSourceCollection"""
        pass

    @staticmethod
    def on_options(req, resp):
        resp.status = falcon.HTTP_200

    @staticmethod
    def on_get(req, resp):
L
LLLkui 已提交
23
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37
        cnx = mysql.connector.connect(**config.myems_system_db)
        cursor = cnx.cursor()

        query = (" SELECT id, name, uuid "
                 " FROM tbl_gateways ")
        cursor.execute(query)
        rows_gateways = cursor.fetchall()
        gateway_dict = dict()
        if rows_gateways is not None and len(rows_gateways) > 0:
            for row in rows_gateways:
                gateway_dict[row[0]] = {"id": row[0],
                                        "name": row[1],
                                        "uuid": row[2]}

38
        query = (" SELECT id, name, uuid, gateway_id, protocol, connection, last_seen_datetime_utc, description "
nengyuangzhang's avatar
nengyuangzhang 已提交
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
                 " FROM tbl_data_sources "
                 " ORDER BY id ")
        cursor.execute(query)
        rows = cursor.fetchall()
        cursor.close()
        cnx.close()

        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
        if config.utc_offset[0] == '-':
            timezone_offset = -timezone_offset

        result = list()
        if rows is not None and len(rows) > 0:
            for row in rows:
                if isinstance(row[6], datetime):
                    last_seen_datetime_local = row[6].replace(tzinfo=timezone.utc) + timedelta(minutes=timezone_offset)
                    last_seen_datetime = last_seen_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
                else:
                    last_seen_datetime = None
                meta_result = {"id": row[0],
                               "name": row[1],
                               "uuid": row[2],
                               "gateway": gateway_dict.get(row[3]),
                               "protocol": row[4],
                               "connection": row[5],
64 65
                               "last_seen_datetime": last_seen_datetime,
                               "description": row[7]
nengyuangzhang's avatar
nengyuangzhang 已提交
66 67 68 69 70 71 72 73 74 75
                               }

                result.append(meta_result)

        resp.text = json.dumps(result)

    @staticmethod
    @user_logger
    def on_post(req, resp):
        """Handles POST requests"""
L
LLLkui 已提交
76
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
77 78 79
        try:
            raw_json = req.stream.read().decode('utf-8')
        except Exception as ex:
80 81 82
            raise falcon.HTTPError(status=falcon.HTTP_400,
                                   title='API.BAD_REQUEST',
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
nengyuangzhang's avatar
nengyuangzhang 已提交
83 84 85 86 87 88

        new_values = json.loads(raw_json)

        if 'name' not in new_values['data'].keys() or \
                not isinstance(new_values['data']['name'], str) or \
                len(str.strip(new_values['data']['name'])) == 0:
89
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
90 91 92 93 94 95
                                   description='API.INVALID_DATA_SOURCE_NAME')
        name = str.strip(new_values['data']['name'])

        if 'gateway_id' not in new_values['data'].keys() or \
                not isinstance(new_values['data']['gateway_id'], int) or \
                new_values['data']['gateway_id'] <= 0:
96
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
97 98 99 100 101
                                   description='API.INVALID_GATEWAY_ID')
        gateway_id = new_values['data']['gateway_id']

        if 'protocol' not in new_values['data'].keys() \
                or new_values['data']['protocol'] not in \
102 103 104
                ('bacnet-ip',
                 'cassandra',
                 'clickhouse',
105
                 'coap',
106 107
                 'controllogix',
                 'dlt645',
108
                 'elexon-bmrs',
109 110 111
                 'iec104',
                 'influxdb',
                 'lora',
nengyuangzhang's avatar
nengyuangzhang 已提交
112
                 'modbus-rtu',
113 114
                 'modbus-tcp',
                 'mongodb',
115
                 'mqtt-acrel',
nengyuangzhang's avatar
nengyuangzhang 已提交
116
                 'mqtt-adw300',
117
                 'mqtt-huiju',
118 119
                 'mqtt-md4220',
                 'mqtt-seg',
nengyuangzhang's avatar
nengyuangzhang 已提交
120
                 'mqtt-weilan',
121 122 123 124 125
                 'mqtt',
                 'mysql',
                 'opc-ua',
                 'oracle',
                 'postgresql',
nengyuangzhang's avatar
nengyuangzhang 已提交
126 127
                 'profibus',
                 'profinet',
128
                 's7',
nengyuangzhang's avatar
nengyuangzhang 已提交
129 130
                 'simulation',
                 'sqlserver',
131 132
                 'tdengine',
                 'weather',):
133
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
134 135 136 137 138 139
                                   description='API.INVALID_DATA_SOURCE_PROTOCOL')
        protocol = new_values['data']['protocol']

        if 'connection' not in new_values['data'].keys() or \
                not isinstance(new_values['data']['connection'], str) or \
                len(str.strip(new_values['data']['connection'])) == 0:
140
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
141 142 143
                                   description='API.INVALID_CONNECTION')
        connection = str.strip(new_values['data']['connection'])

144 145 146 147 148 149 150
        if 'description' in new_values['data'].keys() and \
                new_values['data']['description'] is not None and \
                len(str(new_values['data']['description'])) > 0:
            description = str.strip(new_values['data']['description'])
        else:
            description = None

nengyuangzhang's avatar
nengyuangzhang 已提交
151 152 153 154 155 156 157 158 159
        cnx = mysql.connector.connect(**config.myems_system_db)
        cursor = cnx.cursor()

        cursor.execute(" SELECT name "
                       " FROM tbl_data_sources "
                       " WHERE name = %s ", (name,))
        if cursor.fetchone() is not None:
            cursor.close()
            cnx.close()
160
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
161 162 163 164 165 166 167 168
                                   description='API.DATA_SOURCE_NAME_IS_ALREADY_IN_USE')

        cursor.execute(" SELECT name "
                       " FROM tbl_gateways "
                       " WHERE id = %s ", (gateway_id,))
        if cursor.fetchone() is None:
            cursor.close()
            cnx.close()
169
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
170 171
                                   description='API.INVALID_GATEWAY_ID')

172 173
        add_values = (" INSERT INTO tbl_data_sources (name, uuid, gateway_id, protocol, connection, description) "
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
nengyuangzhang's avatar
nengyuangzhang 已提交
174 175 176 177
        cursor.execute(add_values, (name,
                                    str(uuid.uuid4()),
                                    gateway_id,
                                    protocol,
178 179
                                    connection,
                                    description))
nengyuangzhang's avatar
nengyuangzhang 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        new_id = cursor.lastrowid
        cnx.commit()
        cursor.close()
        cnx.close()

        resp.status = falcon.HTTP_201
        resp.location = '/datasources/' + str(new_id)


class DataSourceItem:
    @staticmethod
    def __init__():
        """"Initializes DataSourceItem"""
        pass

    @staticmethod
    def on_options(req, resp, id_):
        resp.status = falcon.HTTP_200

    @staticmethod
    def on_get(req, resp, id_):
L
LLLkui 已提交
201
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
202
        if not id_.isdigit() or int(id_) <= 0:
203
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
                                   description='API.INVALID_DATA_SOURCE_ID')

        cnx = mysql.connector.connect(**config.myems_system_db)
        cursor = cnx.cursor()

        query = (" SELECT id, name, uuid "
                 " FROM tbl_gateways ")
        cursor.execute(query)
        rows_gateways = cursor.fetchall()
        gateway_dict = dict()
        if rows_gateways is not None and len(rows_gateways) > 0:
            for row in rows_gateways:
                gateway_dict[row[0]] = {"id": row[0],
                                        "name": row[1],
                                        "uuid": row[2]}

220
        query = (" SELECT id, name, uuid, gateway_id, protocol, connection, last_seen_datetime_utc, description "
nengyuangzhang's avatar
nengyuangzhang 已提交
221 222 223 224 225 226 227
                 " FROM tbl_data_sources "
                 " WHERE id = %s ")
        cursor.execute(query, (id_,))
        row = cursor.fetchone()
        cursor.close()
        cnx.close()
        if row is None:
228
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
nengyuangzhang's avatar
nengyuangzhang 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
                                   description='API.DATA_SOURCE_NOT_FOUND')

        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
        if config.utc_offset[0] == '-':
            timezone_offset = -timezone_offset

        if isinstance(row[6], datetime):
            last_seen_datetime_local = row[6].replace(tzinfo=timezone.utc) + \
                timedelta(minutes=timezone_offset)
            last_seen_datetime = last_seen_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
        else:
            last_seen_datetime = None

        result = {"id": row[0],
                  "name": row[1],
                  "uuid": row[2],
                  "gateway": gateway_dict.get(row[3]),
                  "protocol": row[4],
                  "connection": row[5],
248 249
                  "last_seen_datetime": last_seen_datetime,
                  "description": row[7]
nengyuangzhang's avatar
nengyuangzhang 已提交
250 251 252 253 254 255 256
                  }

        resp.text = json.dumps(result)

    @staticmethod
    @user_logger
    def on_delete(req, resp, id_):
L
LLLkui 已提交
257
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
258
        if not id_.isdigit() or int(id_) <= 0:
259
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
260 261 262 263 264 265 266 267 268 269 270
                                   description='API.INVALID_DATA_SOURCE_ID')

        cnx = mysql.connector.connect(**config.myems_system_db)
        cursor = cnx.cursor()

        cursor.execute(" SELECT name "
                       " FROM tbl_data_sources "
                       " WHERE id = %s ", (id_,))
        if cursor.fetchone() is None:
            cursor.close()
            cnx.close()
271
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
nengyuangzhang's avatar
nengyuangzhang 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284
                                   description='API.DATA_SOURCE_NOT_FOUND')

        # check if this data source is being used by any meters
        cursor.execute(" SELECT DISTINCT(m.name) "
                       " FROM tbl_meters m, tbl_meters_points mp, tbl_points p, tbl_data_sources ds "
                       " WHERE m.id = mp.meter_id AND mp.point_id = p.id AND p.data_source_id = ds.id "
                       "       AND ds.id = %s "
                       " LIMIT 1 ",
                       (id_,))
        row_meter = cursor.fetchone()
        if row_meter is not None:
            cursor.close()
            cnx.close()
285
            raise falcon.HTTPError(status=falcon.HTTP_400,
nengyuangzhang's avatar
nengyuangzhang 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
                                   title='API.BAD_REQUEST',
                                   description='API.THIS_DATA_SOURCE_IS_BEING_USED_BY_A_METER' + row_meter[0])

        cursor.execute(" DELETE FROM tbl_points WHERE data_source_id = %s ", (id_,))
        cursor.execute(" DELETE FROM tbl_data_sources WHERE id = %s ", (id_,))
        cnx.commit()

        cursor.close()
        cnx.close()
        resp.status = falcon.HTTP_204

    @staticmethod
    @user_logger
    def on_put(req, resp, id_):
        """Handles PUT requests"""
L
LLLkui 已提交
301
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
302 303 304
        try:
            raw_json = req.stream.read().decode('utf-8')
        except Exception as ex:
305 306 307
            raise falcon.HTTPError(status=falcon.HTTP_400,
                                   title='API.BAD_REQUEST',
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
nengyuangzhang's avatar
nengyuangzhang 已提交
308 309

        if not id_.isdigit() or int(id_) <= 0:
310
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
311 312 313 314 315 316 317
                                   description='API.INVALID_DATA_SOURCE_ID')

        new_values = json.loads(raw_json)

        if 'name' not in new_values['data'].keys() or \
                not isinstance(new_values['data']['name'], str) or \
                len(str.strip(new_values['data']['name'])) == 0:
318
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
319 320 321 322 323 324
                                   description='API.INVALID_DATA_SOURCE_NAME')
        name = str.strip(new_values['data']['name'])

        if 'gateway_id' not in new_values['data'].keys() or \
                not isinstance(new_values['data']['gateway_id'], int) or \
                new_values['data']['gateway_id'] <= 0:
325
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
326 327 328 329 330
                                   description='API.INVALID_GATEWAY_ID')
        gateway_id = new_values['data']['gateway_id']

        if 'protocol' not in new_values['data'].keys() \
                or new_values['data']['protocol'] not in \
331 332 333
                ('bacnet-ip',
                 'cassandra',
                 'clickhouse',
334
                 'coap',
335 336
                 'controllogix',
                 'dlt645',
337
                 'elexon-bmrs',
338 339 340
                 'iec104',
                 'influxdb',
                 'lora',
nengyuangzhang's avatar
nengyuangzhang 已提交
341
                 'modbus-rtu',
342 343
                 'modbus-tcp',
                 'mongodb',
344
                 'mqtt-acrel',
nengyuangzhang's avatar
nengyuangzhang 已提交
345
                 'mqtt-adw300',
346
                 'mqtt-huiju',
347 348
                 'mqtt-md4220',
                 'mqtt-seg',
nengyuangzhang's avatar
nengyuangzhang 已提交
349
                 'mqtt-weilan',
350 351 352 353 354
                 'mqtt',
                 'mysql',
                 'opc-ua',
                 'oracle',
                 'postgresql',
nengyuangzhang's avatar
nengyuangzhang 已提交
355 356
                 'profibus',
                 'profinet',
357
                 's7',
nengyuangzhang's avatar
nengyuangzhang 已提交
358 359
                 'simulation',
                 'sqlserver',
360 361
                 'tdengine',
                 'weather',):
362
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
363 364 365 366 367 368
                                   description='API.INVALID_DATA_SOURCE_PROTOCOL')
        protocol = new_values['data']['protocol']

        if 'connection' not in new_values['data'].keys() or \
                not isinstance(new_values['data']['connection'], str) or \
                len(str.strip(new_values['data']['connection'])) == 0:
369
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
370 371 372
                                   description='API.INVALID_CONNECTION')
        connection = str.strip(new_values['data']['connection'])

373 374 375 376 377 378 379
        if 'description' in new_values['data'].keys() and \
                new_values['data']['description'] is not None and \
                len(str(new_values['data']['description'])) > 0:
            description = str.strip(new_values['data']['description'])
        else:
            description = None

nengyuangzhang's avatar
nengyuangzhang 已提交
380 381 382 383 384 385 386 387 388
        cnx = mysql.connector.connect(**config.myems_system_db)
        cursor = cnx.cursor()

        cursor.execute(" SELECT name "
                       " FROM tbl_data_sources "
                       " WHERE id = %s ", (id_,))
        if cursor.fetchone() is None:
            cursor.close()
            cnx.close()
389
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
nengyuangzhang's avatar
nengyuangzhang 已提交
390 391 392 393 394 395 396 397
                                   description='API.DATA_SOURCE_NOT_FOUND')

        cursor.execute(" SELECT name "
                       " FROM tbl_gateways "
                       " WHERE id = %s ", (gateway_id,))
        if cursor.fetchone() is None:
            cursor.close()
            cnx.close()
398
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
399 400 401
                                   description='API.INVALID_GATEWAY_ID')

        update_row = (" UPDATE tbl_data_sources "
402
                      " SET name = %s, gateway_id = %s, protocol = %s, connection = %s, description = %s "
nengyuangzhang's avatar
nengyuangzhang 已提交
403 404 405 406 407
                      " WHERE id = %s ")
        cursor.execute(update_row, (name,
                                    gateway_id,
                                    protocol,
                                    connection,
408
                                    description,
nengyuangzhang's avatar
nengyuangzhang 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
                                    id_,))
        cnx.commit()

        cursor.close()
        cnx.close()

        resp.status = falcon.HTTP_200


class DataSourcePointCollection:
    @staticmethod
    def __init__():
        """"Initializes DataSourcePointCollection"""
        pass

    @staticmethod
    def on_options(req, resp):
        resp.status = falcon.HTTP_200

    @staticmethod
    def on_get(req, resp, id_):
L
LLLkui 已提交
430
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
431
        if not id_.isdigit() or int(id_) <= 0:
432
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
433 434 435 436 437 438 439 440 441 442 443
                                   description='API.INVALID_DATA_SOURCE_ID')

        cnx = mysql.connector.connect(**config.myems_system_db)
        cursor = cnx.cursor()

        cursor.execute(" SELECT name "
                       " FROM tbl_data_sources "
                       " WHERE id = %s ", (id_,))
        if cursor.fetchone() is None:
            cursor.close()
            cnx.close()
444
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
nengyuangzhang's avatar
nengyuangzhang 已提交
445 446 447 448 449 450
                                   description='API.DATA_SOURCE_NOT_FOUND')

        result = list()
        # Get points of the data source
        # NOTE: there is no uuid in tbl_points
        query_point = (" SELECT id, name, object_type, "
451 452
                       "        units, high_limit, low_limit, higher_limit, lower_limit, ratio, "
                       "        is_trend, is_virtual, address, description "
nengyuangzhang's avatar
nengyuangzhang 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466
                       " FROM tbl_points "
                       " WHERE data_source_id = %s "
                       " ORDER BY id ")
        cursor.execute(query_point, (id_,))
        rows_point = cursor.fetchall()

        if rows_point is not None and len(rows_point) > 0:
            for row in rows_point:
                meta_result = {"id": row[0],
                               "name": row[1],
                               "object_type": row[2],
                               "units": row[3],
                               "high_limit": row[4],
                               "low_limit": row[5],
467 468 469 470 471 472 473
                               "higher_limit": row[6],
                               "lower_limit": row[7],
                               "ratio": float(row[8]),
                               "is_trend": bool(row[9]),
                               "is_virtual": bool(row[10]),
                               "address": row[11],
                               "description": row[12]}
nengyuangzhang's avatar
nengyuangzhang 已提交
474 475 476 477 478
                result.append(meta_result)

        cursor.close()
        cnx.close()
        resp.text = json.dumps(result)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531


class DataSourceExport:
    @staticmethod
    def __init__():
        """"Initializes DataSourceExport"""
        pass

    @staticmethod
    def on_options(req, resp, id_):
        resp.status = falcon.HTTP_200

    @staticmethod
    def on_get(req, resp, id_):
        admin_control(req)
        if not id_.isdigit() or int(id_) <= 0:
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
                                   description='API.INVALID_DATA_SOURCE_ID')

        cnx = mysql.connector.connect(**config.myems_system_db)
        cursor = cnx.cursor()

        query = (" SELECT id, name, uuid "
                 " FROM tbl_gateways ")
        cursor.execute(query)
        rows_gateways = cursor.fetchall()
        gateway_dict = dict()
        if rows_gateways is not None and len(rows_gateways) > 0:
            for row in rows_gateways:
                gateway_dict[row[0]] = {"id": row[0],
                                        "name": row[1],
                                        "uuid": row[2]}

        query = (" SELECT id, name, uuid, gateway_id, protocol, connection, last_seen_datetime_utc, description "
                 " FROM tbl_data_sources "
                 " WHERE id = %s ")
        cursor.execute(query, (id_,))
        row = cursor.fetchone()
        if row is None:
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
                                   description='API.DATA_SOURCE_NOT_FOUND')

        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
        if config.utc_offset[0] == '-':
            timezone_offset = -timezone_offset

        if isinstance(row[6], datetime):
            last_seen_datetime_local = row[6].replace(tzinfo=timezone.utc) + \
                                       timedelta(minutes=timezone_offset)
            last_seen_datetime = last_seen_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
        else:
            last_seen_datetime = None

532
        result = {"name": row[1],
533 534 535 536 537
                  "uuid": row[2],
                  "gateway": gateway_dict.get(row[3]),
                  "protocol": row[4],
                  "connection": row[5],
                  "last_seen_datetime": last_seen_datetime,
U
unknown 已提交
538 539
                  "description": row[7],
                  "points": None
540
                  }
U
unknown 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
        point_result = list()
        # Get points of the data source
        # NOTE: there is no uuid in tbl_points
        query_point = (" SELECT id, name, object_type, "
                       "        units, high_limit, low_limit, higher_limit, lower_limit, ratio, "
                       "        is_trend, is_virtual, address, description "
                       " FROM tbl_points "
                       " WHERE data_source_id = %s "
                       " ORDER BY id ")
        cursor.execute(query_point, (id_,))
        rows_point = cursor.fetchall()

        if rows_point is not None and len(rows_point) > 0:
            for row in rows_point:
                meta_result = {"id": row[0],
                               "name": row[1],
                               "object_type": row[2],
                               "units": row[3],
                               "high_limit": row[4],
                               "low_limit": row[5],
                               "higher_limit": row[6],
                               "lower_limit": row[7],
U
unknown 已提交
563
                               "ratio": Decimal(row[8]),
U
unknown 已提交
564 565 566 567 568 569 570 571
                               "is_trend": bool(row[9]),
                               "is_virtual": bool(row[10]),
                               "address": row[11],
                               "description": row[12]}
                point_result.append(meta_result)
            result['points'] = point_result
        cursor.close()
        cnx.close()
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591

        resp.text = json.dumps(result)


class DataSourceImport:
    @staticmethod
    def __init__():
        """"Initializes DataSourceImport"""
        pass

    @staticmethod
    def on_options(req, resp):
        resp.status = falcon.HTTP_200

    @staticmethod
    @user_logger
    def on_post(req, resp):
        """Handles POST requests"""
        admin_control(req)
        try:
592
            raw_json = req.stream.read().decode('utf-8')
593 594 595 596 597 598
        except Exception as ex:
            raise falcon.HTTPError(status=falcon.HTTP_400,
                                   title='API.BAD_REQUEST',
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')

        new_values = json.loads(raw_json)
599

600 601 602 603 604
        if 'name' not in new_values.keys() or \
                not isinstance(new_values['name'], str) or \
                len(str.strip(new_values['name'])) == 0:
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
                                   description='API.INVALID_DATA_SOURCE_NAME')
605
        name = str.strip(new_values['name'])
606 607 608 609 610 611 612 613

        if 'gateway' not in new_values.keys() or \
                'id' not in new_values['gateway'].keys() or \
                not isinstance(new_values['gateway']['id'], int) or \
                new_values['gateway']['id'] <= 0:
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
                                   description='API.INVALID_GATEWAY_ID')
        gateway_id = new_values['gateway']['id']
614

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
        if 'protocol' not in new_values.keys() \
                or new_values['protocol'] not in \
                ('bacnet-ip',
                 'cassandra',
                 'clickhouse',
                 'coap',
                 'controllogix',
                 'dlt645',
                 'elexon-bmrs',
                 'iec104',
                 'influxdb',
                 'lora',
                 'modbus-rtu',
                 'modbus-tcp',
                 'mongodb',
630
                 'mqtt-acrel',
nengyuangzhang's avatar
nengyuangzhang 已提交
631
                 'mqtt-adw300',
632
                 'mqtt-huiju',
633 634
                 'mqtt-md4220',
                 'mqtt-seg',
nengyuangzhang's avatar
nengyuangzhang 已提交
635
                 'mqtt-weilan',
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
                 'mqtt',
                 'mysql',
                 'opc-ua',
                 'oracle',
                 'postgresql',
                 'profibus',
                 'profinet',
                 's7',
                 'simulation',
                 'sqlserver',
                 'tdengine',
                 'weather',):
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
                                   description='API.INVALID_DATA_SOURCE_PROTOCOL')
        protocol = new_values['protocol']

        if 'connection' not in new_values.keys() or \
                not isinstance(new_values['connection'], str) or \
                len(str.strip(new_values['connection'])) == 0:
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
                                   description='API.INVALID_CONNECTION')
        connection = str.strip(new_values['connection'])

        if 'description' in new_values.keys() and \
                new_values['description'] is not None and \
                len(str(new_values['description'])) > 0:
            description = str.strip(new_values['description'])
        else:
            description = None

        cnx = mysql.connector.connect(**config.myems_system_db)
        cursor = cnx.cursor()

        cursor.execute(" SELECT name "
                       " FROM tbl_data_sources "
                       " WHERE name = %s ", (name,))
        if cursor.fetchone() is not None:
            cursor.close()
            cnx.close()
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
                                   description='API.DATA_SOURCE_NAME_IS_ALREADY_IN_USE')

        cursor.execute(" SELECT name "
                       " FROM tbl_gateways "
                       " WHERE id = %s ", (gateway_id,))
        if cursor.fetchone() is None:
            cursor.close()
            cnx.close()
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
                                   description='API.INVALID_GATEWAY_ID')
686

687 688 689 690 691 692 693 694 695
        add_values = (" INSERT INTO tbl_data_sources (name, uuid, gateway_id, protocol, connection, description) "
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
        cursor.execute(add_values, (name,
                                    str(uuid.uuid4()),
                                    gateway_id,
                                    protocol,
                                    connection,
                                    description))
        new_id = cursor.lastrowid
696 697 698
        if new_values['points'] is not None and len(new_values['points']) > 0:
            for point in new_values['points']:
                # todo: validate point properties
U
unknown 已提交
699 700 701 702
                add_value = (" INSERT INTO tbl_points (name, data_source_id, object_type, units, "
                             "                         high_limit, low_limit, higher_limit, lower_limit, ratio, "
                             "                         is_trend, is_virtual, address, description) "
                             " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
703
                cursor.execute(add_value, (point['name'],
U
unknown 已提交
704
                                           new_id,
705 706 707 708 709 710 711 712 713 714 715
                                           point['object_type'],
                                           point['units'],
                                           point['high_limit'],
                                           point['low_limit'],
                                           point['higher_limit'],
                                           point['lower_limit'],
                                           point['ratio'],
                                           point['is_trend'],
                                           point['is_virtual'],
                                           point['address'],
                                           point['description']))
716 717 718 719 720 721
        cnx.commit()
        cursor.close()
        cnx.close()

        resp.status = falcon.HTTP_201
        resp.location = '/datasources/' + str(new_id)
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762


class DataSourceClone:
    @staticmethod
    def __init__():
        """Initializes Class"""
        pass

    @staticmethod
    def on_options(req, resp, id_):
        resp.status = falcon.HTTP_200

    @staticmethod
    @user_logger
    def on_post(req, resp, id_):
        """Handles POST requests"""
        admin_control(req)
        if not id_.isdigit() or int(id_) <= 0:
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
                                   description='API.INVALID_DATA_SOURCE_ID')

        cnx = mysql.connector.connect(**config.myems_system_db)
        cursor = cnx.cursor()

        query = (" SELECT id, name, uuid, gateway_id, protocol, connection, description "
                 " FROM tbl_data_sources "
                 " WHERE id = %s ")
        cursor.execute(query, (id_,))
        row = cursor.fetchone()
        if row is None:
            cursor.close()
            cnx.close()
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
                                   description='API.DATA_SOURCE_NOT_FOUND')

        meta_result = {"id": row[0],
                       "name": row[1],
                       "uuid": row[2],
                       "gateway_id": row[3],
                       "protocol": row[4],
                       "connection": row[5],
U
unknown 已提交
763 764
                       "description": row[6],
                       "points": None
765
                       }
U
unknown 已提交
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
        point_result = list()
        # Get points of the data source
        # NOTE: there is no uuid in tbl_points
        query_point = (" SELECT id, name, object_type, "
                       "        units, high_limit, low_limit, higher_limit, lower_limit, ratio, "
                       "        is_trend, is_virtual, address, description "
                       " FROM tbl_points "
                       " WHERE data_source_id = %s "
                       " ORDER BY id ")
        cursor.execute(query_point, (id_,))
        rows_point = cursor.fetchall()

        if rows_point is not None and len(rows_point) > 0:
            for row in rows_point:
                result = {"id": row[0],
                          "name": row[1],
                          "object_type": row[2],
                          "units": row[3],
                          "high_limit": row[4],
                          "low_limit": row[5],
                          "higher_limit": row[6],
                          "lower_limit": row[7],
U
unknown 已提交
788
                          "ratio": Decimal(row[8]),
U
unknown 已提交
789 790 791 792 793 794
                          "is_trend": bool(row[9]),
                          "is_virtual": bool(row[10]),
                          "address": row[11],
                          "description": row[12]}
                point_result.append(result)
            meta_result['points'] = point_result
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810

        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
        if config.utc_offset[0] == '-':
            timezone_offset = -timezone_offset
        new_name = str.strip(meta_result['name']) + \
            (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds')

        add_values = (" INSERT INTO tbl_data_sources (name, uuid, gateway_id, protocol, connection, description) "
                      " VALUES (%s, %s, %s, %s, %s, %s) ")
        cursor.execute(add_values, (new_name,
                                    str(uuid.uuid4()),
                                    meta_result['gateway_id'],
                                    meta_result['protocol'],
                                    meta_result['connection'],
                                    meta_result['description']))
        new_id = cursor.lastrowid
U
unknown 已提交
811
        if meta_result['points'] is not None:
812
            for point in meta_result['points']:
U
unknown 已提交
813 814 815 816
                add_value = (" INSERT INTO tbl_points (name, data_source_id, object_type, units, "
                             "                         high_limit, low_limit, higher_limit, lower_limit, ratio, "
                             "                         is_trend, is_virtual, address, description) "
                             " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ")
817
                cursor.execute(add_value, (point['name'],
U
unknown 已提交
818
                                           new_id,
819 820 821 822 823 824 825 826 827 828 829
                                           point['object_type'],
                                           point['units'],
                                           point['high_limit'],
                                           point['low_limit'],
                                           point['higher_limit'],
                                           point['lower_limit'],
                                           point['ratio'],
                                           point['is_trend'],
                                           point['is_virtual'],
                                           point['address'],
                                           point['description']))
830 831 832 833 834 835
        cnx.commit()
        cursor.close()
        cnx.close()

        resp.status = falcon.HTTP_201
        resp.location = '/datasources/' + str(new_id)