class CreateCompany(Common): """Class for CreateCompany""" # INITIALIZE def __init__(self): """The Constructor for CreateCompany class""" self.postgresql_query = PostgreSQL() self._couch_db = CouchDatabase() self.couch_query = Queries() self.log = Log() super(CreateCompany, self).__init__() def create_company(self): """ This API is for Creating Company --- tags: - Company produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: query in: body description: Company required: true schema: id: Company properties: company_name: type: string vessel_ids: types: array example: [] responses: 500: description: Error 200: description: Company """ data = {} # GET JSON REQUEST query_json = request.get_json(force=True) # GET HEADER token = request.headers.get('token') userid = request.headers.get('userid') # EXTRACT QUERY JSON company_name = query_json['company_name'] vessel_ids = query_json['vessel_ids'] # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # CREATE COMPANY company_id = self.insert_company(company_name) if not company_id: data[ "alert"] = "Please check your query! | Company is Already Exist." data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # BIND COMPANY TO VESSELS alert, status = self.insert_company_vessels(company_id, vessel_ids) if status != 'ok': data["alert"] = alert data['status'] = status # RETURN ALERT return self.return_data(data) data['message'] = "Company successfully created!" data['status'] = "ok" return self.return_data(data) def insert_company(self, company_name): """Insert Company""" data = {} data['company_name'] = company_name data['created_on'] = time.time() company_id = self.postgresql_query.insert('company', data, 'company_id') return company_id or 0 def insert_company_vessels(self, company_id, vessel_ids): """Insert Company Vessels""" alert, status = '', '' if not self.check_vessel_existence(vessel_ids): alert = "Some Vessel/s doesn't exists." status = 'Failed' else: for vessel_id in vessel_ids: data = {} data['company_id'] = company_id data['vessel_id'] = vessel_id try: self.postgres.insert('company_vessels', data, 'company_id') alert = "" status = 'ok' except TypeError: alert = "ERROR inserting company vessels" status = 'Failed' return alert, status def check_vessel_existence(self, vessel_ids): """Verify if vessel exists""" for _id in vessel_ids: res = self.couch_query.get_by_id(_id) if res.get('error', False): return 0 if res.get('_id', False): pass else: return 0 return 1
class PortForwarding(Common): """Class for PortForwarding""" # INITIALIZE def __init__(self): """The Constructor for PortForwarding class""" self._couch_db = CouchDatabase() self.couch_query = Queries() self.epoch_default = 26763 super(PortForwarding, self).__init__() def port_forwarding(self): """ This API is for getting Port Forwarding of device --- tags: - Devices produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: vessel_id in: query description: Vessel ID required: true type: string - name: device_id in: query description: Device ID required: false type: string - name: limit in: query description: Limit required: true type: integer - name: page in: query description: Page required: true type: integer responses: 500: description: Error 200: description: Vessel Device Info """ data = {} # VESSEL ID vessel_id = request.args.get('vessel_id') device_id = request.args.get('device_id') limit = int(request.args.get('limit')) page = int(request.args.get('page')) # GET DATA token = request.headers.get('token') userid = request.headers.get('userid') # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) if not vessel_id: data["alert"] = "Please complete parameters!" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # device_list = [] device_name = "" if device_id: device_data = self.couch_query.get_by_id(device_id) dev_name = device_data['device'] # device_list.append(value) # else: # device_list = self.couch_query.get_device(vessel_id) # REMOVE DATA # data_to_remove = ['PARAMETERS', 'COREVALUES', 'FAILOVER', 'NTWCONF', 'NTWPERF1'] # device_list = self.remove_data(device_list, data_to_remove) datas = {} datas['data'] = [] final_data = [] ntwconf = self.couch_query.get_complete_values(vessel_id, "NTWCONF") parameters = self.couch_query.get_complete_values( vessel_id, "PARAMETERS") vpn_ip = ntwconf['NTWCONF']['tun1']['IP'] keys = parameters['PARAMETERS'].keys() for i in range(1, (len(keys))): temp_pf = {} port = 'PORTFORWARDING' + str(i) if port in keys: destination_ip_val = parameters['PARAMETERS'][port][ 'DESTINATIONIP'] destination_port_val = parameters['PARAMETERS'][port][ 'DESTINATIONPORT'] description_val = parameters['PARAMETERS'][port]['DESCRIPTION'] device_name = parameters['PARAMETERS'][port]['DEVICE'] link = description_val.lower() + '://' link += vpn_ip + ':' + parameters['PARAMETERS'][port][ 'SOURCEPORT'] if device_id and dev_name == device_name: temp_pf['destination_ip'] = destination_ip_val temp_pf['destination_port'] = destination_port_val temp_pf['description'] = description_val temp_pf['link'] = link temp_pf['device'] = device_name final_data.append(temp_pf) elif not device_id: temp_pf['destination_ip'] = destination_ip_val temp_pf['destination_port'] = destination_port_val temp_pf['description'] = description_val temp_pf['link'] = link temp_pf['device'] = device_name final_data.append(temp_pf) total_count = len(final_data) - 1 total_page = int(math.ceil(int(total_count) / limit)) + 1 final_data = self.limits(final_data, limit, page) datas['total_rows'] = total_count + 1 datas['total_page'] = total_page datas['limit'] = int(limit) datas['page'] = int(page) datas['data'] = final_data datas['status'] = 'ok' return self.return_data(datas)
class UpdateVesselState(Common): """Class for UpdateVesselState""" # INITIALIZE def __init__(self): """The Constructor for UpdateVesselState class""" self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() super(UpdateVesselState, self).__init__() def update_vessel_state(self): """Update Vessel State""" vessels = self.couch_query.get_vessels() # JUST TO INDEX # self.couch_query.get_system1() vessel_ids = [x['id'] for x in vessels] # DON'T DELETE FOR SYSTEM INDEXING for vssl_id in vessel_ids: self.couch_query.get_system(vssl_id) # INIT SQL QUERY sql_str = "SELECT * FROM vessel" # FETCH ALL rows = self.postgres.query_fetch_all(sql_str) db_vessel_ids = [x['vessel_id'] for x in rows] vessel_ids = set(vessel_ids) db_vessel_ids = set(db_vessel_ids) vessel_ids.difference_update(db_vessel_ids) if vessel_ids: for vessel_id in vessel_ids: doc = self.couch_query.get_by_id(vessel_id) sql_str = "SELECT * FROM vessel WHERE " sql_str += "number='{0}'".format(doc['number']) vssl_nmbr = self.postgres.query_fetch_one(sql_str) if vssl_nmbr: if vssl_nmbr['vessel_id'] and vssl_nmbr['number']: # INIT CONDITION conditions = [] # CONDITION FOR QUERY conditions.append({ "col": "vessel_id", "con": "=", "val": vssl_nmbr['vessel_id'] }) data = {} data['vessel_id'] = vessel_id self.postgres.update('vessel', data, conditions) else: print("SAME VESSEL NUMBER: {0}!!!".format( vssl_nmbr['number'])) else: data = {} data['number'] = doc['number'] data['vessel_name'] = self.get_vessel_name(vessel_id) data['vessel_id'] = vessel_id data['update_on'] = time.time() data['created_on'] = time.time() self.postgres.insert('vessel', data) sql_str = "SELECT * FROM vessel WHERE number IS NULL OR vessel_name IS NULL" null_vessels = self.postgres.query_fetch_all(sql_str) for vssl in null_vessels: # INIT CONDITION conditions = [] # CONDITION FOR QUERY conditions.append({ "col": "vessel_id", "con": "=", "val": vssl['vessel_id'] }) doc = self.couch_query.get_by_id(vssl['vessel_id']) if 'error' in doc.keys(): number = vssl['vessel_id'] else: number = doc['number'] data = {} data['number'] = number data['vessel_name'] = self.get_vessel_name(vssl['vessel_id']) self.postgres.update('vessel', data, conditions) # RETURN return rows def get_vessel_name(self, vessel_id): """ Return Vessel Name """ assert vessel_id, "Vessel ID is required." # GET VESSEL NAME values = self.couch_query.get_complete_values(vessel_id, "PARAMETERS") if values: vessel_name = values['PARAMETERS']['INFO']['VESSELNAME'] else: vessel_name = "" return vessel_name
class DeleteVessel(Common): """Class for DeleteVessel""" # INITIALIZE def __init__(self): """The Constructor for DeleteVessel class""" super(DeleteVessel, self).__init__() self.couch_query = Queries() # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self.postgres = PostgreSQL() self.vpn_db_build = config_section_parser(self.config, "VPNDB")['build'] if self.vpn_db_build.upper() == 'TRUE': self.my_ip = config_section_parser(self.config, "IPS")['my'] self.my_protocol = config_section_parser(self.config, "IPS")['my_protocol'] self.vessel_vpn = config_section_parser(self.config, "IPS")['vessel_vpn'] self.vessel_protocol = config_section_parser( self.config, "IPS")['vessel_protocol'] self.vpn_token = '269c2c3706886d94aeefd6e7f7130ab08346590533d4c5b24ccaea9baa5211ec' def delete_vessel(self): """ This API is for Deleting Permission --- tags: - Vessel produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: query in: body description: Vessel infos required: true schema: id: Delete Vessels properties: vessel_info: types: array example: [{'vessel_id': vesselid1, 'vessel_rev': vesselrev1 }] responses: 500: description: Error 200: description: Delete Vessel """ data = {} # GET JSON REQUEST query_json = request.get_json(force=True) # GET HEADER token = request.headers.get('token') userid = request.headers.get('userid') # GET QUERY vessel_info = query_json["vessel_info"] # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) for vssl in vessel_info: doc = self.couch_query.get_by_id(vssl['vessel_id']) # INIT PARAMS FOR CREATE VPN vpn_params = {} vpn_params['vessel_number'] = vssl['vessel_id'] if 'error' not in doc.keys(): vpn_params['vessel_number'] = doc['number'] if self.vpn_db_build.upper() == 'TRUE': if not self.revoke_vpn(vpn_params): data["alert"] = "Please try again after 5 minutes!" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) vessel_id = vssl['vessel_id'] vessel_rev = vssl['vessel_rev'] os.path.dirname(os.path.realpath(__file__)) subprocess.Popen([ "nohup", "python3", "delete_vessel.py", str(vessel_id), str(vessel_rev), ">", "out.log", "&" ]) data['message'] = "Vessel(s) successfully Deleted!" data['status'] = "ok" return self.return_data(data) def revoke_vpn(self, data): """Update VPN""" try: api_endpoint = self.vessel_protocol + "://" + self.vessel_vpn + "/delete/vessel/vpn" headers = { 'content-type': 'application/json', 'token': self.vpn_token } req = requests.delete(api_endpoint, data=json.dumps(data), headers=headers) res = req.json() if res['status'] == 'ok': cmd = "rm -rf /home/admin/all_vpn/VESSEL_" + str( data['vessel_number']) + ".zip" _ = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True) return res except: return 0
class Vessel(Common): """Class for Vessel""" # INITIALIZE def __init__(self): """The Constructor for Vessel class""" # self._my_db = MySQLDatabase() self._couch_db = CouchDatabase() self.couch_query = Queries() self.postgres = PostgreSQL() self.epoch_default = 26763 self.aws3 = AwsS3() super(Vessel, self).__init__() # # INIT CONFIG # self.config = ConfigParser.ConfigParser() # # CONFIG FILE # self.config.read("config/config.cfg") # GET VESSEL FUNCTION def get_vessels_data(self): """ This API is for Getting Vessel Information --- tags: - Vessel produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: vessel_ids in: query description: Vessels IDs required: false type: string responses: 500: description: Error 200: description: Vessel Information """ # INIT DATA data = {} # GET DATA token = request.headers.get('token') userid = request.headers.get('userid') # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # GET ADMIN ROLE AND SUPER ADMIN ROLE sql_str = "SELECT role_id FROM role WHERE role_name in ('admin', 'super admin')" l_ids = self.postgres.query_fetch_all(sql_str) role_ids = [x['role_id'] for x in l_ids] str_ids = "" if len(role_ids) == 1: str_ids = "(" + str(role_ids[0]) + ")" else: str_ids = str(tuple(role_ids)) # CREATE SQL QUERY # GET ADMIN ACCOUNT sql_str = "SELECT * FROM account_role where account_id='" + str(userid) sql_str += "' AND role_id in " + str_ids res = self.postgres.query_fetch_one(sql_str) # EXTRACT VESSELS ID extracted_vessel_ids = request.args.get('vessel_ids') vessels = [] if res: if extracted_vessel_ids: for vessel_id in extracted_vessel_ids.split(","): res = self.couch_query.get_by_id(vessel_id) if res: ves = {} ves['id'] = res['_id'] ves['key'] = res['number'] vessels.append(ves) else: vessels = self.couch_query.get_vessels() else: vessel_ids = [] try: if not extracted_vessel_ids: # EMPTY vessel_ids = [] else: vessel_ids = extracted_vessel_ids.split(",") except: data["alert"] = "Invalid Vessel IDs" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) company_ids = self.get_company_id(userid) if not company_ids: data["message"] = "User Doesn't belong to any company." data['rows'] = [] data['status'] = 'ok' # RETURN ALERT return self.return_data(data) # ACCOUNT'S AVAILABLE VESSELS company_vessel_ids = self.get_company_vessels(company_ids)['rows'] #FILTER VESSELS TO GET vessels_to_get = [] if not vessel_ids: vessels_to_get = company_vessel_ids else: for vessel_id in vessel_ids: # found_vessel = None for company_vessel in company_vessel_ids: if vessel_id == company_vessel['vessel_id']: vessels_to_get.append(company_vessel) break if len(vessels_to_get) != len(vessel_ids): data["alert"] = "Some Vessel are not belong to this user." data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) temp_ids = [] for vessel_id in vessels_to_get: if vessel_id['vessel_id'] not in temp_ids: temp_ids.append(vessel_id['vessel_id']) res = self.couch_query.get_by_id(vessel_id['vessel_id']) if res: ves = {} ves['id'] = res['_id'] ves['key'] = res['number'] vessels.append(ves) # CHECK DATABASES rows = [] if vessels: vessel_ids = [x['id'] for x in vessels] # INIT SQL QUERY if len(vessel_ids) == 1: sql_str = "SELECT * FROM vessel WHERE state ='1'" sql_str += " AND vessel_id IN ('{0}')".format(vessel_ids[0]) else: sql_str = "SELECT * FROM vessel WHERE state ='1'" sql_str += " AND vessel_id IN {0}".format(tuple(vessel_ids)) # FETCH ALL vessels_state = self.postgres.query_fetch_all(sql_str) to_be_install = [x['vessel_id'] for x in vessels_state] # LOOP DATABASES for item in vessels: row = {} # GET VESSEL NAME vessel_name = self.get_vessel_name(item['id']) # self.vessel_name = vessel_name # GET LONGITUDE AND LATITUDE long_lat = self.get_long_lat(item['id']) if long_lat: # get nearest land from ocean to land google map # GET the nearest landmass # https://stackoverflow.com/questions/41539432/google-maps-reverse- # geocoding-api-returns-nearest-land-address-given-a-latlng-in row['long'] = long_lat['long'] row['lat'] = long_lat['lat'] row['position_source'] = long_lat['position_source'] else: row['long'] = 0 row['lat'] = 0 row['position_source'] = "" # GET HEADING heading, speed = self.get_heading(item['id']) if heading: row['heading'] = float(heading['heading']) row['heading_source'] = heading['heading_source'] else: row['heading_source'] = "" row['heading'] = 0 if speed: row['speed'] = float(speed) # GET UPDATE STATE last_update = self.get_last_update_with_option(item['id']) epoch_time = int(time.time()) update_state = self.check_time_lapse(epoch_time, last_update) # SET THE RETURN VALUE row['isOpen'] = False row['vessel_id'] = item['id'] row['vessel_number'] = item['key'] row['vessel_name'] = vessel_name row['company'] = self.get_vessel_company(item['id']) row['update_state'] = update_state # GET IMAGE URL row['image_url'] = self.aws3.get_vessel_image(item['id']) if item['id'] in to_be_install: row['update_state'] = 'white' rows.append(row) # SORT VESSELS ALPHABETICALLY rows = sorted(rows, key=lambda i: i['vessel_name'].upper()) # SET RETURN data['rows'] = rows data['companies'] = self.get_vessels_company() data['status'] = 'ok' # RETURN return self.return_data(data) # GET THE VESSEL NAME def get_vessel_name(self, vessel_id): """Return Vessel Name""" values = self.couch_query.get_complete_values(vessel_id, "PARAMETERS") if values: return values['PARAMETERS']['INFO']['VESSELNAME'] return '' def get_long_lat(self, vessel_id): """Return Longitude Latitude""" all_devices = self.couch_query.get_all_devices(vessel_id) devices = [] source = 'MODEM' if all_devices: devices = self.get_device(all_devices, source) devices_info = 0 if devices: devices_info = self.device_data(source, devices, vessel_id) if not devices_info: source = 'VSAT' devices = self.get_device(all_devices, source) if devices: devices_info = self.device_data(source, devices, vessel_id) if not devices_info: source = 'IOP' devices = self.get_device(all_devices, source) if devices: devices_info = self.device_data(source, devices, vessel_id) if not devices_info: source = 'NMEA' devices = self.get_device(all_devices, source) if devices: devices_info = self.device_data(source, devices, vessel_id) if not devices_info: source = 'SATC' devices = self.get_device(all_devices, source) if devices: devices_info = self.device_data(source, devices, vessel_id) if not devices_info: source = 'VHF' devices = self.get_device(all_devices, source) if devices: devices_info = self.device_data(source, devices, vessel_id) return devices_info return 0 def get_device(self, devices, pattern): """Return Device""" data = [] for device in devices: if re.findall(r'' + pattern + r'\d', device['doc']['device']): data.append(device['doc']) data = sorted(data, key=lambda i: i['device']) return data def get_heading(self, vessel_id): """Return Heading""" all_devices = self.couch_query.get_all_devices(vessel_id) source = 'VSAT' devices = self.get_device(all_devices, source) data = {} speed = 0 for device in devices: values = self.couch_query.get_complete_values( vessel_id, device['device']) if values: # GET DEVICE NUMBER number = device['device'].split(source)[1] # GET DEVICE COMPLETE NAME heading_source = self.device_complete_name(source, number) # SET RETURN data['heading'] = values[ device['device']]['General']['Heading'] data['heading_source'] = heading_source # RETURN # return [data, 0] source = 'NMEA' devices = self.get_device(all_devices, source) for device in devices: values = self.couch_query.get_complete_values( vessel_id, device['device']) if values: # GET DEVICE NUMBER number = device['device'].split(source)[1] # GET DEVICE COMPLETE NAME heading_source = self.device_complete_name(source, number) gen = values[device['device']].keys() if 'GP0001' in gen: gp0001 = values[device['device']]['GP0001'] # SET RETURN if not data: data['heading'] = gp0001['VTG'][ 'courseOverGroundTrueDegrees'] data['heading_source'] = heading_source speed = gp0001['VTG']['speedOverGroundKnots'] # RETURN return [data, speed] def get_last_update_with_option(self, vessel_id): """Return Last Update with option""" values = self.couch_query.get_complete_values(vessel_id, "COREVALUES", flag='one_doc') if values: return values['timestamp'] return '' def get_company_id(self, userid): """Return Company ID""" sql_str = "select company_id from account_company where account_id = {}".format( userid) res = self.postgres.query_fetch_all(sql_str) return res if res else 0 # GET VESSELS OF COMPANY def get_company_vessels(self, company_ids): """Return Company Vessels""" assert company_ids, "CompanyID is required." # DATA vessels = [] for company_id in company_ids: sql_str = "SELECT * FROM company_vessels" sql_str += " WHERE company_id={0}".format(company_id['company_id']) res = self.postgres.query_fetch_all(sql_str) if res: vessels = vessels + res data = {} data['rows'] = vessels return data def device_data(self, source, devices, vessel_id): """Return Device Data""" for device in devices: values = self.couch_query.get_complete_values( vessel_id, device['device']) if values: try: # GET DEVICE NUMBER number = device['device'].split(source)[1] # GET DEVICE COMPLETE NAME position_source = self.device_complete_name(source, number) # SET RETURN data = {} if source == 'NMEA': lnp = values[ device['device']]['GP0001']['GGA']['eastWest'] ltp = values[ device['device']]['GP0001']['GGA']['northSouth'] ln1 = values[ device['device']]['GP0001']['GGA']['longitude'] lt1 = values[ device['device']]['GP0001']['GGA']['latitude'] longitude = float(ln1) lat = float(lt1) lat /= 100. dec_lat, degrees_lat = math.modf(lat) dec_lat *= 100. dev_lat = degrees_lat + dec_lat / 60 longitude /= 100. dec_long, degrees_long = math.modf(longitude) dec_long *= 100. dev_long = degrees_long + dec_long / 60 data['lat'] = "%.4f" % float(dev_lat) data['long'] = "%.4f" % float(dev_long) if ltp == 'S': data['lat'] = "-" + str(data['lat']) if lnp == 'W': data['long'] = "-" + str(data['long']) elif source == 'SATC': lat_dir = values[ device['device']]['General']['latitudeDirection'] lon_dir = values[ device['device']]['General']['longitudeDirection'] lat = values[device['device']]['General']['latitude'] lon = values[device['device']]['General']['longitude'] lon_val = ''.join(lon.rsplit('.', 1)) if lon_dir == 'W': lon_val = "-" + lon_val lat_val = ''.join(lat.rsplit('.', 1)) if lat_dir == 'S': lat_val = "-" + lat_val data['long'] = lon_val data['lat'] = lat_val elif source == 'VHF': lat = values[device['device']]['General']['latitude'] lon = values[device['device']]['General']['longitude'] lon_val = str(lon[1:]) lon_val = lon_val.replace('.', '') lon_val = lon_val.replace(',', '.') if lon[0] == 'W': lon_val = "-" + lon_val lat_val = str(lat[1:]) lat_val = lat_val.replace('.', '') lat_val = lat_val.replace(',', '.') if lat[0] == 'S': lat_val = "-" + lat_val data['long'] = lon_val data['lat'] = lat_val else: data['long'] = values[ device['device']]['General']['Longitude'] data['lat'] = values[ device['device']]['General']['Latitude'] data['position_source'] = position_source # RETURN return data except: continue return 0 def get_vessel_company(self, vessel_id): """Return Company by Vessel ID""" assert vessel_id, "Vessel ID is required." data = [] sql_str = "SELECT * FROM company_vessels cv" sql_str += " LEFT JOIN company c ON cv.company_id = c.company_id" sql_str += " WHERE vessel_id='{0}'".format(vessel_id) result = self.postgres.query_fetch_all(sql_str) if result: for res in result: data.append({ 'company_id': res['company_id'], 'company_name': res['company_name'] }) return data def get_vessels_company(self): """ Return Vessel List by Company """ sql_str = "SELECT v.vessel_id, v.vessel_name, cv.company_id, c.company_name FROM vessel v" sql_str += " LEFT JOIN company_vessels cv ON v.vessel_id=cv.vessel_id" sql_str += " LEFT JOIN company c ON cv.company_id = c.company_id" sql_str += " GROUP BY v.vessel_id, cv.company_id,c.company_id" sql_str += " ORDER BY c.company_name" results = self.postgres.query_fetch_all(sql_str) data = {} if results: for result in results: if result['company_name'] is None: company = "Others" else: company = result['company_name'] formatted = [{ 'vessel_id': result['vessel_id'], 'vessel_name': result['vessel_name'] }] if company in data: data[company].append(formatted) else: data[company] = formatted return data
class CalculateOperatorResult(Common): """Class for CalculateOperatorResult""" # INITIALIZE def __init__(self): """The Constructor for CalculateOperatorResult class""" self.postgres = PostgreSQL() self.couch_query = Queries() super(CalculateOperatorResult, self).__init__() def calculate_operator_result(self, comparator, params): """Calculate Operator Result""" if len(params) == 1: for param in params: result = self.compute_operator(param, comparator) if len(params) == 2: result = self.split_params(params, comparator) if len(params) == 3: params1 = [params[0], params[1]] params2 = [params[0], params[2]] if comparator == "BETWEEN": param_result1 = self.split_params(params1, ">") param_result2 = self.split_params(params2, "<") elif comparator == "BETWEENEQ": param_result1 = self.split_params(params1, ">=") param_result2 = self.split_params(params2, "<=") elif comparator == "!BETWEEN": param_result1 = self.split_params(params1, "<") param_result2 = self.split_params(params2, ">") elif comparator == "!BETWEENQ": param_result1 = self.split_params(params1, "<=") param_result2 = self.split_params(params2, ">=") param_results = [param_result1, param_result2] result = self.split_params(param_results, "AND") return result def check_param_content(self, params): """Check Parameter Content""" temp_data = [] for param in params: if any("datas" in x for x in param) or any("result" in x for x in param): indicator = "datas" else: indicator = "input" temp_data.append({"indicator": indicator, "data": param}) return temp_data def split_params(self, params, comparator): """Split Parameters""" result = [] param_content = self.check_param_content(params) if param_content[0]['indicator'] == "input" and param_content[1][ 'indicator'] == "datas": swap = True result = self.analyze_param(params[1], params[0], comparator, swap) elif param_content[0]['indicator'] == "input" and param_content[1][ 'indicator'] == "input": if not 'No Data to Show' in params: for param1 in params[0]: for param2 in params[1]: results = self.compute_operator( param1, comparator, param2) result.append({ "value": results, "remarks": self.get_remarks(results) }) else: swap = False result = self.analyze_param(params[0], params[1], comparator, swap) return result def analyze_param(self, param1, param2, comparator, swap=None): """Analyze Parameter""" results = [] for param in param1: parameter1 = param['datas'] core = param['core'] previous_core = param['previous'] vessel_name = self.check_vessel_name(param['vessel_id']) vessel_data = self.check_vessel_number(param['vessel_id']) if len(core) > 0: if param['message'] == "ok": parameter2 = "" if any("datas" in x for x in param2): indicator = "multiple" for par2 in param2: if param['vessel_id'] == par2['vessel_id']: if len(par2['datas']) != 0: parameter2 = par2['datas'] else: indicator = "none" parameter2 = param2 if not parameter2: continue parameter = [parameter1, parameter2] # CHECK DEVICE IF FAILOVER if param['device'].upper() == "FAILOVER": result = self.compute_failover_param(parameter, comparator, swap, flag=indicator) else: result = self.compute_param(parameter, comparator, core, previous_core, swap, flag=indicator) datas = sorted(result, key=lambda i: i["timestamp"]) else: datas = [{ "timestamp": previous_core['timestamp'], "value": previous_core['remarks'], "remarks": self.get_remarks(param['message']) }] results.append({ "vessel_id": param['vessel_id'], "vessel_name": vessel_name, "vessel_number": vessel_data, "device": param['device'], "device_id": param['device_id'], "core": param['core'], "previous": previous_core, "message": param['message'], "module": param['module'], "option": param['option'], "datas": datas }) else: datas = [{ "timestamp": previous_core['timestamp'], "value": previous_core['remarks'], "remarks": self.get_remarks(previous_core['remarks']) }] results.append({ "vessel_id": param['vessel_id'], "vessel_name": vessel_name, "vessel_number": vessel_data, "device": param['device'], "device_id": param['device_id'], "core": param['core'], "previous": previous_core, "message": previous_core['remarks'], "module": param['module'], "option": param['option'], "datas": datas }) return results def compute_param(self, params, comparator, cores, prevcore, swap=None, flag=None): """Compute Parameter""" results = [] param1 = params[0] param2 = params[1] for core in cores: if not param1: res = "" if prevcore['remarks'] in ['Unknown', 'ok']: remarks = "Unknown" else: remarks = "No Data" results.append({ "timestamp": core, "value": res, "remarks": self.get_remarks(remarks) }) else: parameter1 = [param['timestamp'] for param in param1] try: check_param1 = parameter1.index(core) timestamp = param1[check_param1]['timestamp'] val1 = param1[check_param1]['value'] if flag == "multiple": parameter2 = [p['timestamp'] for p in param2] try: check_param2 = parameter2.index(core) val2 = param2[check_param2]['value'] if swap is True: res = self.compute_operator( val2, comparator, val1) else: res = self.compute_operator( val1, comparator, val2) except ValueError: res = "Unknown" else: if not param2: res = "Unknown" else: for par2 in param2: val2 = self.check_data_type(par2) if swap is True: res = self.compute_operator( val2, comparator, val1) else: res = self.compute_operator( val1, comparator, val2) results.append({ "timestamp": timestamp, "value": res, "remarks": self.get_remarks(res) }) except ValueError: res = "Unknown" results.append({ "timestamp": core, "value": res, "remarks": "Unknown" }) return results def get_remarks(self, data): """Get Remarks""" if data is True: return "red" if data is False: return "green" if data == "Unknown": return "orange" if data == "No Data": return "blue" return "violet" def check_data_type(self, data): """Check Data Type""" try: if data in ['True', 'False']: formatted = eval(data) elif data.lstrip("-").isdigit(): formatted = float(int(data)) else: formatted = float(data) return formatted except ValueError: return data def check_vessel_name(self, vessel_id): """Check Vessel Name""" if vessel_id: vessel_name = self.couch_query.get_complete_values( vessel_id, "PARAMETERS") if vessel_name: return vessel_name['PARAMETERS']['INFO']['VESSELNAME'] return "Vessel Not Found" return 0 def check_vessel_number(self, vessel_id): """Check Vessel Number""" data = self.couch_query.get_by_id(vessel_id) if data: if "error" in data: return "No Data Found" return data['number'] return "No Data Found" def compute_failover_param(self, params, comparator, swap=None, flag=None): """Compute Failover Parameter""" results = [] param1 = params[0] param2 = params[1] for param in param1: timestamp = param['timestamp'] if param['value'] is None: res = "Unknown" else: val1 = self.check_data_type(param['value']) if flag == "multiple": parameter2 = [p['timestamp'] for p in param2] try: check_param2 = parameter2.index(param) val2 = self.check_data_type( param2[check_param2]['value']) if swap is True: res = self.compute_operator(val2, comparator, val1) else: res = self.compute_operator(val1, comparator, val2) except ValueError: res = "Unknown" else: if not param2: res = "Unknown" else: for par2 in param2: val2 = self.check_data_type(par2) if swap is True: res = self.compute_operator( val2, comparator, val1) else: res = self.compute_operator( val1, comparator, val2) results.append({ "timestamp": timestamp, "value": res, "remarks": self.get_remarks(res) }) return results
class UpdateCompany(Common): """Class for UpdateCompany""" # INITIALIZE def __init__(self): """The Constructor for UpdateCompany class""" self.postgres = PostgreSQL() self._couch_db = CouchDatabase() self.couch_query = Queries() self.log = Log() super(UpdateCompany, self).__init__() def update_company(self): """ This API is for Updating Company --- tags: - Company produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: query in: body description: Updating Company required: true schema: id: Updating Company properties: company_id: type: string company_name: type: string vessel_ids: types: array example: [] responses: 500: description: Error 200: description: Updating Company """ data = {} # GET JSON REQUEST query_json = request.get_json(force=True) # GET HEADER token = request.headers.get('token') userid = request.headers.get('userid') # GET COMPANY_ID company_id = query_json.get('company_id') vessel_ids = query_json.get('vessel_ids') del query_json['vessel_ids'] # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) vessel_ids = self.check_vessel_existence(vessel_ids) if not self.update_companies(query_json): data["alert"] = "Please check your query! , Company update FAILED." data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) # GET CURRENT VESSELS ID # current_vessels = self.get_current_vessels(company_id) # removed_vessel, added_vessel = self.set_vessels_data(current_vessels, vessel_ids) self.get_users(company_id) # self.update_users_vessel(user_ids, removed_vessel, added_vessel) # DELETE CURRENT VESSELS if not self.delete_current_vessels(company_id): data["alert"] = "Problem in updating the vessels." data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) if len(vessel_ids) > 0: #INSERT NEW VESSELS if not self.add_vessels(company_id, vessel_ids): data["alert"] = "Problem in updating the vessels." data['status'] = "Failed" # RETURN ALERT return self.return_data(data) data['message'] = "Company successfully updated!" data['status'] = "ok" return self.return_data(data) def update_companies(self, query_json): """Update Companies""" query_json['update_on'] = time.time() conditions = [] conditions.append({ "col": "company_id", "con": "=", "val": query_json['company_id'] }) data = self.remove_key(query_json, "company_id") if self.postgres.update('company', data, conditions): return 1 return 0 def check_vessel_existence(self, vessel_ids): """Check Vessel Existence""" ids = [] for _id in vessel_ids: res = self.couch_query.get_by_id(_id) if res.get('_id', False): ids.append(_id) return ids def delete_current_vessels(self, company_id): """Delete Current Vessels""" status = False try: conditions = [] conditions.append({ "col": "company_id", "con": "=", "val": company_id }) if self.postgres.delete('company_vessels', conditions): status = True except Exception as error: self.log.critical(error) status = False return status def add_vessels(self, company_id, vessel_ids): """Add Vessels""" status = '' for vessel_id in vessel_ids: data = {} data['company_id'] = company_id data['vessel_id'] = vessel_id try: self.postgres.insert('company_vessels', data, 'company_id') status = 'ok' except Exception as err: self.log.critical(err) status = 'Failed' return status # def get_current_vessels(self, company_id): # sql_str = "SELECT * FROM company_vessels" # sql_str += " WHERE company_id={0}".format(company_id) # rows = self.postgres.query_fetch_all(sql_str) # if rows: # return [x['vessel_id'] for x in rows] # return [] # def set_vessels_data(self, current_vessels, vessel_ids): # current_vessels = set(current_vessels) # vessel_ids = set(vessel_ids) # rep_current_vessels = current_vessels.copy() # rep_vessel_ids = vessel_ids.copy() # rep_vessel_ids.difference_update(current_vessels) # rep_current_vessels.difference_update(vessel_ids) # return [rep_current_vessels, rep_vessel_ids] def get_users(self, company_id): """Get Users""" sql_str = "SELECT * FROM account_company WHERE company_id={0}".format(company_id) rows = self.postgres.query_fetch_all(sql_str) if rows: for row in rows: # INIT CONDITION conditions = [] # CONDITION FOR QUERY conditions.append({ "col": "id", "con": "=", "val": row['account_id'] }) updates = {} updates['vessel_vpn_state'] = 'pending' # UPDATE VESSEL VPN STATE self.postgres.update('account', updates, conditions) return [x['account_id'] for x in rows] return []
class Device(Common): """Class for Device""" # INITIALIZE def __init__(self): """The Constructor for Device class""" # INIT CONFIG self.config = ConfigParser() # CONFIG FILE self.config.read("config/config.cfg") self._couch_db = CouchDatabase() self.couch_query = Queries() self.aws3 = AwsS3() self.epoch_default = 26763 self.db_host = config_section_parser(self.config, "COUCHDB")['host'] self.db_port = config_section_parser(self.config, "COUCHDB")['port'] super(Device, self).__init__() # GET VESSEL FUNCTION def device_list(self): """ This API is for Getting Vessel Device List --- tags: - Devices produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: vessel_id in: query description: Vessel ID required: true type: string - name: device_id in: query description: Device ID required: false type: string - name: date in: query description: Epoch date required: false type: string responses: 500: description: Error 200: description: Vessel Device List """ # VESSEL ID vessel_id = request.args.get('vessel_id') device_id = request.args.get('device_id') epoch_date = request.args.get('date') # dbs = [] # GET DATA token = request.headers.get('token') userid = request.headers.get('userid') device_list = [] # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data = {} data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) if not vessel_id: data = {} data["alert"] = "No Vessel ID" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) if device_id: value = self.couch_query.get_by_id(device_id) device_list.append(value) else: device_list = self.couch_query.get_device(vessel_id) if epoch_date in ["null", "0", "NaN"]: epoch_date = False # REMOVE DATA data_to_remove = ['PARAMETERS', 'COREVALUES', 'FAILOVER', 'NTWCONF'] device_list = self.remove_data(device_list, data_to_remove) device_info = {} parameters = self.couch_query.get_complete_values( vessel_id, "PARAMETERS") final_data = [] for device in device_list: current_time = time.time() device_type = parameters['PARAMETERS'][device['device']]['TYPE'] row = {} vsat_antenna = {} data_id = "" if device_type in ['Catalyst_2960', 'Catalyst_3750']: device_port, general, all_data, data_id = self.get_switch( vessel_id, device['device'], epoch_date) row['ports'] = device_port row['general'] = general row['device'] = device['device'] row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] elif device_type in ['Sentry3', 'Raritan_PX2']: outlet_status, all_data, data_id = self.get_power_s( vessel_id, device['device'], epoch_date) row['outlet_status'] = outlet_status row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] gen_data = all_data['value'][device['device']]['General'] if device_type == 'Sentry3': infeed_load_value = gen_data['infeedLoadValue'] infeed_power = gen_data['infeedPower'] row['infeed_load_value'] = str(infeed_load_value) + " A" row['infeed_power'] = str(infeed_power) + " W" if device_type == 'Raritan_PX2': pdu_inlet_currentval = "" if gen_data['pduInletCurrent']: pdu_inlet_currentval = float( gen_data['pduInletCurrent']) / 10 pdu_inlet_current = pdu_inlet_currentval pdu_inlet_voltage = gen_data['pduInletVoltage'] pdu_power = ['pduPower'] row['pdu_inlet_current'] = pdu_inlet_current row['pdu_line_frequency'] = 'L1' # pduLineFrequency row['pdu_inlet_voltage'] = pdu_inlet_voltage row['pdu_power'] = pdu_power row['device'] = device['device'] elif device_type == 'IOP': iop_info, all_data, data_id = self.get_iop( vessel_id, device['device'], epoch_date) row['info'] = iop_info row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] row['device'] = device['device'] elif device_type in [ 'Intellian_V80_E2S', 'Intellian_V100_E2S', 'Intellian_V110_E2S', 'Intellian_V80_IARM', 'Intellian_V100_IARM', 'Intellian_V110_IARM', 'Intellian_V100', 'Intellian_V110', 'Sailor_900' ]: general, all_data, data_id = self.get_vsat( vessel_id, device['device'], epoch_date) row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] row['device'] = device['device'] row['general'] = general vsat_antenna = self.get_vsat_azimuth(row['general'], device_type) elif device_type in ['Evolution_X5', 'Evolution_X7']: value, all_data, data_id = self.defaul_data( vessel_id, device['device']) row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] row['device'] = device['device'] row['general'] = value[device['device']]['General'] elif device_type in ['Cisco_SNMP']: device_port, general, all_data, data_id = self.get_cis_snmp( vessel_id, device['device'], epoch_date) row['ports'] = device_port row['general'] = general row['device'] = device['device'] row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] elif device_type in ['Sailor_3027C']: general, all_data, data_id = self.get_sailors_30xxx( vessel_id, device['device'], epoch_date) row['general'] = general row['device'] = device['device'] row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] elif device_type in ['Sailor_62xx']: general, all_data, data_id = self.get_sailor_62xx( vessel_id, device['device'], epoch_date) row['general'] = general row['device'] = device['device'] row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] elif device_type in ['Sailor_6103']: general, all_data, data_id = self.get_sailor_6103( vessel_id, device['device'], epoch_date) row['general'] = general row['device'] = device['device'] row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] elif device_type in ['Cobham_500']: value, all_data, data_id = self.defaul_data( vessel_id, device['device']) row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] row['device'] = device['device'] row['general'] = value[device['device']]['General'] _, all_data, data_id = self.defaul_data(vessel_id, device['device']) row['description'] = "" if 'DESCRIPTION' in parameters['PARAMETERS'][ device['device']].keys(): row['description'] = parameters['PARAMETERS'][ device['device']]['DESCRIPTION'] row['device'] = device['device'] if row: data_url = str(self.db_host) + ":" + str(self.db_port) data_url += "/_utils/#database/vessels_db/" + str(data_id) row['status'] = self.check_time_lapse(current_time, all_data['timestamp']) row['device_type'] = device_type row['device_id'] = device['_id'] row['vessel_id'] = vessel_id row['vsat_antenna'] = vsat_antenna row['data_url'] = data_url row['image_url'] = self.aws3.get_device_image( vessel_id, device['_id']) final_data.append(row) device_info['status'] = 'ok' device_info['data'] = final_data return self.return_data(device_info) def get_iop(self, vessel_id, device, epoch_date): """Return IOP""" if epoch_date: data = self.couch_query.get_complete_values( vessel_id, device, str(self.epoch_default), str(epoch_date), flag='one_doc') else: data = self.couch_query.get_complete_values(vessel_id, device, flag='one_doc') value = data['value'] data_id = data['_id'] iop_info = {} iop_info['status'] = value[device]['General']['Status'] iop_info['signal'] = value[device]['General']['Signal'] iop_info['gps'] = value[device]['General']['GPS'] iop_info['data'] = value[device]['General']['Data'] iop_info['handset1'] = value[device]['General']['Handset1'] iop_info['handset2'] = value[device]['General']['Handset2'] iop_info['handset3'] = value[device]['General']['Handset3'] return [iop_info, data, data_id] def get_power_s(self, vessel_id, device, epoch_date): """Return Power Switch""" if epoch_date: data = self.couch_query.get_complete_values( vessel_id, device, str(self.epoch_default), str(epoch_date), flag='one_doc') else: data = self.couch_query.get_complete_values(vessel_id, device, flag='one_doc') value = data['value'] data_id = data['_id'] device_outlets = [] for i in range(1, 9): temp_device_outlets = {} temp_device_outlets['name'] = 'outlet' + str(i) if ('outlet' + str(i)) in value[device].keys(): temp_device_outlets['value'] = value[device]['outlet' + str(i)]['status'] else: temp_device_outlets['value'] = None device_outlets.append(temp_device_outlets) return [device_outlets, data, data_id] def get_sailor_6103(self, vessel_id, device, epoch_date): """Return Sailor 6103""" if epoch_date: data = self.couch_query.get_complete_values( vessel_id, device, str(self.epoch_default), str(epoch_date), flag='one_doc') else: data = self.couch_query.get_complete_values(vessel_id, device, flag='one_doc') value = data['value'][device] data_id = data['_id'] del value['General'] gen = {} for key in value.keys(): gen[key] = "" if not value[key]['IP'] == "0.0.0.0": gen[key] = value[key]['IP'] return [gen, data, data_id] def get_sailors_30xxx(self, vessel_id, device, epoch_date): """Return Sailor 3027C""" if epoch_date: data = self.couch_query.get_complete_values( vessel_id, device, str(self.epoch_default), str(epoch_date), flag='one_doc') else: data = self.couch_query.get_complete_values(vessel_id, device, flag='one_doc') value = data['value'] data_id = data['_id'] lat_dir = value[device]['General']['latitudeDirection'] lon_dir = value[device]['General']['longitudeDirection'] lat = value[device]['General']['latitude'] lon = value[device]['General']['longitude'] lon_val = ''.join(lon.rsplit('.', 1)) if lon_dir == 'W': lon_val = "-" + lon_val lat_val = ''.join(lat.rsplit('.', 1)) if lat_dir == 'S': lat_val = "-" + lat_val gen = {} gen['currentProtocol'] = value[device]['General']['currentProtocol'] gen['currentOceanRegion'] = value[device]['General'][ 'currentOceanRegion'] gen['latitude'] = self.position_converter(lat_val) gen['longitude'] = self.position_converter(lon_val) gen['latitudeDirection'] = lat_dir gen['longitudeDirection'] = lon_dir return [gen, data, data_id] def position_converter(self, val): """ POSITION CONVERTER """ absolute = abs(float(val)) degrees = math.floor(absolute) minutes_not_truncated = (absolute - degrees) * 60 minutes = math.floor(minutes_not_truncated) seconds = math.floor((minutes_not_truncated - minutes) * 60) return str(degrees) + "." + str(minutes) + "." + str(seconds) def get_sailor_62xx(self, vessel_id, device, epoch_date): """Return Sailor 62xx""" if epoch_date: data = self.couch_query.get_complete_values( vessel_id, device, str(self.epoch_default), str(epoch_date), flag='one_doc') else: data = self.couch_query.get_complete_values(vessel_id, device, flag='one_doc') value = data['value'] data_id = data['_id'] gen = {} gen['currentChDesc'] = value[device]['General']['currentChDesc'] gen['currentCh'] = value[device]['General']['currentCh'] gen['transmitMode'] = value[device]['General']['transmitMode'] return [gen, data, data_id] def get_switch(self, vessel_id, device, epoch_date): """Return Switch""" if epoch_date: data = self.couch_query.get_complete_values( vessel_id, device, str(self.epoch_default), str(epoch_date), flag='one_doc') else: data = self.couch_query.get_complete_values(vessel_id, device, flag='one_doc') value = data['value'] data_id = data['_id'] device_port = [] keys = value[device].keys() for i in range(1, (len(keys))): temp_device_port = {} port = 'Fa0/' + str(i) if port in keys: temp_device_port['name'] = port temp_device_port['value'] = value[device][port]['status'] device_port.append(temp_device_port) for i in range(1, 3): temp_device_port = {} port = 'Gi0/' + str(i) if port in keys: temp_device_port['name'] = port temp_device_port['value'] = value[device][port]['status'] device_port.append(temp_device_port) gen = {} gen['port'] = value[device]['General']['port'] gen['serial'] = value[device]['General']['SerialNumber'] gen['mac'] = value[device]['General']['MacAddress'] gen['model'] = value[device]['General']['ModelNumber'] return [device_port, gen, data, data_id] def get_cis_snmp(self, vessel_id, device, epoch_date): """Return Switch""" if epoch_date: data = self.couch_query.get_complete_values( vessel_id, device, str(self.epoch_default), str(epoch_date), flag='one_doc') else: data = self.couch_query.get_complete_values(vessel_id, device, flag='one_doc') value = data['value'] data_id = data['_id'] device_port = [] keys = value[device].keys() for i in range(1, (len(keys))): temp_device_port = {} port = 'fa' + str(i) if port in keys: temp_device_port['name'] = port temp_device_port['value'] = value[device][port]['ifOperStatus'] device_port.append(temp_device_port) for i in range(1, (len(keys))): temp_device_port = {} port = 'gi' + str(i) if port in keys: temp_device_port['name'] = port temp_device_port['value'] = value[device][port]['ifOperStatus'] device_port.append(temp_device_port) gen = {} for gen_key in value[device]['General'].keys(): gen[gen_key] = value[device]['General'][gen_key] return [device_port, gen, data, data_id] def get_vsat(self, vessel_id, device, epoch_date): """Return VSAT""" if epoch_date: data = self.couch_query.get_complete_values( vessel_id, device, str(self.epoch_default), str(epoch_date), flag='one_doc') else: data = self.couch_query.get_complete_values(vessel_id, device, flag='one_doc') value = data['value'] data_id = data['_id'] return [value[device]['General'], data, data_id] def defaul_data(self, vessel_id, device): """Return Default Data""" data = self.couch_query.get_complete_values(vessel_id, device, flag='one_doc') value = data['value'] data_id = data['_id'] return [value, data, data_id] def get_vsat_azimuth(self, general, device_type): """Return VSAT Azimuth and Elevation Value""" data = {} if device_type in [ 'Intellian_V80_E2S', 'Intellian_V100_E2S', 'Intellian_V110_E2S', 'Intellian_V80_IARM', 'Intellian_V100_IARM', 'Intellian_V110_IARM', 'Intellian_V100', 'Intellian_V110', 'Sailor_900' ]: azimuth = [] elev = [] heading = None target_azimuth = None relative_az = None abosulte_az = None if 'Heading' in general: heading = general['Heading'] if 'TargetAzimuth' in general: target_azimuth = general['TargetAzimuth'] if 'RelativeAz' in general: relative_az = general['RelativeAz'] if 'AbsoluteAz' in general: abosulte_az = general['AbsoluteAz'] azimuth.append({ "Heading": heading, "TargetAzimuth": target_azimuth, "RelativeAz": relative_az, "AbsoluteAz": abosulte_az }) elevation = None target_elevation = None if 'Elevation' in general: elevation = general['Elevation'] if 'TargetElevation' in general: target_elevation = general['TargetElevation'] elev.append({ "Elevation": elevation, "TargetElevation": target_elevation }) data['azimuth'] = azimuth data['elevation'] = elev return data
class Graph(Common): """Class for Graph""" # INITIALIZE def __init__(self): """The Constructor for Graph class""" self.postgres = PostgreSQL() self._couch_db = CouchDatabase() self.couch_query = Queries() super(Graph, self).__init__() def graph(self): """ This API is for Getting Graph --- tags: - Graph produces: - application/json parameters: - name: token in: header description: Token required: true type: string - name: userid in: header description: User ID required: true type: string - name: vessel_id in: query description: Vessel ID required: true type: string - name: device_id in: query description: Device ID required: true type: string - name: hours in: query description: Hours required: false type: integer - name: keys in: query description: Keys required: true type: string - name: combine in: query description: combine required: true type: boolean - name: start_time in: query description: Epoch start required: false type: string - name: end_time in: query description: Epoch end required: false type: string responses: 500: description: Error 200: description: Vessel Device Info """ data = {} # VESSEL ID vessel_id = request.args.get('vessel_id') device_id = request.args.get('device_id') keys = request.args.get('keys') combine = request.args.get('combine') hours = request.args.get('hours') start_time = request.args.get('start_time') end_time = request.args.get('end_time') # GET DATA token = request.headers.get('token') userid = request.headers.get('userid') # CHECK TOKEN token_validation = self.validate_token(token, userid) if not token_validation: data["alert"] = "Invalid Token" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) if not vessel_id: data["alert"] = "Please complete parameters!" data['status'] = 'Failed' # RETURN ALERT return self.return_data(data) if device_id in ['COREVALUES', 'FAILOVER', 'NTWPERF1']: all_devices = self.couch_query.get_all_devices(vessel_id) for dev in all_devices: if dev['doc']['device'] == device_id: device = dev['doc'] break else: device = self.couch_query.get_by_id(device_id) # hours_ago_epoch_ts = int(hours_ago.timestamp()) # current_time = int(ctime.timestamp()) if not start_time and not end_time: ctime = datetime.datetime.now() hours_ago = ctime - datetime.timedelta(hours=int(hours)) start_time = int(hours_ago.timestamp()) end_time = int(ctime.timestamp()) values = self.couch_query.get_complete_values( vessel_id, device['device'], str(start_time), str(end_time), 'all' ) # temp_available_options = [] # str_available_options = [] # available_options = [] opt = [] parameters = self.couch_query.get_complete_values( vessel_id, "PARAMETERS" ) if device['device'] == "COREVALUES": device_type = "COREVALUES" elif device['device'] == "NTWPERF1": device_type = "NTWPERF1" elif device['device'] == 'FAILOVER': device_type = 'FAILOVER' else: device_type = parameters['PARAMETERS'][device['device']]['TYPE'] if combine.upper() == 'TRUE': final_data = [] for value in values: timestamp = float(value['timestamp']) dev_value = value['value'][device['device']] # if re.findall(r'VDR\d', device['device']): # print("ALP ", dev_value) # pass if re.findall(r'NMEA\d', device['device']): nmea_data = self.get_nmea_data(dev_value) opt = list(set(self.get_graph_options(nmea_data))) options = self.get_device_options(nmea_data) if keys: final_data.append(self.set_values(options, keys, timestamp)) else: opt = list(set(self.get_graph_options(dev_value))) options = self.get_device_options(dev_value) if keys: final_data.append(self.set_values(options, keys, timestamp)) final_data = sorted(final_data, key=lambda i: i['name']) for fdata in final_data: fdata['name'] = time.strftime('%d/%m/%Y %H:%M:%S', time.localtime( float(fdata['name']))) data['data'] = final_data data['statistics'] = self.get_stat(final_data, flag=True) else: # FINAL DATA fnl_data = {} # SET DYNAMIC VARIABLE if keys: for key in keys.split(","): fnl_data[key] = [] for value in values: timestamp = float(value['timestamp']) dev_value = value['value'][device['device']] # if re.findall(r'VDR\d', device['device']): # print("ALP ", dev_value) # pass if re.findall(r'NMEA\d', device['device']): nmea_data = self.get_nmea_data(dev_value) opt = list(set(self.get_graph_options(nmea_data))) options = self.get_device_options(nmea_data) for key in keys.split(","): fnl_data[key].append(self.set_values(options, key, timestamp)) else: opt = list(set(self.get_graph_options(dev_value))) options = self.get_device_options(dev_value) for key in keys.split(","): fnl_data[key].append(self.set_values(options, key, timestamp)) for key in keys.split(","): fnl_data[key] = sorted(fnl_data[key], key=lambda i: i['name']) for fdata in fnl_data[key]: fdata['name'] = time.strftime('%d/%m/%Y %H:%M:%S', time.localtime(float( fdata['name']))) data['data'] = fnl_data data['statistics'] = self.get_stat(fnl_data, flag=False) # SET SQL QUERY sql_str = "SELECT * FROM selected_label" sql_str += " WHERE device_type='{0}' and select_type != 'combine'".format(device_type) default_selected = self.postgres.query_fetch_all(sql_str) # SET SQL QUERY sql_str = "SELECT * FROM selected_label" sql_str += " WHERE device_type='{0}' and select_type = 'combine'".format(device_type) default_selected_combine = self.postgres.query_fetch_all(sql_str) data['default_selected_combine'] = self.set_select_values(default_selected_combine) data['default_selected'] = self.set_select_values(default_selected) data['available_options'] = self.format_filter(opt) data['status'] = 'ok' return self.return_data(data) def set_values(self, options, keys, timestamp): """Set Values""" temp_data = {} for key in keys.split(","): if key in options.keys(): if key in ['AntennaStatus', 'TxMode']: if options[key].upper() in ['TRACKING', 'ON']: temp_data[key] = 1 else: temp_data[key] = 0 elif key == 'error': if options[key] is True: temp_data[key] = 1 else: temp_data[key] = 0 else: temp_data[key] = options[key] else: temp_data[key] = None temp_data['name'] = timestamp return temp_data def get_available_options(self, options, temp_available_options, str_available_options): """Return Available Options""" # print("Options --------------------------- >>") # print(options) # print("Options --------------------------- >>") available_options = [] for opt in options.keys(): if opt not in temp_available_options and opt not in str_available_options: if not options[opt]: continue if type(options[opt]) == 'str': if options[opt].isdigit(): options[opt] = float(options[opt]) if self.isfloat(options[opt]) or self.isint(options[opt]) or opt in [ 'AntennaStatus', 'TxMode']: temp_available_options.append(opt) temp = {} temp['value'] = opt temp['label'] = opt available_options.append(temp) # else: # str_available_options.append(op) return available_options def get_nmea_data(self, datas): """ Return NMEA Data """ temp_data = {} # keys = [data for data in datas.keys()] # No need for key in list(datas.keys()): temp_data.update(datas[key]) return temp_data def get_graph_options(self, datas): """Return Options for Graph""" options = [] # modules = [data for data in datas] # No need for mod in list(datas): options += self.get_opt_available(datas[mod]) return options def get_opt_available(self, options): """Return Available Options""" available_options = [] for opt in options.keys(): if not options[opt]: continue if type(options[opt]) == 'str': if options[opt].isdigit(): options[opt] = float(options[opt]) if self.isfloat(options[opt]) or self.isint(options[opt]) or opt in [ 'AntennaStatus', 'TxMode']: available_options.append(opt) return available_options def get_device_options(self, datas): """ Return All Device Options Data """ tmp = [] temp = {} # modules = [data for data in datas] # No need for mod in list(datas): tmp.append(datas[mod]) for dta in tmp: temp.update(dta) return temp def set_select_values(self, datas): """Set Select Values""" final_data = [] for data in datas: temp = {} temp['value'] = data['label'] temp['label'] = data['label'] final_data.append(temp) return final_data def get_stat(self, datas, flag): """ Return Min and Max """ temp = {} tmp = [] if datas: if flag is True: temp_data = {} for data in datas[0].keys(): if data != "name": temp_data[data] = tuple(dta[data] for dta in datas) # keys = [data for data in temp_data.keys()] # for key in keys: # if all(res is None for res in temp_data[key]): # pass # else: # data = self.get_stat_range(temp_data, key) # temp.update({ # key : data # }) for dta in temp_data.values(): tmp += dta if tmp: tmp = [dta for dta in tmp if dta is not None] tmp = sorted(tmp, key=float) data = self.get_stat_range(tmp) temp.update({ "combine" : data }) else: # keys = [data for data in datas.keys()] for key in list(datas.keys()): result = [data[key] for data in datas[key] if data[key] is not None] result = sorted(result, key=float) # if all(res is None for res in result): # pass # else: if result: data = self.get_stat_range(result) temp.update({ key : data }) return temp def get_stat_range(self, data): """ Return Stat Range """ tmp = {} tmp['min'] = data[0] tmp['max'] = data[-1] # tmp['min'] = min(data) # tmp['max'] = max(data) return tmp