datasource.py 35.5 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 109 110
                 'dtu-rtu',
                 'dtu-tcp',
                 'dtu-mqtt',
111
                 'elexon-bmrs',
112 113 114
                 'iec104',
                 'influxdb',
                 'lora',
nengyuangzhang's avatar
nengyuangzhang 已提交
115
                 'modbus-rtu',
116 117
                 'modbus-tcp',
                 'mongodb',
118
                 'mqtt-acrel',
nengyuangzhang's avatar
nengyuangzhang 已提交
119
                 'mqtt-adw300',
120
                 'mqtt-huiju',
121 122
                 'mqtt-md4220',
                 'mqtt-seg',
nengyuangzhang's avatar
nengyuangzhang 已提交
123
                 'mqtt-weilan',
124 125 126 127 128
                 'mqtt',
                 'mysql',
                 'opc-ua',
                 'oracle',
                 'postgresql',
nengyuangzhang's avatar
nengyuangzhang 已提交
129 130
                 'profibus',
                 'profinet',
131
                 's7',
nengyuangzhang's avatar
nengyuangzhang 已提交
132 133
                 'simulation',
                 'sqlserver',
134 135
                 'tdengine',
                 'weather',):
136
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
137 138 139 140 141 142
                                   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:
143
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
144 145 146
                                   description='API.INVALID_CONNECTION')
        connection = str.strip(new_values['data']['connection'])

147 148 149 150 151 152 153
        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 已提交
154 155 156 157 158 159 160 161 162
        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()
163
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
164 165 166 167 168 169 170 171
                                   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()
172
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
173 174
                                   description='API.INVALID_GATEWAY_ID')

175 176
        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 已提交
177 178 179 180
        cursor.execute(add_values, (name,
                                    str(uuid.uuid4()),
                                    gateway_id,
                                    protocol,
181 182
                                    connection,
                                    description))
nengyuangzhang's avatar
nengyuangzhang 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        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 已提交
204
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
205
        if not id_.isdigit() or int(id_) <= 0:
206
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
                                   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]}

223
        query = (" SELECT id, name, uuid, gateway_id, protocol, connection, last_seen_datetime_utc, description "
nengyuangzhang's avatar
nengyuangzhang 已提交
224 225 226 227 228 229 230
                 " FROM tbl_data_sources "
                 " WHERE id = %s ")
        cursor.execute(query, (id_,))
        row = cursor.fetchone()
        cursor.close()
        cnx.close()
        if row is None:
231
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
nengyuangzhang's avatar
nengyuangzhang 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
                                   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],
251 252
                  "last_seen_datetime": last_seen_datetime,
                  "description": row[7]
nengyuangzhang's avatar
nengyuangzhang 已提交
253 254 255 256 257 258 259
                  }

        resp.text = json.dumps(result)

    @staticmethod
    @user_logger
    def on_delete(req, resp, id_):
L
LLLkui 已提交
260
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
261
        if not id_.isdigit() or int(id_) <= 0:
262
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
263 264 265 266 267 268 269 270 271 272 273
                                   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()
274
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
nengyuangzhang's avatar
nengyuangzhang 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287
                                   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()
288
            raise falcon.HTTPError(status=falcon.HTTP_400,
nengyuangzhang's avatar
nengyuangzhang 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
                                   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 已提交
304
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
305 306 307
        try:
            raw_json = req.stream.read().decode('utf-8')
        except Exception as ex:
308 309 310
            raise falcon.HTTPError(status=falcon.HTTP_400,
                                   title='API.BAD_REQUEST',
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
nengyuangzhang's avatar
nengyuangzhang 已提交
311 312

        if not id_.isdigit() or int(id_) <= 0:
313
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
314 315 316 317 318 319 320
                                   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:
321
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
322 323 324 325 326 327
                                   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:
328
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
329 330 331 332 333
                                   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 \
334 335 336
                ('bacnet-ip',
                 'cassandra',
                 'clickhouse',
337
                 'coap',
338 339
                 'controllogix',
                 'dlt645',
340 341 342
                 'dtu-rtu',
                 'dtu-tcp',
                 'dtu-mqtt',
343
                 'elexon-bmrs',
344 345 346
                 'iec104',
                 'influxdb',
                 'lora',
nengyuangzhang's avatar
nengyuangzhang 已提交
347
                 'modbus-rtu',
348 349
                 'modbus-tcp',
                 'mongodb',
350
                 'mqtt-acrel',
nengyuangzhang's avatar
nengyuangzhang 已提交
351
                 'mqtt-adw300',
352
                 'mqtt-huiju',
353 354
                 'mqtt-md4220',
                 'mqtt-seg',
nengyuangzhang's avatar
nengyuangzhang 已提交
355
                 'mqtt-weilan',
356 357 358 359 360
                 'mqtt',
                 'mysql',
                 'opc-ua',
                 'oracle',
                 'postgresql',
nengyuangzhang's avatar
nengyuangzhang 已提交
361 362
                 'profibus',
                 'profinet',
363
                 's7',
nengyuangzhang's avatar
nengyuangzhang 已提交
364 365
                 'simulation',
                 'sqlserver',
366 367
                 'tdengine',
                 'weather',):
368
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
369 370 371 372 373 374
                                   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:
375
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
376 377 378
                                   description='API.INVALID_CONNECTION')
        connection = str.strip(new_values['data']['connection'])

379 380 381 382 383 384 385
        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 已提交
386 387 388 389 390 391 392 393 394
        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()
395
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
nengyuangzhang's avatar
nengyuangzhang 已提交
396 397 398 399 400 401 402 403
                                   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()
404
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
405 406 407
                                   description='API.INVALID_GATEWAY_ID')

        update_row = (" UPDATE tbl_data_sources "
408
                      " SET name = %s, gateway_id = %s, protocol = %s, connection = %s, description = %s "
nengyuangzhang's avatar
nengyuangzhang 已提交
409 410 411 412 413
                      " WHERE id = %s ")
        cursor.execute(update_row, (name,
                                    gateway_id,
                                    protocol,
                                    connection,
414
                                    description,
nengyuangzhang's avatar
nengyuangzhang 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
                                    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 已提交
436
        admin_control(req)
nengyuangzhang's avatar
nengyuangzhang 已提交
437
        if not id_.isdigit() or int(id_) <= 0:
438
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
nengyuangzhang's avatar
nengyuangzhang 已提交
439 440 441 442 443 444 445 446 447 448 449
                                   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()
450
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
nengyuangzhang's avatar
nengyuangzhang 已提交
451 452 453 454 455 456
                                   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, "
457 458
                       "        units, high_limit, low_limit, higher_limit, lower_limit, ratio, "
                       "        is_trend, is_virtual, address, description "
nengyuangzhang's avatar
nengyuangzhang 已提交
459 460 461 462 463 464
                       " FROM tbl_points "
                       " WHERE data_source_id = %s "
                       " ORDER BY id ")
        cursor.execute(query_point, (id_,))
        rows_point = cursor.fetchall()

465 466 467
        cnx_history = mysql.connector.connect(**config.myems_historical_db)
        history = cnx_history.cursor()
        history.execute(" SELECT point_id, utc_date_time, actual_value "
468 469
                        " FROM tbl_analog_value_latest "
                        " WHERE utc_date_time >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 10 MINUTE)")
470 471 472
        analog = history.fetchall()

        history.execute(" SELECT point_id, utc_date_time, actual_value "
473 474
                        " FROM tbl_digital_value_latest "
                        " WHERE utc_date_time >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 10 MINUTE)")
475 476 477
        digital = history.fetchall()

        history.execute(" SELECT point_id, utc_date_time, actual_value "
478 479
                        " FROM tbl_energy_value_latest "
                        " WHERE utc_date_time >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 10 MINUTE)")
480 481
        energy = history.fetchall()

nengyuangzhang's avatar
nengyuangzhang 已提交
482 483 484 485 486 487 488 489
        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],
490 491 492 493 494 495
                               "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],
496 497 498 499 500 501
                               "description": row[12],
                               "analog_value": None,
                               "digital_value": None,
                               "energy_value": None}
                for point in analog:
                    if point[0] == meta_result['id'] and isinstance(point[1], datetime):
502
                        meta_result['analog_value'] = point[2]
503 504
                for point in digital:
                    if point[0] == meta_result['id'] and isinstance(point[1], datetime):
505
                        meta_result['digital_value'] = point[2]
506 507
                for point in energy:
                    if point[0] == meta_result['id'] and isinstance(point[1], datetime):
508
                        meta_result['energy_value'] = point[2]
nengyuangzhang's avatar
nengyuangzhang 已提交
509 510 511 512
                result.append(meta_result)

        cursor.close()
        cnx.close()
513 514
        history.close()
        cnx_history.close()
nengyuangzhang's avatar
nengyuangzhang 已提交
515
        resp.text = json.dumps(result)
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568


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

569
        result = {"name": row[1],
570 571 572 573 574
                  "uuid": row[2],
                  "gateway": gateway_dict.get(row[3]),
                  "protocol": row[4],
                  "connection": row[5],
                  "last_seen_datetime": last_seen_datetime,
U
unknown 已提交
575 576
                  "description": row[7],
                  "points": None
577
                  }
U
unknown 已提交
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
        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 已提交
600
                               "ratio": Decimal(row[8]),
U
unknown 已提交
601 602 603 604 605 606 607 608
                               "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()
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

        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:
629
            raw_json = req.stream.read().decode('utf-8')
630 631 632 633 634 635
        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)
636

637 638 639 640 641
        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')
642
        name = str.strip(new_values['name'])
643 644 645 646 647 648 649 650

        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']
651

652 653 654 655 656 657 658 659
        if 'protocol' not in new_values.keys() \
                or new_values['protocol'] not in \
                ('bacnet-ip',
                 'cassandra',
                 'clickhouse',
                 'coap',
                 'controllogix',
                 'dlt645',
660 661 662
                 'dtu-rtu',
                 'dtu-tcp',
                 'dtu-mqtt',
663 664 665 666 667 668 669
                 'elexon-bmrs',
                 'iec104',
                 'influxdb',
                 'lora',
                 'modbus-rtu',
                 'modbus-tcp',
                 'mongodb',
670
                 'mqtt-acrel',
nengyuangzhang's avatar
nengyuangzhang 已提交
671
                 'mqtt-adw300',
672
                 'mqtt-huiju',
673 674
                 'mqtt-md4220',
                 'mqtt-seg',
nengyuangzhang's avatar
nengyuangzhang 已提交
675
                 'mqtt-weilan',
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
                 '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')
726

727 728 729 730 731 732 733 734 735
        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
736 737 738
        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 已提交
739 740 741 742
                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) ")
743
                cursor.execute(add_value, (point['name'],
U
unknown 已提交
744
                                           new_id,
745 746 747 748 749 750 751 752 753 754 755
                                           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']))
756 757 758 759 760 761
        cnx.commit()
        cursor.close()
        cnx.close()

        resp.status = falcon.HTTP_201
        resp.location = '/datasources/' + str(new_id)
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802


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 已提交
803 804
                       "description": row[6],
                       "points": None
805
                       }
U
unknown 已提交
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
        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 已提交
828
                          "ratio": Decimal(row[8]),
U
unknown 已提交
829 830 831 832 833 834
                          "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
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850

        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 已提交
851
        if meta_result['points'] is not None:
852
            for point in meta_result['points']:
U
unknown 已提交
853 854 855 856
                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) ")
857
                cursor.execute(add_value, (point['name'],
U
unknown 已提交
858
                                           new_id,
859 860 861 862 863 864 865 866 867 868 869
                                           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']))
870 871 872 873 874 875
        cnx.commit()
        cursor.close()
        cnx.close()

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