| Total Complexity | 136 |
| Total Lines | 732 |
| Duplicated Lines | 42.9 % |
| Changes | 0 | ||
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like core.command often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | import uuid |
||
| 2 | from datetime import datetime, timedelta |
||
| 3 | import falcon |
||
| 4 | import mysql.connector |
||
| 5 | import simplejson as json |
||
| 6 | import paho.mqtt.client as mqtt |
||
| 7 | import time |
||
| 8 | from string import Template |
||
| 9 | from core.useractivity import user_logger, admin_control, access_control, api_key_control |
||
| 10 | import config |
||
| 11 | |||
| 12 | |||
| 13 | class CommandCollection: |
||
| 14 | def __init__(self): |
||
| 15 | """"Initializes CommandCollection""" |
||
| 16 | pass |
||
| 17 | |||
| 18 | @staticmethod |
||
| 19 | def on_options(req, resp): |
||
| 20 | _=req |
||
| 21 | resp.status = falcon.HTTP_200 |
||
| 22 | |||
| 23 | View Code Duplication | @staticmethod |
|
|
|
|||
| 24 | def on_get(req, resp): |
||
| 25 | if 'API-KEY' not in req.headers or \ |
||
| 26 | not isinstance(req.headers['API-KEY'], str) or \ |
||
| 27 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
| 28 | access_control(req) |
||
| 29 | else: |
||
| 30 | api_key_control(req) |
||
| 31 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 32 | cursor = cnx.cursor() |
||
| 33 | |||
| 34 | query = (" SELECT id, name, uuid, " |
||
| 35 | " topic, payload, set_value, description " |
||
| 36 | " FROM tbl_commands " |
||
| 37 | " ORDER BY id ") |
||
| 38 | cursor.execute(query) |
||
| 39 | rows = cursor.fetchall() |
||
| 40 | cursor.close() |
||
| 41 | cnx.close() |
||
| 42 | |||
| 43 | result = list() |
||
| 44 | if rows is not None and len(rows) > 0: |
||
| 45 | for row in rows: |
||
| 46 | meta_result = {"id": row[0], |
||
| 47 | "name": row[1], |
||
| 48 | "uuid": row[2], |
||
| 49 | "topic": row[3], |
||
| 50 | "payload": row[4], |
||
| 51 | "set_value": row[5], |
||
| 52 | "description": row[6]} |
||
| 53 | result.append(meta_result) |
||
| 54 | |||
| 55 | resp.text = json.dumps(result) |
||
| 56 | |||
| 57 | @staticmethod |
||
| 58 | @user_logger |
||
| 59 | def on_post(req, resp): |
||
| 60 | """Handles POST requests""" |
||
| 61 | admin_control(req) |
||
| 62 | try: |
||
| 63 | raw_json = req.stream.read().decode('utf-8') |
||
| 64 | except Exception as ex: |
||
| 65 | print(str(ex)) |
||
| 66 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 67 | title='API.BAD_REQUEST', |
||
| 68 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 69 | |||
| 70 | new_values = json.loads(raw_json) |
||
| 71 | |||
| 72 | if 'name' not in new_values['data'].keys() or \ |
||
| 73 | not isinstance(new_values['data']['name'], str) or \ |
||
| 74 | len(str.strip(new_values['data']['name'])) == 0: |
||
| 75 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 76 | description='API.INVALID_COMMAND_NAME') |
||
| 77 | name = str.strip(new_values['data']['name']) |
||
| 78 | |||
| 79 | if 'topic' not in new_values['data'].keys() or \ |
||
| 80 | not isinstance(new_values['data']['topic'], str) or \ |
||
| 81 | len(str.strip(new_values['data']['topic'])) == 0: |
||
| 82 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 83 | description='API.INVALID_TOPIC') |
||
| 84 | topic = str.strip(new_values['data']['topic']) |
||
| 85 | |||
| 86 | if 'payload' not in new_values['data'].keys() or \ |
||
| 87 | not isinstance(new_values['data']['payload'], str) or \ |
||
| 88 | len(str.strip(new_values['data']['payload'])) == 0: |
||
| 89 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 90 | description='API.INVALID_PAYLOAD') |
||
| 91 | payload = str.strip(new_values['data']['payload']) |
||
| 92 | |||
| 93 | if 'set_value' not in new_values['data'].keys() or new_values['data']['set_value'] is None: |
||
| 94 | set_value = None |
||
| 95 | elif isinstance(new_values['data']['set_value'], float) or \ |
||
| 96 | isinstance(new_values['data']['set_value'], int): |
||
| 97 | set_value = float(new_values['data']['set_value']) |
||
| 98 | else: |
||
| 99 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 100 | description='API.INVALID_SET_VALUE') |
||
| 101 | |||
| 102 | if 'description' in new_values['data'].keys() and \ |
||
| 103 | new_values['data']['description'] is not None and \ |
||
| 104 | len(str(new_values['data']['description'])) > 0: |
||
| 105 | description = str.strip(new_values['data']['description']) |
||
| 106 | else: |
||
| 107 | description = None |
||
| 108 | |||
| 109 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 110 | cursor = cnx.cursor() |
||
| 111 | |||
| 112 | cursor.execute(" SELECT name " |
||
| 113 | " FROM tbl_commands " |
||
| 114 | " WHERE name = %s ", (name,)) |
||
| 115 | if cursor.fetchone() is not None: |
||
| 116 | cursor.close() |
||
| 117 | cnx.close() |
||
| 118 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 119 | description='API.COMMAND_NAME_IS_ALREADY_IN_USE') |
||
| 120 | |||
| 121 | add_row = (" INSERT INTO tbl_commands " |
||
| 122 | " (name, uuid, topic, payload, set_value, description) " |
||
| 123 | " VALUES (%s, %s, %s, %s, %s, %s) ") |
||
| 124 | |||
| 125 | cursor.execute(add_row, (name, |
||
| 126 | str(uuid.uuid4()), |
||
| 127 | topic, |
||
| 128 | payload, |
||
| 129 | set_value, |
||
| 130 | description)) |
||
| 131 | new_id = cursor.lastrowid |
||
| 132 | cnx.commit() |
||
| 133 | cursor.close() |
||
| 134 | cnx.close() |
||
| 135 | |||
| 136 | resp.status = falcon.HTTP_201 |
||
| 137 | resp.location = '/commands/' + str(new_id) |
||
| 138 | |||
| 139 | |||
| 140 | class CommandItem: |
||
| 141 | def __init__(self): |
||
| 142 | """"Initializes CommandItem""" |
||
| 143 | pass |
||
| 144 | |||
| 145 | @staticmethod |
||
| 146 | def on_options(req, resp, id_): |
||
| 147 | _=req |
||
| 148 | resp.status = falcon.HTTP_200 |
||
| 149 | _=id_ |
||
| 150 | View Code Duplication | @staticmethod |
|
| 151 | def on_get(req, resp, id_): |
||
| 152 | if 'API-KEY' not in req.headers or \ |
||
| 153 | not isinstance(req.headers['API-KEY'], str) or \ |
||
| 154 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
| 155 | access_control(req) |
||
| 156 | else: |
||
| 157 | api_key_control(req) |
||
| 158 | if not id_.isdigit() or int(id_) <= 0: |
||
| 159 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 160 | description='API.INVALID_COMMAND_ID') |
||
| 161 | |||
| 162 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 163 | cursor = cnx.cursor() |
||
| 164 | |||
| 165 | query = (" SELECT id, name, uuid, topic, payload, set_value, description " |
||
| 166 | " FROM tbl_commands " |
||
| 167 | " WHERE id = %s ") |
||
| 168 | cursor.execute(query, (id_,)) |
||
| 169 | row = cursor.fetchone() |
||
| 170 | cursor.close() |
||
| 171 | cnx.close() |
||
| 172 | |||
| 173 | if row is None: |
||
| 174 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 175 | description='API.COMMAND_NOT_FOUND') |
||
| 176 | |||
| 177 | result = {"id": row[0], |
||
| 178 | "name": row[1], |
||
| 179 | "uuid": row[2], |
||
| 180 | "topic": row[3], |
||
| 181 | "payload": row[4], |
||
| 182 | "set_value": row[5], |
||
| 183 | "description": row[6]} |
||
| 184 | resp.text = json.dumps(result) |
||
| 185 | |||
| 186 | View Code Duplication | @staticmethod |
|
| 187 | @user_logger |
||
| 188 | def on_delete(req, resp, id_): |
||
| 189 | admin_control(req) |
||
| 190 | if not id_.isdigit() or int(id_) <= 0: |
||
| 191 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 192 | description='API.INVALID_COMMAND_ID') |
||
| 193 | |||
| 194 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 195 | cursor = cnx.cursor() |
||
| 196 | |||
| 197 | cursor.execute(" SELECT name " |
||
| 198 | " FROM tbl_commands " |
||
| 199 | " WHERE id = %s ", (id_,)) |
||
| 200 | if cursor.fetchone() is None: |
||
| 201 | cursor.close() |
||
| 202 | cnx.close() |
||
| 203 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 204 | description='API.COMMAND_NOT_FOUND') |
||
| 205 | |||
| 206 | # check relation with meter |
||
| 207 | cursor.execute(" SELECT meter_id " |
||
| 208 | " FROM tbl_meters_commands " |
||
| 209 | " WHERE command_id = %s ", |
||
| 210 | (id_,)) |
||
| 211 | rows = cursor.fetchall() |
||
| 212 | if rows is not None and len(rows) > 0: |
||
| 213 | cursor.close() |
||
| 214 | cnx.close() |
||
| 215 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 216 | title='API.BAD_REQUEST', |
||
| 217 | description='API.THERE_IS_RELATION_WITH_METERS') |
||
| 218 | |||
| 219 | # check relation with space |
||
| 220 | cursor.execute(" SELECT space_id " |
||
| 221 | " FROM tbl_spaces_commands " |
||
| 222 | " WHERE command_id = %s ", |
||
| 223 | (id_,)) |
||
| 224 | rows_spaces = cursor.fetchall() |
||
| 225 | if rows_spaces is not None and len(rows_spaces) > 0: |
||
| 226 | cursor.close() |
||
| 227 | cnx.close() |
||
| 228 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 229 | title='API.BAD_REQUEST', |
||
| 230 | description='API.THERE_IS_RELATION_WITH_SPACES') |
||
| 231 | |||
| 232 | # check relation with equipment |
||
| 233 | cursor.execute(" SELECT equipment_id " |
||
| 234 | " FROM tbl_equipments_commands " |
||
| 235 | " WHERE command_id = %s ", |
||
| 236 | (id_,)) |
||
| 237 | rows = cursor.fetchall() |
||
| 238 | if rows is not None and len(rows) > 0: |
||
| 239 | cursor.close() |
||
| 240 | cnx.close() |
||
| 241 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 242 | title='API.BAD_REQUEST', |
||
| 243 | description='API.THERE_IS_RELATION_WITH_EQUIPMENTS') |
||
| 244 | |||
| 245 | # check relation with combined equipment |
||
| 246 | cursor.execute(" SELECT combined_equipment_id " |
||
| 247 | " FROM tbl_combined_equipments_commands " |
||
| 248 | " WHERE command_id = %s ", |
||
| 249 | (id_,)) |
||
| 250 | rows = cursor.fetchall() |
||
| 251 | if rows is not None and len(rows) > 0: |
||
| 252 | cursor.close() |
||
| 253 | cnx.close() |
||
| 254 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 255 | title='API.BAD_REQUEST', |
||
| 256 | description='API.THERE_IS_RELATION_WITH_COMBINED_EQUIPMENTS') |
||
| 257 | |||
| 258 | # check relation with tenant |
||
| 259 | cursor.execute(" SELECT tenant_id " |
||
| 260 | " FROM tbl_tenants_commands " |
||
| 261 | " WHERE command_id = %s ", |
||
| 262 | (id_,)) |
||
| 263 | rows = cursor.fetchall() |
||
| 264 | if rows is not None and len(rows) > 0: |
||
| 265 | cursor.close() |
||
| 266 | cnx.close() |
||
| 267 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 268 | title='API.BAD_REQUEST', |
||
| 269 | description='API.THERE_IS_RELATION_WITH_TENANTS') |
||
| 270 | |||
| 271 | # check relation with store |
||
| 272 | cursor.execute(" SELECT store_id " |
||
| 273 | " FROM tbl_stores_commands " |
||
| 274 | " WHERE command_id = %s ", |
||
| 275 | (id_,)) |
||
| 276 | rows = cursor.fetchall() |
||
| 277 | if rows is not None and len(rows) > 0: |
||
| 278 | cursor.close() |
||
| 279 | cnx.close() |
||
| 280 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 281 | title='API.BAD_REQUEST', |
||
| 282 | description='API.THERE_IS_RELATION_WITH_STORES') |
||
| 283 | |||
| 284 | # check relation with shopfloor |
||
| 285 | cursor.execute(" SELECT shopfloor_id " |
||
| 286 | " FROM tbl_shopfloors_commands " |
||
| 287 | " WHERE command_id = %s ", |
||
| 288 | (id_,)) |
||
| 289 | rows = cursor.fetchall() |
||
| 290 | if rows is not None and len(rows) > 0: |
||
| 291 | cursor.close() |
||
| 292 | cnx.close() |
||
| 293 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 294 | title='API.BAD_REQUEST', |
||
| 295 | description='API.THERE_IS_RELATION_WITH_SHOPFLOORS') |
||
| 296 | |||
| 297 | # check relation with energy storage container |
||
| 298 | cursor.execute(" SELECT energy_storage_container_id " |
||
| 299 | " FROM tbl_energy_storage_containers_commands " |
||
| 300 | " WHERE command_id = %s ", |
||
| 301 | (id_,)) |
||
| 302 | rows = cursor.fetchall() |
||
| 303 | if rows is not None and len(rows) > 0: |
||
| 304 | cursor.close() |
||
| 305 | cnx.close() |
||
| 306 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 307 | title='API.BAD_REQUEST', |
||
| 308 | description='API.THERE_IS_RELATION_WITH_ENERGY_STORAGE_CONTAINERS') |
||
| 309 | |||
| 310 | # check relation with microgrid |
||
| 311 | cursor.execute(" SELECT microgrid_id " |
||
| 312 | " FROM tbl_microgrids_commands " |
||
| 313 | " WHERE command_id = %s ", |
||
| 314 | (id_,)) |
||
| 315 | rows = cursor.fetchall() |
||
| 316 | if rows is not None and len(rows) > 0: |
||
| 317 | cursor.close() |
||
| 318 | cnx.close() |
||
| 319 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 320 | title='API.BAD_REQUEST', |
||
| 321 | description='API.THERE_IS_RELATION_WITH_MICROGRIDS') |
||
| 322 | |||
| 323 | # todo: check relation with points |
||
| 324 | |||
| 325 | cursor.execute(" DELETE FROM tbl_commands WHERE id = %s ", (id_,)) |
||
| 326 | cnx.commit() |
||
| 327 | |||
| 328 | cursor.close() |
||
| 329 | cnx.close() |
||
| 330 | |||
| 331 | resp.status = falcon.HTTP_204 |
||
| 332 | |||
| 333 | @staticmethod |
||
| 334 | @user_logger |
||
| 335 | def on_put(req, resp, id_): |
||
| 336 | """Handles PUT requests""" |
||
| 337 | admin_control(req) |
||
| 338 | try: |
||
| 339 | raw_json = req.stream.read().decode('utf-8') |
||
| 340 | except Exception as ex: |
||
| 341 | print(str(ex)) |
||
| 342 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 343 | title='API.BAD_REQUEST', |
||
| 344 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 345 | |||
| 346 | if not id_.isdigit() or int(id_) <= 0: |
||
| 347 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 348 | description='API.INVALID_COMMAND_ID') |
||
| 349 | |||
| 350 | new_values = json.loads(raw_json) |
||
| 351 | |||
| 352 | if 'name' not in new_values['data'].keys() or \ |
||
| 353 | not isinstance(new_values['data']['name'], str) or \ |
||
| 354 | len(str.strip(new_values['data']['name'])) == 0: |
||
| 355 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 356 | description='API.INVALID_COMMAND_NAME') |
||
| 357 | name = str.strip(new_values['data']['name']) |
||
| 358 | |||
| 359 | if 'topic' not in new_values['data'].keys() or \ |
||
| 360 | not isinstance(new_values['data']['topic'], str) or \ |
||
| 361 | len(str.strip(new_values['data']['topic'])) == 0: |
||
| 362 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 363 | description='API.INVALID_TOPIC') |
||
| 364 | topic = str.strip(new_values['data']['topic']) |
||
| 365 | |||
| 366 | if 'payload' not in new_values['data'].keys() or \ |
||
| 367 | not isinstance(new_values['data']['payload'], str) or \ |
||
| 368 | len(str.strip(new_values['data']['payload'])) == 0: |
||
| 369 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 370 | description='API.INVALID_PAYLOAD') |
||
| 371 | payload = str.strip(new_values['data']['payload']) |
||
| 372 | |||
| 373 | if 'set_value' not in new_values['data'].keys() or new_values['data']['set_value'] is None: |
||
| 374 | set_value = None |
||
| 375 | elif isinstance(new_values['data']['set_value'], float) or \ |
||
| 376 | isinstance(new_values['data']['set_value'], int): |
||
| 377 | set_value = float(new_values['data']['set_value']) |
||
| 378 | else: |
||
| 379 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 380 | description='API.INVALID_SET_VALUE') |
||
| 381 | |||
| 382 | if 'description' in new_values['data'].keys() and \ |
||
| 383 | new_values['data']['description'] is not None and \ |
||
| 384 | len(str(new_values['data']['description'])) > 0: |
||
| 385 | description = str.strip(new_values['data']['description']) |
||
| 386 | else: |
||
| 387 | description = None |
||
| 388 | |||
| 389 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 390 | cursor = cnx.cursor() |
||
| 391 | |||
| 392 | cursor.execute(" SELECT name " |
||
| 393 | " FROM tbl_commands " |
||
| 394 | " WHERE id = %s ", (id_,)) |
||
| 395 | if cursor.fetchone() is None: |
||
| 396 | cursor.close() |
||
| 397 | cnx.close() |
||
| 398 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 399 | description='API.COMMAND_NOT_FOUND') |
||
| 400 | |||
| 401 | cursor.execute(" SELECT name " |
||
| 402 | " FROM tbl_commands " |
||
| 403 | " WHERE name = %s AND id != %s ", (name, id_)) |
||
| 404 | if cursor.fetchone() is not None: |
||
| 405 | cursor.close() |
||
| 406 | cnx.close() |
||
| 407 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 408 | description='API.COMMAND_NAME_IS_ALREADY_IN_USE') |
||
| 409 | |||
| 410 | update_row = (" UPDATE tbl_commands " |
||
| 411 | " SET name = %s, topic = %s, payload = %s, set_value = %s, description = %s " |
||
| 412 | " WHERE id = %s ") |
||
| 413 | cursor.execute(update_row, (name, |
||
| 414 | topic, |
||
| 415 | payload, |
||
| 416 | set_value, |
||
| 417 | description, |
||
| 418 | id_,)) |
||
| 419 | cnx.commit() |
||
| 420 | |||
| 421 | cursor.close() |
||
| 422 | cnx.close() |
||
| 423 | |||
| 424 | resp.status = falcon.HTTP_200 |
||
| 425 | |||
| 426 | |||
| 427 | class CommandSend: |
||
| 428 | def __init__(self): |
||
| 429 | """"Initializes CommandSend""" |
||
| 430 | pass |
||
| 431 | |||
| 432 | @staticmethod |
||
| 433 | def on_options(req, resp, id_): |
||
| 434 | _=req |
||
| 435 | resp.status = falcon.HTTP_200 |
||
| 436 | _=id_ |
||
| 437 | @staticmethod |
||
| 438 | def on_put(req, resp, id_): |
||
| 439 | """Handles GET requests""" |
||
| 440 | admin_control(req) |
||
| 441 | # Get command by ID |
||
| 442 | if not id_.isdigit() or int(id_) <= 0: |
||
| 443 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 444 | description='API.INVALID_COMMAND_ID') |
||
| 445 | |||
| 446 | try: |
||
| 447 | raw_json = req.stream.read().decode('utf-8') |
||
| 448 | except Exception as ex: |
||
| 449 | print(str(ex)) |
||
| 450 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 451 | title='API.BAD_REQUEST', |
||
| 452 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 453 | |||
| 454 | new_values = json.loads(raw_json) |
||
| 455 | |||
| 456 | if 'set_value' not in new_values['data'].keys() or new_values['data']['set_value'] is None: |
||
| 457 | set_value = None |
||
| 458 | elif isinstance(new_values['data']['set_value'], float): |
||
| 459 | set_value = float(new_values['data']['set_value']) |
||
| 460 | elif isinstance(new_values['data']['set_value'], int): |
||
| 461 | set_value = int(new_values['data']['set_value']) |
||
| 462 | else: |
||
| 463 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 464 | description='API.INVALID_SET_VALUE') |
||
| 465 | |||
| 466 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 467 | cursor = cnx.cursor() |
||
| 468 | |||
| 469 | query = (" SELECT id, name, uuid, topic, payload, set_value " |
||
| 470 | " FROM tbl_commands " |
||
| 471 | " WHERE id = %s ") |
||
| 472 | cursor.execute(query, (id_,)) |
||
| 473 | row = cursor.fetchone() |
||
| 474 | |||
| 475 | if row is None: |
||
| 476 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 477 | description='API.COMMAND_NOT_FOUND') |
||
| 478 | |||
| 479 | command = {"id": row[0], |
||
| 480 | "name": row[1], |
||
| 481 | "uuid": row[2], |
||
| 482 | "topic": row[3], |
||
| 483 | "payload": row[4], |
||
| 484 | "set_value": set_value if set_value is not None else row[5]} |
||
| 485 | |||
| 486 | update_row = (" UPDATE tbl_commands " |
||
| 487 | " SET set_value = %s " |
||
| 488 | " WHERE id = %s ") |
||
| 489 | cursor.execute(update_row, (set_value, |
||
| 490 | id_,)) |
||
| 491 | cnx.commit() |
||
| 492 | |||
| 493 | cursor.close() |
||
| 494 | cnx.close() |
||
| 495 | |||
| 496 | mqc = None |
||
| 497 | try: |
||
| 498 | mqc = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2, |
||
| 499 | client_id='MYEMS' + "-" + str(time.time()), |
||
| 500 | clean_session=None, |
||
| 501 | userdata=None, |
||
| 502 | protocol=mqtt.MQTTv5, |
||
| 503 | transport='tcp', |
||
| 504 | reconnect_on_failure=True, |
||
| 505 | manual_ack=False) |
||
| 506 | mqc.username_pw_set(config.myems_mqtt_broker['username'], config.myems_mqtt_broker['password']) |
||
| 507 | mqc.connect(config.myems_mqtt_broker['host'], config.myems_mqtt_broker['port'], 60) |
||
| 508 | except Exception as e: |
||
| 509 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 510 | description='API.MQTT_CONNECTION_ERROR') |
||
| 511 | |||
| 512 | try: |
||
| 513 | if command['set_value'] is not None: |
||
| 514 | payload = Template(command['payload']).substitute(s1=str(command['set_value'])) |
||
| 515 | else: |
||
| 516 | payload = Template(command['payload']).substitute(s1=str(0)) |
||
| 517 | print('payload=' + str(payload)) |
||
| 518 | mqc.publish(command['topic'], payload=payload) |
||
| 519 | except Exception as e: |
||
| 520 | print(str(e)) |
||
| 521 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 522 | description='API.MQTT_PUBLISH_ERROR') |
||
| 523 | |||
| 524 | resp.text = json.dumps('success') |
||
| 525 | |||
| 526 | |||
| 527 | class CommandExport: |
||
| 528 | def __init__(self): |
||
| 529 | """"Initializes CommandItem""" |
||
| 530 | pass |
||
| 531 | |||
| 532 | @staticmethod |
||
| 533 | def on_options(req, resp, id_): |
||
| 534 | _=req |
||
| 535 | resp.status = falcon.HTTP_200 |
||
| 536 | _=id_ |
||
| 537 | View Code Duplication | @staticmethod |
|
| 538 | def on_get(req, resp, id_): |
||
| 539 | if 'API-KEY' not in req.headers or \ |
||
| 540 | not isinstance(req.headers['API-KEY'], str) or \ |
||
| 541 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
| 542 | access_control(req) |
||
| 543 | else: |
||
| 544 | api_key_control(req) |
||
| 545 | if not id_.isdigit() or int(id_) <= 0: |
||
| 546 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 547 | description='API.INVALID_COMMAND_ID') |
||
| 548 | |||
| 549 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 550 | cursor = cnx.cursor() |
||
| 551 | |||
| 552 | query = (" SELECT id, name, uuid, topic, payload, set_value, description " |
||
| 553 | " FROM tbl_commands " |
||
| 554 | " WHERE id = %s ") |
||
| 555 | cursor.execute(query, (id_,)) |
||
| 556 | row = cursor.fetchone() |
||
| 557 | cursor.close() |
||
| 558 | cnx.close() |
||
| 559 | |||
| 560 | if row is None: |
||
| 561 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 562 | description='API.COMMAND_NOT_FOUND') |
||
| 563 | |||
| 564 | result = {"id": row[0], |
||
| 565 | "name": row[1], |
||
| 566 | "uuid": row[2], |
||
| 567 | "topic": row[3], |
||
| 568 | "payload": row[4], |
||
| 569 | "set_value": row[5], |
||
| 570 | "description": row[6]} |
||
| 571 | resp.text = json.dumps(result) |
||
| 572 | |||
| 573 | |||
| 574 | class CommandImport: |
||
| 575 | def __init__(self): |
||
| 576 | """"Initializes CommandCollection""" |
||
| 577 | pass |
||
| 578 | |||
| 579 | @staticmethod |
||
| 580 | def on_options(req, resp): |
||
| 581 | _=req |
||
| 582 | resp.status = falcon.HTTP_200 |
||
| 583 | |||
| 584 | @staticmethod |
||
| 585 | @user_logger |
||
| 586 | def on_post(req, resp): |
||
| 587 | """Handles POST requests""" |
||
| 588 | admin_control(req) |
||
| 589 | try: |
||
| 590 | raw_json = req.stream.read().decode('utf-8') |
||
| 591 | except Exception as ex: |
||
| 592 | print(str(ex)) |
||
| 593 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 594 | title='API.BAD_REQUEST', |
||
| 595 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 596 | |||
| 597 | new_values = json.loads(raw_json) |
||
| 598 | |||
| 599 | if 'name' not in new_values.keys() or \ |
||
| 600 | not isinstance(new_values['name'], str) or \ |
||
| 601 | len(str.strip(new_values['name'])) == 0: |
||
| 602 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 603 | description='API.INVALID_COMMAND_NAME') |
||
| 604 | name = str.strip(new_values['name']) |
||
| 605 | |||
| 606 | if 'topic' not in new_values.keys() or \ |
||
| 607 | not isinstance(new_values['topic'], str) or \ |
||
| 608 | len(str.strip(new_values['topic'])) == 0: |
||
| 609 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 610 | description='API.INVALID_TOPIC') |
||
| 611 | topic = str.strip(new_values['topic']) |
||
| 612 | |||
| 613 | if 'payload' not in new_values.keys() or \ |
||
| 614 | not isinstance(new_values['payload'], str) or \ |
||
| 615 | len(str.strip(new_values['payload'])) == 0: |
||
| 616 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 617 | description='API.INVALID_PAYLOAD') |
||
| 618 | payload = str.strip(new_values['payload']) |
||
| 619 | |||
| 620 | if 'set_value' not in new_values.keys() or new_values['data']['set_value'] is None: |
||
| 621 | set_value = None |
||
| 622 | elif isinstance(new_values['set_value'], float) or \ |
||
| 623 | isinstance(new_values['set_value'], int): |
||
| 624 | set_value = float(new_values['set_value']) |
||
| 625 | else: |
||
| 626 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 627 | description='API.INVALID_SET_VALUE') |
||
| 628 | |||
| 629 | if 'description' in new_values.keys() and \ |
||
| 630 | new_values['description'] is not None and \ |
||
| 631 | len(str(new_values['description'])) > 0: |
||
| 632 | description = str.strip(new_values['description']) |
||
| 633 | else: |
||
| 634 | description = None |
||
| 635 | |||
| 636 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 637 | cursor = cnx.cursor() |
||
| 638 | |||
| 639 | cursor.execute(" SELECT name " |
||
| 640 | " FROM tbl_commands " |
||
| 641 | " WHERE name = %s ", (name,)) |
||
| 642 | if cursor.fetchone() is not None: |
||
| 643 | cursor.close() |
||
| 644 | cnx.close() |
||
| 645 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 646 | description='API.COMMAND_NAME_IS_ALREADY_IN_USE') |
||
| 647 | |||
| 648 | add_row = (" INSERT INTO tbl_commands " |
||
| 649 | " (name, uuid, topic, payload, set_value, description) " |
||
| 650 | " VALUES (%s, %s, %s, %s, %s, %s) ") |
||
| 651 | |||
| 652 | cursor.execute(add_row, (name, |
||
| 653 | str(uuid.uuid4()), |
||
| 654 | topic, |
||
| 655 | payload, |
||
| 656 | set_value, |
||
| 657 | description)) |
||
| 658 | new_id = cursor.lastrowid |
||
| 659 | cnx.commit() |
||
| 660 | cursor.close() |
||
| 661 | cnx.close() |
||
| 662 | |||
| 663 | resp.status = falcon.HTTP_201 |
||
| 664 | resp.location = '/commands/' + str(new_id) |
||
| 665 | |||
| 666 | |||
| 667 | View Code Duplication | class CommandClone: |
|
| 668 | def __init__(self): |
||
| 669 | """"Initializes CommandItem""" |
||
| 670 | pass |
||
| 671 | |||
| 672 | @staticmethod |
||
| 673 | def on_options(req, resp, id_): |
||
| 674 | _=req |
||
| 675 | resp.status = falcon.HTTP_200 |
||
| 676 | _=id_ |
||
| 677 | @staticmethod |
||
| 678 | @user_logger |
||
| 679 | def on_post(req, resp, id_): |
||
| 680 | if 'API-KEY' not in req.headers or \ |
||
| 681 | not isinstance(req.headers['API-KEY'], str) or \ |
||
| 682 | len(str.strip(req.headers['API-KEY'])) == 0: |
||
| 683 | access_control(req) |
||
| 684 | else: |
||
| 685 | api_key_control(req) |
||
| 686 | if not id_.isdigit() or int(id_) <= 0: |
||
| 687 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 688 | description='API.INVALID_COMMAND_ID') |
||
| 689 | |||
| 690 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 691 | cursor = cnx.cursor() |
||
| 692 | |||
| 693 | query = (" SELECT id, name, uuid, topic, payload, set_value, description " |
||
| 694 | " FROM tbl_commands " |
||
| 695 | " WHERE id = %s ") |
||
| 696 | cursor.execute(query, (id_,)) |
||
| 697 | row = cursor.fetchone() |
||
| 698 | |||
| 699 | if row is None: |
||
| 700 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 701 | description='API.COMMAND_NOT_FOUND') |
||
| 702 | |||
| 703 | result = {"id": row[0], |
||
| 704 | "name": row[1], |
||
| 705 | "uuid": row[2], |
||
| 706 | "topic": row[3], |
||
| 707 | "payload": row[4], |
||
| 708 | "set_value": row[5], |
||
| 709 | "description": row[6]} |
||
| 710 | add_row = (" INSERT INTO tbl_commands " |
||
| 711 | " (name, uuid, topic, payload, set_value, description) " |
||
| 712 | " VALUES (%s, %s, %s, %s, %s, %s) ") |
||
| 713 | |||
| 714 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
| 715 | if config.utc_offset[0] == '-': |
||
| 716 | timezone_offset = -timezone_offset |
||
| 717 | new_name = (str.strip(result['name']) + |
||
| 718 | (datetime.utcnow() + timedelta(minutes=timezone_offset)).isoformat(sep='-', timespec='seconds')) |
||
| 719 | cursor.execute(add_row, (new_name, |
||
| 720 | str(uuid.uuid4()), |
||
| 721 | result['topic'], |
||
| 722 | result['payload'], |
||
| 723 | result['set_value'], |
||
| 724 | result['description'])) |
||
| 725 | new_id = cursor.lastrowid |
||
| 726 | cnx.commit() |
||
| 727 | cursor.close() |
||
| 728 | cnx.close() |
||
| 729 | |||
| 730 | resp.status = falcon.HTTP_201 |
||
| 731 | resp.location = '/commands/' + str(new_id) |
||
| 732 | |||
| 733 |