diff --git a/.gitignore b/.gitignore index d47ebfb6..be347234 100644 --- a/.gitignore +++ b/.gitignore @@ -104,4 +104,5 @@ Projects/LRF_Server/Debug/* Projects/LRF_Server/Release/* Projects/argus/Release/* Projects/LRF_ServerSlim/Debug_MASTER -Projects/LRF_ServerSlim/Debug_MASTER/* \ No newline at end of file +Projects/LRF_ServerSlim/Debug_MASTER/* +Projects/la_mojo/Debug/* \ No newline at end of file diff --git a/Linux_Workspace.vpw b/Linux_Workspace.vpw index 78bcb1c9..905fef46 100644 --- a/Linux_Workspace.vpw +++ b/Linux_Workspace.vpw @@ -3,6 +3,7 @@ + diff --git a/Projects/argus/argus.vpj b/Projects/argus/argus.vpj index 1c0973c3..143c8a39 100644 --- a/Projects/argus/argus.vpj +++ b/Projects/argus/argus.vpj @@ -301,7 +301,6 @@ - @@ -310,6 +309,7 @@ + diff --git a/Projects/argus/file12 b/Projects/argus/file12 new file mode 100644 index 00000000..c074f875 --- /dev/null +++ b/Projects/argus/file12 @@ -0,0 +1,300 @@ +# Allow password authentication? +openssh-server openssh-server/password-authentication boolean true +# Time zone: +# Choices: Casey, Davis, Dumont d'Urville, Macquarie, Mawson, McMurdo (South Pole), Palmer, Rothera, Syowa, Troll, Vostok +tzdata tzdata/Zones/Antarctica select +# Do you want to add the group ? +base-passwd base-passwd/group-add boolean true +# Enable bitmapped fonts by default? +fontconfig-config fontconfig/enable_bitmaps boolean false +# What do you want to do about modified configuration file ? +# Choices: install the package maintainer's version, keep the local version currently installed, show the differences between the versions, show a side-by-side difference between the versions, start a new shell to examine the situation +ucf ucf/changeprompt select keep_current +# xscreensaver and xlockmore must be restarted before upgrading +libpam-modules libpam-modules/disable-screensaver error +# Local SSL certificates must be replaced +ssl-cert make-ssl-cert/vulnerable_prng note +# Alternative name(s): +ssl-cert make-ssl-cert/altname string +# Time zone: +# Choices: Alaska, Aleutian, Arizona, Central, Eastern, Hawaii, Starke County (Indiana), Michigan, Mountain, Pacific Ocean, Samoa +tzdata tzdata/Zones/US select +# Time zone: +# Choices: Apia, Auckland, Bougainville, Chatham, Chuuk, Easter, Efate, Enderbury, Fakaofo, Fiji, Funafuti, Galapagos, Gambier, Guadalcanal, Guam, Honolulu, Johnston, Kiritimati, Kosrae, Kwajalein, Majuro, Marquesas, Midway, Nauru, Niue, Norfolk, Noumea, Pago Pago, Palau, Pitcairn, Pohnpei, Pohnpei, Port Moresby, Rarotonga, Saipan, Samoa, Tahiti, Tarawa, Tongatapu, Truk, Wake, Wallis, Yap +tzdata tzdata/Zones/Pacific select +# Font size: +# Choices: 8x13, 8x14, 8x15, 8x16, 8x18 +console-setup console-setup/fontsize-fb47 select 8x16 +# for internal use +keyboard-configuration keyboard-configuration/modelcode string pc105 +# Trust new certificates from certificate authorities? +# Choices: yes, no, ask +ca-certificates ca-certificates/trust_new_crts select yes +# Important note for NIS/YP users +mariadb-server-10.3 mariadb-server-10.3/nis_warning note +# Geographic area: +# Choices: Africa, America, Antarctica, Australia, Arctic Ocean, Asia, Atlantic Ocean, Europe, Indian Ocean, Pacific Ocean, System V timezones, US, None of the above +tzdata tzdata/Areas select Europe +# What do you want to do about modified configuration file ? +# Choices: install the package maintainer's version, keep the local version currently installed, show the differences between the versions, show a side-by-side difference between the versions, show a 3-way difference between available versions, do a 3-way merge between available versions, start a new shell to examine the situation +ucf ucf/changeprompt_threeway select keep_current +# Services to restart to make them use the new libraries: +libssl1.1 libssl1.1/restart-services string +libssl1.1:armhf libssl1.1/restart-services string +# Time zone: +# Choices: Amsterdam, Andorra, Astrakhan, Athens, Belfast, Belgrade, Berlin, Bratislava, Brussels, Bucharest, Budapest, Büsingen, Chisinau, Copenhagen, Dublin, Gibraltar, Guernsey, Helsinki, Isle of Man, Istanbul, Jersey, Kaliningrad, Kiev, Kirov, Lisbon, Ljubljana, London, Luxembourg, Madrid, Malta, Mariehamn, Minsk, Monaco, Moscow, Nicosia, Oslo, Paris, Podgorica, Prague, Riga, Rome, Samara, San Marino, Sarajevo, Saratov, Simferopol, Skopje, Sofia, Stockholm, Tallinn, Tirane, Tiraspol, Ulyanovsk, Uzhgorod, Vaduz, Vatican, Vienna, Vilnius, Volgograd, Warsaw, Zagreb, Zaporozhye, Zurich +tzdata tzdata/Zones/Europe select London +# Do you want to remove the user ? +base-passwd base-passwd/user-remove boolean true +# for internal use +console-setup console-setup/codesetcode string Lat15 +# Method for temporarily toggling between national and Latin input: +# Choices: No temporary switch, Both Logo keys, Right Alt (AltGr), Right Logo key, Left Alt, Left Logo key +keyboard-configuration keyboard-configuration/switch select No temporary switch +# Restart services during package upgrades without asking? +libc6 libraries/restart-without-asking boolean false +libc6:armhf libraries/restart-without-asking boolean false +libpam0g libraries/restart-without-asking boolean false +libpam0g:armhf libraries/restart-without-asking boolean false +# Do you want to change the GID of group ? +base-passwd base-passwd/group-change-gid boolean true +# Configure smb.conf automatically? +samba-common samba-common/do_debconf boolean true +# Keep default keyboard layout ()? +keyboard-configuration keyboard-configuration/unsupported_layout boolean true +# Do you want to change the GECOS of user ? +base-passwd base-passwd/user-change-gecos boolean true +# Font size: +# Choices: +console-setup console-setup/fontsize-text47 select 8x16 +# Create the TUN/TAP device? +openvpn openvpn/create_tun boolean false +# E-mail address(es) which will receive changes: +apt-listchanges apt-listchanges/email-address string root +# Time zone: +# Choices: Adak, Anchorage, Anguilla, Antigua, Araguaina, Buenos Aires (Argentina), Catamarca (Argentina), Cordoba (Argentina), Jujuy (Argentina), La Rioja (Argentina), Mendoza (Argentina), Rio Gallegos (Argentina), Salta (Argentina), San Juan (Argentina), San Luis (Argentina), Tucuman (Argentina), Ushuaia (Argentina), Aruba, Asuncion, Atikokan, Atka, Bahia, Bahia_Banderas, Barbados, Belem, Belize, Blanc-Sablon, Boa Vista, Bogota, Boise, Cambridge Bay, Campo Grande, Cancun, Caracas, Cayenne, Cayman, Chicago, Chihuahua, Coral Harbour, Costa Rica, Creston, Cuiaba, Curaçao, Danmarkshavn, Dawson, Dawson Creek, Denver, Detroit, Dominica, Edmonton, Eirunepe, El Salvador, Ensenada, Fort_Nelson, Fortaleza, Glace Bay, Godthab, Goose Bay, Grand Turk, Grenada, Guadeloupe, Guatemala, Guayaquil, Guyana, Halifax, Havana, Hermosillo, Indianapolis (Indiana), Knox (Indiana), Marengo (Indiana), Petersburg (Indiana), Tell City (Indiana), Vevay (Indiana), Vincennes (Indiana), Winamac (Indiana), Inuvik, Iqaluit, Jamaica, Juneau, Louisville (Kentucky), Monticello (Kentucky), Kralendijk, La Paz, Lima, Los Angeles, Lower Princes, Maceio, Managua, Manaus, Marigot, Martinique, Matamoros, Mazatlan, Menominee, Merida, Metlakatla, Mexico City, Miquelon, Moncton, Monterrey, Montevideo, Montreal, Montserrat, Nassau, New York, Nipigon, Nome, Fernando de Noronha, Beulah (North Dakota), Center (North Dakota), New Salem (North Dakota), Ojinaga, Panama, Pangnirtung, Paramaribo, Phoenix, Port-au-Prince, Port of Spain, Porto Acre, Porto Velho, Puerto Rico, Punta_Arenas, Rainy River, Rankin Inlet, Recife, Regina, Resolute, Rio Branco, Santa Isabel, Santarém, Santiago, Santo Domingo, São Paulo, Scoresbysund, Shiprock, Sitka, St Barthelemy, St Johns, St Kitts, St Lucia, St Thomas, St Vincent, Swift Current, Tegucigalpa, Thule, Thunder Bay, Tijuana, Toronto, Tortola, Vancouver, Virgin, Whitehorse, Winnipeg, Yakutat, Yellowknife +tzdata tzdata/Zones/America select +# Time zone: +# Choices: Azores, Bermuda, Canary, Cape Verde, Faroe, Jan Mayen, Madeira, Reykjavik, South Georgia, St. Helena, Stanley +tzdata tzdata/Zones/Atlantic select +# Enable subpixel rendering for screen: +# Choices: Automatic, Always, Never +fontconfig-config fontconfig/subpixel_rendering select Automatic +# Do you want to add the user ? +base-passwd base-passwd/user-add boolean true +# Failure restarting some services for OpenSSL upgrade +libssl1.1 libssl1.1/restart-failed error +libssl1.1:armhf libssl1.1/restart-failed error +# Remove all MariaDB databases? +mariadb-server-10.3 mariadb-server-10.3/postrm_remove_databases boolean false +# Modify smb.conf to use WINS settings from DHCP? +samba-common samba-common/dhcp boolean true +# Do you want to remove the group ? +base-passwd base-passwd/group-remove boolean true +# Insert headers before changelogs? +apt-listchanges apt-listchanges/headers boolean false +# Should apt-listchanges skip changes that have already been seen? +apt-listchanges apt-listchanges/save-seen boolean true +# Incompatible PAM profiles selected. +libpam-runtime libpam-runtime/conflicts error +# Interface to use: +# Choices: Dialog, Readline, Gnome, Kde, Editor, Noninteractive +debconf debconf/frontend select Dialog +# Do you want to change the home directory of user ? +base-passwd base-passwd/user-change-home boolean true +# Time zone: +# Choices: Longyearbyen +tzdata tzdata/Zones/Arctic select +# Format of e-mail messages: +# Choices: text, html +apt-listchanges apt-listchanges/email-format select text +# Compose key: +# Choices: No compose key, Right Alt (AltGr), Right Control, Right Logo key, Menu key, Left Logo key, Caps Lock +keyboard-configuration keyboard-configuration/compose select No compose key +# Prompt for confirmation after displaying changes? +apt-listchanges apt-listchanges/confirm boolean false +# Allow ordinary users to run ip vrf exec using capabilities? +iproute2 iproute2/setcaps boolean false +# Changes displayed with APT: +# Choices: news, changelogs, both +apt-listchanges apt-listchanges/which select news +# Host name: +ssl-cert make-ssl-cert/hostname string localhost +# The old data directory will be saved at new location +mariadb-server-10.3 mariadb-server-10.3/old_data_directory_saved note +# Failure restarting some services for PAM upgrade +libpam0g libpam0g/restart-failed error +libpam0g:armhf libpam0g/restart-failed error +# Conflicts found in three-way merge +ucf ucf/conflicts_found error +# Method to be used to display changes: +# Choices: pager, browser, xterm-pager, xterm-browser, gtk, text, mail, none +apt-listchanges apt-listchanges/frontend select pager +# Time zone: +# Choices: Abidjan, Accra, Addis Ababa, Algiers, Asmara, Bamako, Bangui, Banjul, Bissau, Blantyre, Brazzaville, Bujumbura, Cairo, Casablanca, Ceuta, Conakry, Dakar, Dar es Salaam, Djibouti, Douala, El-Aaiún, Freetown, Gaborone, Harare, Johannesburg, Juba, Kampala, Khartoum, Kigali, Kinshasa, Lagos, Libreville, Lome, Luanda, Lubumbashi, Lusaka, Malabo, Maputo, Maseru, Mbabane, Mogadishu, Monrovia, Nairobi, Ndjamena, Niamey, Nouakchott, Ouagadougou, Porto-Novo, Sao Tome, Timbuktu, Tripoli, Tunis, Windhoek +tzdata tzdata/Zones/Africa select +# PAM profiles to enable: +# Choices: Unix authentication, Register user sessions in the systemd control group hierarchy, Create home directory on login, Register check to see if default password has been changed when SSH is enabled +libpam-runtime libpam-runtime/profiles multiselect unix, systemd, chksshpwd +# Display manager must be restarted manually +libpam0g libpam0g/xdm-needs-restart error +libpam0g:armhf libpam0g/xdm-needs-restart error +# Time zone: +# Choices: Aden, Almaty, Amman, Anadyr, Aqtau, Aqtobe, Ashgabat, Atyrau, Baghdad, Bahrain, Baku, Bangkok, Barnaul, Beirut, Bishkek, Brunei, Chita, Choibalsan, Chongqing, Colombo, Damascus, Dhaka, Dili, Dubai, Dushanbe, Famagusta, Gaza, Harbin, Hebron, Ho Chi Minh City, Hong Kong, Hovd, Irkutsk, Istanbul, Jakarta, Jayapura, Jerusalem, Kabul, Kamchatka, Karachi, Kashgar, Katmandu, Khandyga, Kolkata, Krasnoyarsk, Kuala Lumpur, Kuching, Kuwait, Macau, Magadan, Makassar, Manila, Muscat, Nicosia, Novokuznetsk, Novosibirsk, Omsk, Oral, Phnom Penh, Pontianak, Pyongyang, Qatar, Qostanay, Qyzylorda, Rangoon, Riyadh, Sakhalin, Samarkand, Seoul, Shanghai, Singapore, Srednekolymsk, Taipei, Tashkent, Tbilisi, Tehran, Tel Aviv, Thimphu, Tokyo, Tomsk, Ujung Pandang, Ulaanbaatar, Urumqi, Ust-Nera, Vientiane, Vladivostok, Yakutsk, Yangon, Yekaterinburg, Yerevan +tzdata tzdata/Zones/Asia select +# Kernel must be upgraded +libc6 glibc/kernel-too-old error +libc6:armhf glibc/kernel-too-old error +# for internal use +console-setup console-setup/store_defaults_in_debconf_db boolean true +# Failure restarting some services for OpenSSL upgrade +libssl1.0.2 libssl1.0.2/restart-failed error +libssl1.0.2:armhf libssl1.0.2/restart-failed error +# Disable SSH password authentication for root? +openssh-server openssh-server/permit-root-login boolean true +# for internal use +keyboard-configuration keyboard-configuration/layoutcode string gb +# Choose software to install: +# Choices: +tasksel tasksel/first multiselect +# Kernel version not supported +libc6 glibc/kernel-not-supported note +libc6:armhf glibc/kernel-not-supported note +# Keyboard model: +# Choices: A4Tech KB-21, A4Tech KBS-8, A4Tech Wireless Desktop RFKB-23, Acer AirKey V, Acer C300, Acer Ferrari 4000, Acer laptop, Advance Scorpius KI, Amiga, Apple, Apple Aluminium (ANSI), Apple Aluminium (ISO), Apple Aluminium (JIS), Apple laptop, Asus laptop, Atari TT, Azona RF2300 wireless Internet, BenQ X-Touch, BenQ X-Touch 730, BenQ X-Touch 800, Brother Internet, BTC 5090, BTC 5113RF Multimedia, BTC 5126T, BTC 6301URF, BTC 9000, BTC 9000A, BTC 9001AH, BTC 9019U, BTC 9116U Mini Wireless Internet and Gaming, Cherry Blue Line CyBo@rd, Cherry Blue Line CyBo@rd (alt.), Cherry B.UNLIMITED, Cherry CyBo@rd USB-Hub, Cherry CyMotion Expert, Cherry CyMotion Master Linux, Cherry CyMotion Master XPress, Chicony Internet, Chicony KB-9885, Chicony KU-0108, Chicony KU-0420, Chromebook, Classmate PC, Compaq Armada laptop, Compaq Easy Access, Compaq Internet (13 keys), Compaq Internet (18 keys), Compaq Internet (7 keys), Compaq iPaq, Compaq Presario laptop, Creative Desktop Wireless 7000, Dell, Dell 101-key PC, Dell Inspiron 6000/8000 laptop, Dell Latitude laptop, Dell Precision M65 laptop, Dell Precision M laptop, Dell SK-8125, Dell SK-8135, Dell USB Multimedia, Dexxa Wireless Desktop, Diamond 9801/9802, DTK2000, eMachines m6800 laptop, Ennyah DKB-1008, Everex STEPnote, FL90, Fujitsu-Siemens Amilo laptop, Generic 101-key PC, Generic 102-key PC (intl.), Generic 104-key PC, Generic 105-key PC (intl.), Genius Comfy KB-12e, Genius Comfy KB-16M/Multimedia KWD-910, Genius Comfy KB-21e-Scroll, Genius KB-19e NB, Genius KKB-2050HS, Gyration, Happy Hacking, Happy Hacking for Mac, Hewlett-Packard Internet, Hewlett-Packard Mini 110 laptop, Hewlett-Packard NEC SK-2500 Multimedia, Hewlett-Packard nx9020, Hewlett-Packard Omnibook 500, Hewlett-Packard Omnibook 500 FA, Hewlett-Packard Omnibook 6000/6100, Hewlett-Packard Omnibook XE3 GC, Hewlett-Packard Omnibook XE3 GF, Hewlett-Packard Omnibook XT1000, Hewlett-Packard Pavilion dv5, Hewlett-Packard Pavilion ZT1100, Honeywell Euroboard, HTC Dream, Htc Dream phone, IBM Rapid Access, IBM Rapid Access II, IBM Space Saver, IBM ThinkPad 560Z/600/600E/A22E, IBM ThinkPad R60/T60/R61/T61, IBM ThinkPad Z60m/Z60t/Z61m/Z61t, Keytronic FlexPro, Kinesis, Logitech, Logitech Access, Logitech Cordless Desktop, Logitech Cordless Desktop (alt.), Logitech Cordless Desktop EX110, Logitech Cordless Desktop iTouch, Logitech Cordless Desktop LX-300, Logitech Cordless Desktop Navigator, Logitech Cordless Desktop Optical, Logitech Cordless Desktop Pro (2nd alt.), Logitech Cordless Freedom/Desktop Navigator, Logitech diNovo, Logitech diNovo Edge, Logitech G15 extra keys via G15daemon, Logitech Internet, Logitech Internet 350, Logitech Internet Navigator, Logitech iTouch, Logitech iTouch Cordless Y-RB6, Logitech iTouch Internet Navigator SE, Logitech iTouch Internet Navigator SE USB, Logitech Ultra-X, Logitech Ultra-X Cordless Media Desktop, MacBook/MacBook Pro, MacBook/MacBook Pro (intl.), Macintosh, Macintosh Old, Memorex MX1998, Memorex MX2500 EZ-Access, Memorex MX2750, Microsoft Comfort Curve 2000, Microsoft Internet, Microsoft Internet Pro (Swedish), Microsoft Natural, Microsoft Natural Elite, Microsoft Natural Ergonomic 4000, Microsoft Natural Pro OEM, Microsoft Natural Pro/Internet Pro, Microsoft Natural Pro USB/Internet Pro, Microsoft Natural Wireless Ergonomic 7000, Microsoft Office Keyboard, Microsoft Wireless Multimedia 1.0A, NEC SK-1300, NEC SK-2500, NEC SK-6200, NEC SK-7100, Northgate OmniKey 101, OLPC, Ortek Multimedia/Internet MCK-800, PC-98, Propeller Voyager KTEZ-1000, QTronix Scorpius 98N+, Samsung SDM 4500P, Samsung SDM 4510P, Sanwa Supply SKB-KG3, Silvercrest Multimedia Wireless, SteelSeries Apex 300 (Apex RAW), Sun Type 4, Sun Type 5, Sun Type 6 (Japanese), Sun Type 6/7 USB, Sun Type 6/7 USB (European), Sun Type 6 USB (Japanese), Sun Type 6 USB (Unix), Sun Type 7 USB, Sun Type 7 USB (European), Sun Type 7 USB (Japanese)/Japanese 106-key, Sun Type 7 USB (Unix), Super Power Multimedia, SVEN Ergonomic 2500, SVEN Slim 303, Symplon PaceBook tablet, Targa Visionary 811, Toshiba Satellite S3000, Truly Ergonomic 227, Truly Ergonomic 229, Truly Ergonomic Computer Keyboard Model 227 (Wide Alt keys), Truly Ergonomic Computer Keyboard Model 229 (Standard sized Alt keys\, additional Super and Menu key), Trust Direct Access, Trust Slimline, Trust Wireless Classic, TypeMatrix EZ-Reach 2020, TypeMatrix EZ-Reach 2030 PS2, TypeMatrix EZ-Reach 2030 USB, TypeMatrix EZ-Reach 2030 USB (102/105:EU mode), TypeMatrix EZ-Reach 2030 USB (106:JP mode), Unitek KB-1925, ViewSonic KU-306 Internet, Winbook Model XP5, Yahoo! Internet +keyboard-configuration keyboard-configuration/model select Generic 105-key PC (intl.) +# Do you want to change the shell of user ? +base-passwd base-passwd/user-change-shell boolean true +# Workgroup/Domain Name: +samba-common samba-common/workgroup string WORKGROUP +# Do you want to change the GID of user ? +base-passwd base-passwd/user-change-gid boolean true +# Key to function as AltGr: +# Choices: The default for the keyboard layout, No AltGr key, Right Alt (AltGr), Right Control, Right Logo key, Menu key, Left Alt, Left Logo key, Keypad Enter key, Both Logo keys, Both Alt keys +keyboard-configuration keyboard-configuration/altgr select The default for the keyboard layout +# Country of origin for the keyboard: +# Choices: +keyboard-configuration keyboard-configuration/layout select +# Time zone: +# Choices: GMT, GMT+0, GMT+1, GMT+10, GMT+11, GMT+12, GMT+2, GMT+3, GMT+4, GMT+5, GMT+6, GMT+7, GMT+8, GMT+9, GMT-0, GMT-1, GMT-10, GMT-11, GMT-12, GMT-13, GMT-14, GMT-2, GMT-3, GMT-4, GMT-5, GMT-6, GMT-7, GMT-8, GMT-9, GMT0, Greenwich, UCT, UTC, Universal, Zulu +tzdata tzdata/Zones/Etc select UTC +# Time zone: +# Choices: Adelaide, Brisbane, Broken Hill, Canberra, Currie, Darwin, Eucla, Hobart, Lindeman, Lord Howe, Melbourne, Perth, Sydney, Yancowinna +tzdata tzdata/Zones/Australia select +# Services to restart to make them use the new libraries: +libssl1.0.2 libssl1.0.2/restart-services string +libssl1.0.2:armhf libssl1.0.2/restart-services string +# Locales to be generated: +# Choices: All locales, aa_DJ ISO-8859-1, aa_DJ.UTF-8 UTF-8, aa_ER UTF-8, aa_ER@saaho UTF-8, aa_ET UTF-8, af_ZA ISO-8859-1, af_ZA.UTF-8 UTF-8, agr_PE UTF-8, ak_GH UTF-8, am_ET UTF-8, an_ES ISO-8859-15, an_ES.UTF-8 UTF-8, anp_IN UTF-8, ar_AE ISO-8859-6, ar_AE.UTF-8 UTF-8, ar_BH ISO-8859-6, ar_BH.UTF-8 UTF-8, ar_DZ ISO-8859-6, ar_DZ.UTF-8 UTF-8, ar_EG ISO-8859-6, ar_EG.UTF-8 UTF-8, ar_IN UTF-8, ar_IQ ISO-8859-6, ar_IQ.UTF-8 UTF-8, ar_JO ISO-8859-6, ar_JO.UTF-8 UTF-8, ar_KW ISO-8859-6, ar_KW.UTF-8 UTF-8, ar_LB ISO-8859-6, ar_LB.UTF-8 UTF-8, ar_LY ISO-8859-6, ar_LY.UTF-8 UTF-8, ar_MA ISO-8859-6, ar_MA.UTF-8 UTF-8, ar_OM ISO-8859-6, ar_OM.UTF-8 UTF-8, ar_QA ISO-8859-6, ar_QA.UTF-8 UTF-8, ar_SA ISO-8859-6, ar_SA.UTF-8 UTF-8, ar_SD ISO-8859-6, ar_SD.UTF-8 UTF-8, ar_SS UTF-8, ar_SY ISO-8859-6, ar_SY.UTF-8 UTF-8, ar_TN ISO-8859-6, ar_TN.UTF-8 UTF-8, ar_YE ISO-8859-6, ar_YE.UTF-8 UTF-8, as_IN UTF-8, ast_ES ISO-8859-15, ast_ES.UTF-8 UTF-8, ayc_PE UTF-8, az_AZ UTF-8, az_IR UTF-8, be_BY CP1251, be_BY.UTF-8 UTF-8, be_BY@latin UTF-8, bem_ZM UTF-8, ber_DZ UTF-8, ber_MA UTF-8, bg_BG CP1251, bg_BG.UTF-8 UTF-8, bhb_IN.UTF-8 UTF-8, bho_IN UTF-8, bho_NP UTF-8, bi_VU UTF-8, bn_BD UTF-8, bn_IN UTF-8, bo_CN UTF-8, bo_IN UTF-8, br_FR ISO-8859-1, br_FR.UTF-8 UTF-8, br_FR@euro ISO-8859-15, brx_IN UTF-8, bs_BA ISO-8859-2, bs_BA.UTF-8 UTF-8, byn_ER UTF-8, ca_AD ISO-8859-15, ca_AD.UTF-8 UTF-8, ca_ES ISO-8859-1, ca_ES.UTF-8 UTF-8, ca_ES@euro ISO-8859-15, ca_ES@valencia UTF-8, ca_FR ISO-8859-15, ca_FR.UTF-8 UTF-8, ca_IT ISO-8859-15, ca_IT.UTF-8 UTF-8, ce_RU UTF-8, chr_US UTF-8, cmn_TW UTF-8, crh_UA UTF-8, cs_CZ ISO-8859-2, cs_CZ.UTF-8 UTF-8, csb_PL UTF-8, cv_RU UTF-8, cy_GB ISO-8859-14, cy_GB.UTF-8 UTF-8, da_DK ISO-8859-1, da_DK.UTF-8 UTF-8, de_AT ISO-8859-1, de_AT.UTF-8 UTF-8, de_AT@euro ISO-8859-15, de_BE ISO-8859-1, de_BE.UTF-8 UTF-8, de_BE@euro ISO-8859-15, de_CH ISO-8859-1, de_CH.UTF-8 UTF-8, de_DE ISO-8859-1, de_DE.UTF-8 UTF-8, de_DE@euro ISO-8859-15, de_IT ISO-8859-1, de_IT.UTF-8 UTF-8, de_LI.UTF-8 UTF-8, de_LU ISO-8859-1, de_LU.UTF-8 UTF-8, de_LU@euro ISO-8859-15, doi_IN UTF-8, dsb_DE UTF-8, dv_MV UTF-8, dz_BT UTF-8, el_CY ISO-8859-7, el_CY.UTF-8 UTF-8, el_GR ISO-8859-7, el_GR.UTF-8 UTF-8, el_GR@euro ISO-8859-7, en_AG UTF-8, en_AU ISO-8859-1, en_AU.UTF-8 UTF-8, en_BW ISO-8859-1, en_BW.UTF-8 UTF-8, en_CA ISO-8859-1, en_CA.UTF-8 UTF-8, en_DK ISO-8859-1, en_DK.ISO-8859-15 ISO-8859-15, en_DK.UTF-8 UTF-8, en_GB ISO-8859-1, en_GB.ISO-8859-15 ISO-8859-15, en_GB.UTF-8 UTF-8, en_HK ISO-8859-1, en_HK.UTF-8 UTF-8, en_IE ISO-8859-1, en_IE.UTF-8 UTF-8, en_IE@euro ISO-8859-15, en_IL UTF-8, en_IN UTF-8, en_NG UTF-8, en_NZ ISO-8859-1, en_NZ.UTF-8 UTF-8, en_PH ISO-8859-1, en_PH.UTF-8 UTF-8, en_SC.UTF-8 UTF-8, en_SG ISO-8859-1, en_SG.UTF-8 UTF-8, en_US ISO-8859-1, en_US.ISO-8859-15 ISO-8859-15, en_US.UTF-8 UTF-8, en_ZA ISO-8859-1, en_ZA.UTF-8 UTF-8, en_ZM UTF-8, en_ZW ISO-8859-1, en_ZW.UTF-8 UTF-8, eo UTF-8, es_AR ISO-8859-1, es_AR.UTF-8 UTF-8, es_BO ISO-8859-1, es_BO.UTF-8 UTF-8, es_CL ISO-8859-1, es_CL.UTF-8 UTF-8, es_CO ISO-8859-1, es_CO.UTF-8 UTF-8, es_CR ISO-8859-1, es_CR.UTF-8 UTF-8, es_CU UTF-8, es_DO ISO-8859-1, es_DO.UTF-8 UTF-8, es_EC ISO-8859-1, es_EC.UTF-8 UTF-8, es_ES ISO-8859-1, es_ES.UTF-8 UTF-8, es_ES@euro ISO-8859-15, es_GT ISO-8859-1, es_GT.UTF-8 UTF-8, es_HN ISO-8859-1, es_HN.UTF-8 UTF-8, es_MX ISO-8859-1, es_MX.UTF-8 UTF-8, es_NI ISO-8859-1, es_NI.UTF-8 UTF-8, es_PA ISO-8859-1, es_PA.UTF-8 UTF-8, es_PE ISO-8859-1, es_PE.UTF-8 UTF-8, es_PR ISO-8859-1, es_PR.UTF-8 UTF-8, es_PY ISO-8859-1, es_PY.UTF-8 UTF-8, es_SV ISO-8859-1, es_SV.UTF-8 UTF-8, es_US ISO-8859-1, es_US.UTF-8 UTF-8, es_UY ISO-8859-1, es_UY.UTF-8 UTF-8, es_VE ISO-8859-1, es_VE.UTF-8 UTF-8, et_EE ISO-8859-1, et_EE.ISO-8859-15 ISO-8859-15, et_EE.UTF-8 UTF-8, eu_ES ISO-8859-1, eu_ES.UTF-8 UTF-8, eu_ES@euro ISO-8859-15, eu_FR ISO-8859-1, eu_FR.UTF-8 UTF-8, eu_FR@euro ISO-8859-15, fa_IR UTF-8, ff_SN UTF-8, fi_FI ISO-8859-1, fi_FI.UTF-8 UTF-8, fi_FI@euro ISO-8859-15, fil_PH UTF-8, fo_FO ISO-8859-1, fo_FO.UTF-8 UTF-8, fr_BE ISO-8859-1, fr_BE.UTF-8 UTF-8, fr_BE@euro ISO-8859-15, fr_CA ISO-8859-1, fr_CA.UTF-8 UTF-8, fr_CH ISO-8859-1, fr_CH.UTF-8 UTF-8, fr_FR ISO-8859-1, fr_FR.UTF-8 UTF-8, fr_FR@euro ISO-8859-15, fr_LU ISO-8859-1, fr_LU.UTF-8 UTF-8, fr_LU@euro ISO-8859-15, fur_IT UTF-8, fy_DE UTF-8, fy_NL UTF-8, ga_IE ISO-8859-1, ga_IE.UTF-8 UTF-8, ga_IE@euro ISO-8859-15, gd_GB ISO-8859-15, gd_GB.UTF-8 UTF-8, gez_ER UTF-8, gez_ER@abegede UTF-8, gez_ET UTF-8, gez_ET@abegede UTF-8, gl_ES ISO-8859-1, gl_ES.UTF-8 UTF-8, gl_ES@euro ISO-8859-15, gu_IN UTF-8, gv_GB ISO-8859-1, gv_GB.UTF-8 UTF-8, ha_NG UTF-8, hak_TW UTF-8, he_IL ISO-8859-8, he_IL.UTF-8 UTF-8, hi_IN UTF-8, hif_FJ UTF-8, hne_IN UTF-8, hr_HR ISO-8859-2, hr_HR.UTF-8 UTF-8, hsb_DE ISO-8859-2, hsb_DE.UTF-8 UTF-8, ht_HT UTF-8, hu_HU ISO-8859-2, hu_HU.UTF-8 UTF-8, hy_AM UTF-8, hy_AM.ARMSCII-8 ARMSCII-8, ia_FR UTF-8, id_ID ISO-8859-1, id_ID.UTF-8 UTF-8, ig_NG UTF-8, ik_CA UTF-8, is_IS ISO-8859-1, is_IS.UTF-8 UTF-8, it_CH ISO-8859-1, it_CH.UTF-8 UTF-8, it_IT ISO-8859-1, it_IT.UTF-8 UTF-8, it_IT@euro ISO-8859-15, iu_CA UTF-8, ja_JP.EUC-JP EUC-JP, ja_JP.UTF-8 UTF-8, ka_GE GEORGIAN-PS, ka_GE.UTF-8 UTF-8, kab_DZ UTF-8, kk_KZ PT154, kk_KZ.RK1048 RK1048, kk_KZ.UTF-8 UTF-8, kl_GL ISO-8859-1, kl_GL.UTF-8 UTF-8, km_KH UTF-8, kn_IN UTF-8, ko_KR.EUC-KR EUC-KR, ko_KR.UTF-8 UTF-8, kok_IN UTF-8, ks_IN UTF-8, ks_IN@devanagari UTF-8, ku_TR ISO-8859-9, ku_TR.UTF-8 UTF-8, kw_GB ISO-8859-1, kw_GB.UTF-8 UTF-8, ky_KG UTF-8, lb_LU UTF-8, lg_UG ISO-8859-10, lg_UG.UTF-8 UTF-8, li_BE UTF-8, li_NL UTF-8, lij_IT UTF-8, ln_CD UTF-8, lo_LA UTF-8, lt_LT ISO-8859-13, lt_LT.UTF-8 UTF-8, lv_LV ISO-8859-13, lv_LV.UTF-8 UTF-8, lzh_TW UTF-8, mag_IN UTF-8, mai_IN UTF-8, mai_NP UTF-8, mfe_MU UTF-8, mg_MG ISO-8859-15, mg_MG.UTF-8 UTF-8, mhr_RU UTF-8, mi_NZ ISO-8859-13, mi_NZ.UTF-8 UTF-8, miq_NI UTF-8, mjw_IN UTF-8, mk_MK ISO-8859-5, mk_MK.UTF-8 UTF-8, ml_IN UTF-8, mn_MN UTF-8, mni_IN UTF-8, mr_IN UTF-8, ms_MY ISO-8859-1, ms_MY.UTF-8 UTF-8, mt_MT ISO-8859-3, mt_MT.UTF-8 UTF-8, my_MM UTF-8, nan_TW UTF-8, nan_TW@latin UTF-8, nb_NO ISO-8859-1, nb_NO.UTF-8 UTF-8, nds_DE UTF-8, nds_NL UTF-8, ne_NP UTF-8, nhn_MX UTF-8, niu_NU UTF-8, niu_NZ UTF-8, nl_AW UTF-8, nl_BE ISO-8859-1, nl_BE.UTF-8 UTF-8, nl_BE@euro ISO-8859-15, nl_NL ISO-8859-1, nl_NL.UTF-8 UTF-8, nl_NL@euro ISO-8859-15, nn_NO ISO-8859-1, nn_NO.UTF-8 UTF-8, nr_ZA UTF-8, nso_ZA UTF-8, oc_FR ISO-8859-1, oc_FR.UTF-8 UTF-8, om_ET UTF-8, om_KE ISO-8859-1, om_KE.UTF-8 UTF-8, or_IN UTF-8, os_RU UTF-8, pa_IN UTF-8, pa_PK UTF-8, pap_AW UTF-8, pap_CW UTF-8, pl_PL ISO-8859-2, pl_PL.UTF-8 UTF-8, ps_AF UTF-8, pt_BR ISO-8859-1, pt_BR.UTF-8 UTF-8, pt_PT ISO-8859-1, pt_PT.UTF-8 UTF-8, pt_PT@euro ISO-8859-15, quz_PE UTF-8, raj_IN UTF-8, ro_RO ISO-8859-2, ro_RO.UTF-8 UTF-8, ru_RU ISO-8859-5, ru_RU.CP1251 CP1251, ru_RU.KOI8-R KOI8-R, ru_RU.UTF-8 UTF-8, ru_UA KOI8-U, ru_UA.UTF-8 UTF-8, rw_RW UTF-8, sa_IN UTF-8, sah_RU UTF-8, sat_IN UTF-8, sc_IT UTF-8, sd_IN UTF-8, sd_IN@devanagari UTF-8, se_NO UTF-8, sgs_LT UTF-8, shn_MM UTF-8, shs_CA UTF-8, si_LK UTF-8, sid_ET UTF-8, sk_SK ISO-8859-2, sk_SK.UTF-8 UTF-8, sl_SI ISO-8859-2, sl_SI.UTF-8 UTF-8, sm_WS UTF-8, so_DJ ISO-8859-1, so_DJ.UTF-8 UTF-8, so_ET UTF-8, so_KE ISO-8859-1, so_KE.UTF-8 UTF-8, so_SO ISO-8859-1, so_SO.UTF-8 UTF-8, sq_AL ISO-8859-1, sq_AL.UTF-8 UTF-8, sq_MK UTF-8, sr_ME UTF-8, sr_RS UTF-8, sr_RS@latin UTF-8, ss_ZA UTF-8, st_ZA ISO-8859-1, st_ZA.UTF-8 UTF-8, sv_FI ISO-8859-1, sv_FI.UTF-8 UTF-8, sv_FI@euro ISO-8859-15, sv_SE ISO-8859-1, sv_SE.ISO-8859-15 ISO-8859-15, sv_SE.UTF-8 UTF-8, sw_KE UTF-8, sw_TZ UTF-8, szl_PL UTF-8, ta_IN UTF-8, ta_LK UTF-8, tcy_IN.UTF-8 UTF-8, te_IN UTF-8, tg_TJ KOI8-T, tg_TJ.UTF-8 UTF-8, th_TH TIS-620, th_TH.UTF-8 UTF-8, the_NP UTF-8, ti_ER UTF-8, ti_ET UTF-8, tig_ER UTF-8, tk_TM UTF-8, tl_PH ISO-8859-1, tl_PH.UTF-8 UTF-8, tn_ZA UTF-8, to_TO UTF-8, tpi_PG UTF-8, tr_CY ISO-8859-9, tr_CY.UTF-8 UTF-8, tr_TR ISO-8859-9, tr_TR.UTF-8 UTF-8, ts_ZA UTF-8, tt_RU UTF-8, tt_RU@iqtelif UTF-8, ug_CN UTF-8, uk_UA KOI8-U, uk_UA.UTF-8 UTF-8, unm_US UTF-8, ur_IN UTF-8, ur_PK UTF-8, uz_UZ ISO-8859-1, uz_UZ.UTF-8 UTF-8, uz_UZ@cyrillic UTF-8, ve_ZA UTF-8, vi_VN UTF-8, wa_BE ISO-8859-1, wa_BE.UTF-8 UTF-8, wa_BE@euro ISO-8859-15, wae_CH UTF-8, wal_ET UTF-8, wo_SN UTF-8, xh_ZA ISO-8859-1, xh_ZA.UTF-8 UTF-8, yi_US CP1255, yi_US.UTF-8 UTF-8, yo_NG UTF-8, yue_HK UTF-8, yuw_PG UTF-8, zh_CN GB2312, zh_CN.GB18030 GB18030, zh_CN.GBK GBK, zh_CN.UTF-8 UTF-8, zh_HK BIG5-HKSCS, zh_HK.UTF-8 UTF-8, zh_SG GB2312, zh_SG.GBK GBK, zh_SG.UTF-8 UTF-8, zh_TW BIG5, zh_TW.EUC-TW EUC-TW, zh_TW.UTF-8 UTF-8, zu_ZA ISO-8859-1, zu_ZA.UTF-8 UTF-8 +locales locales/locales_to_be_generated multiselect en_GB.UTF-8 UTF-8 +# xscreensaver and xlockmore must be restarted before upgrading +libc6 glibc/disable-screensaver error +libc6:armhf glibc/disable-screensaver error +# Automatic font hinting style: +# Choices: None, Slight, Medium, Full +fontconfig-config fontconfig/hinting_style select hintslight +# Keyboard layout: +# Choices: English (UK), English (UK) - English (UK\, Colemak), English (UK) - English (UK\, Dvorak), English (UK) - English (UK\, Dvorak\, with UK punctuation), English (UK) - English (UK\, extended\, with Win keys), English (UK) - English (UK\, intl.\, Macintosh), English (UK) - English (UK\, intl.\, with dead keys), English (UK) - English (UK\, Macintosh), English (UK) - Polish (British keyboard), Other +keyboard-configuration keyboard-configuration/variant select English (UK) +# Keymap to use: +# Choices: American English, Albanian, Arabic, Asturian, Bangladesh, Belarusian, Bengali, Belgian, Bosnian, Brazilian, British English, Bulgarian (BDS layout), Bulgarian (phonetic layout), Burmese, Canadian French, Canadian Multilingual, Catalan, Chinese, Croatian, Czech, Danish, Dutch, Dvorak, Dzongkha, Esperanto, Estonian, Ethiopian, Finnish, French, Georgian, German, Greek, Gujarati, Gurmukhi, Hebrew, Hindi, Hungarian, Icelandic, Irish, Italian, Japanese, Kannada, Kazakh, Khmer, Kirghiz, Korean, Kurdish (F layout), Kurdish (Q layout), Lao, Latin American, Latvian, Lithuanian, Macedonian, Malayalam, Nepali, Northern Sami, Norwegian, Persian, Philippines, Polish, Portuguese, Punjabi, Romanian, Russian, Serbian (Cyrillic), Sindhi, Sinhala, Slovak, Slovenian, Spanish, Swedish, Swiss French, Swiss German, Tajik, Tamil, Telugu, Thai, Tibetan, Turkish (F layout), Turkish (Q layout), Ukrainian, Uyghur, Vietnamese +keyboard-configuration keyboard-configuration/xkb-keymap select gb +# Should man and mandb be installed 'setuid man'? +man-db man-db/install-setuid boolean false +# Keep the current keyboard layout in the configuration file? +keyboard-configuration keyboard-configuration/unsupported_config_layout boolean true +# Do you want system-wide readable home directories? +adduser adduser/homedir-permission boolean true +# Do you want to upgrade glibc now? +libc6 glibc/upgrade boolean true +libc6:armhf glibc/upgrade boolean true +# for internal use +console-setup console-setup/fontsize string 8x16 +# Choose software to install: +# Choices: +tasksel tasksel/tasks multiselect +# for internal use; can be preseeded +man-db man-db/auto-update boolean true +# System's default paper size: +# Choices: letter, a4, note, legal, executive, halfletter, halfexecutive, 11x17, statement, folio, quarto, 10x14, ledger, tabloid, a0, a1, a2, a3, a5, a6, a7, a8, a9, a10, b0, b1, b2, b3, b4, b5, c5, DL, Comm10, Monarch, archE, archD, archC, archB, archA, flsa, flse, csheet, dsheet, esheet +libpaper1 libpaper/defaultpaper select a4 +libpaper1:armhf libpaper/defaultpaper select a4 +# No PAM profiles have been selected. +libpam-runtime libpam-runtime/no_profiles_chosen error +# Certificates to activate: +# Choices: mozilla/ACCVRAIZ1.crt, mozilla/AC_RAIZ_FNMT-RCM.crt, mozilla/Actalis_Authentication_Root_CA.crt, mozilla/AddTrust_External_Root.crt, mozilla/AffirmTrust_Commercial.crt, mozilla/AffirmTrust_Networking.crt, mozilla/AffirmTrust_Premium.crt, mozilla/AffirmTrust_Premium_ECC.crt, mozilla/Amazon_Root_CA_1.crt, mozilla/Amazon_Root_CA_2.crt, mozilla/Amazon_Root_CA_3.crt, mozilla/Amazon_Root_CA_4.crt, mozilla/Atos_TrustedRoot_2011.crt, mozilla/Autoridad_de_Certificacion_Firmaprofesional_CIF_A62634068.crt, mozilla/Baltimore_CyberTrust_Root.crt, mozilla/Buypass_Class_2_Root_CA.crt, mozilla/Buypass_Class_3_Root_CA.crt, mozilla/CA_Disig_Root_R2.crt, mozilla/Certigna.crt, mozilla/Certinomis_-_Root_CA.crt, mozilla/Certplus_Class_2_Primary_CA.crt, mozilla/certSIGN_ROOT_CA.crt, mozilla/Certum_Trusted_Network_CA_2.crt, mozilla/Certum_Trusted_Network_CA.crt, mozilla/CFCA_EV_ROOT.crt, mozilla/Chambers_of_Commerce_Root_-_2008.crt, mozilla/Comodo_AAA_Services_root.crt, mozilla/COMODO_Certification_Authority.crt, mozilla/COMODO_ECC_Certification_Authority.crt, mozilla/COMODO_RSA_Certification_Authority.crt, mozilla/Cybertrust_Global_Root.crt, mozilla/Deutsche_Telekom_Root_CA_2.crt, mozilla/DigiCert_Assured_ID_Root_CA.crt, mozilla/DigiCert_Assured_ID_Root_G2.crt, mozilla/DigiCert_Assured_ID_Root_G3.crt, mozilla/DigiCert_Global_Root_CA.crt, mozilla/DigiCert_Global_Root_G2.crt, mozilla/DigiCert_Global_Root_G3.crt, mozilla/DigiCert_High_Assurance_EV_Root_CA.crt, mozilla/DigiCert_Trusted_Root_G4.crt, mozilla/DST_Root_CA_X3.crt, mozilla/D-TRUST_Root_Class_3_CA_2_2009.crt, mozilla/D-TRUST_Root_Class_3_CA_2_EV_2009.crt, mozilla/EC-ACC.crt, mozilla/EE_Certification_Centre_Root_CA.crt, mozilla/Entrust.net_Premium_2048_Secure_Server_CA.crt, mozilla/Entrust_Root_Certification_Authority.crt, mozilla/Entrust_Root_Certification_Authority_-_EC1.crt, mozilla/Entrust_Root_Certification_Authority_-_G2.crt, mozilla/ePKI_Root_Certification_Authority.crt, mozilla/E-Tugra_Certification_Authority.crt, mozilla/GDCA_TrustAUTH_R5_ROOT.crt, mozilla/GeoTrust_Global_CA.crt, mozilla/GeoTrust_Primary_Certification_Authority.crt, mozilla/GeoTrust_Primary_Certification_Authority_-_G2.crt, mozilla/GeoTrust_Primary_Certification_Authority_-_G3.crt, mozilla/GeoTrust_Universal_CA_2.crt, mozilla/GeoTrust_Universal_CA.crt, mozilla/Global_Chambersign_Root_-_2008.crt, mozilla/GlobalSign_ECC_Root_CA_-_R4.crt, mozilla/GlobalSign_ECC_Root_CA_-_R5.crt, mozilla/GlobalSign_Root_CA.crt, mozilla/GlobalSign_Root_CA_-_R2.crt, mozilla/GlobalSign_Root_CA_-_R3.crt, mozilla/GlobalSign_Root_CA_-_R6.crt, mozilla/Go_Daddy_Class_2_CA.crt, mozilla/Go_Daddy_Root_Certificate_Authority_-_G2.crt, mozilla/Hellenic_Academic_and_Research_Institutions_ECC_RootCA_2015.crt, mozilla/Hellenic_Academic_and_Research_Institutions_RootCA_2011.crt, mozilla/Hellenic_Academic_and_Research_Institutions_RootCA_2015.crt, mozilla/Hongkong_Post_Root_CA_1.crt, mozilla/IdenTrust_Commercial_Root_CA_1.crt, mozilla/IdenTrust_Public_Sector_Root_CA_1.crt, mozilla/ISRG_Root_X1.crt, mozilla/Izenpe.com.crt, mozilla/LuxTrust_Global_Root_2.crt, mozilla/Microsec_e-Szigno_Root_CA_2009.crt, mozilla/NetLock_Arany_=Class_Gold=_FÅ‘tanúsítvány.crt, mozilla/Network_Solutions_Certificate_Authority.crt, mozilla/OISTE_WISeKey_Global_Root_GA_CA.crt, mozilla/OISTE_WISeKey_Global_Root_GB_CA.crt, mozilla/OISTE_WISeKey_Global_Root_GC_CA.crt, mozilla/QuoVadis_Root_CA_1_G3.crt, mozilla/QuoVadis_Root_CA_2.crt, mozilla/QuoVadis_Root_CA_2_G3.crt, mozilla/QuoVadis_Root_CA_3.crt, mozilla/QuoVadis_Root_CA_3_G3.crt, mozilla/QuoVadis_Root_CA.crt, mozilla/Secure_Global_CA.crt, mozilla/SecureSign_RootCA11.crt, mozilla/SecureTrust_CA.crt, mozilla/Security_Communication_RootCA2.crt, mozilla/Security_Communication_Root_CA.crt, mozilla/Sonera_Class_2_Root_CA.crt, mozilla/SSL.com_EV_Root_Certification_Authority_ECC.crt, mozilla/SSL.com_EV_Root_Certification_Authority_RSA_R2.crt, mozilla/SSL.com_Root_Certification_Authority_ECC.crt, mozilla/SSL.com_Root_Certification_Authority_RSA.crt, mozilla/Staat_der_Nederlanden_EV_Root_CA.crt, mozilla/Staat_der_Nederlanden_Root_CA_-_G2.crt, mozilla/Staat_der_Nederlanden_Root_CA_-_G3.crt, mozilla/Starfield_Class_2_CA.crt, mozilla/Starfield_Root_Certificate_Authority_-_G2.crt, mozilla/Starfield_Services_Root_Certificate_Authority_-_G2.crt, mozilla/SwissSign_Gold_CA_-_G2.crt, mozilla/SwissSign_Silver_CA_-_G2.crt, mozilla/SZAFIR_ROOT_CA2.crt, mozilla/Taiwan_GRCA.crt, mozilla/TeliaSonera_Root_CA_v1.crt, mozilla/thawte_Primary_Root_CA.crt, mozilla/thawte_Primary_Root_CA_-_G2.crt, mozilla/thawte_Primary_Root_CA_-_G3.crt, mozilla/TrustCor_ECA-1.crt, mozilla/TrustCor_RootCert_CA-1.crt, mozilla/TrustCor_RootCert_CA-2.crt, mozilla/Trustis_FPS_Root_CA.crt, mozilla/T-TeleSec_GlobalRoot_Class_2.crt, mozilla/T-TeleSec_GlobalRoot_Class_3.crt, mozilla/TUBITAK_Kamu_SM_SSL_Kok_Sertifikasi_-_Surum_1.crt, mozilla/TWCA_Global_Root_CA.crt, mozilla/TWCA_Root_Certification_Authority.crt, mozilla/USERTrust_ECC_Certification_Authority.crt, mozilla/USERTrust_RSA_Certification_Authority.crt, mozilla/Verisign_Class_3_Public_Primary_Certification_Authority_-_G3.crt, mozilla/VeriSign_Class_3_Public_Primary_Certification_Authority_-_G4.crt, mozilla/VeriSign_Class_3_Public_Primary_Certification_Authority_-_G5.crt, mozilla/VeriSign_Universal_Root_Certification_Authority.crt, mozilla/XRamp_Global_CA_Root.crt +ca-certificates ca-certificates/enable_crts multiselect mozilla/ACCVRAIZ1.crt, mozilla/AC_RAIZ_FNMT-RCM.crt, mozilla/Actalis_Authentication_Root_CA.crt, mozilla/AddTrust_External_Root.crt, mozilla/AffirmTrust_Commercial.crt, mozilla/AffirmTrust_Networking.crt, mozilla/AffirmTrust_Premium.crt, mozilla/AffirmTrust_Premium_ECC.crt, mozilla/Amazon_Root_CA_1.crt, mozilla/Amazon_Root_CA_2.crt, mozilla/Amazon_Root_CA_3.crt, mozilla/Amazon_Root_CA_4.crt, mozilla/Atos_TrustedRoot_2011.crt, mozilla/Autoridad_de_Certificacion_Firmaprofesional_CIF_A62634068.crt, mozilla/Baltimore_CyberTrust_Root.crt, mozilla/Buypass_Class_2_Root_CA.crt, mozilla/Buypass_Class_3_Root_CA.crt, mozilla/CA_Disig_Root_R2.crt, mozilla/Certigna.crt, mozilla/Certinomis_-_Root_CA.crt, mozilla/Certplus_Class_2_Primary_CA.crt, mozilla/certSIGN_ROOT_CA.crt, mozilla/Certum_Trusted_Network_CA_2.crt, mozilla/Certum_Trusted_Network_CA.crt, mozilla/CFCA_EV_ROOT.crt, mozilla/Chambers_of_Commerce_Root_-_2008.crt, mozilla/Comodo_AAA_Services_root.crt, mozilla/COMODO_Certification_Authority.crt, mozilla/COMODO_ECC_Certification_Authority.crt, mozilla/COMODO_RSA_Certification_Authority.crt, mozilla/Cybertrust_Global_Root.crt, mozilla/Deutsche_Telekom_Root_CA_2.crt, mozilla/DigiCert_Assured_ID_Root_CA.crt, mozilla/DigiCert_Assured_ID_Root_G2.crt, mozilla/DigiCert_Assured_ID_Root_G3.crt, mozilla/DigiCert_Global_Root_CA.crt, mozilla/DigiCert_Global_Root_G2.crt, mozilla/DigiCert_Global_Root_G3.crt, mozilla/DigiCert_High_Assurance_EV_Root_CA.crt, mozilla/DigiCert_Trusted_Root_G4.crt, mozilla/DST_Root_CA_X3.crt, mozilla/D-TRUST_Root_Class_3_CA_2_2009.crt, mozilla/D-TRUST_Root_Class_3_CA_2_EV_2009.crt, mozilla/EC-ACC.crt, mozilla/EE_Certification_Centre_Root_CA.crt, mozilla/Entrust.net_Premium_2048_Secure_Server_CA.crt, mozilla/Entrust_Root_Certification_Authority.crt, mozilla/Entrust_Root_Certification_Authority_-_EC1.crt, mozilla/Entrust_Root_Certification_Authority_-_G2.crt, mozilla/ePKI_Root_Certification_Authority.crt, mozilla/E-Tugra_Certification_Authority.crt, mozilla/GDCA_TrustAUTH_R5_ROOT.crt, mozilla/GeoTrust_Global_CA.crt, mozilla/GeoTrust_Primary_Certification_Authority.crt, mozilla/GeoTrust_Primary_Certification_Authority_-_G2.crt, mozilla/GeoTrust_Primary_Certification_Authority_-_G3.crt, mozilla/GeoTrust_Universal_CA_2.crt, mozilla/GeoTrust_Universal_CA.crt, mozilla/Global_Chambersign_Root_-_2008.crt, mozilla/GlobalSign_ECC_Root_CA_-_R4.crt, mozilla/GlobalSign_ECC_Root_CA_-_R5.crt, mozilla/GlobalSign_Root_CA.crt, mozilla/GlobalSign_Root_CA_-_R2.crt, mozilla/GlobalSign_Root_CA_-_R3.crt, mozilla/GlobalSign_Root_CA_-_R6.crt, mozilla/Go_Daddy_Class_2_CA.crt, mozilla/Go_Daddy_Root_Certificate_Authority_-_G2.crt, mozilla/Hellenic_Academic_and_Research_Institutions_ECC_RootCA_2015.crt, mozilla/Hellenic_Academic_and_Research_Institutions_RootCA_2011.crt, mozilla/Hellenic_Academic_and_Research_Institutions_RootCA_2015.crt, mozilla/Hongkong_Post_Root_CA_1.crt, mozilla/IdenTrust_Commercial_Root_CA_1.crt, mozilla/IdenTrust_Public_Sector_Root_CA_1.crt, mozilla/ISRG_Root_X1.crt, mozilla/Izenpe.com.crt, mozilla/LuxTrust_Global_Root_2.crt, mozilla/Microsec_e-Szigno_Root_CA_2009.crt, mozilla/NetLock_Arany_=Class_Gold=_FÅ‘tanúsítvány.crt, mozilla/Network_Solutions_Certificate_Authority.crt, mozilla/OISTE_WISeKey_Global_Root_GA_CA.crt, mozilla/OISTE_WISeKey_Global_Root_GB_CA.crt, mozilla/OISTE_WISeKey_Global_Root_GC_CA.crt, mozilla/QuoVadis_Root_CA_1_G3.crt, mozilla/QuoVadis_Root_CA_2.crt, mozilla/QuoVadis_Root_CA_2_G3.crt, mozilla/QuoVadis_Root_CA_3.crt, mozilla/QuoVadis_Root_CA_3_G3.crt, mozilla/QuoVadis_Root_CA.crt, mozilla/Secure_Global_CA.crt, mozilla/SecureSign_RootCA11.crt, mozilla/SecureTrust_CA.crt, mozilla/Security_Communication_RootCA2.crt, mozilla/Security_Communication_Root_CA.crt, mozilla/Sonera_Class_2_Root_CA.crt, mozilla/SSL.com_EV_Root_Certification_Authority_ECC.crt, mozilla/SSL.com_EV_Root_Certification_Authority_RSA_R2.crt, mozilla/SSL.com_Root_Certification_Authority_ECC.crt, mozilla/SSL.com_Root_Certification_Authority_RSA.crt, mozilla/Staat_der_Nederlanden_EV_Root_CA.crt, mozilla/Staat_der_Nederlanden_Root_CA_-_G2.crt, mozilla/Staat_der_Nederlanden_Root_CA_-_G3.crt, mozilla/Starfield_Class_2_CA.crt, mozilla/Starfield_Root_Certificate_Authority_-_G2.crt, mozilla/Starfield_Services_Root_Certificate_Authority_-_G2.crt, mozilla/SwissSign_Gold_CA_-_G2.crt, mozilla/SwissSign_Silver_CA_-_G2.crt, mozilla/SZAFIR_ROOT_CA2.crt, mozilla/Taiwan_GRCA.crt, mozilla/TeliaSonera_Root_CA_v1.crt, mozilla/thawte_Primary_Root_CA.crt, mozilla/thawte_Primary_Root_CA_-_G2.crt, mozilla/thawte_Primary_Root_CA_-_G3.crt, mozilla/TrustCor_ECA-1.crt, mozilla/TrustCor_RootCert_CA-1.crt, mozilla/TrustCor_RootCert_CA-2.crt, mozilla/Trustis_FPS_Root_CA.crt, mozilla/T-TeleSec_GlobalRoot_Class_2.crt, mozilla/T-TeleSec_GlobalRoot_Class_3.crt, mozilla/TUBITAK_Kamu_SM_SSL_Kok_Sertifikasi_-_Surum_1.crt, mozilla/TWCA_Global_Root_CA.crt, mozilla/TWCA_Root_Certification_Authority.crt, mozilla/USERTrust_ECC_Certification_Authority.crt, mozilla/USERTrust_RSA_Certification_Authority.crt, mozilla/Verisign_Class_3_Public_Primary_Certification_Authority_-_G3.crt, mozilla/VeriSign_Class_3_Public_Primary_Certification_Authority_-_G4.crt, mozilla/VeriSign_Class_3_Public_Primary_Certification_Authority_-_G5.crt, mozilla/VeriSign_Universal_Root_Certification_Authority.crt, mozilla/XRamp_Global_CA_Root.crt +# Font tuning method for screen (system default): +# Choices: Native, Autohinter, None +fontconfig-config fontconfig/hinting_type select Native +# Disable retrieving changes over network? +apt-listchanges apt-listchanges/no-network boolean false +# Failure restarting some services for GNU libc upgrade +libc6 glibc/restart-failed error +libc6:armhf glibc/restart-failed error +# Font for the console: +# Choices: Fixed, Terminus, TerminusBold, TerminusBoldVGA, VGA, Do not change the boot/kernel font, Let the system select a suitable font +console-setup console-setup/fontface47 select Fixed +# Use Control+Alt+Backspace to terminate the X server? +keyboard-configuration keyboard-configuration/ctrl_alt_bksp boolean false +# Line by line differences between versions +ucf ucf/show_diff note +# Do you want to change the UID of user ? +base-passwd base-passwd/user-change-uid boolean true +# Ignore questions with a priority less than: +# Choices: critical, high, medium, low +debconf debconf/priority select high +# for internal use +keyboard-configuration keyboard-configuration/variantcode string +# Dummy template +wolfram-engine shared/accepted-wolfram-eula boolean true +# Services to restart for PAM library upgrade: +libpam0g libpam0g/restart-services string +libpam0g:armhf libpam0g/restart-services string +# Network interfaces on which the DHCP server should listen: +isc-dhcp-server isc-dhcp-server/interfaces string +# Services to restart for GNU libc library upgrade: +libc6 glibc/restart-services string +libc6:armhf glibc/restart-services string +# for internal use +keyboard-configuration keyboard-configuration/optionscode string +# Time zone: +# Choices: AST4, AST4ADT, CST6, CST6CDT, EST5, EST5EDT, HST10, MST7, MST7MDT, PST8, PST8PDT, YST9, YST9YDT +tzdata tzdata/Zones/SystemV select +# Method for toggling between national and Latin mode: +# Choices: Caps Lock, Right Alt (AltGr), Right Control, Right Shift, Right Logo key, Menu key, Alt+Shift, Control+Shift, Control+Alt, Alt+Caps Lock, Left Control+Left Shift, Left Alt, Left Control, Left Shift, Left Logo key, Scroll Lock key, No toggling +keyboard-configuration keyboard-configuration/toggle select No toggling +# Encoding to use on the console: +# Choices: ARMSCII-8, CP1251, CP1255, CP1256, GEORGIAN-ACADEMY, GEORGIAN-PS, IBM1133, ISIRI-3342, ISO-8859-1, ISO-8859-10, ISO-8859-11, ISO-8859-13, ISO-8859-14, ISO-8859-15, ISO-8859-16, ISO-8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, ISO-8859-9, KOI8-R, KOI8-U, TIS-620, UTF-8, VISCII +console-setup console-setup/charmap47 select UTF-8 +# for internal use +keyboard-configuration keyboard-configuration/store_defaults_in_debconf_db boolean true +# Keep default keyboard options ()? +keyboard-configuration keyboard-configuration/unsupported_options boolean true +# Use dash as the default system shell (/bin/sh)? +dash dash/sh boolean true +# Time zone: +# Choices: Antananarivo, Chagos, Christmas, Cocos, Comoro, Kerguelen, Mahe, Maldives, Mauritius, Mayotte, Reunion +tzdata tzdata/Zones/Indian select +# Do you want to move the group ? +base-passwd base-passwd/group-move boolean true +# Character set to support: +# Choices: . Arabic, # Armenian, # Cyrillic - KOI8-R and KOI8-U, # Cyrillic - non-Slavic languages, . Cyrillic - non-Slavic languages (for blind users), # Cyrillic - Slavic languages (also Bosnian and Serbian Latin), . Cyrillic - Slavic languages (for blind users), . Ethiopic, # Georgian, # Greek, . Greek (for blind users), # Hebrew, # Lao, # Latin1 and Latin5 - western Europe and Turkic languages, # Latin2 - central Europe and Romanian, # Latin3 and Latin8 - Chichewa; Esperanto; Irish; Maltese and Welsh, # Latin7 - Lithuanian; Latvian; Maori and Marshallese, . Latin - Vietnamese, # Thai, . Combined - Latin; Slavic Cyrillic; Hebrew; basic Arabic, . Combined - Latin; Slavic Cyrillic; Greek, . Combined - Latin; Slavic and non-Slavic Cyrillic, Guess optimal character set +console-setup console-setup/codeset47 select # Latin1 and Latin5 - western Europe and Turkic languages +# Default locale for the system environment: +# Choices: None, C.UTF-8, en_GB.UTF-8 +locales locales/default_environment_locale select en_GB.UTF-8 +# Keep current keyboard options in the configuration file? +keyboard-configuration keyboard-configuration/unsupported_config_options boolean true +# Do you want to move the user ? +base-passwd base-passwd/user-move boolean true +# Show changes in reverse order? +apt-listchanges apt-listchanges/reverse boolean false +# New certificates to activate: +# Choices: +ca-certificates ca-certificates/new_crts multiselect +# Override local changes to /etc/pam.d/common-*? +libpam-runtime libpam-runtime/override boolean false +# This can be preseeded to override the default desktop. +# Choices: gnome, kde, xfce, lxde, cinnamon, mate, lxqt +tasksel tasksel/desktop multiselect diff --git a/Projects/la_mojo/Debug/server.conf b/Projects/la_mojo/Debug/server.conf new file mode 100644 index 00000000..d8cf92c9 --- /dev/null +++ b/Projects/la_mojo/Debug/server.conf @@ -0,0 +1,16 @@ +GENERAL : +{ + SSDP_ENABLE = true; + DATABASE : + { + DATA_FILE_NAME = "data/mysqlitedb.db"; + WEB_ACCESS_USER = "www-data"; + WEB_ACCESS_GROUP = "www-data"; + DATA_MEMORY_NAME = "mem_db.db"; + }; + KERNEL : + { + IDENTITY = "f96cc595a9122000d9448cefde7289a4"; + SITE_ID = 1; + }; +}; diff --git a/Projects/la_mojo/build b/Projects/la_mojo/build new file mode 100755 index 00000000..c5c7e6e3 --- /dev/null +++ b/Projects/la_mojo/build @@ -0,0 +1,9 @@ +#! /bin/sh + + +make clean -e "CFG=Debug_MASTER" +make -e "CFG=Debug_MASTER" -j4 + + +#make clean -e "CFG=Debug_SLAVE" +#make -e "CFG=Debug_SLAVE" -j4 diff --git a/Projects/la_mojo/la_mojo.vpj b/Projects/la_mojo/la_mojo.vpj new file mode 100644 index 00000000..adcd7395 --- /dev/null +++ b/Projects/la_mojo/la_mojo.vpj @@ -0,0 +1,401 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Projects/la_mojo/makefile b/Projects/la_mojo/makefile new file mode 100644 index 00000000..05e78b70 --- /dev/null +++ b/Projects/la_mojo/makefile @@ -0,0 +1,468 @@ +# SlickEdit generated file. Do not edit this file except in designated areas. + +# Make command to use for dependencies +MAKE=make +RM=rm +MKDIR=mkdir + +# -----Begin user-editable area----- + +# -----End user-editable area----- + +# If no configuration is specified, "Debug" will be used +ifndef CFG +CFG=Debug +endif + +# +# Configuration: Debug +# +ifeq "$(CFG)" "Debug" +OUTDIR=Debug +OUTFILE=$(OUTDIR)/mojo_d +CFG_INC= +CFG_LIB=-lsqlite3 -lpthread -lmysqlclient -lssl -lcurl -lm -lcrypto \ + -lconfig -lz -lv4l1 -lv4l2 -lhidapi-libusb `pkg-config libavcodec \ + libavdevice libavfilter libavformat libavutil libpostproc \ + libswresample libswscale --libs` -latomic `pkg-config --libs openssl \ + opencv4 rdkafka++` -lwiringPi -lliveMedia -lgroupsock \ + -lBasicUsageEnvironment -lUsageEnvironment +CFG_OBJ= +COMMON_OBJ=$(OUTDIR)/base64.o $(OUTDIR)/basicCameraInfo.o \ + $(OUTDIR)/basicDualThread.o $(OUTDIR)/basicEngine.o \ + $(OUTDIR)/basicEvent.o $(OUTDIR)/basicEventHandler.o \ + $(OUTDIR)/basicEventHeap.o $(OUTDIR)/basicFunctionality.o \ + $(OUTDIR)/basicLIBAV.o $(OUTDIR)/basicLogCollection.o \ + $(OUTDIR)/basicLoggingService.o $(OUTDIR)/basicMemoryOperation.o \ + $(OUTDIR)/basicObject.o $(OUTDIR)/basicPosition.o \ + $(OUTDIR)/basicRing.o $(OUTDIR)/basicSettings.o \ + $(OUTDIR)/basicSettingsProvider.o $(OUTDIR)/basicThread.o \ + $(OUTDIR)/basicTransport.o $(OUTDIR)/clientPort.o \ + $(OUTDIR)/curlRequest.o $(OUTDIR)/curlRequestsManager.o \ + $(OUTDIR)/dataBinder.o $(OUTDIR)/detector.o $(OUTDIR)/deviceNode.o \ + $(OUTDIR)/deviceNode2D.o $(OUTDIR)/deviceNode3D.o \ + $(OUTDIR)/deviceNodeCamera.o $(OUTDIR)/deviceNodeEthernet2Serial.o \ + $(OUTDIR)/deviceNodeFactory.o $(OUTDIR)/deviceNodePTZCamControl.o \ + $(OUTDIR)/deviceNodeSensor.o $(OUTDIR)/deviceNodeStaticCamControl.o \ + $(OUTDIR)/hardwareManager.o $(OUTDIR)/hardwareResource.o \ + $(OUTDIR)/hardwareResourceDryContactProvider.o \ + $(OUTDIR)/hardwareResourceNetworkProvider.o \ + $(OUTDIR)/hardwareResourceSerialProvider.o \ + $(OUTDIR)/hardwareResourceVideoProvider.o $(OUTDIR)/heapDebug.o \ + $(OUTDIR)/hid_dc.o $(OUTDIR)/json_reader.o $(OUTDIR)/json_value.o \ + $(OUTDIR)/json_writer.o $(OUTDIR)/kernelEventFilter.o \ + $(OUTDIR)/kernelEventFilterAPF.o $(OUTDIR)/kernelModule.o \ + $(OUTDIR)/kernelModuleEmbedVideo.o $(OUTDIR)/kernelModuleFactory.o \ + $(OUTDIR)/kernelModuleFlyHunter.o $(OUTDIR)/kernelModuleKafka.o \ + $(OUTDIR)/kernelModuleModemManager.o \ + $(OUTDIR)/kernelModuleOnvifObserver.o $(OUTDIR)/kernelModuleSSDP.o \ + $(OUTDIR)/kernelModuleUSBRelay.o $(OUTDIR)/kernelPrototype.o \ + $(OUTDIR)/libzip.o $(OUTDIR)/mask.o $(OUTDIR)/md5.o \ + $(OUTDIR)/mojoBackend.o $(OUTDIR)/mojoKernel.o \ + $(OUTDIR)/mysql_class.o $(OUTDIR)/MySQL_dataBinder.o \ + $(OUTDIR)/netClientHandler.o $(OUTDIR)/netServer.o \ + $(OUTDIR)/objectFileLoggingService.o $(OUTDIR)/objectSystemAnchor.o \ + $(OUTDIR)/ponvif.o $(OUTDIR)/protocol.o $(OUTDIR)/protocolHTTP.o \ + $(OUTDIR)/protocolKAFKA.o $(OUTDIR)/protocolLGS2D.o \ + $(OUTDIR)/protocolLGS3D.o $(OUTDIR)/protocolLGS3D_client.o \ + $(OUTDIR)/protocolONVIF.o $(OUTDIR)/protocolPTZ.o \ + $(OUTDIR)/protocolPTZ_ONVIF.o $(OUTDIR)/protocolPTZ_PELCO.o \ + $(OUTDIR)/protocolPTZ_VISCA.o $(OUTDIR)/serverPort.o \ + $(OUTDIR)/sqlite_class.o $(OUTDIR)/SQLite_dataBinder.o \ + $(OUTDIR)/Transform.o $(OUTDIR)/transportSerial.o \ + $(OUTDIR)/transportSocket.o $(OUTDIR)/utm.o \ + $(OUTDIR)/videoAVLIBSource.o $(OUTDIR)/videoLive555AVLibSource.o \ + $(OUTDIR)/xmlParser.o +OBJ=$(COMMON_OBJ) $(CFG_OBJ) +ALL_OBJ=$(OUTDIR)/base64.o $(OUTDIR)/basicCameraInfo.o \ + $(OUTDIR)/basicDualThread.o $(OUTDIR)/basicEngine.o \ + $(OUTDIR)/basicEvent.o $(OUTDIR)/basicEventHandler.o \ + $(OUTDIR)/basicEventHeap.o $(OUTDIR)/basicFunctionality.o \ + $(OUTDIR)/basicLIBAV.o $(OUTDIR)/basicLogCollection.o \ + $(OUTDIR)/basicLoggingService.o $(OUTDIR)/basicMemoryOperation.o \ + $(OUTDIR)/basicObject.o $(OUTDIR)/basicPosition.o \ + $(OUTDIR)/basicRing.o $(OUTDIR)/basicSettings.o \ + $(OUTDIR)/basicSettingsProvider.o $(OUTDIR)/basicThread.o \ + $(OUTDIR)/basicTransport.o $(OUTDIR)/clientPort.o \ + $(OUTDIR)/curlRequest.o $(OUTDIR)/curlRequestsManager.o \ + $(OUTDIR)/dataBinder.o $(OUTDIR)/detector.o $(OUTDIR)/deviceNode.o \ + $(OUTDIR)/deviceNode2D.o $(OUTDIR)/deviceNode3D.o \ + $(OUTDIR)/deviceNodeCamera.o $(OUTDIR)/deviceNodeEthernet2Serial.o \ + $(OUTDIR)/deviceNodeFactory.o $(OUTDIR)/deviceNodePTZCamControl.o \ + $(OUTDIR)/deviceNodeSensor.o $(OUTDIR)/deviceNodeStaticCamControl.o \ + $(OUTDIR)/hardwareManager.o $(OUTDIR)/hardwareResource.o \ + $(OUTDIR)/hardwareResourceDryContactProvider.o \ + $(OUTDIR)/hardwareResourceNetworkProvider.o \ + $(OUTDIR)/hardwareResourceSerialProvider.o \ + $(OUTDIR)/hardwareResourceVideoProvider.o $(OUTDIR)/heapDebug.o \ + $(OUTDIR)/hid_dc.o $(OUTDIR)/json_reader.o $(OUTDIR)/json_value.o \ + $(OUTDIR)/json_writer.o $(OUTDIR)/kernelEventFilter.o \ + $(OUTDIR)/kernelEventFilterAPF.o $(OUTDIR)/kernelModule.o \ + $(OUTDIR)/kernelModuleEmbedVideo.o $(OUTDIR)/kernelModuleFactory.o \ + $(OUTDIR)/kernelModuleFlyHunter.o $(OUTDIR)/kernelModuleKafka.o \ + $(OUTDIR)/kernelModuleModemManager.o \ + $(OUTDIR)/kernelModuleOnvifObserver.o $(OUTDIR)/kernelModuleSSDP.o \ + $(OUTDIR)/kernelModuleUSBRelay.o $(OUTDIR)/kernelPrototype.o \ + $(OUTDIR)/libzip.o $(OUTDIR)/mask.o $(OUTDIR)/md5.o \ + $(OUTDIR)/mojoBackend.o $(OUTDIR)/mojoKernel.o \ + $(OUTDIR)/mysql_class.o $(OUTDIR)/MySQL_dataBinder.o \ + $(OUTDIR)/netClientHandler.o $(OUTDIR)/netServer.o \ + $(OUTDIR)/objectFileLoggingService.o $(OUTDIR)/objectSystemAnchor.o \ + $(OUTDIR)/ponvif.o $(OUTDIR)/protocol.o $(OUTDIR)/protocolHTTP.o \ + $(OUTDIR)/protocolKAFKA.o $(OUTDIR)/protocolLGS2D.o \ + $(OUTDIR)/protocolLGS3D.o $(OUTDIR)/protocolLGS3D_client.o \ + $(OUTDIR)/protocolONVIF.o $(OUTDIR)/protocolPTZ.o \ + $(OUTDIR)/protocolPTZ_ONVIF.o $(OUTDIR)/protocolPTZ_PELCO.o \ + $(OUTDIR)/protocolPTZ_VISCA.o $(OUTDIR)/serverPort.o \ + $(OUTDIR)/sqlite_class.o $(OUTDIR)/SQLite_dataBinder.o \ + $(OUTDIR)/Transform.o $(OUTDIR)/transportSerial.o \ + $(OUTDIR)/transportSocket.o $(OUTDIR)/utm.o \ + $(OUTDIR)/videoAVLIBSource.o $(OUTDIR)/videoLive555AVLibSource.o \ + $(OUTDIR)/xmlParser.o -lsqlite3 -lpthread -lmysqlclient -lssl -lcurl \ + -lm -lcrypto -lconfig -lz -lv4l1 -lv4l2 -lhidapi-libusb `pkg-config \ + libavcodec libavdevice libavfilter libavformat libavutil libpostproc \ + libswresample libswscale --libs` -latomic `pkg-config --libs openssl \ + opencv4 rdkafka++` -lwiringPi -lliveMedia -lgroupsock \ + -lBasicUsageEnvironment -lUsageEnvironment + +COMPILE=g++ -c -x c++ "-DDEBUG" "-D__STDC_CONSTANT_MACROS" "-D_CLIENT_APPLICATION_" "-D_OPENCV_" "-DRASPI_HARDWARE" -O0 -g1 -ggdb -w -Wpointer-arith -std=c++11 -Wno-write-strings -I../../lib/include -I/usr/local/include/liveMedia -I/usr/local/include/BasicUsageEnvironment -I/usr/local/include/UsageEnvironment -I/usr/local/include/groupsock `pkg-config opencv4 libavcodec libavdevice libavfilter libavformat libavutil libpostproc libswresample libswscale --cflags` -o "$(OUTDIR)/$(*F).o" $(CFG_INC) $< +LINK=g++ -O0 -g1 -ggdb -w -o "$(OUTFILE)" $(ALL_OBJ) + +# Pattern rules +$(OUTDIR)/%.o : ../../lib/components/object/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/json/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/transport/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/protocol/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/App/mojo/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/App/common/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/net/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/media/video/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/hardware/hid/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/alg/lgs/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/mysql/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/components/base/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/curl/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/alg/generic/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/sqlite/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/ponvif/%.cpp + $(COMPILE) + +# Build rules +all: $(OUTFILE) + +$(OUTFILE): $(OUTDIR) $(OBJ) + $(LINK) + +$(OUTDIR): + $(MKDIR) -p "$(OUTDIR)" + +# Rebuild this project +rebuild: cleanall + @$(MAKE) -f "$(strip $(MAKEFILE_LIST))" $(MAKEFLAGS) all + +# Clean this project +clean: + $(RM) -f $(OUTFILE) + $(RM) -f $(OBJ) + +# Clean this project and all dependencies +cleanall: clean +endif + +# +# Configuration: Release +# +ifeq "$(CFG)" "Release" +OUTDIR=Release +OUTFILE=$(OUTDIR)/mojo +CFG_INC= +CFG_LIB= +CFG_OBJ= +COMMON_OBJ=$(OUTDIR)/base64.o $(OUTDIR)/basicCameraInfo.o \ + $(OUTDIR)/basicDualThread.o $(OUTDIR)/basicEngine.o \ + $(OUTDIR)/basicEvent.o $(OUTDIR)/basicEventHandler.o \ + $(OUTDIR)/basicEventHeap.o $(OUTDIR)/basicFunctionality.o \ + $(OUTDIR)/basicLIBAV.o $(OUTDIR)/basicLogCollection.o \ + $(OUTDIR)/basicLoggingService.o $(OUTDIR)/basicMemoryOperation.o \ + $(OUTDIR)/basicObject.o $(OUTDIR)/basicPosition.o \ + $(OUTDIR)/basicRing.o $(OUTDIR)/basicSettings.o \ + $(OUTDIR)/basicSettingsProvider.o $(OUTDIR)/basicThread.o \ + $(OUTDIR)/basicTransport.o $(OUTDIR)/clientPort.o \ + $(OUTDIR)/curlRequest.o $(OUTDIR)/curlRequestsManager.o \ + $(OUTDIR)/dataBinder.o $(OUTDIR)/detector.o $(OUTDIR)/deviceNode.o \ + $(OUTDIR)/deviceNode2D.o $(OUTDIR)/deviceNode3D.o \ + $(OUTDIR)/deviceNodeCamera.o $(OUTDIR)/deviceNodeEthernet2Serial.o \ + $(OUTDIR)/deviceNodeFactory.o $(OUTDIR)/deviceNodePTZCamControl.o \ + $(OUTDIR)/deviceNodeSensor.o $(OUTDIR)/deviceNodeStaticCamControl.o \ + $(OUTDIR)/hardwareManager.o $(OUTDIR)/hardwareResource.o \ + $(OUTDIR)/hardwareResourceDryContactProvider.o \ + $(OUTDIR)/hardwareResourceNetworkProvider.o \ + $(OUTDIR)/hardwareResourceSerialProvider.o \ + $(OUTDIR)/hardwareResourceVideoProvider.o $(OUTDIR)/heapDebug.o \ + $(OUTDIR)/hid_dc.o $(OUTDIR)/json_reader.o $(OUTDIR)/json_value.o \ + $(OUTDIR)/json_writer.o $(OUTDIR)/kernelEventFilter.o \ + $(OUTDIR)/kernelEventFilterAPF.o $(OUTDIR)/kernelModule.o \ + $(OUTDIR)/kernelModuleEmbedVideo.o $(OUTDIR)/kernelModuleFactory.o \ + $(OUTDIR)/kernelModuleFlyHunter.o $(OUTDIR)/kernelModuleKafka.o \ + $(OUTDIR)/kernelModuleModemManager.o \ + $(OUTDIR)/kernelModuleOnvifObserver.o $(OUTDIR)/kernelModuleSSDP.o \ + $(OUTDIR)/kernelModuleUSBRelay.o $(OUTDIR)/kernelPrototype.o \ + $(OUTDIR)/libzip.o $(OUTDIR)/mask.o $(OUTDIR)/md5.o \ + $(OUTDIR)/mojoBackend.o $(OUTDIR)/mojoKernel.o \ + $(OUTDIR)/mysql_class.o $(OUTDIR)/MySQL_dataBinder.o \ + $(OUTDIR)/netClientHandler.o $(OUTDIR)/netServer.o \ + $(OUTDIR)/objectFileLoggingService.o $(OUTDIR)/objectSystemAnchor.o \ + $(OUTDIR)/ponvif.o $(OUTDIR)/protocol.o $(OUTDIR)/protocolHTTP.o \ + $(OUTDIR)/protocolKAFKA.o $(OUTDIR)/protocolLGS2D.o \ + $(OUTDIR)/protocolLGS3D.o $(OUTDIR)/protocolLGS3D_client.o \ + $(OUTDIR)/protocolONVIF.o $(OUTDIR)/protocolPTZ.o \ + $(OUTDIR)/protocolPTZ_ONVIF.o $(OUTDIR)/protocolPTZ_PELCO.o \ + $(OUTDIR)/protocolPTZ_VISCA.o $(OUTDIR)/serverPort.o \ + $(OUTDIR)/sqlite_class.o $(OUTDIR)/SQLite_dataBinder.o \ + $(OUTDIR)/Transform.o $(OUTDIR)/transportSerial.o \ + $(OUTDIR)/transportSocket.o $(OUTDIR)/utm.o \ + $(OUTDIR)/videoAVLIBSource.o $(OUTDIR)/videoLive555AVLibSource.o \ + $(OUTDIR)/xmlParser.o +OBJ=$(COMMON_OBJ) $(CFG_OBJ) +ALL_OBJ=$(OUTDIR)/base64.o $(OUTDIR)/basicCameraInfo.o \ + $(OUTDIR)/basicDualThread.o $(OUTDIR)/basicEngine.o \ + $(OUTDIR)/basicEvent.o $(OUTDIR)/basicEventHandler.o \ + $(OUTDIR)/basicEventHeap.o $(OUTDIR)/basicFunctionality.o \ + $(OUTDIR)/basicLIBAV.o $(OUTDIR)/basicLogCollection.o \ + $(OUTDIR)/basicLoggingService.o $(OUTDIR)/basicMemoryOperation.o \ + $(OUTDIR)/basicObject.o $(OUTDIR)/basicPosition.o \ + $(OUTDIR)/basicRing.o $(OUTDIR)/basicSettings.o \ + $(OUTDIR)/basicSettingsProvider.o $(OUTDIR)/basicThread.o \ + $(OUTDIR)/basicTransport.o $(OUTDIR)/clientPort.o \ + $(OUTDIR)/curlRequest.o $(OUTDIR)/curlRequestsManager.o \ + $(OUTDIR)/dataBinder.o $(OUTDIR)/detector.o $(OUTDIR)/deviceNode.o \ + $(OUTDIR)/deviceNode2D.o $(OUTDIR)/deviceNode3D.o \ + $(OUTDIR)/deviceNodeCamera.o $(OUTDIR)/deviceNodeEthernet2Serial.o \ + $(OUTDIR)/deviceNodeFactory.o $(OUTDIR)/deviceNodePTZCamControl.o \ + $(OUTDIR)/deviceNodeSensor.o $(OUTDIR)/deviceNodeStaticCamControl.o \ + $(OUTDIR)/hardwareManager.o $(OUTDIR)/hardwareResource.o \ + $(OUTDIR)/hardwareResourceDryContactProvider.o \ + $(OUTDIR)/hardwareResourceNetworkProvider.o \ + $(OUTDIR)/hardwareResourceSerialProvider.o \ + $(OUTDIR)/hardwareResourceVideoProvider.o $(OUTDIR)/heapDebug.o \ + $(OUTDIR)/hid_dc.o $(OUTDIR)/json_reader.o $(OUTDIR)/json_value.o \ + $(OUTDIR)/json_writer.o $(OUTDIR)/kernelEventFilter.o \ + $(OUTDIR)/kernelEventFilterAPF.o $(OUTDIR)/kernelModule.o \ + $(OUTDIR)/kernelModuleEmbedVideo.o $(OUTDIR)/kernelModuleFactory.o \ + $(OUTDIR)/kernelModuleFlyHunter.o $(OUTDIR)/kernelModuleKafka.o \ + $(OUTDIR)/kernelModuleModemManager.o \ + $(OUTDIR)/kernelModuleOnvifObserver.o $(OUTDIR)/kernelModuleSSDP.o \ + $(OUTDIR)/kernelModuleUSBRelay.o $(OUTDIR)/kernelPrototype.o \ + $(OUTDIR)/libzip.o $(OUTDIR)/mask.o $(OUTDIR)/md5.o \ + $(OUTDIR)/mojoBackend.o $(OUTDIR)/mojoKernel.o \ + $(OUTDIR)/mysql_class.o $(OUTDIR)/MySQL_dataBinder.o \ + $(OUTDIR)/netClientHandler.o $(OUTDIR)/netServer.o \ + $(OUTDIR)/objectFileLoggingService.o $(OUTDIR)/objectSystemAnchor.o \ + $(OUTDIR)/ponvif.o $(OUTDIR)/protocol.o $(OUTDIR)/protocolHTTP.o \ + $(OUTDIR)/protocolKAFKA.o $(OUTDIR)/protocolLGS2D.o \ + $(OUTDIR)/protocolLGS3D.o $(OUTDIR)/protocolLGS3D_client.o \ + $(OUTDIR)/protocolONVIF.o $(OUTDIR)/protocolPTZ.o \ + $(OUTDIR)/protocolPTZ_ONVIF.o $(OUTDIR)/protocolPTZ_PELCO.o \ + $(OUTDIR)/protocolPTZ_VISCA.o $(OUTDIR)/serverPort.o \ + $(OUTDIR)/sqlite_class.o $(OUTDIR)/SQLite_dataBinder.o \ + $(OUTDIR)/Transform.o $(OUTDIR)/transportSerial.o \ + $(OUTDIR)/transportSocket.o $(OUTDIR)/utm.o \ + $(OUTDIR)/videoAVLIBSource.o $(OUTDIR)/videoLive555AVLibSource.o \ + $(OUTDIR)/xmlParser.o + +COMPILE=g++ -c -x c++ "-DSLIM_KERNEL" "-D_THREAD_SAFE" "-D_BSD_SOURCE" "-D_REENTRANT" -O3 -w -Wpointer-arith -std=gnu++11 -I../../lib/include -o "$(OUTDIR)/$(*F).o" $(CFG_INC) $< +LINK=g++ -O3 -w -lconfig -lpthread -lelf -lcurses -lcdk -lcurl `pkg-config --libs rdkafka++` -lsqlite3 -s -o "$(OUTFILE)" $(ALL_OBJ) + +# Pattern rules +$(OUTDIR)/%.o : ../../lib/components/object/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/json/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/transport/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/protocol/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/App/mojo/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/App/common/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/net/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/media/video/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/hardware/hid/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/alg/lgs/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/mysql/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/components/base/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/curl/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/alg/generic/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/sqlite/%.cpp + $(COMPILE) + +$(OUTDIR)/%.o : ../../lib/data/ponvif/%.cpp + $(COMPILE) + +# Build rules +all: $(OUTFILE) + +$(OUTFILE): $(OUTDIR) $(OBJ) + $(LINK) + +$(OUTDIR): + $(MKDIR) -p "$(OUTDIR)" + +# Rebuild this project +rebuild: cleanall + @$(MAKE) -f "$(strip $(MAKEFILE_LIST))" $(MAKEFLAGS) all + +# Clean this project +clean: + $(RM) -f $(OUTFILE) + $(RM) -f $(OBJ) + +# Clean this project and all dependencies +cleanall: clean +endif + +# +# include dependencies: +# +$(OUTDIR)/base64.o: ../../lib/alg/generic/base64.cpp ../../lib/alg/generic/base64.h +$(OUTDIR)/basicCameraInfo.o: ../../lib/components/base/basicCameraInfo.cpp ../../lib/components/base/basicCameraInfo.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h +$(OUTDIR)/basicDualThread.o: ../../lib/components/base/basicDualThread.cpp ../../lib/components/base/basicDualThread.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h +$(OUTDIR)/basicEngine.o: ../../lib/components/base/basicEngine.cpp ../../lib/components/base/basicEngine.h ../../lib/components/base/basicObject.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicValidatable.h ../../lib/components/base/basicMutex.h +$(OUTDIR)/basicEvent.o: ../../lib/components/base/basicEvent.cpp ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h +$(OUTDIR)/basicEventHandler.o: ../../lib/components/base/basicEventHandler.cpp ../../lib/components/base/basicEventHandler.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h ../../lib/components/base/basicEventHeap.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h +$(OUTDIR)/basicEventHeap.o: ../../lib/components/base/basicEventHeap.cpp ../../lib/components/base/basicEventHeap.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h ../../lib/components/base/basicEventHandler.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h +$(OUTDIR)/basicFunctionality.o: ../../lib/components/base/basicFunctionality.cpp ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h ../../lib/alg/generic/md5.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h +$(OUTDIR)/basicLIBAV.o: ../../lib/components/base/basicLIBAV.cpp ../../lib/components/base/basicLIBAV.h +$(OUTDIR)/basicLogCollection.o: ../../lib/components/base/basicLogCollection.cpp ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/alg/generic/heapDebug.h +$(OUTDIR)/basicLoggingService.o: ../../lib/components/base/basicLoggingService.cpp ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h +$(OUTDIR)/basicMemoryOperation.o: ../../lib/components/base/basicMemoryOperation.cpp ../../lib/components/base/basicMemoryOperation.h +$(OUTDIR)/basicObject.o: ../../lib/components/base/basicObject.cpp ../../lib/components/base/basicObject.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicValidatable.h ../../lib/alg/generic/md5.h +$(OUTDIR)/basicPosition.o: ../../lib/components/base/basicPosition.cpp ../../lib/components/base/basicPosition.h +$(OUTDIR)/basicRing.o: ../../lib/components/base/basicRing.cpp ../../lib/components/base/basicRing.h +$(OUTDIR)/basicSettings.o: ../../lib/components/base/basicSettings.cpp ../../lib/components/base/basicSettings.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h +$(OUTDIR)/basicSettingsProvider.o: ../../lib/components/base/basicSettingsProvider.cpp ../../lib/components/base/basicSettingsProvider.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h +$(OUTDIR)/basicThread.o: ../../lib/components/base/basicThread.cpp ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h +$(OUTDIR)/basicTransport.o: ../../lib/components/base/basicTransport.cpp ../../lib/components/base/basicTransport.h ../../lib/data/protocol/protocol.h +$(OUTDIR)/clientPort.o: ../../lib/data/net/clientPort.cpp ../../lib/data/net/clientPort.h ../../lib/data/transport/transportSocket.h ../../lib/components/base/basicDualThread.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicTransport.h +$(OUTDIR)/curlRequest.o: ../../lib/data/curl/curlRequest.cpp ../../lib/data/curl/curlRequest.h +$(OUTDIR)/curlRequestsManager.o: ../../lib/data/curl/curlRequestsManager.cpp ../../lib/data/curl/curlRequestsManager.h +$(OUTDIR)/dataBinder.o: ../../lib/App/common/dataBinder.cpp ../../lib/App/common/dataBinder.h ../../lib/App/common/dataBinder_structures.h +$(OUTDIR)/detector.o: ../../lib/alg/lgs/detector.cpp ../../lib/alg/lgs/detector.h ../../lib/components/base/basicObject.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicValidatable.h ../../lib/alg/lgs/detectorStructures.h ../../lib/components/base/basicTypes.h +$(OUTDIR)/deviceNode.o: ../../lib/App/common/deviceNode.cpp ../../lib/App/common/deviceNode.h ../../lib/App/common/MySQL_dataBinder.h ../../lib/App/common/SQLite_dataBinder.h +$(OUTDIR)/deviceNode2D.o: ../../lib/App/common/deviceNode2D.cpp ../../lib/App/common/deviceNode2D.h ../../lib/App/common/hardwareResourceSerialProvider.h ../../lib/App/common/kernelPrototype.h ../../lib/App/common/hardwareManager.h +$(OUTDIR)/deviceNode3D.o: ../../lib/App/common/deviceNode3D.cpp ../../lib/App/common/deviceNode3D.h +$(OUTDIR)/deviceNodeCamera.o: ../../lib/App/common/deviceNodeCamera.cpp ../../lib/App/common/deviceNodeCamera.h ../../lib/components/base/basicCameraInfo.h ../../lib/components/object/objectSystemAnchor.h ../../lib/hardware/uart/serialPort.h ../../lib/hardware/uart/serialSOL.h ../../lib/data/protocol/protocolPTZ_VISCA.h ../../lib/data/protocol/protocolPTZ_ONVIF.h ../../lib/data/protocol/protocolPTZ_PELCO.h ../../lib/App/common/hardwareManager.h ../../lib/App/common/hardwareResourceSerialProvider.h +$(OUTDIR)/deviceNodeEthernet2Serial.o: ../../lib/App/common/deviceNodeEthernet2Serial.cpp ../../lib/App/common/deviceNodeEthernet2Serial.h ../../lib/App/common/hardwareManager.h ../../lib/data/protocol/protocol.h +$(OUTDIR)/deviceNodeFactory.o: ../../lib/App/common/deviceNodeFactory.cpp ../../lib/App/common/deviceNodeFactory.h ../../lib/App/common/MySQL_dataBinder.h ../../lib/App/common/SQLite_dataBinder.h ../../lib/App/common/deviceNode3D.h ../../lib/App/common/deviceNode2D.h ../../lib/App/common/deviceNodePTZCamControl.h ../../lib/App/common/deviceNodeStaticCamControl.h ../../lib/App/common/deviceNodeEthernet2Serial.h +$(OUTDIR)/deviceNodePTZCamControl.o: ../../lib/App/common/deviceNodePTZCamControl.cpp ../../lib/App/common/deviceNodePTZCamControl.h +$(OUTDIR)/deviceNodeSensor.o: ../../lib/App/common/deviceNodeSensor.cpp ../../lib/App/common/deviceNodeSensor.h ../../lib/components/object/objectSystemAnchor.h +$(OUTDIR)/deviceNodeStaticCamControl.o: ../../lib/App/common/deviceNodeStaticCamControl.cpp ../../lib/App/common/deviceNodeStaticCamControl.h +$(OUTDIR)/hardwareManager.o: ../../lib/App/common/hardwareManager.cpp ../../lib/App/common/hardwareManager.h ../../lib/App/common/MySQL_dataBinder.h ../../lib/App/common/SQLite_dataBinder.h ../../lib/App/common/hardwareResourceSerialProvider.h ../../lib/App/common/hardwareResourceNetworkProvider.h +$(OUTDIR)/hardwareResource.o: ../../lib/App/common/hardwareResource.cpp ../../lib/App/common/hardwareResource.h ../../lib/App/common/MySQL_dataBinder.h ../../lib/App/common/SQLite_dataBinder.h +$(OUTDIR)/hardwareResourceDryContactProvider.o: ../../lib/App/common/hardwareResourceDryContactProvider.cpp ../../lib/App/common/hardwareResourceDryContactProvider.h +$(OUTDIR)/hardwareResourceNetworkProvider.o: ../../lib/App/common/hardwareResourceNetworkProvider.cpp ../../lib/App/common/hardwareResourceNetworkProvider.h +$(OUTDIR)/hardwareResourceSerialProvider.o: ../../lib/App/common/hardwareResourceSerialProvider.cpp ../../lib/App/common/hardwareResourceSerialProvider.h +$(OUTDIR)/hardwareResourceVideoProvider.o: ../../lib/App/common/hardwareResourceVideoProvider.cpp ../../lib/App/common/hardwareResourceVideoProvider.h +$(OUTDIR)/heapDebug.o: ../../lib/alg/generic/heapDebug.cpp ../../lib/alg/generic/heapDebug.h +$(OUTDIR)/hid_dc.o: ../../lib/hardware/hid/hid_dc.cpp +$(OUTDIR)/json_reader.o: ../../lib/data/json/json_reader.cpp ../../lib/data/json/json_tool.h +$(OUTDIR)/json_value.o: ../../lib/data/json/json_value.cpp ../../lib/data/json/json_valueiterator.inl +$(OUTDIR)/json_writer.o: ../../lib/data/json/json_writer.cpp ../../lib/data/json/json_tool.h +$(OUTDIR)/kernelEventFilter.o: ../../lib/App/common/kernelEventFilter.cpp ../../lib/App/common/kernelEventFilter.h +$(OUTDIR)/kernelEventFilterAPF.o: ../../lib/App/common/kernelEventFilterAPF.cpp ../../lib/App/common/kernelEventFilterAPF.h ../../lib/App/common/MySQL_dataBinder.h ../../lib/App/common/SQLite_dataBinder.h +$(OUTDIR)/kernelModule.o: ../../lib/App/common/kernelModule.cpp ../../lib/App/common/kernelModule.h ../../lib/App/common/MySQL_dataBinder.h ../../lib/App/common/SQLite_dataBinder.h +$(OUTDIR)/kernelModuleEmbedVideo.o: ../../lib/App/common/kernelModuleEmbedVideo.cpp ../../lib/App/common/kernelModuleEmbedVideo.h +$(OUTDIR)/kernelModuleFactory.o: ../../lib/App/common/kernelModuleFactory.cpp ../../lib/App/common/kernelModuleFactory.h ../../lib/App/common/kernelModuleUSBRelay.h ../../lib/App/common/kernelModuleKafka.h ../../lib/App/common/kernelModuleFlyHunter.h ../../lib/App/common/kernelModuleSSDP.h ../../lib/App/common/kernelModuleOnvifObserver.h ../../lib/App/common/kernelModuleEmbedVideo.h ../../lib/App/common/kernelModuleModemManager.h ../../lib/App/common/MySQL_dataBinder.h ../../lib/App/common/SQLite_dataBinder.h +$(OUTDIR)/kernelModuleFlyHunter.o: ../../lib/App/common/kernelModuleFlyHunter.cpp ../../lib/App/common/kernelModuleFlyHunter.h +$(OUTDIR)/kernelModuleKafka.o: ../../lib/App/common/kernelModuleKafka.cpp ../../lib/App/common/kernelModuleKafka.h +$(OUTDIR)/kernelModuleModemManager.o: ../../lib/App/common/kernelModuleModemManager.cpp ../../lib/App/common/kernelModuleModemManager.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h +$(OUTDIR)/kernelModuleOnvifObserver.o: ../../lib/App/common/kernelModuleOnvifObserver.cpp ../../lib/App/common/kernelModuleOnvifObserver.h ../../lib/App/common/hardwareManager.h ../../lib/App/common/hardwareResourceNetworkProvider.h +$(OUTDIR)/kernelModuleSSDP.o: ../../lib/App/common/kernelModuleSSDP.cpp ../../lib/App/common/kernelModuleSSDP.h +$(OUTDIR)/kernelModuleUSBRelay.o: ../../lib/App/common/kernelModuleUSBRelay.cpp ../../lib/App/common/kernelModuleUSBRelay.h +$(OUTDIR)/kernelPrototype.o: ../../lib/App/common/kernelPrototype.cpp ../../lib/App/common/kernelPrototype.h ../../lib/App/common/MySQL_dataBinder.h ../../lib/App/common/SQLite_dataBinder.h +$(OUTDIR)/libzip.o: ../../lib/alg/generic/libzip.cpp ../../lib/alg/generic/libzip.h +$(OUTDIR)/mask.o: ../../lib/alg/lgs/mask.cpp ../../lib/alg/lgs/mask.h ../../lib/components/base/basicTypes.h ../../lib/hardware/soc/general/3DLRF.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/gui/gui.h +$(OUTDIR)/md5.o: ../../lib/alg/generic/md5.cpp ../../lib/alg/generic/md5.h +$(OUTDIR)/mojoBackend.o: ../../lib/App/mojo/mojoBackend.cpp ../../lib/App/mojo/mojoBackend.h ../../lib/components/base/basicSettings.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicMemoryOperation.h ../../lib/components/object/objectFileLoggingService.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/App/mojo/mojoKernel.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicSettingsProvider.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicEventHeap.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h ../../lib/components/object/objectSystemAnchor.h ../../lib/alg/lgs/detectorStructures.h ../../lib/components/base/basicTypes.h ../../lib/alg/lgs/detector.h ../../lib/components/base/basicObject.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicValidatable.h ../../lib/alg/lgs/detectorStructures.h ../../lib/components/base/basicTypes.h ../../lib/alg/lgs/mask.h ../../lib/components/base/basicTypes.h ../../lib/hardware/soc/general/3DLRF.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/gui/gui.h ../../lib/alg/generic/md5.h ../../lib/App/common/kernelPrototype.h ../../lib/App/common/MySQL_dataBinder.h ../../lib/App/common/SQLite_dataBinder.h +$(OUTDIR)/mojoKernel.o: ../../lib/App/mojo/mojoKernel.cpp ../../lib/App/mojo/mojoKernel.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicSettingsProvider.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicEventHeap.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h ../../lib/components/object/objectSystemAnchor.h ../../lib/alg/lgs/detectorStructures.h ../../lib/components/base/basicTypes.h ../../lib/alg/lgs/detector.h ../../lib/components/base/basicObject.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicValidatable.h ../../lib/alg/lgs/detectorStructures.h ../../lib/components/base/basicTypes.h ../../lib/alg/lgs/mask.h ../../lib/components/base/basicTypes.h ../../lib/hardware/soc/general/3DLRF.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/gui/gui.h ../../lib/alg/generic/md5.h ../../lib/App/common/kernelPrototype.h ../../lib/App/common/kernelEventFilterAPF.h +$(OUTDIR)/mysql_class.o: ../../lib/data/mysql/mysql_class.cpp ../../lib/data/mysql/mysql_class.h +$(OUTDIR)/MySQL_dataBinder.o: ../../lib/App/common/MySQL_dataBinder.cpp ../../lib/App/common/MySQL_dataBinder.h +$(OUTDIR)/netClientHandler.o: ../../lib/data/net/netClientHandler.cpp ../../lib/data/net/netClientHandler.h ../../lib/data/protocol/protocol.h ../../lib/components/base/basicEventHandler.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/data/net/serverPort.h ../../lib/data/transport/transportSocket.h ../../lib/components/base/basicDualThread.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicTransport.h ../../lib/data/net/netServiceEngine.h +$(OUTDIR)/netServer.o: ../../lib/data/net/netServer.cpp ../../lib/data/net/netServer.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicSettingsProvider.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicEventHeap.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h ../../lib/data/protocol/protocol.h ../../lib/data/net/netServiceEngine.h ../../lib/data/net/netClientHandler.h ../../lib/data/protocol/protocol.h ../../lib/components/base/basicEventHandler.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/data/net/serverPort.h ../../lib/data/transport/transportSocket.h ../../lib/components/base/basicDualThread.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicTransport.h ../../lib/data/net/netServiceEngine.h ../../lib/data/net/netClientHandler.h ../../lib/data/protocol/protocol.h ../../lib/components/base/basicEventHandler.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicEvent.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicPosition.h ../../lib/alg/generic/Transform.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/data/net/serverPort.h ../../lib/data/transport/transportSocket.h ../../lib/components/base/basicDualThread.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicTransport.h ../../lib/data/net/netServiceEngine.h +$(OUTDIR)/objectFileLoggingService.o: ../../lib/components/object/objectFileLoggingService.cpp ../../lib/components/object/objectFileLoggingService.h ../../lib/components/base/basicFunctionality.h ../../lib/components/base/basicBuildTimeStamp.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h +$(OUTDIR)/objectSystemAnchor.o: ../../lib/components/object/objectSystemAnchor.cpp ../../lib/components/object/objectSystemAnchor.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h +$(OUTDIR)/ponvif.o: ../../lib/data/ponvif/ponvif.cpp ../../lib/data/ponvif/ponvif.h +$(OUTDIR)/protocol.o: ../../lib/data/protocol/protocol.cpp ../../lib/data/protocol/protocol.h +$(OUTDIR)/protocolHTTP.o: ../../lib/data/protocol/protocolHTTP.cpp ../../lib/data/protocol/protocolHTTP.h +$(OUTDIR)/protocolKAFKA.o: ../../lib/data/protocol/protocolKAFKA.cpp ../../lib/data/protocol/protocolKAFKA.h ../../lib/alg/generic/md5.h ../../lib/data/json/json_tool.h +$(OUTDIR)/protocolLGS2D.o: ../../lib/data/protocol/protocolLGS2D.cpp ../../lib/data/protocol/protocolLGS2D.h +$(OUTDIR)/protocolLGS3D.o: ../../lib/data/protocol/protocolLGS3D.cpp ../../lib/data/protocol/protocolLGS3D.h +$(OUTDIR)/protocolLGS3D_client.o: ../../lib/data/protocol/protocolLGS3D_client.cpp ../../lib/data/protocol/protocolLGS3D_client.h +$(OUTDIR)/protocolONVIF.o: ../../lib/data/protocol/protocolONVIF.cpp ../../lib/data/protocol/protocolONVIF.h +$(OUTDIR)/protocolPTZ.o: ../../lib/data/protocol/protocolPTZ.cpp ../../lib/data/protocol/protocolPTZ.h +$(OUTDIR)/protocolPTZ_ONVIF.o: ../../lib/data/protocol/protocolPTZ_ONVIF.cpp ../../lib/data/protocol/protocolPTZ_ONVIF.h ../../lib/hardware/uart/serialPort.h +$(OUTDIR)/protocolPTZ_PELCO.o: ../../lib/data/protocol/protocolPTZ_PELCO.cpp ../../lib/data/protocol/protocolPTZ_PELCO.h +$(OUTDIR)/protocolPTZ_VISCA.o: ../../lib/data/protocol/protocolPTZ_VISCA.cpp ../../lib/data/protocol/protocolPTZ_VISCA.h +$(OUTDIR)/serverPort.o: ../../lib/data/net/serverPort.cpp ../../lib/data/net/serverPort.h ../../lib/data/transport/transportSocket.h ../../lib/components/base/basicDualThread.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicTransport.h +$(OUTDIR)/sqlite_class.o: ../../lib/data/sqlite/sqlite_class.cpp ../../lib/data/sqlite/sqlite_class.h ../../lib/components/base/basicTypes.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h +$(OUTDIR)/SQLite_dataBinder.o: ../../lib/App/common/SQLite_dataBinder.cpp ../../lib/App/common/SQLite_dataBinder.h +$(OUTDIR)/Transform.o: ../../lib/alg/generic/Transform.cpp ../../lib/alg/generic/Transform.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h +$(OUTDIR)/transportSerial.o: ../../lib/data/transport/transportSerial.cpp ../../lib/data/transport/transportSerial.h ../../lib/components/base/basicDualThread.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicTransport.h ../../lib/data/protocol/protocol.h +$(OUTDIR)/transportSocket.o: ../../lib/data/transport/transportSocket.cpp ../../lib/data/transport/transportSocket.h ../../lib/components/base/basicDualThread.h ../../lib/components/base/basicThread.h ../../lib/components/base/basicLogCollection.h ../../lib/components/base/basicLoggingService.h ../../lib/components/base/basicRing.h ../../lib/components/base/basicMutex.h ../../lib/components/base/basicTransport.h ../../lib/data/protocol/protocol.h +$(OUTDIR)/utm.o: ../../lib/alg/generic/utm.cpp ../../lib/alg/generic/utm.h +$(OUTDIR)/videoAVLIBSource.o: ../../lib/data/media/video/videoAVLIBSource.cpp ../../lib/data/media/video/videoAVLIBSource.h +$(OUTDIR)/videoLive555AVLibSource.o: ../../lib/data/media/video/videoLive555AVLibSource.cpp ../../lib/data/media/video/videoLive555AVLibSource.h +$(OUTDIR)/xmlParser.o: ../../lib/data/protocol/xmlParser.cpp ../../lib/data/protocol/xmlParser.h diff --git a/Projects/la_mojo/mem_db.db b/Projects/la_mojo/mem_db.db new file mode 100644 index 00000000..a3f4aa19 Binary files /dev/null and b/Projects/la_mojo/mem_db.db differ diff --git a/Projects/la_mojo/mysqlitedb.db b/Projects/la_mojo/mysqlitedb.db new file mode 100644 index 00000000..f3ecb9c1 Binary files /dev/null and b/Projects/la_mojo/mysqlitedb.db differ diff --git a/lib/App/common/MySQL_dataBinder.cpp b/lib/App/common/MySQL_dataBinder.cpp new file mode 100644 index 00000000..68372b2d --- /dev/null +++ b/lib/App/common/MySQL_dataBinder.cpp @@ -0,0 +1,4818 @@ +#include "MySQL_dataBinder.h" + +#define LOG( X ) m_pLog->Log( "MDBC", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "MDBC", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "MDBC", this, _LOG_ERROR, X ); +#endif + +mysqlDBC *mysqlDBC::_instance = NULL; + +/** + * Returns the single instance of the object. + */ +mysqlDBC* mysqlDBC::getInstance( config_setting_t * Settings ) { + // check if the instance has been created yet + if( 0 == _instance ){ + // if not, then create it + _instance = new mysqlDBC( Settings ); + }; + // return the single instance + return _instance; +}; + + +mysqlDBC::mysqlDBC( config_setting_t * Settings ):dataBinder(){ + m_pLog = basicLogCollection::getInstance(); + m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "DBC" ); + m_bIsConnected = false; + m_bIsServerLocal = false; + m_nSiteID = 0; + m_pDatabase = NULL; +}; + +mysqlDBC::~mysqlDBC(){ + m_bIsConnected = false; + if( m_pDatabase != NULL ) delete( m_pDatabase ); + m_pDatabase = NULL; + _instance = NULL; +}; + +bool mysqlDBC::connect( void ){ + config_setting_t * tSetting; + m_bIsConnected = false; + if( m_pSettings!= NULL ) { + tSetting = config_setting_get_member( m_pSettings, "DATABASE_HOST" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "DATABASE_HOST", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "localhost" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No DB Host Setting! Using default!"); + }; + sprintf(m_pDbHost, "%s", config_setting_get_string(tSetting)); + + //Check if using local database + if( strstr( m_pDbHost, "localhost" )!= NULL ){ + m_bIsServerLocal = true; + } else { + // Check if setting is local IP address + + }; + + tSetting = config_setting_get_member(m_pSettings, "DATABASE_NAME"); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "DATABASE_NAME", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "dfsl_gunter" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No DB Database Setting! Using default!"); + }; + sprintf(m_pDbDatabase, "%s", config_setting_get_string(tSetting)); + tSetting = config_setting_get_member( m_pSettings, "DATABASE_USER" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "DATABASE_USER", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "dbroot" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No DB User Setting! Using default!"); + }; + sprintf(m_pDbUsername, "%s", config_setting_get_string(tSetting)); + tSetting = config_setting_get_member( m_pSettings, "DATABASE_PASSWORD" ); + if( tSetting == NULL ){ + tSetting = config_setting_add(m_pSettings, "DATABASE_PASSWORD", CONFIG_TYPE_STRING ); + config_setting_set_string( tSetting, "123567" ); + basicSettingsProvider::getInstance()->compromise(); + LOG("No DB Password Setting! Using default!"); + }; + sprintf(m_pDbPassword, "%s", config_setting_get_string(tSetting)); + basicSettingsProvider::getInstance()->validate(); + m_pDatabase = new MySQL_Connector(); + if( m_pDatabase == NULL )return false; + m_bIsConnected = m_pDatabase->Connect( m_pDbDatabase, m_pDbHost, m_pDbUsername, m_pDbPassword ); + } else { + LOG_ERROR("No Settings Provided!"); + }; + return m_bIsConnected; +}; + +void mysqlDBC::deleteCamCapPicture( uint32_t PicID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `pictures` WHERE `id`=%d", PicID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteNode( uint32_t NodeID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `nodes` WHERE `id`=%d", NodeID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteCamera( uint32_t CamID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `cameras` WHERE `id`=%d", CamID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteResource( uint32_t ResourceID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `resources` WHERE `id`=%d", ResourceID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteSensor( uint32_t SensorID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `lrf_sensors` WHERE `id`=%d", SensorID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteNodeEvents( uint32_t NodeID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf(tQBuf, "DELETE `ep` FROM `events_2_pictures` `ep` LEFT JOIN `events_archive` `ea` ON ( `ep`.`evt_id` = `ea`.`id` ) WHERE `ea`.`node_id`=%d", NodeID); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + + sprintf(tQBuf, "DELETE `ep` FROM `events_2_videos` `ep` LEFT JOIN `events_archive` `ea` ON ( `ep`.`evt_id` = `ea`.`id` ) WHERE `ea`.`node_id`=%d", NodeID); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + + sprintf( tQBuf, "DELETE FROM `events_archive` WHERE `node_id`=%d", NodeID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + + sprintf( tQBuf, "DELETE FROM `events_cloud` WHERE `node_id`=%d", NodeID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteUART( uint32_t UARTID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `uart_settings` WHERE `id`=%d", UARTID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteConnections( uint32_t NodeID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `connections` WHERE `from`=%d OR `to`=%d", NodeID, NodeID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteMediaStream( uint32_t MediaID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `media_streams` WHERE `id`=%d", MediaID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteNIF( uint32_t NifID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `network_interfaces` WHERE `id`=%d", NifID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +void mysqlDBC::deleteNIS( uint32_t NisID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `network_infrastructure` WHERE `id`=%d", NisID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +bool mysqlDBC::cleanEvents2PictureBinding( uint32_t PicID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `events_2_pictures` WHERE `picture_id`=%d", PicID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::cleanEvents2VideoBinding( uint32_t VidID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `events_2_videos` WHERE `video_id`=%d", VidID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + + +bool mysqlDBC::cleanResources(bool all ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + if( all ) { + sprintf( tQBuf, "UPDATE `resources` SET `active`=0 WHERE `node_id`=%d", m_nServerNodeID ); + } else { + sprintf( tQBuf, "UPDATE `resources` SET `active`=0 WHERE ( `node_id`=%d ) AND ( `type`=100 OR `type`=101 OR `type`=103 OR `type`=120 )", m_nServerNodeID ); + }; +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::cleanNodeEvents( uint32_t NodeID, bool all ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + if( all ) { + sprintf( tQBuf, "DELETE FROM `events_cloud` WHERE `node_id`=%d", NodeID ); + m_pDatabase->SilentQuery( tQBuf ); + sprintf( tQBuf, "DELETE FROM `events_archive` WHERE `node_id`=%d", NodeID ); + m_pDatabase->SilentQuery( tQBuf ); + } else { + sprintf( tQBuf, "DELETE FROM `events_cloud` WHERE `node_id`=%d", NodeID ); + }; +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::cleanLRFMask( uint32_t maskID, bool deleteMask ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "DELETE FROM `lrf_mask_trace_zones` WHERE `zone_id` IN ( SELECT `id` FROM `lrf_mask_traces` WHERE `mask_id`=%d )", maskID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + sprintf( tQBuf, "DELETE FROM `lrf_mask_traces` WHERE `mask_id`=%d", maskID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + sprintf( tQBuf, "DELETE FROM `lrf_mask_vertex_points` WHERE `vertex_id` IN ( SELECT `id` FROM `lrf_mask_vertexes` WHERE `mask_id`=%d )", maskID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + sprintf( tQBuf, "DELETE FROM `lrf_mask_vertexes` WHERE `mask_id`=%d", maskID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + //Delete Mask Itself! + if ( deleteMask ) { + sprintf( tQBuf, "DELETE FROM `lrf_masks` WHERE `id`=%d", maskID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; + return true; + }; + return false; +}; + +bool mysqlDBC::updateCamRange( uint32_t camID, float range ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf(tQBuf,"UPDATE cameras SET `max_range`=%.3f WHERE `id`=%d", + range, + camID + ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::updateIPCam( CSTR uuid, CSTR Addr ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + char tIpBuf[CTEXT]; + char *tPos; + char *tPos2; + + tPos = strstr(Addr,"//"); + if( tPos != NULL ) { + tPos2 = strstr( tPos + 2,"/"); + if( tPos2 != NULL ) { + int len; + len = tPos2 - tPos - 2; + strncpy(tIpBuf,tPos + 2,len); + tIpBuf[len] = (char)0; + } else { + LOG_ERROR("Pos 2 - err"); + tIpBuf[0] = (char)0; + }; + } else { + LOG_ERROR("Pos 0 - err"); + tIpBuf[0] = (char)0; + }; + sprintf(tQBuf,"UPDATE cameras SET `online`=1,`onvif_ctrl`='%s', `ip`='%s' WHERE `uuid`='%s'", + Addr, + tIpBuf, + uuid + ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::updateIPCam( uint32_t CamID, CSTR Addr ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + char tIpBuf[CTEXT]; + char *tPos; + char *tPos2; + + tPos = strstr(Addr,"//"); + if( tPos != NULL ) { + tPos2 = strstr( tPos + 2,"/"); + if( tPos2 != NULL ) { + int len; + len = tPos2 - tPos - 2; + strncpy(tIpBuf,tPos + 2,len); + tIpBuf[len] = (char)0; + } else { + LOG_ERROR("Pos 2 - err"); + tIpBuf[0] = (char)0; + }; + } else { + LOG_ERROR("Pos 0 - err"); + tIpBuf[0] = (char)0; + }; + sprintf(tQBuf,"UPDATE cameras SET `online`=1, `onvif_ctrl`='%s', `ip`='%s' WHERE `id`=%d", + Addr, + tIpBuf, + CamID + ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + sprintf(tQBuf,"UPDATE media_streams SET `valid`=1 WHERE source_id=%d AND source_type='D'", CamID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; +/* +bool mysqlDBC::addIPCam( uint32_t SiteID, resultWoWo *tPtr ){ + if(m_bIsConnected) { + char tQBuf[1024]; + char tIpBuf[32]; + char tProto[32]; + char tPath[CTEXT]; + char *tPos; + char *tPos2; + + memcpy( tProto, tPtr->XAddrs, 5 ); + tProto[5] = (char)0; + if( tProto[4] == ':') tProto[4] = (char)0; + memset( tPath, 0, CTEXT ); + tPos = strstr(tPtr->XAddrs,"//"); + if( tPos != NULL ) { + tPos2 = strstr( tPos + 2,"/"); + if( tPos2 != NULL ) { + int len,len2,len3; + len = tPos2 - tPos - 2; + strncpy( tIpBuf, tPos + 2, len); + tIpBuf[len] = (char)0; + strncpy( tPath, tPos + 2 + len, CTEXT ); + } else { + LOG_ERROR("Pos 2 - err"); + tIpBuf[0] = (char)0; + }; + } else { + LOG_ERROR("Pos 0 - err"); + tIpBuf[0] = (char)0; + }; + sprintf(tQBuf,"INSERT INTO cameras SET `online`=1, `uuid`='%s', `onvif_ctrl`='%s', `ip`='%s', `type`=2, `status`=0, `site_id`=%d, `mac`='%s', `hardware`='%s', `name`='%s', `onvif_access`='%s' ON DUPLICATE KEY UPDATE `online`=1, `ip`='%s'", + tPtr->RefID, + //tPtr->XAddrs, + tPath, + tIpBuf, + SiteID, + tPtr->MAC, + tPtr->Hardware, + tPtr->Name, + tProto, + //tPtr->XAddrs, + tIpBuf + ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; +*/ +bool mysqlDBC::addIPCam( OBSERVER_RESULT *tPtr ){ + if(m_bIsConnected) { + char tQBuf[1024]; + char tIpBuf[32]; + char tProto[32]; + char tPath[CTEXT]; + char *tPos; + char *tPos2; + memcpy( tProto, tPtr->XAddrs, 5 ); + tProto[5] = (char)0; + if( tProto[4] == ':') tProto[4] = (char)0; + memset( tPath, 0, CTEXT ); + tPos = strstr(tPtr->XAddrs,"//"); + if( tPos != NULL ) { + tPos2 = strstr( tPos + 2,"/"); + if( tPos2 != NULL ) { + int len,len2,len3; + len = tPos2 - tPos - 2; + strncpy( tIpBuf, tPos + 2, len); + tIpBuf[len] = (char)0; + strncpy( tPath, tPos + 2 + len, CTEXT ); + } else { + LOG_ERROR("Pos 2 - err"); + tIpBuf[0] = (char)0; + }; + } else { + LOG_ERROR("Pos 0 - err"); + tIpBuf[0] = (char)0; + }; + sprintf(tQBuf,"INSERT INTO cameras SET `online`=1, `uuid`='%s', `onvif_ctrl`='%s', `ip`='%s', `type`=2, `status`=0, `site_id`=%d, `mac`='%s', `hardware`='%s', `name`='%s', `onvif_access`='%s' ON DUPLICATE KEY UPDATE `online`=1, `ip`='%s'", + tPtr->RefID, + //tPtr->XAddrs, + tPath, + tIpBuf, + m_nSiteID, + tPtr->MAC, + tPtr->Hardware, + tPtr->Name, + tProto, + //tPtr->XAddrs, + tIpBuf + ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::transferEvtToArchive( uint32_t SECONDS ){ + if(m_bIsConnected) { + if( SECONDS > 0 ) { + char tQBuf[CTEXT]; + sprintf(tQBuf,"INSERT INTO events_archive ( SELECT * FROM events_cloud ec WHERE ec.ts < ( UNIX_TIMESTAMP(NOW()) - %d ) ); DELETE FROM events_cloud WHERE ts < ( UNIX_TIMESTAMP(NOW()) - %d );", SECONDS, SECONDS ); + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + }; + return false; +} +/* +bool mysqlDBC::getLastEvents( vectorEventRecords &VR, uint32_t tss, uint32_t tsms ){ + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM events_cloud WHERE `ts`>%d AND `ts_ms`>%d", tss, tsms ); + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + DBC_EVT_DATA *tPtr; + Assoc *cArr; + for(int i=0;isize();i++) { + cArr = result->at(i); + tPtr = (DBC_EVT_DATA*)malloc(sizeof(DBC_EVT_DATA)); + if( tPtr!= NULL ) { + Assoc::iterator it; + memset(tPtr,0,sizeof(DBC_EVT_DATA)); + it = cArr->find("id"); + if( it != cArr->end() ){ + tPtr->id = atoi( it->second.c_str() ); + }; + it = cArr->find("node_id"); + if( it != cArr->end() ){ + tPtr->node_id = atoi( it->second.c_str() ); + }; + it = cArr->find("uuid"); + if( it != cArr->end() ){ + strncpy( tPtr->uuid, it->second.c_str(),64 ); + }; + it = cArr->find("ts"); + if( it != cArr->end() ){ + tPtr->ts_s = atoi( it->second.c_str() ); + }; + it = cArr->find("ts_ms"); + if( it != cArr->end() ){ + tPtr->ts_ms = atoi( it->second.c_str() ); + }; + it = cArr->find("evt_type"); + if( it != cArr->end() ){ + tPtr->type = atoi( it->second.c_str() ); + }; + it = cArr->find("range_digital"); + if( it != cArr->end() ){ + tPtr->range_digital = atoi( it->second.c_str() ); + }; + it = cArr->find("azimuth"); + if( it != cArr->end() ){ + tPtr->az = atof( it->second.c_str() ); + }; + it = cArr->find("elevation"); + if( it != cArr->end() ){ + tPtr->el = atof( it->second.c_str() ); + }; + it = cArr->find("range"); + if( it != cArr->end() ){ + tPtr->ra = atof( it->second.c_str() ); + }; + it = cArr->find("area"); + if( it != cArr->end() ){ + tPtr->area = atof( it->second.c_str() ); + }; + it = cArr->find("lat"); + if( it != cArr->end() ){ + tPtr->lat = atof( it->second.c_str() ); + }; + it = cArr->find("lon"); + if( it != cArr->end() ){ + tPtr->lon = atof( it->second.c_str() ); + }; + it = cArr->find("alt"); + if( it != cArr->end() ){ + tPtr->alt = atof( it->second.c_str() ); + }; + it = cArr->find("ref_uuid"); + if( it != cArr->end() ){ + strncpy( tPtr->uuid, it->second.c_str(),64 ); + }; + char tBuf[CLOG]; + sprintf(tBuf,"Evt: %d %d %d", tPtr->type, tPtr->ts_s, tPtr->ts_ms ); + LOG(tBuf); + VR.push_back(tPtr); + }; + }; + }; + deleteResult( result ); + if( m_pDatabase->isConnected()) return true; + }; + return false; +}; +*/ + +//Is safe to remove??? +bool mysqlDBC::getAllCamRecords( uint32_t SiteID, vectorCamRecords &VR ){ + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM cameras WHERE `site_id`=%d AND `type`=2 AND `status`=2", SiteID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + DBC_CAM_DATA *tVal; + Assoc *cArr; + for(int i=0;isize();i++) { + LOG("Cam_Record!"); + cArr = result->at(i); + tVal = (DBC_CAM_DATA*)malloc(sizeof(DBC_CAM_DATA)); + if( tVal!= NULL ) { + Assoc::iterator it; + memset(tVal,0,sizeof(DBC_CAM_DATA)); + + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->id = atoi( it->second.c_str() ); + }; + it = cArr->find("site_id"); + if( it != cArr->end() ){ + tVal->site_id = atoi( it->second.c_str() ); + }; + it = cArr->find("node_id"); + if( it != cArr->end() ){ + tVal->node_id = atoi( it->second.c_str() ); + }; + it = cArr->find("online"); + if( it != cArr->end() ){ + tVal->online = (bool) atoi( it->second.c_str() ); + }; + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi( it->second.c_str() ); + }; + it = cArr->find("name"); + if( it != cArr->end() ){ + strncpy( tVal->name, it->second.c_str(), 64 ); + }; + it = cArr->find("hardware"); + if( it != cArr->end() ){ + strncpy( tVal->hardware, it->second.c_str(), 32 ); + }; + it = cArr->find("status"); + if( it != cArr->end() ){ + tVal->status = atoi( it->second.c_str() ); + }; + it = cArr->find("session"); + if( it != cArr->end() ){ + strncpy( tVal->session, it->second.c_str(), 32 ); + }; + it = cArr->find("protocol"); + if( it != cArr->end() ){ + tVal->protocol = atoi( it->second.c_str() ); + }; + it = cArr->find("protocol_aux"); + if( it != cArr->end() ){ + tVal->protocol_aux = atoi( it->second.c_str() ); + }; + it = cArr->find("x"); + if( it != cArr->end() ){ + tVal->x = atof( it->second.c_str() ); + }; + it = cArr->find("y"); + if( it != cArr->end() ){ + tVal->y = atof( it->second.c_str() ); + }; + it = cArr->find("z"); + if( it != cArr->end() ){ + tVal->z = atof( it->second.c_str() ); + }; + it = cArr->find("x_rot"); + if( it != cArr->end() ){ + tVal->x_rot = atof( it->second.c_str() ); + }; + it = cArr->find("y_rot"); + if( it != cArr->end() ){ + tVal->y_rot = atof( it->second.c_str() ); + }; + it = cArr->find("z_rot"); + if( it != cArr->end() ){ + tVal->z_rot = atof( it->second.c_str() ); + }; + it = cArr->find("imager_type"); + if( it != cArr->end() ){ + tVal->imager_type = atoi( it->second.c_str() ); + }; + it = cArr->find("lense_f"); + if( it != cArr->end() ){ + tVal->lens_f = atoi( it->second.c_str() ); + }; + it = cArr->find("zoom"); + if( it != cArr->end() ){ + tVal->zoom = atof( it->second.c_str() ); + }; + it = cArr->find("access_login"); + if( it != cArr->end() ){ + strncpy( tVal->username, it->second.c_str(), 32 ); + }; + it = cArr->find("access_pass"); + if( it != cArr->end() ){ + strncpy( tVal->password, it->second.c_str(), 32 ); + }; + it = cArr->find("uuid"); + if( it != cArr->end() ){ + strncpy( tVal->uuid, it->second.c_str(), 64 ); + }; + it = cArr->find("mac"); + if( it != cArr->end() ){ + strncpy( tVal->mac, it->second.c_str(), 17 ); + }; + it = cArr->find("ip"); + if( it != cArr->end() ){ + strncpy( tVal->ip, it->second.c_str(), 17 ); + }; + it = cArr->find("port"); + if( it != cArr->end() ){ + tVal->port = atoi( it->second.c_str() ); + }; + it = cArr->find("onvif_access"); + if( it != cArr->end() ){ + strncpy( tVal->onvif_access, it->second.c_str(), 5); + }; + it = cArr->find("onvif_ctrl"); + if( it != cArr->end() ){ + strncpy( tVal->onvif_ctrl, it->second.c_str(), 250); + }; + it = cArr->find("ptz_token"); + if( it != cArr->end() ){ + strncpy( tVal->ptz_token, it->second.c_str(), 64); + }; + VR.push_back(tVal); + }; + //?? + //delete(cArr); + }; + }; + deleteResult( result ); +#ifdef DEBUG + sprintf( tQBuf,"Now %d Camera Records in System", VR.size()); + LOG(tQBuf); +#endif + if( m_pDatabase->isConnected()) return true; + }; + return false; +}; + + +DBC_INT_LIST *mysqlDBC::listNodes( uint32_t SiteID, uint32_t ServerID, bool all ){ + DBC_INT_LIST * tVal = NULL; + if( m_bIsConnected ){ + char tQBuf[1024]; + AAssoc *result; + if( all ) { + if ( ServerID == 0 ) { + sprintf(tQBuf, "SELECT `id` FROM `nodes` WHERE `site_id`=%d", SiteID); + } else { + sprintf(tQBuf, "SELECT `id` FROM `nodes` WHERE `site_id`=%d AND `server_id`=%d", SiteID, ServerID ); + }; + } else { + if ( ServerID == 0 ){ + sprintf(tQBuf, "SELECT `id` FROM `nodes` WHERE `site_id`=%d AND `type` > 0", SiteID ); + } else { + sprintf(tQBuf, "SELECT `id` FROM `nodes` WHERE `site_id`=%d AND `server_id`=%d AND `type` > 0", SiteID, ServerID ); + }; + }; +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0; i size();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listNewNodes( uint32_t SiteID, uint32_t ServerID, DBC_INT_LIST *old_ids ){ + DBC_INT_LIST * tVal = NULL; + char tParam[CTEXT]; + //memset( tParam, 0, CTEXT ); + sprintf(tParam,"0"); + if( old_ids != NULL ) { + char tBuffer[CTEXT]; + for(int i = 0; i< old_ids->size(); i++ ) { + sprintf( tBuffer, "%s,%d", tParam, old_ids->at(i) ); + strncpy( tParam, tBuffer, CTEXT ); + }; + }; + if( m_bIsConnected ){ + char tQBuf[CTEXT]; + AAssoc *result; + if ( ServerID == 0 ) { + sprintf(tQBuf, "SELECT id FROM nodes WHERE `site_id`=%d AND `type` > 0 AND `id` NOT IN(%s)", SiteID, tParam); + } else { + sprintf(tQBuf, "SELECT id FROM nodes WHERE `site_id`=%d AND `server_id`=%d AND `type` > 0 AND `id` NOT IN(%s)", SiteID, ServerID, tParam ); + }; +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +void mysqlDBC::lazyEventArchiver( uint32_t DalayTime ){ + if( m_bIsConnected ){ + char tQBuf[CTEXT]; + AAssoc *result; + uint32_t LastID = 0; + sprintf( tQBuf, "SELECT * FROM `events_cloud` WHERE ( UNIX_TIMESTAMP(NOW()) - `ts` ) > %d ORDER BY `id` ASC LIMIT 10", DalayTime ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + for(int i=0;isize();i++){ + uint32_t nodeid=0; + char uuid[64]={0}; + uint32_t ts=0; + uint32_t ts_ms=0; + uint32_t evt_t=0; + uint32_t range_d=0; + float az=.0f, el=.0f, ra=.0f, ar=.0f, lat=.0f, lon=.0f, alt=.0f; + uint32_t ref_id=0; + char ref_uuid[64]={0}; + Assoc::iterator it; + + cArr = result->at(i); + + it = cArr->find("id"); + if( it != cArr->end() ){ + LastID = atoi( it->second.c_str()); + }; + it = cArr->find("node_id"); + if( it != cArr->end() ){ + nodeid = atoi( it->second.c_str()); + }; + it = cArr->find("uuid"); + if( it != cArr->end() ){ + strncpy( uuid, it->second.c_str(), 64 ); + }; + it = cArr->find("ts"); + if( it != cArr->end() ){ + ts = atoi( it->second.c_str()); + }; + it = cArr->find("ts_ms"); + if( it != cArr->end() ){ + ts_ms = atoi( it->second.c_str()); + }; + it = cArr->find("evt_type"); + if( it != cArr->end() ){ + evt_t = atoi( it->second.c_str()); + }; + it = cArr->find("range_digital"); + if( it != cArr->end() ){ + range_d = atoi( it->second.c_str()); + }; + it = cArr->find("azimuth"); + if( it != cArr->end() ){ + az = (float)atof( it->second.c_str()); + }; + it = cArr->find("elevation"); + if( it != cArr->end() ){ + el = (float)atof( it->second.c_str()); + }; + it = cArr->find("range"); + if( it != cArr->end() ){ + ra = (float)atof( it->second.c_str()); + }; + it = cArr->find("area"); + if( it != cArr->end() ){ + ar = (float)atof( it->second.c_str()); + }; + it = cArr->find("lat"); + if( it != cArr->end() ){ + lat = (float)atof( it->second.c_str()); + }; + it = cArr->find("lon"); + if( it != cArr->end() ){ + lon = (float)atof( it->second.c_str()); + }; + it = cArr->find("alt"); + if( it != cArr->end() ){ + alt = (float)atof( it->second.c_str()); + }; + it = cArr->find("ref_id"); + if( it != cArr->end() ){ + ref_id = atoi( it->second.c_str()); + }; + it = cArr->find("ref_uuid"); + if( it != cArr->end() ){ + strncpy( ref_uuid, it->second.c_str(), 64 ); + }; + sprintf(tQBuf, "INSERT INTO `events_archive` SET `node_id`=%d, `uuid`='%s', `ts`=%d, `ts_ms`=%d, `evt_type`=%d, `range_digital`=%d, `azimuth`=%0.8f, `elevation`=%0.8f, `range`=%0.2f, `area`=%0.5f, `lat`=%0.8f, `lon`=%0.8f, `alt`=%0.3f, `ref_id`=%d, `ref_uuid`='%s'", + nodeid, + uuid, + ts, + ts_ms, + evt_t, + range_d, + az, + el, + ra, + ar, + lat, + lon, + alt, + ref_id, + ref_uuid + ); + uint32_t IID = (uint32_t) m_pDatabase->QueryID(tQBuf); + sprintf(tQBuf,"UPDATE `events_2_pictures` SET `event_id`=%d WHERE `event_id`=%d", IID, LastID ); + //m_pDatabase->SilentQuery(tQBuf); + sprintf(tQBuf,"UPDATE `events_2_videos` SET `event_id`=%d WHERE `event_id`=%d", IID, LastID ); + //m_pDatabase->SilentQuery(tQBuf); + }; + }; + }; + deleteResult( result ); + }; +}; + +DBC_INT_LIST *mysqlDBC::listCamMediaStreams( uint32_t CAMID ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT id FROM media_streams WHERE `source_id`=%d AND `valid`=1", CAMID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listStreamCapPictures( uint32_t StreamID, uint32_t cnt ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `pictures` WHERE `media_stream_id`=%d LIMIT %d", StreamID, cnt ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_NETWORK_DATA *mysqlDBC::getNetworkData( uint32_t net_id ){ + DBC_NETWORK_DATA * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM `networks` WHERE `id`=%d", net_id ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_NETWORK_DATA*) malloc(sizeof(DBC_NETWORK_DATA)); + if( tVal != NULL ) { + memset(tVal, 0, sizeof(DBC_NETWORK_DATA)); + Assoc::iterator it; + tVal->id = net_id; + cArr = result->at(0); + it = cArr->find("nif_id"); + if( it != cArr->end() ){ + tVal->nif_id = atoi(it->second.c_str()); + }; + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = (NETWORK_TYPE) atoi(it->second.c_str()); + }; + it = cArr->find("address"); + if( it != cArr->end() ){ + strncpy( tVal->address, it->second.c_str(), 65 ); + tVal->address[64]=(char)0; + }; + it = cArr->find("gateway"); + if( it != cArr->end() ){ + strncpy(tVal->gateway, it->second.c_str(), 65); + tVal->gateway[64]=(char)0; + }; + it = cArr->find("mask"); + if( it != cArr->end() ){ + strncpy( tVal->netmask, it->second.c_str(), 65 ); + tVal->netmask[64]=(char)0; + }; + it = cArr->find("broadcast"); + if( it != cArr->end() ){ + strncpy( tVal->broadcast, it->second.c_str(), 65 ); + tVal->broadcast[64]=(char)0; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_NET_IF_DATA *mysqlDBC::getNIF_Data( uint32_t nif_id ){ + DBC_NET_IF_DATA * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `type`, `mode`, `device_name`, `mac`, `aux_id` FROM `network_interfaces` WHERE `id`=%d", nif_id ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_NET_IF_DATA*) malloc(sizeof(DBC_NET_IF_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + tVal->id = nif_id; + cArr = result->at(0); + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi(it->second.c_str()); + }; + it = cArr->find("mode"); + if( it != cArr->end() ){ + tVal->mode = atoi(it->second.c_str()); + }; + it = cArr->find("device_name"); + if( it != cArr->end() ){ + strncpy( tVal->device_name, it->second.c_str(),11); + tVal->device_name[10]=(char)0; + }; + it = cArr->find("mac"); + if( it != cArr->end() ){ + strncpy( tVal->mac, it->second.c_str(), 33 ); + tVal->mac[32]=(char)0; + }; + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal->aux_id = atoi(it->second.c_str()); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t mysqlDBC::getNetworkInfrastructureID( uint32_t nif_id ){ + uint32_t tVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT id FROM `network_infrastructure` WHERE `nif_id`=%d", nif_id ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +CSTR mysqlDBC::getNodeName( uint32_t NodeID ){ + CSTR tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `name` FROM `nodes` WHERE `id`=%d", NodeID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("name"); + if( it != cArr->end() ){ + tVal = strdup( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t mysqlDBC::getNodeAuxID( uint32_t NodeID ){ + uint32_t tVal; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `aux_id` FROM `nodes` WHERE `id`=%d", NodeID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t mysqlDBC::getNodeAuxParam( uint32_t NodeID ){ + uint32_t tVal; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `aux_parameter` FROM `nodes` WHERE `id`=%d", NodeID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("aux_parameter"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + + +uint32_t mysqlDBC::getWiFi_ID( uint32_t nif_id ){ + uint32_t tVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `wifis` WHERE `nif_id`=%d", nif_id ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t mysqlDBC::getNIF_ID( CSTR key ){ + uint32_t tVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT id FROM `network_interfaces` WHERE `key`='%s'", key ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t mysqlDBC::getNIF_IDbyDevice( CSTR device ){ + uint32_t tVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT id FROM `network_interfaces` WHERE `device_name`='%s'", device ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_NODE_DATA *mysqlDBC::getNodeData( uint32_t ID ){ + DBC_NODE_DATA * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM nodes WHERE `id`=%d", ID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_NODE_DATA*) malloc(sizeof(DBC_NODE_DATA)); + if( tVal != NULL ) { + memset( tVal, 0, sizeof(DBC_NODE_DATA)); + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->node_id = atoi( it->second.c_str() ); + }; + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = /*(NODE_TYPE)*/ atoi( it->second.c_str() ); + }; + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal->aux_id = atoi( it->second.c_str() ); + }; + it = cArr->find("aux_parameter"); + if( it != cArr->end() ){ + tVal->aux_parameter = atoi( it->second.c_str() ); + }; + it = cArr->find("name"); + if( it != cArr->end() ){ + sprintf( tVal->name, it->second.c_str() ); + }; + it = cArr->find("ts_s"); + if( it != cArr->end() ){ + tVal->tss = atoi( it->second.c_str() ); + }; + it = cArr->find("ts_ms"); + if( it != cArr->end() ){ + tVal->tsm = atoi( it->second.c_str() ); + }; + it = cArr->find("online"); + if( it != cArr->end() ){ + tVal->online = (bool)atoi( it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_APF_DATA *mysqlDBC::getAPFData( uint32_t APFID ){ + DBC_APF_DATA * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM `target_filter_apf` WHERE `id`=%d", APFID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_APF_DATA*) malloc(sizeof(DBC_APF_DATA)); + if( tVal != NULL ) { + memset( tVal, 0 , sizeof(DBC_APF_DATA)); + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("mode"); + if( it != cArr->end() ){ + sprintf( tVal->mode, it->second.c_str() ); + }; + it = cArr->find("port"); + if( it != cArr->end() ){ + tVal->port = atoi( it->second.c_str() ); + }; + it = cArr->find("lat"); + if( it != cArr->end() ){ + tVal->lat = atof( it->second.c_str() ); + }; + it = cArr->find("lon"); + if( it != cArr->end() ){ + tVal->lon = atof( it->second.c_str() ); + }; + it = cArr->find("alt"); + if( it != cArr->end() ){ + tVal->alt = atof( it->second.c_str() ); + }; + it = cArr->find("roll"); + if( it != cArr->end() ){ + tVal->roll = atof( it->second.c_str() ); + }; + it = cArr->find("pitch"); + if( it != cArr->end() ){ + tVal->pitch = atof( it->second.c_str() ); + }; + it = cArr->find("yaw"); + if( it != cArr->end() ){ + tVal->yaw = atof( it->second.c_str() ); + }; + it = cArr->find("dx"); + if( it != cArr->end() ){ + tVal->dx = atof( it->second.c_str() ); + }; + it = cArr->find("dy"); + if( it != cArr->end() ){ + tVal->dy = atof( it->second.c_str() ); + }; + it = cArr->find("dz"); + if( it != cArr->end() ){ + tVal->dz = atof( it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_FH_DATA *mysqlDBC::getFlyHunterData( uint32_t ID ){ + DBC_FH_DATA * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM `modules_fly_hunter` WHERE `id`=%d", ID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_FH_DATA*) malloc(sizeof(DBC_FH_DATA)); + if( tVal != NULL ) { + memset( tVal, 0 , sizeof(DBC_FH_DATA)); + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("name"); + if( it != cArr->end() ){ + sprintf( tVal->name, it->second.c_str() ); + }; + it = cArr->find("lat"); + if( it != cArr->end() ){ + tVal->lat = atof( it->second.c_str() ); + }; + it = cArr->find("lon"); + if( it != cArr->end() ){ + tVal->lon = atof( it->second.c_str() ); + }; + it = cArr->find("alt"); + if( it != cArr->end() ){ + tVal->alt = atof( it->second.c_str() ); + }; + it = cArr->find("dc_module_id"); + if( it != cArr->end() ){ + tVal->dc_id = atoi( it->second.c_str() ); + }; + it = cArr->find("uart_id"); + if( it != cArr->end() ){ + tVal->uart_id = atoi( it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; +bool mysqlDBC::fillShadow2D( uint32_t ID, SHADOW & SH ){ + if( m_bIsConnected ){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `lv`.`id`, `lm`.`layer`, `lm`.`status` FROM `lrf_mask_vertexes` `lv` LEFT JOIN `lrf_masks` `lm` ON (`lm`.`id` = `lv`.`mask_id`) WHERE `lm`.`sensor_id`=%d ORDER BY `lv`.`id`", ID ); + LOG(tQBuf); + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + SH.m_nEnabled = 0xFFFFFFFF; + SH.m_nPolygonCount = result->size(); + SH.pPolygones = (SHADOW_POLY *) calloc( SH.m_nPolygonCount, sizeof( SHADOW_POLY ) ); + if ( SH.pPolygones ) { + Assoc * cArr; + for ( uint8_t idx = 0; idx < result->size(); idx++ ) { + Assoc::iterator it; + cArr = result->at(idx); + it = cArr->find("id"); + if( it != cArr->end() ){ + SH.pPolygones[idx].m_nDBID = atoi(it->second.c_str()); + }; + it = cArr->find("layer"); + if( it != cArr->end() ){ + SH.pPolygones[idx].bType = atoi(it->second.c_str()); + }; + it = cArr->find("status"); + if( it != cArr->end() ){ + SH.m_nEnabled &= ( it->second.c_str()[0] == 'E' )?0xFFFFFFFF:~(1<Query( tQBuf ); + if( v_result!= NULL ) { + if( v_result->size() > 0 ) { + SH.pPolygones[idx].wCount = v_result->size(); + SH.pPolygones[idx].pPoint = (HZ_POINT *) calloc( SH.pPolygones[idx].wCount, sizeof( HZ_POINT ) ); + if(SH.pPolygones[idx].pPoint ) { + for ( uint32_t zdx =0; zdx < SH.pPolygones[idx].wCount; zdx++ ) { + cArr = v_result->at(zdx); + it = cArr->find("x"); + if( it != cArr->end() ){ + SH.pPolygones[idx].pPoint[zdx].wX = atoi(it->second.c_str()); + }; + it = cArr->find("y"); + if( it != cArr->end() ){ + SH.pPolygones[idx].pPoint[zdx].wY = atoi(it->second.c_str()); + }; + LOG("Point Added!"); + }; + } else { + LOG("No mem for Points!"); + }; + } else { + LOG("No Points!"); + SH.pPolygones[idx].wCount = 0; + SH.pPolygones[idx].pPoint = NULL; + }; + deleteResult( v_result ); + }; + }; + }; + }; + deleteResult( result ); + }; + return true; + }; + return false; +}; + +DBC_SITE_DATA *mysqlDBC::getSiteData( uint32_t ID ){ + DBC_SITE_DATA * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM sites WHERE `id`=%d", ID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_SITE_DATA*) malloc(sizeof(DBC_SITE_DATA)); + if( tVal != NULL ) { + memset( tVal, 0 , sizeof(DBC_SITE_DATA)); + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("account_id"); + if( it != cArr->end() ){ + tVal->account_id = atoi( it->second.c_str() ); + }; + it = cArr->find("name"); + if( it != cArr->end() ){ + sprintf( tVal->name, it->second.c_str() ); + }; + it = cArr->find("server_ident"); + if( it != cArr->end() ){ + sprintf( tVal->ident, it->second.c_str() ); + }; + it = cArr->find("anchor_lat"); + if( it != cArr->end() ){ + tVal->lat = atof( it->second.c_str() ); + }; + it = cArr->find("anchor_lon"); + if( it != cArr->end() ){ + tVal->lon = atof( it->second.c_str() ); + }; + it = cArr->find("anchor_alt"); + if( it != cArr->end() ){ + tVal->alt = atof( it->second.c_str() ); + }; + it = cArr->find("hemisphere"); + if( it != cArr->end() ){ + tVal->SH = ( it->second.c_str()[0] == 'S' ); + }; + it = cArr->find("map_id"); + if( it != cArr->end() ){ + tVal->map_id = atoi( it->second.c_str() ); + }; + it = cArr->find("local_binding"); + if( it != cArr->end() ){ + tVal->local_binding = (bool) atoi(it->second.c_str()); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_TARGET_FLITER_DATA *mysqlDBC::getTargetFilterData( uint32_t ID ){ + DBC_TARGET_FLITER_DATA * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM target_filters WHERE `id`=%d", ID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_TARGET_FLITER_DATA*) malloc(sizeof(DBC_TARGET_FLITER_DATA)); + if( tVal != NULL ) { + memset( tVal, 0 , sizeof(DBC_TARGET_FLITER_DATA)); + Assoc::iterator it; + tVal->id = ID; + cArr = result->at(0); + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi( it->second.c_str() ); + }; + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal->aux_id = atoi( it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_LRF_DATA *mysqlDBC::getLRFData( uint32_t ID ){ + DBC_LRF_DATA * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM lrf_sensors WHERE `id`=%d", ID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_LRF_DATA*) malloc(sizeof(DBC_LRF_DATA)); + if( tVal != NULL ) { + memset( tVal, 0 , sizeof(DBC_LRF_DATA)); + Assoc::iterator it; + tVal->id = ID; + cArr = result->at(0); + it = cArr->find("data_status"); + if( it != cArr->end() ){ + tVal->data_status = atoi( it->second.c_str() ); + }; + it = cArr->find("serial"); + if( it != cArr->end() ){ + strncpy( tVal->serial, it->second.c_str(), sizeof(tVal->serial)-1 ); + tVal->serial[sizeof(tVal->serial)-1]=(char)0; + }; + it = cArr->find("version"); + if( it != cArr->end() ){ + strncpy( tVal->version, it->second.c_str(), sizeof(tVal->version)-1 ); + tVal->version[sizeof(tVal->version)-1]=(char)0; + }; + it = cArr->find("x"); + if( it != cArr->end() ){ + tVal->x = atof( it->second.c_str() ); + }; + it = cArr->find("y"); + if( it != cArr->end() ){ + tVal->y = atof( it->second.c_str() ); + }; + it = cArr->find("z"); + if( it != cArr->end() ){ + tVal->z = atof( it->second.c_str() ); + }; + it = cArr->find("x_rot"); + if( it != cArr->end() ){ + tVal->x_rot = atof( it->second.c_str() ); + }; + it = cArr->find("y_rot"); + if( it != cArr->end() ){ + tVal->y_rot = atof( it->second.c_str() ); + }; + it = cArr->find("z_rot"); + if( it != cArr->end() ){ + tVal->z_rot = atof( it->second.c_str() ); + }; + it = cArr->find("uart_id"); + if( it != cArr->end() ){ + tVal->uart_id = atoi( it->second.c_str() ); + }; + it = cArr->find("device_id"); + if( it != cArr->end() ){ + tVal->device_id = atoi( it->second.c_str() ); + }; + it = cArr->find("ip_address"); + if( it != cArr->end() ){ + sprintf( tVal->master_host, it->second.c_str() ); + }; + it = cArr->find("aux_ip_address"); + if( it != cArr->end() ){ + sprintf( tVal->slave_host, it->second.c_str() ); + }; + it = cArr->find("port"); + if( it != cArr->end() ){ + tVal->master_port = atoi( it->second.c_str() ); + }; + it = cArr->find("aux_port"); + if( it != cArr->end() ){ + tVal->slave_port = atoi( it->second.c_str() ); + }; + it = cArr->find("auto_draw"); + if( it != cArr->end() ){ + tVal->auto_draw = atoi( it->second.c_str() ); + }; + it = cArr->find("filter_id"); + if( it != cArr->end() ){ + tVal->filter_id = atoi( it->second.c_str() ); + }; + + //it = cArr->find("enabled_lrf"); + //if( it != cArr->end() ){ + // tVal->enabled_lrf = atoi( it->second.c_str() ); + //}; + it = cArr->find("max_range"); + if( it != cArr->end() ){ + tVal->max_range = atof( it->second.c_str() ); + }; + it = cArr->find("base_shift"); + if( it != cArr->end() ){ + tVal->base_shift = atoi( it->second.c_str() ); + }; + it = cArr->find("mirror_shift"); + if( it != cArr->end() ){ + tVal->mirror_shift = atoi( it->second.c_str() ); + }; + it = cArr->find("detection_profile_id"); + if( it != cArr->end() ){ + tVal->detection_profile_id = atoi( it->second.c_str() ); + }; + it = cArr->find("draw_lrf_id"); + if( it != cArr->end() ){ + tVal->draw_lrf_id = atoi( it->second.c_str() ); + }; + it = cArr->find("width_table_id"); + if( it != cArr->end() ){ + tVal->width_table_id = atoi( it->second.c_str() ); + }; + it = cArr->find("zoom_table_id"); + if( it != cArr->end() ){ + tVal->zoom_table_id = atoi( it->second.c_str() ); + }; + it = cArr->find("embd_cam"); + if( it != cArr->end() ){ + tVal->embd_cam = atoi( it->second.c_str() ); + }; + it = cArr->find("embd_cam_auto"); + if( it != cArr->end() ){ + tVal->embd_cam_auto = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("embd_dc"); + if( it != cArr->end() ){ + tVal->embd_dc = atoi( it->second.c_str() ); + }; + it = cArr->find("autoreset"); + if( it != cArr->end() ){ + tVal->autoreset = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("force_settings"); + if( it != cArr->end() ){ + tVal->force_settings = (bool)atoi( it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint8_t mysqlDBC::getLRFDataStatus( uint32_t ID ){ + uint8_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `data_status` FROM `lrf_sensors` WHERE `id`=%d", ID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("data_status"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +PLGS_2D_PARAMETERS mysqlDBC::getLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master ){ + PLGS_2D_PARAMETERS retVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM `lrf_detection_profiles` WHERE `aux_id`=%d AND `profile_id`=%d AND `master`=b'%c'", lrfID, profileID,((master)?'1':'0') ); + +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + retVal = (PLGS_2D_PARAMETERS) malloc(sizeof(LGS_2D_PARAMETERS)); + memset( retVal, 0, sizeof(LGS_2D_PARAMETERS)); + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("order"); + if( it != cArr->end() ){ + retVal->nOrder = atoi(it->second.c_str()); + }; + it = cArr->find("offset"); + if( it != cArr->end() ){ + retVal->nOffset = atoi(it->second.c_str()); + }; + it = cArr->find("delta"); + if( it != cArr->end() ){ + retVal->nDelta = atoi(it->second.c_str()); + }; + it = cArr->find("flip"); + if( it != cArr->end() ){ + retVal->nFlip = atoi(it->second.c_str()); + }; + it = cArr->find("width"); + if( it != cArr->end() ){ + retVal->nWidth = atoi(it->second.c_str()); + }; + it = cArr->find("sst"); + if( it != cArr->end() ){ + retVal->bSST = atoi(it->second.c_str()); + }; + it = cArr->find("sun"); + if( it != cArr->end() ){ + retVal->nSun = atoi(it->second.c_str()); + }; + }; + }; + deleteResult( result ); + }; + return retVal; +}; +CSTR mysqlDBC::getLRFDraw( uint32_t DBID ){ + CSTR RetVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `md5` FROM `lrf_draw` WHERE `node_id`=%d", DBID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("md5"); + if( it != cArr->end() ){ + RetVal = strdup( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +uint32_t mysqlDBC::getLRFMaskID( uint32_t deviceID, uint8_t lrfID, uint8_t layer ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `lrf_masks` WHERE `sensor_id`=%d AND `lrf_id`=%d AND `layer`=%d ", deviceID, lrfID, layer ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; +/* +DBC_PUSHED_CMD *mysqlDBC::getLRFPushedCMD( uint32_t ID ){ + DBC_PUSHED_CMD *RetVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `pushed_cmd`, `pushed_param` FROM `lrf_sensors` WHERE `id`=%d AND `pushed_cmd` > 0", ID ); +#ifdef DEBUG + //LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + RetVal = (DBC_PUSHED_CMD*)malloc(sizeof(DBC_PUSHED_CMD)); + if( RetVal ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("pushed_cmd"); + if( it != cArr->end() ){ + RetVal->CMD = atoi( it->second.c_str() ); + }; + it = cArr->find("pushed_param"); + if( it != cArr->end() ){ + RetVal->PARAM = atoi( it->second.c_str() ); + }; + }; + }; + //Only If Result is Fetched - Clear Current CMD + sprintf(tQBuf, "UPDATE `lrf_sensors` SET `pushed_cmd`=0, `pushed_param`=0 WHERE `id`=%d", ID ); + m_pDatabase->SilentQuery( tQBuf ); + }; + deleteResult( result ); + }; + return RetVal; +}; +*/ + +DBC_INT_LIST *mysqlDBC::listModules(){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `server_modules` WHERE `server_id`=%d AND `enabled`=1", m_nServerID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listFilters( uint32_t ServerID ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `target_filters` WHERE `server_id`=%d AND `enabled`=1", ServerID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listLRFMaskVertexes( uint32_t MaskID ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `lrf_mask_vertexes` WHERE `mask_id`=%d", MaskID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listLRFMaskVertexPoints( uint32_t VertexID ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `lrf_mask_vertex_points` WHERE `vertex_id`=%d ORDER BY `id`", VertexID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listMediaServerStreams( uint32_t SiteId, uint32_t MediaServerID, uint8_t listMode ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + switch( listMode ){ + case LIST_VALID_RECORDS: sprintf(tQBuf, "SELECT id FROM media_server_streams WHERE `valid`=1 AND `site_id`=%d AND `media_server_id`=%d", SiteId, MediaServerID ); break; + case LIST_INVALID_RECORDS: sprintf(tQBuf, "SELECT id FROM media_server_streams WHERE `valid`=0 AND `site_id`=%d AND `media_server_id`=%d", SiteId, MediaServerID ); break; + default: sprintf(tQBuf, "SELECT id FROM media_server_streams WHERE `site_id`=%d AND `media_server_id`=%d", SiteId, MediaServerID ); + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listMediaStreams( uint32_t SiteId, uint8_t listMode ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + switch( listMode ){ + case LIST_VALID_RECORDS: + sprintf(tQBuf, "SELECT `ms`.`id` FROM `nodes` `nd` LEFT JOIN `media_streams` `ms` ON (`ms`.`id`=`nd`.`aux_parameter`) WHERE `nd`.`type` IN (10,11,12,13) AND `nd`.`site_id`=%d AND `ms`.`valid`=1 AND `nd`.`online`=1", SiteId ); + break; + case LIST_INVALID_RECORDS: + sprintf(tQBuf, "SELECT `ms`.`id` FROM `nodes` `nd` LEFT JOIN `media_streams` `ms` ON (`ms`.`id`=`nd`.`aux_parameter`) WHERE `nd`.`type` IN (10,11,12,13) AND `nd`.`site_id`=%d AND `ms`.`valid`=1 AND `nd`.`online`=0", SiteId ); + break; + default: + sprintf(tQBuf, "SELECT `ms`.`id` FROM `nodes` `nd` LEFT JOIN `media_streams` `ms` ON (`ms`.`id`=`nd`.`aux_parameter`) WHERE `nd`.`type` IN (10,11,12,13) AND `nd`.`site_id`=%d AND `ms`.`valid`=1", SiteId ); + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listDetectionProfileIDs( uint32_t nodeID ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `profile_id` FROM `lrf_detection_profiles` WHERE `aux_id`=%d ", nodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("profile_id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listDetectionProfiles( uint32_t nodeID ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `lrf_detection_profiles` WHERE `aux_id`=%d ", nodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +/* +DBC_INT_LIST *mysqlDBC::listSockets( uint32_t NodeID ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT id FROM sockets WHERE `node_id`=%d", NodeID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; +*/ + +DBC_INT_LIST *mysqlDBC::listResources( uint32_t NodeID ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + if( NodeID ) { + sprintf(tQBuf, "SELECT `id` FROM `resources` WHERE `node_id`=%d AND `active`=1 AND `used`=1", NodeID ); + } else { + sprintf(tQBuf, "SELECT `re`.`id` FROM `resources` `re` LEFT JOIN `nodes` `no` ON( `re`.`node_id` = `no`.`id` ) WHERE `no`.`site_id`=%d AND `re`.`used`=1", m_nSiteID );// AND `re`.`active`=1", m_nSiteID ); + }; +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +simplePolygone *mysqlDBC::loadLRFMaskVertex( uint32_t vid ){ + simplePolygone *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM `lrf_mask_vertexes` WHERE `id`=%d", vid ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + tVal = (simplePolygone *) malloc(sizeof(simplePolygone)); + if ( tVal ) { + Assoc * cArr; + memset( tVal, 0, sizeof(simplePolygone)); + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("r"); + if( it != cArr->end() ){ + tVal->color[0] = atoi( it->second.c_str() ); + }; + it = cArr->find("g"); + if( it != cArr->end() ){ + tVal->color[1] = atoi( it->second.c_str() ); + }; + it = cArr->find("b"); + if( it != cArr->end() ){ + tVal->color[2] = atoi( it->second.c_str() ); + }; + AAssoc *points; + sprintf(tQBuf, "SELECT * FROM `lrf_mask_vertex_points` WHERE `vertex_id`=%d ORDER BY `id`", vid ); +#ifdef DEBUG + LOG(tQBuf); +#endif + points = m_pDatabase->Query( tQBuf ); + if( points!= NULL ) { + if ( points->size() ) { + tVal->count = points->size(); + tVal->points = (simplePoint *) calloc( points->size(), sizeof(simplePoint) ); + if( tVal->points!= NULL ) { + for (int i = 0; i < points->size(); i++) { + cArr = points->at( i ); + it = cArr->find("x"); + if( it != cArr->end() ){ + tVal->points[i].setX( atoi( it->second.c_str() ) ); + }; + it = cArr->find("y"); + if( it != cArr->end() ){ + tVal->points[i].setY( atoi( it->second.c_str() ) ); + }; + }; + }; + }; + }; + deleteResult( points ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listNetworks( uint32_t nif_id ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `networks` WHERE `nif_id`=%d", nif_id ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *mysqlDBC::listNewModules( DBC_INT_LIST * old_ids ){ + DBC_INT_LIST * tVal = NULL; + char tParam[CTEXT]; + //memset( tParam, 0, CTEXT ); + sprintf(tParam,"0"); + if( old_ids != NULL ) { + char tBuffer[CTEXT]; + for(int i = 0; i< old_ids->size(); i++ ) { + sprintf( tBuffer, "%s,%d", tParam, old_ids->at(i) ); + strncpy( tParam, tBuffer, CTEXT ); + }; + }; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `server_modules` WHERE `server_id`=%d AND `enabled`=1 AND `id` NOT IN (%s)", m_nServerID, tParam ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t mysqlDBC::getCamId( CSTR UUID ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT id FROM cameras WHERE `uuid`='%s'", UUID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +DBC_CAP_DATA *mysqlDBC::getCamCapPictureData( uint32_t PicID ){ + DBC_CAP_DATA *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT md5, ext FROM pictures WHERE `id`=%d", PicID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_CAP_DATA*) malloc(sizeof(DBC_CAP_DATA)); + if( tVal != NULL ) { + memset( tVal, 0 , sizeof(DBC_CAP_DATA)); + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("md5"); + if( it != cArr->end() ){ + strncpy(tVal->md5, it->second.c_str(), 32); + }; + it = cArr->find("ext"); + if( it != cArr->end() ){ + strncpy(tVal->ext, it->second.c_str(), 3 ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_CAM_DATA *mysqlDBC::getCamData( uint32_t ID ){ + DBC_CAM_DATA *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM cameras WHERE `id`=%d", ID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_CAM_DATA*) malloc(sizeof(DBC_CAM_DATA)); + if( tVal != NULL ) { + memset( tVal, 0 , sizeof(DBC_CAM_DATA)); + tVal->id = ID; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("site_id"); + if( it != cArr->end() ){ + tVal->site_id = atoi( it->second.c_str() ); + }; + it = cArr->find("node_id"); + if( it != cArr->end() ){ + tVal->node_id = atoi( it->second.c_str() ); + }; + it = cArr->find("online"); + if( it != cArr->end() ){ + tVal->online = (bool) atoi( it->second.c_str() ); + }; + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi( it->second.c_str() ); + }; + it = cArr->find("name"); + if( it != cArr->end() ){ + strncpy( tVal->name, it->second.c_str(), 64 ); + }; + it = cArr->find("hardware"); + if( it != cArr->end() ){ + strncpy( tVal->hardware, it->second.c_str(), 32 ); + }; + it = cArr->find("status"); + if( it != cArr->end() ){ + tVal->status = atoi( it->second.c_str() ); + }; + it = cArr->find("session"); + if( it != cArr->end() ){ + strncpy( tVal->session, it->second.c_str(), 32 ); + }; + it = cArr->find("protocol"); + if( it != cArr->end() ){ + tVal->protocol = atoi( it->second.c_str() ); + }; + it = cArr->find("protocol_aux"); + if( it != cArr->end() ){ + tVal->protocol_aux = atoi( it->second.c_str() ); + }; + it = cArr->find("uart_id"); + if( it != cArr->end() ){ + tVal->uart_id = atoi( it->second.c_str() ); + }; + it = cArr->find("x"); + if( it != cArr->end() ){ + tVal->x = atof( it->second.c_str() ); + }; + it = cArr->find("y"); + if( it != cArr->end() ){ + tVal->y = atof( it->second.c_str() ); + }; + it = cArr->find("z"); + if( it != cArr->end() ){ + tVal->z = atof( it->second.c_str() ); + }; + it = cArr->find("x_rot"); + if( it != cArr->end() ){ + tVal->x_rot = atof( it->second.c_str() ); + }; + it = cArr->find("y_rot"); + if( it != cArr->end() ){ + tVal->y_rot = atof( it->second.c_str() ); + }; + it = cArr->find("z_rot"); + if( it != cArr->end() ){ + tVal->z_rot = atof( it->second.c_str() ); + }; + it = cArr->find("imager_type"); + if( it != cArr->end() ){ + tVal->imager_type = atoi( it->second.c_str() ); + }; + it = cArr->find("lens_f"); + if( it != cArr->end() ){ + tVal->lens_f = atoi( it->second.c_str() ); + }; + it = cArr->find("ptz_speed_step"); + if( it != cArr->end() ){ + tVal->ptz_speed_step = atof( it->second.c_str() ); + }; + it = cArr->find("pan_model"); + if( it != cArr->end() ){ + tVal->pan_model = atoi( it->second.c_str() ); + }; + it = cArr->find("pan_angles"); + if( it != cArr->end() ){ + tVal->pan_angles = atoi( it->second.c_str() ); + }; + it = cArr->find("tilt_model"); + if( it != cArr->end() ){ + tVal->tilt_model = atoi( it->second.c_str() ); + }; + it = cArr->find("tilt_angles"); + if( it != cArr->end() ){ + tVal->tilt_angles = atoi( it->second.c_str() ); + }; + it = cArr->find("zoom_model"); + if( it != cArr->end() ){ + tVal->zoom_model = atoi( it->second.c_str() ); + }; + it = cArr->find("zoom"); + if( it != cArr->end() ){ + tVal->zoom = atof( it->second.c_str() ); + }; + + //it = cArr->find("max_range"); + //if( it != cArr->end() ){ + // tVal->max_range = atof( it->second.c_str() ); + //}; + it = cArr->find("access_login"); + if( it != cArr->end() ){ + strncpy( tVal->username, it->second.c_str(), 16 ); + }; + it = cArr->find("access_pass"); + if( it != cArr->end() ){ + strncpy( tVal->password, it->second.c_str(), 16 ); + }; + it = cArr->find("uuid"); + if( it != cArr->end() ){ + strncpy( tVal->uuid, it->second.c_str(), 64 ); + }; + it = cArr->find("mac"); + if( it != cArr->end() ){ + strncpy( tVal->mac, it->second.c_str(), 16 ); + }; + it = cArr->find("ip"); + if( it != cArr->end() ){ + strncpy( tVal->ip, it->second.c_str(), 16 ); + }; + it = cArr->find("port"); + if( it != cArr->end() ){ + tVal->port = atoi( it->second.c_str() ); + }; + it = cArr->find("onvif_access"); + if( it != cArr->end() ){ + strncpy( tVal->onvif_access, it->second.c_str(), 5); + }; + it = cArr->find("onvif_ctrl"); + if( it != cArr->end() ){ + strncpy( tVal->onvif_ctrl, it->second.c_str(), 250); + }; + it = cArr->find("ptz_token"); + if( it != cArr->end() ){ + strncpy( tVal->ptz_token, it->second.c_str(), 64); + }; + it = cArr->find("trigger_mode"); + if( it != cArr->end() ){ + tVal->triggering_mode = atoi( it->second.c_str() ); + }; + it = cArr->find("auth_mode"); + if( it != cArr->end() ){ + tVal->auth_mode = atoi( it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_PUSHED_CMD *mysqlDBC::getActivePushedCMD( uint32_t NodeID ){ + DBC_PUSHED_CMD *RetVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM `nodes_qcq` WHERE `node_id`=%d AND `status` > 0 AND `status` < 100", NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + RetVal = (DBC_PUSHED_CMD*)malloc(sizeof(DBC_PUSHED_CMD)); + if( RetVal ) { + Assoc * cArr; + Assoc::iterator it; + + memset( RetVal, 0, sizeof(DBC_PUSHED_CMD)); + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal->id = atoi( it->second.c_str() ); + }; + it = cArr->find("cmd"); + if( it != cArr->end() ){ + RetVal->CMD = atoi( it->second.c_str() ); + }; + it = cArr->find("parameter"); + if( it != cArr->end() ){ + strncpy( RetVal->PARAM, it->second.c_str(), 256 ); + RetVal->PARAM[255] = (char)0; + }; + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +DBC_PUSHED_CMD *mysqlDBC::getPushedCMD( uint32_t CmdID ){ + DBC_PUSHED_CMD *RetVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM `nodes_qcq` WHERE `id`=%d", CmdID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + RetVal = (DBC_PUSHED_CMD*)malloc(sizeof(DBC_PUSHED_CMD)); + if( RetVal ) { + Assoc * cArr; + Assoc::iterator it; + + memset( RetVal, 0, sizeof(DBC_PUSHED_CMD)); + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal->id = atoi( it->second.c_str() ); + }; + it = cArr->find("cmd"); + if( it != cArr->end() ){ + RetVal->CMD = atoi( it->second.c_str() ); + }; + it = cArr->find("parameter"); + if( it != cArr->end() ){ + strncpy( RetVal->PARAM, it->second.c_str(), 256 ); + RetVal->PARAM[255] = (char)0; + }; + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +DBC_PUSHED_CMD *mysqlDBC::getNodePushedCMD( uint32_t NodeID ){ + DBC_PUSHED_CMD *RetVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM `nodes_qcq` WHERE `node_id`=%d AND `status`=0 LIMIT 1", NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + RetVal = (DBC_PUSHED_CMD*)malloc(sizeof(DBC_PUSHED_CMD)); + if( RetVal ) { + Assoc * cArr; + Assoc::iterator it; + + memset( RetVal, 0, sizeof(DBC_PUSHED_CMD)); + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal->id = atoi( it->second.c_str() ); + }; + it = cArr->find("cmd"); + if( it != cArr->end() ){ + RetVal->CMD = atoi( it->second.c_str() ); + }; + it = cArr->find("parameter"); + if( it != cArr->end() ){ + strncpy( RetVal->PARAM, it->second.c_str(), 256 ); + RetVal->PARAM[255] = (char)0; + }; + //Only If Result is Fetched - Clear Current CMD + //sprintf(tQBuf, "DELETE FROM `nodes_qcq` WHERE `id`=%d", RetVal->id ); + //m_pDatabase->SilentQuery( tQBuf ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +bool mysqlDBC::updateNodePushedCMD( uint32_t CmdID, uint8_t status ){ + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf(tQBuf, "UPDATE `nodes_qcq` SET `status`=%d WHERE `id`=%d ", status, CmdID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +DBC_MODULE_DATA *mysqlDBC::getModuleData( uint32_t ID ){ + DBC_MODULE_DATA *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM server_modules WHERE `id`=%d", ID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_MODULE_DATA*) malloc(sizeof(DBC_MODULE_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->module_id = atoi( it->second.c_str() ); + }; + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal->aux_id = atoi( it->second.c_str() ); + }; + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi( it->second.c_str() ); + }; + it = cArr->find("enabled"); + if( it != cArr->end() ){ + tVal->enabled = (bool)atoi( it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; +/* +DBC_SOCKET_DATA *mysqlDBC::getSocketData( uint32_t ID ){ + DBC_SOCKET_DATA *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM sockets WHERE `id`=%d", ID ); +#ifdef DEBUG + //LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_SOCKET_DATA*) malloc(sizeof(DBC_SOCKET_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->socket_id = atoi( it->second.c_str() ); + }; + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal->aux_id = atoi( it->second.c_str() ); + }; + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi( it->second.c_str() ); + }; + it = cArr->find("binded"); + if( it != cArr->end() ){ + tVal->binded = (bool)atoi( it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; +*/ + +DBC_MEDIA_STREAM_DATA *mysqlDBC::getMediaStreamData( uint32_t ID ){ + DBC_MEDIA_STREAM_DATA *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM media_streams WHERE `id`=%d", ID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_MEDIA_STREAM_DATA*) malloc(sizeof(DBC_MEDIA_STREAM_DATA)); + if( tVal != NULL ) { + memset( tVal, 0, sizeof(DBC_MEDIA_STREAM_DATA) ); + Assoc::iterator it; + cArr = result->at(0); + tVal->id = ID; + it = cArr->find("source_id"); + if( it != cArr->end() ){ + tVal->source_id = atoi( it->second.c_str() ); + }; + it = cArr->find("source_type"); + if( it != cArr->end() ){ + sprintf( tVal->source_type, it->second.c_str() ); + }; + it = cArr->find("valid"); + if( it != cArr->end() ){ + tVal->valid = (bool) atoi( it->second.c_str() ); + }; + it = cArr->find("token"); + if( it != cArr->end() ){ + sprintf( tVal->token, it->second.c_str() ); + }; + it = cArr->find("img_width"); + if( it != cArr->end() ){ + tVal->width = atoi( it->second.c_str() ); + }; + it = cArr->find("img_height"); + if( it != cArr->end() ){ + tVal->height = atoi( it->second.c_str() ); + }; + it = cArr->find("fps"); + if( it != cArr->end() ){ + tVal->fps = atoi( it->second.c_str() ); + }; + it = cArr->find("compression_type"); + if( it != cArr->end() ){ + sprintf(tVal->c_type, it->second.c_str()); + }; + it = cArr->find("mrl_proto"); + if( it != cArr->end() ){ + sprintf( tVal->mrl_proto, it->second.c_str() ); + }; + it = cArr->find("mrl_port"); + if( it != cArr->end() ){ + tVal->mrl_port = atoi( it->second.c_str() ); + }; + it = cArr->find("mrl"); + if( it != cArr->end() ){ + sprintf( tVal->mrl, it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_MEDIA_SERVER_DATA *mysqlDBC::getMediaServerData( uint32_t ID ){ + DBC_MEDIA_SERVER_DATA *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM media_servers WHERE `id`=%d", ID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_MEDIA_SERVER_DATA*) malloc(sizeof(DBC_MEDIA_SERVER_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + tVal->id = ID; + it = cArr->find("secret_key"); + if( it != cArr->end() ){ + sprintf( tVal->key, it->second.c_str() ); + }; + it = cArr->find("ip"); + if( it != cArr->end() ){ + sprintf( tVal->ip, it->second.c_str() ); + }; + it = cArr->find("REST_port"); + if( it != cArr->end() ){ + tVal->port = atoi( it->second.c_str() ); + }; + it = cArr->find("virtual_host"); + if( it != cArr->end() ){ + sprintf( tVal->host, it->second.c_str() ); + }; + it = cArr->find("recording"); + if( it != cArr->end() ){ + tVal->recording = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("local"); + if( it != cArr->end() ){ + tVal->local = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("docRoot"); + if( it != cArr->end() ){ + sprintf( tVal->docRoot, it->second.c_str() ); + }; + sprintf( tVal->name,"ZLMedia_%d", tVal->id ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_MEDIA_SERVER_STREAM_DATA *mysqlDBC::getMediaServerStreamDataBySource( uint32_t ID ){ + DBC_MEDIA_SERVER_STREAM_DATA *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[MAX_PATH_LEN]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id`, `media_stream_id`, `online`, `key`, `mrl` FROM media_server_streams WHERE `media_stream_id`=%d", ID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_MEDIA_SERVER_STREAM_DATA*) malloc(sizeof(DBC_MEDIA_SERVER_STREAM_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + tVal->id = ID; + it = cArr->find("media_stream_id"); + if( it != cArr->end() ){ + tVal->media_stream_id = atoi( it->second.c_str() ); + }; + it = cArr->find("online"); + if( it != cArr->end() ){ + tVal->online = atoi( it->second.c_str() ); + }; + it = cArr->find("key"); + if( it != cArr->end() ){ + sprintf( tVal->key, it->second.c_str() ); + }; + it = cArr->find("mrl"); + if( it != cArr->end() ){ + sprintf( tVal->mrl, it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_MEDIA_SERVER_STREAM_DATA *mysqlDBC::getMediaServerStreamData( uint32_t ID ){ + DBC_MEDIA_SERVER_STREAM_DATA *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[MAX_PATH_LEN]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id`, `media_stream_id`, `online`, `key`, `mrl` FROM media_server_streams WHERE `id`=%d", ID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_MEDIA_SERVER_STREAM_DATA*) malloc(sizeof(DBC_MEDIA_SERVER_STREAM_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + tVal->id = ID; + it = cArr->find("media_stream_id"); + if( it != cArr->end() ){ + tVal->media_stream_id = atoi( it->second.c_str() ); + }; + it = cArr->find("online"); + if( it != cArr->end() ){ + tVal->online = atoi( it->second.c_str() ); + }; + it = cArr->find("key"); + if( it != cArr->end() ){ + sprintf( tVal->key, it->second.c_str() ); + }; + it = cArr->find("mrl"); + if( it != cArr->end() ){ + sprintf( tVal->mrl, it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +void mysqlDBC::registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_t *ServID, uint32_t *ServNode ){ + if(m_bIsConnected){ + m_nSiteID = SiteID; + + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO servers SET `site_id`=%d, `identity`='%s', `version_string`='%s', `online`=1, `ts`=UNIX_TIMESTAMP(now()), pid=%d ON DUPLICATE KEY UPDATE `version_string`='%s', `ts`=UNIX_TIMESTAMP(now()), `online`=1, pid=%d", + SiteID, identity, _BUILD_STRING_, PID, _BUILD_STRING_, PID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + + *ServID = getServerID( identity ); + m_nServerID = *ServID; + if( *ServID ) { + + sprintf(tQBuf,"INSERT INTO nodes SET `site_id`=%d, `aux_id`='%d', `type`= 0, `online`=1, `name`='Server Node' ON DUPLICATE KEY UPDATE `online`=1", m_nSiteID, *ServID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + *ServNode = ( uint32_t ) m_pDatabase->QueryID( tQBuf ); + + if( *ServNode == 0 ){ + *ServNode = getServerNode( *ServID ); + }; + m_nServerNodeID = *ServNode; + // Clenup Nodes and services ... + sprintf(tQBuf,"UPDATE nodes SET `online`=0 WHERE `server_id`=%d ", *ServID ); + #ifdef DEBUG_ALL + LOG(tQBuf); + #endif + m_pDatabase->SilentQuery( tQBuf ); + sprintf(tQBuf,"UPDATE cameras SET `online`=0 WHERE `site_id`=%d ", SiteID ); + #ifdef DEBUG_ALL + LOG(tQBuf); + #endif + m_pDatabase->SilentQuery( tQBuf ); + + sprintf(tQBuf,"UPDATE media_streams SET `valid`=0 WHERE `site_id`=%d ", SiteID ); + #ifdef DEBUG_ALL + LOG(tQBuf); + #endif + m_pDatabase->SilentQuery( tQBuf ); + + sprintf(tQBuf,"UPDATE media_server_streams SET `valid`=0, `online`=0 WHERE `site_id`=%d ", SiteID ); + #ifdef DEBUG_ALL + LOG(tQBuf); + #endif + m_pDatabase->SilentQuery( tQBuf ); + + //cleanResources( tServerNodeID ); + setNodeOnline( m_nServerNodeID ); + } + }; +}; + +void mysqlDBC::unregisterServer(){ + if( setNodeOffline( m_nServerNodeID ) ){ + char tQBuf[CTEXT]; + sprintf(tQBuf,"UPDATE servers SET `online`=0, `ts`=UNIX_TIMESTAMP(now()) WHERE `id`=%d", m_nServerID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; +}; + +bool mysqlDBC::setNodeOnline( uint32_t NodeID, uint8_t status ){ + if(m_bIsConnected){ + char tQBuf[CTEXT]; + if( NodeID ) { + sprintf(tQBuf,"UPDATE nodes SET `online`=%d WHERE `id`=%d", status, NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + sprintf(tQBuf,"UPDATE `resources` SET `active`=1 WHERE `node_id`=%d", NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + }; + return false; +}; + +bool mysqlDBC::setNodeOffline( uint32_t NodeID ){ + if(m_bIsConnected){ + char tQBuf[CTEXT]; + if( NodeID ) { + sprintf(tQBuf,"UPDATE nodes SET `online`=0 WHERE `id` = %d", NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + sprintf(tQBuf,"UPDATE `resources` SET `active`=0 WHERE `node_id` = %d", NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + }; + return false; +}; +DBC_RESOURCE_DATA *mysqlDBC::getResourceData( uint32_t ResourceID ){ + DBC_RESOURCE_DATA *tVal = NULL; + if( m_bIsConnected ){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `node_id`, `type`, `aux_id`, `device` FROM resources WHERE `id`=%d", ResourceID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_RESOURCE_DATA*) malloc(sizeof(DBC_RESOURCE_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + tVal->id = ResourceID; + it = cArr->find("node_id"); + if( it != cArr->end() ){ + tVal->node_id = atoi( it->second.c_str() ); + }; + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi( it->second.c_str() ); + }; + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal->aux_id = atoi( it->second.c_str() ); + }; + it = cArr->find("device"); + if( it != cArr->end() ){ + strncpy( tVal->device, it->second.c_str(), 64 ); + tVal->device[63] = (char)0; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t mysqlDBC::getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf(tQBuf,"SELECT `id` FROM `resources` WHERE `node_id`=%d AND `type`=%d AND `aux_id`=%d", NodeID, type, auxID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +uint32_t mysqlDBC::getServerID( CSTR identity ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf(tQBuf,"SELECT id FROM servers WHERE `identity`='%s'", identity ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +uint32_t mysqlDBC::getServerNode( uint32_t SID ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf(tQBuf,"SELECT id FROM nodes WHERE `type`=0 AND `aux_id`=%d", SID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +uint32_t mysqlDBC::addLocalMediaSource( uint32_t SiteID, CSTR path, uint32_t width, uint32_t height ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[1024]; + char tM5[33]; + CSTR tMD5 = MD5String( path ); + if( tMD5 != NULL ) { + memcpy( tM5, tMD5, 33 ); + tM5[32]=(char)0; + free( tMD5 ); + sprintf( tQBuf, "INSERT INTO media_streams SET `site_id`=%d, `source_id`=0, source_type='A', `valid`=1, `name`='Local Frame Grabber', `token`='%s', `img_width`=%d, `img_height`=%d, `mrl_proto`='v4l2', `mrl_port`='', `picture_proto`='', mrl='%s' ON DUPLICATE KEY UPDATE id=id, `valid`=1",//, img_width=%d, img_height=%d", + SiteID, tM5, width, height, path );//, width, height ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = (uint32_t) m_pDatabase->QueryID( tQBuf ); + }; + + }; + return RetVal; +}; +/* +uint32_t mysqlDBC::addNodeSocket( uint32_t NodeID, uint32_t auxID, uint8_t SocketType, uint8_t SocketMode, bool multidrop, CSTR path, CSTR name ){ + uint32_t retVal = 0; + if(m_bIsConnected){ + char tQBuf[2048]; + char tM5[33]; + CSTR tMD5 = MD5String( path ); + if( tMD5 != NULL ) { + memcpy( tM5, tMD5, 33 ); + free( tMD5 ); + if( multidrop ) { + sprintf(tQBuf,"INSERT INTO `sockets` SET `node_id`=%d, `type`=%d, `mode`=%d, `multidrop`=1, `md5`='%s', `path`='%s', `name`='%s', `aux_id`=%d ON DUPLICATE KEY UPDATE `id`=`id`, `name`='%s'", + NodeID, SocketType, SocketMode, tM5, path, name, auxID, name ); + } else { + sprintf(tQBuf,"INSERT INTO `sockets` SET `node_id`=%d, `type`=%d, `mode`=%d, `multidrop`=0, `md5`='%s', `path`='%s', `name`='%s', `aux_id`=%d ON DUPLICATE KEY UPDATE `id`=`id`, `name`='%s'", + NodeID, SocketType, SocketMode, tM5, path, name, auxID, name ); + }; +#ifdef DEBUG + LOG(tQBuf); +#endif + //m_pDatabase->SilentQuery( tQBuf ); + retVal = (uint32_t) m_pDatabase->QueryID( tQBuf ); + }; + }; + return retVal; +}; +*/ +bool mysqlDBC::addNotification( uint32_t MSG_ID, uint8_t DIS_LVL, uint32_t OBJ_ID ){ + if(m_bIsConnected){ + char tQBuf[2048]; + sprintf(tQBuf,"INSERT INTO `notifications` SET `site_id`=%d, `ts`=NOW(), `lvl`=%d, `type`=%d, `obj_id`=%d ON DUPLICATE KEY UPDATE `status`='A', `ts`=NOW()", m_nSiteID, DIS_LVL, MSG_ID, OBJ_ID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +uint32_t mysqlDBC::addResource( /*uint32_t NodeID,*/ uint8_t type, CSTR devName, uint32_t auxID ){ + uint32_t RetVal = 0; + if( m_bIsConnected ){ + char tQBuf[2048]; + sprintf( tQBuf, "%d:%d:%s", m_nServerNodeID, type, devName ); + CSTR tMD5 = MD5String( tQBuf ); + if( tMD5 ) { + sprintf( tQBuf, "INSERT INTO `resources` SET `node_id`=%d, `type`=%d, `md5`='%s', `aux_id`=%d, `device`='%s', `active`=1 ON DUPLICATE KEY UPDATE `active`=1, `aux_id`=%d", m_nServerNodeID, type, tMD5, auxID, devName, auxID ); + //sprintf( tQBuf, "INSERT INTO `resources` SET `node_id`=%d, `type`=%d, `aux_id`=%d, `device`='%s', `active`=1 ON DUPLICATE KEY UPDATE `active`=1, `aux_id`=%d, `device`='%s'", NodeID, type, auxID, devName, auxID, devName ); + free( tMD5 ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = (uint32_t) m_pDatabase->QueryID( tQBuf ); + if( RetVal == 0 ) { + RetVal = getResourceID( m_nServerNodeID, type, auxID ); + }; + }; + }; + return RetVal; +}; +/* +uint32_t mysqlDBC::getNodeSocketID( uint32_t NodeID, uint32_t auxID, uint8_t SocketType, CSTR path ){ + uint32_t retVal = 0; + if(m_bIsConnected){ + char tQBuf[2048]; + char tM5[33]; + CSTR tMD5 = MD5String( path ); + if( tMD5 != NULL ) { + memcpy( tM5, tMD5, 33 ); + free( tMD5 ); + sprintf( tQBuf,"SELECT id FROM `sockets` WHERE `node_id`=%d AND `type`=%d AND `md5`='%s' AND `aux_id`=%d", NodeID, SocketType, tM5, auxID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + retVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + }; + return retVal; +}; +*/ + +/* +CSTR mysqlDBC::getSocketName( uint32_t NodeID, uint32_t Type ){ + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf( tQBuf, "SELECT `name` FROM `sockets` WHERE `node_id`=%d AND `type`=%d LIMIT 1", + NodeID, Type ); +#ifdef DEBUG + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("name"); + if( it != cArr->end() ){ + strncpy( tQBuf, it->second.c_str(), CTEXT ); + }; + }; + }; + deleteResult( result ); + return strdup(tQBuf); + }; + return NULL; +}; +*/ +KAFKA_SETTINGS *mysqlDBC::getSettingsKAFKA( uint32_t ModuleID ){ + KAFKA_SETTINGS *tVal = NULL; + if( m_bIsConnected ) { + char tQBuf[CTEXT]; + AAssoc *result; + sprintf( tQBuf, "SELECT * FROM modules_kafka WHERE module_id = %d", ModuleID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (KAFKA_SETTINGS*) malloc(sizeof(KAFKA_SETTINGS)); + if( tVal != NULL ) { + memset( tVal, 0, sizeof(KAFKA_SETTINGS) ); + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("brocker_address"); + if( it != cArr->end() ){ + strncpy( tVal->brocker_addr, it->second.c_str(), 255 ); + }; + it = cArr->find("brocker_port"); + if( it != cArr->end() ){ + tVal->brocker_port = atoi( it->second.c_str() ); + }; + it = cArr->find("use_ssl"); + if( it != cArr->end() ){ + tVal->use_ssl = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("auth_cert"); + if( it != cArr->end() ){ + tVal->auth_by_cert = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("auth_cred"); + if( it != cArr->end() ){ + tVal->auth_by_cred = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("vault_md5"); + if( it != cArr->end() ){ + strncpy( tVal->vault_md5, it->second.c_str(), 32 ); + }; + it = cArr->find("truststore"); + if( it != cArr->end() ){ + tVal->truststore = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("certstore"); + if( it != cArr->end() ){ + tVal->certstore = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("keystore"); + if( it != cArr->end() ){ + tVal->keystore = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("cred_username"); + if( it != cArr->end() ){ + strncpy( tVal->cred_username, it->second.c_str(), 32 ); + }; + it = cArr->find("cred_password"); + if( it != cArr->end() ){ + strncpy( tVal->cred_password, it->second.c_str(), 32 ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +KAFKA_TEMPLATE *mysqlDBC::getKafkaTemplateForEvent( uint32_t ModuleID, uint32_t ClassID, uint32_t EventID ){ + KAFKA_TEMPLATE *tVal = NULL; + if( m_bIsConnected ) { + char tQBuf[CTEXT]; + AAssoc *result; + sprintf( tQBuf, "SELECT topic, template FROM module_kafka_settings WHERE module_id=%d AND class_id=%d AND event_id=%d", ModuleID, ClassID, EventID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (KAFKA_TEMPLATE*) malloc(sizeof(KAFKA_TEMPLATE)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("topic"); + if( it != cArr->end() ){ + memset( tVal->topic, 0, 128 ); + strncpy( tVal->topic , it->second.c_str(), 127 ); + }; + it = cArr->find("template"); + if( it != cArr->end() ){ + tVal->tpl = (CSTR)malloc( it->second.length() + 1 ); + if( tVal->tpl!= NULL) { + memset( tVal->tpl, 0, it->second.length() + 1 ); + strncpy( tVal->tpl, it->second.c_str(), it->second.length() ); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_UART_DATA *mysqlDBC::getUartData( uint32_t UartID ){ + DBC_UART_DATA *tVal = NULL; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + AAssoc *result; + sprintf( tQBuf, "SELECT * FROM uart_settings WHERE id = %d", UartID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_UART_DATA*) malloc(sizeof(DBC_UART_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi( it->second.c_str() ); + }; + it = cArr->find("speed"); + if( it != cArr->end() ){ + tVal->speed = atoi( it->second.c_str() ); + }; + it = cArr->find("mode"); + if( it != cArr->end() ){ + tVal->mode = atoi( it->second.c_str() ); + }; + it = cArr->find("port"); + if( it != cArr->end() ){ + tVal->port = atoi( it->second.c_str() ); + }; + it = cArr->find("path"); + if( it != cArr->end() ){ + strncpy( tVal->path, it->second.c_str(), 128 ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t mysqlDBC::getUartID( uint32_t NodeID, uint8_t Type, CSTR path ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf(tQBuf,"SELECT `id` FROM `uart_settings` WHERE `node_id`=%d AND `type`=%d AND `path`='%s' ", NodeID, Type, path ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +bool mysqlDBC::updateMediaServerStream( uint32_t id, CSTR mrl, CSTR key ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + if( key == NULL ) { + if( mrl == NULL ) { + sprintf( tQBuf,"UPDATE media_server_streams SET `online`=0, `key`='', mrl='', `valid`=0 WHERE `id`=%d", id ); + } else { + sprintf( tQBuf,"UPDATE media_server_streams SET `online`=0, `key`='', `mrl`='%s', `valid`=1 WHERE `id`=%d", mrl, id ); + }; + } else { + sprintf( tQBuf,"UPDATE media_server_streams SET `online`=1, `key`='%s', `mrl`='%s', `valid`=1 WHERE `id`=%d", + key, + mrl, + id + ); + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::updateResourceAUX( uint32_t ResID, uint32_t AUX ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "UPDATE `resources` SET `aux_id`=%d WHERE `id`=%d", AUX, ResID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +//bool mysqlDBC::updateServerUtilisation( uint32_t ServerID, uint32_t nCores, float cpu1, float cpu5, float cpu15, float mem, float disk, uint64_t dtsize, uint64_t dcsize, uint64_t mtsize, uint64_t mcsize ){ +bool mysqlDBC::updateServerUtilisation( DBC_SYS_LOAD_INFO *ptr ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "UPDATE `servers` SET `ts`=UNIX_TIMESTAMP(now()), `cpu_cores`=%d, `stat_cpu1`=%0.2f, `stat_cpu5`=%0.2f, `stat_cpu15`=%0.2f, `stat_mem`=%0.2f, `stat_disk`=%0.2f, `temp0`=%0.1f, `val_mem_tottal`=%" PRIu64 ", `val_mem_current`=%" PRIu64 ", `val_disk_tottal`=%" PRIu64 ", `val_disk_current`=%" PRIu64 " WHERE `id`=%d", + ptr->CPU_CORES, + ptr->cpu1, + ptr->cpu5, + ptr->cpu15, + ptr->mem, + ptr->disk, + ptr->temperature, + ptr->T_DISK, + ptr->C_DISK, + ptr->T_MEM, + ptr->C_MEM, + m_nServerID + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +uint32_t mysqlDBC::addLocalDCB( uint32_t SiteID, CSTR PATH, CSTR SERIAL, uint8_t CNT, uint32_t status ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO modules_dcr SET site_id=%d, status=%d, channels=%d, serial_id='%s' ON DUPLICATE KEY UPDATE status=%d, channels=%d", + SiteID, + status, + CNT, + SERIAL, + status, + CNT + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + uint64_t cid = m_pDatabase->QueryID( tQBuf ); + if( cid == 0 ) { + AAssoc *result; + sprintf( tQBuf, "SELECT id FROM modules_dcr WHERE site_id=%d AND serial_id='%s'", + SiteID, + SERIAL + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + cid = atoi( it->second.c_str() ); + }; + }; + deleteResult( result ); + }; + }; + if( cid!= 0 ) { + for( uint8_t idx = 0; idx < CNT; idx++ ) { + if( status & ( 1 << idx ) ){ + sprintf( tQBuf, "INSERT INTO module_dcr_chanels SET dcr_id=%d, channel_id=%d, mode='O', status='C' ON DUPLICATE KEY UPDATE status='C'", + (uint32_t) cid, + idx + ); + } else { + sprintf( tQBuf, "INSERT INTO module_dcr_chanels SET dcr_id=%d, channel_id=%d, mode='O', status='O' ON DUPLICATE KEY UPDATE status='O'", + (uint32_t) cid, + idx + ); + } +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + }; + }; + }; + return RetVal; +}; + +uint32_t mysqlDBC::addLocalUART( /*uint32_t NodeID,*/ uint8_t utype, uint32_t speed, uint8_t bit, char parity, float stop_bit, CSTR PATH, uint8_t mode, uint16_t port ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `uart_settings` SET `node_id`=%d, `type`=%d, `speed`=%d, `bit`=%d, `parity`='%c', `stop_bit`=%.1f, `mode`=%d, `port`=%d, `path`='%s' ON DUPLICATE KEY UPDATE `id`=`id`", + m_nServerNodeID, + utype, + speed, + bit, + parity, + stop_bit, + mode, + port, + PATH + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = m_pDatabase->QueryID( tQBuf ); + if( RetVal == 0 ) { + RetVal = getUartID( m_nServerNodeID, utype, PATH ); + }; + }; + return RetVal; +}; + +uint32_t mysqlDBC::addLocalNIF( CSTR device, CSTR mac, NIF_TYPE dtype, NIF_MODE dmode, uint32_t aux_id ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + char * tKey = MD5String( device ); + if( tKey != NULL ) { + sprintf( tQBuf, "INSERT INTO `network_interfaces` SET `type`=%d, `key`='%s', `device_name`='%s', `mac`='%s', `mode`=%d, `aux_id`=%d ON DUPLICATE KEY UPDATE `mode`=%d, `aux_id`=%d, `mac`='%s'", + dtype, + tKey, + device, + mac, + dmode, + aux_id, + dmode, + aux_id, + mac + ); +#ifdef DEBUG + LOG(tQBuf); +#endif + RetVal = m_pDatabase->QueryID( tQBuf ); + if( RetVal == 0 ) { + RetVal = getNIF_ID( tKey ); + }; + free( tKey ); + }; + }; + return RetVal; +}; + +uint32_t mysqlDBC::addLocalWiFi( uint32_t NIF_ID, WIFI_MODE mode, CSTR SSID, CSTR password, WIFI_ENCRIPTION encryption, uint32_t router_id ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `wifis` SET `nif_id`=%d, `mode`=%d, `aux_id`=%d, `SSID`='%s', `password`='%s', `encryption_type`=%d ON DUPLICATE KEY UPDATE `mode`=%d, `aux_id`=%d, `SSID`='%s', `password`='%s', `encryption_type`=%d", + NIF_ID, + mode, + router_id, + SSID, + password, + encryption, + mode, + router_id, + SSID, + password, + encryption + ); +#ifdef DEBUG + LOG(tQBuf); +#endif + RetVal = m_pDatabase->QueryID( tQBuf ); + if( RetVal == 0 ) { + RetVal = getWiFi_ID( NIF_ID ); + }; + }; + return RetVal; +}; + +uint32_t mysqlDBC::addLRFMask( uint32_t devID, uint8_t lrfID, uint8_t layerID ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `lrf_masks` SET `sensor_id`=%d, `lrf_id`=%d, `layer`=%d ON DUPLICATE KEY UPDATE `id`=`id`", + devID, + lrfID, + layerID + ); +#ifdef DEBUG + LOG(tQBuf); +#endif + RetVal = m_pDatabase->QueryID( tQBuf ); + if( RetVal == 0 ) { + RetVal = getLRFMaskID( devID, lrfID, layerID ); + }; + }; + return RetVal; +}; + +uint32_t mysqlDBC::addLRFMaskPolygone( uint32_t maskID, uint8_t r, uint8_t g, uint8_t b ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `lrf_mask_vertexes` SET `mask_id`=%d, `r`=%d, `g`=%d, `b`=%d", + maskID, + r, + g, + b + ); +#ifdef DEBUG + LOG(tQBuf); +#endif + RetVal = m_pDatabase->QueryID( tQBuf ); + }; + return RetVal; +}; + +bool mysqlDBC::addLRFMaskPolygonePoint( uint32_t polyID, int16_t x, int16_t y ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `lrf_mask_vertex_points` SET `vertex_id`=%d, `x`=%d, `y`=%d", + polyID, + x, + y + ); +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +uint32_t mysqlDBC::addLocalNetwork( uint32_t NIF_ID, NETWORK_TYPE net_type, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `networks` SET `nif_id`=%d, `type`=%d, `address`='%s', `gateway`='%s', `mask`='%s', `broadcast`='%s' ON DUPLICATE KEY UPDATE `address`='%s', `gateway`='%s', `mask`='%s', `broadcast`='%s'", + NIF_ID, + net_type, + address, + gateway, + mask, + broadcast, + address, + gateway, + mask, + broadcast + ); +#ifdef DEBUG + LOG(tQBuf); +#endif + RetVal = m_pDatabase->QueryID( tQBuf ); + // On Update IF data no need to return ID + //if( RetVal == 0 ) { + // RetVal = getNetworkInterfaceID( tKey ); + //}; + }; + return RetVal; +}; + +uint32_t mysqlDBC::addLocalNetworkInfrastructure( uint32_t NIF_ID, uint32_t OUTBOUND_NIF, bool ena_dhcp, CSTR BRANG, CSTR ERANG, CSTR MASK, CSTR LEASE_TIME ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + bool ena_routing = true; + if( OUTBOUND_NIF == 0 ){ + ena_routing = false; + }; + if( ena_dhcp ){ + if ( BRANG == NULL || ERANG == NULL || MASK == NULL || LEASE_TIME == NULL ) { + LOG_ERROR("Wrong DHCP parameters to create Network Infrastructure!"); + return 0; + }; + sprintf(tQBuf, "INSERT INTO `network_infrastructure` SET `nif_id`=%d, `enable_routing`=%d, `outbond_nif`=%d, `enable_dhcp`=1, `dhcp_range_begin`='%s', `dhcp_range_end`='%s', `dhcp_range_mask`='%s', `dhcp_lease_time`='%s' ON DUPLICATE KEY UPDATE `enable_routing`=%d, `outbond_nif`=%d, `enable_dhcp`=1, `dhcp_range_begin`='%s', `dhcp_range_end`='%s', `dhcp_range_mask`='%s', `dhcp_lease_time`='%s'", + NIF_ID, + ena_routing, + OUTBOUND_NIF, + BRANG, + ERANG, + MASK, + LEASE_TIME, + ena_routing, + OUTBOUND_NIF, + BRANG, + ERANG, + MASK, + LEASE_TIME + ); + } else { + if( ena_routing ){ + sprintf(tQBuf, "INSERT INTO `network_infrastructure` SET `nif_id`=%d, `enable_routing`=1, `outbond_nif`=%d ON DUPLICATE KEY UPDATE `enable_routing`=1, `outbond_nif`=%d", + NIF_ID, + OUTBOUND_NIF, + OUTBOUND_NIF + ); + } else { + LOG_ERROR("No Special Service Defined To Network Infrastructure!"); + return 0; + }; + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = m_pDatabase->QueryID( tQBuf ); + // On Update IF data no need to return ID + if( RetVal == 0 ) { + RetVal = getNetworkInfrastructureID( NIF_ID ); + }; + }; + return RetVal; +}; + +bool mysqlDBC::addLRFDraw( uint32_t DBID, uint32_t SIZE, CSTR ID, uint8_t kID, uint8_t type, bool rendered ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + if ( rendered ) { + sprintf(tQBuf, "INSERT INTO `lrf_draw` SET `node_id`=%d,`ts`=NOW(),`md5`='%s',`size`=%d, `lrf_id`=%d, `type`=%d, `rendered`='Y' ON DUPLICATE KEY UPDATE `ts`=NOW(),`md5`='%s',`size`=%d, `rendered`='Y'", + DBID, + ID, + SIZE, + kID, + type, + ID, + SIZE + ); + } else { + sprintf(tQBuf, "INSERT INTO `lrf_draw` SET `node_id`=%d,`ts`=NOW(),`md5`='%s',`size`=%d, `lrf_id`=%d, `type`=%d ON DUPLICATE KEY UPDATE `ts`=NOW(),`md5`='%s',`size`=%d, `rendered`='N'", + DBID, + ID, + SIZE, + kID, + type, + ID, + SIZE + ); + }; +#ifdef DEBUG + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; +uint32_t mysqlDBC::addEvent( uint32_t SRC, CSTR UUID, uint32_t tss, uint32_t tsms, uint8_t evt_type, uint8_t k_id, uint16_t dig_r, float EL, float AZ, float RANGE, float AREA, float lat, float lon, float alt, uint32_t RefID, CSTR RefUUID ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + if( RefUUID == NULL ) { + sprintf( tQBuf,"INSERT INTO events_archive SET node_id=%d, uuid='%s', ts=%d, ts_ms=%d, evt_type=%d, lrf_id=%d, range_digital=%d, azimuth=%0.6f, elevation=%0.6f, `range`=%0.2f, area=%0.3f, lat=%0.6f, lon=%0.6f, alt=%0.3f", + SRC, + UUID, + tss, + tsms, + evt_type, + k_id, + dig_r, + AZ, + EL, + RANGE, + AREA, + lat, + lon, + alt + ); + } else { + sprintf( tQBuf,"INSERT INTO events_archive SET node_id=%d, uuid='%s', ts=%d, ts_ms=%d, evt_type=%d, lrf_id=%d, range_digital=%d, azimuth=%0.6f, elevation=%0.6f, `range`=%0.2f, area=%0.3f, lat=%0.6f, lon=%0.6f, alt=%0.3f, ref_uuid='%s'", + SRC, + UUID, + tss, + tsms, + evt_type, + k_id, + dig_r, + AZ, + EL, + RANGE, + AREA, + lat, + lon, + alt, + RefUUID + ); + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = (uint32_t) m_pDatabase->QueryID( tQBuf ); + if( RetVal ) { + if (RefUUID == NULL) { + sprintf( tQBuf,"INSERT INTO events_cloud SET id=%d, node_id=%d, uuid='%s', ts=%d, ts_ms=%d, evt_type=%d, lrf_id=%d, range_digital=%d, azimuth=%0.6f, elevation=%0.6f, `range`=%0.2f, area=%0.3f, lat=%0.6f, lon=%0.6f, alt=%0.3f", + RetVal, + SRC, + UUID, + tss, + tsms, + evt_type, + k_id, + dig_r, + AZ, + EL, + RANGE, + AREA, + lat, + lon, + alt + ); + } else { + sprintf( tQBuf,"INSERT INTO events_cloud SET id=%d, node_id=%d, uuid='%s', ts=%d, ts_ms=%d, evt_type=%d, lrf_id=%d, range_digital=%d, azimuth=%0.6f, elevation=%0.6f, `range`=%0.2f, area=%0.3f, lat=%0.6f, lon=%0.6f, alt=%0.3f, ref_uuid='%s'", + RetVal, + SRC, + UUID, + tss, + tsms, + evt_type, + k_id, + dig_r, + AZ, + EL, + RANGE, + AREA, + lat, + lon, + alt, + RefUUID + ); + }; + m_pDatabase->SilentQuery( tQBuf ); + }; + // Cleanup Mem Targets Older then 1 Hour + sprintf( tQBuf, "DELETE FROM events_cloud WHERE ts < ( UNIX_TIMESTAMP(NOW()) - 3600 )" ); + m_pDatabase->SilentQuery( tQBuf ); + }; + return RetVal; +}; + +bool mysqlDBC::addDeviceDraw( uint32_t DBID, uint8_t type, uint8_t lrf, void *th_data, uint32_t th_size ){ + bool rVal = false; + if( th_data != NULL && th_size ){ + if( m_bIsConnected ){ + CSTR tPData = m_pDatabase->escapeBinary( (uint8_t *) th_data, th_size ); + if ( tPData ) { + CSTR tQBuf = (CSTR)malloc(BUF_4MB); + if( tQBuf ) { + sprintf( tQBuf, "DELETE FROM `lrf_draw` WHERE `node_id`=%d AND `lrf_id`=%d AND `type`=%d", DBID, lrf, type ); + LOG( tQBuf ); + m_pDatabase->SilentQuery( tQBuf ); + sprintf( tQBuf, "INSERT INTO lrf_draw(node_id,ts,lrf_id,type,size,data) VALUES(%d,NOW(),%d,%d,%d,'%s')", DBID, lrf, type, th_size, tPData ); + m_pDatabase->SilentQuery( tQBuf ); + LOG( "Inserted Draw OK!" ); + free( tQBuf ); + rVal = true; + } else { + LOG_ERROR("Error Allocating Query Buffer!"); + }; + free( tPData ); + } else { + LOG_ERROR( "Error escaping Pic Data!"); + }; + }; + }; + return rVal; +}; + +bool mysqlDBC::addVideoEvent( uint32_t evtID, uint32_t videoID, uint32_t clen ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `events_2_videos` SET `evt_id`=%d, `video_id`=%d, `frame`=%d", evtID, videoID, clen ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return true; +}; +/* +bool mysqlDBC::addPictureEvent( uint32_t evtID, uint32_t pictureoID ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `events_2_pictures` SET `evt_id`=%d, `picture_id`=%d", evtID, pictureoID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return true; +}; +*/ + +uint32_t mysqlDBC::addVideoRecord( uint32_t streamID, CSTR md5, CSTR ext, uint32_t ts, uint32_t tsms, uint32_t fps ){ + uint32_t tID = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `videos` SET `media_stream_id`=%d, `uts`=%d, `uts_ms`=%d, `md5`='%s', `ext`='%s', `fps`=%d ", streamID, ts, tsms, md5, ext, fps ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + tID = (uint32_t) m_pDatabase->QueryID( tQBuf ); + } + return tID; +}; + +bool mysqlDBC::addPicture( DBC_SNAPSHOT_DATA *ptr, CSTR ext ){ + bool rVal = false; + if( ptr != NULL ){ + if( m_bIsConnected ){ + CSTR tPData = m_pDatabase->escapeBinary( ptr->data, ptr->data_size ); + if ( tPData ) { + uint32_t pic_id; + CSTR tQBuf = (CSTR)malloc(BUF_4MB); + if( tQBuf ) { + //sprintf( tQBuf, "INSERT INTO `pictures` SET `media_stream_id`=%d, `ts`=NOW(), `md5`='%s', `ext`='%s'", + sprintf( tQBuf, "INSERT INTO pictures(media_stream_id,ts,md5,ext,data) VALUES(%d,NOW(),'%s','%s','%s')", + ptr->stream_id, ptr->md5, ext, tPData ); + pic_id = (uint32_t) m_pDatabase->QueryID( tQBuf ); + if ( pic_id ) { + for( DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++ ) { + sprintf( tQBuf, "INSERT INTO `events_2_pictures` SET `evt_id`=%d, `picture_id`=%d", (*idx), pic_id ); + m_pDatabase->SilentQuery( tQBuf ); + }; + rVal = true; + }; + free( tQBuf ); + } else { + LOG_ERROR("Error Allocating Query Buffer!"); + }; + free( tPData ); + } else { + LOG_ERROR( "Error escaping Pic Data!"); + }; + }; + }; + return rVal; +}; + +bool mysqlDBC::updateLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master, uint16_t nOrder, uint16_t nOffset, uint16_t nDelta, uint16_t nWidth, uint16_t nFlip, uint16_t nSun, uint8_t bSST, uint32_t GP, uint32_t spikes ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + if( master ) { + sprintf( tQBuf, "INSERT INTO `lrf_detection_profiles` SET `aux_id`=%d, `profile_id`=%d, `master`=b'1', `order`=%d, `offset`=%d, `delta`=%d, `flip`=%d, `width`=%d, `sst`=%d, `sun`=%d, `gp`=%d, `spikes`=%d ON DUPLICATE KEY UPDATE `order`=%d, `offset`=%d, `delta`=%d, `flip`=%d, `width`=%d, `sst`=%d, `sun`=%d, `gp`=%d, `spikes`=%d", + lrfID, + profileID, + nOrder, + nOffset, + nDelta, + nFlip, + nWidth, + bSST, + nSun, + GP, + spikes, + nOrder, + nOffset, + nDelta, + nFlip, + nWidth, + bSST, + nSun, + GP, + spikes ); + } else { + sprintf( tQBuf, "INSERT INTO `lrf_detection_profiles` SET `aux_id`=%d, `profile_id`=%d, `master`=b'0', `order`=%d, `offset`=%d, `delta`=%d, `flip`=%d, `width`=%d, `sst`=%d, `sun`=%d, `gp`=%d, `spikes`=%d ON DUPLICATE KEY UPDATE `order`=%d, `offset`=%d, `delta`=%d, `flip`=%d, `width`=%d, `sst`=%d, `sun`=%d, `gp`=%d, `spikes`=%d", + lrfID, + profileID, + nOrder, + nOffset, + nDelta, + nFlip, + nWidth, + bSST, + nSun, + GP, + spikes, + nOrder, + nOffset, + nDelta, + nFlip, + nWidth, + bSST, + nSun, + GP, + spikes ); + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::updateLRFSerial( uint32_t lrfID, CSTR Serial ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + CSTR tES = m_pDatabase->escapeString( Serial ); + if( tES ) { + sprintf( tQBuf, "UPDATE `lrf_sensors` SET `serial`='%s' WHERE `id`=%d", tES, lrfID ); + free( tES ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + }; + return false; +}; +bool mysqlDBC::updateLRFVerison( uint32_t lrfID, CSTR version ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + CSTR tES = m_pDatabase->escapeString( version ); + if( tES ) { + sprintf( tQBuf, "UPDATE `lrf_sensors` SET `version`='%s' WHERE `id`=%d", tES, lrfID ); + free( tES ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + }; + return false; +}; + +bool mysqlDBC::update3DRuntimeStatus( uint32_t lrfID, ALG_RUN_STATUS *ptr ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `lrf_runtime_status` SET `lrf_id`=%d ON DUPLICATE KEY UPDATE `lrf_id`=`lrf_id`", lrfID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + sprintf( tQBuf, + "UPDATE `lrf_runtime_status` SET " + "`hw_status`=%d," + "`detecting_kernels`=%d," + "`th_ready`=%d," + "`master_flips`=%d," + "`slave_flips`=%d," + "`twinc`=%d," + "`master_mp_0`=%d," + "`master_mp_1`=%d," + "`master_mp_2`=%d," + "`master_mp_3`=%d," + "`master_mp_4`=%d," + "`master_mp_5`=%d," + "`master_mp_6`=%d," + "`master_mp_7`=%d," + "`master_gp_0`=%d," + "`master_gp_1`=%d," + "`master_gp_2`=%d," + "`master_gp_3`=%d," + "`master_gp_4`=%d," + "`master_gp_5`=%d," + "`master_gp_6`=%d," + "`master_gp_7`=%d," + "`master_wp_0`=%d," + "`master_wp_1`=%d," + "`master_wp_2`=%d," + "`master_wp_3`=%d," + "`master_wp_4`=%d," + "`master_wp_5`=%d," + "`master_wp_6`=%d," + "`master_wp_7`=%d," + "`slave_mp_0`=%d," + "`slave_mp_1`=%d," + "`slave_mp_2`=%d," + "`slave_mp_3`=%d," + "`slave_mp_4`=%d," + "`slave_mp_5`=%d," + "`slave_mp_6`=%d," + "`slave_mp_7`=%d," + "`slave_gp_0`=%d," + "`slave_gp_1`=%d," + "`slave_gp_2`=%d," + "`slave_gp_3`=%d," + "`slave_gp_4`=%d," + "`slave_gp_5`=%d," + "`slave_gp_6`=%d," + "`slave_gp_7`=%d," + "`slave_wp_0`=%d," + "`slave_wp_1`=%d," + "`slave_wp_2`=%d," + "`slave_wp_3`=%d," + "`slave_wp_4`=%d," + "`slave_wp_5`=%d," + "`slave_wp_6`=%d," + "`slave_wp_7`=%d" + " WHERE `lrf_id`=%d", + ptr->HW_STATUS, + ptr->DETECTING_LRF, + ptr->TH_READY, + ptr->MASTER_FLIP_CNT, + ptr->SLAVE_FLIP_CNT, + ptr->TWINC_STATUS, + ptr->MASTER_MP[0], + ptr->MASTER_MP[1], + ptr->MASTER_MP[2], + ptr->MASTER_MP[3], + ptr->MASTER_MP[4], + ptr->MASTER_MP[5], + ptr->MASTER_MP[6], + ptr->MASTER_MP[7], + ptr->MASTER_GP[0], + ptr->MASTER_GP[1], + ptr->MASTER_GP[2], + ptr->MASTER_GP[3], + ptr->MASTER_GP[4], + ptr->MASTER_GP[5], + ptr->MASTER_GP[6], + ptr->MASTER_GP[7], + ptr->MASTER_WP[0], + ptr->MASTER_WP[1], + ptr->MASTER_WP[2], + ptr->MASTER_WP[3], + ptr->MASTER_WP[4], + ptr->MASTER_WP[5], + ptr->MASTER_WP[6], + ptr->MASTER_WP[7], + ptr->SLAVE_MP[0], + ptr->SLAVE_MP[1], + ptr->SLAVE_MP[2], + ptr->SLAVE_MP[3], + ptr->SLAVE_MP[4], + ptr->SLAVE_MP[5], + ptr->SLAVE_MP[6], + ptr->SLAVE_MP[7], + ptr->SLAVE_GP[0], + ptr->SLAVE_GP[1], + ptr->SLAVE_GP[2], + ptr->SLAVE_GP[3], + ptr->SLAVE_GP[4], + ptr->SLAVE_GP[5], + ptr->SLAVE_GP[6], + ptr->SLAVE_GP[7], + ptr->SLAVE_WP[0], + ptr->SLAVE_WP[1], + ptr->SLAVE_WP[2], + ptr->SLAVE_WP[3], + ptr->SLAVE_WP[4], + ptr->SLAVE_WP[5], + ptr->SLAVE_WP[6], + ptr->SLAVE_WP[7], + lrfID + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::setLRFDataStatus( uint32_t lrfID, uint8_t ST ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "UPDATE `lrf_sensors` SET `data_status`=%d WHERE `id`=%d", ST, lrfID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::setLRFDetectionProfile( uint32_t lrfID, uint8_t profileID ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "UPDATE `lrf_sensors` SET `detection_profile_id`=%d WHERE `id`=%d", profileID, lrfID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::setLRFMaskStatus( uint32_t maskID, bool status ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + char S[2]; + if (status ) { + S[0] = 'E'; + S[1] = (char)0; + } else { + S[0] = 'D'; + S[1] = (char)0; + }; + sprintf( tQBuf, "UPDATE `lrf_masks` SET `status`='%s' WHERE `id`=%d", S, maskID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; +bool mysqlDBC::setLRFAltSerial( uint32_t lrfID, CSTR Serial ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "UPDATE `lrf_sensors` SET `alt_serial`='%s' WHERE `id`=%d", Serial, lrfID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; +bool mysqlDBC::setLRFAltVerison( uint32_t lrfID, CSTR version ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "UPDATE `lrf_sensors` SET `alt_version`='%s' WHERE `id`=%d", version, lrfID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::setStreamValid( uint32_t streamID, bool status ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + if ( status ) { + sprintf(tQBuf, "UPDATE `media_streams` SET `valid`=1 WHERE `id`=%d", streamID); + } else { + sprintf(tQBuf, "UPDATE `media_streams` SET `valid`=0 WHERE `id`=%d", streamID); + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool mysqlDBC::updateAFPBox( uint32_t filterID, CSTR Tag, float x, float y, float z ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `target_filter_apf_boxes` SET `filter_id`=%d, `tag`='%s', `ts`=NOW(), `x`=%0.3f, `y`=%0.3f, `z`=%0.3f ON DUPLICATE KEY UPDATE `ts`=NOW(), `x`=%0.3f, `y`=%0.3f, `z`=%0.3f", + filterID, + Tag, + x,y,z, + x,y,z + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDatabase->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +DBC_MODULE_EMBED_VIDEO_DATA *mysqlDBC::getEmbedVideoData( uint32_t ID ){ + DBC_MODULE_EMBED_VIDEO_DATA *tPtr = NULL; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + AAssoc *result; + sprintf( tQBuf, "SELECT * FROM `module_eve` WHERE `id`=%d", ID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tPtr = (DBC_MODULE_EMBED_VIDEO_DATA*)malloc(sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); + if( tPtr!= NULL ) { + Assoc::iterator it; + memset(tPtr,0,sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); + cArr = result->at(0); + it = cArr->find("output_mode"); + if( it != cArr->end() ){ + tPtr->output_mode = atoi( it->second.c_str() ); + }; + it = cArr->find("web_port"); + if( it != cArr->end() ){ + tPtr->port = atoi( it->second.c_str() ); + }; + it = cArr->find("width"); + if( it != cArr->end() ){ + tPtr->width = atoi( it->second.c_str() ); + }; + it = cArr->find("height"); + if( it != cArr->end() ){ + tPtr->height = atoi( it->second.c_str() ); + }; + it = cArr->find("compression_quality"); + if( it != cArr->end() ){ + tPtr->compression_quality = atoi( it->second.c_str() ); + }; + it = cArr->find("show_ts"); + if( it != cArr->end() ){ + tPtr->show_ts = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("ts_x"); + if( it != cArr->end() ){ + tPtr->ts_x = atoi( it->second.c_str() ); + }; + it = cArr->find("ts_y"); + if( it != cArr->end() ){ + tPtr->ts_y = atoi( it->second.c_str() ); + }; + it = cArr->find("ts_font_face"); + if( it != cArr->end() ){ + tPtr->ts_font_face = atoi( it->second.c_str() ); + }; + it = cArr->find("ts_font_scale"); + if( it != cArr->end() ){ + tPtr->ts_font_scale = atof( it->second.c_str() ); + }; + it = cArr->find("ts_font_thickness"); + if( it != cArr->end() ){ + tPtr->ts_font_thickness = atoi( it->second.c_str() ); + }; + it = cArr->find("ts_line_type"); + if( it != cArr->end() ){ + tPtr->ts_line_type = atoi( it->second.c_str() ); + }; + it = cArr->find("ts_transperant"); + if( it != cArr->end() ){ + tPtr->ts_transperant = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("show_label"); + if( it != cArr->end() ){ + tPtr->show_label = (bool)atoi( it->second.c_str() ); + }; + it = cArr->find("label_x"); + if( it != cArr->end() ){ + tPtr->label_x = atoi( it->second.c_str() ); + }; + it = cArr->find("label_y"); + if( it != cArr->end() ){ + tPtr->label_y = atoi( it->second.c_str() ); + }; + it = cArr->find("label_font_face"); + if( it != cArr->end() ){ + tPtr->label_font_face = atoi( it->second.c_str() ); + }; + it = cArr->find("label_font_scale"); + if( it != cArr->end() ){ + tPtr->label_font_scale = atof( it->second.c_str() ); + }; + it = cArr->find("label_font_thickness"); + if( it != cArr->end() ){ + tPtr->label_font_thickness = atoi( it->second.c_str() ); + }; + it = cArr->find("label_line_type"); + if( it != cArr->end() ){ + tPtr->label_line_type = atoi( it->second.c_str() ); + }; + it = cArr->find("label_transperant"); + if( it != cArr->end() ){ + tPtr->label_transperant = (bool) atoi( it->second.c_str() ); + }; + it = cArr->find("show_logo"); + if( it != cArr->end() ){ + tPtr->show_logo = (bool) atoi( it->second.c_str() ); + }; + it = cArr->find("logo_w"); + if( it != cArr->end() ){ + tPtr->logo_w = atoi( it->second.c_str() ); + }; + it = cArr->find("logo_h"); + if( it != cArr->end() ){ + tPtr->logo_h = atoi( it->second.c_str() ); + }; + it = cArr->find("logo_x"); + if( it != cArr->end() ){ + tPtr->logo_x = atoi( it->second.c_str() ); + }; + it = cArr->find("logo_y"); + if( it != cArr->end() ){ + tPtr->logo_y = atoi( it->second.c_str() ); + }; + it = cArr->find("logo_md5"); + if( it != cArr->end() ){ + strncpy( tPtr->logo_md5, it->second.c_str(),32); + tPtr->logo_md5[32]=(char)0; + }; + }; + }; + }; + deleteResult( result ); + }; + return tPtr; +}; + +DBC_EVT_RECORD *mysqlDBC::getEventByUUID( CSTR UUID ){ + DBC_EVT_RECORD *tPtr = NULL; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + AAssoc *result; + sprintf( tQBuf, "SELECT * FROM events_cloud WHERE uuid = '%s'", UUID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDatabase->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tPtr = (DBC_EVT_RECORD*)malloc(sizeof(DBC_EVT_RECORD)); + if( tPtr!= NULL ) { + Assoc::iterator it; + memset(tPtr,0,sizeof(DBC_EVT_RECORD)); + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tPtr->id = atoi( it->second.c_str() ); + }; + it = cArr->find("node_id"); + if( it != cArr->end() ){ + tPtr->node_id = atoi( it->second.c_str() ); + }; + it = cArr->find("uuid"); + if( it != cArr->end() ){ + strncpy( tPtr->uuid, it->second.c_str(),64 ); + }; + it = cArr->find("ts"); + if( it != cArr->end() ){ + tPtr->ts_s = atoi( it->second.c_str() ); + }; + it = cArr->find("ts_ms"); + if( it != cArr->end() ){ + tPtr->ts_ms = atoi( it->second.c_str() ); + }; + it = cArr->find("evt_type"); + if( it != cArr->end() ){ + tPtr->type = atoi( it->second.c_str() ); + }; + it = cArr->find("range_digital"); + if( it != cArr->end() ){ + tPtr->range_digital = atoi( it->second.c_str() ); + }; + it = cArr->find("azimuth"); + if( it != cArr->end() ){ + tPtr->az = atof( it->second.c_str() ); + }; + it = cArr->find("elevation"); + if( it != cArr->end() ){ + tPtr->el = atof( it->second.c_str() ); + }; + it = cArr->find("range"); + if( it != cArr->end() ){ + tPtr->ra = atof( it->second.c_str() ); + }; + it = cArr->find("area"); + if( it != cArr->end() ){ + tPtr->area = atof( it->second.c_str() ); + }; + it = cArr->find("lat"); + if( it != cArr->end() ){ + tPtr->lat = atof( it->second.c_str() ); + }; + it = cArr->find("lon"); + if( it != cArr->end() ){ + tPtr->lon = atof( it->second.c_str() ); + }; + it = cArr->find("alt"); + if( it != cArr->end() ){ + tPtr->alt = atof( it->second.c_str() ); + }; + it = cArr->find("ref_id"); + if( it != cArr->end() ){ + tPtr->ref_id = atoi( it->second.c_str() ); + }; + it = cArr->find("ref_uuid"); + if( it != cArr->end() ){ + strncpy( tPtr->ref_uuid, it->second.c_str(),64 ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tPtr; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/MySQL_dataBinder.h b/lib/App/common/MySQL_dataBinder.h new file mode 100644 index 00000000..3b457d86 --- /dev/null +++ b/lib/App/common/MySQL_dataBinder.h @@ -0,0 +1,198 @@ +#ifndef __MYSQL_DATA_BINDER_HEADER__ +#define __MYSQL_DATA_BINDER_HEADER__ + +#include "dataBinder.h" +#include "../../data/mysql/mysql_class.h" +#include "../../components/base/basicSettingsProvider.h" +#include "../../alg/generic/md5.h" +#include "../../alg/lgs/mask.h" + + +class mysqlDBC: public dataBinder { + private: + basicLogCollection * m_pLog; + config_setting_t * m_pSettings; + MySQL_Connector * m_pDatabase; + bool m_bIsConnected; + bool m_bIsServerLocal; + char m_pDbHost[CLOG]; + char m_pDbUsername[CLOG]; + char m_pDbPassword[CLOG]; + char m_pDbDatabase[CLOG]; + uint32_t m_nSiteID; + uint32_t m_nServerID; + uint32_t m_nServerNodeID; + + static mysqlDBC * _instance; + explicit mysqlDBC( config_setting_t * Settings = NULL ); + public: + static mysqlDBC * getInstance( config_setting_t * Settings = NULL ); + virtual ~mysqlDBC(); + /* Functionality */ + bool connect( void ); + bool isLocal( void ) const { return m_bIsServerLocal; }; + + //SET GLOBAL tmp_table_size = 1024 * 1024 * 1024 * 2; + //SET GLOBAL max_heap_table_size = 1024 * 1024 * 1024 * 2; + //SELECT @@max_heap_table_size; + //SHOW VARIABLES LIKE 'max_heap_table_size'; + + + + + + uint32_t addEvent( uint32_t SRC, CSTR UUID, uint32_t tss, uint32_t tsms, uint8_t evt_type, uint8_t k_id=0, uint16_t dig_r=0, float EL=.0f, float AZ=.0f, float RANGE=.0f, float AREA=.0f, float lat=.0f, float lon=.0f, float alt=.0f, uint32_t RefID=0, CSTR RefUUID=NULL ); + bool addDeviceDraw( uint32_t DBID, uint8_t type, uint8_t lrf, void *th_data, uint32_t th_size ); + + bool addLRFDraw( uint32_t DBID, uint32_t SIZE, CSTR ID, uint8_t kID =0, uint8_t type = 0, bool rendered = false ); + uint32_t addLRFMask( uint32_t devID, uint8_t lrfID = 0, uint8_t layerID = 0 ); + uint32_t addLRFMaskPolygone( uint32_t maskID, uint8_t r, uint8_t g, uint8_t b ); + bool addLRFMaskPolygonePoint( uint32_t polyID, int16_t x, int16_t y ); + + bool addIPCam( OBSERVER_RESULT *tPtr ); + uint32_t addLocalMediaSource( uint32_t SiteID, CSTR path, uint32_t width, uint32_t height ); + uint32_t addLocalDCB( uint32_t SiteID, CSTR PATH, CSTR SERIAL, uint8_t CNT, uint32_t status ); + uint32_t addLocalUART( /*uint32_t NodeID,*/ uint8_t utype, uint32_t speed, uint8_t bit, char parity, float stop_bit, CSTR PATH, uint8_t mode=0, uint16_t port=0 ); + uint32_t addLocalNIF( CSTR device, CSTR mac, NIF_TYPE dtype, NIF_MODE dmode, uint32_t aux_id = 0 ); + uint32_t addLocalNetwork( uint32_t NIF_ID, NETWORK_TYPE net_type, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ); + uint32_t addLocalNetworkInfrastructure( uint32_t NIF_ID, uint32_t OUTBOUND_NIF, bool ena_dhcp=false, CSTR BRANG=NULL, CSTR ERANG=NULL, CSTR MASK=NULL, CSTR LEASE_TIME=NULL ); + uint32_t addLocalWiFi( uint32_t NIF_ID, WIFI_MODE mode, CSTR SSID, CSTR password, WIFI_ENCRIPTION encryption, uint32_t router_id=0 ); + bool addNotification( uint32_t MSG_ID, uint8_t DIS_LVL = 0, uint32_t OBJ_ID=0 ); + bool addPicture( DBC_SNAPSHOT_DATA *ptr, CSTR ext ); + + //bool addPictureEvent( uint32_t evtID, uint32_t pictureoID ); + virtual uint32_t addResource( uint8_t type, CSTR devName, uint32_t auxID = 0 ); + //uint32_t addResource( uint32_t NodeID, uint8_t type, CSTR devName, uint32_t auxID = 0 ); + //uint32_t addUploadFile( uint32_t NodeID, CSTR uid, CSTR fileName ); + + bool addVideoEvent( uint32_t evtID, uint32_t videoID, uint32_t clen ); + uint32_t addVideoRecord( uint32_t streamID, CSTR md5, CSTR ext, uint32_t ts, uint32_t tsms, uint32_t fps ); + + bool cleanResources( bool all = false ); + bool cleanLRFMask( uint32_t maskID, bool deleteMask = false ); + bool cleanNodeEvents( uint32_t NodeID, bool all = false ); + bool cleanEvents2PictureBinding( uint32_t PicID ); + bool cleanEvents2VideoBinding( uint32_t PicID ); + + + void lazyEventArchiver( uint32_t DalayTime = 10 ); + DBC_INT_LIST * listCamMediaStreams( uint32_t CAMID ); + DBC_INT_LIST * listStreamCapPictures( uint32_t StreamID, uint32_t cnt ); + DBC_INT_LIST * listDetectionProfileIDs( uint32_t nodeID ); + DBC_INT_LIST * listDetectionProfiles( uint32_t nodeID ); + DBC_INT_LIST * listFilters( uint32_t ServerID ); + DBC_INT_LIST * listLRFMaskVertexes( uint32_t MaskID ); + DBC_INT_LIST * listLRFMaskVertexPoints( uint32_t VertexID ); + DBC_INT_LIST * listMediaServerStreams( uint32_t SiteId, uint32_t MediaServerID, uint8_t listingType = LIST_ALL_RECORDS ); + DBC_INT_LIST * listMediaStreams( uint32_t SiteId, uint8_t listingType = LIST_ALL_RECORDS ); + DBC_INT_LIST * listModules(); + DBC_INT_LIST * listNetworks( uint32_t nif_id ); + DBC_INT_LIST * listNewModules( DBC_INT_LIST * old_ids ); + + DBC_INT_LIST * listNewNodes( uint32_t SiteID, uint32_t ServerID, DBC_INT_LIST * old_ids ); + DBC_INT_LIST * listNodes( uint32_t SiteID, uint32_t ServerID, bool all = false ); + //DBC_INT_LIST * listSockets( uint32_t NodeID ); + DBC_INT_LIST * listResources( uint32_t NodeID = 0 ); + simplePolygone * loadLRFMaskVertex( uint32_t vid ); + + bool getAllCamRecords( uint32_t SiteID, vectorCamRecords &VR ); + DBC_APF_DATA * getAPFData( uint32_t APFID ); + DBC_CAM_DATA * getCamData( uint32_t CamID ); + uint32_t getCamId( CSTR UUID ); + + bool getConnectionStatus(void){return m_bIsConnected;}; + DBC_CAP_DATA * getCamCapPictureData( uint32_t PicID ); + DBC_EVT_RECORD * getEventByUUID( CSTR UUID ); + DBC_MODULE_EMBED_VIDEO_DATA * getEmbedVideoData( uint32_t ID ); + DBC_FH_DATA * getFlyHunterData( uint32_t ID ); + //int getIPCamCount( uint32_t SiteID ); + KAFKA_TEMPLATE * getKafkaTemplateForEvent( uint32_t ModuleID, uint32_t ClassID, uint32_t EventID ); + //bool getLastEvents( vectorEventRecords &VR, uint32_t tss, uint32_t tsms ); + DBC_LRF_DATA * getLRFData( uint32_t ID ); + uint8_t getLRFDataStatus( uint32_t ID ); + PLGS_2D_PARAMETERS getLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master ); + CSTR getLRFDraw( uint32_t DBID ); + uint32_t getLRFMaskID( uint32_t deviceID, uint8_t lrfID = 0, uint8_t layer = 0 ); + DBC_MEDIA_STREAM_DATA * getMediaStreamData( uint32_t ID ); + DBC_MEDIA_SERVER_DATA * getMediaServerData( uint32_t ID ); + DBC_MEDIA_SERVER_STREAM_DATA * getMediaServerStreamData( uint32_t ID ); + DBC_MEDIA_SERVER_STREAM_DATA * getMediaServerStreamDataBySource( uint32_t ID ); + DBC_MODULE_DATA * getModuleData( uint32_t ID ); + CSTR getNodeName( uint32_t NodeID ); + uint32_t getNodeAuxParam( uint32_t NodeID ); + uint32_t getNodeAuxID( uint32_t NodeID ); + DBC_NETWORK_DATA * getNetworkData( uint32_t net_id ); + uint32_t getNetworkInfrastructureID( uint32_t nif_id ); + DBC_NET_IF_DATA * getNIF_Data( uint32_t ID ); + uint32_t getNIF_ID( CSTR key ); + uint32_t getNIF_IDbyDevice( CSTR device ); + DBC_NODE_DATA * getNodeData( uint32_t ID ); + + DBC_PUSHED_CMD * getNodePushedCMD( uint32_t NodeID ); + DBC_PUSHED_CMD * getActivePushedCMD( uint32_t NodeID ); + DBC_PUSHED_CMD * getPushedCMD( uint32_t CmdID ); + + //uint32_t getNodeSocketID( uint32_t NodeID, uint32_t auxID, uint8_t SocketType, CSTR path ); + DBC_RESOURCE_DATA * getResourceData( uint32_t ResourceID ); + uint32_t getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID ); + uint32_t getServerID( CSTR identity ); + uint32_t getServerNode( uint32_t SID ); + KAFKA_SETTINGS * getSettingsKAFKA( uint32_t NodeID ); + DBC_SITE_DATA * getSiteData( uint32_t ID ); + //DBC_SOCKET_DATA * getSocketData( uint32_t ID ); + DBC_TARGET_FLITER_DATA * getTargetFilterData( uint32_t ID ); + DBC_UART_DATA * getUartData( uint32_t UartID ); + uint32_t getUartID( uint32_t NodeID, uint8_t Type, CSTR path ); + uint32_t getWiFi_ID( uint32_t nif_id ); + bool fillShadow2D( uint32_t ID, SHADOW & SH ); + + void deleteCamCapPicture( uint32_t PicID ); + void deleteNode( uint32_t NodeID ); + void deleteCamera( uint32_t CamID ); + void deleteConnections( uint32_t NodeID ); + void deleteNodeEvents( uint32_t NodeID ); + void deleteMediaStream( uint32_t MediaID ); + void deleteNIF( uint32_t NifID ); + void deleteNIS( uint32_t NisID ); + void deleteResource( uint32_t ResourceID ); + void deleteSensor( uint32_t SensorID ); + void deleteUART( uint32_t UARTID ); + + //void finalizeVideoRecord( uint32_t videoID, uint32_t clen ); + + void registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_t *ServID, uint32_t *ServNode ); + void unregisterServer(); + + bool transferEvtToArchive( uint32_t SECONDS = ONE_DAY_HISTORY ); + + + + bool setNodeOnline( uint32_t NodeID, uint8_t status=NODE_STATUS_WORK ); + bool setNodeOffline( uint32_t NodeID ); + //bool setOnlineStatus( bool Status ); + bool setLRFDetectionProfile( uint32_t lrfID, uint8_t profileID ); + bool setLRFDataStatus( uint32_t lrfID, uint8_t ST ); + bool setLRFAltSerial( uint32_t lrfID, CSTR Serial ); + bool setLRFAltVerison( uint32_t lrfID, CSTR version ); + bool setLRFMaskStatus( uint32_t maskID, bool status ); + bool setStreamValid( uint32_t streamID, bool status = true ); + //bool syncEventArchive( void ); ALTER TABLE table_name AUTO_INCREMENT = start_value; + bool update3DRuntimeStatus( uint32_t lrfID, ALG_RUN_STATUS *ptr ); + bool updateAFPBox( uint32_t filterID, CSTR Tag, float x, float y, float z ); + bool updateCamRange( uint32_t camID, float range ); + bool updateIPCam( CSTR uuid, CSTR Addr ); + bool updateIPCam( uint32_t CamID, CSTR Addr ); + bool updateLRFSerial( uint32_t lrfID, CSTR Serial ); + bool updateLRFVerison( uint32_t lrfID, CSTR version ); + bool updateLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master, uint16_t nOrder, uint16_t nOffset, uint16_t nDelta, uint16_t nWidth, uint16_t nFlip, uint16_t nSun, uint8_t bSST, uint32_t GP=0, uint32_t spikes=0 ); + bool updateMediaServerStream( uint32_t id, CSTR mrl=NULL, CSTR key = NULL ); + //bool updateNetworkNode( bool OnlineStatus ); + bool updateNodePushedCMD( uint32_t CmdID, uint8_t status ); + bool updateResourceAUX( uint32_t ResID, uint32_t AUX ); + //bool updateServerUtilisation( uint32_t ServerID, uint32_t nCores, float cpu1, float cpu5, float cpu15, float mem, float disk, uint64_t dtsize, uint64_t dcsize, uint64_t mtsize, uint64_t mcsize ); + virtual bool updateServerUtilisation( DBC_SYS_LOAD_INFO *ptr ); +}; + + + +#endif \ No newline at end of file diff --git a/lib/App/common/SQLite_dataBinder.cpp b/lib/App/common/SQLite_dataBinder.cpp new file mode 100644 index 00000000..ccf6c02d --- /dev/null +++ b/lib/App/common/SQLite_dataBinder.cpp @@ -0,0 +1,1305 @@ +#include "SQLite_dataBinder.h" + +#define LOG( X ) m_pLog->Log( "SDBC", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "SDBC", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "SDBC", this, _LOG_ERROR, X ); +#endif + +sqliteDBC *sqliteDBC::_instance = NULL; + +/** + * Returns the single instance of the object. + */ +sqliteDBC *sqliteDBC::getInstance( config_setting_t * Settings ) { + // check if the instance has been created yet + if( 0 == _instance ){ + // if not, then create it + _instance = new sqliteDBC( Settings ); + }; + // return the single instance + return _instance; +}; + + +sqliteDBC::sqliteDBC( config_setting_t * Settings ):dataBinder(){ + m_pLog = basicLogCollection::getInstance(); + m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "DATABASE" ); + m_bIsConnected = false; + m_pDataStorage = NULL; + m_pDataMemory = NULL; + m_nServerID = 1; +}; + +sqliteDBC::~sqliteDBC(){ + if ( m_pDataStorage ) delete( m_pDataStorage ); + if ( m_pDataMemory ) delete( m_pDataMemory ); + _instance = NULL; +}; + +bool sqliteDBC::connect( void ){ + if ( m_pSettings == NULL) return false; + bool bRecreateMemStructures = false; + config_setting_t * pSetting; + const char * tBuff; + //Disconnect if Connected + m_bIsConnected = false; + char web_access_user[64]; + char web_access_group[64]; + + //Apply New Config +#ifdef DEBUG + LOG( "Reading DB Settings ... " ); +#endif + if(!config_setting_lookup_string(m_pSettings, "DATA_FILE_NAME", (const char**)&tBuff )){ + pSetting = config_setting_add(m_pSettings, "DATA_FILE_NAME", CONFIG_TYPE_STRING); + sprintf( m_pDbFile, "data/mysqlitedb.db" ); + config_setting_set_string( pSetting, m_pDbFile ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Data Storage not set - using default"); + } else { + sprintf( m_pDbFile, tBuff ); + }; + if(!config_setting_lookup_string(m_pSettings, "WEB_ACCESS_USER", (const char**)&tBuff )){ + pSetting = config_setting_add(m_pSettings, "WEB_ACCESS_USER", CONFIG_TYPE_STRING); + sprintf( web_access_user, "www-data" ); + config_setting_set_string( pSetting, web_access_user ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Web Access User not set - using default"); + } else { + sprintf( web_access_user, tBuff ); + }; + if(!config_setting_lookup_string(m_pSettings, "WEB_ACCESS_GROUP", (const char**)&tBuff )){ + pSetting = config_setting_add(m_pSettings, "WEB_ACCESS_GROUP", CONFIG_TYPE_STRING); + sprintf( web_access_group, "www-data" ); + config_setting_set_string( pSetting, web_access_group ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Web Access Group not set - using default"); + } else { + sprintf( web_access_group, tBuff ); + }; + if( !fileExist( DB_SHMEM_POINT )) { + bRecreateMemStructures = true; + mkdir( DB_SHMEM_POINT, 0775 );// S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH ); + chown( DB_SHMEM_POINT, web_access_user, web_access_group ); //To make Accessed from PHP + chmod( DB_SHMEM_POINT, 0775 ); + }; + char tB[128]; + if (!config_setting_lookup_string(m_pSettings, "DATA_MEMORY_NAME", (const char **)&tBuff)) { + pSetting = config_setting_add(m_pSettings, "DATA_MEMORY_NAME", CONFIG_TYPE_STRING); + tBuff = tB; + sprintf( tB, "mem_db.db" ); + config_setting_set_string( pSetting, tB ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Memory Storage not set - using default"); + }; + sprintf( m_pDbMemory, "%s/%s", DB_SHMEM_POINT, tBuff ); + basicSettingsProvider::getInstance()->validate(); + + // Kill Connection if any + if ( m_pDataStorage ) delete( m_pDataStorage ); + if ( m_pDataMemory ) delete( m_pDataMemory ); + +#ifdef DEBUG + LOG( m_pDbFile ); +#endif + // Create New Connections + m_pDataStorage = new SQLite_Connector(); + if ( m_pDataStorage ) { + if( m_pDataStorage->Connect( m_pDbFile, 0, true ) ){ +#ifdef DEBUG + LOG("DB File Opened"); +#endif + chown( m_pDbFile, web_access_user, web_access_group ); + chmod( m_pDbFile, 0664 ); + } else{ + LOG_ERROR("Cannot Connect to DB File"); + delete( m_pDataStorage ); + m_pDataStorage = NULL; + LOG("Storage Deleted!"); + return false; + }; + }; +#ifdef DEBUG + LOG( m_pDbMemory ); +#endif + if( !fileExist( m_pDbMemory )) { + bRecreateMemStructures = true; + //Always recreate + //unlink( m_pDbMemory ); + }; + m_pDataMemory = new SQLite_Connector(); + if ( m_pDataMemory ) { + + if( m_pDataMemory->Connect( m_pDbMemory, 0, true ) ){ +#ifdef DEBUG + LOG("DB Memory Opened"); +#endif + chown( m_pDbMemory, web_access_user, web_access_group ); + chmod( m_pDbMemory, 0664 ); + //Recreate at Register Server + //if ( bRecreateMemStructures ) initMemDB(); + } else{ + LOG_ERROR("Cannot Connect to DB Memory"); + delete( m_pDataStorage ); + delete( m_pDataMemory ); + m_pDataStorage = NULL; + m_pDataMemory = NULL; + return false; + }; + }; + m_bIsConnected = true; + return m_bIsConnected; +}; + +void sqliteDBC::initMemDB( uint32_t sid ){ +m_pDataMemory->Query("DROP TABLE \"nodes_qcq\""); +m_pDataMemory->Query("CREATE TABLE \"nodes_qcq\" ( \ + \"id\" INTEGER NOT NULL,\ + \"node_id\" INTEGER NOT NULL,\ + \"cmd\" INTEGER NOT NULL,\ + \"status\" INTEGER DEFAULT 0,\ + \"parameter\" TEXT,\ + PRIMARY KEY(\"id\" AUTOINCREMENT)\ +);"); +m_pDataMemory->Query("DROP TABLE \"servers\""); +m_pDataMemory->Query("CREATE TABLE \"servers\" (\ +\"id\" INTEGER NOT NULL,\ + \"ts\" INTEGER DEFAULT 0,\ + \"pid\" INTEGER DEFAULT 0,\ + \"hw_info\" TEXT,\ + \"os_info\" TEXT,\ + \"cpu_cores\" INTEGER DEFAULT 0.0,\ + \"stat_cpu1\" REAL DEFAULT 0.0,\ + \"stat_cpu5\" REAL DEFAULT 0.0,\ + \"stat_cpu15\" REAL DEFAULT 0.0,\ + \"stat_mem\" REAL DEFAULT 0.0,\ + \"stat_disk\" REAL DEFAULT 0.0,\ + \"val_mem_tottal\" INTEGER DEFAULT 0,\ + \"val_mem_current\" INTEGER DEFAULT 0,\ + \"val_disk_tottal\" INTEGER DEFAULT 0,\ + \"val_disk_current\" INTEGER DEFAULT 0,\ + \"temp0\" REAL DEFAULT 0.0,\ + PRIMARY KEY(\"id\" AUTOINCREMENT)\ +);"); +char tB[128]; +sprintf( tB, "INSERT INTO `servers` (`id`,`ts`) VALUES (%d, strftime('%%s') )", sid ); +m_pDataMemory->Query( tB ); + +}; + + +DBC_PUSHED_CMD *sqliteDBC::getNodePushedCMD( uint32_t NodeID ){ + DBC_PUSHED_CMD * RetVal = NULL; + if ( m_bIsConnected ) { + char QS[MAX_PATH]; + AAssoc * result; + sprintf( QS, "select * FROM `nodes_qcq` WHERE `node_id`=%d AND `status`=0 ORDER BY `id` LIMIT 1", NodeID ); + result = m_pDataMemory->Query( QS ); + if ( result ) { + if( result->size() > 0 ) { + RetVal = (DBC_PUSHED_CMD*)malloc(sizeof(DBC_PUSHED_CMD)); + if( RetVal ) { + Assoc * cArr; + Assoc::iterator it; + + memset( RetVal, 0, sizeof(DBC_PUSHED_CMD)); + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal->id = atoi( it->second.c_str() ); + }; + it = cArr->find("cmd"); + if( it != cArr->end() ){ + RetVal->CMD = atoi( it->second.c_str() ); + }; + it = cArr->find("parameter"); + if( it != cArr->end() ){ + strncpy( RetVal->PARAM, it->second.c_str(), 256 ); + RetVal->PARAM[255] = (char)0; + }; + }; + }; + }; + m_pDataMemory->deleteResult( result ); + }; + return RetVal; +}; + +bool sqliteDBC::updateIPCam( uint32_t CamID, CSTR Addr ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + char tIpBuf[CTEXT]; + char *tPos; + char *tPos2; + + tPos = strstr(Addr,"//"); + if( tPos != NULL ) { + tPos2 = strstr( tPos + 2,"/"); + if( tPos2 != NULL ) { + int len; + len = tPos2 - tPos - 2; + strncpy(tIpBuf,tPos + 2,len); + tIpBuf[len] = (char)0; + } else { + LOG_ERROR("Pos 2 - err"); + tIpBuf[0] = (char)0; + }; + } else { + LOG_ERROR("Pos 0 - err"); + tIpBuf[0] = (char)0; + }; + sprintf(tQBuf,"UPDATE cameras SET `online`=1, `onvif_ctrl`='%s', `ip`='%s' WHERE `id`=%d", + Addr, + tIpBuf, + CamID + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + sprintf(tQBuf,"UPDATE `media_streams` SET `valid`=1 WHERE `source_id`=%d", CamID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool sqliteDBC::updateIPCam( CSTR uuid, CSTR Addr ){ + if(m_bIsConnected) { + uint32_t cID = getCamId( uuid ); + if ( cID ) { + return updateIPCam( cID, Addr ); + }; + }; + return false; +}; + +bool sqliteDBC::updateLocalCam( CSTR uuid ){ + if(m_bIsConnected) { + uint32_t cID = getCamId( uuid ); + if ( cID ) { + return updateLocalCam( cID ); + }; + }; + return false; +}; + +bool sqliteDBC::updateLocalCam( uint32_t CamID ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + sprintf(tQBuf,"UPDATE cameras SET `online`=1 WHERE `id`=%d", CamID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + sprintf(tQBuf,"UPDATE `media_streams` SET `valid`=1 WHERE `source_id`=%d", CamID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +bool sqliteDBC::updateNodePushedCMD( uint32_t CmdID, uint8_t status ){ + if ( m_bIsConnected ) { + char QS[MAX_PATH]; + sprintf( QS, "UPDATE `nodes_qcq` SET `status`=%d WHERE `id`=%d ", status, CmdID ); + return m_pDataMemory->SilentQuery( QS ); + }; + return false; +}; + +bool sqliteDBC::cleanNodePushedCMD( void ){ + if ( m_bIsConnected ) { + return m_pDataMemory->SilentQuery( "DELETE FROM `nodes_qcq` WHERE `status` > 200" ); + }; + return false; +}; + +bool sqliteDBC::updateServerUtilisation( DBC_SYS_LOAD_INFO *ptr ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf(tQBuf, "UPDATE `servers` SET `ts`=STRFTIME('%%s'), `cpu_cores`=%d, `stat_cpu1`=%0.1f, `stat_cpu5`=%0.1f, `stat_cpu15`=%0.1f, `stat_mem`=%0.1f, `stat_disk`=%0.1f, `temp0`=%0.1f, `val_mem_tottal`=%" PRIu64 ", `val_mem_current`=%" PRIu64 ", `val_disk_tottal`=%" PRIu64 ", `val_disk_current`=%" PRIu64 " WHERE `id`=%d", + ptr->CPU_CORES, + ptr->cpu1, + ptr->cpu5, + ptr->cpu15, + ptr->mem, + ptr->disk, + ptr->temperature, + ptr->T_DISK, + ptr->C_DISK, + ptr->T_MEM, + ptr->C_MEM, + m_nServerID + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataMemory->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + + +/******************************************************************** + * * + * Slow DB Functions * + * * + ********************************************************************/ +bool sqliteDBC::addDeviceDraw( uint32_t DBID, uint8_t type, uint8_t lrf, void *th_data, uint32_t th_size ){ + return false; +}; + +bool sqliteDBC::addIPCam( OBSERVER_RESULT *tPtr ){ + if(m_bIsConnected) { + char tQBuf[1024]; + char tIpBuf[32]; + char tProto[32]; + char tPath[CTEXT]; + char *tPos; + char *tPos2; + memcpy( tProto, tPtr->XAddrs, 5 ); + tProto[5] = (char)0; + if( tProto[4] == ':') tProto[4] = (char)0; + memset( tPath, 0, CTEXT ); + tPos = strstr(tPtr->XAddrs,"//"); + if( tPos != NULL ) { + tPos2 = strstr( tPos + 2,"/"); + if( tPos2 != NULL ) { + int len,len2,len3; + len = tPos2 - tPos - 2; + strncpy( tIpBuf, tPos + 2, len); + tIpBuf[len] = (char)0; + strncpy( tPath, tPos + 2 + len, CTEXT ); + } else { + LOG_ERROR("Pos 2 - err"); + tIpBuf[0] = (char)0; + }; + } else { + LOG_ERROR("Pos 0 - err"); + tIpBuf[0] = (char)0; + }; + sprintf(tQBuf,"INSERT INTO cameras (`online`,`uuid`,`onvif_ctrl`,`ip`,`type`,`status`,`mac`,`hardware`,`name`,`onvif_access`) VALUES (1,'%s','%s','%s',2,0,'%s','%s','%s','%s') ON CONFLICT(`uuid`) DO UPDATE SET `online`=1, `ip`='%s'", + tPtr->RefID, + //tPtr->XAddrs, + tPath, + tIpBuf, + tPtr->MAC, + tPtr->Hardware, + tPtr->Name, + tProto, + //tPtr->XAddrs, + tIpBuf + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +uint32_t sqliteDBC::addLocalCam( CSTR name, CSTR hardware, CSTR path, uint32_t width, uint32_t height ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[1024]; + char tM5[33]; + + CSTR tMD5 = MD5String( path ); + if( tMD5 != NULL ) { + memcpy( tM5, tMD5, 33 ); + tM5[32]=(char)0; + free( tMD5 ); + + sprintf(tQBuf,"INSERT INTO cameras (`online`,`uuid`,`type`,`status`,`hardware`,`name`,`ip`) VALUES (1,'%s',0,0,'%s','%s','%s') ON CONFLICT(`uuid`) DO UPDATE SET `online`=1", + tM5, + hardware, + name, + path + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + uint32_t camID = (uint32_t) m_pDataStorage->QueryID( tQBuf ); + if ( camID == 0 ) { + camID = getCamId( tM5 ); + }; + sprintf(tQBuf, "INSERT INTO `media_streams`(`source_id`,`source_type`,`valid`,`name`,`token`,`img_width`,`img_height`,`mrl_proto`,`mrl`,`picture_proto`) VALUES(%d,'A',1,'%s','%s',%d,%d,'v4l2','%s','v4l2') ON CONFLICT(`source_id`,`token`) DO UPDATE SET `valid`=1, img_width=%d, img_height=%d", + camID, name, tM5, width, height, path, width, height ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + RetVal = (uint32_t) m_pDataStorage->QueryID( tQBuf ); + if( RetVal == 0 ){ + RetVal = getMediaStreamID( camID, tM5 ); + }; + }; + }; + return RetVal; +}; + +uint32_t sqliteDBC::addLocalNetwork( uint32_t NIF_ID, NETWORK_TYPE net_type, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `networks`(`nif_id`,`type`,`address`,`gateway`,`mask`,`broadcast`) VALUES (%d,%d,'%s','%s','%s','%s') ON CONFLICT(`nif_id`,`type`) DO UPDATE SET `address`='%s', `gateway`='%s', `mask`='%s', `broadcast`='%s'", + NIF_ID, + net_type, + address, + gateway, + mask, + broadcast, + address, + gateway, + mask, + broadcast + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = m_pDataStorage->QueryID( tQBuf ); + // On Update IF data no need to return ID + //if( RetVal == 0 ) { + // RetVal = getNetworkInterfaceID( tKey ); + //}; + }; + return RetVal; +}; + +uint32_t sqliteDBC::addLocalNetworkInfrastructure( uint32_t NIF_ID, uint32_t OUTBOUND_NIF, bool ena_dhcp, CSTR BRANG, CSTR ERANG, CSTR MASK, CSTR LEASE_TIME ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + bool ena_routing = true; + if( OUTBOUND_NIF == 0 ){ + ena_routing = false; + }; + if( ena_dhcp ){ + if ( BRANG == NULL || ERANG == NULL || MASK == NULL || LEASE_TIME == NULL ) { + LOG_ERROR("Wrong DHCP parameters to create Network Infrastructure!"); + return 0; + }; + sprintf(tQBuf, "INSERT INTO `network_infrastructure`(`nif_id`,`enable_routing`,`outbond_nif`,`enable_dhcp`,`dhcp_range_begin`,`dhcp_range_end`,`dhcp_range_mask`,`dhcp_lease_time`) VALUES (%d,%d,%d,1,'%s','%s','%s','%s') ON CONFLICT(`nif_id`) DO UPDATE SET `enable_routing`=%d, `outbond_nif`=%d, `enable_dhcp`=1, `dhcp_range_begin`='%s', `dhcp_range_end`='%s', `dhcp_range_mask`='%s', `dhcp_lease_time`='%s'", + NIF_ID, + ena_routing, + OUTBOUND_NIF, + BRANG, + ERANG, + MASK, + LEASE_TIME, + ena_routing, + OUTBOUND_NIF, + BRANG, + ERANG, + MASK, + LEASE_TIME + ); + } else { + if( ena_routing ){ + sprintf(tQBuf, "INSERT INTO `network_infrastructure`(`nif_id`,`enable_routing`,`outbond_nif`) VALUES(%d,1,%d) ON CONFLICT(`nif_id`) DO UPDATE SET `enable_routing`=1, `outbond_nif`=%d", + NIF_ID, + OUTBOUND_NIF, + OUTBOUND_NIF + ); + } else { + LOG_ERROR("No Special Service Defined To Network Infrastructure!"); + return 0; + }; + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = m_pDataStorage->QueryID( tQBuf ); + // On Update IF data no need to return ID + if( RetVal == 0 ) { + RetVal = getNetworkInfrastructureID( NIF_ID ); + }; + }; + return RetVal; +}; + +uint32_t sqliteDBC::addLocalNIF( CSTR device, CSTR mac, NIF_TYPE dtype, NIF_MODE dmode, uint32_t aux_id ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + char * tKey = MD5String( device ); + if( tKey != NULL ) { + sprintf( tQBuf, "INSERT INTO `network_interfaces` (`type`,`key`,`device_name`,`mac`,`mode`,`aux_id`) VALUES (%d,'%s','%s','%s',%d,%d) ON CONFLICT(`key`) DO UPDATE SET `mode`=%d,`aux_id`=%d,`mac`='%s'", + dtype, + tKey, + device, + mac, + dmode, + aux_id, + dmode, + aux_id, + mac + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = m_pDataStorage->QueryID( tQBuf ); + if( RetVal == 0 ) { + RetVal = getNIF_ID( tKey ); + }; + free( tKey ); + }; + }; + return RetVal; +}; + +uint32_t sqliteDBC::addLocalUART( uint8_t utype, uint32_t speed, uint8_t bit, char parity, float stop_bit, CSTR PATH, uint8_t mode, uint16_t port ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `uart_settings`(`node_id`,`type`,`speed`,`bit`,`parity`,`stop_bit`,`mode`,`port`,`path`) VALUES (%d,%d,%d,%d,'%c',%.1f,%d,%d,'%s') ON CONFLICT(`node_id`,`type`,`path`) DO UPDATE SET `id`=`id`", + m_nServerNodeID, + utype, + speed, + bit, + parity, + stop_bit, + mode, + port, + PATH + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = m_pDataStorage->QueryID( tQBuf ); + if( RetVal == 0 ) { + RetVal = getUartID( m_nServerNodeID, utype, PATH ); + }; + }; + return RetVal; +}; + +uint32_t sqliteDBC::addLocalWiFi( uint32_t NIF_ID, WIFI_MODE mode, CSTR SSID, CSTR password, WIFI_ENCRIPTION encryption, uint32_t router_id ){ + uint32_t RetVal = 0; + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `wifis` (`nif_id`,`mode`,`aux_id`,`SSID`,`password`,`encryption_type`) VALUES (%d,%d,%d,'%s','%s',%d) ON CONFLICT (`nif_id`) DO UPDATE SET `mode`=%d, `aux_id`=%d, `SSID`='%s', `password`='%s', `encryption_type`=%d", + NIF_ID, + mode, + router_id, + SSID, + password, + encryption, + mode, + router_id, + SSID, + password, + encryption + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = m_pDataStorage->QueryID( tQBuf ); + if( RetVal == 0 ) { + RetVal = getWiFi_ID( NIF_ID ); + }; + }; + return RetVal; +}; + +bool sqliteDBC::cleanResources( bool all ){ + if(m_bIsConnected) { + char tQBuf[MAX_PATH_LEN]; + if( all ) { + sprintf( tQBuf, "UPDATE `resources` SET `active`=0 WHERE `node_id`=%d", m_nServerNodeID ); + } else { + sprintf( tQBuf, "UPDATE `resources` SET `active`=0 WHERE ( `node_id`=%d ) AND ( `type`=100 OR `type`=101 OR `type`=103 OR `type`=120 )", m_nServerNodeID ); + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +uint32_t sqliteDBC::addResource( uint8_t type, CSTR devName, uint32_t auxID ){ + uint32_t RetVal = 0; + if( m_bIsConnected ){ + char tQBuf[2048]; + sprintf( tQBuf, "%d:%d:%s", m_nServerNodeID, type, devName ); + CSTR tMD5 = MD5String( tQBuf ); + if( tMD5 ) { + sprintf( tQBuf, "INSERT INTO `resources`(`node_id`,`type`,`md5`,`aux_id`,`device`,`active`) VALUES (%d,%d,'%s',%d,'%s',1) ON CONFLICT(`md5`) DO UPDATE SET `active`=1, `aux_id`=%d", + m_nServerNodeID, + type, + tMD5, + auxID, + devName, + auxID + ); + free( tMD5 ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + RetVal = (uint32_t) m_pDataStorage->QueryID( tQBuf ); + if( RetVal == 0 ) { + RetVal = getResourceID( m_nServerNodeID, type, auxID ); + }; + }; + }; + return RetVal; +}; + +uint32_t sqliteDBC::getMediaStreamID( uint32_t source_id, CSTR token ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `media_streams` WHERE `source_id`=%d AND `token`='%s'", source_id, token ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +DBC_MODULE_DATA *sqliteDBC::getModuleData( uint32_t ID ){ + DBC_MODULE_DATA *tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT * FROM modules WHERE `id`=%d", ID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_MODULE_DATA*) malloc(sizeof(DBC_MODULE_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->module_id = atoi( it->second.c_str() ); + }; + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal->aux_id = atoi( it->second.c_str() ); + }; + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi( it->second.c_str() ); + }; + it = cArr->find("enabled"); + if( it != cArr->end() ){ + tVal->enabled = (bool)atoi( it->second.c_str() ); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_NET_IF_DATA *sqliteDBC::getNIF_Data( uint32_t nif_id ){ + DBC_NET_IF_DATA * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `type`, `mode`, `device_name`, `mac`, `aux_id` FROM `network_interfaces` WHERE `id`=%d", nif_id ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_NET_IF_DATA*) malloc(sizeof(DBC_NET_IF_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + tVal->id = nif_id; + cArr = result->at(0); + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi(it->second.c_str()); + }; + it = cArr->find("mode"); + if( it != cArr->end() ){ + tVal->mode = atoi(it->second.c_str()); + }; + it = cArr->find("device_name"); + if( it != cArr->end() ){ + strncpy( tVal->device_name, it->second.c_str(),11); + tVal->device_name[10]=(char)0; + }; + it = cArr->find("mac"); + if( it != cArr->end() ){ + strncpy( tVal->mac, it->second.c_str(), 33 ); + tVal->mac[32]=(char)0; + }; + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal->aux_id = atoi(it->second.c_str()); + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t sqliteDBC::getNIF_ID( CSTR key ){ + uint32_t tVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT id FROM `network_interfaces` WHERE `key`='%s'", key ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; +uint32_t sqliteDBC::getNIF_IDbyDevice( CSTR device ){ + uint32_t tVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT id FROM `network_interfaces` WHERE `device_name`='%s'", device ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t sqliteDBC::getNetworkInfrastructureID( uint32_t nif_id ){ + uint32_t tVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT id FROM `network_infrastructure` WHERE `nif_id`=%d", nif_id ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_RESOURCE_DATA *sqliteDBC::getResourceData( uint32_t ResourceID ){ + DBC_RESOURCE_DATA *tVal = NULL; + if( m_bIsConnected ){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `node_id`, `type`, `aux_id`, `device` FROM `resources` WHERE `id`=%d", ResourceID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = (DBC_RESOURCE_DATA*) malloc(sizeof(DBC_RESOURCE_DATA)); + if( tVal != NULL ) { + Assoc::iterator it; + cArr = result->at(0); + tVal->id = ResourceID; + it = cArr->find("node_id"); + if( it != cArr->end() ){ + tVal->node_id = atoi( it->second.c_str() ); + }; + it = cArr->find("type"); + if( it != cArr->end() ){ + tVal->type = atoi( it->second.c_str() ); + }; + it = cArr->find("aux_id"); + if( it != cArr->end() ){ + tVal->aux_id = atoi( it->second.c_str() ); + }; + it = cArr->find("device"); + if( it != cArr->end() ){ + strncpy( tVal->device, it->second.c_str(), 64 ); + tVal->device[63] = (char)0; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +uint32_t sqliteDBC::getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf(tQBuf,"SELECT `id` FROM `resources` WHERE `node_id`=%d AND `type`=%d AND `aux_id`=%d", NodeID, type, auxID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +uint32_t sqliteDBC::getServerID( CSTR identity ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf(tQBuf,"SELECT `id` FROM `servers` WHERE `identity`='%s'", identity ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +uint32_t sqliteDBC::getServerNode( uint32_t SID ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf(tQBuf,"SELECT id FROM nodes WHERE `type`=0 AND `aux_id`=%d", SID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +} + +uint32_t sqliteDBC::getUartID( uint32_t NodeID, uint8_t Type, CSTR path ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + sprintf(tQBuf,"SELECT `id` FROM `uart_settings` WHERE `node_id`=%d AND `type`=%d AND `path`='%s' ", NodeID, Type, path ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + AAssoc *result; + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +uint32_t sqliteDBC::getWiFi_ID( uint32_t nif_id ){ + uint32_t tVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `wifis` WHERE `nif_id`=%d", nif_id ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *sqliteDBC::listModules(){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + AAssoc *result; + result = m_pDataStorage->Query( "SELECT `id` FROM `modules` WHERE `enabled`=1" ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *sqliteDBC::listNewModules( DBC_INT_LIST * old_ids ){ + DBC_INT_LIST * tVal = NULL; + char tParam[CTEXT]; + //memset( tParam, 0, CTEXT ); + sprintf(tParam,"0"); + if( old_ids != NULL ) { + char tBuffer[CTEXT]; + for(int i = 0; i< old_ids->size(); i++ ) { + sprintf( tBuffer, "%s,%d", tParam, old_ids->at(i) ); + strncpy( tParam, tBuffer, CTEXT ); + }; + }; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `modules` WHERE `enabled`=1 AND `id` NOT IN (%s)", tParam ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +DBC_INT_LIST *sqliteDBC::listResources( uint32_t NodeID ){ + DBC_INT_LIST * tVal = NULL; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + if ( NodeID == 0 ) NodeID = m_nServerNodeID; + sprintf(tQBuf, "SELECT `id` FROM `resources` WHERE `node_id`=%d", NodeID ); +#ifdef DEBUG + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + tVal = new DBC_INT_LIST(); + if( tVal != NULL ) { + Assoc::iterator it; + for(int i=0;isize();i++) { + cArr = result->at(i); + it = cArr->find("id"); + if( it != cArr->end() ){ + tVal->push_back( atoi( it->second.c_str() )); + }; + }; + }; + }; + }; + deleteResult( result ); + }; + return tVal; +}; + +void sqliteDBC::registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_t *ServID, uint32_t *ServNode ){ + if( m_bIsConnected ){ + m_nSiteID = SiteID; + + char tQBuf[MAX_PATH_LEN]; + sprintf( tQBuf, "INSERT INTO `servers`(`site_id`,`identity`,`version_string`) VALUES (%d,'%s','%s') ON CONFLICT(`identity`) DO UPDATE SET `version_string`='%s'", + SiteID, identity, _BUILD_STRING_, _BUILD_STRING_ ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + + m_nServerID = getServerID( identity ); + *ServID = m_nServerID; + if( m_nServerID ) { + + //if ( bRecreateMemStructures ) + initMemDB( m_nServerID ); + sprintf( tQBuf, "UPDATE `servers` SET `pid`=%d,`ts`=STRFTIME('%%s') WHERE `id`=%d", PID, m_nServerID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataMemory->SilentQuery( tQBuf ); + + sprintf(tQBuf,"INSERT INTO `nodes`(`aux_id`,`type`,`online`,`name`) VALUES (%d, 0,1,'Controller') ON CONFLICT(`type`,`aux_id`) DO UPDATE SET `online`=1", *ServID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_nServerNodeID = ( uint32_t ) m_pDataStorage->QueryID( tQBuf ); + + if( m_nServerNodeID== 0 ){ + m_nServerNodeID = getServerNode( m_nServerID ); + }; + *ServNode = m_nServerNodeID; + // Clenup Nodes and services ... + sprintf(tQBuf,"UPDATE `nodes` SET `online`=0" ); + #ifdef DEBUG_ALL + LOG(tQBuf); + #endif + m_pDataStorage->SilentQuery( tQBuf ); + sprintf(tQBuf,"UPDATE `cameras` SET `online`=0" ); + #ifdef DEBUG_ALL + LOG(tQBuf); + #endif + m_pDataStorage->SilentQuery( tQBuf ); + + sprintf(tQBuf,"UPDATE `media_streams` SET `valid`=0" ); + #ifdef DEBUG_ALL + LOG(tQBuf); + #endif + m_pDataStorage->SilentQuery( tQBuf ); + + // sprintf(tQBuf,"UPDATE `media_server_streams` SET `valid`=0, `online`=0" ); + #ifdef DEBUG_ALL + // LOG(tQBuf); + #endif + // m_pDataStorage->SilentQuery( tQBuf ); + + //cleanResources( tServerNodeID ); + setNodeOnline( m_nServerNodeID ); + }; + }; +}; + +bool sqliteDBC::setNodeOffline( uint32_t NodeID ){ + if(m_bIsConnected){ + char tQBuf[CTEXT]; + if( NodeID ) { + sprintf(tQBuf,"UPDATE nodes SET `online`=0 WHERE `id` = %d", NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + sprintf(tQBuf,"UPDATE `resources` SET `active`=0 WHERE `node_id` = %d", NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + return true; + }; + }; + return false; +}; + +bool sqliteDBC::setNodeOnline( uint32_t NodeID, uint8_t status ){ + if(m_bIsConnected){ + char tQBuf[CTEXT]; + if( NodeID ) { + sprintf(tQBuf,"UPDATE nodes SET `online`=%d WHERE `id`=%d", status, NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + sprintf(tQBuf,"UPDATE `resources` SET `active`=1 WHERE `node_id`=%d", NodeID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + return true; + }; + }; + return false; +}; + +bool sqliteDBC::setStreamValid( uint32_t streamID, bool status ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + if ( status ) { + sprintf(tQBuf, "UPDATE `media_streams` SET `valid`=1 WHERE `id`=%d", streamID); + } else { + sprintf(tQBuf, "UPDATE `media_streams` SET `valid`=0 WHERE `id`=%d", streamID); + }; +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +void sqliteDBC::unregisterServer( void ){ + setNodeOffline( m_nServerNodeID ); +}; + +bool sqliteDBC::updateSystemInfo( DBC_SYS_INFO *ptr ){ + if( m_bIsConnected ) { + char tQBuf[MAX_PATH_LEN]; + sprintf(tQBuf, "UPDATE `system_props` SET `os_info`='%s', `hw_info`='%s' WHERE `id`=%d", + ptr->OS_INFO, + ptr->HW_INFO, + m_nSiteID + ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + m_pDataStorage->SilentQuery( tQBuf ); + return true; + }; + return false; +}; + +uint32_t sqliteDBC::getCamId( CSTR UUID ){ + uint32_t RetVal = 0; + if(m_bIsConnected){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `cameras` WHERE `uuid`='%s'", UUID ); +#ifdef DEBUG_ALL + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return RetVal; +}; + +CSTR sqliteDBC::getDataParam( uint8_t pid ){ + switch ( pid ) { + case 0: return strdup( m_pDbFile ); + }; + return NULL; +}; + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/common/SQLite_dataBinder.h b/lib/App/common/SQLite_dataBinder.h new file mode 100644 index 00000000..3680f069 --- /dev/null +++ b/lib/App/common/SQLite_dataBinder.h @@ -0,0 +1,88 @@ +#ifndef __SQLITE_DATA_BINDER_HEADER__ +#define __SQLITE_DATA_BINDER_HEADER__ + +#include "dataBinder.h" +#include "../data/sqlite/sqlite_class.h" +#include "../../components/base/basicSettingsProvider.h" +#include "../../alg/generic/md5.h" +#include "../../alg/lgs/mask.h" + + +#define DB_SHMEM_POINT "/dev/shm/argus" + + +class sqliteDBC: public dataBinder { + private: + basicLogCollection * m_pLog; + config_setting_t * m_pSettings; + SQLite_Connector * m_pDataStorage; + SQLite_Connector * m_pDataMemory; + bool m_bIsConnected; + bool m_bRecreateMemStructures; + char m_pDbFile[CLOG]; + char m_pDbMemory[CLOG]; + char m_pDbUsername[CLOG]; + char m_pDbPassword[CLOG]; + char m_pDbDatabase[CLOG]; + + uint32_t m_nSiteID; + uint32_t m_nServerID; + uint32_t m_nServerNodeID; + + void initMemDB( uint32_t sid = 1 ); + + static sqliteDBC * _instance; + explicit sqliteDBC( config_setting_t * Settings ); + public: + static sqliteDBC * getInstance( config_setting_t * Settings = NULL ); + virtual ~sqliteDBC(); + /* Functionality */ + bool connect( void ); + virtual bool cleanResources( bool all = false ); + virtual bool isLocal( void ) const { return true; }; + virtual bool addDeviceDraw( uint32_t DBID, uint8_t type, uint8_t lrf, void *th_data, uint32_t th_size ); + virtual bool addIPCam( OBSERVER_RESULT *tPtr ); + virtual uint32_t addLocalCam( CSTR name, CSTR hardware, CSTR path, uint32_t width, uint32_t height ); + virtual uint32_t addLocalNetwork( uint32_t NIF_ID, NETWORK_TYPE net_type, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ); + virtual uint32_t addLocalNetworkInfrastructure( uint32_t NIF_ID, uint32_t OUTBOUND_NIF, bool ena_dhcp=false, CSTR BRANG=NULL, CSTR ERANG=NULL, CSTR MASK=NULL, CSTR LEASE_TIME=NULL ); + virtual uint32_t addLocalNIF( CSTR device, CSTR mac, NIF_TYPE dtype, NIF_MODE dmode, uint32_t aux_id = 0 ); + virtual uint32_t addLocalUART( uint8_t utype, uint32_t speed, uint8_t bit, char parity, float stop_bit, CSTR PATH, uint8_t mode=0, uint16_t port=0 ); + virtual uint32_t addLocalWiFi( uint32_t NIF_ID, WIFI_MODE mode, CSTR SSID, CSTR password, WIFI_ENCRIPTION encryption, uint32_t router_id=0 ); + virtual uint32_t addResource( uint8_t type, CSTR devName, uint32_t auxID = 0 ); + virtual bool cleanNodePushedCMD( void ); + virtual uint32_t getCamId( CSTR UUID ); + virtual DBC_MODULE_DATA * getModuleData( uint32_t ID ); + virtual uint32_t getMediaStreamID( uint32_t source_id, CSTR token ); + virtual DBC_NET_IF_DATA * getNIF_Data( uint32_t ID ); + virtual uint32_t getNIF_ID( CSTR key ); + virtual uint32_t getNIF_IDbyDevice( CSTR device ); + virtual uint32_t getWiFi_ID( uint32_t nif_id ); + virtual uint32_t getNetworkInfrastructureID( uint32_t nif_id ); + virtual DBC_PUSHED_CMD * getNodePushedCMD( uint32_t NodeID ); + virtual DBC_RESOURCE_DATA * getResourceData( uint32_t ResourceID ); + virtual uint32_t getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID ); + virtual uint32_t getServerID( CSTR identity ); + virtual uint32_t getServerNode( uint32_t SID ); + virtual uint32_t getUartID( uint32_t NodeID, uint8_t Type, CSTR path ); + + virtual DBC_INT_LIST * listModules(); + virtual DBC_INT_LIST * listNewModules( DBC_INT_LIST * old_ids ); + virtual DBC_INT_LIST * listResources( uint32_t NodeID = 0 ); + + virtual void registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_t *ServID, uint32_t *ServNode ); + virtual bool setNodeOffline( uint32_t NodeID ); + virtual bool setNodeOnline( uint32_t NodeID, uint8_t status=NODE_STATUS_WORK ); + virtual bool setStreamValid( uint32_t streamID, bool status = true ); + virtual void unregisterServer( void ); + virtual bool updateIPCam( uint32_t CamID, CSTR Addr ); + virtual bool updateIPCam( CSTR uuid, CSTR Addr ); + virtual bool updateLocalCam( CSTR uuid ); + virtual bool updateLocalCam( uint32_t CamID ); + virtual bool updateNodePushedCMD( uint32_t CmdID, uint8_t status ); + virtual bool updateServerUtilisation( DBC_SYS_LOAD_INFO *ptr ); + virtual bool updateSystemInfo( DBC_SYS_INFO *ptr ); + virtual CSTR getDataParam( uint8_t pid = 0 ); +}; + +#endif + diff --git a/lib/App/common/dataBinder.cpp b/lib/App/common/dataBinder.cpp new file mode 100644 index 00000000..32da8ce9 --- /dev/null +++ b/lib/App/common/dataBinder.cpp @@ -0,0 +1,3 @@ +#include "dataBinder.h" +dataBinder::dataBinder(){}; +dataBinder::~dataBinder(){}; \ No newline at end of file diff --git a/lib/App/common/dataBinder.h b/lib/App/common/dataBinder.h new file mode 100644 index 00000000..5bf1dd69 --- /dev/null +++ b/lib/App/common/dataBinder.h @@ -0,0 +1,177 @@ +#ifndef __DFSL_DATA_BINDER_HEADER__ +#define __DFSL_DATA_BINDER_HEADER__ + +#include "dataBinder_structures.h" + + +class dataBinder{ + protected: + dataBinder(); + public: + virtual ~dataBinder(); + virtual bool isLocal(){ return true; }; + //virtual uint32_t addEvent( uint32_t SRC, CSTR UUID, uint32_t tss, uint32_t tsms, uint8_t evt_type, uint8_t k_id=0, uint16_t dig_r=0, float EL=.0f, float AZ=.0f, float RANGE=.0f, float AREA=.0f, float lat=.0f, float lon=.0f, float alt=.0f, uint32_t RefID=0, CSTR RefUUID=NULL ); + virtual uint32_t addEvent( DBC_EVT_RECORD *ptr ){ return 0;}; + virtual bool addDeviceDraw( uint32_t DBID, uint8_t type, uint8_t lrf, void *th_data, uint32_t th_size ){ return false;}; + + virtual bool addLRFDraw( uint32_t DBID, uint32_t SIZE, CSTR ID, uint8_t kID =0, uint8_t type = 0, bool rendered = false ){ return false;}; + virtual uint32_t addLRFMask( uint32_t devID, uint8_t lrfID = 0, uint8_t layerID = 0 ){ return 0;}; + virtual uint32_t addLRFMaskPolygone( uint32_t maskID, uint8_t r, uint8_t g, uint8_t b ){ return 0;}; + virtual bool addLRFMaskPolygonePoint( uint32_t polyID, int16_t x, int16_t y ){ return false;}; + + //virtual bool addIPCam( uint32_t SiteID, resultWoWo *tPtr ); + + virtual bool addIPCam( OBSERVER_RESULT *tPtr ){ return false;}; + virtual uint32_t addLocalMediaSource( uint32_t SiteID, CSTR path, uint32_t width, uint32_t height ){ return 0;}; + virtual uint32_t addLocalDCB( uint32_t SiteID, CSTR PATH, CSTR SERIAL, uint8_t CNT, uint32_t status ){ return 0;}; + virtual uint32_t addLocalCam( CSTR name, CSTR hardware, CSTR path, uint32_t width, uint32_t height ){ return 0;}; + virtual uint32_t addLocalUART( /*uint32_t NodeID,*/ uint8_t utype, uint32_t speed, uint8_t bit, char parity, float stop_bit, CSTR PATH, uint8_t mode=0, uint16_t port=0 ){ return 0;}; + virtual uint32_t addLocalNIF( CSTR device, CSTR mac, NIF_TYPE dtype, NIF_MODE dmode, uint32_t aux_id = 0 ){ return 0;}; + virtual uint32_t addLocalNetwork( uint32_t NIF_ID, NETWORK_TYPE net_type, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ){ return 0;}; + virtual uint32_t addLocalNetworkInfrastructure( uint32_t NIF_ID, uint32_t OUTBOUND_NIF, bool ena_dhcp=false, CSTR BRANG=NULL, CSTR ERANG=NULL, CSTR MASK=NULL, CSTR LEASE_TIME=NULL ){ return 0;}; + virtual uint32_t addLocalWiFi( uint32_t NIF_ID, WIFI_MODE mode, CSTR SSID, CSTR password, WIFI_ENCRIPTION encryption, uint32_t router_id=0 ){ return 0;}; + virtual bool addNotification( uint32_t MSG_ID, uint8_t DIS_LVL = 0, uint32_t OBJ_ID=0 ){ return false;}; + virtual bool addPicture( DBC_SNAPSHOT_DATA *ptr, CSTR ext ){ return false;}; + + //virtual bool addPictureEvent( uint32_t evtID, uint32_t pictureoID ){ return false;}; + virtual uint32_t addResource( /*uint32_t NodeID,*/ uint8_t type, CSTR devName, uint32_t auxID = 0 ){ return 0;}; + virtual uint32_t addUploadFile( uint32_t NodeID, CSTR uid, CSTR fileName ){ return 0;}; + + virtual bool addVideoEvent( uint32_t evtID, uint32_t videoID, uint32_t clen ){ return false;}; + virtual uint32_t addVideoRecord( uint32_t streamID, CSTR md5, CSTR ext, uint32_t ts, uint32_t tsms, uint32_t fps ){ return 0;}; + + virtual bool cleanResources( bool all = false ){ return false;}; + virtual bool cleanLRFMask( uint32_t maskID, bool deleteMask = false ){ return false;}; + virtual bool cleanNodeEvents( uint32_t NodeID, bool all = false ){ return false;}; + virtual bool cleanEvents2PictureBinding( uint32_t PicID ){ return false;}; + virtual bool cleanEvents2VideoBinding( uint32_t PicID ){ return false;}; + virtual bool cleanNodePushedCMD( void ){ return false;}; + + + virtual void lazyEventArchiver( uint32_t DalayTime = 10 ){}; + virtual DBC_INT_LIST * listCamMediaStreams( uint32_t CAMID ){ return NULL;}; + virtual DBC_INT_LIST * listStreamCapPictures( uint32_t StreamID, uint32_t cnt ){ return NULL;}; + virtual DBC_INT_LIST * listDetectionProfileIDs( uint32_t nodeID ){ return NULL;}; + virtual DBC_INT_LIST * listDetectionProfiles( uint32_t nodeID ){ return NULL;}; + virtual DBC_INT_LIST * listFilters( uint32_t ServerID ){ return NULL;}; + virtual DBC_INT_LIST * listLRFMaskVertexes( uint32_t MaskID ){ return NULL;}; + virtual DBC_INT_LIST * listLRFMaskVertexPoints( uint32_t VertexID ){ return NULL;}; + virtual DBC_INT_LIST * listMediaServerStreams( uint32_t SiteId, uint32_t MediaServerID, uint8_t listingType = LIST_ALL_RECORDS ){ return NULL;}; + virtual DBC_INT_LIST * listMediaStreams( uint32_t SiteId, uint8_t listingType = LIST_ALL_RECORDS ){ return NULL;}; + virtual DBC_INT_LIST * listModules(){ return NULL;}; + virtual DBC_INT_LIST * listNetworks( uint32_t nif_id ){ return NULL;}; + virtual DBC_INT_LIST * listNewModules( DBC_INT_LIST * old_ids ){ return NULL;}; + + virtual DBC_INT_LIST * listNewNodes( DBC_INT_LIST * old_ids ){ return NULL;}; + virtual DBC_INT_LIST * listNodes( bool all = false ){ return NULL;}; + //virtual DBC_INT_LIST * listSockets( uint32_t NodeID ){ return NULL;}; + virtual DBC_INT_LIST * listResources( uint32_t NodeID = 0 ){ return NULL;}; + virtual simplePolygone * loadLRFMaskVertex( uint32_t vid ){ return NULL;}; + + virtual bool getAllCamRecords( uint32_t SiteID, vectorCamRecords &VR ){ return false;}; + virtual DBC_APF_DATA * getAPFData( uint32_t APFID ){ return NULL;}; + virtual DBC_CAM_DATA * getCamData( uint32_t CamID ){ return NULL;}; + virtual uint32_t getCamId( CSTR UUID ){ return 0;}; + + virtual bool getConnectionStatus(void){return false;}; + virtual DBC_CAP_DATA * getCamCapPictureData( uint32_t PicID ){ return NULL;}; + virtual DBC_EVT_RECORD * getEventByUUID( CSTR UUID ){ return NULL;}; + virtual DBC_MODULE_EMBED_VIDEO_DATA * getEmbedVideoData( uint32_t ID ){ return NULL;}; + virtual DBC_FH_DATA * getFlyHunterData( uint32_t ID ){ return NULL;}; + virtual int getIPCamCount( uint32_t SiteID ){ return 0;}; + virtual KAFKA_TEMPLATE * getKafkaTemplateForEvent( uint32_t ModuleID, uint32_t ClassID, uint32_t EventID ){ return NULL;}; + //virtual bool getLastEvents( vectorEventRecords &VR, uint32_t tss, uint32_t tsms ); + virtual DBC_LRF_DATA * getLRFData( uint32_t ID ){ return NULL;}; + virtual uint8_t getLRFDataStatus( uint32_t ID ){ return 0;}; + virtual PLGS_2D_PARAMETERS getLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master ){ return NULL;}; + virtual CSTR getLRFDraw( uint32_t DBID ){ return NULL;}; + virtual uint32_t getLRFMaskID( uint32_t deviceID, uint8_t lrfID = 0, uint8_t layer = 0 ){ return 0;}; + virtual DBC_MEDIA_STREAM_DATA * getMediaStreamData( uint32_t ID ){ return NULL;}; + virtual uint32_t getMediaStreamID( uint32_t source_id, CSTR token ){ return NULL;}; + virtual DBC_MEDIA_SERVER_DATA * getMediaServerData( uint32_t ID ){ return NULL;}; + virtual DBC_MEDIA_SERVER_STREAM_DATA * getMediaServerStreamData( uint32_t ID ){ return NULL;}; + virtual DBC_MEDIA_SERVER_STREAM_DATA * getMediaServerStreamDataBySource( uint32_t ID ){ return NULL;}; + virtual DBC_MODULE_DATA * getModuleData( uint32_t ID ){ return NULL;}; + //virtual * getModuleEveSettings( uint32_t ID ){}; + //virtual * getModuleSSDPSettings( uint32_t ID ){}; + virtual CSTR getNodeName( uint32_t NodeID ){ return NULL;}; + virtual uint32_t getNodeAuxParam( uint32_t NodeID ){ return 0;}; + virtual uint32_t getNodeAuxID( uint32_t NodeID ){ return 0;}; + virtual DBC_NETWORK_DATA * getNetworkData( uint32_t net_id ){ return NULL;}; + virtual uint32_t getNetworkInfrastructureID( uint32_t nif_id ){ return 0;}; + virtual DBC_NET_IF_DATA * getNIF_Data( uint32_t ID ){ return NULL;}; + virtual uint32_t getNIF_ID( CSTR key ){ return 0;}; + virtual uint32_t getNIF_IDbyDevice( CSTR device ){ return 0;}; + virtual DBC_NODE_DATA * getNodeData( uint32_t ID ){ return NULL;}; + + virtual DBC_PUSHED_CMD * getNodePushedCMD( uint32_t NodeID ){ return NULL;}; + virtual DBC_PUSHED_CMD * getActivePushedCMD( uint32_t NodeID ){ return NULL;}; + virtual DBC_PUSHED_CMD * getPushedCMD( uint32_t CmdID ){ return NULL;}; + + //virtual uint32_t getNodeSocketID( uint32_t NodeID, uint32_t auxID, uint8_t SocketType, CSTR path ); + virtual DBC_RESOURCE_DATA * getResourceData( uint32_t ResourceID ){ return NULL;}; + virtual uint32_t getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID ){ return 0;}; + virtual uint32_t getServerID( CSTR identity ){ return 0;}; + virtual uint32_t getServerNode( uint32_t SID ){ return 0;}; + virtual KAFKA_SETTINGS * getSettingsKAFKA( uint32_t NodeID ){ return NULL;}; + virtual DBC_SITE_DATA * getSiteData( uint32_t ID ){ return NULL;}; + //virtual DBC_SOCKET_DATA * getSocketData( uint32_t ID ){ return NULL;}; + virtual DBC_TARGET_FLITER_DATA * getTargetFilterData( uint32_t ID ){ return NULL;}; + virtual DBC_UART_DATA * getUartData( uint32_t UartID ){ return NULL;}; + virtual uint32_t getUartID( uint32_t NodeID, uint8_t Type, CSTR path ){ return 0;}; + virtual uint32_t getWiFi_ID( uint32_t nif_id ){ return 0;}; + virtual bool fillShadow2D( uint32_t ID, SHADOW & SH ){ return false;}; + + virtual void deleteCamCapPicture( uint32_t PicID ){}; + virtual void deleteNode( uint32_t NodeID ){}; + virtual void deleteCamera( uint32_t CamID ){}; + virtual void deleteConnections( uint32_t NodeID ){}; + virtual void deleteNodeEvents( uint32_t NodeID ){}; + virtual void deleteMediaStream( uint32_t MediaID ){}; + virtual void deleteNIF( uint32_t NifID ){}; + virtual void deleteNIS( uint32_t NisID ){}; + virtual void deleteResource( uint32_t ResourceID ){}; + virtual void deleteSensor( uint32_t SensorID ){}; + virtual void deleteUART( uint32_t UARTID ){}; + + virtual void finalizeVideoRecord( uint32_t videoID, uint32_t clen ){}; + + virtual void registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_t *ServID, uint32_t *ServNode ){}; + virtual void unregisterServer( void ){}; + + virtual bool transferEvtToArchive( uint32_t SECONDS = ONE_DAY_HISTORY ){ return false;}; + + + + virtual bool setNodeOnline( uint32_t NodeID, uint8_t status=NODE_STATUS_WORK ){ return false;}; + virtual bool setNodeOffline( uint32_t NodeID ){ return false;}; + virtual bool setOnlineStatus( bool Status ){ return false;}; + virtual bool setLRFDetectionProfile( uint32_t lrfID, uint8_t profileID ){ return false;}; + virtual bool setLRFDataStatus( uint32_t lrfID, uint8_t ST ){ return false;}; + virtual bool setLRFAltSerial( uint32_t lrfID, CSTR Serial ){ return false;}; + virtual bool setLRFAltVerison( uint32_t lrfID, CSTR version ){ return false;}; + virtual bool setLRFMaskStatus( uint32_t maskID, bool status ){ return false;}; + virtual bool setStreamValid( uint32_t streamID, bool status = true ){ return false;}; + //virtual bool syncEventArchive( void ); ALTER TABLE table_name AUTO_INCREMENT = start_value; + virtual bool update3DRuntimeStatus( uint32_t lrfID, ALG_RUN_STATUS *ptr ){ return false;}; + virtual bool updateAFPBox( uint32_t filterID, CSTR Tag, float x, float y, float z ){ return false;}; + virtual bool updateCamRange( uint32_t camID, float range ){ return false;}; + virtual bool updateIPCam( CSTR uuid, CSTR Addr ){ return false;}; + virtual bool updateIPCam( uint32_t CamID, CSTR Addr ){ return false;}; + virtual bool updateLocalCam( CSTR uuid ){ return false;}; + virtual bool updateLocalCam( uint32_t CamID ){ return false;}; + virtual bool updateLRFSerial( uint32_t lrfID, CSTR Serial ){ return false;}; + virtual bool updateLRFVerison( uint32_t lrfID, CSTR version ){ return false;}; + virtual bool updateLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master, uint16_t nOrder, uint16_t nOffset, uint16_t nDelta, uint16_t nWidth, uint16_t nFlip, uint16_t nSun, uint8_t bSST, uint32_t GP=0, uint32_t spikes=0 ){ return false;}; + virtual bool updateMediaServerStream( uint32_t id, CSTR mrl=NULL, CSTR key = NULL ){ return false;}; + virtual bool updateNetworkNode( bool OnlineStatus ){ return false;}; + virtual bool updateNodePushedCMD( uint32_t CmdID, uint8_t status ){ return false;}; + virtual bool updateResourceAUX( uint32_t ResID, uint32_t AUX ){ return false;}; + virtual bool updateServerUtilisation( DBC_SYS_LOAD_INFO *ptr ){ return false;}; + virtual bool updateSystemInfo( DBC_SYS_INFO *ptr ){ return false; }; + virtual CSTR getDataParam( uint8_t pid = 0 ){ return NULL; }; + +}; + + +#endif \ No newline at end of file diff --git a/lib/App/common/dataBinder_structures.h b/lib/App/common/dataBinder_structures.h new file mode 100644 index 00000000..291fcea4 --- /dev/null +++ b/lib/App/common/dataBinder_structures.h @@ -0,0 +1,645 @@ +#ifndef __DFSL_DATABINDING_STRUCTURES_HEADER__ +#define __DFSL_DATABINDING_STRUCTURES_HEADER__ + +#define __STDC_FORMAT_MACROS 1 +#include + +#include "../../alg/lgs/mask.h" +#include "../../alg/lgs/detectorStructures.h" +#include "../../data/protocol/protocolLGS_data.h" + +#define MAX_BUFF_SIZE 102400 //100K + +#define LIST_ALL_RECORDS 0 +#define LIST_VALID_RECORDS 1 +#define LIST_INVALID_RECORDS 2 + +#define ONE_DAY_HISTORY 86400 +#define ONE_HOUR_HISTORY 3600 +#define ONE_SECOND_HISTORY 1 + +#define NM_DISMISS_LEVEL_VIEWER 1 +#define NM_DISMISS_LEVEL_OPERATOR 2 +#define NM_DISMISS_LEVEL_ADMIN 5 +#define NM_DISMISS_LEVEL_FOUNDER 9 + +#define NM_DEVICE_MISTMATCH 1 + +#define NODE_STATUS_WORK 1 +#define NODE_STATUS_INIT 2 +#define NODE_STATUS_TROUBLE 3 +#define NODE_STATUS_ALARM 4 + +typedef enum E_ARGUS_NODE_TYPE{ + ARGUS_SERVER = 0, + ARGUS_ALS_SENSOR = 1, + ARGUS_LFS_SENSOR = 2, + ARGUS_PLS_200_SENSOR = 3, + ARGUS_PLS_360_SENSOR = 4, + ARGUS_3D_SENSOR = 5, + ARGUS_NET_PLS_200 = 6, + ARGUS_CLD_SENSOR = 7, + ARGUS_LGS_SENSOR = 8, + ARGUS_ACC_SENSOR = 9, + ARGUS_ANALOG_STATIC_CAMERA = 10, + ARGUS_ANALOG_PTZ_CAMERA = 11, + ARGUS_IP_STATIC_CAMERA = 12, + ARGUS_IP_PTZ_CAMERA = 13, + ARGUS_IP_UART_GATEWAY = 20, + ARGUS_JAMER = 40, + ARGUS_IP_VIDEO_SERVER = 50, + ARGUS_DRONE_CONTROL = 60, + ARGUS_CELLULAR_GATEWAY = 61, + + ARGUS_NAPD_FILTER = 100, + ARGUS_METRO_FILTER = 101, + ARGUS_UNKNOWN = 255 +}ARGUS_NODE_TYPE; + +#ifdef __linux__ + #ifdef __arm__ + #ifdef RASPI_HARDWARE + #define _BUILD_STRING_ ( "RPI_22.06.17 [" __DATE__ " " __TIME__ "]") + #else + #define _BUILD_STRING_ ( "ALS_22.06.17 [" __DATE__ " " __TIME__ "]") + #endif + #else + #define _BUILD_STRING_ ( "ILS_22.06.17 [" __DATE__ " " __TIME__ "]") + #endif +#else + #define _BUILD_STRING_ ( "WIN_22.06.17 [" __DATE__ " " __TIME__ "]") +#endif + +typedef uint8_t NODE_TYPE; + +typedef struct S_OBSERVER_RESULT{ + int resultID; + char RefID[CTEXT]; + char Type[CTEXT]; + char MAC[CTEXT]; + char Hardware[CTEXT]; + char Name[CTEXT]; + char XAddrs[CTEXT]; +}OBSERVER_RESULT; + +typedef struct S_MEDIA_SOURCE_DESC{ + uint32_t mediaStreamId; + uint32_t mediaSourceId; + char mediaName[128]; +}MEDIA_SOURCE_DESC; + +typedef enum E_HARDWARE_PROVIDERS{ + HARDWARE_PROVIDER_UNKNOWN = 0, + HARDWARE_PROVIDER_SERIAL = 1, + HARDWARE_PROVIDER_NETWORK = 2, + HARDWARE_PROVIDER_VIDEO = 3, + HARDWARE_PROVIDER_DRY_CONTACT = 4 +} HARDWARE_PROVIDERS; + +typedef std::vector vectorCSTR; + +typedef enum E_RESOURCE_CLASS{ + HARDWARE_CLASS_UNKNOWN = 0, + HARDWARE_CLASS_SERIAL = 1, + HARDWARE_CLASS_GPIO = 2, + HARDWARE_CLASS_NETWORK = 3, + HARDWARE_CLASS_MEDIA = 4 +} RESOURCE_CLASS; + +typedef enum E_RESOURCE_TYPE{ + HARDWARE_UNKNOWN = 0, + HARDWARE_UART = 1, + HARDWARE_USB_DC = 6, + HARDWARE_GPIO_IN = 7, + HARDWARE_GPIO_OUT = 8, + + HARDWARE_ANALOG_VIDEO_OUT = 30, + HARDWARE_ANALOG_VIDEO_IN = 31, + HARDWARE_DIGITAL_VIDEO_OUT = 32, + HARDWARE_DIGITAL_VIDEO_IN = 33, + + HARDWARE_NIF_LOOPBACK = 100, + HARDWARE_NIF_ETHERNET = 101, + HARDWARE_NIF_WIFI = 102, + HARDWARE_NIF_VIRTUAL = 103, + HARDWARE_NIF_TUNEL = 104, + HARDWARE_NIF_WAN = 105, + + HARDWARE_MODEM = 120, + HARDWARE_IP_UART = 129, + HARDWARE_IP_VIDEO_OUT = 130, + HARDWARE_IP_VIDEO_IN = 131 +} RESOURCE_TYPE; + +typedef enum E_NIF_TYPE{ + NIF_LOOPBACK = 0, + NIF_ETHERNET = 1, + NIF_ETHERNET_VIRTUAL = 2, + NIF_WIFI = 3, + NIF_VPN_TUNEL = 4, + NIF_WAN = 5 +}NIF_TYPE; + +typedef enum E_NIF_MODE{ + ADDRESS_DISABLED = 0, + ADDRESS_DYNAMIC = 1, + ADDRESS_STATIC = 2, + ADDRESS_STATIC_RAP = 3 +} NIF_MODE; + +typedef enum E_WIFI_MODE{ + WIFI_DISABLED = 0, + WIFI_ADHOC = 1, + WIFI_CONNECTED_TO_AP = 2, + WIFI_IS_AP = 3 +}WIFI_MODE; + +typedef enum E_WIFI_ENCRIPTION{ + ENCRIPTION_NONE = 0, + ENCRIPTION_WPA_PSK = 1, + ENCRIPTION_WPE = 2, + ENCRIPTION_TKIP = 3 +}WIFI_ENCRIPTION; + +typedef enum E_NETWORK_TYPE{ + NETWORK_IPV4 = 0, + NETWORK_IPV6 = 1, +} NETWORK_TYPE; + +typedef enum E_CAM_TRIGGER_MODE{ + CAM_TRIGGER_STRICT = 0, + CAM_TRIGGER_ALL_NEAR = 1, + CAM_TRIGGER_ALL_FAR = 2, + CAM_TRIGGER_ALL = 3 +} CAM_TRIGGER_MODE; + +typedef struct S_DBC_CAM_DATA{ + uint32_t id; + uint32_t site_id; + uint32_t node_id; + bool online; + uint8_t type; + char name[65]; + char hardware[33]; + uint8_t status; + char session[33]; + uint8_t protocol; + uint8_t protocol_aux; + uint32_t uart_id; + float x; + float y; + float z; + float x_rot; + float y_rot; + float z_rot; + uint8_t imager_type; + uint8_t lens_f; + //float max_range; + float ptz_speed_step; + uint8_t pan_model; + uint16_t pan_angles; + uint8_t tilt_model; + uint8_t tilt_angles; + uint8_t zoom_model; + float zoom; + char username[33]; + char password[33]; + char uuid[65]; + char ip[18]; + uint16_t port; + char mac[18]; + char onvif_access[6]; + char onvif_ctrl[251]; + char ptz_token[65]; + uint8_t triggering_mode; + uint8_t auth_mode; +}DBC_CAM_DATA; + +typedef struct S_DBC_NETWORK_DATA{ + uint32_t id; + uint32_t nif_id; + char address[65]; + char netmask[65]; + char broadcast[65]; + char gateway[65]; + NETWORK_TYPE type; +}DBC_NETWORK_DATA; + +typedef struct S_DBC_WIFI_DATA{ + uint32_t id; + uint32_t if_id; + char SSID[65]; + char password[65]; + uint8_t mode; // disabled connected_to_ap ap + uint32_t aux_id; // ap_router +}DBC_WIFI_DATA; + +typedef struct S_DBC_NET_ROUTER_DATA{ + char address_range[128]; +}DBC_NET_ROUTER_DATA; + +typedef struct S_DBC_NET_IF_DATA{ + uint32_t id; + uint8_t type; // Ethernet Wifi + uint8_t mode; // dynamic static static-router + char device_name[11]; + char mac[33]; + uint32_t aux_id; // wifi_id router_id + + DBC_NETWORK_DATA ** networks; + uint8_t networkCount; +} DBC_NET_IF_DATA; + + +typedef struct S_DBC_NODE_DATA{ + uint32_t node_id; + uint32_t aux_id; + uint32_t aux_parameter; + uint8_t type; + bool online; + uint32_t tss; + uint32_t tsm; + char name[128]; +}DBC_NODE_DATA; + +typedef struct S_DBC_MODULE_DATA{ + uint32_t module_id; + uint32_t aux_id; + uint32_t type; + bool enabled; + char name[128]; +}DBC_MODULE_DATA; + +typedef struct S_DBC_MODULE_EMBED_VIDEO_DATA{ + uint8_t output_mode; + uint16_t port; + bool show_ts; + bool show_label; + bool show_logo; + uint16_t width; + uint16_t height; + uint8_t compression_quality; + int ts_x; + int ts_y; + uint8_t ts_font_face; + float ts_font_scale; + int8_t ts_font_thickness; + int ts_line_type; + bool ts_transperant; + int label_x; + int label_y; + uint8_t label_font_face; + float label_font_scale; + int8_t label_font_thickness; + int label_line_type; + bool label_transperant; + uint8_t logo_w; + uint8_t logo_h; + int logo_x; + int logo_y; + char logo_md5[33]; +}DBC_MODULE_EMBED_VIDEO_DATA; + +/* +typedef struct S_DBC_SOCKET_DATA{ + uint32_t socket_id; + uint32_t node_id; + uint32_t aux_id; + uint32_t type; + uint32_t state; + uint32_t mode; + bool binded; + char path[128]; + char name[128]; +}DBC_SOCKET_DATA; +*/ + +typedef struct S_DBC_RESOURCE_DATA{ + uint32_t id; + uint32_t node_id; + uint32_t aux_id; + uint8_t type; + char device[64]; +}DBC_RESOURCE_DATA; + + +#define CMD_KRNL_SYSTEM_TASK 120 +#define CMD_KRNL_RELOAD 128 +#define CMD_KRNL_DELNODE 240 +#define CMD_KRNL_RESET_SITE 245 +#define CMD_KRNL_RESTART 250 +#define CMD_KRNL_PNP 251 +#define CMD_KRNL_SYNC_TIME 252 +#define CMD_KRNL_OS_REBOOT 253 +#define CMD_KRNL_FACTORY_RESET 254 +#define CMD_KRNL_SHUTDOWN 255 + + +#define CMD_MODULES_RELOAD 60 +#define CMD_MODULE_ENABLE 61 +#define CMD_MODULE_DISABLE 62 +#define CMD_NODES_RELOAD 80 +#define CMD_NODE_RELOAD 81 +#define CMD_NODE_UPDATE 82 +#define CMD_ROI_GEO 40 +#define CMD_PTZ_GEO 41 +#define CMD_PTZ_ONVIF 42 +#define CMD_PTZ_MOVE 43 +#define CMD_HARDWARE_DETECT 27 + +#define CMD_STATUS_NEW 0 +#define CMD_STATUS_ACTIVE 1 +#define CMD_STATUS_FINISHED 2 + +#define DBC_CMD_STARTED 1 +#define DBC_CMD_FINISHED 100 +#define DBC_CMD_FINISHED_ERROR 128 +#define DBC_CMD_READY_TO_CLEAN 250 + + +typedef struct S_DBC_PUSHED_CMD{ + uint32_t id; + uint8_t CMD; + char PARAM[256]; +}DBC_PUSHED_CMD; + +typedef struct S_ROI_CMD_DATA{ + uint16_t az_d; + uint16_t el_d; + uint16_t r_d; +}ROI_CMD_DATA; + +typedef struct S_DBC_MEDIA_STREAM_DATA{ + uint32_t id; + uint32_t source_id; + char source_type[2]; + bool valid; + char token[65]; + uint32_t width; + uint32_t height; + uint8_t fps; + char c_type[7]; + char mrl_proto[6]; + uint16_t mrl_port; + char mrl[251]; +}DBC_MEDIA_STREAM_DATA; + +typedef struct S_DBC_MEDIA_SERVER_DATA{ + uint32_t id; + char key[46]; + char ip[16]; + uint16_t port; + char host[64]; + bool recording; + bool local; + char docRoot[256]; + char name[128]; +}DBC_MEDIA_SERVER_DATA; + +typedef struct S_DBC_MEDIA_SERVER_STREAM_DATA{ + uint32_t id; + uint32_t media_stream_id; + bool online; + char key[64]; + char mrl[128]; +} DBC_MEDIA_SERVER_STREAM_DATA; + +#define LRF_MAX_DETECTION_PROFILES 4 + +typedef struct S_LRF_DETECTION_PROFILE{ + uint16_t order; + uint16_t offset; + uint16_t delta; + uint16_t flip; + uint32_t width; + uint16_t sst; + uint16_t sun; + uint16_t gp; + uint16_t spikes; +}LRF_DETECTION_PROFILE; + +typedef struct S_DBC_LRF_DATA{ + uint32_t id; + uint8_t data_status; + char serial[65]; + char version[129]; + float x; + float y; + float z; + float x_rot; + float y_rot; + float z_rot; + uint32_t filter_id; + uint32_t uart_id; + uint32_t device_id; + char master_host[64]; + uint16_t master_port; + char slave_host[64]; + uint8_t auto_draw; + uint16_t slave_port; + uint16_t enabled_lrf; + float max_range; + int32_t base_shift; + int32_t mirror_shift; + uint8_t detection_profile_id; + uint8_t draw_lrf_id; + uint32_t width_table_id; + uint32_t zoom_table_id; + uint8_t embd_cam; + bool embd_cam_auto; + uint8_t embd_dc; + bool autoreset; + bool force_settings; + //LRF_DETECTION_PROFILE mlrf_profile[LRF_MAX_DETECTION_PROFILES]; + //LRF_DETECTION_PROFILE slrf_profile[LRF_MAX_DETECTION_PROFILES]; + //LRF_DETECTION_PROFILE *mlrf_profile; + //LRF_DETECTION_PROFILE *slrf_profile; +}DBC_LRF_DATA; + +typedef struct S_DBC_UART_DATA{ + uint8_t type; + uint8_t mode; + char path[128]; + uint16_t port; + uint32_t speed; + float stop_bits; + uint8_t flow_ctrl; +}DBC_UART_DATA; + +typedef struct S_EVT_DATA{ + uint32_t id; + uint32_t node_id; + char uuid[65]; + uint32_t ts_s; + uint32_t ts_ms; + uint8_t type; + uint32_t ref_id; + char ref_uuid[65]; +}EVT_DATA; + +typedef struct S_DBC_EVT_RECORD{ + uint32_t id; + uint32_t node_id; + char uuid[65]; + uint32_t ts_s; + uint32_t ts_ms; + uint8_t type; + uint8_t lrf_id; + uint32_t range_digital; + float az; + float el; + float ra; + float area; + float lat; + float lon; + float alt; + uint32_t ref_id; + char ref_uuid[65]; +}DBC_EVT_RECORD; + +typedef struct S_DBC_SITE_DATA{ + uint32_t account_id; + char name[129]; + char ident[33]; + float lat; + float lon; + float alt; + bool SH; + uint8_t map_id; + bool local_binding; +}DBC_SITE_DATA; + +typedef struct S_DBC_FH_DATA{ + char name[129]; + float lat; + float lon; + float alt; + uint32_t dc_id; + uint32_t uart_id; +}DBC_FH_DATA; + +typedef struct S_DBC_TARGET_FLITER_DATA{ + uint32_t id; + uint8_t type; + uint32_t aux_id; +}DBC_TARGET_FLITER_DATA; + + +typedef struct S_DBC_APF_DATA{ + uint16_t port; + char mode[3]; + float lat; + float lon; + float alt; + float pitch; + float yaw; + float roll; + float dx; + float dy; + float dz; +}DBC_APF_DATA; + +typedef struct S_DBC_MODEM_MANAGER_DATA{ + uint32_t id; + uint32_t time_window; + uint32_t evt_trigers; +}DBC_MODEM_MANAGER_DATA; + +typedef struct S_DBC_MODEM_DATA{ + uint32_t id; + uint32_t modem_id; + char imei[17]; + char dbus_dev_id[65]; + char hw_model[65]; + char hw_manufac[65]; + char hw_revision[65]; + char hw_version[33]; + char hw_id[33]; + uint32_t at_uart_id; + uint32_t at_uart_id_aux; + char sim_pin[7]; + char sim_pin2[7]; + char sim_puk[7]; + char sim_puk2[7]; + char status[2]; + char power[2]; + uint8_t signal; + uint32_t operator_id; + char conmection_tech[6]; + char registration[65]; +}DBC_MODEM_DATA; + +typedef struct S_DBC_3DLRF_WSTAT{ + +}DBC_3DLRF_WSTAT; + +typedef struct S_DBC_MASKING_POINT{ + +}DBC_MASKING_POINT; + +typedef struct S_DBC_MASKING_RAY{ + +}DBC_MASKING_RAY; + +typedef struct S_DBC_MASKING_VERTEX{ + uint32_t mask_id; + uint8_t color[3]; + uint32_t vertex_id; + uint16_t points_cnt; + DBC_MASKING_POINT * points; +}DBC_MASKING_VERTEX; + +typedef struct S_DBC_ZONE_MASK{ + uint32_t id; + uint8_t status; + uint16_t vertexes_cnt; + DBC_MASKING_VERTEX * vertexes; + uint16_t rays_cnt; + DBC_MASKING_RAY rays; +}DBC_ZONE_MASK; + +typedef struct S_DBC_CAP_DATA{ + char md5[33]; + char ext[5]; +}DBC_CAP_DATA; + +typedef std::vector DBC_INT_LIST; +typedef std::vector vectorCamRecords; +typedef std::vector vectorEventRecords; + +typedef struct S_DBC_SNAPSHOT_DATA{ + char md5[33]; + DBC_INT_LIST assoc_event_ids; + uint32_t stream_id; + uint32_t ts; + uint32_t data_size; + uint8_t * data; +}DBC_SNAPSHOT_DATA; + +typedef struct S_DBC_SYS_INFO{ + char OS_INFO[128]; + char HW_INFO[128]; + char SW_INFO[128]; +}DBC_SYS_INFO; + +typedef struct S_DBC_SYS_LOAD_INFO{ + //Percs + float cpu1; + float cpu5; + float cpu15; + float mem; + float disk; + float temperature; + // Abs + uint64_t T_MEM; + uint64_t T_DISK; + uint64_t C_MEM; + uint64_t C_DISK; + uint32_t CPU_CORES; +}DBC_SYS_LOAD_INFO; + +typedef struct S_DBC_SSDP_SETTINGS{ + +}DBC_SSDP_SETTINGS; + +#endif \ No newline at end of file diff --git a/lib/App/common/deviceNode.cpp b/lib/App/common/deviceNode.cpp new file mode 100644 index 00000000..03521cb3 --- /dev/null +++ b/lib/App/common/deviceNode.cpp @@ -0,0 +1,119 @@ +#include "deviceNode.h" + +#ifdef USE_MYSQL + #include "MySQL_dataBinder.h" +#else + #include "SQLite_dataBinder.h" +#endif + +#define LOG( X ) m_pLog->Log( "NODE", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "NODE", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "NODE", this, _LOG_ERROR, X ); +#endif + +deviceNode::deviceNode( uint32_t id ):basicEngine(){ + m_pLog = basicLogCollection::getInstance(); +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + m_mCommandProtector.unlock(); + if( m_pDBC != NULL ) { + DBC_NODE_DATA *tData = m_pDBC->getNodeData( id ); + if( tData != NULL ) { + memcpy( &m_sNodeData , tData, sizeof(DBC_NODE_DATA)); + m_sNodeData.online = m_pDBC->setNodeOnline( m_sNodeData.node_id ); + free( tData ); + } else { + memset( &m_sNodeData , 0, sizeof(DBC_NODE_DATA)); + m_sNodeData.type = ARGUS_UNKNOWN; + m_sNodeData.node_id = id; + }; + } else { + memset( &m_sNodeData , 0, sizeof(DBC_NODE_DATA)); + m_sNodeData.type = ARGUS_UNKNOWN; + m_sNodeData.node_id = id; + }; +}; + +deviceNode::deviceNode( DBC_NODE_DATA *Data ):basicEngine(){ + m_pLog = basicLogCollection::getInstance(); +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + m_mCommandProtector.unlock(); + if( Data ) { + memcpy( &m_sNodeData , Data, sizeof(DBC_NODE_DATA)); + if( m_pDBC ) { + m_sNodeData.online = m_pDBC->setNodeOnline( m_sNodeData.node_id ); + }; + } else { + memset( &m_sNodeData , 0, sizeof(DBC_NODE_DATA)); + m_sNodeData.type = ARGUS_UNKNOWN; + }; +}; + +deviceNode::~deviceNode(){ + m_mCommandProtector.lock(); + if( m_qCommands.size() ) { + NI_COMMAND *tVal = NULL; + while( tVal = m_qCommands.front() ){ + m_qCommands.pop(); + if( tVal->parameter ) { + free( tVal->parameter ); + }; + free( tVal ); + }; + }; + m_mCommandProtector.unlock(); + m_pDBC->setNodeOffline( m_sNodeData.node_id ); +}; + + +NI_COMMAND *deviceNode::fetchCommand(){ + NI_COMMAND *RetVal = NULL; + m_mCommandProtector.lock(); + if( m_qCommands.size() ) { + RetVal = m_qCommands.front(); + m_qCommands.pop(); + }; + m_mCommandProtector.unlock(); + return RetVal; +}; + +void deviceNode::enqueueCommand( NI_COMMAND *ptr ){ + if( ptr ) { + m_mCommandProtector.lock(); + m_qCommands.push( ptr ); + m_mCommandProtector.unlock(); + }; +}; + +bool deviceNode::validate(){ + DBC_NODE_DATA *tDATA = m_pDBC->getNodeData( m_sNodeData.node_id ); + if( tDATA ) { + if( memcmp( &m_sNodeData, tDATA, sizeof(DBC_NODE_DATA)) != 0 ){ + free( tDATA ); + LOG("Node Settings Changed!"); + return false; + }; + free( tDATA ); + } else { + LOG("Node is Deleted!"); + return false; + }; + return true; +}; +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/deviceNode.h b/lib/App/common/deviceNode.h new file mode 100644 index 00000000..b94b140c --- /dev/null +++ b/lib/App/common/deviceNode.h @@ -0,0 +1,42 @@ +#ifndef __DEVICE_NODE_HEADER__ +#define __DEVICE_NODE_HEADER__ + +#include "../../components/base/basicEngine.h" +#include "dataBinder.h" +#include +#include +#include + +typedef struct S_NI_COMMAND{ + uint8_t cmd; + uint32_t db_cmd; + void * parameter; +}NI_COMMAND; + +typedef std::queue queueNI_COMMANDS; + +class deviceNode: public basicEngine{ + private: + queueNI_COMMANDS m_qCommands; + basicMutex m_mCommandProtector; + protected: + basicLogCollection * m_pLog; + dataBinder * m_pDBC; + DBC_NODE_DATA m_sNodeData; + NI_COMMAND * fetchCommand(); + public: + explicit deviceNode( uint32_t id ); + explicit deviceNode( DBC_NODE_DATA *Data ); + virtual ~deviceNode(); + uint32_t getNodeID() const { return m_sNodeData.node_id; }; + uint32_t getDeviceID() const { return m_sNodeData.aux_id; }; + ARGUS_NODE_TYPE getNodeType() const { return (ARGUS_NODE_TYPE) m_sNodeData.type; }; + bool isNodeOnline( void ) const { return m_sNodeData.online; }; + void enqueueCommand( NI_COMMAND *ptr ); + virtual bool validate(); +}; + +typedef std::vector vectorDeviceNodes; +typedef std::map mapDeviceNode2Id; + +#endif \ No newline at end of file diff --git a/lib/App/common/deviceNode2D.cpp b/lib/App/common/deviceNode2D.cpp new file mode 100644 index 00000000..cd81056f --- /dev/null +++ b/lib/App/common/deviceNode2D.cpp @@ -0,0 +1,2157 @@ +#include "deviceNode2D.h" +#include "hardwareResourceSerialProvider.h" +#include "kernelPrototype.h" +#include "hardwareManager.h" + +#define LGS_MAX_DETECTOR_RANGE 2047 + +#define LOG( X ) deviceNode::m_pLog->Log( "NODE2D", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + deviceNode::m_pLog->Log( "NODE2D", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) deviceNode::m_pLog->Log( "NODE2D", this, _LOG_ERROR, X ); +#endif + +/* + USER.INI + +AUTORESET_ENABLE=0 +AUTORESET_INTERLEAVE=2000 +AUTORESET_TIMEOUT=-5536 +BOARD_TEMPERATURE=20 +BOARD_ZEROSHIFT=0 +BOARD_ENCODERSTEPS=6 +BOARD_GEARRATIO=61 +SWITCHER_TABLE=27,55,82 +SWITCHER_REPLY_TIMEOUT=100 +SWITCHER_COMMAND_TIMEOUT=500 +SWITCHER_AUTO_MODE=0 +SWITCHER_AUTO_ENTER_TIMEOUT=60 +SWITCHER_AUTO_SWITCH_TIMEOUT=3 + + + +*/ +const CSTR settings_user_ini_fields[ 13 ] = { + "AUTORESET_ENABLE", + "AUTORESET_INTERLEAVE", + "AUTORESET_TIMEOUT", + "BOARD_TEMPERATURE", + "BOARD_ZEROSHIFT", + "BOARD_ENCODERSTEPS", + "BOARD_GEARRATIO", + "SWITCHER_TABLE", + "SWITCHER_REPLY_TIMEOUT", + "SWITCHER_COMMAND_TIMEOUT", + "SWITCHER_AUTO_MODE", + "SWITCHER_AUTO_ENTER_TIMEOUT", + "SWITCHER_AUTO_SWITCH_TIMEOUT" +}; + +/* +LPCTSTR m_pSetting[] = +{ + { "SN" }, + { "ADDRESS" }, + { "CAMERA_TYPE" }, + { "CAMERA_SHIFT" }, + { "CAMERA_AUTO" }, + { "CAMERA_DELAY" }, + { "RELAY_NC" }, + { "RELAY_AUTO" }, + { "RELAY_DELAY" }, + { "VOLTAGE_CONTROL" }, + { "MASTER_DISABLED" }, + { "SLAVE_DISABLED" }, + + { "AUTORESET_ENABLE" }, + { "AUTORESET_INTERLEAVE" }, + { "AUTORESET_TIMEOUT" }, + + { "BOARD_TEMPERATURE" }, + { "BOARD_ZEROSHIFT" }, + { "BOARD_ENCODERSTEPS" }, + { "BOARD_GEARRATIO" }, + { "BOARD_MAXRANGE" }, + { "BOARD_SPEED" }, + { "RUN_DIR" }, + + { "SWITCHER_TABLE" }, + { "SWITCHER_REPLY_TIMEOUT" }, + { "SWITCHER_COMMAND_TIMEOUT" }, + { "SWITCHER_AUTO_MODE" }, + { "SWITCHER_AUTO_ENTER_TIMEOUT" }, + { "SWITCHER_AUTO_SWITCH_TIMEOUT" }, + + { "NO_BLACK_TARGETS" }, + { "JUST_MOVING_TARGETS" }, + { "JUST_MOVING_RADIAL" }, + { "JUST_MOVING_DISTANCE" }, + + { "BLIND_ZONE_START_ANGLE" }, + { "BLIND_ZONE_END_ANGLE" }, + { "BLIND_ZONE_START_RANGE" }, + { "BLIND_ZONE_END_RANGE" }, + { "BLIND_ZONE_WIDTH" }, + { "BLIND_ZONE_DEPTH" }, + { "BLIND_ZONE_ANGLE" }, + { "BLIND_ZONE_RANGE" } +#ifdef STORE_FIRST_SAF + ,{ "FREEZ_FIRST_TH" } + ,( "SAVE_FIRST_TH" ) +#endif +}; +*/ +device2DSensor::device2DSensor( uint32_t id ):deviceNodeSensor( id ), basicThread(), protocolLGS_2D(){ + m_pPort = NULL; + m_bPortType = 0; + m_bOpRetryCnt = 3; + m_nProcessingCmdId = 0; + m_bDeviceIsSynced = false; + cleanupDeviceStructures(); + memset( m_vDrawRanges, 0, sizeof( m_vDrawRanges )); + memset( &m_sShadowHelper, 0 , sizeof(SHADOW_IO_HELPER)); + memset( &m_sShadow, 0 , sizeof(SHADOW)); + memset( &m_sGetFileHelper, 0, sizeof(GETFILE_IO_HELPER)); + if( m_sLRF_DATA.uart_id ) { + DBC_UART_DATA *tUART = NULL; + tUART = m_pDBC->getUartData( m_sLRF_DATA.uart_id ); + if( tUART!= NULL ) { + m_bPortType = tUART->type; + free( tUART ); + }; + }; +}; + +void device2DSensor::cleanupDeviceStructures( void ){ + setWM( 0 ); + setWM( 0 ); // To prevent OWM keeping prev value + m_bDeviceWM = 0x00; + m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bInitialFlips = LGS_INITIAL_FLIPS; + m_nCurrentAngle = 0; + m_bDrawType = 0; + m_bOpRetryCnt = 3; + memset( m_tSN, 0, 33 ); + memset( m_tSV, 0, 65 ); + cleanShadowStructs(); + if (m_sGetFileHelper.fd!= NULL ) { + fclose( m_sGetFileHelper.fd ); + }; + memset( &m_sGetFileHelper, 0, sizeof(GETFILE_IO_HELPER)); + m_bSerialStringValid = false; + m_bVersionStringValid = false; +}; + +void device2DSensor::cleanShadowStructs(){ + if ( m_sShadow.pPolygones ) { + for (int i = 0; i < m_sShadow.m_nPolygonCount; i++) if (m_sShadow.pPolygones[i].pPoint) free( m_sShadow.pPolygones[i].pPoint ); + free(m_sShadow.pPolygones); + }; + for (int i = 0; i < 360; i++) if (m_sShadow.ray_lines[i].rays) free(m_sShadow.ray_lines[i].rays ); + memset(&m_sShadow, 0, sizeof(SHADOW)); + memset(&m_sShadowHelper, 0, sizeof(SHADOW_IO_HELPER)); +}; + +device2DSensor::~device2DSensor(){ +#ifdef DEBUG + LOG("Stoping Service"); +#endif + stopService(); +#ifdef DEBUG + LOG("Service is Stoped"); +#endif + if( m_pPort != NULL ) { + // Do Nothing here - HW manager handles resources +#ifdef DEBUG_EXTRA + } else { + LOG_ERROR("No Transport Assigned!"); +#endif + }; +}; + +bool device2DSensor::startService() { + if( m_sLRF_DATA.id == 0 ){ + LOG_ERROR("No DATA From Database!"); + return false; + }; + if( setDeviceID( m_sLRF_DATA.device_id ) ){ + if( !create() ){ + LOG_ERROR("Protocol <<< Create >>> Failure!"); + return false; + }; + }; + if( m_sLRF_DATA.filter_id > 0 ) { +#ifdef DEBUG + LOG("DEFINED FILTER"); +#endif + kernelPrototype *AK = kernelPrototype::getInstance(); + if( AK==NULL ){ + LOG_ERROR("KERNEL <<< GRAB >>> Failure!"); + return false; + }; + m_pTargetFilter = AK->getFilter( m_sLRF_DATA.filter_id ); + }; + return init(); +}; + +bool device2DSensor::stopService() { + LOG( "Kiling Thread"); + waitThreadEnd( true ); + LOG( "Thread is Dead!"); + m_pDBC->setNodeOffline( m_sNodeData.node_id ); + LOG( "Start Clenup Structs!"); + cleanupDeviceStructures(); + LOG( "Clenup Structs Done!"); + return true; +}; + +bool device2DSensor::validate(){ + if( m_pDBC == NULL ) return false; + DBC_PUSHED_CMD *tCMD = m_pDBC->getNodePushedCMD(m_sNodeData.node_id); + if ( tCMD!= NULL ) { + m_pDBC->updateNodePushedCMD( tCMD->id, DBC_CMD_STARTED ); + switch( tCMD->CMD ){ + case ARGUS_LRF_PCMD_FULL_RESET:{ +#ifdef DEBUG + LOG("Full Reset Push CMD!"); +#endif + NI_COMMAND *tNCMD = (NI_COMMAND *) malloc( sizeof(NI_COMMAND)); + if (tNCMD) { + tNCMD->cmd = NODE_CMD_FULL_RESET; + tNCMD->db_cmd = tCMD->id; + tNCMD->parameter = NULL; + enqueueCommand( tNCMD ); + }; + break; + }; + case ARGUS_LRF_PCMD_RESET:{ +#ifdef DEBUG + LOG("Small Reset Push CMD!"); +#endif + NI_COMMAND *tNCMD = (NI_COMMAND *) malloc( sizeof(NI_COMMAND)); + if (tNCMD) { + tNCMD->cmd = NODE_CMD_RESET_STUDY; + tNCMD->db_cmd = tCMD->id; + tNCMD->parameter = NULL; + enqueueCommand( tNCMD ); + }; + break; + }; + case ARGUS_LRF_PCMD_DRAW:{ +#ifdef DEBUG + LOG("Get Draw Push CMD!"); +#endif + NI_COMMAND *tNCMD = (NI_COMMAND *) malloc( sizeof(NI_COMMAND)); + if (tNCMD) { + tNCMD->cmd = NODE_CMD_GET_DEVICE_DRAW; + tNCMD->db_cmd = tCMD->id; + tNCMD->parameter = NULL; + enqueueCommand( tNCMD ); + }; + break; + }; + case ARGUS_LRF_PCMD_SET_DP_0:{ + NI_COMMAND *tNCMD = (NI_COMMAND *) malloc( sizeof(NI_COMMAND)); + if (tNCMD) { + tNCMD->cmd = NODE_CMD_UPLOAD_SETTINGS_0; + tNCMD->db_cmd = tCMD->id; + tNCMD->parameter = NULL; + enqueueCommand( tNCMD ); + }; + break; + }; + case ARGUS_LRF_PCMD_SET_DP_1:{ + NI_COMMAND *tNCMD = (NI_COMMAND *) malloc( sizeof(NI_COMMAND)); + if (tNCMD) { + tNCMD->cmd = NODE_CMD_UPLOAD_SETTINGS_1; + tNCMD->db_cmd = tCMD->id; + tNCMD->parameter = NULL; + enqueueCommand( tNCMD ); + }; + break; + }; + case ARGUS_LRF_PCMD_SET_DP_2:{ + NI_COMMAND *tNCMD = (NI_COMMAND *) malloc( sizeof(NI_COMMAND)); + if (tNCMD) { + tNCMD->cmd = NODE_CMD_UPLOAD_SETTINGS_2; + tNCMD->db_cmd = tCMD->id; + tNCMD->parameter = NULL; + enqueueCommand( tNCMD ); + }; + break; + }; + case ARGUS_LRF_PCMD_SET_DP_3:{ + NI_COMMAND *tNCMD = (NI_COMMAND *) malloc( sizeof(NI_COMMAND)); + if (tNCMD) { + tNCMD->cmd = NODE_CMD_UPLOAD_SETTINGS_3; + tNCMD->db_cmd = tCMD->id; + tNCMD->parameter = NULL; + enqueueCommand( tNCMD ); + }; + break; + }; + case ARGUS_LRF_PCMD_UPLOAD_FILE:{ +#ifdef DEBUG + LOG("Upload File CMD!"); +#endif + uint16_t sz = strlen(tCMD->PARAM); + if( sz ){ + NI_COMMAND *tNCMD = (NI_COMMAND *)malloc(sizeof(NI_COMMAND)); + if( tNCMD ){ + tNCMD->cmd = NODE_CMD_UPLOAD_FILE; + tNCMD->db_cmd = tCMD->id; + tNCMD->parameter = malloc( sz+1 ); + if ( tNCMD->parameter != NULL ) { + memcpy(tNCMD->parameter, tCMD->PARAM, sz); + ((uint8_t *)tNCMD->parameter)[sz] = 0; + enqueueCommand( tNCMD ); + } else { + free( tNCMD ); + }; + }; + }; + break; + }; + case ARGUS_LRF_ROI_ACTIVATION:{ +#ifdef DEBUG + LOG("ROI Cam Move!"); +#endif + uint16_t sz = strlen(tCMD->PARAM); + if( sz ){ + //NODE_COMMAND *tNCMD = (NODE_COMMAND *)malloc(sizeof(NODE_COMMAND)); + //if( tNCMD ){ + // tNCMD->cmd = NODE_CMD_ROI_ACTIVE; + // tNCMD->db_cmd = tCMD->id; + // tNCMD->parameter = malloc( sizeof( ROI_CMD_DATA ) ); + // if ( tNCMD->parameter != NULL ) { + // memset( tNCMD->parameter, 0, sizeof( ROI_CMD_DATA ) ); + // ((ROI_CMD_DATA *)tNCMD->parameter)->az_d = atoi( tCMD->PARAM ); + // ((ROI_CMD_DATA *)tNCMD->parameter)->az_d = atoi( strstr(tCMD->PARAM,":") + 1 ); + // //((ROI_CMD_DATA *)tNCMD->parameter)->el_d + // enqueueCommand( tNCMD ); + // } else { + // free( tNCMD ); + // }; + //}; + + uint16_t AZ, RANGE, WIDTH; + uint8_t LRFID = 0; + AZ = atoi(strstr(tCMD->PARAM, ":") + 1) - m_sLRF_DATA.base_shift; + RANGE = atoi( tCMD->PARAM ); + WIDTH = 8888; +#ifdef DEBUG + char tBuff[128]; + sprintf( tBuff, "ROI AZ: %d RANGE: %d WIDTH: %d", AZ, RANGE, WIDTH ); + LOG( tBuff ); +#endif + EVENT_CONTAINER * bEVT = NULL; + TARGET_DATA * tData = prepareTargetData( AZ, RANGE, WIDTH, LRFID ); + + bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_ROI_ACTIVE, NULL, NULL, tData ); + if( bEVT != NULL ) { + m_pEventHeap->broadcast(bEVT); + } else { + free( tData ); + }; + + }; + break; + }; + case ARGUS_LRF_PUSH_FALSE_TARGET:{ +#ifdef DEBUG + LOG("Simulate Target by Command!"); +#endif + break; + }; + case NODE_CMD_UPDATE_SHADOW:{ + LOG("Update Shadow CMD!"); + if (tCMD->CMD) m_nProcessingCmdId = tCMD->id; else m_nProcessingCmdId = 0; + cleanShadowStructs(); + if( m_pDBC->fillShadow2D( m_sNodeData.aux_id, m_sShadow ) ){ + LOG("Loadded From DB"); + if( rasterizeShadow() ){ + LOG("Mask is Rasterized"); + setWM( ANODE_WM_2D_SET_MASK_INFO ); + }; + }; + break; + }; + default: + m_pDBC->updateNodePushedCMD( tCMD->id, DBC_CMD_FINISHED ); + }; + free(tCMD); + }; + return true; +}; + +void device2DSensor::m_fThreadProc( void ){ + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ){ + + if( getConnectionStatus() != CS_CONNECTED ) setWM( ANODE_WM_2D_CREATE_PORT ); + + switch( getWM() ) { + // Physical Connection Channel + case ANODE_WM_2D_CREATE_PORT:{ + //kernelPrototype *AK = kernelPrototype::getInstance(); + m_pDBC->setNodeOffline( m_sNodeData.node_id ); + m_bInitialFlips = LGS_INITIAL_FLIPS; + //if( AK != NULL ) { + hardwareManager *tHM = hardwareManager::getInstance();//AK->getHardwareManager(); + if( tHM != NULL ) { + hardwareResource *tRES = tHM->requestResource( HARDWARE_PROVIDER_SERIAL, m_sLRF_DATA.uart_id ); + if( tRES != NULL ) { + if( tRES->isValid()) { + m_pPort = static_cast(static_cast(tRES)); +#ifdef DEBUG + //Bind To Proto + char tB[64]; + sprintf( tB, "PortOBJ: %p", m_pPort ); + LOG( tB ); +#endif + if( !setTransport( m_pPort, false )){ + LOG_ERROR("Binding Port Failure!"); + } else { +#ifdef DEBUG + LOG("Port Bind Sucessfully Done"); +#endif + m_bDeviceWM = 0x00; + setWM( ANODE_WM_2D_CONNECT ); + break; + }; + }; +#ifdef DEBUG + } else { + char tB[256]; + sprintf( tB, "HWM Has No UART PORT[%d]!", m_sLRF_DATA.uart_id ); + LOG( tB ); +#endif + }; + } else { + LOG_ERROR("Can not access Hardware Manager"); + }; + //} else { + // LOG_ERROR("Can not access Kernel"); + //}; + setTransport( NULL, false ); + SLEEP( 500 ); + break; + }; + // Logical Connection Checking + case ANODE_WM_2D_CONNECT:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if( !getMode() ) { + //m_pDBC->setNodeOffline( m_sNodeData.node_id ); + setWM( ANODE_WM_2D_CREATE_PORT ); + LOG_ERROR("Fall Back to Disconnected!"); + } else { + // Cleanup Current data; + LOG("BCS"); + cleanupDeviceStructures(); + LOG("ACS"); + setWM( ANODE_WM_2D_WAIT_CONNECT ); + }; + break; + }; + case ANODE_WM_2D_WAIT_CONNECT:{ + if(( m_bTimeOutCounter-- )==0 ){ + m_pDBC->setNodeOffline( m_sNodeData.node_id ); + setWM( ANODE_WM_2D_CONNECT ); + LOG_ERROR("Communication TO!"); + }; + break; + }; + case ANODE_WM_2D_SET_INIT_MODE:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if( !setMode(MODE_DETECTOR) ) { + m_pDBC->setNodeOffline( m_sNodeData.node_id ); + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_GET_SERIAL_NUM:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if( !getSerialNumber() ) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_GET_VERSION:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if( !getVersionString() ) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_GET_DETECTION_PROFILE:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if( !getDetectionProfile() ) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_GET_MASTER_PARAM:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if( m_sLRF_DATA.force_settings ) { + PLGS_2D_PARAMETERS chDATA = m_pDBC->getLRFDetectionProfile(m_sLRF_DATA.id, m_nActiveDetectionProfile, true ); + if ( chDATA == NULL ){ + if( !getParameters( true ) ) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + } else { + free( chDATA ); + if( m_sNodeData.type == ARGUS_ALS_SENSOR ) { + setWM(ANODE_WM_2D_GET_SLAVE_PARAM); + } else { + setWM( ANODE_WM_2D_SET_MASTER_PARAM ); + }; + }; + } else { + if( !getParameters( true ) ) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + }; + break; + }; + case ANODE_WM_2D_GET_SLAVE_PARAM:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if( m_sLRF_DATA.force_settings ){ + PLGS_2D_PARAMETERS chDATA = m_pDBC->getLRFDetectionProfile(m_sLRF_DATA.id, m_nActiveDetectionProfile, false ); + if ( chDATA == NULL ){ + if( !getParameters( false ) ) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + } else { + free( chDATA ); + setWM( ANODE_WM_2D_SET_MASTER_PARAM ); + }; + } else { + if( !getParameters( false ) ) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + }; + break; + }; + //Masks! + case ANODE_WM_2D_GET_MASK_INFO:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if( !getShadowInfo() ) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_GET_SHADOW_POLY_INFO:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if (!getShadowPoly( m_sShadowHelper.m_nCurrentPolygon )) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_GET_SHADOW_POLY_POINT:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if (!getShadowPolyPoint(m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint)) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_SET_MASK_INFO:{ + if (!setShadowInfo( m_sShadow )) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_SET_SHADOW_POLY_INFO:{ + if(!setShadowPoly(m_sShadow, m_sShadowHelper.m_nCurrentPolygon)){ + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else{ + setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + //while( m_bWM == ANODE_WM_2D_WAIT_DEVICE_REPLAY ) SLEEP(1); + //continue; + }; + break; + }; + case ANODE_WM_2D_SET_SHADOW_POLY_POINT:{ + if (!setShadowPolyPoint(m_sShadow, m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint)) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else{ + setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + //while( m_bWM == ANODE_WM_2D_WAIT_DEVICE_REPLAY ) SLEEP(1); + //continue; + }; + break; + }; + case ANODE_WM_2D_SET_SHADOW_RAY_LINE:{ + if (!setShadowRayLine(m_sShadow, m_sShadowHelper.m_nCurrentRayLine )) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else { + setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + //while( m_bWM == ANODE_WM_2D_WAIT_DEVICE_REPLAY ) SLEEP(1); + //continue; + }; + break; + }; + case ANODE_WM_2D_SET_SHADOW_RAY:{ + if (!setShadowRay(m_sShadow, m_sShadowHelper.m_nCurrentRayLine, m_sShadowHelper.m_nCurrentRay )) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else { + setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + //while( m_bWM == ANODE_WM_2D_WAIT_DEVICE_REPLAY ) SLEEP(1); + //continue; + }; + break; + }; + case ANODE_WM_2D_SET_SHADOW_DONE:{ + if (!setShadowDone()) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_SET_GETFILE_MODE:{ + if (!setMode( MODE_GETFILE )) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_SEND_GETFILE_MODE:{ + switch( m_sGetFileHelper.state ) { + case GF_OP_OK:{ + m_sGetFileHelper.fd = fopen( m_sGetFileHelper.sourceName, "rb" ); + if ( m_sGetFileHelper.fd ) { + m_sGetFileHelper.state = GF_OP_OPEN; + m_sGetFileHelper.data_size = strlen(m_sGetFileHelper.destName); + memcpy( m_sGetFileHelper.data, m_sGetFileHelper.destName, m_sGetFileHelper.data_size ); + } else { + memset( &m_sGetFileHelper, 0, sizeof( GETFILE_IO_HELPER )); + setWM( ANODE_WM_2D_SET_DETECTION_MODE ); + continue; + }; + break; + }; + case GF_OP_OPEN:{ + m_sGetFileHelper.state = GF_OP_DATA; + m_sGetFileHelper.data_size = fread(m_sGetFileHelper.data, 1, 250, m_sGetFileHelper.fd); + break; + }; + case GF_OP_DATA:{ + m_sGetFileHelper.data_size = fread(m_sGetFileHelper.data, 1, 250, m_sGetFileHelper.fd); + if ( m_sGetFileHelper.data_size == 0 || feof( m_sGetFileHelper.fd )) { + m_sGetFileHelper.state = GF_OP_CLOSE; + continue; + }; + break; + }; + case GF_OP_CLOSE:{ + m_sGetFileHelper.data_size = 0; + fclose( m_sGetFileHelper.fd ); + break; + }; + }; + if ( !sendGF_package( m_sGetFileHelper.state, m_sGetFileHelper.data_size, m_sGetFileHelper.data )) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_SET_BORDER_MODE:{ + m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; + if( !setMode( MODE_BORDER )){ + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_GET_FAST_DRAW:{ + if( m_bDeviceWM != MODE_BORDER ) { + setWM( ANODE_WM_2D_SET_BORDER_MODE ); + } else { + m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; + if( !getFastDraw( m_nCurrentAngle ) ) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else { + m_nSleepTime = LGS_ALERT_SLEEP_TIME; + setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + }; + } + break; + }; + case ANODE_WM_2D_SET_DETECTION_MODE:{ + m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; + if( !setMode(MODE_DETECTOR)) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_SET_FILESYSTEM_MODE:{ + if( !setMode(MODE_FILESYSTEM)) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_FS_TRANSFER_MODE:{ + + break; + }; + // Special Mode - Push COMMMANDS + case ANODE_WM_2D_SET_MASTER_PARAM:{ + PLGS_2D_PARAMETERS tData = m_pDBC->getLRFDetectionProfile( m_sNodeData.aux_id, m_nActiveDetectionProfile, true ); + if ( tData ) { + if (!setParameters( tData, true, m_nActiveDetectionProfile)) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + free( tData ); + } else setWM( ANODE_WM_2D_PING ); + break; + }; + case ANODE_WM_2D_SET_SLAVE_PARAM:{ + PLGS_2D_PARAMETERS tData = m_pDBC->getLRFDetectionProfile( m_sNodeData.aux_id, m_nActiveDetectionProfile, false ); + if ( tData ) { + if (!setParameters( tData, false, m_nActiveDetectionProfile)) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + free( tData ); + } else setWM( ANODE_WM_2D_PING ); + break; + }; + case ANODE_WM_2D_ISSUE_FULL_RESET:{ + if( !doFullReset()) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_ISSUE_RESET:{ + if( !doReset()) { + LOG_ERROR("Fall Back to Disconnected!"); + setWM( ANODE_WM_2D_CREATE_PORT ); + } else setWM( ANODE_WM_2D_WAIT_DEVICE_REPLAY ); + break; + }; + case ANODE_WM_2D_WAIT_DEVICE_REPLAY: + m_bOpRetryCnt = 10; + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + setWM( ANODE_WM_2D_WAIT_CHECK_REPLAY ); + // going directly through -> ANODE_WM_2D_WAIT_CHECK_REPLAY + // break; + case ANODE_WM_2D_WAIT_CHECK_REPLAY:{ + if(( --m_bTimeOutCounter )==0 ){ +#ifdef DEBUG_EXTRA + LOG_ERROR("Communication TO!"); +#endif + if( --m_bOpRetryCnt ){ + setBackOWM(); + } else { + setWM( ANODE_WM_2D_CONNECT );//ANODE_WM_2D_CREATE_PORT ); + }; + }; + break; + }; + // Idle Work + case ANODE_WM_2D_PING:{ + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + if( NI_COMMAND * tCMD = fetchCommand() ) { +#ifdef DEBUG + LOG("fetched cmd"); +#endif + switch( tCMD->cmd ) { + case NODE_CMD_FULL_RESET:{ + if( tCMD->db_cmd ) m_nProcessingCmdId = tCMD->db_cmd; else m_nProcessingCmdId = 0; + setWM(ANODE_WM_2D_ISSUE_FULL_RESET); + break; + }; + case NODE_CMD_RESET_STUDY:{ + if( tCMD->db_cmd ) m_nProcessingCmdId = tCMD->db_cmd; else m_nProcessingCmdId = 0; + setWM( ANODE_WM_2D_ISSUE_RESET ); + break; + }; + case NODE_CMD_UPLOAD_FILE:{ + if( tCMD->db_cmd ) m_nProcessingCmdId = tCMD->db_cmd; else m_nProcessingCmdId = 0; + m_nUploadID = atoi( (CSTR) tCMD->parameter ); + //m_sCurrentFile, m_pDBC->get + break; + }; + case NODE_CMD_GET_DEVICE_DRAW:{ + if( tCMD->db_cmd ) m_nProcessingCmdId = tCMD->db_cmd; else m_nProcessingCmdId = 0; + setWM( ANODE_WM_2D_SET_BORDER_MODE ); + break; + }; + case NODE_CMD_UPLOAD_SETTINGS_0:{ + if( tCMD->db_cmd ) m_nProcessingCmdId = tCMD->db_cmd; else m_nProcessingCmdId = 0; + m_nActiveDetectionProfile = 0; + setWM( ANODE_WM_2D_SET_MASTER_PARAM ); + break; + }; + case NODE_CMD_ROI_ACTIVE:{ + uint16_t AZ, RANGE, WIDTH; + uint8_t LRFID = 0; + AZ = ((ROI_CMD_DATA *)tCMD->parameter)->az_d; + RANGE = ((ROI_CMD_DATA *)tCMD->parameter)->r_d; + WIDTH = 8888; +#ifdef DEBUG + char tBuff[128]; + sprintf( tBuff, "ROI AZ: %d RANGE: %d WIDTH: %d", AZ, RANGE, WIDTH ); + LOG( tBuff ); +#endif + EVENT_CONTAINER * bEVT = NULL; + TARGET_DATA * tData = prepareTargetData( AZ, RANGE, WIDTH, LRFID ); + + bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_ROI_ACTIVE, NULL, NULL, tData ); + if( bEVT != NULL ) { + m_pEventHeap->broadcast(bEVT); + } else { + free( tData ); + }; + break; + }; + }; + if( tCMD->parameter ) free( tCMD->parameter ); + free( tCMD ); + } else { + if( !getState2() ) { + LOG_ERROR("Fall Back to getState1!"); + setWM( ANODE_WM_2D_CONNECT ); + } else { + setWM( ANODE_WM_2D_PONG ); + }; + }; + break; + }; + case ANODE_WM_2D_PONG:{ + //Wait ACK + if((m_bTimeOutCounter--)==0){ + if( m_bOpRetryCnt-- ){ + setWM( ANODE_WM_2D_PING ); + } else { + LOG_ERROR("Communication TO!"); + setWM( ANODE_WM_2D_CONNECT ); + }; + }; + break; + }; + case ANODE_WM_2D_SLEEP_AND_RECONNECT:{ + if(( m_bTimeOutCounter-- )==0 ){ + LOG_ERROR("Going Reconnect Device after while!"); + setWM( ANODE_WM_2D_CONNECT ); + }; + }; + }; + SLEEP( m_nSleepTime ); + validate(); + }; +}; + +#define SIZE_IDX 1 +#define DEV_ID_IDX 2 +#define CMD_IDX 3 +#define SUB_CMD_IDX 4 +#define DATA_BEGIN_IDX 5 + +#define PRINTOUT {for( int z=0; z < Package->m_nSize; z++ ) { \ + sprintf( tBuff, "P[%d]:0x%02X", z, Package->m_pData[z]); \ + LOG( tBuff ); \ + };} + + +bool device2DSensor::packetHandler( protocolPackage *Package ){ + uint8_t cDeviceID = Package->m_pData[DEV_ID_IDX]; + if( ( cDeviceID == m_sLRF_DATA.device_id ) || ( m_sLRF_DATA.device_id == 0 ) ) { +#ifdef DEBUG + char tBuff[256]; + #ifdef DEBUG_EXTRA + LOG("Device Reply"); + sprintf( tBuff, "Code 0x%02X",Package->m_pData[CMD_IDX] ); + LOG( tBuff ); + #endif +#endif + + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + switch( Package->m_pData[CMD_IDX] ) { + case CMD_STATE:{ +#ifdef DEBUG + LOG("CMD State"); +#endif + // Set Node Online! + m_pDBC->setNodeOnline( m_sNodeData.node_id, NODE_STATUS_WORK ); + if ( m_bDeviceIsSynced ) { + setWM( ANODE_WM_2D_PING ); + } else { + setWM( ANODE_WM_2D_GET_MASTER_PARAM ); + }; + break; + }; + case CMD_QUIT:{ + setWM( ANODE_WM_2D_PING ); + break; + }; + case CMD_RESET:{ + //Clean Targets + m_pDBC->cleanNodeEvents( m_sNodeData.node_id ); + setWM( ANODE_WM_2D_PING ); + break; + }; + case CMD_BORDER:{ + //if( m_bOWM == ANODE_WM_2D_GET_FAST_DRAW ){ + m_bOpRetryCnt = 3; + if ((Package->m_pData[SUB_CMD_IDX] & BD_ERRORMASK) == 0x00) { + uint16_t AZ; + uint16_t RANGE_A; + uint16_t RANGE_B; + AZ = ( ( ( Package->m_pData[SUB_CMD_IDX] & 0x10 ) >> 4 ) << 8 ) | Package->m_pData[5]; + RANGE_A = ( ( ( Package->m_pData[SUB_CMD_IDX] & 0x0C ) >> 2 ) << 8 ) | Package->m_pData[6]; + RANGE_B = ( ( Package->m_pData[SUB_CMD_IDX] & 0x03 ) << 8 ) | Package->m_pData[7]; + if( AZ < 359 ) { + m_vDrawRanges[m_nCurrentAngle]=( RANGE_A << 16 ) | RANGE_B; + m_nCurrentAngle = AZ+1; + setWM( ANODE_WM_2D_GET_FAST_DRAW ); + if( m_nProcessingCmdId ){ + m_pDBC->updateNodePushedCMD( m_nProcessingCmdId, (( ( 100 * AZ ) / 360 ) - 1 ) | 1 ); + m_nProcessingCmdId = 0; + }; + } else { + // Store Draw + m_nCurrentAngle = 0; + setWM( ANODE_WM_2D_SET_DETECTION_MODE ); + handleDeviceDraw( 0, (void *)m_vDrawRanges, 360 * sizeof(uint32_t) ); + if( m_nProcessingCmdId ){ + m_pDBC->updateNodePushedCMD(m_nProcessingCmdId, 100 ); + m_nProcessingCmdId = 0; + }; + }; + } else { + switch((Package->m_pData[SUB_CMD_IDX] & BD_ERRORMASK)){ + case BD_NOTREADY: { + // Data Not Ready + m_nCurrentAngle = 0; + //check WM + setWM( ANODE_WM_2D_GET_FAST_DRAW ); + break; + }; + case BD_ERRORANGLE:{ + // Error Requested Angle + setWM( ANODE_WM_2D_PING ); + break; + }; + case BD_ERRORMODE:{ + setWM( ANODE_WM_2D_PING ); + break; + }; + }; + }; + //} else { + // LOG("ERR Wrong Mode!"); + // setWM( ANODE_WM_2D_SET_DETECTION_MODE ); + // m_nCurrentAngle = 0; + //}; + break; + }; + case CMD_MODE:{ + m_bDeviceWM = Package->m_pData[SUB_CMD_IDX]; + uint8_t tCWD = getWM(); +#ifdef DEBUG + sprintf( tBuff, "Working Mode:0x%02X Real Mode:0x%02X Virtual Mode:0x%02X", tCWD, getWM(), m_bDeviceWM ); + LOG( tBuff ); +#endif + switch( getOWM() ) { + case ANODE_WM_2D_CONNECT:{ + // Initial Connection + m_pDBC->setNodeOnline( m_sNodeData.node_id, NODE_STATUS_INIT ); + if( m_bDeviceWM != MODE_DETECTOR ) { + setWM( ANODE_WM_2D_SET_INIT_MODE ); + } else { + setWM( ANODE_WM_2D_GET_SERIAL_NUM ); + }; + break; + }; + case ANODE_WM_2D_SET_INIT_MODE:{ + if( m_bDeviceWM != MODE_DETECTOR ) { + setWM( ANODE_WM_2D_SET_INIT_MODE ); + } else { + setWM( ANODE_WM_2D_GET_SERIAL_NUM ); + }; + break; + }; + case ANODE_WM_2D_SET_BORDER_MODE:{ + if( m_bDeviceWM == MODE_BORDER ) { + m_nCurrentAngle = 0; + setWM( ANODE_WM_2D_GET_FAST_DRAW ); + //m_nSleepTime = LGS_ALERT_SLEEP_TIME; + } else { + setWM( ANODE_WM_2D_SET_BORDER_MODE ); + }; + break; + }; + case ANODE_WM_2D_SET_DETECTION_MODE:{ + if( m_bDeviceWM == MODE_DETECTOR ) { + setWM( ANODE_WM_2D_PING ); + m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; +#ifdef DEBUG + LOG("Return to Ping-Pong!"); +#endif + } else { + setWM( ANODE_WM_2D_SET_DETECTION_MODE ); + }; + break; + }; + case ANODE_WM_2D_SET_FILESYSTEM_MODE:{ + if( m_bDeviceWM == MODE_FILESYSTEM ) { + setWM( ANODE_WM_2D_FS_TRANSFER_MODE ); + m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; +#ifdef DEBUG + LOG("Start Transfer FS Data!"); +#endif + } else { + // Error? + setWM( ANODE_WM_2D_SET_FILESYSTEM_MODE ); + }; + break; + }; + case ANODE_WM_2D_SET_GETFILE_MODE:{ + if ( m_bDeviceWM == MODE_GETFILE ) { + if( m_sGetFileHelper.state == GF_OP_OK ) { + setWM( ANODE_WM_2D_SEND_GETFILE_MODE ); + } else { + setWM( ANODE_WM_2D_SET_DETECTION_MODE ); + }; + } else { + setWM( ANODE_WM_2D_SET_GETFILE_MODE ); + }; + break; + }; + }; + break; + }; + case CMD_GET_SERIAL_NUMBER:{ + uint8_t tSize = Package->m_pData[SUB_CMD_IDX + 1]; + memcpy( m_tSN, Package->m_pData + SUB_CMD_IDX + 2, tSize ); + m_tSN[tSize] = (char)0; +#ifdef DEBUG + LOG("CMD_GET_SERIAL_NUMBER"); + LOG( m_tSN ); +#endif + //Checking SN of actual connected device with one stored in database + //in case there is new device -> the SN in database will be updated + if( strncmp( m_sLRF_DATA.serial, m_tSN, tSize ) == 0 ) { + // Equal +#ifdef DEBUG + LOG("SN is OK"); +#endif + m_bSerialStringValid = true; + } else { + LOG_ERROR( m_sLRF_DATA.serial ); + LOG_ERROR("SN is INVALID!"); + LOG_ERROR( m_tSN ); + m_bSerialStringValid = false; + }; + + setWM( ANODE_WM_2D_GET_VERSION ); + break; + }; + case CMD_GET_SOFTWARE_VERSION:{ + uint8_t tSize = Package->m_pData[SUB_CMD_IDX]; + memcpy( m_tSV, Package->m_pData + SUB_CMD_IDX + 1, tSize ); + m_tSV[tSize] = (char)0; +#ifdef DEBUG + LOG("CMD_GET_SOFTWARE_VERSION"); + LOG( m_tSV ); +#endif + if( strncmp( m_sLRF_DATA.version, m_tSV, tSize ) == 0 ) { +#ifdef DEBUG + LOG("Version is OK"); +#endif + m_bVersionStringValid = true; + } else { + LOG_ERROR( m_sLRF_DATA.version ); + LOG_ERROR("Version is INVALID!"); + LOG_ERROR( m_tSV ); + m_bVersionStringValid = false; + }; + if( m_bVersionStringValid && m_bSerialStringValid ) { + // The Device is OK + setWM( ANODE_WM_2D_GET_DETECTION_PROFILE ); + m_pDBC->setNodeOnline( m_sNodeData.node_id, NODE_STATUS_WORK ); + } else { + m_sLRF_DATA.data_status = m_pDBC->getLRFDataStatus( m_sLRF_DATA.id ); + switch ( m_sLRF_DATA.data_status ) { + case ARGUS_DS_NONE:{ + // Go Sleep and Restart in 2 seconds + m_bVersionStringValid = false; + m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; + m_bTimeOutCounter = 6; // 2 sec + setWM( ANODE_WM_2D_SLEEP_AND_RECONNECT ); + + m_pDBC->addNotification( NM_DEVICE_MISTMATCH, NM_DISMISS_LEVEL_ADMIN, m_sNodeData.node_id ); + m_pDBC->setNodeOnline( m_sNodeData.node_id, NODE_STATUS_TROUBLE ); + break; + }; + case ARGUS_DS_CREATED: + case ARGUS_DS_GET_CONFIG:{ + //In case Init new Device - updating SN and Version + m_bVersionStringValid = true; + m_bSerialStringValid = true; + //proceed to next stage + setWM( ANODE_WM_2D_GET_DETECTION_PROFILE ); + + m_pDBC->updateLRFSerial( m_sLRF_DATA.id, m_tSN ); + m_pDBC->updateLRFVerison( m_sLRF_DATA.id, m_tSV ); + m_pDBC->setLRFDataStatus( m_sLRF_DATA.id, ARGUS_DS_VALID ); + //m_pDBC->setLRFDataStatus( m_sLRF_DATA.id, ARGUS_DS_GET_CONFIG ); + m_pDBC->setNodeOnline( m_sNodeData.node_id, NODE_STATUS_WORK ); + break; + }; + case ARGUS_DS_VALID: + case ARGUS_DS_CONF_MISTMATCH:{ + // Go Sleep and Restart in 2 seconds + m_bVersionStringValid = false; + m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; + m_bTimeOutCounter = 6; // 2 sec + setWM( ANODE_WM_2D_SLEEP_AND_RECONNECT ); + + m_pDBC->setLRFAltSerial( m_sLRF_DATA.id, m_tSN ); + m_pDBC->setLRFAltVerison( m_sLRF_DATA.id, m_tSV ); + m_pDBC->setLRFDataStatus( m_sLRF_DATA.id, ARGUS_DS_CONF_MISTMATCH ); + m_pDBC->addNotification( NM_DEVICE_MISTMATCH, NM_DISMISS_LEVEL_ADMIN, m_sNodeData.node_id ); + m_pDBC->setNodeOnline( m_sNodeData.node_id, NODE_STATUS_TROUBLE ); + break; + }; + }; + }; + break; + }; + case CMD_UNSUPPORTED:{ +#ifdef DEBUG + LOG("CMD_UNSUPPORTED"); +#endif + switch( getOWM() ) { + case ANODE_WM_2D_GET_DETECTION_PROFILE:{ + //m_bMultiProfileSupported = false; + m_nActiveDetectionProfile = 0; + setWM( ANODE_WM_2D_GET_MASTER_PARAM ); + break; + }; + default: + setWM( ANODE_WM_2D_PING ); + break; + }; + break; + }; + case CMD_PARAMETERS:{ + LOG("PARAMETERS"); + switch ( getOWM() ) { + case ANODE_WM_2D_SET_MASTER_PARAM: + LOG("SET MASTER ACK"); + setWM(ANODE_WM_2D_SET_SLAVE_PARAM); + break; + case ANODE_WM_2D_SET_SLAVE_PARAM: + LOG("SET SLAVE ACK"); + setWM(ANODE_WM_2D_PING); + break; + default:{ + LOG("FROM DEVICE"); + LGS_2D_PARAMETERS tParams; + bool bMaster = true; + + //RaspberyPi - not Intel - cannot copy + //memcpy( &tParams, Package->m_pData + DATA_BEGIN_IDX, sizeof( LGS_2D_PARAMETERS ) ); + tParams.nOrder = ( Package->m_pData[5] << 8 ) | Package->m_pData[6]; + tParams.nOffset = ( Package->m_pData[7] << 8 ) | Package->m_pData[8]; + tParams.nDelta = ( Package->m_pData[9] << 8 ) | Package->m_pData[10]; + tParams.nWidth = ( Package->m_pData[11] << 8 ) | Package->m_pData[12]; + tParams.nFlip = ( Package->m_pData[13] << 8 ) | Package->m_pData[14]; + tParams.nSun = ( Package->m_pData[15] << 8 ) | Package->m_pData[16]; + tParams.bSST = Package->m_pData[17]; +#ifdef DEBUG + if( Package->m_pData[SUB_CMD_IDX] == 0x80 ) LOG("CMD MASTER PARAMETERS"); else LOG("CMD SLAVE PARAMETERS"); + sprintf(tBuff, " SST:\t%d", tParams.bSST ); + LOG(tBuff); + sprintf(tBuff, " DELTA:\t%d", tParams.nDelta ); + LOG(tBuff); + sprintf(tBuff, " Flip:\t%d", tParams.nFlip ); + LOG(tBuff); + sprintf(tBuff, " OFFSET:\t%d", tParams.nOffset ); + LOG(tBuff); + sprintf(tBuff, " ORDER:\t%d", tParams.nOrder ); + LOG(tBuff); + sprintf(tBuff, " SUN:\t%d", tParams.nSun ); + LOG(tBuff); + sprintf(tBuff, " WIDTH:\t%d", tParams.nWidth ); + LOG(tBuff); +#endif + if( Package->m_pData[SUB_CMD_IDX] != 0x80 ) bMaster = false; + + if( m_sLRF_DATA.force_settings ){ + // Check if Settings Are Equal + PLGS_2D_PARAMETERS chDATA = m_pDBC->getLRFDetectionProfile( m_sLRF_DATA.id, m_nActiveDetectionProfile, bMaster ); + if ( chDATA == NULL ) { + // No Profile in DB -> Set Once! + m_pDBC->updateLRFDetectionProfile( m_sNodeData.aux_id, m_nActiveDetectionProfile, bMaster, tParams.nOrder, tParams.nOffset, tParams.nDelta, tParams.nWidth, tParams.nFlip, tParams.nSun, tParams.bSST ); + if( bMaster && m_sNodeData.type == ARGUS_ALS_SENSOR ){ + setWM( ANODE_WM_2D_GET_SLAVE_PARAM ); + } else { + setWM( ANODE_WM_2D_PING ); + }; + } else { + setWM( ANODE_WM_2D_PING ); + free( chDATA ); + }; + } else { + m_pDBC->updateLRFDetectionProfile( m_sNodeData.aux_id, m_nActiveDetectionProfile, bMaster, tParams.nOrder, tParams.nOffset, tParams.nDelta, tParams.nWidth, tParams.nFlip, tParams.nSun, tParams.bSST ); + if( bMaster ){ + if( m_sNodeData.type == ARGUS_ALS_SENSOR ){ + setWM( ANODE_WM_2D_GET_SLAVE_PARAM ); + } else { + setWM( ANODE_WM_2D_GET_MASK_INFO ); + }; + } else { + setWM( ANODE_WM_2D_GET_MASK_INFO ); + }; + }; + break; + }; + }; + break; + }; + case CMD_FULL_BORDER:{ +#ifdef DEBUG + LOG("CMD Full Draw"); +#endif + if( ( Package->m_pData[SUB_CMD_IDX] & 0x80 ) == 0x80 ) { + // Data Ready + uint16_t AZ; + uint16_t MASTER; + uint16_t SLAVE; + AZ = (( Package->m_pData[DATA_BEGIN_IDX] & 0x0F ) << 8 ) | Package->m_pData[6]; + MASTER = (( Package->m_pData[7] & 0x07 ) << 8 ) | Package->m_pData[8]; + SLAVE = (( Package->m_pData[7] & 0x70 ) << 4 ) | Package->m_pData[9]; + if( AZ == 6000 ) { + // Finished + setWM( ANODE_WM_2D_PING ); + }; + } else { + // Not Ready + }; + break; + }; + case CMD_FULL_RESET:{ + m_pDBC->cleanNodeEvents( m_sNodeData.node_id ); + setWM( ANODE_WM_2D_PING ); + break; + }; + case CMD_STATE_2:{ +#ifdef DEBUG + //LOG("CMD State 2"); +#endif + //Parsning sub commagds + uint8_t cIDX = SUB_CMD_IDX; +#ifdef DEBUG + //if( Package->m_nSize > 8 ) { + // sprintf( tBuff, "Pack Size: %d", Package->m_nSize ); + // LOG( tBuff ); + // PRINTOUT; + //}; +#endif + m_bOpRetryCnt = 3; + m_bDeviceIsSynced = true; // At this point all data structs must be synced! + setWM( ANODE_WM_2D_PING ); + m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; + while( Package->m_nSize > ( cIDX + 2 ) ) { + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + switch( Package->m_pData[cIDX+1] ) { + case 0x00:{ +#ifdef DEBUG + LOG("SUB PACKAGE - Intruder detected"); + sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); + LOG( tBuff ); +#endif + + uint16_t AZ, RANGE; + uint32_t WIDTH; + uint8_t LRFID = 0; + AZ = (( Package->m_pData[cIDX + 3] >> 3 ) << 8 ) | Package->m_pData[cIDX + 4]; + RANGE = (( Package->m_pData[cIDX + 3] & 0x07 ) << 8 ) | Package->m_pData[cIDX + 5]; + WIDTH = 8888; +#ifdef DEBUG_EXTRA + sprintf( tBuff, "AZ: %d RANGE: %d WIDTH: %d", AZ, RANGE, WIDTH ); + LOG( tBuff ); +#endif + EVENT_CONTAINER * bEVT = NULL; + TARGET_DATA * tData = prepareTargetData( AZ, RANGE, WIDTH, LRFID ); + if( m_pTargetFilter != NULL ) { + if( !m_pTargetFilter->validateTarget( m_sNodeData.node_id, tData ) ){ + free( tData ); + break; + }; + }; + bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_TARGET_2D_WHITE, NULL, NULL, tData ); + if( bEVT != NULL ) { + m_pEventHeap->broadcast(bEVT); + } else { + free( tData ); + }; + + + m_nSleepTime = LGS_ALERT_SLEEP_TIME; + cIDX += 6; + break; + }; + case 0x02:{ +#ifdef DEBUG_EXTRA + LOG("SUB PACKAGE - Maintenance notification"); + sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); + LOG( tBuff ); +#endif + cIDX += 3; + break; + }; + case 0x03:{ +#ifdef DEBUG + LOG("SUB PACKAGE - LRF problems notification"); + sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); + LOG( tBuff ); +#endif + cIDX += 4; + break; + }; + case 0x04:{ +#ifdef DEBUG + LOG("SUB PACKAGE - Error Angle notification"); + sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); + LOG( tBuff ); +#endif + cIDX += 4; + break; + }; + case 0x05:{ +#ifdef DEBUG_EXTRA + LOG("SUB PACKAGE - Flip Complete notification"); + sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); + LOG( tBuff ); +#endif + if( m_bInitialFlips ){ + m_bInitialFlips--; + } else { +#ifdef DEBUG_EXTRA + LOG("INITIAL FLIPS ARE DONE!"); +#endif + if ( ANODE_WM_2D_PING == getWM() ) { + if (m_sLRF_DATA.auto_draw > 0) { +#ifdef DEBUG_EXTRA + LOG("Start AutoDraw!"); +#endif + m_bInitialFlips = m_sLRF_DATA.auto_draw; + setWM( ANODE_WM_2D_SET_BORDER_MODE ); + m_nCurrentAngle = 0; + } else { +#ifdef DEBUG_EXTRA + LOG("No AutoDraw Defined!"); +#endif + }; + } else { + LOG_ERROR("Wrong WM Mode! (possible error in init process)"); + }; + }; + cIDX += 5; + break; + }; + case 0x06:{ +#ifdef DEBUG + LOG("SUB PACKAGE - System visibility changes"); + sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); + LOG( tBuff ); +#endif + cIDX += 4; + break; + }; + case 0x07:{ +#ifdef DEBUG_EXTRA + LOG("SUB PACKAGE - Intruder with Width detected"); + sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); + LOG( tBuff ); +#endif + uint16_t AZ, RANGE; + uint32_t WIDTH; + AZ = (( Package->m_pData[cIDX + 3] >> 3 ) << 8 ) | Package->m_pData[cIDX + 4]; + RANGE = (( Package->m_pData[cIDX + 3] & 0x07 ) << 8 ) | Package->m_pData[cIDX + 5]; + WIDTH = ( Package->m_pData[cIDX + 6] << 24 ) | ( Package->m_pData[cIDX + 7] << 16 ) | ( Package->m_pData[cIDX + 8] << 8 ) | Package->m_pData[cIDX + 9]; +#ifdef DEBUG_EXTRA + sprintf( tBuff, "AZ: %d RANGE: %d WIDTH: %d", AZ, RANGE, WIDTH ); + LOG( tBuff ); +#endif + EVENT_CONTAINER * bEVT = NULL; + TARGET_DATA * tData = prepareTargetData( AZ, RANGE, WIDTH ); + if( m_pTargetFilter != NULL ) { + if( !m_pTargetFilter->validateTarget( m_sNodeData.node_id, tData ) ){ + free( tData ); + break; + }; + }; + bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_TARGET_2D_WHITE, NULL, NULL, tData ); + if( bEVT != NULL ) { + m_pEventHeap->broadcast(bEVT); + } else { + free( tData ); + }; + + m_nSleepTime = LGS_ALERT_SLEEP_TIME; + cIDX += 10; + break; + }; + default:{ +#ifdef DEBUG + LOG("SUB PACKAGE - Unhandled One!"); + sprintf( tBuff, "Code: %d Sub Size: %d", Package->m_pData[cIDX+1], Package->m_pData[cIDX] ); + LOG( tBuff ); +#endif + cIDX += Package->m_pData[cIDX] + 3; + break; + }; + }; + }; + break; + }; + case CMD_FS_SUB_PACKET:{ + if( getWM() == ANODE_WM_2D_FS_TRANSFER_MODE ) { + } else { + }; + break; + }; + case CMD_GET_ACTIVE_PROFILE:{ + setWM( ANODE_WM_2D_GET_MASTER_PARAM ); + //m_bMultiProfileSupported = true; + m_nActiveDetectionProfile = 0; + break; + }; + case CMD_GET_HZ_DATA:{ + //HZ_PACKET tPack = (PHZ_PACKET) Package->m_pData + SUB_CMD_IDX; + switch( Package->m_pData[DATA_BEGIN_IDX] ) { + case HZIT_EVT_GET_HEADER:{ + HZ_EVT_GET_HEADER pC; + pC.bSubSize = Package->m_pData[SUB_CMD_IDX]; + pC.bType = Package->m_pData[DATA_BEGIN_IDX]; + pC.bSequence = Package->m_pData[DATA_BEGIN_IDX+1]; + pC.wPolygonCount = Package->m_pData[DATA_BEGIN_IDX+3]; + pC.wPolygonCount = ( pC.wPolygonCount << 8 ) | Package->m_pData[DATA_BEGIN_IDX+2]; + pC.wRayCount = Package->m_pData[DATA_BEGIN_IDX+5]; + pC.wRayCount = ( pC.wRayCount << 8 ) | Package->m_pData[DATA_BEGIN_IDX+4]; + pC.dwTypeOn = Package->m_pData[DATA_BEGIN_IDX+9]; + pC.dwTypeOn = ( pC.dwTypeOn << 8 ) | Package->m_pData[DATA_BEGIN_IDX+8]; + pC.dwTypeOn = ( pC.dwTypeOn << 8 ) | Package->m_pData[DATA_BEGIN_IDX+7]; + pC.dwTypeOn = ( pC.dwTypeOn << 8 ) | Package->m_pData[DATA_BEGIN_IDX+6]; +#ifdef DEBUG + sprintf( tBuff, "Poly Cnt: %d Ray Cnt: %d Status: 0x%04X", pC.wPolygonCount, pC.wRayCount, pC.dwTypeOn ); + LOG( tBuff ); +#endif + if ( pC.wPolygonCount ) { + cleanShadowStructs(); + m_sShadow.m_nEnabled = pC.dwTypeOn; + m_sShadow.pPolygones = (SHADOW_POLY *) calloc(pC.wPolygonCount,sizeof(SHADOW_POLY)); + if ( m_sShadow.pPolygones ) { + memset( m_sShadow.pPolygones, 0, pC.wPolygonCount*sizeof(SHADOW_POLY) ); + m_sShadow.m_nPolygonCount = pC.wPolygonCount; + setWM(ANODE_WM_2D_GET_SHADOW_POLY_INFO); + } else { + LOG_ERROR("Error Alocation Memory foe Shadow!"); + setWM( ANODE_WM_2D_PING ); + }; + } else { + setWM( ANODE_WM_2D_PING ); + }; + break; + }; + case HZIT_EVT_GET_POLYGON:{ + uint16_t wPointCount = Package->m_pData[DATA_BEGIN_IDX+4]; + wPointCount = ( wPointCount << 8 ) | Package->m_pData[DATA_BEGIN_IDX+3]; +#ifdef DEBUG + sprintf( tBuff, "Poly[%d] Info: Points %d type: %d", + m_sShadowHelper.m_nCurrentPolygon, + wPointCount, Package->m_pData[DATA_BEGIN_IDX+2] + ); + LOG( tBuff ); +#endif + if ( wPointCount ) { + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].bType = Package->m_pData[DATA_BEGIN_IDX+2]; + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint = (HZ_POINT*)calloc( wPointCount, sizeof(HZ_POINT)); + if ( m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint ) { + memset(m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint, 0, wPointCount*sizeof(HZ_POINT)); + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount = wPointCount; + m_sShadowHelper.m_nCurrentPoint = 0; + setWM( ANODE_WM_2D_GET_SHADOW_POLY_POINT ); + } else { + LOG_ERROR("Error Alloc Memory for Polygone points!"); + setWM(ANODE_WM_2D_PING); + }; + } else { + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint = NULL; + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount = 0; + if(m_sShadowHelper.m_nCurrentPolygon < m_sShadow.m_nPolygonCount ) { + m_sShadowHelper.m_nCurrentPolygon++; + setWM(ANODE_WM_2D_GET_SHADOW_POLY_INFO); + } else { + setWM(ANODE_WM_2D_PING); + }; + }; + break; + }; + case HZIT_EVT_GET_POLYGON_POINT:{ + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint[m_sShadowHelper.m_nCurrentPoint].wX = Package->m_pData[DATA_BEGIN_IDX+3]; + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint[m_sShadowHelper.m_nCurrentPoint].wX = (m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint[m_sShadowHelper.m_nCurrentPoint].wX << 8 ) | Package->m_pData[DATA_BEGIN_IDX+2]; + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint[m_sShadowHelper.m_nCurrentPoint].wY = Package->m_pData[DATA_BEGIN_IDX+5]; + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint[m_sShadowHelper.m_nCurrentPoint].wY = (m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint[m_sShadowHelper.m_nCurrentPoint].wY << 8 ) | Package->m_pData[DATA_BEGIN_IDX+4]; +#ifdef DEBUG + sprintf( tBuff, "PolyPoint[%d] of %d X: %d Y: %d", + m_sShadowHelper.m_nCurrentPoint, + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount, + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint[m_sShadowHelper.m_nCurrentPoint].wX, + m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].pPoint[m_sShadowHelper.m_nCurrentPoint].wY + ); + LOG( tBuff ); +#endif + m_sShadowHelper.m_nCurrentPoint++; + if( m_sShadowHelper.m_nCurrentPoint < m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount ) { + setWM( ANODE_WM_2D_GET_SHADOW_POLY_POINT ); + } else { +#ifdef DEBUG + LOG("Done Load Poly Points"); +#endif + m_sShadowHelper.m_nCurrentPolygon++; + if(m_sShadowHelper.m_nCurrentPolygon < m_sShadow.m_nPolygonCount ) { + setWM( ANODE_WM_2D_GET_SHADOW_POLY_INFO ); + } else { + for( uint8_t MaskLayer=0; MaskLayer < 5; MaskLayer++ ) { + uint32_t tMaskID = m_pDBC->getLRFMaskID( m_sLRF_DATA.id , 0, MaskLayer ); + if( tMaskID ) { + m_pDBC->cleanLRFMask( tMaskID, true ); + tMaskID = 0; + }; + for( uint8_t i = 0; i < m_sShadow.m_nPolygonCount; i++ ){ + if( m_sShadow.pPolygones[i].bType == MaskLayer ){ + if( m_sShadow.pPolygones[i].pPoint ){ + if( tMaskID == 0 ) { + tMaskID = m_pDBC->addLRFMask( m_sLRF_DATA.id, 0, MaskLayer ); + }; + if( tMaskID ) { + uint32_t tPolyID = 0; + switch( MaskLayer ) { + case 0: tPolyID = m_pDBC->addLRFMaskPolygone(tMaskID, 255, 0, 255); break; + case 1: tPolyID = m_pDBC->addLRFMaskPolygone(tMaskID, 255, 255, 0); break; + case 2: tPolyID = m_pDBC->addLRFMaskPolygone(tMaskID, 0, 255, 255); break; + case 3: tPolyID = m_pDBC->addLRFMaskPolygone(tMaskID, 0, 255, 0); break; + case 4: tPolyID = m_pDBC->addLRFMaskPolygone(tMaskID, 0, 0, 255); break; + default: tPolyID = m_pDBC->addLRFMaskPolygone(tMaskID, 0, 0, 0 ); break; + }; + if ( tPolyID ) { + for ( uint16_t k=0;k < m_sShadow.pPolygones[i].wCount; k++ ) { + m_pDBC->addLRFMaskPolygonePoint( + tPolyID, + m_sShadow.pPolygones[i].pPoint[k].wX, + m_sShadow.pPolygones[i].pPoint[k].wY + ); + }; + }; + }; + }; + }; + }; + if ( tMaskID ) { + m_pDBC->setLRFMaskStatus( tMaskID, ( m_sShadow.m_nEnabled & (1<m_pData[DATA_BEGIN_IDX] ); + LOG( tBuff ); +#endif + switch( Package->m_pData[DATA_BEGIN_IDX] ) { + case HZIT_EVT_SET_HEADER: + LOG("Header OK"); + memset( &m_sShadowHelper, 0, sizeof(SHADOW_IO_HELPER) ); + setWM( ANODE_WM_2D_SET_SHADOW_POLY_INFO ); + break; + case HZIT_EVT_SET_POLYGON: + LOG("Poligon Added OK"); + m_sShadowHelper.m_nCurrentPoint = 0; + setWM( ANODE_WM_2D_SET_SHADOW_POLY_POINT ); + break; + case HZIT_EVT_SET_POLYGON_POINT: + if (m_sShadowHelper.m_nCurrentPoint < (m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount - 1) ) { +#ifdef DEBUG + sprintf( tBuff,"Send Point %d of %d", (m_sShadowHelper.m_nCurrentPoint + 1), m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount ); + LOG( tBuff ); +#endif + m_sShadowHelper.m_nCurrentPoint++; + setWM( ANODE_WM_2D_SET_SHADOW_POLY_POINT ); + } else { + if (m_sShadowHelper.m_nCurrentPolygon < (m_sShadow.m_nPolygonCount - 1)) { +#ifdef DEBUG + sprintf(tBuff, "Send Polygon %d of %d", (m_sShadowHelper.m_nCurrentPolygon + 1), m_sShadow.m_nPolygonCount ); + LOG( tBuff ); +#endif + m_sShadowHelper.m_nCurrentPolygon++; + setWM( ANODE_WM_2D_SET_SHADOW_POLY_INFO ); + } else { +#ifdef DEBUG + LOG("Start Send Rays!"); +#endif + m_sShadowHelper.m_nCurrentRayLine = 0; + for( ; m_sShadowHelper.m_nCurrentRayLine < MAX_2D_SHADOW_RAY_LINES; m_sShadowHelper.m_nCurrentRayLine++ ) if( m_sShadow.ray_lines[m_sShadowHelper.m_nCurrentRayLine].nCount ) break; + if ( m_sShadowHelper.m_nCurrentRayLine < MAX_2D_SHADOW_RAY_LINES ) { +#ifdef DEBUG + sprintf( tBuff,"Send Ray Line %d of %d", ( m_sShadowHelper.m_nCurrentRayLine + 1 ), MAX_2D_SHADOW_RAY_LINES ); + LOG( tBuff ); +#endif + setWM(ANODE_WM_2D_SET_SHADOW_RAY_LINE); + } else { +#ifdef DEBUG + LOG("Skip Uploading Rays -> No Rays Detected!"); +#endif + setWM( ANODE_WM_2D_SET_SHADOW_DONE ); + }; + }; + }; + break; + case HZIT_EVT_SET_RAY: + LOG("Rey Line Added OK"); + m_sShadowHelper.m_nCurrentRay = 0; + setWM( ANODE_WM_2D_SET_SHADOW_RAY ); + break; + case HZIT_EVT_SET_RAY_LINE: + if( m_sShadowHelper.m_nCurrentRay < (m_sShadow.ray_lines[m_sShadowHelper.m_nCurrentRayLine].nCount-1)) { +#ifdef DEBUG + sprintf( tBuff,"Send Ray %d of %d", (m_sShadowHelper.m_nCurrentRay + 1), m_sShadow.ray_lines[m_sShadowHelper.m_nCurrentRayLine].nCount ); + LOG( tBuff ); +#endif + m_sShadowHelper.m_nCurrentRay++; + setWM( ANODE_WM_2D_SET_SHADOW_RAY ); + } else { + if (m_sShadowHelper.m_nCurrentRayLine < (MAX_2D_SHADOW_RAY_LINES-1) ) { + m_sShadowHelper.m_nCurrentRayLine++; + for( ; m_sShadowHelper.m_nCurrentRayLine < MAX_2D_SHADOW_RAY_LINES; m_sShadowHelper.m_nCurrentRayLine++ ) if( m_sShadow.ray_lines[m_sShadowHelper.m_nCurrentRayLine].nCount ) break; + if ( m_sShadowHelper.m_nCurrentRayLine < MAX_2D_SHADOW_RAY_LINES ) { +#ifdef DEBUG + sprintf( tBuff,"Send Ray Line %d of %d", ( m_sShadowHelper.m_nCurrentRayLine + 1 ), MAX_2D_SHADOW_RAY_LINES ); + LOG( tBuff ); +#endif + setWM(ANODE_WM_2D_SET_SHADOW_RAY_LINE); + } else { +#ifdef DEBUG + LOG("Finish Uploadding Rays!"); +#endif + setWM( ANODE_WM_2D_SET_SHADOW_DONE ); + }; + } else { + setWM( ANODE_WM_2D_SET_SHADOW_DONE ); + }; + }; + break; + case HZIT_EVT_SET_DONE: +#ifdef DEBUG + LOG("Cleanup!"); +#endif + memset( &m_sShadowHelper, 0, sizeof(SHADOW_IO_HELPER) ); + setWM( ANODE_WM_2D_PING ); + break; + case HZIT_EVT_ERROR:{ + HZ_EVT_ERROR pC; +#ifdef DEBUG + LOG("ERROR SET SHADOW PING_PONG!"); +#endif + setWM( ANODE_WM_2D_PING ); + break; + }; + }; + break; + }; + case CMD_GETFILE:{ + if( ( Package->m_pData[SUB_CMD_IDX] & GF_ERRORMASK ) != 0 ){ + if( ( Package->m_pData[SUB_CMD_IDX] & GF_ERRORMODE ) != 0 ){ + LOG_ERROR("Error: GF-Wrond WM!"); + }; + if( ( Package->m_pData[SUB_CMD_IDX] & GF_ERRORFILE ) != 0 ){ + LOG_ERROR("Error: GF-File Error!"); + }; + setWM( ANODE_WM_2D_PING ); + } else { + + }; + break; + }; + }; + }; + return true; +}; + +#undef PRINTOUT + + +TARGET_DATA *device2DSensor::prepareTargetData( uint16_t AZ, uint16_t RANGE, uint32_t WIDTH, uint8_t LRFID ){ + TARGET_DATA* tVal = NULL; + systemAnchor* tSystem = systemAnchor::getInstance(); + if( tSystem != NULL ) { + tVal = (TARGET_DATA*)malloc(sizeof(TARGET_DATA)); + if (tVal != NULL) { + uint16_t cX, cY; + memset( tVal, 0, sizeof(TARGET_DATA) ); + tVal->source_position.lat = m_oPosition.getLat(); + tVal->source_position.lon = m_oPosition.getLon(); + tVal->source_position.alt = m_oPosition.getAlt(); + tVal->local_target.r = m_sLRF_DATA.max_range / 2048.0f * (float)RANGE; + AZ = ( AZ + m_sLRF_DATA.base_shift ) % 6000; + //tVal->local_target.fi = 360.0f - (360.0f / 6000.0f) * (float) AZ; + tVal->local_target.tetta = 90.0f; + tVal->local_target.fi = (360.0f / 6000.0f) * (float) AZ; + tVal->area = WIDTH; + tVal->lrf_id = LRFID;//0; // Always Master? + tVal->digital = RANGE; + // local - C3D_SPH_DEGREES + // system - C3D_DECART + // global - C3D_WGS84_LOC + tSystem->convertToSystem( &m_oPosition, tVal->local_target, tVal->system_target ); + //ToDo: Fix Convert! + //tSystem->convertToGlobal( &m_oPosition, tVal->local_target, tVal->global_target ); + tSystem->convertToGlobal( &m_oPosition, tVal->system_target, tVal->global_target ); +#ifdef DEBUG + char tB[128]; + sprintf(tB, "tCords Local: %0.3f %0.3f %0.3f", tVal->local_target.r, tVal->local_target.fi, tVal->local_target.tetta ); + LOG( tB ); + sprintf(tB, "tCords System: %0.3f %0.3f %0.3f", tVal->system_target.x, tVal->system_target.y, tVal->system_target.z ); + LOG( tB ); + sprintf(tB, "tCords Global: %0.3f %0.3f %0.3f", tVal->global_target.lat, tVal->global_target.lon, tVal->global_target.alt ); + LOG( tB ); +#endif + }; + }; + return tVal; +}; + +void device2DSensor::simulateTarget( void ){ + uint16_t AZ, RANGE; + uint32_t WIDTH; + AZ = uint16_t ( rand() * ( 6000.0f /(float) RAND_MAX )); + RANGE = uint16_t ( rand() * ( 2048.0f /(float) RAND_MAX )); + WIDTH = 4000; + + + TARGET_DATA * tData = prepareTargetData( AZ, RANGE, WIDTH ); + + if( tData != NULL ){ + if( m_pTargetFilter != NULL ) { + if( !m_pTargetFilter->validateTarget( m_sNodeData.node_id, tData ) ){ + free( tData ); + return; + }; + }; + EVENT_CONTAINER * bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_TARGET_2D_WHITE, NULL, NULL, tData ); + if (bEVT != NULL) { + m_pEventHeap->broadcast( bEVT ); + }; + }; +}; + +/* +void device2DSensor::saveRawDrawData( uint16_t alngles ){ + CSTR tID = getUniqID_MD5(); + if( tID!= NULL ) { + char cPATH[256]; + FILE *fp; + sprintf( cPATH, "data/device_draws/%s.raw", tID ); + fp = fopen( cPATH, "wb"); + if( fp != NULL ) { + uint32_t tVal = alngles; + fwrite( &tVal, 4, 1, fp ); + fwrite( m_vDrawRanges, 4, alngles, fp ); + fclose( fp ); + m_pDBC->addLRFDraw( m_sNodeData.node_id, alngles, tID ); + } else { + LOG_ERROR("Cannot open DRAW file!"); + } + free( tID ); + }; +}; +*/ + +CSTR device2DSensor::generateSettingFile(){ + FILE * fd = NULL; + CSTR RetVal = getUniqID_MD5(); + if ( RetVal ) { + char tB[256]; + sprintf( tB,"data/uploads/%s", RetVal ); + fd = fopen( tB, "wb+" ); + if ( fd ) { + for ( int idx=0; idx < 13; idx++ ) { + switch( idx ){ + case 0: fprintf(fd, "%s=%d\r\n", settings_user_ini_fields[idx]); break; + }; + }; + fclose( fd ); + } else { + free( RetVal ); + RetVal = NULL; + }; + }; + return RetVal; +}; + + + +inline int DBL_CMP( const double& a, const double& b, const double quality = 1e-10 ){ + if( fabs(a - b) <= fabs(quality) ) return 0; + if( a > b ) return 1; + return -1; +}; + +typedef struct S_VERTEX{ + double x, y, r; + BOOL f; + int n; +}VERTEX, *PVERTEX; + +typedef struct S_SEGMENT{ + int pPoints[2]; + int nIndex; +}SEGMENT, *PSEGMENT; + +typedef struct S_SEGMENTS{ + PVERTEX pPoints; + int nCount; +}SEGMENTS, *PSEGMENTS; + +BOOL CrossProduct( PVERTEX ln0, PVERTEX ln1, PVERTEX pCross, bool fCheck0 = true, bool fCheck1 = true ){ +#undef B0 + double A0, A1, B0, B1, X, Y; + + if( DBL_CMP(ln0[0].x, ln0[1].x) == 0 ){ + A0 = DBL_MAX; + B0 = ln0[0].x; + } else { + A0 = (ln0[0].y - ln0[1].y) / (ln0[0].x - ln0[1].x); + B0 = ln0[0].y - A0 * ln0[0].x; + }; + if(DBL_CMP(ln1[0].x , ln1[1].x) == 0){ + A1 = DBL_MAX; + B1 = ln1[0].x; + } else { + A1 = (ln1[0].y - ln1[1].y) / (ln1[0].x - ln1[1].x); + B1 = ln1[0].y - A1 * ln1[0].x; + }; + if(A0 == DBL_MAX){ + if(A1 == DBL_MAX) return FALSE; + X = B0; + Y = A1 * X + B1; + } else { + if(A1 == DBL_MAX) X = B1; + else { + if(DBL_CMP( A1, A0 ) != 0) X = (B0 - B1) / (A1 - A0); else return FALSE; + }; + Y = A0 * X + B0; + }; + double y = Y, x = X; + if( fCheck0 ){ + double x0 = ln0[0].x, x1 = ln0[1].x; + double y0 = ln0[0].y, y1 = ln0[1].y; + if(DBL_CMP(y0, y1) == -1 && (DBL_CMP(y0, y) == 1 || DBL_CMP(y, y1) == 1)) return FALSE; + if(DBL_CMP(y0, y1) == 1 && (DBL_CMP(y0, y) == -1 || DBL_CMP(y, y1) == -1)) return FALSE; + if(DBL_CMP(x0, x1) == -1 && (DBL_CMP(x0, x) == 1 || DBL_CMP(x, x1) == 1)) return FALSE; + if(DBL_CMP(x0, x1) == 1 && (DBL_CMP(x0, x) == -1 || DBL_CMP(x, x1) == -1)) return FALSE; + }; + + if( fCheck1 ){ + double x0 = ln1[0].x, x1 = ln1[1].x; + double y0 = ln1[0].y, y1 = ln1[1].y; + if(DBL_CMP(y0, y1) == -1 && (DBL_CMP(y0, y) == 1 || DBL_CMP(y, y1) == 1)) return FALSE; + if(DBL_CMP(y0, y1) == 1 && (DBL_CMP(y0, y) == -1 || DBL_CMP(y, y1) == -1)) return FALSE; + if(DBL_CMP(x0, x1) == -1 && (DBL_CMP(x0, x) == 1 || DBL_CMP(x, x1) == 1)) return FALSE; + if(DBL_CMP(x0, x1) == 1 && (DBL_CMP(x0, x) == -1 || DBL_CMP(x, x1) == -1)) return FALSE; + }; + pCross->x = X; + pCross->y = Y; + return TRUE; +}; + +BOOL PtInLine( PVERTEX ln, VERTEX& p ){ + double A, B; + if(DBL_CMP(ln[0].x, ln[1].x) == 0){ + A = DBL_MAX; + B = ln[0].x; + } else { + A = (ln[0].y - ln[1].y) / (ln[0].x - ln[1].x); + B = ln[0].y - A * ln[0].x; + }; + + if(A == DBL_MAX) { + if( DBL_CMP(p.x, B) == 0) return TRUE; + } else { + if(DBL_CMP(p.x * A + B, p.y) == 0) return TRUE; + }; + return FALSE; +}; + +int comparePoints( const void *arg1, const void *arg2 ){ + if(((PVERTEX)arg1)->r > ((PVERTEX)arg2)->r) return +1; + if(((PVERTEX)arg1)->r < ((PVERTEX)arg2)->r) return -1; + return 0; +}; + +void AddPointToSegment( PSEGMENTS pSegments, int nIndex, PVERTEX pPoint){ + PVERTEX pNew = new VERTEX[pSegments[nIndex].nCount + 1]; + + memcpy( pNew, pSegments[nIndex].pPoints, sizeof(VERTEX) * pSegments[nIndex].nCount ); + memcpy( pNew + pSegments[nIndex].nCount, pPoint, sizeof(VERTEX)); + + if(pSegments[nIndex].pPoints) delete pSegments[nIndex].pPoints; + + pSegments[nIndex].pPoints = pNew; + pSegments[nIndex].nCount++; +}; + + +void StickSegments( PSEGMENTS pSegments, int nIndex ){ + if( pSegments[nIndex].nCount ){ + qsort( pSegments[nIndex].pPoints, pSegments[nIndex].nCount, sizeof(VERTEX), comparePoints ); + + PVERTEX pTemp = new VERTEX[pSegments[nIndex].nCount]; + PVERTEX pPoints = pSegments[nIndex].pPoints; + + int f, nT = 0; + pTemp[nT++] = pPoints[0]; + f = pPoints[0].f; + + for(int i = 1; i < pSegments[nIndex].nCount;){ + f += pPoints[i].f; + if(f == 0){ + pTemp[nT++] = pPoints[i++]; + if(i < pSegments[nIndex].nCount){ + pTemp[nT++] = pPoints[i]; + f = pPoints[i++].f; + }; + } else i++; + }; + if(pSegments[nIndex].pPoints) delete[] pSegments[nIndex].pPoints; + pSegments[nIndex].pPoints = new VERTEX[nT]; + memcpy( pSegments[nIndex].pPoints, pTemp, sizeof(VERTEX) * nT ); + pSegments[nIndex].nCount = nT; + if(pTemp) delete[] pTemp; + }; +}; + +int compareSegments(const void *arg1, const void *arg2){ + if(((PSEGMENT)arg1)->nIndex > ((PSEGMENT)arg2)->nIndex) return +1; + if(((PSEGMENT)arg1)->nIndex < ((PSEGMENT)arg2)->nIndex) return -1; + if(((PSEGMENT)arg1)->pPoints[0] > ((PSEGMENT)arg2)->pPoints[0]) return +1; + if(((PSEGMENT)arg1)->pPoints[0] < ((PSEGMENT)arg2)->pPoints[0]) return -1; + return 0; +}; + +uint16_t pnpoly( uint16_t nvert, float *vertx, float *verty, float testx, float testy ){ + uint16_t c = 0; + for( uint16_t i = 0, j = nvert-1; i < nvert; j = i++ ) if ( ((verty[i]>testy) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ) c = !c; + return c; +}; + +bool device2DSensor::PtInPolygons( TEST_POINT& point, uint8_t F ){ + for( uint16_t i = 0; i < m_sShadow.m_nPolygonCount; i++) if( F == m_sShadow.pPolygones[i].bType ) if ( PtInPolygon( m_sShadow.pPolygones[i], point ) ) return true; + return false; +}; + +bool device2DSensor::PtInPolygon( SHADOW_POLY& Poly, TEST_POINT& point ){ + if( Poly.wCount < 3 ) return false; + float *vertx = (float *) calloc( Poly.wCount, sizeof(float)); + float *verty = (float *) calloc( Poly.wCount, sizeof(float)); + for( int z =0; z < Poly.wCount; z++ ) { + vertx[z] = (float)Poly.pPoint[z].wX; + verty[z] = (float)Poly.pPoint[z].wY; + }; + if ( pnpoly( Poly.wCount, vertx, verty, point.x, point.y )){ + free(vertx); + free(verty); + return TRUE; + }; + free(vertx); + free(verty); + return FALSE; +}; + +bool device2DSensor::rasterizeShadow(){ + const double TWO_PI = 6.2831853071796; + bool masked[5] = {0}; + uint16_t cMin, cMax; + double k = TWO_PI /((double)MAX_2D_SHADOW_RAY_LINES ); + double z_shift = k * ((double)m_sLRF_DATA.base_shift ); + + for( uint16_t i=0; i < MAX_2D_SHADOW_RAY_LINES; i++ ) { + double ca = k * i + z_shift; // must be checked sign!! + double sin_val = sin( ca ); + double cos_val = cos( ca ); + for( uint16_t range_digital = 0; range_digital < 2047; range_digital++ ) { + TEST_POINT TP; + TP.x = (float)(cos_val*((double)range_digital)); + TP.y = (float)(sin_val*((double)range_digital)); + for( uint8_t z=0; z < 5; z++ ){ + if (masked[z]) { + if(!PtInPolygons( TP, z )){ + masked[z] = false; + cMax = range_digital; + m_sShadow.ray_lines[i].rays = (SHADOW_RAY *) realloc( m_sShadow.ray_lines[i].rays, m_sShadow.ray_lines[i].nCount+1 ); + if ( m_sShadow.ray_lines[i].rays == NULL ) { + m_sShadow.ray_lines[i].nCount = 0; + return false; + }; + m_sShadow.ray_lines[i].rays[m_sShadow.ray_lines[i].nCount].nMin = cMin; + m_sShadow.ray_lines[i].rays[m_sShadow.ray_lines[i].nCount].nMax = cMax; + m_sShadow.ray_lines[i].rays[m_sShadow.ray_lines[i].nCount].bType = z; + m_sShadow.ray_lines[i].nCount++; +#ifdef DEBUG + char tB[128]; + sprintf( tB ,"New Ray: Mask[%d] angle[%d] min[%d] max[%d]", z, i, cMin, cMax ); + LOG(tB); +#endif + }; + } else { + if(PtInPolygons( TP, z )){ + masked[z] = true; + cMin = range_digital; + }; + }; + }; + }; + for( uint8_t z=0; z < 5; z++ ){ + if ( masked[z] ) { + masked[z] = false; + cMax = 2047; + m_sShadow.ray_lines[i].rays = (SHADOW_RAY *) realloc( m_sShadow.ray_lines[i].rays, m_sShadow.ray_lines[i].nCount + 1 ); + if ( m_sShadow.ray_lines[i].rays == NULL ) { + m_sShadow.ray_lines[i].nCount = 0; + return false; + }; + m_sShadow.ray_lines[i].rays[m_sShadow.ray_lines[i].nCount].nMin = cMin; + m_sShadow.ray_lines[i].rays[m_sShadow.ray_lines[i].nCount].nMax = cMax; + m_sShadow.ray_lines[i].rays[m_sShadow.ray_lines[i].nCount].bType = z; + m_sShadow.ray_lines[i].nCount++; +#ifdef DEBUG + char tB[128]; + sprintf( tB ,"New Ray: Mask[%d] angle[%d] min[%d] max[%d]", z, i, cMin, cMax ); + LOG(tB); +#endif + }; + }; + }; + return true; +}; + +#ifdef DEBUG_EXTRA_ +void device2DSensor::makeShadowPic( CSTR picname ){ + cv::Scalar zone_colors[6] = { cv::Scalar(0, 0, 255), + cv::Scalar(255, 20, 255), + cv::Scalar(0, 255, 255), + cv::Scalar(0, 255, 0), + cv::Scalar(255, 0, 0), + cv::Scalar(120, 120, 120) + }; + const double TWO_PI = 6.2831853071796; + double k = TWO_PI /((double)MAX_2D_SHADOW_RAY_LINES ); + double z_shift = k * ((double)m_sLRF_DATA.base_shift ); + cv::Mat tPic(512, 512, CV_8UC3, cv::Scalar(20, 20, 20)); + double cx = 256.0; + double cy = 256.0; + double r = 255.0/2048.0; + for ( int i = 0; i < 360; i++ ) { + double ca = k * i + z_shift; // must be checked sign!! + double sin_val = sin( ca ); + double cos_val = cos( ca ); + cv::line( tPic, cv::Point( cx, cy ), cv::Point( cx+cos_val*256, cy+sin_val*256 ), zone_colors[5], 1, cv::LINE_AA ); + if( m_sShadow.ray_lines[i].nCount ){ + for ( int z=0; z < m_sShadow.ray_lines[i].nCount; z++ ) { + int r1 = m_sShadow.ray_lines[i].rays[z].nMin; + int r2 = m_sShadow.ray_lines[i].rays[z].nMax; + cv::Scalar color = zone_colors[m_sShadow.ray_lines[i].rays[z].bType]; + int x1 = cx+(cos_val*r1*r); + int y1 = cy+(sin_val*r1*r); + int x2 = cx+(cos_val*r2*r); + int y2 = cy+(sin_val*r2*r); + cv::line(tPic, cv::Point(x1, y1), cv::Point( x2, y2), color, 1, cv::LINE_AA); + }; + }; + }; + vector compression_params; + compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION); + compression_params.push_back(9); + //compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); + //compression_params.push_back( m_sEmbedVideoData.compression_quality ); + vector buf; + cv::imencode( ".png", tPic, buf, compression_params ); + FILE *fd; + fd = fopen( picname, "wb"); + if ( fd ) { + fwrite( buf.data(), 1, buf.size(), fd ); + fclose( fd ); + }; + buf.clear(); +}; +#endif + +#undef SIZE_IDX +#undef DEV_ID_IDX +#undef CMD_IDX +#undef SUB_CMD_IDX +#undef DATA_BEGIN_IDX + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/deviceNode2D.h b/lib/App/common/deviceNode2D.h new file mode 100644 index 00000000..9830f3d6 --- /dev/null +++ b/lib/App/common/deviceNode2D.h @@ -0,0 +1,148 @@ +#ifndef __OBJECT_NET_NODE_2D_HEADERS__ +#define __OBJECT_NET_NODE_2D_HEADERS__ + +#include "deviceNodeSensor.h" +#include //For DBL_MAX +#include + +#include "../../components/base/basicObject.h" +#include "../../components/base/basicMutex.h" +#include "../../components/base/basicThread.h" +#include "../../components/base/basicLogCollection.h" +#include "../../components/base/basicSettingsProvider.h" +#include "../../alg/lgs/mask.h" +#include "../../data/protocol/protocolLGS2D.h" + +#define LGS_DEFAULT_SLEEP_TIME 100 +#define LGS_ALERT_SLEEP_TIME 1 +#define LGS_DEFAULT_TO_COUNTER 10 +#define LGS_INITIAL_FLIPS 8 + +#define ANODE_WM_2D_BEFORE_START 0 +#define ANODE_WM_2D_CREATE_PORT 1 +#define ANODE_WM_2D_CONNECT 2 +#define ANODE_WM_2D_WAIT_CONNECT 3 +#define ANODE_WM_2D_SET_INIT_MODE 4 +#define ANODE_WM_2D_GET_SERIAL_NUM 6 +#define ANODE_WM_2D_GET_VERSION 8 +#define ANODE_WM_2D_GET_DETECTION_PROFILE 10 +#define ANODE_WM_2D_GET_MASTER_PARAM 12 +#define ANODE_WM_2D_GET_SLAVE_PARAM 14 +#define ANODE_WM_2D_GET_MASK_INFO 16 +#define ANODE_WM_2D_SET_MASK_INFO 18 + + + +#define ANODE_WM_2D_SET_BORDER_MODE 32 +#define ANODE_WM_2D_GET_FAST_DRAW 34 +#define ANODE_WM_2D_SET_DETECTION_MODE 36 +#define ANODE_WM_2D_SET_FILESYSTEM_MODE 38 +#define ANODE_WM_2D_FS_TRANSFER_MODE 39 + +#define ANODE_WM_2D_SET_SHADOW_DONE 40 +#define ANODE_WM_2D_GET_SHADOW_POLY_INFO 41 +#define ANODE_WM_2D_GET_SHADOW_POLY_POINT 43 +#define ANODE_WM_2D_SET_SHADOW_POLY_INFO 45 +#define ANODE_WM_2D_SET_SHADOW_POLY_POINT 47 +#define ANODE_WM_2D_SET_SHADOW_RAY_LINE 48 +#define ANODE_WM_2D_SET_SHADOW_RAY 49 + +#define ANODE_WM_2D_SET_GETFILE_MODE 50 +#define ANODE_WM_2D_SEND_GETFILE_MODE 52 +#define ANODE_WM_2D_SET_MASTER_PARAM 58 +#define ANODE_WM_2D_SET_SLAVE_PARAM 59 +#define ANODE_WM_2D_ISSUE_FULL_RESET 64 + +#define ANODE_WM_2D_ISSUE_RESET 66 + +#define ANODE_WM_2D_PING 128 +#define ANODE_WM_2D_PONG 129 + +#define ANODE_WM_2D_SLEEP_AND_RECONNECT 130 +#define ANODE_WM_2D_WAIT_DEVICE_REPLAY 254 +#define ANODE_WM_2D_WAIT_CHECK_REPLAY 255 + +#define ANODE_2D_MAX_DRAW_ANGLES 6000 + +#define ARGUS_DS_NONE 0 +#define ARGUS_DS_CREATED 1 +#define ARGUS_DS_GET_CONFIG 2 +#define ARGUS_DS_VALID 3 +#define ARGUS_DS_CONF_MISTMATCH 4 + +typedef struct S_SHADOW_IO_HELPER{ + uint16_t m_nCurrentPolygon; + uint16_t m_nCurrentPoint; + uint16_t m_nCurrentRayLine; + uint16_t m_nCurrentRay; +}SHADOW_IO_HELPER; + +typedef struct S_GETFILE_IO_HELPER{ + uint32_t fileSize; + uint32_t index; + char destName[33]; + char sourceName[33]; + uint8_t state; + FILE * fd; + uint8_t data[250]; + uint8_t data_size; +}GETFILE_IO_HELPER; + +typedef struct S_TEST_POINT{ + float x; + float y; +}TEST_POINT; + +class device2DSensor: public deviceNodeSensor, public basicThread, public protocolLGS_2D{ + private: + //basicLogCollection * m_pLog; + uint8_t m_bPortType; + basicTransport * m_pPort; + + uint8_t m_bDeviceWM; + uint32_t m_nSleepTime; + uint16_t m_bTimeOutCounter; + uint8_t m_bInitialFlips; + uint16_t m_nCurrentAngle; + uint8_t m_bDrawType; + uint8_t m_bOpRetryCnt; + uint32_t m_nProcessingCmdId; + uint32_t m_vDrawRanges[ANODE_2D_MAX_DRAW_ANGLES]; + bool m_bDeviceIsSynced; + bool m_bSerialStringValid; + bool m_bVersionStringValid; + char m_tSN[65]; + char m_tSV[129]; + char m_sCurrentFile[MAX_PATH]; + uint32_t m_nUploadID; + uint8_t m_nActiveDetectionProfile; + //Shadow + SHADOW_IO_HELPER m_sShadowHelper; + SHADOW m_sShadow; + //GetFile + GETFILE_IO_HELPER m_sGetFileHelper; + + TARGET_DATA * prepareTargetData( uint16_t AZ, uint16_t RANGE, uint32_t WIDTH, uint8_t LRFID = 0 ); + //void saveRawDrawData( uint16_t alngles ); + void cleanupDeviceStructures(); + CSTR generateSettingFile(); + void cleanShadowStructs(); + bool PtInPolygons( TEST_POINT& point, uint8_t F ); + bool PtInPolygon( SHADOW_POLY& Poly, TEST_POINT& point ); + bool rasterizeShadow(); +#ifdef DEBUG_EXTRA + void makeShadowPic( CSTR picname ); +#endif + protected: + virtual bool packetHandler( protocolPackage *Package ); + virtual void m_fThreadProc( void ); + public: + explicit device2DSensor( uint32_t id ); + ~device2DSensor(); + virtual bool startService(); + virtual bool stopService(); + virtual bool validate(); + virtual void simulateTarget( void ); +}; + +#endif diff --git a/lib/App/common/deviceNode3D.cpp b/lib/App/common/deviceNode3D.cpp new file mode 100644 index 00000000..a963f8c9 --- /dev/null +++ b/lib/App/common/deviceNode3D.cpp @@ -0,0 +1,1769 @@ +#include "deviceNode3D.h" + +#define LOG( X ) deviceNode::m_pLog->Log( "NODE3D", this, X ) +#define LOG_ERROR( X ) deviceNode::m_pLog->Log( "NODE3D", this, _LOG_ERROR, X ) + +device3DSensor::device3DSensor( uint32_t ID ): deviceNodeSensor( ID ){ + //m_pLog = basicLogCollection::getInstance(); + //m_pEventHeap = basicEventHeap::getInstance(); + //m_pThresholdData = NULL; + m_pThresholdData = (thresholdNode *) malloc( sizeof(thresholdNode) * TH_SIZE_NODES ); + m_nFullBorderDataIndex = 0; + m_nFullBorderKernelIndex = 0; + m_bTWINC = false; + m_pShadow = NULL; + +#ifdef SIMULATE_3D_TARGETS + m_pSimulationConfig = basicSettingsProvider::getInstance()->getSubNode( NULL, "SIMULATOR" ); + memset( &m_dIntruderSpeed, 0, sizeof(C3D_DECART)); + memset( &m_dHunterSpeed, 0, sizeof(C3D_DECART)); + m_bSymStage = 0; +#endif +}; + +device3DSensor::~device3DSensor(){ + stopService(); + #ifdef SIMULATE_3D_TARGETS + + #endif +}; + +bool device3DSensor::startService(){ +#ifdef DEBUG + LOG("START SERVICE"); +#endif + +#ifdef SIMULATE_3D_TARGETS + LOG("Init Simulation!"); + if ( m_pSimulationConfig != NULL ) { + config_setting_t * pSetting; + int tVal; + double fVal1, fVal2, fVal3; + const char * tBuf; + config_setting_t * tpSettings = basicSettingsProvider::getInstance()->getSubNode( m_pSimulationConfig, "AGRESSOR" ); + if( !config_setting_lookup_float( tpSettings, "ENTRY_POINT_LAT", &fVal1 ) ){ + fVal1 = 0.0f; + pSetting = config_setting_add( tpSettings, "ENTRY_POINT_LAT", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal1 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Entry LAT not defined - using default value!"); + } else { + sprintf( tB, "Intruder Entry LAT Read From Settings: %2.10f", fVal1 ); + LOG( tB ); + }; + if( !config_setting_lookup_float( tpSettings, "ENTRY_POINT_LON", &fVal2 ) ){ + fVal2 = 0.0f; + pSetting = config_setting_add( tpSettings, "ENTRY_POINT_LON", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal2 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Entry LON not defined - using default value!"); + } else { + sprintf( tB, "Intruder Entry LON Read From Settings: %2.10f", fVal2 ); + LOG( tB ); + }; + if( !config_setting_lookup_float( tpSettings, "ENTRY_POINT_ALT", &fVal3 ) ){ + fVal3 = 50.0f; + pSetting = config_setting_add( tpSettings, "ENTRY_POINT_ALT", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal3 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Entry ALT not defined - using default value!"); + } else { + sprintf( tB, "Intruder Entry LON Read From Settings: %2.10f", fVal3 ); + LOG( tB ); + }; + + if ( SA ) { + LOG("SYS Anchor OK"); + if( SA->beLocal() ) { + LOG("SYS Anchor LOCAL"); + m_oIntruder_Start.setPositionXYZ( fVal1, fVal2, fVal3, 0 ); + m_oIntruder_Start.updateMatrix(); + m_oIntruder_.setPositionXYZ( fVal1, fVal2, fVal3, 0 ); + m_oIntruder_.updateMatrix(); + } else { + LOG("SYS Anchor GLOBAL"); + m_oIntruder_Start.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oIntruder_Start.updateMatrix(); + m_oIntruder_.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oIntruder_.updateMatrix(); + }; + } else { + LOG("No SYS Anchor!"); + m_oIntruder_Start.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oIntruder_Start.updateMatrix(); + m_oIntruder_.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oIntruder_.updateMatrix(); + }; + + if( !config_setting_lookup_float( tpSettings, "ESCAPE_POINT_LAT", &fVal1 ) ){ + fVal1 = 0.0f; + pSetting = config_setting_add( tpSettings, "ESCAPE_POINT_LAT", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal1 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Escape LAT not defined - using default value!"); + } else { + sprintf( tB, "Intruder Escape LAT Read From Settings: %2.10f", fVal1 ); + LOG( tB ); + }; + if( !config_setting_lookup_float( tpSettings, "ESCAPE_POINT_LON", &fVal2 ) ){ + fVal2 = 0.0f; + pSetting = config_setting_add( tpSettings, "ESCAPE_POINT_LON", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal2 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Escape LON not defined - using default value!"); + } else { + sprintf( tB, "Intruder Escape LON Read From Settings: %2.10f", fVal2 ); + LOG( tB ); + }; + if( !config_setting_lookup_float( tpSettings, "ESCAPE_POINT_ALT", &fVal3 ) ){ + fVal3 = 50.0f; + pSetting = config_setting_add( tpSettings, "ESCAPE_POINT_ALT", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal3 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Escape ALT not defined - using default value!"); + } else { + sprintf( tB, "Intruder Escape ALT Read From Settings: %2.10f", fVal3 ); + LOG( tB ); + }; + + if ( SA ) { + LOG("SYS Anchor OK"); + if( SA->beLocal() ) { + LOG("SYS Anchor LOCAL"); + m_oIntruder_Finish.setPositionXYZ( fVal1, fVal2, fVal3, 0 ); + m_oIntruder_Finish.updateMatrix(); + } else { + LOG("SYS Anchor GLOBAL"); + m_oIntruder_Finish.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oIntruder_Finish.updateMatrix(); + }; + } else { + LOG("No SYS Anchor!"); + m_oIntruder_Finish.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oIntruder_Finish.updateMatrix(); + }; + + if( !config_setting_lookup_float( tpSettings, "SPEED", &fVal1 ) ){ + m_dIntruderSpeed = fVal1 = 5.0f; + pSetting = config_setting_add( tpSettings, "SPEED", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal1 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Speed not defined - using default value!"); + } else { + m_dIntruderSpeed = fVal1; + sprintf( tB, "Intruder Speed Read From Settings: %0.3f", fVal1 ); + LOG( tB ); + }; + + tpSettings = basicSettingsProvider::getInstance()->getSubNode( m_pSimulationConfig, "INTERCEPTOR" ); + if( !config_setting_lookup_float( tpSettings, "ENTRY_POINT_LAT", &fVal1 ) ){ + fVal1 = 0.0f; + pSetting = config_setting_add( tpSettings, "ENTRY_POINT_LAT", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal1 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Entry LAT not defined - using default value!"); + } else { + sprintf( tB, "Intruder Entry LAT Read From Settings: %2.10f", fVal1 ); + LOG( tB ); + }; + if( !config_setting_lookup_float( tpSettings, "ENTRY_POINT_LON", &fVal2 ) ){ + fVal2 = 0.0f; + pSetting = config_setting_add( tpSettings, "ENTRY_POINT_LON", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal2 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Entry LON not defined - using default value!"); + } else { + sprintf( tB, "Intruder Entry LON Read From Settings: %2.10f", fVal2 ); + LOG( tB ); + }; + if( !config_setting_lookup_float( tpSettings, "ENTRY_POINT_ALT", &fVal3 ) ){ + fVal3 = 50.0f; + pSetting = config_setting_add( tpSettings, "ENTRY_POINT_ALT", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal3 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Entry ALT not defined - using default value!"); + } else { + sprintf( tB, "Intruder Entry LON Read From Settings: %2.10f", fVal3 ); + LOG( tB ); + }; + if ( SA ) { + LOG("SYS Anchor OK"); + if( SA->beLocal() ) { + LOG("SYS Anchor LOCAL"); + m_oHunter_Home.setPositionXYZ( fVal1, fVal2, fVal3, 0 ); + m_oHunter_Home.updateMatrix(); + m_oHunter_.setPositionXYZ( fVal1, fVal2, fVal3, 0 ); + m_oHunter_.updateMatrix(); + } else { + LOG("SYS Anchor GLOBAL"); + m_oHunter_Home.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oHunter_Home.updateMatrix(); + m_oHunter_.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oHunter_.updateMatrix(); + }; + } else { + LOG("No SYS Anchor!"); + m_oHunter_Home.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oHunter_Home.updateMatrix(); + m_oHunter_.setPositionWGS84( fVal1, fVal2, fVal3 ); + m_oHunter_.updateMatrix(); + }; + if( !config_setting_lookup_float( tpSettings, "SPEED", &fVal1 ) ){ + m_dHunterSpeed = fVal1 = 8.0f; + pSetting = config_setting_add( tpSettings, "SPEED", CONFIG_TYPE_FLOAT ); + config_setting_set_float( pSetting, fVal1 ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Intruder Speed not defined - using default value!"); + } else { + m_dHunterSpeed = fVal1; + sprintf( tB, "Intruder Speed Read From Settings: %0.3f", fVal1 ); + LOG( tB ); + }; + basicSettingsProvider::getInstance()->validate(); + + headIntruderTo( m_oIntruder_Finish ); + headHunterTo( m_oIntruder_Start ); + } else LOG_ERROR("Cannot Access to Simulator Config!!"); + m_nAutoScript = 0; +#endif + // Check if Allredy Working + if( m_bThreadStatus > TH_ARMED ){ + if( m_bThreadStatus == TH_WORKING ) return true; + return false; + }; + + m_pShadow = new ShadowMask(); + if( m_pShadow ) { + m_pShadow->disableAutoSave(); + m_pShadow->clear(); + }; + return init(); +}; + +bool device3DSensor::stopService(){ + LOG("STOP SERVICE"); + LOG("unlock all mutexes"); + m_mDataMutex.unlock(); + m_mStatusMutex.unlock(); + m_mPackageMutex.unlock(); + LOG("Kill Thread"); + waitThreadEnd( true ); + LOG("Clean Data"); + cleanDataTH(); + LOG("Remove Shadow"); + if( m_pShadow ) delete( m_pShadow ); + LOG("Done!"); + return true; +}; + +bool device3DSensor::validate(){ + +#ifdef SIMULATE_3D_TARGETS + if ( m_nAutoScript ) { + switch ( m_nAutoScript ) { + case 48:{ + m_bSymStage = 2; + m_dHunterSpeed = 0.5; + break; + }; + case 58:{ + m_dHunterSpeed = 12.0; + break; + }; + case 80:{ + m_oIntruder_.setPositionXYZ( + m_oIntruder_.getX(), + m_oIntruder_.getY(), + 0, + systemAnchor::getInstance()->getUTMZone() + ); + m_oIntruder_.updateMatrix(); + m_dHunterSpeed = m_dHunterSpeed / 2; + headHunterTo( m_oHunter_Home ); + m_bSymStage = 3; + break; + }; + case 95:{ + m_dHunterMove.x = .0f; + m_dHunterMove.y = .0f; + m_dHunterMove.z = .0f; + m_dHunterSpeed = m_dHunterSpeed / 2; + m_bSymStage = 3; + break; + }; + case 109:{ + headHunterTo( m_oHunter_Home ); + break; + }; + case 119:{ + m_dHunterMove.z = -40.0f; + m_bSymStage = 3; + break; + }; + }; + m_nAutoScript++; + }; +#endif + DBC_PUSHED_CMD *tCMD = m_pDBC->getNodePushedCMD( m_sNodeData.node_id ); + if ( tCMD!= NULL ) { + m_pDBC->updateNodePushedCMD( tCMD->id, DBC_CMD_STARTED ); + switch( tCMD->CMD ){ +#ifdef SIMULATE_3D_TARGETS + case ARGUS_SYM_CMD_0:{ + LOG("Start Simulation"); + m_bSymStage = 1; + m_nAutoScript = 1; + break; + }; + case ARGUS_SYM_CMD_1:{ + LOG("Start Hunting Drone"); + m_bSymStage = 2; + break; + }; + case ARGUS_SYM_CMD_2:{ + LOG("Catched and Return Hunter Home"); + m_oIntruder_.setPositionXYZ( + m_oIntruder_.getX(), + m_oIntruder_.getY(), + 0, + systemAnchor::getInstance()->getUTMZone() + ); + m_oIntruder_.updateMatrix(); + headHunterTo( m_oHunter_Home ); + m_bSymStage = 3; + break; + }; + case ARGUS_SYM_CMD_3:{ + LOG("Force Return Hunter Home"); + headHunterTo( m_oHunter_Home ); + m_bSymStage = 3; + break; + }; + case ARGUS_SYM_CMD_4:{ + LOG("Force Fly Intruder to Start"); + headIntruderTo( m_oIntruder_Start ); + break; + }; + case ARGUS_SYM_CMD_5:{ + LOG("Force Fly Intruder to End"); + headIntruderTo( m_oIntruder_Finish ); + break; + }; + case ARGUS_SYM_CMD_6:{ + LOG("Freeze Intruder"); + m_dIntruderMove.x = .0f; + m_dIntruderMove.y = .0f; + m_dIntruderMove.z = .0f; + break; + }; + case ARGUS_SYM_CMD_7:{ + LOG("Freeze Hunter"); + m_dHunterMove.x = .0f; + m_dHunterMove.y = .0f; + m_dHunterMove.z = .0f; + m_bSymStage = 3; + break; + }; + case ARGUS_SYM_CMD_8:{ + LOG("Contoinue Hunt"); + headHunterTo( m_oIntruder_ ); + m_bSymStage = 2; + break; + }; + case ARGUS_SYM_CMD_9:{ + LOG("Restart Simulation from begining"); + m_bSymStage = 0; + m_nAutoScript = 0; + m_oIntruder_.setPositionWGS84( m_oIntruder_Start.getLat(), m_oIntruder_Start.getLon(), m_oIntruder_Start.getAlt() ); + m_oIntruder_.updateMatrix(); + m_oHunter_.setPositionWGS84( m_oHunter_Home.getLat(), m_oHunter_Home.getLon(), m_oHunter_Home.getAlt() ); + m_oHunter_.updateMatrix(); + headIntruderTo( m_oIntruder_Finish ); + headHunterTo( m_oIntruder_Start ); + break; + }; + case ARGUS_SYM_CMD_10:{ + LOG("Land Hunter"); + m_dHunterMove.z = -40.0f; + m_bSymStage = 3; + break; + }; +#endif + case ARGUS_LRF_PCMD_FULL_RESET:{ +#ifdef DEBUG + LOG("Full Reset Push CMD!"); +#endif + NI_COMMAND *tNCMD = (NI_COMMAND *) malloc( sizeof(NI_COMMAND)); + if (tNCMD) { + tNCMD->cmd = NODE_CMD_FULL_RESET; + tNCMD->parameter = NULL; + LOG("B E"); + enqueueCommand( tNCMD ); + LOG("A E"); + }; + break; + }; + case ARGUS_LRF_PCMD_DRAW:{ +#ifdef DEBUG + LOG("Get Draw Push CMD!"); +#endif + NI_COMMAND *tNCMD = (NI_COMMAND *) malloc( sizeof(NI_COMMAND)); + if (tNCMD) { + tNCMD->cmd = NODE_CMD_GET_DEVICE_DRAW; + tNCMD->parameter = NULL; + enqueueCommand( tNCMD ); + } + break; + }; + case ARGUS_LRF_PCMD_UPLOAD_FILE:{ +#ifdef DEBUG + LOG("Upload File CMD!"); +#endif + uint16_t sz = strlen(tCMD->PARAM); + if( sz ){ + NI_COMMAND *tNCMD = (NI_COMMAND *)malloc(sizeof(NI_COMMAND)); + if( tNCMD ){ + tNCMD->cmd = NODE_CMD_UPLOAD_FILE; + tNCMD->parameter = malloc( sz+1 ); + if ( tNCMD->parameter != NULL ) { + memcpy(tNCMD->parameter, tCMD->PARAM, sz); + ((uint8_t *)tNCMD->parameter)[sz] = 0; + enqueueCommand( tNCMD ); + } else { + free( tNCMD ); + }; + }; + }; + break; + }; + case ARGUS_LRF_PCMD_SET_MASK_1: + case ARGUS_LRF_PCMD_SET_MASK_2: + case ARGUS_LRF_PCMD_SET_MASK_3: + case ARGUS_LRF_PCMD_SET_MASK_4: + case ARGUS_LRF_PCMD_SET_MASK_5:{ + //Rasterize Masks and upload + m_nCurrentMaskID = m_pDBC->getLRFMaskID( m_sNodeData.aux_id ); // 3DLRF has onli one mask + if( m_nCurrentMaskID ){ + if( m_pShadow == NULL ){ + m_pShadow = new ShadowMask(); + }; + if ( m_pShadow != NULL ) { + m_pShadow->clear(); + DBC_INT_LIST *tVertexes = m_pDBC->listLRFMaskVertexes( m_nCurrentMaskID ); + if ( tVertexes ){ + if( tVertexes->size() ){ + LOG("Has POLY"); + for ( int vidx=0; vidx < tVertexes->size(); vidx++ ) { + simplePolygone *tPoly = m_pDBC->loadLRFMaskVertex( tVertexes->at(vidx) ); + if( tPoly ) { + LOG("POLY LOADDED!"); + m_pShadow->addPoly( tPoly ); + LOG("POLY ADDED!"); + if( m_pShadow->rasterizeVertexes() ){ + LOG("Vertexes Rasterized!"); + } else { + LOG("Vertexes ARE NOT Rasterized!"); + }; + }; + }; + LOG("Create Command!"); + NI_COMMAND *tNCMD = (NI_COMMAND *)malloc(sizeof(NI_COMMAND)); + if( tNCMD ){ + tNCMD->cmd = NODE_CMD_UPLOAD_SHADOW; + tNCMD->parameter = NULL; + m_nCurrentPolyID = 0; + enqueueCommand( tNCMD ); + LOG("Command Queued!"); + }; + } + delete( tVertexes ); + }; + }; + }; + }; + }; + free(tCMD); + }; + + simulateTarget(); + + return true; +}; + +void device3DSensor::m_fThreadProc(void){ + uint32_t nTimeOut = 20; + clientPort * tPort = NULL; + + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ){ + uint8_t cWM = getWM(); + + switch( cWM ) { + case CWM_INIT:{ + if ( tPort!= NULL ) { + delete( tPort ); + tPort = NULL; + EVENT_CONTAINER *tEVT; + //ToDo: Change Device Name! + m_pDBC->setNodeOffline( getNodeID() ); + tEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_ERROR, NULL, "Device is Disconnected"); + m_pEventHeap->broadcast( tEVT ); + SLEEP(100); + } else { + if( strlen( m_sLRF_DATA.slave_host ) < 7 ) { //minimal size of "X.X.X.X" + tPort = new clientPort( m_sLRF_DATA.master_host, m_sLRF_DATA.master_port ); + } else { + tPort = new clientPort( m_sLRF_DATA.slave_host, m_sLRF_DATA.slave_port ); + }; + if( tPort!= NULL ) { + setWM(CWM_CONNECT); + }; + }; + break; + }; + case CWM_CONNECT:{ + if( CS_CONNECTED == getConnectionStatus() ) { + EVENT_CONTAINER *tEVT; +#ifdef DEBUG + LOG("Set Device Connected!"); +#endif + m_pDBC->setNodeOnline( getNodeID() ); + tEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_READY, NULL, "Device is connected"); + m_pEventHeap->broadcast( tEVT ); + setWM( CWM_INITIAL_GET_TWINC ); + + } else { + if( tPort!= NULL ) { + if ( tPort->create() ) { + if( setTransport( tPort , false ) ){ + break; + } else { + LOG_ERROR("Transport is not Attached to Parser!"); + }; + } else { + LOG_ERROR("Transport is not Created!"); + }; + }; + SLEEP(1000); + setWM( CWM_INIT ); + }; + break; + }; + case CWM_INITIAL_GET_TWINC:{ + if( !getTwincSupport() ) { +#ifdef DEBUG + LOG_ERROR("Get TWINC Support"); +#endif + setWM( CWM_INIT ); + } else { + LOG("Waiting ACK Twinc"); + setWM( CWM_INITIAL_WAIT_TWINC ); + }; + break; + }; + case CWM_INITIAL_GET_PARAM:{ + if( !getParameters() ) { +#ifdef DEBUG + LOG_ERROR("Get Param Failure"); +#endif + setWM( CWM_INIT ); + } else { + LOG("Waiting ACK Param"); + setWM( CWM_INITIAL_WAIT_PARAM ); + }; + break; + }; + case CWM_INITIAL_GET_MASKS_INFO:{ + if( !getShadowInfo() ){ + LOG_ERROR("Error INITIAL CMD_GET_SHADOW_INFO!"); + setWM( CWM_INIT ); + } else { + setWM( CWM_INITIAL_WAIT_MASKS_INFO ); + }; + break; + }; + case CWM_INITIAL_GET_VERTEX_DATA:{ + char tB[64]; + sprintf(tB, "Ini Get Vertex[%d]", m_nCurrentPolyID ); + LOG( tB ); + if( !getShadowPoly( m_nCurrentPolyID ) ){ + if( CS_CONNECTED != getConnectionStatus() ) { + setWM( CWM_INIT ); + } else LOG_ERROR("Error INITIAL CMD_GET_SHADOW_DATA!"); + } else { + setWM( CWM_INITIAL_WAIT_VERTEX_DATA ); + }; + break; + }; + + case CWM_GET_BORDER:{ + if( !getDraw( m_nFullBorderDataIndex, m_nFullBorderKernelIndex ) ){ + if( CS_CONNECTED != getConnectionStatus() ) { + setWM( CWM_INIT ); + } else LOG_ERROR("Error Sending CMD_FULL_BORDER!"); + } else { + setWM( CWM_WAIT_BORDER ); + }; + break; + }; + case CWM_GET_MASK:{ + if( !setShadowPoly(NULL) ){ + if( CS_CONNECTED != getConnectionStatus() ) { + setWM( CWM_INIT ); + } else LOG_ERROR("Error Sending CMD_SET_HZ_POLY!"); + } else { + setWM( CWM_WAIT_MASK ); + }; + break; + }; + case CWM_SET_MASK:{ + m_pShadow->getPolyCount(); + if( !setShadowPoly(NULL) ){ + if( CS_CONNECTED != getConnectionStatus() ) { + setWM( CWM_INIT ); + } else LOG_ERROR("Error Sending CMD_SET_HZ_POLY!"); + } else { + setWM( CWM_WAIT_MASK ); + }; + break; + }; + case CWM_GET_PARAMS:{ + if( !getParameters() ){ + if( CS_CONNECTED != getConnectionStatus() ) { + setWM( CWM_INIT ); + } else LOG_ERROR("Error Sending CMD_GET_PARAMETERS!"); + } else { + setWM( CWM_WAIT_PARAMS ); + }; + break; + }; + case CWM_SET_PARAMS:{ + //if( !setParameters( &m_sLGS_MASTER_PARAMETERS ) ){ + // setWM( CWM_INIT ); + // LOG_ERROR("Error Sending CMD_SET_PARAMETERS!"); + //} else { + // setWM( CWM_WAIT_ACK_PARAMS ); + //}; + break; + }; + case CWM_GET_STATUS:{ + if( !getState2() ){ + setWM( CWM_INIT ); + LOG_ERROR("Error Sending CMD_GET_STATUS2!"); + } else { + setWM( CWM_WAIT_STATUS ); + }; + break; + }; + case CWM_GET_EVENTS:{ + if( !getEvents() ){ + setWM( CWM_INIT ); + LOG_ERROR("Error Sending CMD_GET_EVENTS!"); + } else { + LOG("GetEVENTS sent"); + setWM( CWM_WAIT_EVENTS ); + }; + break; + }; + case CWM_SET_MODE_DETECTOR:{ + if( !setMode( MODE_DETECTOR )){ + setWM( CWM_INIT ); + LOG_ERROR("Error Sending CMD_GET_EVENTS!"); + } else { + setWM( CWM_WAIT_MODE_ACK ); + }; + break; + }; + case CWM_IDLE: + default:{ + if( NI_COMMAND * tCMD = fetchCommand() ) { + switch( tCMD->cmd ) { + case NODE_CMD_FULL_RESET:{ + setWM( CWM_ISSUE_FULL_RESET ); + break; + }; + case NODE_CMD_UPLOAD_FILE:{ + //m_nUploadID = atoi( (CSTR) tCMD->parameter ); + //m_sCurrentFile, m_pDBC->get + break; + }; + case NODE_CMD_GET_DEVICE_DRAW:{ + m_nFullBorderDataIndex = 0; + if( tCMD->parameter != NULL ) { + m_nFullBorderKernelIndex = *((uint8_t *)tCMD->parameter); + } else m_nFullBorderKernelIndex = m_sLRF_DATA.draw_lrf_id; + setWM( CWM_GET_BORDER ); + break; + }; + case NODE_CMD_UPLOAD_SHADOW:{ + setWM( CWM_SET_MASK ); + break; + }; + }; + if( tCMD->parameter ) free( tCMD->parameter ); + free( tCMD ); + break; + }; + //Time Driven Logic + if( nTimeOut ){ + nTimeOut--; + } else { + nTimeOut = 20; + setWM( CWM_GET_STATUS ); + }; + break; + }; + }; + SLEEP( 50 ); + }; + if( tPort != NULL ){ + delete( tPort ); + }; +}; + +thresholdNode *device3DSensor::grabDataAccess( void ){ + if( m_mDataMutex.try_lock() ){ + if(( m_pThresholdData != NULL ) && ( m_nFullBorderDataIndex == TH_SIZE_NODES )){ + return m_pThresholdData; + }; + m_mDataMutex.unlock(); + }; + return NULL; +}; + +void device3DSensor::cleanDataTH( void ){ + m_mDataMutex.lock(); + if( m_pThresholdData != NULL ){ + free( m_pThresholdData ); + m_pThresholdData = NULL; + m_nFullBorderDataIndex = 0; + }; + m_mDataMutex.unlock(); +}; + +void device3DSensor::releaseDataAccess( void ){ + m_mDataMutex.unlock(); +}; + +#ifdef SIMULATE_3D_TARGETS + +TARGET_DATA *device3DSensor::prepareSimData( basicPosition &bp ){ + TARGET_DATA* tVal = NULL; + tVal = (TARGET_DATA*)malloc(sizeof(TARGET_DATA)); + if( tVal != NULL ){ + memset( tVal, 0, sizeof(TARGET_DATA)); + systemAnchor* SA = systemAnchor::getInstance(); + tVal->system_target = bp.getXYZ(); + tVal->global_target = bp.getWGS84(); + SA->convertToLocal( &m_oPosition, bp.getXYZ(), tVal->local_target ); + }; + return tVal; +}; + +#endif +TARGET_DATA *device3DSensor::prepareTargetData(CLIENT_EVENT* CE) { + TARGET_DATA* tVal = NULL; + if (CE != NULL) { +#ifdef DEBUG + char tB[256]; +#ifdef DEBUG_EXTRA + sprintf( tB, "TRAW Type[%d] K[%d] R[%d] TH[%d] AA[%d] W[%d]", + CE->type, + CE->k_id, + CE->range, + CE->th_id, + TH_SIZE_NODES, + CE->w_cnt + ); + LOG( tB ); +#endif +#endif + tVal = (TARGET_DATA*)malloc(sizeof(TARGET_DATA)); + if (tVal != NULL) { + systemAnchor* tSystem = systemAnchor::getInstance(); + uint16_t cX, cY; + memset(tVal, 0, sizeof(TARGET_DATA)); + if( tSystem->beLocal() ){ + //tVal->source_position = ( C3D_WGS84_LOC ) m_oPosition.getXYZ(); + } else { + //tSystem->convertToGlobal( &m_oPosition, m_oPosition.getXYZ(), tVal->source_position ); + tVal->source_position = m_oPosition.getWGS84(); + }; + + makeXY(CE->th_id, cX, cY, (CE->k_id < 8)); + + tVal->local_target.r = m_sLRF_DATA.max_range / 4095.0f * (float)CE->range; + tVal->local_target.fi = 360.0f - (360.0f / (float)TH_LINE_NODES) * (float)cX; + tVal->local_target.tetta = /* 90.0f - */ ((float)Q_DEGREE_FOV / (float)Q_SCAN_COUNT) * (float)( cY + Q_SHIFT_DOWN_FOV ); + if( tVal->local_target.tetta > 90.0f ) { + tVal->local_target.tetta = 180.0f - tVal->local_target.tetta; + tVal->local_target.fi = tVal->local_target.fi + 180.0f; + if( tVal->local_target.fi > 360.0f ) tVal->local_target.fi = tVal->local_target.fi - 360.0f; + }; + tVal->digital = CE->range; + tVal->lrf_id = CE->k_id; + //CE->w_cnt * CE->range + tVal->area = CE->w_cnt * tVal->local_target.r; + // local - C3D_SPH_RADIANS/C3D_SPH_DEGREES + // system - C3D_DECART + // global - C3D_WGS84_LOC + tSystem->convertToSystem( &m_oPosition, tVal->local_target, tVal->system_target ); + tSystem->convertToGlobal( &m_oPosition, tVal->local_target, tVal->global_target ); +#ifdef DEBUG_EXTRA + sprintf(tB, "Local T: %.3f %.3f %.3f", tVal->local_target.r, tVal->local_target.fi, tVal->local_target.tetta ); + LOG( tB ); + sprintf(tB, "System T: %.3f %.3f %.3f", tVal->system_target.x, tVal->system_target.y, tVal->system_target.z ); + LOG( tB ); + sprintf(tB, "Global T: %.3f %.3f %.3f", tVal->global_target.lat, tVal->global_target.lon, tVal->global_target.alt ); + LOG( tB ); +#endif + }; + }; + return tVal; +}; + +#define SIZE_IDX_A 1 +#define SIZE_IDX_B 2 +#define DEV_ID_IDX 3 +#define CMD_IDX 4 +#define SUB_CMD_IDX 5 +#define DATA_BEGIN_IDX 6 + +bool device3DSensor::packetHandler( protocolPackage* Package ) { + uint8_t * pReceivedPackage = NULL; + size_t nReceivedPackageSize = 0; + bool bPackageIsArived = false; + EVENT_CONTAINER * tEVT; + CLIENT_EVENT * tData; + if( Package == NULL ) return true; + if( Package->m_pData == NULL ) return true; + + pReceivedPackage = Package->m_pData; + nReceivedPackageSize = Package->m_nSize; + + uint8_t CUR_CMD; + uint16_t PKG_LEN; + uint8_t index; + uint8_t SUB_LEN; + uint8_t SUB_CMD; + uint16_t Range; + uint32_t Angle; + uint32_t Width; + bool State; + uint8_t Status; + uint8_t Code; + PKG_LEN = ((pReceivedPackage[SIZE_IDX_A] & 0x7F) << 8) | pReceivedPackage[SIZE_IDX_B]; + CUR_CMD = pReceivedPackage[CMD_IDX]; + SUB_CMD = pReceivedPackage[SUB_CMD_IDX]; +#ifdef DEBUG_EXTRA + char tZ[128]; + sprintf(tZ,"CMD: 0x%02X SUB: 0x%02X WM:0x%02X", CUR_CMD, SUB_CMD, getWM() ); + LOG( tZ ); +#endif + m_nBusyCounter = 0; + switch( CUR_CMD ){ + case CMD_STATE:{ +#ifdef DEBUG + LOG("CMD_STATE"); +#endif + if( SUB_CMD > WM_INIT ){ + SOFTWARE_INFO tINFO; + uint8_t* ptr; + ptr = (uint8_t*)&tINFO; + + for (uint8_t i = 0; i < sizeof( SOFTWARE_INFO ); i++) ptr[i] = pReceivedPackage[DATA_BEGIN_IDX + i]; +#ifdef DEBUG + LOG("SOFT INFO FILLED!"); +#endif + char tB[65]; + sprintf(tB, "%08X", tINFO.SW_MODE_FLAGS ); + m_pDBC->updateLRFSerial( getDeviceID(), tB ); + sprintf(tB, "%08X", tINFO.SW_BUILD_DATE ); + m_pDBC->updateLRFVerison( getDeviceID(), tB ); + sprintf(tB, "%08X%08X%08X%08X", tINFO.FW_CORE1_TYP, tINFO.FW_CORE2_TYP, tINFO.FW_CORE3_TYP, tINFO.FW_CORE4_TYP); + m_pDBC->setLRFAltSerial( getDeviceID(), tB ); + sprintf(tB, "%08X%08X%08X%08X", tINFO.FW_CORE1_VER, tINFO.FW_CORE2_VER, tINFO.FW_CORE3_VER, tINFO.FW_CORE4_VER ); + m_pDBC->setLRFAltVerison( getDeviceID(), tB ); + }; + //setWM( CWM_INITIAL_GET_PARAM ); + setWM( CWM_INITIAL_GET_TWINC ); + break; + }; + case CMD_QUIT: + break; + case CMD_RESET: +#ifdef DEBUG + LOG("Reset ACK"); +#endif + break; + case CMD_FULL_BORDER: + case CMD_BORDER: +#ifdef DEBUG_EXTRA + LOG("CMD_BORDER"); +#endif + if (SUB_CMD == BD_ERRORMODE) { + LOG_ERROR("BOARD DATA ERROR!"); + m_nFullBorderDataIndex = 0; + setWM( CWM_IDLE ); + } else if (SUB_CMD == BD_NOTREADY) { + LOG_ERROR("BOARD DATA NOT READY!"); + m_nFullBorderDataIndex = 0; + setWM( CWM_IDLE ); + } else { + uint32_t index = 6; + while (index < (nReceivedPackageSize - 7) && m_nFullBorderDataIndex < TH_SIZE_NODES) { + m_pThresholdData[m_nFullBorderDataIndex].data = pReceivedPackage[index++]; + m_pThresholdData[m_nFullBorderDataIndex].data = (m_pThresholdData[m_nFullBorderDataIndex].data << 8) | pReceivedPackage[index++]; + m_pThresholdData[m_nFullBorderDataIndex].data = (m_pThresholdData[m_nFullBorderDataIndex].data << 8) | pReceivedPackage[index++]; + m_pThresholdData[m_nFullBorderDataIndex].data = (m_pThresholdData[m_nFullBorderDataIndex].data << 8) | pReceivedPackage[index++]; + m_nFullBorderDataIndex++; + }; + if (m_nFullBorderDataIndex < TH_SIZE_NODES) { + setWM( CWM_GET_BORDER ); + } else { +#ifdef DEBUG + LOG("FINISH GET BOARD DATA"); +#endif + if( m_pThresholdData!= NULL ){ + if( m_nFullBorderDataIndex > 0 ){ + /* + CSTR tID = getUniqID_MD5(); + if( tID!= NULL ) { + if( saveTHPicture( m_pThresholdData, tID, ((m_nFullBorderKernelIndex < 16 )?true:false), true ) ){ + m_pDBC->addDraw( getNodeID(), TH_SIZE_NODES, tID, m_nFullBorderKernelIndex, 1, true ); + } else { + char cPATH[256]; + FILE *fd; + sprintf( cPATH, "data/device_draws/%s.raw", tID ); + fd = fopen( cPATH, "wb"); + if( fd != NULL ) { + fwrite( &m_nFullBorderDataIndex, sizeof(uint32_t), 1, fd ); + fwrite( m_pThresholdData, sizeof( thresholdNode ), m_nFullBorderDataIndex, fd ); + fclose( fd ); + m_pDBC->addDraw( getNodeID(), TH_SIZE_NODES, tID, m_nFullBorderKernelIndex, 1 ); + } else { + LOG_ERROR("Cannot open DRAW file!"); + }; + }; + free( tID ); + };*/ + + handleDeviceDraw( m_nFullBorderKernelIndex, m_pThresholdData, TH_SIZE_NODES ); + }; + }; +#ifdef DEBUG + LOG("FINISH SAVE BOARD DATA"); +#endif + m_nFullBorderDataIndex = 0; + setWM( CWM_SET_MODE_DETECTOR ); + }; + }; + break; + case CMD_GETFILE: + break; + case CMD_RESTART: + break; + case CMD_GET_PARAMETERS: + case CMD_PARAMETERS: + case CMD_SET_PARAMETERS: { + uint8_t cWM = getWM(); + if( cWM == CWM_WAIT_PARAMS || cWM == CWM_INITIAL_WAIT_PARAM ){ +#ifdef DEBUG + LOG("Finish Get Params"); +#endif + if( SUB_CMD == SUB_DATA_INTEGRITY_VALID ){ + PLGS_3D_PARAMETERS tParam = (PLGS_3D_PARAMETERS)(pReceivedPackage + 6); + //memcpy( &m_sLGS_MASTER_PARAMETERS, tParam, sizeof(LGS_3D_PARAMETERS) ); + if( cWM == CWM_INITIAL_WAIT_PARAM ) { + setWM( CWM_INITIAL_GET_MASKS_INFO ); + } else { + setWM( CWM_IDLE ); + }; + } else { + LOG_ERROR("Data Integrity Error(on Get Parameters)!"); + if( cWM == CWM_INITIAL_WAIT_PARAM ) { + setWM( CWM_INITIAL_GET_PARAM ); + } else { + setWM( CWM_GET_PARAMS ); + }; + }; + } else { + LOG_ERROR("Not Requested Parameters Package!"); + }; + break; + }; + case CMD_SET_HZ_INFO: { + uint8_t cWM = getWM(); + if( cWM == CWM_WAIT_MASK_INFO || cWM == CWM_INITIAL_WAIT_MASKS_INFO ) { +#ifdef DEBUG + LOG("Finish Get HZ INFO"); +#endif + m_nDevicePolyCount = pReceivedPackage[6]; + + m_nCurrentMaskID = m_pDBC->getLRFMaskID( getDeviceID() ); + if ( m_nCurrentMaskID == 0 ) { + m_nCurrentMaskID = m_pDBC->addLRFMask( getDeviceID() ); + } else { + // Clear Existed Masks + m_pShadow->clear(); + m_pDBC->cleanLRFMask( m_nCurrentMaskID ); + }; +#ifdef DEBUG + char tB[64]; + sprintf( tB, "Mask Info: %d vertexes: %d", m_nCurrentMaskID, m_nDevicePolyCount ); + LOG(tB); +#endif + if( m_nDevicePolyCount ){ + m_pDBC->setLRFMaskStatus( m_nCurrentMaskID, ( SUB_CMD > 0 ) ); + } else { + m_pDBC->setLRFMaskStatus( m_nCurrentMaskID, false ); + }; + if( m_nDevicePolyCount && m_nCurrentMaskID ){ + if( cWM == CWM_INITIAL_WAIT_MASKS_INFO ) { + setWM( CWM_INITIAL_GET_VERTEX_DATA ); + } else { + setWM( CWM_IDLE ); + }; + } else { + setWM( CWM_IDLE ); + }; + }; + break; + }; + case CMD_SET_HZ_POLY: { +#ifdef DEBUG + LOG("Finish Get HZ POLY"); +#endif + uint8_t r = pReceivedPackage[6]; + uint8_t g = pReceivedPackage[7]; + uint8_t b = pReceivedPackage[8]; + uint32_t tLID = m_pDBC->addLRFMaskPolygone( m_nCurrentMaskID, r, g, b ); + + + //simplePolygone* tPolygone; + //tPolygone = new simplePolygone(); + //if (tPolygone != NULL) { + if( tLID ) { + uint8_t pCount = pReceivedPackage[5]; + //tPolygone->count = pReceivedPackage[5]; + //tPolygone->color[0] = pReceivedPackage[6]; + //tPolygone->color[1] = pReceivedPackage[7]; + //tPolygone->color[2] = pReceivedPackage[8]; + +#if defined( __linux__ ) && !defined( __GUI__ ) + //tPolygone->points = (simplePoint*)malloc(sizeof(simplePoint) * tPolygone->count); +#else + //tPolygone->points = (QPoint*)malloc(sizeof(QPoint) * tPolygone->count); +#endif + //if (tPolygone->count && tPolygone->points != NULL) { + if( pCount ) { + char tB[64]; + sprintf( tB, "Have Poly[%d] of %d Points", tLID, pCount ); + LOG( tB ); + uint16_t x, y; + int index = 9; + for (int i = 0; i < pCount; i++) { + x = pReceivedPackage[index++]; + x = (x << 8) | pReceivedPackage[index++]; + y = pReceivedPackage[index++]; + y = (y << 8) | pReceivedPackage[index++]; + //tPolygone->points[i].setX(x); + //tPolygone->points[i].setY(y); + m_pDBC->addLRFMaskPolygonePoint( tLID, x, y ); + }; + //m_pShadow->addPoly(tPolygone); + // } else { + // free( tPolygone ); + }; + }; + m_nCurrentPolyID++; + if ( m_nCurrentPolyID < m_nDevicePolyCount ) { + setWM( CWM_INITIAL_GET_VERTEX_DATA ); + } else { + //setWM( CWM_IDLE ); + setWM( CWM_GET_BORDER ); + m_nFullBorderKernelIndex = m_sLRF_DATA.draw_lrf_id; + } + break; + }; + case CMD_SET_HZ_POLY_ACK: { + m_nCurrentPolyID = SUB_CMD; + if (m_nCurrentPolyID < m_pShadow->getPolyCount()) { + simplePolygone* tPoly; + tPoly = m_pShadow->getPoly(m_nCurrentPolyID); + if (tPoly != NULL) { + setShadowPoly(tPoly); + } else { + }; + } else { +#ifdef DEBUG + LOG("Send RayTraces"); +#endif + vectorZoneMask VZ; + if (m_pShadow->getZoneMask(VZ)) { + if (setShadowTrace(&VZ)) { + } else { + }; + } else { + }; + }; + break; + }; + case CMD_GET_SERIAL_NUMBER: + break; + case CMD_SET_ADDRESS: + break; + case CMD_GET_SOFTWARE_VERSION: + break; + case CMD_UNSUPPORTED: + break; + case CMD_SET_COMM_SPEED: + break; + case CMD_FULL_RESET: +#ifdef DEBUG + LOG("Full Reset ACK"); +#endif + break; + case CMD_CAMERA: + break; + case CMD_SET_SERIAL_NUMBER: + break; + case CMD_BOARDDATA: + break; + case CMD_GET_CAMERA_PARAMETERS: + break; + case CMD_SET_CAMERA_PARAMETERS: + break; + case CMD_RELAY: + break; + case CMD_GET_RELAY_PARAMETERS: + break; + case CMD_SET_RELAY_PARAMETERS: + break; + case CMD_FS_SUB_PACKET: + break; + case CMD_STATE_2:{ + //if( cWM != CWM_GET_STATUS ) { + // LOG("Wrong WM - No Status Requested!"); + //} else { + LRF_WORK_MODE tStatus = ( LRF_WORK_MODE ) SUB_CMD; + uint8_t evtCnt = pReceivedPackage[DATA_BEGIN_IDX]; + + if ( tStatus > WM_NONE ) { + if ( PKG_LEN > 10 ) { + ALG_RUN_STATUS *ptr = (ALG_RUN_STATUS *)&pReceivedPackage[DATA_BEGIN_IDX + 1]; + m_pDBC->update3DRuntimeStatus( getDeviceID(), ptr ); + }; + if ( evtCnt ) { + char tB[64]; + sprintf( tB, "Have [%d] Events!", evtCnt ); + LOG(tB); + setWM( CWM_GET_EVENTS ); + } else { + //LOG("No Events!"); + setWM( CWM_IDLE ); + }; + } else { + LOG("STATUS WM_NONE!"); + setWM( CWM_IDLE ); + }; + /* + if( m_sDeviceStatus.Status != tStatus ){ + LOG("Device Status Changed!"); + switch( tStatus ){ + case STG_STUDY: { + //EVENT_CONTAINER * tEVT; + tEVT = createBasicEvent( m_sNodeData.node_id, EVT_CLASS_SENSOR_3D, EVT_STUDY, NULL, "Device in STUDY mode"); + m_pEventHeap->broadcast(tEVT); + break; + }; + case STG_READY: { + //basicEvent* tEVT; + tEVT = createBasicEvent( m_sNodeData.node_id, EVT_CLASS_SENSOR_3D, EVT_READY, NULL, "Device in DETECTION mode"); + m_pEventHeap->broadcast(tEVT); + break; + }; + case STG_BUSY: { + //basicEvent* tEVT; + tEVT = createBasicEvent( m_sNodeData.node_id, EVT_CLASS_SENSOR_3D, EVT_ERROR, NULL, "Device in BUSY mode"); + m_pEventHeap->broadcast(tEVT); + break; + }; + }; + m_sDeviceStatus.Status = tStatus; + }; + */ + //}; + + + //setWM( CWM_IDLE ); + break; + }; + case CMD_EVT:{ + char tBuffer[256]; + uint8_t tCount = pReceivedPackage[SUB_CMD_IDX];//DATA_BEGIN_IDX]; + if( tCount > 0 ){ + CLIENT_EVENT *cEVT = (CLIENT_EVENT*)& pReceivedPackage[DATA_BEGIN_IDX];// + 1]; + for( uint8_t xindex = 0; xindex < tCount; xindex++ ) { + switch (cEVT[xindex].type) { + case EVT_TARGET_2D_WHITE: + case EVT_TARGET_2D_BLACK: + case EVT_TARGET_3D_WHITE: + case EVT_TARGET_3D_BLACK:{ + TARGET_DATA *tData; + tData = prepareTargetData(cEVT+xindex); + if(tData != NULL){ + EVENT_CONTAINER * bEVT = NULL; +#ifndef DISABLE_FRIENDLY_MESSAGES + sprintf(tBuffer, "%s[%d] %s target \tRange: %.2fm. \tAzimuth: %.2f \tElevation: %.2f \tTS: %d@%d W:%.2f", + ((tData->lrf_id < 8) ? "M" : "S"), + //bKernelID, + tData->lrf_id, + ((cEVT[xindex].type == EVT_TARGET_3D_WHITE) ? "White" : "Black"), + tData->local_target.r, + tData->local_target.fi, + tData->local_target.tetta, + cEVT[xindex].uts, + cEVT[xindex].ums, + tData->area + ); + #ifdef DEBUG_EXTRA + LOG( tBuffer ); + #endif + bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, (basicEventTypeID) cEVT[xindex].type, NULL, tBuffer, tData ); +#else + bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, (basicEventTypeID) cEVT[xindex].type, NULL, NULL, tData ); +#endif + if (bEVT != NULL) { + m_pEventHeap->broadcast(bEVT); + } else { + free(tData); + }; + } else { + LOG_ERROR("Error Preparing Target Data!"); + }; + break; + }; + default:{ + sprintf( tBuffer, "Event[%d] Type:[%d]", xindex, cEVT[xindex].type ); + break; + }; + }; + }; + //set new stage2 + m_nIdleTarget = m_nIdleTarget >> 1; + if( m_nIdleTarget < LGS_MIN_IDLE_DELAY ) m_nIdleTarget = LGS_MIN_IDLE_DELAY; + setWM( CWM_GET_EVENTS ); + } else { + LOG("No Events in Package???"); + m_nIdleTarget = m_nIdleTarget << 1; + if (m_nIdleTarget > LGS_MAX_IDLE_DELAY) m_nIdleTarget = LGS_MAX_IDLE_DELAY; + setWM( CWM_IDLE ); + }; + break; + }; + case CMD_GET_WIDTH_TABLE: + break; + case CMD_SET_WIDTH_TABLE: + break; + case CMD_GET_VOLTAGE: + break; + case CMD_GET_VOLTAGE_PARAMETERS: + break; + case CMD_SET_VOLTAGE_PARAMETERS: + break; + case CMD_GET_HZ_DATA: + break; + case CMD_SET_HZ_DATA: + break; + case CMD_GET_CALIBRATION_TABLE: + break; + case CMD_SET_CALIBRATION_TABLE: + break; + case CMD_GET_LRF_DISABLE: + break; + case CMD_SET_LRF_DISABLE: + break; + case CMD_GET_ZOOM_TABLE: + break; + case CMD_SET_ZOOM_TABLE: + break; + case CMD_GET_TILT_TABLE: + break; + case CMD_SET_TILT_TABLE: + break; + case CMD_GET_HZ_ENABLE: + break; + case CMD_SET_HZ_ENABLE: + break; + case CMD_FLIP_COMPLETE: { + tEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_FLIP, NULL, "Flip Complete"); + m_pEventHeap->broadcast(tEVT); + break; + }; + case CMD_SCAN_COMPLETE: { + tEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_SCAN, NULL, "Scan Complete"); + m_pEventHeap->broadcast(tEVT); + break; + }; + case CMD_TARGET: { + tEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_TARGET_3D_WHITE, NULL, "Target"); + m_pEventHeap->broadcast(tEVT); + break; + }; + case CMD_TARGET_WW: { + + tEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_TARGET_3D_WHITE, NULL, "Target with Width"); + m_pEventHeap->broadcast(tEVT); + break; + }; + case CMD_TARGET_MW: { + tData = (CLIENT_EVENT*)malloc(sizeof(CLIENT_EVENT)); + if (tData != NULL) { + /* + tData->mSampleID = (pReceivedPackage[5] << 24) + (pReceivedPackage[6] << 16) + (pReceivedPackage[7] << 8) + pReceivedPackage[8]; + tData->mInfo = pReceivedPackage[9]; + tData->mRange = (pReceivedPackage[12] << 8) + pReceivedPackage[11]; + tData->mWidth = (pReceivedPackage[12] << 24) + (pReceivedPackage[13] << 16) + (pReceivedPackage[14] << 8) + pReceivedPackage[15]; + //if( m_pMapWidget != NULL ) m_pMapWidget->addTarget(tData->mSampleID ); + //if( m_pRadarWidget != NULL ) m_pRadarWidget->addTarget(tData->mSampleID, tData->mRange, m_bIsMaster ); + tEVT = createBasicEvent( m_DbId, EVT_CLASS_SENSOR, EVT_TARGET_3D_WHITE, NULL, "White Intruder Detection", tData ); + m_pEventHeap->broadcast( tEVT ); + */ + }; + break; + }; + case CMD_TARGET_MB: { + tData = (CLIENT_EVENT*)malloc(sizeof(CLIENT_EVENT)); + if (tData != NULL) { + /* + tData->mSampleID = (pReceivedPackage[5] << 24) + (pReceivedPackage[6] << 16) + (pReceivedPackage[7] << 8) + pReceivedPackage[8]; + tData->mInfo = pReceivedPackage[9]; + tData->mRange = (pReceivedPackage[12] << 8) + pReceivedPackage[11]; + tData->mWidth = (pReceivedPackage[12] << 24) + (pReceivedPackage[13] << 16) + (pReceivedPackage[14] << 8) + pReceivedPackage[15]; + //if( m_pMapWidget != NULL ) m_pMapWidget->addTarget(tData->mSampleID, m_bIsMaster ); + //if( m_pRadarWidget != NULL ) m_pRadarWidget->addTarget(tData->mSampleID, tData->mRange, m_bIsMaster ); + tEVT = createBasicEvent( m_DbId, EVT_CLASS_SENSOR, EVT_TARGET_3D_BLACK, NULL, "Target Black", tData ); + m_pEventHeap->broadcast( tEVT ); + */ + }; + break; + }; + case CMD_TARGET_ZZ: { + uint8_t cWM = getWM(); + if( cWM == CWM_IDLE ){ + tData = (CLIENT_EVENT*)malloc(sizeof(CLIENT_EVENT)); + if (tData != NULL) { + /* + char tBuffer[256]; + float fRange, fAzimuth, fElevation; + int sX, sY, eX, eY, cX, cY; + for( int index = 0; index < sizeof(CLIENT_EVENT); index++ ){ + ((uint8_t*)tData)[index] = pReceivedPackage[5+index]; + }; + + fRange = 300.0 / 4095.0 * tData->mRange; + makeCds( tData->mStartID, sX, sY, ( tData->mInfo & 0xFF000000 ) > 0 ); + makeCds( tData->mEndID, eX, eY, ( tData->mInfo & 0xFF000000 ) > 0 ); + cX = ((sX+eX)>>1); + cY = ((sY+eY)>>1); + fAzimuth = (360.0 / TH_LINE_NODES )*cX; + fElevation = 90.0 - (90.0/Q_SCAN_COUNT )*cY; + //if( m_pMapWidget != NULL ) m_pMapWidget->addTarget( makeIds( cX, cY ), m_bIsMaster ); + //if( m_pRadarWidget != NULL ) m_pRadarWidget->addTarget( makeIds( cX, cY ), tData->mRange, m_bIsMaster ); + if( ( tData->mInfo & 0x00FF0000 ) > 0 ){ + sprintf( tBuffer, "[%s]:%.2fm. Azimuth: %.2f Elevation: %.2f", + (m_bIsMaster?"M":"S"), + fRange, + fAzimuth, + fElevation + ); + tEVT = createBasicEvent( m_DbId, EVT_CLASS_SENSOR, EVT_TARGET_3D_WHITE, NULL, tBuffer, tData ); + } else { + sprintf( tBuffer, "[%s]:%.2fm. Azimuth: %.2f Elevation: %.2f", + (m_bIsMaster?"M":"S"), + fRange, + fAzimuth, + fElevation + ); + tEVT = createBasicEvent( m_DbId, EVT_CLASS_SENSOR, EVT_TARGET_3D_BLACK, NULL, tBuffer, tData ); + }; + m_pEventHeap->broadcast( tEVT ); + */ + }; + }; + break; + }; + case CMD_ACK_TWINK_LINK:{ + char tB[64]; + m_bSlaveConnectionStatus = SUB_CMD; + m_bTWINC =true; + sprintf( tB, "WINK SUPPORTED! [0x%02X]", SUB_CMD ); + LOG( tB ); + setWM( CWM_INITIAL_GET_PARAM ); + break; + }; + case CMD_ACK:{ + setWM( CWM_IDLE ); + break; + }; + case CMD_NACK:{ + if( SUB_CMD == CMD_QUERY_TWINK_LINK ) { + m_bTWINC =true; + LOG("TWINK SUPPORTED BUT TROUBLE!"); + setWM( CWM_INITIAL_GET_PARAM ); + }; + break; + }; + case CMD_IDONK:{ + char tB[64]; + sprintf( tB, "Not Recognized Command [0x%02X]", SUB_CMD ); + LOG( tB ); + break; + }; + case CMD_NONE: + default:{ + break; + }; + }; // CMD SWITCH + return true; +}; + +#undef SIZE_IDX +#undef DEV_ID_IDX +#undef CMD_IDX +#undef SUB_CMD_IDX +#undef DATA_BEGIN_IDX + +bool device3DSensor::startGetScanData( uint8_t kID, uint32_t *th_zone ){ + //if( getOperation() == CMD_FULL_BORDER ) return true; + m_mDataMutex.lock(); + if( th_zone == NULL ){ + if( m_pThresholdData != NULL ) free(m_pThresholdData); + m_pThresholdData = (thresholdNode *) malloc( sizeof(thresholdNode) * TH_SIZE_NODES ); + } else { + m_pThresholdData = (thresholdNode *) th_zone; + }; + m_nFullBorderDataIndex = 0; + m_nFullBorderKernelIndex = kID; + m_mDataMutex.unlock(); + if( m_pThresholdData!= NULL ){ + LOG("TH Assigned - OK"); + return setOperation( CMD_FULL_BORDER ); + } else { + LOG_ERROR("TH Assigned - NOK (mem issue)"); + }; + return false; +}; + +bool device3DSensor::startGetParameters( uint32_t timeout ){ + //if (CMD_GET_PARAMETERS == getOperation()) return true; + return setOperation( CMD_GET_PARAMETERS ); +}; + +bool device3DSensor::startDeviceReset( bool FullReset ){ + if( FullReset ){ + //if (CMD_FULL_RESET == getOperation()) return true; + return setOperation( CMD_FULL_RESET ); + }; + //if (CMD_RESET == getOperation()) return true; + return setOperation( CMD_RESET ); +}; + +bool device3DSensor::startUploadMask(void){ + simplePolygone *tPoly; + m_nCurrentPolyID = 0; +#ifndef __linux__ + m_pShadow->rasterizeVertexes(); +#endif + if (setOperation(CMD_SET_HZ_POLY, true)){ + return true; + }; + return false; +}; + +bool device3DSensor::startStopMotors( void ){ + if (setOperation(CMD_DHWM_STOP_MOTORS, true)){ + return true; + }; + return false; +}; + +bool device3DSensor::startStartMotors( void ){ + if (setOperation(CMD_DHWM_START_MOTORS, true)){ + return true; + }; + return false; +}; + +bool device3DSensor::startMasksStatus(bool Active){ + if ( m_pShadow!=NULL ){ + m_pShadow->setActive(Active); + if (setOperation(CMD_SET_HZ_STATUS, true)){ + return true; + }; + }; + return false; +}; + +bool device3DSensor::setOperation( E_LGS_CMD opCode, bool fNOW ){ + m_mStatusMutex.lock(); +/* + if( m_sDeviceStatus.CurrentOperation == CMD_NONE ){ + m_sDeviceStatus.CurrentOperation = opCode; + } else if( fNOW ){ + m_mStatusMutex.unlock(); + return false; + } else if( m_sDeviceStatus.PendingOperation == CMD_NONE ){ + m_sDeviceStatus.PendingOperation = opCode; + } else { + m_mStatusMutex.unlock(); + return false; + }; +*/ + m_mStatusMutex.unlock(); + return true; +}; + +void device3DSensor::simulateTarget( void ){ + TARGET_DATA * tData = NULL; + CLIENT_EVENT cEVT; + char tB[128]; + +#ifdef SIMULATE_3D_TARGETS + + systemAnchor* SA = systemAnchor::getInstance(); + switch ( m_bSymStage ) { + case 1: { + if( IntruderIsVisible() ){ + tData = prepareSimData( m_oIntruder_ ); + if ( tData ) { + EVENT_CONTAINER *bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_TARGET_3D_WHITE, NULL, NULL, tData); + if (bEVT != NULL) { + m_pEventHeap->broadcast( bEVT ); + } else { + free( tData ); + }; + }; + }; + if ( m_oIntruder_.getZ() < 120.0f ) { + m_dIntruderMove.z = 20.0f; + } else { + m_dIntruderMove.z = .0f; + }; + m_oIntruder_.setPositionXYZ( + m_oIntruder_.getX() + m_dIntruderMove.x, + m_oIntruder_.getY() + m_dIntruderMove.y, + m_oIntruder_.getZ() + m_dIntruderMove.z, + SA->getUTMZone() + ); + m_oIntruder_.updateMatrix(); + break; + }; + case 2:{ + if( IntruderIsVisible() ){ + tData = prepareSimData( m_oIntruder_ ); + if ( tData ) { + EVENT_CONTAINER *bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_TARGET_3D_WHITE, NULL, NULL, tData); + if (bEVT != NULL) { + m_pEventHeap->broadcast( bEVT ); + } else { + free( tData ); + }; + }; + }; + m_oIntruder_.setPositionXYZ( + m_oIntruder_.getX() + m_dIntruderMove.x, + m_oIntruder_.getY() + m_dIntruderMove.y, + m_oIntruder_.getZ() + m_dIntruderMove.z, + SA->getUTMZone() + ); + m_oIntruder_.updateMatrix(); + + if( HunterIsVisible() ){ + tData = prepareSimData( m_oHunter_ ); + if ( tData ) { + EVENT_CONTAINER *bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_TARGET_3D_WHITE, NULL, NULL, tData); + if (bEVT != NULL) { + m_pEventHeap->broadcast( bEVT ); + } else { + free( tData ); + }; + }; + }; + headHunterTo( m_oIntruder_ ); + if ( m_oHunter_.getZ() < 120.0f ){ + m_dHunterMove.z = 20.0f; + } else { + m_dHunterMove.z = .0f; + }; + m_oHunter_.setPositionXYZ( + m_oHunter_.getX() + m_dHunterMove.x, + m_oHunter_.getY() + m_dHunterMove.y, + m_oHunter_.getZ() + m_dHunterMove.z, + SA->getUTMZone() + ); + m_oHunter_.updateMatrix(); + break; + }; + case 3:{ + if( IntruderIsVisible() ){ + tData = prepareSimData( m_oIntruder_ ); + if ( tData ) { + EVENT_CONTAINER *bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_TARGET_3D_WHITE, NULL, NULL, tData); + if (bEVT != NULL) { + m_pEventHeap->broadcast( bEVT ); + } else { + free( tData ); + }; + }; + }; + m_oIntruder_.setPositionXYZ( + m_oIntruder_.getX() + m_dIntruderMove.x, + m_oIntruder_.getY() + m_dIntruderMove.y, + m_oIntruder_.getZ() + m_dIntruderMove.z, + SA->getUTMZone() + ); + m_oIntruder_.updateMatrix(); + + if( HunterIsVisible() ){ + tData = prepareSimData( m_oHunter_ ); + if ( tData ) { + EVENT_CONTAINER *bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_TARGET_3D_WHITE, NULL, NULL, tData); + if (bEVT != NULL) { + m_pEventHeap->broadcast( bEVT ); + } else { + free( tData ); + }; + }; + }; + m_oHunter_.setPositionXYZ( + m_oHunter_.getX() + m_dHunterMove.x, + m_oHunter_.getY() + m_dHunterMove.y, + m_oHunter_.getZ() + m_dHunterMove.z, + SA->getUTMZone() + ); + m_oHunter_.updateMatrix(); + break; + }; + case 4:{ + if( HunterIsVisible() ){ + tData = prepareSimData(m_oHunter_); + if ( tData ) { + EVENT_CONTAINER *bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_TARGET_3D_WHITE, NULL, NULL, tData); + if (bEVT != NULL) { + m_pEventHeap->broadcast( bEVT ); + } else { + free( tData ); + }; + }; + }; + m_oHunter_.setPositionXYZ( + m_oHunter_.getX() + m_dHunterMove.x, + m_oHunter_.getY() + m_dHunterMove.y, + m_oHunter_.getZ() + m_dHunterMove.z, + SA->getUTMZone() + ); + m_oHunter_.updateMatrix(); + break; + }; + case 5:{ + if( HunterIsVisible() ){ + tData = prepareSimData(m_oHunter_); + if ( tData ) { + EVENT_CONTAINER *bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, EVT_TARGET_3D_WHITE, NULL, NULL, tData); + if (bEVT != NULL) { + m_pEventHeap->broadcast( bEVT ); + } else { + free( tData ); + }; + }; + }; + if ( m_oHunter_.getZ() > 1.0f ){ + m_dHunterMove.z = -20.0f; + } else { + m_dHunterMove.z = .0f; + m_bSymStage = 5; + }; + m_oHunter_.setPositionXYZ( + m_oHunter_.getX(), + m_oHunter_.getY(), + m_oHunter_.getZ() + m_dHunterMove.z, + SA->getUTMZone() + ); + m_oHunter_.updateMatrix(); + break; + }; + case 6:{ + // Finish Sim + break; + }; + }; +#else + cEVT.range = 1050; + cEVT.type = EVT_TARGET_3D_WHITE; + cEVT.th_id = 1211; + cEVT.a_th_node = 1211; + cEVT.k_id = 5; + cEVT.w_cnt = 5; + + //tData = m_pMasterNode-> + tData = prepareTargetData( &cEVT ); + if( tData != NULL ){ + EVENT_CONTAINER *bEVT = createBasicEvent( getNodeID(), EVT_CLASS_SENSOR_3D, (basicEventTypeID)cEVT.type, NULL, NULL, tData); + if (bEVT != NULL) { + m_pEventHeap->broadcast( bEVT ); + }; + }; +#endif +}; + +#ifdef SIMULATE_3D_TARGETS + +#include + + +void device3DSensor::headIntruderTo( basicPosition &bp ){ + float A = bp.getX() - m_oIntruder_.getX(); + float B = bp.getY() - m_oIntruder_.getY(); + float C = bp.getZ() - m_oIntruder_.getZ(); + float time = sqrtf( A*A + B*B ) / m_dIntruderSpeed; + m_dIntruderMove.x = A / time; + m_dIntruderMove.y = B / time; + m_dIntruderMove.z = C / time; +}; + +void device3DSensor::headHunterTo( basicPosition &bp ){ + float A = bp.getX() - m_oHunter_.getX(); + float B = bp.getY() - m_oHunter_.getY(); + float C = bp.getZ() - m_oHunter_.getZ(); + float time = sqrtf( A*A + B*B ) / m_dHunterSpeed; + m_dHunterMove.x = A / time; + m_dHunterMove.y = B / time; + m_dHunterMove.z = C / time; +}; + +bool device3DSensor::IntruderIsVisible(){ + if ( m_oIntruder_.getZ() > 5 ) { + float A = m_oPosition.getX() - m_oIntruder_.getX(); + float B = m_oPosition.getY() - m_oIntruder_.getY(); + if( sqrtf( A*A + B*B ) < m_sLRF_DATA.max_range ) return true; + }; + return false; +}; + +bool device3DSensor::HunterIsVisible(){ + if ( m_oHunter_.getZ() > 5 ) { + float A = m_oPosition.getX() - m_oHunter_.getX(); + float B = m_oPosition.getY() - m_oHunter_.getY(); + if( sqrtf( A*A + B*B ) < m_sLRF_DATA.max_range ) return true; + }; + return false; +}; + +#endif + +#undef LOG +#undef LOG_ERROR + + diff --git a/lib/App/common/deviceNode3D.h b/lib/App/common/deviceNode3D.h new file mode 100644 index 00000000..8f0f4845 --- /dev/null +++ b/lib/App/common/deviceNode3D.h @@ -0,0 +1,140 @@ +#ifndef __DEVICE_NODE_3D_HEADERS__ +#define __DEVICE_NET_NODE_3D_HEADERS__ + +#include "../components/base/basicEngine.h" +#include "../components/base/basicDualThread.h" +#include "../components/base/basicLogCollection.h" +#include "../components/base/basicEventHeap.h" +#include "../components/base/basicPosition.h" +#include "../components/object/objectSystemAnchor.h" +#include "../components/base/basicSettingsProvider.h" +#include "../alg/lgs/mask.h" + +#include "../data/net/clientPort.h" +#include "../data/protocol/protocolLGS3D_client.h" +#include "../hardware/soc/general/3DLRF.h" + + +//#include "../hardware/sensors/lrf/lrf_3d.h" + +#include "deviceNodeSensor.h" + +//#define SIMULATE_3D_TARGETS + +#ifdef SIMULATE_3D_TARGETS + #include "../components/base/basicSettingsProvider.h" +#endif + +#define LGS_TIMEOUT_COUNT 100 +#define LGS_MAX_IDLE_DELAY 40 // x10 msec +#define LGS_MIN_IDLE_DELAY 1 // x10 msec + +#define USE_MUTEX true +#define DONT_USE_MUTEX false + +class device3DSensor: public deviceNodeSensor, public basicThread, public protocolLGS3D_Client{ + private: + //basicLogCollection * m_pLog; + //basicEventHeap * m_pEventHeap; + + //DBC_LRF_DATA m_sDATA; + + //LGS_3D_PARAMETERS m_sLGS_MASTER_PARAMETERS; + //LGS_3D_PARAMETERS m_sLGS_SLAVE_PARAMETERS; + + //DEVICE_STATUS m_sDeviceStatus; + //SOFTWARE_INFO m_sDeviceSoftNFO; + + //char m_pHost[255]; + //uint16_t m_nPort; + bool m_bTWINC; + uint8_t m_bSlaveConnectionStatus; + int m_nBusyCounter; + int m_nIdleCounter; + int m_nIdleTarget; + + basicMutex m_mPackageMutex; + basicMutex m_mStatusMutex; + basicMutex m_mDataMutex; + + thresholdNode * m_pThresholdData; + + uint32_t m_nFullBorderDataIndex; + uint8_t m_nFullBorderKernelIndex; + + uint8_t m_nDevicePolyCount; + uint32_t m_nCurrentPolyID; + uint32_t m_nCurrentMaskID; + ShadowMask * m_pShadow; + +#ifdef SIMULATE_3D_TARGETS + config_setting_t * m_pSimulationConfig; + basicPosition m_oIntruder_Start; + basicPosition m_oIntruder_Finish; + + basicPosition m_oIntruder_; + C3D_DECART m_dIntruderMove; + float m_dIntruderSpeed; + + int m_nIntruder_time; + + basicPosition m_oHunter_Home; + basicPosition m_oHunter_; + C3D_DECART m_dHunterMove; + float m_dHunterSpeed; + + uint8_t m_bSymStage; + + bool IntruderIsVisible(); + bool HunterIsVisible(); + void headIntruderTo( basicPosition &bp ); + void headHunterTo( basicPosition &bp ); + void restartSimulation( void ); + TARGET_DATA * prepareSimData( basicPosition &bp ); + uint32_t m_nAutoScript; +#endif + + bool setOperation( E_LGS_CMD opCode, bool fNOW = false ); + bool forceOperation( E_LGS_CMD opCode ); + void setCompelition( uint8_t Perc ); + E_LGS_CMD getOperation( void ); + void promoteOperation( void ); + void completeOperation( bool success = true ); + void cleanOperation( void ); + void comSetIdle( bool useMutex = true ); + void comSetBusy( bool useMutex = true ); + bool comIsIdle( void ); + void cleanDataTH( void ); + bool saveTHPicture( thresholdNode *ptr, CSTR uid, bool master = true, bool byMinimum = false, bool monochrome = false ); + protected: + virtual void m_fThreadProc( void ); + virtual bool packetHandler( protocolPackage* Package ); + public: + TARGET_DATA * prepareTargetData(CLIENT_EVENT* CE); + explicit device3DSensor( uint32_t dbID ); + virtual ~device3DSensor(); + virtual bool startService(); + virtual bool stopService(); + virtual bool validate(); + virtual void simulateTarget( void ); + + bool startGetScanData( uint8_t kID = 0, uint32_t *th_zone = NULL ); + bool startGetParameters( uint32_t timeout=0 ); + bool startUploadMask(void); + bool startDeviceReset( bool FullReset = true ); + bool startStopMotors( void ); + bool startStartMotors( void ); + bool startMasksStatus(bool Active); + + basicPosition * getPosition(void){ return &m_oPosition; }; + void updateSettings(void); + + // New Order + thresholdNode * grabDataAccess( void ); + void releaseDataAccess( void ); + + bool lastTaskComplete( void ); + void cleanLastTaskStatus( void ); +}; + +#endif diff --git a/lib/App/common/deviceNodeCamera.cpp b/lib/App/common/deviceNodeCamera.cpp new file mode 100644 index 00000000..5dc52721 --- /dev/null +++ b/lib/App/common/deviceNodeCamera.cpp @@ -0,0 +1,1432 @@ +#include "deviceNodeCamera.h" +#include "../../components/base/basicCameraInfo.h" +#include "../../components/object/objectSystemAnchor.h" + +#include "../../hardware/uart/serialPort.h" +#include "../../hardware/uart/serialSOL.h" + +#include "../../data/protocol/protocolPTZ_VISCA.h" +#include "../../data/protocol/protocolPTZ_ONVIF.h" +#include "../../data/protocol/protocolPTZ_PELCO.h" + +#include "hardwareManager.h" +#include "hardwareResourceSerialProvider.h" +//#include "rgooseModuleEmbedVideo.h" + +#define LOG( X ) deviceNode::m_pLog->Log( "RCAM", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + deviceNode::m_pLog->Log( "RCAM", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) deviceNode::m_pLog->Log( "RCAM", this, _LOG_ERROR, X ); +#endif + +// all sizes in mm + +static const float AC_imager_diag[12] = { 5.0f, 5.68f, 6.0f, 6.592f, 8.0f, 8.933f, 11.0f, 16.0f, 22.5f, 30.1f, 43.3f, 69.7f }; +static const float AC_imager_width[12] = { 4.0f, 4.536f, 4.8f, 5.27f, 6.4f, 7.176f, 8.8f, 12.8f, 18.0f, 25.1f, 36.0f, 56.0f }; +static const float AC_imager_height[12] = { 3.0f, 3.416f, 3.6f, 3.96f, 4.8f, 5.319f, 6.6f, 9.6f, 13.5f, 16.7f, 24.0f, 41.5f }; + +#define CAM_FOCAL_LENGTH_CNT 49 +static const float cam_predef_focal_length[CAM_FOCAL_LENGTH_CNT]={ + 2.7f, + 3.0f, + 3.2f, + 3.5f, + 3.7f, + 3.9f, + 4.0f, + 4.3f, + 4.8f, + 5.0f, + 5.1f, + 5.5f, + 5.8f, + 6.0f, + 6.2f, + 6.6f, + 7.0f, + 7.1f, + 7.5f, + 7.6f, + 8.0f, + 8.6f, + 8.9f, + 9.0f, + 9.2f, + 9.3f, + 10.0f, + 10.5f, + 10.6f, + 10.7f, + 11.0f, + 11.3f, + 12.0f, + 12.9f, + 13.0f, + 13.5f, + 13.6f, + 14.0f, + 14.6f, + 15.0f, + 15.1f, + 15.5f, + 16.0f, + 17.0f, + 17.5f, + 17.7f, + 18.0f, + 18.2f, + 19.0f +}; + + +deviceNodeCamera::deviceNodeCamera( uint32_t NodeID ): deviceNode( NodeID ), basicThread(){ + //m_pLog = basicLogCollection::getInstance(); + m_pBEH = basicEventHeap::getInstance(); + + m_tTimeTSeconds = 0; + m_pProtocol = NULL; + m_pTransport = NULL; + m_pCurrentROI = NULL; + m_nRealFrameWidth = 640; + //m_bState = 0; + //m_bBusy = true; + m_fMaxRange = m_fMinHFov = m_fMaxHFov = m_fMinVFov = m_fMaxVFov = .0f; + m_nRelativeMoveCounter = 0; + m_bRelativeMoveMatrix = 0; + m_fSpeedRise = 0.03f; + m_fRM_Pan = m_fRM_Tilt = m_fRM_Zoom = .0f; + //m_bSourceConnected = false; + //m_pSource = NULL; +}; + +deviceNodeCamera::deviceNodeCamera( DBC_NODE_DATA *Data ): deviceNode( Data ), basicThread(){ + //m_pLog = basicLogCollection::getInstance(); + m_pBEH = basicEventHeap::getInstance(); + + m_tTimeTSeconds = 0; + m_pProtocol = NULL; + m_pTransport = NULL; + m_pCurrentROI = NULL; + m_nRealFrameWidth = 640; + //m_bState = 0; + //m_bBusy = true; + m_fMaxRange = m_fMinHFov = m_fMaxHFov = m_fMinVFov = m_fMaxVFov = .0f; + m_nRelativeMoveCounter = 0; + m_bRelativeMoveMatrix = 0; + m_fSpeedRise = 0.03f; + m_fRM_Pan = m_fRM_Tilt = m_fRM_Zoom = .0f; + //m_bSourceConnected = false; + //m_pSource = NULL; +}; + +deviceNodeCamera::~deviceNodeCamera(){ + LOG("Destruct"); + //m_mQPROTECTOR.unlock(); + waitThreadEnd( true ); + LOG("Thread Del OK"); + if( m_pTransport!= NULL ) { + if( m_sCamData.uart_id ) { + DBC_UART_DATA *tData = NULL; + tData = m_pDBC->getUartData( m_sCamData.uart_id ); + switch( tData->type ) { + case UART_TYPE_HARDWARE:{ + delete((serialPort*)m_pTransport); + break; + }; + case UART_TYPE_SOL:{ + delete((serialSOL*)m_pTransport); + break; + }; + }; + } + }; + LOG("Transport Del OK"); + if( m_pProtocol != NULL ) { + switch( m_sCamData.protocol ) { + case CAM_CTRL_PROTO_VISCA: + delete( (protocolPTZ_VISCA *) m_pProtocol ); + break; + case CAM_CTRL_PROTO_PELCO: + delete( (protocolPTZ_PELCO *) m_pProtocol ); + break; + case CAM_CTRL_PROTO_ONVIF: + delete( (protocolPTZ_ONVIF *) m_pProtocol ); + break; + default: + delete( m_pProtocol ); + }; + }; + LOG("Proto Del OK"); + //if( m_pPosition != NULL ) delete( m_pPosition ); + //LOG("Pos Del OK"); + //if( m_bSourceConnected ){ + // if( m_pSource != NULL ){ + // m_pSource->_close(); + // delete( m_pSource ); + // }; + //}; + //LOG("Stream Del OK"); +}; + +void deviceNodeCamera::updateOpticalParameters( uint16_t frame_width, uint16_t frame_heigth ){ +#ifdef DEBUG + char tB[128]; +#endif + if( frame_width > 0 && frame_heigth > 0 ) { + m_nRealFrameWidth = frame_width; + m_nRealFrameHeight = frame_heigth; + float tFrameDiag = sqrtf( m_nRealFrameHeight*m_nRealFrameHeight+m_nRealFrameWidth*m_nRealFrameWidth ); + switch( m_sCamData.zoom_model ) { + case 0:{ + m_fMinFL = cam_predef_focal_length[m_sCamData.lens_f]; + m_fMinRange = calcMinDistance_mm( AC_imager_diag[m_sCamData.imager_type], m_fMinFL, tFrameDiag ); + m_fMaxFL = cam_predef_focal_length[m_sCamData.lens_f] * m_sCamData.zoom; + m_fMaxRange = calcMaxDistance_mm( AC_imager_diag[m_sCamData.imager_type], m_fMaxFL, tFrameDiag ); + if( m_fMaxRange > m_fMinRange ){ + m_fR2FL = ((m_fMaxFL - m_fMinFL) / (m_fMaxRange - m_fMinRange)); + } else { + m_fR2FL = .0f; + }; + break; + }; + case 1:{ + // Fixed Zoom + m_fMaxFL = m_fMinFL = cam_predef_focal_length[m_sCamData.lens_f]; + m_fMinRange = calcMinDistance_mm( AC_imager_diag[m_sCamData.imager_type], m_fMinFL, tFrameDiag ); + m_fMaxRange = calcMaxDistance_mm( AC_imager_diag[m_sCamData.imager_type], m_fMaxFL, tFrameDiag ); + m_fR2FL = .0f; + break; + }; + }; + m_pDBC->updateCamRange( m_sCamData.id, m_fMaxRange ); + m_fMinHFov = rad2deg(calcFOV_mm( AC_imager_width[m_sCamData.imager_type], m_fMinFL )); + m_fMaxHFov = rad2deg(calcFOV_mm( AC_imager_width[m_sCamData.imager_type], m_fMaxFL )); + + m_fMinVFov = rad2deg(calcFOV_mm( AC_imager_height[m_sCamData.imager_type], m_fMinFL )); + m_fMaxVFov = rad2deg(calcFOV_mm( AC_imager_height[m_sCamData.imager_type], m_fMaxFL )); +#ifdef DEBUG + LOG("Set Optical Parameters"); + sprintf( tB, "\tCapturing Frame: %dx%d ", frame_width, frame_heigth ); + LOG(tB); + sprintf( tB, "\tMinimal FL: %0.3fmm. Maximal FL: %0.3fmm. ", m_fMinFL, m_fMaxFL ); + LOG(tB); + sprintf( tB, "\tMinimal Range: %0.2fm. Maximal Range: %0.2fm. ", m_fMinRange, m_fMaxRange ); + LOG(tB); + sprintf( tB, "\tMaximal FOVs, Horizontal: %0.2f Vertical: %0.2f", m_fMinHFov, m_fMinVFov ); + LOG(tB); + sprintf( tB, "\tMinimal FOVs, Horizontal: %0.2f Vertical: %0.2f", m_fMaxHFov, m_fMaxVFov ); + LOG(tB); +#endif + }; +}; + +bool deviceNodeCamera::create(){ + + setWM( CAM_WS_INIT ); + + if( m_sNodeData.aux_id == 0 ) return false; + + DBC_CAM_DATA * tData = m_pDBC->getCamData( m_sNodeData.aux_id ); + if( tData != NULL ) { + memcpy( &m_sCamData, tData, sizeof(DBC_CAM_DATA) ); + free( tData ); + } else { + LOG_ERROR("Cannot Fetch CAM Data from Database!"); + return false; + }; + if( !( m_sCamData.lens_f < CAM_FOCAL_LENGTH_CNT ) ) m_sCamData.lens_f = CAM_FOCAL_LENGTH_CNT - 1; + + updateOpticalParameters( 640,480 ); + + if( m_sCamData.ptz_speed_step > .0f ) { + m_fSpeedRise = m_sCamData.ptz_speed_step; + }; + + //m_pPosition = new basicPosition();// m_sCamData.lat, m_sCamData.lon, m_sCamData.alt, m_sCamData.roll, m_sCamData.pitch, m_sCamData.yaw ); + + //if( m_pPosition == NULL ) { + // LOG_ERROR("Position Constructor Failure!"); + // return false; + //}; + + //m_oPosition.setPositionXYZ( m_sCamData.x, m_sCamData.y, m_sCamData.z ); + //m_oPosition.setOrientationDeg( m_sCamData.x_rot, m_sCamData.y_rot, m_sCamData.z_rot ); + + + + systemAnchor * SA = systemAnchor::getInstance(); + if( SA ){ + LOG("SysAnchor OK"); + if ( SA->beLocal() ) { + LOG("SysAnchor beLocal!"); + m_oPosition.setPositionXYZ( m_sCamData.x, m_sCamData.y, m_sCamData.z, 0 ); //SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sCamData.x_rot , m_sCamData.y_rot, m_sCamData.z_rot ); + } else { + LOG("SysAnchor is Global Position System!"); + C3D_DECART LD = SA->getXYZ(); + m_oPosition.setPositionXYZ( LD.x + m_sCamData.x, LD.y + m_sCamData.y, LD.z + m_sCamData.z, SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sCamData.x_rot , m_sCamData.y_rot, m_sCamData.z_rot ); + }; + } else { + LOG("No SysAnchor!"); + m_oPosition.setPositionXYZ( m_sCamData.x , m_sCamData.y, m_sCamData.z ); + m_oPosition.setOrientationDeg( m_sCamData.x_rot , m_sCamData.y_rot, m_sCamData.z_rot ); + }; + m_oPosition.updateMatrix(); + +#ifdef DEBUG + char tB[128]; + sprintf( tB, "Finalized Sensor Location: Lat:%.3f Lon:%.3f Alt:%.3f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); + LOG( tB ); + sprintf( tB, "Finalized Sensor Location: x:%.3f y:%.3f z:%.3f", m_oPosition.getX(), m_oPosition.getY(), m_oPosition.getZ() ); + LOG( tB ); + sprintf( tB, "Orientation: x:%.3f y:%.3f z:%.3f", m_oPosition.getRotX_deg(), m_oPosition.getRotY_deg(), m_oPosition.getRotZ_deg() ); + LOG( tB ); +#endif + + if( m_pProtocol != NULL ){ + LOG_ERROR("Cannot Start: Service Already Running!"); + return false; + }; + switch( m_sCamData.protocol ){ + case CAM_CTRL_PROTO_VISCA: { +#ifdef DEBUG + LOG("VISCA"); +#endif + m_pProtocol = (protocolPTZ *) new protocolPTZ_VISCA( m_sCamData.protocol_aux ); + if( m_pProtocol!= NULL ) { + basicTransport *tTransport = NULL; + hardwareManager *tHM = hardwareManager::getInstance(); + if( tHM ){ + hardwareResource *tRES = tHM->requestResource( HARDWARE_PROVIDER_SERIAL, m_sCamData.uart_id ); + if( tRES != NULL ) { + if( tRES->isValid()) { + tTransport = static_cast(static_cast(tRES)); + if( m_pProtocol->setTransport( tTransport )){ + if( !m_pProtocol->create() ){ + LOG_ERROR("Protocol <<< Create >>> Failure!"); + }; + } else { + LOG_ERROR("Binding Port Failure!"); + }; + }; +#ifdef DEBUG + } else { + LOG("HWM Has No UART PORT!"); +#endif + }; +#ifdef DEBUG + } else { + LOG_ERROR("Can not get Hardware Manager!"); +#endif + }; + if( tTransport!= NULL ) { + LOG( "Bind Transport Port!" ); + } else { + LOG_ERROR("Transport Creation Failure!"); + delete( ( protocolPTZ_VISCA * )m_pProtocol ); + m_pProtocol = NULL; + }; +#ifdef DEBUG + } else { + LOG_ERROR("Protocol Creation failure!"); +#endif + }; + break; + }; + case CAM_CTRL_PROTO_PELCO:{ +#ifdef DEBUG + LOG("PELCO"); +#endif + m_pProtocol = (protocolPTZ *) new protocolPTZ_PELCO( m_sCamData.protocol_aux ); + + if( m_pProtocol!= NULL ) { + basicTransport *tTransport = NULL; + hardwareManager *tHM = hardwareManager::getInstance(); + if ( tHM ) { + hardwareResource * tRES = tHM->requestResource( HARDWARE_PROVIDER_SERIAL, m_sCamData.uart_id ); + if( tRES != NULL ) { + if( tRES->isValid()) { + tTransport = static_cast(static_cast(tRES)); + if( m_pProtocol->setTransport( tTransport )){ + if( !m_pProtocol->create() ){ + LOG_ERROR("Protocol <<< Create >>> Failure!"); + }; + } else { + LOG_ERROR("Binding Port Failure!"); + }; + }; +#ifdef DEBUG + } else { + LOG("HWM Has No UART PORT!"); +#endif + }; +#ifdef DEBUG + } else { + LOG_ERROR("Can not get Hardware Manager!"); +#endif + }; + if( tTransport!= NULL ) { + LOG( "Bind Transport Port!" ); + } else { + LOG_ERROR("Transport Creation Failure!"); + delete( ( protocolPTZ_PELCO * )m_pProtocol ); + m_pProtocol = NULL; + }; +#ifdef DEBUG + } else { + LOG_ERROR("Protocol Creation failure!"); +#endif + }; + break; + }; + case CAM_CTRL_PROTO_ONVIF:{ +#ifdef DEBUG + LOG("ONVIF"); +#endif + m_pProtocol = (protocolPTZ *) new protocolPTZ_ONVIF( m_sCamData.ip, m_sCamData.username, m_sCamData.password, m_sCamData.auth_mode ); + if( m_pProtocol!=NULL ) { + if( !m_pProtocol->create() ) { + LOG_ERROR("Error Creating Proto!"); + delete( (protocolPTZ_ONVIF*) m_pProtocol ); + m_pProtocol = NULL; + }; + }; + break; + }; + default:{ +#ifdef DEBUG + LOG("Camera Has no defined control protocol"); +#endif + }; + }; + if( m_pProtocol == NULL ) { + if( m_sCamData.protocol == 0 ) { + m_sCamData.online = true; + } else LOG_ERROR("No Proto Created!"); + } else { +#ifdef DEBUG + LOG("Proto is OK"); +#endif + m_sCamData.online = init(); + }; + return m_sCamData.online; +}; + + + +//void deviceNodeCamera::setBusy( bool Status ){ + //m_bBusy = Status; +//}; + + +bool deviceNodeCamera::relativeMove( float PanSPD, float TiltSPD, float ZoomSPD ){ + if( m_sCamData.online ) { + uint32_t MoveMatrix = 0; + if( PanSPD != .0f ){ + if( PanSPD > 0 ) { + MoveMatrix |= PTZ_DRIVE_PAN_RIGHT; + } else { + MoveMatrix |= PTZ_DRIVE_PAN_LEFT; + }; + }; + if( TiltSPD != .0f ){ + if( TiltSPD > 0 ) { + MoveMatrix |= PTZ_DRIVE_TILT_UP; + } else { + MoveMatrix |= PTZ_DRIVE_TILT_DOWN; + }; + }; + if( ZoomSPD != .0f ){ + if( ZoomSPD > 0 ) { + MoveMatrix |= PTZ_DRIVE_ZOOM_WIDE; + } else { + MoveMatrix |= PTZ_DRIVE_ZOOM_TELE; + }; + }; + if( MoveMatrix != 0 ) { + m_pProtocol->setPTZSpeed( fabs(PanSPD), fabs(TiltSPD), fabs(ZoomSPD) ); + }; + return m_pProtocol->move( MoveMatrix ); + }; + return false; +}; + +bool deviceNodeCamera::relativeStop(){ + if( m_sCamData.online ) { + return m_pProtocol->move( 0 ); + }; + return false; +}; + +CAM_TASK *deviceNodeCamera::fetchCamTask( void ){ + CAM_TASK *rVal = NULL; + m_mQPROTECTOR.lock(); + if (m_qCAM_TASK.size()) { + rVal = m_qCAM_TASK.front(); + m_qCAM_TASK.pop(); + }; + m_mQPROTECTOR.unlock(); + return rVal; +}; + +bool deviceNodeCamera::pushCamTask( CAM_TASK *ptr ){ + if ( ptr == NULL ) return false; + m_mQPROTECTOR.lock(); + m_qCAM_TASK.push( ptr ); + m_mQPROTECTOR.unlock(); + return true; +}; + +bool deviceNodeCamera::fusion_compare( CAM_ROI *ptr, C3D_SPH_DEGREES tp ){ + if( ptr == NULL ) return false; + float tFI = fabsf( ptr->cam_position.fi - tp.fi ); + float tTETTA = fabsf( ptr->cam_position.tetta - tp.tetta ); +#ifdef DEBUG + char tB[128]; + sprintf(tB,"FC: FOV:[%.5f:%.5f] dTG:[%.5f:%.5f] %.2f<%.2f>%.2f",ptr->h_fov ,ptr->v_fov, tFI, tTETTA, ptr->min_range, tp.r, ptr->max_range ); + LOG(tB); +#endif + if( tFI > ptr->h_fov ) return false; + if( tTETTA > ptr->v_fov ) return false; + if( tp.r < ptr->min_range ) return false; + if( tp.r > ptr->max_range ) return false; + return true; +}; + +bool deviceNodeCamera::fusion_consumeData( uint32_t db_id, C3D_SPH_DEGREES tOR ){ + if( db_id == 0 ) return false; + CAM_TRACK_RECORD * tTrackRecords = (CAM_TRACK_RECORD * ) malloc( sizeof(CAM_TRACK_RECORD)); + if( tTrackRecords == NULL ) return false; +#ifdef DEBUG + LOG("Fusion: Consuming new Data!"); +#endif + memset(tTrackRecords, 0, sizeof(CAM_TRACK_RECORD)); + tTrackRecords->target_direction.fi = tOR.fi; + tTrackRecords->target_direction.r = tOR.r; + tTrackRecords->target_direction.tetta = tOR.tetta; + tTrackRecords->evt_db_ID = db_id; + tTrackRecords->ts_ms = getMilliseconds(); + m_mROIsProtector.lock(); + if( m_vROIS.size() ){ + vCAM_ROIS::iterator idx = m_vROIS.begin(); + for( ; idx < m_vROIS.end(); idx++ ) if ( fusion_compare( *idx, tOR ) ) break; + if ( idx != m_vROIS.end() ) { + // have Match! + LOG("ROI MATCHED!"); + (*idx)->targets.push_back( tTrackRecords ); + fusion_validateROI( tTrackRecords->ts_ms, (*idx) ); + } else { + LOG("NO MATCH FOUND!"); + // No mathced ROI -> create new one + CAM_ROI * tROI = (CAM_ROI *)malloc(sizeof(CAM_ROI)); + if ( tROI ) { + memset( tROI, 0 , sizeof(CAM_ROI) ); + tROI->ts_ms = tTrackRecords->ts_ms; + spherical2onvif( tOR, tROI->cam_orientation, m_fMaxRange, m_sCamData.pan_model, m_sCamData.pan_angles, m_sCamData.tilt_model, m_sCamData.tilt_angles ); + + tROI->cam_position.fi = tOR.fi; + tROI->cam_position.tetta = tOR.tetta; + tROI->cam_position.r = tOR.r; + + float cFL = m_fMinFL + m_fR2FL * ( tROI->cam_position.r - m_fMinRange ); + + tROI->max_range = calcMaxDistance_mm( AC_imager_diag[m_sCamData.imager_type], cFL, m_nRealFrameWidth ); + tROI->min_range = calcMinDistance_mm( AC_imager_diag[m_sCamData.imager_type], cFL, m_nRealFrameWidth ); + tROI->h_fov = rad2deg( calcFOV_mm( AC_imager_width[m_sCamData.imager_type], cFL ) ) / 2.0f; // div to no to div in comparation function + tROI->v_fov = rad2deg( calcFOV_mm( AC_imager_height[m_sCamData.imager_type], cFL ) ) / 2.0f; // that will be called more ofthen + + tROI->targets.push_back( tTrackRecords ); + m_vROIS.push_back( tROI ); + }; + }; + } else { + // empty ROIs -> create new one + CAM_ROI * tROI = (CAM_ROI *)malloc(sizeof(CAM_ROI)); + if ( tROI ) { + memset( tROI, 0 , sizeof(CAM_ROI) ); + tROI->ts_ms = tTrackRecords->ts_ms; + //Set vector Cam Coordinates + tROI->cam_position.fi = tOR.fi; + tROI->cam_position.tetta = tOR.tetta; + tROI->cam_position.r = tOR.r; + // Set vector OnVIF coordinates + spherical2onvif( tOR, tROI->cam_orientation, m_fMaxRange, m_sCamData.pan_model, m_sCamData.pan_angles, m_sCamData.tilt_model, m_sCamData.tilt_angles ); + + // make fusion data BOX + float cFL = m_fMinFL + m_fR2FL * ( tROI->cam_position.r );// - m_fMinRange ); + + tROI->min_range = calcMinDistance_mm( AC_imager_diag[m_sCamData.imager_type], cFL, m_nRealFrameWidth ); + tROI->max_range = calcMaxDistance_mm( AC_imager_diag[m_sCamData.imager_type], cFL, m_nRealFrameWidth ); + tROI->h_fov = rad2deg( calcFOV_mm( AC_imager_width[m_sCamData.imager_type], cFL ) )/ 2.0f; // div to prevent division in comparation + tROI->v_fov = rad2deg( calcFOV_mm( AC_imager_height[m_sCamData.imager_type], cFL ) )/ 2.0f; // function that will be called more ofthen + + // Add ROI to vector + tROI->targets.push_back( tTrackRecords ); + m_vROIS.push_back( tROI ); + }; + }; + m_mROIsProtector.unlock(); + return true; +}; + +bool deviceNodeCamera::fusion_validateROI( uint64_t cts, CAM_ROI *ptr ){ + if( ptr == NULL ) return false; + if( (cts - ptr->ts_ms) > LOSE_INTERES_TIME_MS ) return false; + +#ifdef DEBUG + char tB[128]; + sprintf( tB, "\tROI [%d]", ptr->targets.size() ); + LOG( tB ); +#endif + + if( ptr->targets.size() ) { + double tA = 0.0; + double tB = 0.0; + double tC = 0.0; + uint32_t tCNT = 0; + for( vCAM_TRACK_RECORDS::iterator idx = ptr->targets.begin(); idx < ptr->targets.end(); idx++ ) { + if( ( cts - (*idx)->ts_ms ) > LOSE_INTERES_TIME_MS ) { + free( (*idx) ); + ptr->targets.erase( idx ); + } else { + tA = tA + (*idx)->target_direction.fi; + tB = tB + (*idx)->target_direction.tetta; + tC = tC + (*idx)->target_direction.r; + tCNT++; + }; + }; + if( tCNT ) { + C3D_SPH_DEGREES L = { 0 }; + L.fi = (float) ( tA /(double) tCNT ); + L.tetta = (float) ( tB /(double) tCNT ); + L.r = (float) ( tC /(double) tCNT ); + spherical2onvif(L, ptr->cam_orientation, m_fMaxRange, m_sCamData.pan_model, m_sCamData.pan_angles, m_sCamData.tilt_model, m_sCamData.tilt_angles); + ptr->ts_ms = cts; + + float cFL = m_fMinFL + m_fR2FL * ( ptr->cam_position.r - m_fMinRange ); + + ptr->max_range = calcMaxDistance_mm( AC_imager_diag[m_sCamData.imager_type], cFL, m_nRealFrameWidth ); + ptr->min_range = calcMinDistance_mm( AC_imager_diag[m_sCamData.imager_type], cFL, m_nRealFrameWidth ); + ptr->h_fov = rad2deg( calcFOV_mm(AC_imager_width[m_sCamData.imager_type], cFL) )/ 2.0f; // div to prevent division in comparation + ptr->v_fov = rad2deg( calcFOV_mm( AC_imager_height[m_sCamData.imager_type], cFL ) )/ 2.0f; // function that will be called more ofthen + + return true; + }; + }; + return false; +}; + +CAM_ROI *deviceNodeCamera::fusion_fetchROI( void ){ + CAM_ROI *tVAL = NULL; + uint64_t cts = 0; + m_mROIsProtector.lock(); + vCAM_ROIS::iterator sRec; + if( m_vROIS.size() ){ + for( vCAM_ROIS::iterator idx = m_vROIS.begin(); idx < m_vROIS.end(); idx++ ){ + if ( tVAL == NULL ) { + sRec = idx; + tVAL = (*idx); + cts = tVAL->ts_ms; + } else { +#ifdef CAM_FETCH_ROI_NEWEST + if ( (*idx)->ts_ms > cts ) +#else + if ( (*idx)->ts_ms < cts ) +#endif + { + sRec = idx; + tVAL = (*idx); + cts = tVAL->ts_ms; + }; + }; + }; + m_vROIS.erase( sRec ); + }; + m_mROIsProtector.unlock(); + return tVAL; +}; + +DBC_SNAPSHOT_DATA *deviceNodeCamera::fusion_translate_ROI( CAM_ROI *(&ptr) ){ + DBC_SNAPSHOT_DATA *rVal = NULL; + if( ptr == NULL ) return NULL; + if( ptr->targets.size() ){ + //if( m_bSourceConnected ){ + rVal = (DBC_SNAPSHOT_DATA *)malloc(sizeof(DBC_SNAPSHOT_DATA)); + if( rVal ){ + memset( rVal, 0, sizeof(DBC_SNAPSHOT_DATA) ); + //rVal->stream_id = m_nActiveStreamID; + rVal->stream_id = m_sNodeData.aux_parameter; + for( vCAM_TRACK_RECORDS::iterator idx = ptr->targets.begin(); idx < ptr->targets.end(); idx++ ) { + rVal->assoc_event_ids.push_back( (*idx)->evt_db_ID ); + }; + }; + //}; + ptr->targets.clear(); + }; + // Destruct ROI MEM + delete( (CAM_ROI *) ptr ); + ptr = NULL; + // Not Setting MD5 and TS -> will set at capture time + return rVal; +}; + +void deviceNodeCamera::fusion_validate( void ){ + m_mROIsProtector.lock(); + if( m_vROIS.size() ){ +#ifdef DEBUG + char tB[128]; + sprintf( tB, "Fusion: Have [%d] Regions Of Interes", m_vROIS.size() ); + LOG( tB ); +#endif + uint64_t cts = getMilliseconds(); + for( vCAM_ROIS::iterator idx = m_vROIS.begin(); idx < m_vROIS.end(); idx++ ){ + if( !fusion_validateROI( cts, *idx ) ) { + free( (*idx) ); + m_vROIS.erase( idx ); + }; + }; + }; + m_mROIsProtector.unlock(); +}; + +bool deviceNodeCamera::absoluteMove( uint32_t TargetRefID, float PanPOS, float TiltPOS, float ZoomPOS ){ + if( m_sCamData.online ){ + CAM_TASK *tTask = (CAM_TASK *)malloc(sizeof(CAM_TASK)); + if( tTask ){ + memset(tTask, 0, sizeof(CAM_TASK)); + tTask->CMD = (CAM_PTZ_CMD *)malloc(sizeof(CAM_PTZ_CMD)); + if( tTask->CMD ){ + tTask->CMD->CMD = PTZ_ABSOLUTE; + tTask->CMD->PAN = PanPOS; + tTask->CMD->TILT = TiltPOS; + tTask->CMD->ZOOM = ZoomPOS; + tTask->movemet_needed = true; + tTask->source_evt_id = TargetRefID; + setWM( CAM_WS_BUSY ); + return pushCamTask( tTask ); + } else { + LOG_ERROR("CMD malloc Error!"); + free( tTask ); + }; + } else { + LOG_ERROR("Task malloc error!"); + }; + }; + return false; +}; + +bool deviceNodeCamera::absoluteMove( uint32_t TargetRefID, C3D_ORIENT_ONVIF O ){ + if( m_sCamData.online ){ + CAM_TASK *tTask = (CAM_TASK *)malloc(sizeof(CAM_TASK)); + if( tTask ){ + memset(tTask, 0, sizeof(CAM_TASK)); + tTask->CMD = (CAM_PTZ_CMD *)malloc(sizeof(CAM_PTZ_CMD)); + if( tTask->CMD ){ + tTask->CMD->CMD = PTZ_ABSOLUTE; + tTask->CMD->PAN = O.pan; + tTask->CMD->TILT = O.tilt; + tTask->CMD->ZOOM = O.zoom; + tTask->movemet_needed = true; + tTask->source_evt_id = TargetRefID; + setWM( CAM_WS_BUSY ); + return pushCamTask( tTask ); + } else { + LOG_ERROR("CMD malloc Error!"); + free( tTask ); + }; + } else { + LOG_ERROR("Task malloc error!"); + }; + }; + return false; +}; + +void deviceNodeCamera::m_fThreadProc( void ){ + DBC_PUSHED_CMD * PUSHED = NULL; + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { + //Local Recorder + //if( m_bSourceConnected ) { +// + // }; + uint8_t tState = getWM(); + + char tB[128]; + //sprintf( tB, "CWM: 0x%02X", tState ); + //LOG( tB ); + + fusion_validate(); + + switch( tState ) { + case CAM_WS_INIT:{ +#ifdef DEBUG + LOG("Init Camera - PowerMode"); +#endif + //setBusy( true ); + if( m_pProtocol->initCamera() ) setWM( CAM_WS_WHITE_BALLANCE ); + //setBusy( false ); + break; + }; + case CAM_WS_WHITE_BALLANCE:{ +#ifdef DEBUG + LOG("Set WB"); +#endif + //setBusy( true ); + if( m_pProtocol->setWhiteBalanceMode( WB_AUTO ) ) setWM( CAM_WS_BACKLIGHT ); + //setBusy( false ); + break; + }; + case CAM_WS_BACKLIGHT:{ +#ifdef DEBUG + LOG("Set BLC"); +#endif + //setBusy( true ); + if( m_pProtocol->setBackLightMode( true ) ) setWM( CAM_WS_AUTO_FOCUS ); + //setBusy( false ); + break; + }; + case CAM_WS_AUTO_FOCUS:{ +#ifdef DEBUG + LOG("Set AF"); +#endif + //setBusy( true ); + if( m_pProtocol->setAutoFocus( true ) ) setWM( CAM_WS_INIT_GO_HOME ); + //setBusy( false ); + break; + }; + case CAM_WS_INIT_GO_HOME:{ +#ifdef DEBUG + LOG("INIT GO -1 -1 -1"); +#endif + //setBusy( true ); + if( m_pProtocol->goAbsolute( -1, 0, -1 ) ) setWM( CAM_WS_READY ); + //setBusy( false ); + break; + }; + case CAM_WS_AUTOMATED_MOVE:{ + m_nRelativeMoveCounter++; + if( ( m_bRelativeMoveMatrix & 0x03 ) != 0 ) { + //Pan Move + if( ( m_bRelativeMoveMatrix & 0x01 ) == 0 ) { + m_fRM_Pan -= m_fSpeedRise; + } else { + m_fRM_Pan += m_fSpeedRise; + }; + }; + if( ( m_bRelativeMoveMatrix & 0x0C ) != 0 ) { + //TILT Move + if( ( m_bRelativeMoveMatrix & 0x04 ) == 0 ) { + m_fRM_Tilt -= m_fSpeedRise; + } else { + m_fRM_Tilt += m_fSpeedRise; + } + }; + if( ( m_bRelativeMoveMatrix & 0x30 ) != 0 ) { + //ZOOM Move + if( ( m_bRelativeMoveMatrix & 0x10 ) == 0 ) { + //Wide + m_fRM_Zoom -= m_fSpeedRise; + } else { + //Tele + m_fRM_Zoom += m_fSpeedRise; + }; + }; + if( m_fRM_Pan < -1.0f ) m_fRM_Pan = -1.0f; + if( m_fRM_Pan > 1.0f ) m_fRM_Pan = 1.0f; + if( m_fRM_Tilt < -1.0f ) m_fRM_Tilt = -1.0f; + if( m_fRM_Tilt > 1.0f ) m_fRM_Tilt = 1.0f; + if( m_fRM_Zoom < -1.0f ) m_fRM_Zoom = -1.0f; + if( m_fRM_Zoom > 1.0f ) m_fRM_Zoom = 1.0f; + if( !relativeMove( m_fRM_Pan, m_fRM_Tilt, m_fRM_Zoom ) ){ + m_nRelativeMoveCounter = 0; + setWM( CAM_WS_READY ); + break; + }; + if( m_nRelativeMoveCounter > 10 ) { + m_nRelativeMoveCounter = 0; + setWM( CAM_WS_READY ); + }; + break; + }; + case CAM_WS_STOP_MOVE:{ + m_nRelativeMoveCounter++; + m_fRM_Pan = .0f; + m_fRM_Pan = .0f; + m_fRM_Tilt = .0f; + m_fRM_Tilt = .0f; + m_fRM_Zoom = .0f; + m_fRM_Zoom = .0f; + if( relativeStop() ) { + m_nRelativeMoveCounter = 0; + setWM( CAM_WS_READY ); + break; + }; + if( m_nRelativeMoveCounter > 10 ) setWM( CAM_WS_READY ); + break; + }; + case CAM_WS_GO_ABS_POSITION:{ + setWM( CAM_WS_BUSY ); + if ( m_pCurrentROI != NULL ) { + if( m_pBEH ){ + EVENT_CONTAINER *tEVT = createBasicEvent( + m_sCamData.node_id, + EVT_CLASS_CAMERA_CTRL, + EVT_CAMERA_MOVE_TO, + NULL, NULL, NULL ); + if( tEVT ){ + //tEVT->m_db_id = tTASK->source_evt_id; // EVT ids embed in DATA + m_pBEH->broadcast( tEVT ); + }; + }; + + if( !m_pProtocol->goAbsolute( + m_pCurrentROI->cam_orientation.pan, + m_pCurrentROI->cam_orientation.tilt, + m_pCurrentROI->cam_orientation.zoom + )){ + LOG_ERROR("Cannot Issue goAbsolute Command!"); + setWM( CAM_WS_READY ); + } else { + // Send Capture event + DBC_SNAPSHOT_DATA *tData = fusion_translate_ROI( m_pCurrentROI ); + if( tData != NULL ) { + if( m_pBEH ){ + EVENT_CONTAINER *tEVT = createBasicEvent( + m_sCamData.node_id, + EVT_CLASS_CAMERA_CTRL, + EVT_CAMERA_ON_POSITION, + NULL, NULL, tData ); + if( tEVT ){ + //tEVT->m_db_id = tTASK->source_evt_id; // EVT ids embed in DATA + m_pBEH->broadcast( tEVT ); + }; + }; + }; + // Waiting capture finish + //setWM( CAM_WS_BUSY ); + }; + } else setWM( CAM_WS_READY ); + break; + }; + case CAM_WS_BUSY:{ + //Handle Operation TO + setWM( CAM_WS_READY ); + break; + }; + case CAM_WS_READY:{ + /* + uint32_t tSLEEP = DEFAULT_THREAD_SLEEP_TIME; + CAM_TASK * tTASK = fetchCamTask(); + if ( tTASK != NULL ) { + if( tTASK->movemet_needed ){ + CAM_PTZ_CMD *tCMD = tTASK->CMD; + if( tCMD ) { + switch( tCMD->CMD ) { + case PTZ_STOP:{ + m_pProtocol->goStop(); + break; + }; + case PTZ_MOVE:{ + uint32_t MoveMatrix = 0; + if( m_pProtocol->setPTZSpeed( tCMD->PAN, tCMD->TILT, tCMD->ZOOM ) ){ + tSLEEP = 15; + m_pProtocol->move( MoveMatrix ); + }; + break; + }; + case PTZ_ABSOLUTE:{ + + + if( !m_pProtocol->goAbsolute( tCMD->PAN, tCMD->TILT, tCMD->ZOOM ) ) { + LOG_ERROR("Cannot Issue goAbsolute Command!"); + tSLEEP= 100; + } else { + // Send Capture event + //fusion_translate_ROI( CAM_ROI *ptr ); + if( m_pBEH ){ + EVENT_CONTAINER *tEVT = createBasicEvent( + m_sCamData.node_id, + EVT_CLASS_CAMERA_CTRL, + EVT_CAMERA_ON_POSITION, + NULL, NULL, NULL ); + if( tEVT ){ + tEVT->m_db_id = tTASK->source_evt_id; + m_pBEH->broadcast(tEVT); + }; + }; + + }; + break; + }; + case PTZ_RELOAD_CAMERA:{ + LOG("Exit Command Rcpt"); + m_bThreadStatus = TH_ENDED; + }; + }; + free( tCMD ); + tTASK->CMD = NULL; + }; + }; + free( tTASK ); + } else { + // Lowest Priority to Web Client Commands + PUSHED = m_pDBC->getNodePushedCMD( m_sCamData.node_id ); + if( PUSHED != NULL ) { + if( ( PUSHED->CMD & ARGUS_CAM_PCMD_CMD_MASK ) == ARGUS_CAM_PCMD_CMD_MASK ) { + switch( PUSHED->CMD ) { + case 0x80:{ + //m_bWM = ANODE_WM_2D_ISSUE_FULL_RESET; + break; + }; + case 0x81:{ + //m_bWM = ANODE_WM_2D_GET_FAST_DRAW; + break; + }; + case 0x82:{ + break; + }; + }; //?? Check if we don't miss something!! + } else if ( tState == CAM_WS_READY || tState == CAM_WS_AUTOMATED_MOVE ){ + //Direct Movment Mode + if( PUSHED->CMD == ARGUS_CAM_PCMD_STOP ) { + setWM( CAM_WS_STOP_MOVE ); + } else { + char tB[64]; + if( tState != CAM_WS_AUTOMATED_MOVE ) m_nRelativeMoveCounter = 0; + m_bRelativeMoveMatrix = ( PUSHED->CMD ) >> 1; + setWM( CAM_WS_AUTOMATED_MOVE ); + }; + }; + free( PUSHED ); + PUSHED = NULL; + }; + }; + + if( tSLEEP ) { + SLEEP( tSLEEP ); + }; + */ + m_pCurrentROI = fusion_fetchROI(); + if( m_pCurrentROI != NULL ) { + setWM( CAM_WS_GO_ABS_POSITION ); + } else { + // Lowest Priority to Web Client Commands + PUSHED = m_pDBC->getNodePushedCMD( m_sCamData.node_id ); + if( PUSHED != NULL ) { + m_pDBC->updateNodePushedCMD( PUSHED->id, DBC_CMD_READY_TO_CLEAN ); + if( ( PUSHED->CMD & ARGUS_CAM_PCMD_CMD_MASK ) == ARGUS_CAM_PCMD_CMD_MASK ) { + switch( PUSHED->CMD ) { + case 0x80:{ + //m_bWM = ANODE_WM_2D_ISSUE_FULL_RESET; + break; + }; + case 0x81:{ + //m_bWM = ANODE_WM_2D_GET_FAST_DRAW; + break; + }; + case 0x82:{ + break; + }; + }; //?? Check if we don't miss something!! + } else if ( tState == CAM_WS_READY || tState == CAM_WS_AUTOMATED_MOVE ){ + //Direct Movment Mode + if( PUSHED->CMD == ARGUS_CAM_PCMD_STOP ) { + setWM( CAM_WS_STOP_MOVE ); + } else { + char tB[64]; + if( tState != CAM_WS_AUTOMATED_MOVE ) m_nRelativeMoveCounter = 0; + m_bRelativeMoveMatrix = ( PUSHED->CMD ) >> 1; + setWM( CAM_WS_AUTOMATED_MOVE ); + }; + }; + free( PUSHED ); + PUSHED = NULL; + }; + }; + break; + }; + case CAM_WS_END:{ + LOG("Exit Command Rcpt"); + m_bThreadStatus = TH_ENDED; + //setBusy( true ); + break; + }; + }; + SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + }; + //LOG("CTRL Loop End!"); +}; + +bool deviceNodeCamera::testFOV( C3D_DECART L ){ + //System Coords -> trans to local and go to funct + systemAnchor* tSystem = systemAnchor::getInstance(); + if ( tSystem == NULL ) return false; + C3D_SPH_DEGREES SL; +#ifdef DEBUG + LOG("Test FOV local Decart coords"); +#endif + if( !tSystem->convertToLocal( &m_oPosition, L, SL ) ) return false; + return testFOV( SL ); +}; + +bool deviceNodeCamera::testFOV( C3D_WGS84_LOC L ){ + //Global Coords + systemAnchor* tSystem = systemAnchor::getInstance(); + if ( tSystem == NULL ) return false; + C3D_SPH_DEGREES SL; +#ifdef DEBUG + LOG("Test FOV WGS coords"); +#endif + if( !tSystem->convertToLocal( &m_oPosition, L, SL ) ) return false; + return testFOV( SL ); +}; + +bool deviceNodeCamera::testFOV( C3D_SPH_RADIANS L ){ + //Local Coords + C3D_SPH_DEGREES SL; +#ifdef DEBUG + LOG("Test FOV local Spherical(rad) coords"); +#endif + spherical2spherical( L, SL ); + return testFOV( SL ); +}; + +bool deviceNodeCamera::testFOV( C3D_SPH_DEGREES SL ){ +#ifdef DEBUG + char tB[128]; +#endif +#ifdef DEBUG + LOG("Test FOV local Spherical(deg) coords"); +#endif + switch ( m_sCamData.triggering_mode ) { + case CAM_TRIGGER_STRICT:{ + if( SL.r > m_fMaxRange || SL.r < m_fMinRange ){ +#ifdef DEBUG + sprintf( tB, "Target Range( %.3f.m ) is not in a Range %.3f.m <-> %.3f.m", SL.r, m_fMinRange, m_fMaxRange ); + LOG( tB ); +#endif + return false; + }; + break; + }; + case CAM_TRIGGER_ALL_NEAR:{ + if( SL.r > m_fMaxRange ){ +#ifdef DEBUG + sprintf( tB, "Target Range( %.3f.m ) is not in a Range %.3f.m <-> %.3f.m", SL.r, m_fMinRange, m_fMaxRange ); + LOG( tB ); +#endif + return false; + }; + break; + }; + case CAM_TRIGGER_ALL_FAR:{ + if( SL.r < m_fMinRange ){ +#ifdef DEBUG + sprintf( tB, "Target Range( %.3f.m ) is not in a Range %.3f.m <-> %.3f.m", SL.r, m_fMinRange, m_fMaxRange ); + LOG( tB ); +#endif + return false; + }; + break; + }; + case CAM_TRIGGER_ALL: return true; + }; + + float HS = AC_imager_width[m_sCamData.imager_type]; + float VS = AC_imager_height[m_sCamData.imager_type]; + float HS2 = HS * HS; + float VS2 = VS * VS; + float IR = HS / VS; + float IR2 = IR * IR; + + if( m_sCamData.pan_angles == 0 ) { + // Fixed Camera + float tA = fabsf( SL.fi ); + float tZ = 0.5f * ( m_fMinHFov + ( SL.r - m_fMinRange ) * m_fR2FL ); + if ( tA > tZ ) return false; + } else { + if( m_sCamData.pan_angles < 360 ) { // If endless PAN -> PASSED + // Partial Pan + switch( m_sCamData.pan_model ) { + case 1: { + // Regular Pan + float tFOV = 0.5f * ( m_fMinHFov + ( SL.r - m_fMinRange ) * m_fR2FL ); + float tRad = deg2rad( SL.fi ); +#ifdef DEBUG + sprintf( tB, "FOV: %0.3f CC: %0.3f", tFOV, tRad ); + LOG( tB ); +#endif + if( ( tRad < ( -1.0 * tFOV ) ) || ( tRad > ( deg2rad( m_sCamData.pan_angles ) + tFOV ) ) ) return false; + break; + }; + case 2:{ + + break; + }; + case 3:{ + + break; + }; + }; + }; + }; + + if( m_sCamData.tilt_angles == 0 ){ + //Fixed Camera + if ( ( SL.tetta < ( m_fMaxVFov / -2.0f ) ) || ( SL.tetta > ( m_fMaxVFov / 2.0f ) ) )return false; + } else { + if( m_sCamData.tilt_angles < 90 ) { // if Cam CAN DO 90 -> Pass + // Partial Tilt + switch( m_sCamData.tilt_model ) { + case 1: { + // Regular Tilt + float tFOV = 0.5f * ( m_fMinVFov + ( m_fMaxVFov - m_fMinVFov ) * ( SL.r / m_fMaxRange ) ) ; + float tRad = deg2rad( SL.tetta ); + if( ( tRad < ( -1.0 * tFOV ) ) || ( tRad > ( deg2rad( m_sCamData.tilt_angles ) + tFOV ) ) )return false; + break; + }; + case 2:{ + break; + }; + }; + }; + }; + return true; +}; + +bool deviceNodeCamera::lookAt( uint32_t TargetRefID, C3D_WGS84_LOC L ){ + systemAnchor* tSystem = systemAnchor::getInstance(); + if( tSystem == NULL ) return false; + C3D_SPH_DEGREES SL; +#ifdef DEBUG + LOG("Look at WGS coords!"); +#endif + tSystem->convertToLocal(&m_oPosition, L, SL ); + return lookAt(TargetRefID, SL ); +}; + +bool deviceNodeCamera::lookAt( uint32_t TargetRefID, C3D_DECART L ){ + systemAnchor* tSystem = systemAnchor::getInstance(); + if( tSystem == NULL ) return false; + C3D_SPH_DEGREES SL; +#ifdef DEBUG + LOG("Look at System Decart coords!"); +#endif + tSystem->convertToLocal( &m_oPosition, L, SL ); + return lookAt(TargetRefID, SL ); +}; + +bool deviceNodeCamera::lookAt( uint32_t TargetRefID, C3D_SPH_RADIANS L ){ + C3D_SPH_DEGREES SL; +#ifdef DEBUG + LOG("Look at spherical(rad) 2 spherical(deg) coords!"); +#endif + spherical2spherical( L, SL ); + return lookAt(TargetRefID, SL ); +}; + +bool deviceNodeCamera::lookAt( uint32_t TargetRefID, C3D_SPH_DEGREES L ){ + //char tB[128]; + //sprintf(tB, "Target On %.3f %.3f %.3f", L.r, L.fi, L.tetta ); + //LOG( tB ); + //sprintf( tB, "Cam GoTo %.3f %.3f %.3f", fP, fT, fZ ); + //LOG( tB ); +#ifdef DEBUG + LOG("Look at local spherical deg. coords!(final)"); +#endif + //if( getWM() == CAM_WS_READY ){ + // C3D_ORIENT_ONVIF LL; + // spherical2onvif( L, LL, m_fMaxRange, m_sCamData.pan_model, m_sCamData.pan_angles, m_sCamData.tilt_model, m_sCamData.tilt_angles ); + // return absoluteMove( TargetRefID, LL ); + //}; + // Camera is Busy + return fusion_consumeData( TargetRefID, L ); +}; + +bool deviceNodeCamera::makeSnap( uint32_t TargetRefID ){ + CAM_TASK *tTask = (CAM_TASK *)malloc(sizeof(CAM_TASK)); + if( tTask ){ + memset(tTask, 0, sizeof(CAM_TASK)); + tTask->CMD = (CAM_PTZ_CMD *) malloc( sizeof(CAM_PTZ_CMD) ); + if( tTask->CMD ){ + tTask->CMD->CMD = PTZ_CAPTURE_ONLY; + tTask->source_evt_id = TargetRefID; + return pushCamTask( tTask ); + } else { + free( tTask ); + }; + }; + return false; +}; + +bool deviceNodeCamera::connectToStream( uint32_t id ){ + /* + if( id ){ + argusKernelModule * tKM = NULL; + argusKernel * tKRNL = NULL; + argusModuleFactory * tMF = NULL; + if( m_pDBC == NULL ) { + LOG_ERROR("No Database Connector!"); + return false; + }; + tKRNL = argusKernel::getInstance(); + if( tKRNL ) { + tMF = tKRNL->getModuleFactory(); + if( tMF ) { + tKM = tMF->getModule( ARGUS_MODULE_EMBED_VIDEO ); + } else { + LOG_ERROR("No ModuleFactory Instance!"); + return false; + }; + } else { + LOG_ERROR("No Kernel Instance!"); + return false; + }; + if( tKM ) { + // New Module + DBC_MEDIA_STREAM_DATA *tDATA = m_pDBC->getMediaStreamData( id ); + if( tDATA ) { + m_sMediaSource.mediaStreamId = id; + if( strncmp(tDATA->mrl_proto, "v4l2", 4) == 0 ) { + if (m_pSource != NULL) delete((videoAVLIBSource*)m_pSource); + m_pSource = (basicMediaSource *) new videoAVLIBSource(&m_sMediaSource); + } else { + if (m_pSource != NULL) delete((videoLIVE555Source*)m_pSource); + m_pSource = (basicMediaSource *) new videoLIVE555Source(&m_sMediaSource ); + }; + + if( m_pSource != NULL ) { + char tMRL[1024]; +#ifdef DEBUG + LOG("Source OK"); +#endif + ((videoLIVE555Source*)m_pSource)->setWM( MS_MODE_STREAM_PROXY | MS_MODE_OVERLAYED_LOOPS | MS_MODE_DECODE_FRAMES ); + + int tW = ((argusModuleEmbedVideo*)tKM)->getWidh(); + int tH = ((argusModuleEmbedVideo*)tKM)->getHeight(); + int pix = -1; + bool in_16_9 = (((tDATA->width*100) / tDATA->height ) > 140 ); + bool out_16_9 = (((tW*100) / tH ) > 140 ); + updateOpticalParameters( tW, tH ); + if( strlen( tDATA->c_type ) ){ + + }; + //if( tW > 0 ){ + // //m_pSource->setProportionalByWidth( tW ); + // m_pSource->setSize( tW, tH ); + //}; + if( in_16_9 != out_16_9 ){ + if( in_16_9 ){ + tH = ((( tW * 1000 ) / 16 ) * 9 ) / 1000; + } else { + tW = ((( tH * 1000 ) / 3 ) * 4 ) / 1000; + }; + }; + if (strncmp(tDATA->mrl_proto, "v4l2", 4) == 0) { + sprintf( tMRL, tDATA->mrl ); + } else { + DBC_CAM_DATA *tCAM = m_pDBC->getCamData( tDATA->source_id ); + if( tCAM ) { + sprintf( tMRL, "%s://%s:%s@%s:%d%s", tDATA->mrl_proto, tCAM->username, tCAM->password, tCAM->ip, tDATA->mrl_port, tDATA->mrl ); + free( tCAM ); + } else { + LOG_ERROR("Error Getting CAM Data!"); + delete( m_pSource ); + m_pSource = NULL; + return false; + }; + }; + LOG( tMRL ); + if( m_pSource->_open( tMRL, false, -1.0f, pix, tDATA->width, tDATA->height, tW, tH ) ){ + m_bSourceConnected = m_pSource->attachDestination( (argusModuleEmbedVideo*) tKM ); + if ( !m_bSourceConnected ) { + //delete( m_pSource ); + if( strncmp(tDATA->mrl_proto, "v4l2", 4) == 0 ) { + delete((videoAVLIBSource*)m_pSource); + } else { + delete((videoLIVE555Source*)m_pSource); + }; + m_pSource = NULL; + } else { + m_nActiveStreamID = id; +#ifdef DEBUG + LOG("Source is Connected to Output."); +#endif + }; + } else { + LOG_ERROR("Can not Open Video Source!"); + //delete( m_pSource ); + if( strncmp(tDATA->mrl_proto, "v4l2", 4) == 0 ) { + delete((videoAVLIBSource*)m_pSource); + } else { + delete((videoLIVE555Source*)m_pSource); + }; + m_pSource = NULL; + }; + } else { + LOG_ERROR("Video Source Stream Failure!"); + }; + free( tDATA ); + }; + } +#ifdef DEBUG + else LOG("No Video Module!") +#endif + ; + }; + LOG("Connect Finished!"); + return m_bSourceConnected; + */ + return true; +}; + +bool deviceNodeCamera::disconnectFromStream( void ){ + /*if( m_bSourceConnected ) { + if( m_pSource ){ + delete( m_pSource ); + m_pSource = NULL; + }; + m_bSourceConnected = false; + }; + return !m_bSourceConnected; + */ + return true; +}; + +bool deviceNodeCamera::validateStream( void ){ + /* + if( m_bSourceConnected ) { + if( m_pSource ) { + if( m_pSource->isAttached() ){ + if( m_pSource->getStatus() < MS_STOPED ) return true; +#ifdef DEBUG + LOG("Source is Finished!"); +#endif + }; +#ifdef DEBUG + LOG("Source is Disconnected!"); +#endif + } else LOG_ERROR("No Source Object! Set Disconnected!"); + + disconnectFromStream(); + }; + return false; + */ + return true; +}; + +bool deviceNodeCamera::validate(){ + if( !validateStream() ) return false; + return deviceNode::validate(); +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/deviceNodeCamera.h b/lib/App/common/deviceNodeCamera.h new file mode 100644 index 00000000..820005e2 --- /dev/null +++ b/lib/App/common/deviceNodeCamera.h @@ -0,0 +1,202 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2017. All Rights Reserved. +// Version 2.0 6/11/2019 +// Last modification: 6/11/2019 +// PROJECT: +// SUBSYSTEM: +// FILE: rgooseIPCamera.h +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// Header file of rgooseIPCamera.h +//---------------------------------------------------------------------------- +// +#ifndef __DEVICE_NODE_CAMERA_HEADER__ +#define __DEVICE_NODE_CAMERA_HEADER__ + +#include +#include +#include "../../components/base/basicThread.h" +#include "../../components/base/basicMutex.h" +#include "../../data/protocol/protocolPTZ.h" + +#include "../../components/base/basicEventHeap.h" +//#include "rgooseDBConnector.h" +#include "deviceNode.h" + +//https://www.ebay.com/itm/Professional-Rolling-Makeup-Case-Bulb-Mirror-Cosmetic-Artist-Dressing-Train-Case/233264525474 + +//ffmpeg -i input.mp4 -af loudnorm=I=-23:LRA=7:tp=-2:print_format=json -f null - +//ffmpeg -i input.mp4 -af loudnorm=I=-23:LRA=7:tp=-2:measured_I=-30:measured_LRA=1.1:measured_tp=-11 04:measured_thresh=-40.21:offset=-0.47 -ar 48k -y output.mp4 + +#define CAM_CTRL_PROTO_VISCA 1 +#define CAM_CTRL_PROTO_PELCO 2 +#define CAM_CTRL_PROTO_ONVIF 3 +#define CAM_CTRL_PROTO_PSIA 4 +#define CAM_CTRL_PROTO_T28181 5 + +#define UART_TYPE_HARDWARE 1 +#define UART_TYPE_SOL 2 + +#define ARGUS_CAM_PCMD_MOVE_MASK 0x7F +#define ARGUS_CAM_PCMD_CMD_MASK 0x80 +#define ARGUS_CAM_PCMD_STOP 1 + + +typedef struct S_CAM_PTZ_CMD{ + uint8_t CMD; + float PAN; + float TILT; + float ZOOM; +}CAM_PTZ_CMD; + +typedef enum E_CAM_PTZ_CMD{ + PTZ_STOP = 0, + PTZ_MOVE = 1, + PTZ_ABSOLUTE = 2, + PTZ_RELOAD_CAMERA = 3, + PTZ_CAPTURE_ONLY = 4 +}PTZ_CMD; + +typedef std::queue CAM_PTZ_CMD_QUEUE; + +typedef enum E_CAM_WORKING_STATE{ + CAM_WS_INIT = 0, + CAM_WS_WHITE_BALLANCE = 1, + CAM_WS_BACKLIGHT = 2, + CAM_WS_AUTO_FOCUS = 3, + CAM_WS_INIT_GO_HOME = 4, + CAM_WS_AUTOMATED_MOVE = 10, + CAM_WS_STOP_MOVE = 11, + CAM_WS_GO_ABS_POSITION = 12, + CAM_WS_READY = 64, + CAM_WS_BUSY = 128, + CAM_WS_END = 255 +}CAM_WORK_STATE; + +typedef struct S_CAM_TASK{ + bool isDone; + uint32_t source_evt_id; + bool movemet_needed; + CAM_PTZ_CMD * CMD; +} CAM_TASK; + +typedef std::queue CAM_TASK_QUEUE; + +typedef struct S_CAM_TRACK_RECORD{ + C3D_SPH_DEGREES target_direction; + uint32_t evt_db_ID; + uint64_t ts_ms; +}CAM_TRACK_RECORD; + +typedef std::vector vCAM_TRACK_RECORDS; + + + +typedef struct S_CAM_ROI{ + C3D_ORIENT_ONVIF cam_orientation; + vCAM_TRACK_RECORDS targets; + uint64_t ts_ms; + /** to do fusion things - consume more targets **/ + C3D_SPH_DEGREES cam_position; + float h_fov; + float v_fov; + float min_range; + float max_range; +}CAM_ROI; + +typedef std::vector vCAM_ROIS; + +#define LOSE_INTERES_TIME_MS 2000 + +class deviceNodeCamera: public deviceNode, public basicThread { + private: + basicPosition m_oPosition; + time_t m_tTimeTSeconds; + CAM_ROI * m_pCurrentROI; + + float m_fMaxRange; + float m_fMinRange; + float m_fMaxFL; + float m_fMinFL; + float m_fR2FL; // Range to Focal Length + + uint16_t m_nRealFrameWidth; + uint16_t m_nRealFrameHeight; + float m_fMinHFov; + float m_fMaxHFov; + float m_fMinVFov; + float m_fMaxVFov; + + protocolPTZ * m_pProtocol; + basicTransport * m_pTransport; + + CAM_TASK_QUEUE m_qCAM_TASK; + basicMutex m_mQPROTECTOR; + + //videoAVLIBSource * m_pSource; + //videoLIVE555Source * m_pSource; + //basicMediaSource * m_pSource; + uint32_t m_nRelativeMoveCounter; + uint8_t m_bRelativeMoveMatrix; + float m_fSpeedRise; + float m_fRM_Pan; + float m_fRM_Tilt; + float m_fRM_Zoom; + + /* Methotds Sutable to Control Camera */ + bool relativeMove( float PanSPD, float TiltSPD, float ZoomSPD ); + bool relativeStop(); + bool absoluteMove( uint32_t RefID, float PanPOS, float TiltPOS, float ZoomPOS ); + bool absoluteMove( uint32_t RefID, C3D_ORIENT_ONVIF O ); + + /* tracking Fusion methods */ + vCAM_ROIS m_vROIS; + basicMutex m_mROIsProtector; + bool fusion_consumeData( uint32_t db_id, C3D_SPH_DEGREES tOR ); + bool fusion_validateROI( uint64_t cts, CAM_ROI *ptr ); + bool fusion_compare( CAM_ROI *ptr, C3D_SPH_DEGREES tp ); + void fusion_validate( void ); + CAM_ROI * fusion_fetchROI( void ); + DBC_SNAPSHOT_DATA * fusion_translate_ROI( CAM_ROI *(&ptr) ); + void updateOpticalParameters( uint16_t frame_width, uint16_t frame_heigth ); + protected: + DBC_CAM_DATA m_sCamData; + MEDIA_SOURCE_DESC m_sMediaSource; + basicEventHeap * m_pBEH; + //bool m_bSourceConnected; + //uint32_t m_nActiveStreamID; + //bool inTheFOV( float lat, float lon, float alt ); + + bool testFOV( C3D_WGS84_LOC ); //Global Coords + bool testFOV( C3D_DECART ); //System Coords + bool testFOV( C3D_SPH_RADIANS ); //Local Coords + bool testFOV( C3D_SPH_DEGREES ); //Local Coords + + //bool lookAtWGS84( uint32_t TargetRefID, float lat, float lon, float alt ); + bool lookAt( uint32_t TargetRefID, C3D_WGS84_LOC L ); // GLobal + bool lookAt( uint32_t TargetRefID, C3D_DECART L ); // System + bool lookAt( uint32_t TargetRefID, C3D_SPH_RADIANS L ); // Local + bool lookAt( uint32_t TargetRefID, C3D_SPH_DEGREES L ); // Local + + bool makeSnap( uint32_t TargetRefID ); + //void setBusy( bool Status ); + bool connectToStream( uint32_t id ); + bool disconnectFromStream( void ); + bool validateStream( void ); + CAM_TASK * fetchCamTask( void ); + bool pushCamTask( CAM_TASK * ); + virtual void m_fThreadProc( void ); + public: + explicit deviceNodeCamera( uint32_t NodeID ); + explicit deviceNodeCamera( DBC_NODE_DATA *Data ); + virtual ~deviceNodeCamera(); + bool create(); + virtual bool validate(); + +}; + +typedef std::vector vectorNodeCameras; + +#endif diff --git a/lib/App/common/deviceNodeEthernet2Serial.cpp b/lib/App/common/deviceNodeEthernet2Serial.cpp new file mode 100644 index 00000000..dd645778 --- /dev/null +++ b/lib/App/common/deviceNodeEthernet2Serial.cpp @@ -0,0 +1,703 @@ +#include "deviceNodeEthernet2Serial.h" +#include "hardwareManager.h" +#include "../../data/protocol/protocol.h" + +#define LOG( X ) deviceNode::m_pLog->Log( "E2UART", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + deviceNode::m_pLog->Log( "E2UART", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) deviceNode::m_pLog->Log( "E2UART", this, _LOG_ERROR, X ); +#endif + +deviceETH2UART::deviceETH2UART( uint32_t nodeID ) : deviceNode( nodeID ), hardwareResource(), basicTransport(), basicDualThread(){ + //m_pLog = basicLogCollection::getInstance(); + memset( &m_sUartData, 0, sizeof(m_sUartData)); + m_nInputBufferSize = 0; + m_nOutputBufferSize = 0; + m_iDeviceFD = -1; + m_iMasterFD = -1; + m_iInFID = -1; + m_iOutFID = -1; + LOG("CREATE res!"); + hardwareResource::create( m_sNodeData.aux_parameter, HARDWARE_PROVIDER_SERIAL ); +}; + +deviceETH2UART::~deviceETH2UART(){ + closePort(); + hardwareManager *tH = hardwareManager::getInstance(); + if( tH ) tH->resignResource( this ); +}; + +bool deviceETH2UART::create( void ){ + DBC_UART_DATA *tDATA = NULL; + LOG("CREATE!"); + if( m_sResourceSettings.id == 0 ) return false; + if( m_sResourceSettings.aux_id == 0 ) return false; + + tDATA = deviceNode::m_pDBC->getUartData( m_sResourceSettings.aux_id ); + if( tDATA!= NULL ) { + memcpy( &m_sUartData, tDATA, sizeof(DBC_UART_DATA)); +#ifdef DEBUG + LOG("KOKO!"); + LOG( m_sUartData.path ); +#endif + free( tDATA ); + m_bValid = create_SOL(); + }; + + if ( m_bValid ) { + hardwareManager * tH = hardwareManager::getInstance(); + if( tH ) tH->assignResource( this ); + }; + return m_bValid; +}; + +bool deviceETH2UART::validate( void ){ + if( m_bValid ) { + m_bValid = pingDevice(); + if( !m_bValid ){ + LOG_ERROR("No Ping to device!"); + closePort(); + }; + }; +#ifdef DEBUG_EXTRA + LOG("Check Settings For Changes"); +#endif + DBC_UART_DATA *tDATA = deviceNode::m_pDBC->getUartData( m_sResourceSettings.aux_id ); + if( tDATA!= NULL ){ + bool bFlag = true; + if( strcmp(tDATA->path,m_sUartData.path)!= 0 ) bFlag = false; + //if( bFlag && ( m_sUartData.speed != tDATA->speed ) ) bFlag = false; //Speed for SOL port Erelevant + if( bFlag && ( m_sUartData.mode != tDATA->mode ) ) bFlag = false; + if( bFlag && ( m_sUartData.port != tDATA->port ) ) bFlag = false; + if( !bFlag ) { +#ifdef DEBUG + LOG("Settings Has been Changed!"); +#endif + if( m_bValid ) closePort(); // if port not closed + // Apply new settings + memcpy( &m_sUartData, tDATA, sizeof(DBC_UART_DATA)); +#ifdef DEBUG + LOG("Reconect with new settings"); +#endif + m_bValid = create_SOL(); + }; + free( tDATA ); + } else { + LOG_ERROR("Error Fetch DB Data!"); + }; + // Finally in any case If Not Connected -> try to Connect! + if( !m_bValid ) { +#ifdef DEBUG + LOG("Try to Conncet"); +#endif + m_bValid = create_SOL(); + }; + if( m_bValid ) m_bValid = deviceNode::validate(); + return m_bValid; +}; + + +#include +// Define the Packet Constants +// ping packet size +#define PING_PKT_S 64 + +// Automatic port number +#define PORT_NO 0 + +// Automatic port number +#define PING_SLEEP_RATE 1000000 + +// Gives the timeout delay for receiving packets +// in seconds +#define RECV_TIMEOUT 1 + +// ping packet structure +struct ping_pkt { + struct icmphdr hdr; + char msg[PING_PKT_S-sizeof(struct icmphdr)]; +}; + +bool deviceETH2UART::pingDevice(){ + bool RetVal = false; + if( m_bValid ) { +#ifdef DEBUG_EXTRA + LOG("Pinging Device!"); +#endif + int sockfd; + int ttl_val=64, msg_count=0, i, flag=1, msg_received_count=0; + struct ping_pkt pckt; + struct sockaddr_in ping_addr; + struct sockaddr_in r_addr; + struct timeval tv_out; + + tv_out.tv_sec = 0; + tv_out.tv_usec = 300000; // 1/3 of second + + + ping_addr.sin_family = AF_INET; + ping_addr.sin_addr.s_addr = inet_addr( m_sUartData.path ); + //ping_addr.sin_port = htons( m_nPort ); +#ifdef DEBUG_EXTRA + LOG( m_sUartData.path ); +#endif + sockfd = socket( AF_INET, SOCK_RAW, IPPROTO_ICMP ); + if( sockfd < 0 ){ + LOG_ERROR("Socket file descriptor not received!"); + return false; + }; + + // set socket options at ip to TTL and value to 64, + // change to what you want by setting ttl_val + if( setsockopt( sockfd, SOL_IP, IP_TTL, &ttl_val, sizeof(ttl_val)) != 0 ){ + LOG_ERROR("Setting socket options to TTL failed!"); + shutdown( sockfd, SHUT_RDWR ); + close( sockfd ); + return false; + }; + + // setting timeout of recv setting + setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv_out, sizeof tv_out ); + + // flag is whether packet was sent or not + flag=1; + + //filling packet + bzero(&pckt, sizeof(pckt)); + + pckt.hdr.type = ICMP_ECHO; + pckt.hdr.un.echo.id = getpid(); + + for ( i = 0; i < sizeof(pckt.msg)-1; i++ ) pckt.msg[i] = i+'0'; + + pckt.msg[i] = 0; + pckt.hdr.un.echo.sequence = msg_count++; + pckt.hdr.checksum = checksumPing( &pckt, sizeof(pckt)); //checksum(&pckt, sizeof(pckt)); + + + //SLEEP( 300 ); + + //send packet + if( sendto( sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&ping_addr, sizeof(ping_addr)) <= 0 ){ + LOG_ERROR("Packet Sending Failed!"); + shutdown( sockfd, SHUT_RDWR ); + close( sockfd ); + return false; + }; + + //receive packet + socklen_t addr_len = sizeof(r_addr); + + if( recvfrom( sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&r_addr, &addr_len) <= 0 ){ + LOG_ERROR("Packet receive failed!"); + shutdown( sockfd, SHUT_RDWR ); + close( sockfd ); + return false; + } else { +#ifdef DEBUG_EXTRA + LOG("Device Is OK!"); +#endif + RetVal = true; + }; + shutdown( sockfd, SHUT_RDWR ); + close( sockfd ); + }; + return RetVal; +}; + +bool deviceETH2UART::create_SOL(){ + + /* + if( m_sUartData.mode == SOL_NOT_DEFINED ) { + LOG_ERROR("No Connection Type Defined!"); + return false; + }; + */ + if( m_sUartData.port == 0 ) { + LOG_ERROR("No Port Defined!"); + return false; + }; + if( m_sUartData.speed == 0 ){ + LOG_ERROR("No Speed Defined!"); + return false; + }; + if( m_sUartData.path[0] == (char)0 ) { + LOG_ERROR("No Adress Defined!"); + return false; + }; + + switch( m_sUartData.mode ) { + case SOL_UDP_CLIENT:{ +#ifdef DEBUG + LOG("PORT IS CLIENT - Create UDP Server"); +#endif +#ifdef __linux__ + // Creating socket file descriptor + if ( (m_iDeviceFD = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) { + LOG_ERROR("UDP Socket Creation Failed!"); + return false; + }; + fcntl( m_iDeviceFD, F_SETFL, O_NONBLOCK); + // Filling server information + struct sockaddr_in tServerAddr; + memset( &tServerAddr, 0, sizeof(tServerAddr) ); + tServerAddr.sin_family = AF_INET; // IPv4 + tServerAddr.sin_addr.s_addr = INADDR_ANY; + tServerAddr.sin_port = htons( m_sUartData.port ); + + // Bind the socket with the server address + if ( bind( m_iDeviceFD, (const struct sockaddr *)&tServerAddr, sizeof(tServerAddr)) < 0 ){ + LOG_ERROR("UDP Bind Failed"); + return false; + }; +#else + WSADATA wsaData; + // Initialize Winsock version 2.2 + char tBuff[128]; + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { + sprintf(tBuff, "WSAStartup failed with error %ld", WSAGetLastError()); + LOG_ERROR(tBuff); + return false; + } else { + sprintf(tBuff, "The Winsock DLL status is %s.", wsaData.szSystemStatus); + LOG(tBuff); + }; + // Set up a SOCKADDR_IN structure that will tell bind that we + // want to receive datagrams from all interfaces using port 5150. + // The IPv4 family + ReceiverAddr.sin_family = AF_INET; + // Port no. 5150 + ReceiverAddr.sin_port = htons( m_nPort ); + // From all interface (0.0.0.0) + ReceiverAddr.sin_addr.s_addr = htonl(INADDR_ANY); + // Associate the address information with the socket using bind. + // At this point you can receive datagrams on your bound socket. + if( bind(m_sSocket, (SOCKADDR*)&ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR ){ + sprintf( tBuff, "Server: bind() failed!Error : %ld.", WSAGetLastError()); + // Close the socket + closesocket(m_sSocket); + // Do the clean up + WSACleanup(); + // and exit with error + LOG_ERROR(tBuff); + return false; + } else { + LOG("UDP Server: bind() is OK!"); + }; + // Some info on the receiver side... + SOCKADDR_IN tAddr; + int tLen = sizeof(SOCKADDR_IN); + getsockname(m_sSocket, (SOCKADDR*)&tAddr, &tLen); + sprintf( tBuff, "Receiving IP(s) used : %s", inet_ntoa(tAddr.sin_addr)); + LOG(tBuff); + sprintf(tBuff,"Receiving port used : %d", htons(tAddr.sin_port)); + LOG(tBuff); + SelectTiming = recvfromTimeOutUDP(m_sSocket, 10, 0); +#endif + break; + }; + case SOL_TCP_CLIENT:{ +#ifdef DEBUG + LOG("PORT IS CLIENT - Create TCP Server"); +#endif + break; + }; + case SOL_UDP_SERVER:{ +#ifdef DEBUG + LOG("PORT IS SERVER - Create UDP Client"); +#endif +#ifdef __linux__ + // Creating socket file descriptor + if ( (m_iDeviceFD = socket( AF_INET, SOCK_DGRAM, 0)) < 0 ) { + LOG_ERROR("Socket Creation Failed!"); + return false; + }; + fcntl( m_iDeviceFD, F_SETFL, O_NONBLOCK ); + + // Filling server information + struct sockaddr_in tServerAddr; + memset( &tServerAddr, 0, sizeof(tServerAddr) ); + tServerAddr.sin_family = AF_INET; + tServerAddr.sin_addr.s_addr = INADDR_ANY; + tServerAddr.sin_port = htons( m_sUartData.port ); +#else + +#endif + break; + }; + case SOL_TCP_SERVER:{ +#ifdef DEBUG + LOG("PORT IS SERVER - Create TCP Client"); +#endif + + // socket create and varification + m_iDeviceFD = socket( AF_INET, SOCK_STREAM, 0 ); + if( m_iDeviceFD == -1) { + LOG_ERROR("Socket creation failed!"); + return false; + } +#ifdef DEBUG + else LOG("Socket successfully created"); +#endif + + + // assign IP, PORT + struct sockaddr_in tServerAddr; + memset( &tServerAddr, 0, sizeof(tServerAddr) ); + tServerAddr.sin_family = AF_INET; + tServerAddr.sin_addr.s_addr = inet_addr( m_sUartData.path ); + tServerAddr.sin_port = htons( m_sUartData.port ); + + // connect the client socket to server socket + if( connect( m_iDeviceFD, (struct sockaddr *)&tServerAddr, sizeof(tServerAddr) ) !=0 ){ + char cBuffer[128]; + sprintf(cBuffer,"ERROR connect to [%s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno) ); + LOG_ERROR( cBuffer ); + return false; + } +#ifdef DEBUG + else LOG("Connected to the server"); +#endif + + // Set non-blocking + int arg; + if( (arg = fcntl( m_iDeviceFD, F_GETFL, NULL)) < 0) { + char tBuf[128]; + sprintf( tBuf, "Error fcntl(..., F_GETFL) (%s)", strerror(errno)); + LOG_ERROR( tBuf ); + return false; + }; + arg |= O_NONBLOCK; + if( fcntl( m_iDeviceFD, F_SETFL, arg) < 0) { + char tBuf[128]; + sprintf( tBuf, "Error fcntl(..., F_SETFL) (%s)", strerror(errno)); + LOG_ERROR( tBuf ); + return false; + }; + setConnectionStatus( CS_CONNECTED ); + break; + }; + }; + return init(); +}; + +bool deviceETH2UART::closePort(){ + char tBuff[128]; + + setConnectionStatus( CS_DISCONNECTED ); + + if( m_bThreadAStatus != TH_PRE_INIT && m_bThreadBStatus != TH_PRE_INIT ){ + uninit(); + }; + if( m_iDeviceFD != -1 ) { + switch( m_sUartData.mode ) { + case SOL_UDP_CLIENT: + case SOL_TCP_CLIENT: + case SOL_UDP_SERVER: { + #ifdef __linux__ + close( m_iDeviceFD ); + #else + // When your application is finished receiving datagrams close the socket. + LOG("Server: Finished receiving.Closing the listening socket..."); + if( closesocket(m_sSocket) != 0 ){ + sprintf(tBuff, "closesocket() failed!Error code : %ld", WSAGetLastError()); + LOG_ERROR(tBuff); + } else { + LOG("closesocket() is OK..."); + }; + // When your application is finished call WSACleanup. + LOG("Server: Cleaning up..."); + if (WSACleanup() != 0) { + sprintf(tBuff, "WSACleanup() failed!Error code : %ld", WSAGetLastError()); + LOG_ERROR(tBuff); + } else { + LOG("WSACleanup() is OK"); + }; + #endif + break; + }; + case SOL_TCP_SERVER:{ + close( m_iDeviceFD ); + break; + }; + }; + m_iDeviceFD = -1; + }; + return true; +}; + +void deviceETH2UART::m_fThreadAProc(void){ + int index; + int RetVal; + m_bThreadAStatus = TH_WORKING; +#ifdef DEBUG + LOG("Sender Thread Started!"); +#endif + while (m_bThreadAStatus < TH_ENDED) { + m_mBufferProtectorMutex.lock(); + if( m_nOutputBufferSize > 0 ){ + index = 0; + while ((index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED)){ + RetVal = sendBlock(m_pOutputBuffer + index, m_nOutputBufferSize - index); + if( RetVal > 0 ) index += RetVal; + if( RetVal == -1 ){ + setConnectionStatus( CS_DISCONNECTED ); + m_nOutputBufferSize = 0; + m_bThreadBStatus = TH_ENDED; + m_bThreadAStatus = TH_ENDED; + LOG_ERROR("Connection Droped on Sending Data"); + }; + }; + m_nOutputBufferSize = 0; + m_mBufferProtectorMutex.unlock(); + } else { + m_mBufferProtectorMutex.unlock(); + SLEEP(5); + }; + }; +}; + +void deviceETH2UART::m_fThreadBProc(void){ + m_bThreadBStatus = TH_WORKING; + int RetVal; +#ifdef DEBUG + LOG("Recipient Thread Started!"); +#endif + while( m_bThreadBStatus < TH_ENDED ){ + RetVal = recptBlock( m_pInputBuffer, &m_nInputBufferSize); + if( RetVal == -1 ){ + setConnectionStatus(CS_DISCONNECTED); + m_nInputBufferSize = 0; + //if(!getStatus()) { + m_bThreadBStatus = TH_ENDED; + m_bThreadAStatus = TH_ENDED; + //} else SLEEP(100); + LOG_ERROR("Connection Droped on Reception Data"); + } else if( m_nInputBufferSize > 0 ){ + do{ + m_mQueueProtectorMutex.lock(); + if( m_vParsers.size() ){ + for (parseQueue::iterator index = m_vParsers.begin(); index != m_vParsers.end(); index++) (*index)->parse(m_pInputBuffer, m_nInputBufferSize); + m_nInputBufferSize = 0; + m_mQueueProtectorMutex.unlock(); + } else { + m_nInputBufferSize = 0; + m_mQueueProtectorMutex.unlock(); +#ifdef DEBUG_EXTRA + LOG_ERROR("Try to parse data but No Parsers Assigned!"); +#endif + SLEEP(100); + }; + } while( ( m_vParsers.size() == 0 ) && ( m_bThreadBStatus < TH_ENDED ) && ( m_bThreadBStatus < TH_ENDED ) ); + } else { + SLEEP(5); + }; + }; +}; + +bool deviceETH2UART::sendData( uint8_t *Data, int DataSize ){ + if( m_bThreadAStatus != TH_WORKING ) { + if( m_bThreadAStatus < TH_WORKING ) { + LOG_ERROR("Trying to Send Data Before Thread is Started!"); + } else { + LOG_ERROR("Trying to Send Data After Thread is Dead!"); + } + return false; + }; + m_mBufferProtectorMutex.lock(); + if (m_nOutputBufferSize + DataSize > MAXIMAL_SOCKET_PACKET_LENGTH ){ + m_mBufferProtectorMutex.unlock(); + LOG_ERROR("Data Too BIG"); + return false; + }; + memcpy(m_pOutputBuffer + m_nOutputBufferSize, Data, DataSize); + m_nOutputBufferSize += DataSize; + m_mBufferProtectorMutex.unlock(); + return true; +}; + +bool deviceETH2UART::reconnect( void ){ + closePort(); + m_bValid = create_SOL(); + return m_bValid; +}; + +int deviceETH2UART::recptBlock( unsigned char *Buffer, int *BufferLength ){ + +#ifdef __linux__ + int RetVal = 0; +#else + DWORD RetVal = 0; +#endif + + if( m_eConnectionStatus == CS_CONNECTED ){ +#ifdef __linux__ + if( m_iDeviceFD > -1 ) { + struct sockaddr ClientAddress; + socklen_t addr_len = sizeof( ClientAddress ); //len is value/resuslt + //RetVal = recvfrom( m_nSocketFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_WAITALL, ( struct sockaddr *) &m_sClientAddr, &addr_len ); + RetVal = recvfrom( m_iDeviceFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_DONTWAIT, ( struct sockaddr *) &ClientAddress, &addr_len ); + if( RetVal < 1 ){ + if( errno!=EAGAIN && errno!=EINTR ) { + LOG_ERROR("Peer Closes Connection!"); + shutdown( m_iDeviceFD, 2 ); + close( m_iDeviceFD ); + *BufferLength = 0; + m_iDeviceFD = -1; + setConnectionStatus( CS_DISCONNECTED ); + return -1; + }; + }; + + } else { + LOG_ERROR("Not Connected!"); + *BufferLength = 0; + setConnectionStatus( CS_DISCONNECTED ); + return -1; + }; +#else + switch ( m_eType ) { + case SOL_UDP_CLIENT: + case SOL_TCP_CLIENT: + case SOL_UDP_SERVER: { + SOCKADDR_IN tAddr; + int tLen = sizeof(SOCKADDR_IN); + RetVal = recvfrom( m_sSocket, (char*)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, 0, (struct sockaddr*) &tAddr, &tLen); + if (RetVal == SOCKET_ERROR){ + char cBuffer[165]; + sprintf(cBuffer,"recvfrom() failed with error code : %d", WSAGetLastError()); + LOG_ERROR(cBuffer); + }; + break; + }; + }; +#endif + } else { + //make prep for connection SOL_TCP_SERVER + if( m_sUartData.mode == SOL_TCP_CLIENT ){ + //ACCEPT + struct sockaddr ClientAddress; + socklen_t size = (socklen_t) sizeof( struct sockaddr_in ); + //int ClientSocket; + m_iDeviceFD = accept( m_iMasterFD, &ClientAddress, &size ); + if( m_iDeviceFD < 0 ) { + setConnectionStatus( CS_DISCONNECTED ); + LOG_ERROR("Connection Accept Failure!"); + }; + } else { + LOG_ERROR("RCPT ON not connected!"); + shutdown( m_iDeviceFD, 2 ); + close( m_iDeviceFD ); + *BufferLength = 0; + m_iDeviceFD = -1; + setConnectionStatus( CS_DISCONNECTED ); + }; + return -1; // Exit after unsuccess reconnect + }; + + if( RetVal > 0 ){ +#ifdef DEBUG_SERIAL_COMMUNICATION + char MsgBuffer[CLOG]; + if( RetVal > 1 || RetVal == 0 ) { + sprintf( MsgBuffer, "Received %d bytes", RetVal ); + } else { + sprintf( MsgBuffer, "Received 1 byte"); + }; + LOG( MsgBuffer ); + for (int i = 0; i < RetVal; i++) { + sprintf(MsgBuffer, "0x%02X", Buffer[i]); + LOG(MsgBuffer); + }; +#endif + *BufferLength = RetVal; + return RetVal; + }; + + *BufferLength = 0; + + if (RetVal == -1) return 0; + + if (RetVal == 0){ + errno = 0; + return 0; + }; + + /* r < -1, should never happen. */ + errno = EIO; + return 0; +}; + +int deviceETH2UART::sendBlock(unsigned char* Data, int DataSize) { +#ifdef __linux__ + int RetVal = 0; +#else + DWORD RetVal = 0; +#endif + + if( m_eConnectionStatus == CS_CONNECTED ){ +#ifdef __linux__ + if( m_iDeviceFD > -1 ){ + + #ifdef DEBUG_EXTRA + char cBuffer[256]; + sprintf(cBuffer, "Write into Port %d bytes", DataSize); + LOG(cBuffer); + #endif + struct sockaddr ClientAddress; + socklen_t addr_len = sizeof(ClientAddress); + RetVal = sendto( m_iDeviceFD, (const char*)Data, DataSize, MSG_CONFIRM, (const struct sockaddr*) &ClientAddress, addr_len); + + if ((RetVal == -1) && (errno != EINTR) && (errno != EWOULDBLOCK)) { + LOG_ERROR("Error acures while writing data into the Socket"); + shutdown( m_iDeviceFD, 2); + close( m_iDeviceFD); + m_iDeviceFD = -1; + setConnectionStatus(CS_DISCONNECTED); + return -1; + }; + + if (RetVal < 0) RetVal = 0; + + #ifdef DEBUG_EXTRA + sprintf(cBuffer, "Bytes Sent: %ld", RetVal); + LOG(cBuffer); + #ifdef DEBUG_SERIAL_COMMUNICATION + for(int zz=0; zz < RetVal; zz++ ) { + sprintf(cBuffer, "SD: 0x%02X", (uint8_t)Data[zz]); + LOG(cBuffer); + }; + #endif + #endif + + } else { + LOG_ERROR("Not Connected!"); + //m_bConnected = false; + setConnectionStatus(CS_DISCONNECTED); + return -1; + }; +#else // Windows + if (sendto( m_sSocket, (char *)Data, DataSize, 0, (struct sockaddr*) &ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR) { + char cBuffer[256]; + sprintf(cBuffer, "sendto() failed with error code : %d", WSAGetLastError()); + LOG_ERROR( cBuffer ); + return -1; + }; +#endif + } else { +#ifdef DEBUG + LOG( "Port is not Ready to Send" ); +#endif + return -1; + }; + return RetVal; +}; + + +#undef LOG_ERROR +#undef LOG diff --git a/lib/App/common/deviceNodeEthernet2Serial.h b/lib/App/common/deviceNodeEthernet2Serial.h new file mode 100644 index 00000000..51a3b328 --- /dev/null +++ b/lib/App/common/deviceNodeEthernet2Serial.h @@ -0,0 +1,55 @@ +#ifndef __DEVICE_NODE_ETHERNET2SERIAL_HEADER__ +#define __DEVICE_NODE_ETHERNET2SERIAL_HEADER__ + +#include "deviceNode.h" +#include "hardwareResource.h" +#include "../../components/base/basicTransport.h" +#include "../../components/base/basicDualThread.h" + +#ifndef MAXIMAL_SOCKET_PACKET_LENGTH + #define MAXIMAL_SOCKET_PACKET_LENGTH 102400 +#endif + +#ifndef MAXIMAL_SERIAL_PACKET_LENGTH + #define MAXIMAL_SERIAL_PACKET_LENGTH MAXIMAL_SOCKET_PACKET_LENGTH +#endif + +class deviceETH2UART: public deviceNode, public hardwareResource, public basicTransport, public basicDualThread{ + private: + //basicLogCollection * m_pLog; + DBC_UART_DATA m_sUartData; + + int m_iDeviceFD; + int m_iMasterFD; +#ifdef __linux__ + int m_iInFID; + int m_iOutFID; +#else + DCB PortDCB; + HANDLE m_ioFID; +#endif + bool pingDevice(); + bool create_SOL(); + bool closePort(); + int sendBlock(unsigned char *Data, int DataSize); + int recptBlock(unsigned char *Buffer, int *BufferLength); + protected: + U8 m_pInputBuffer[MAXIMAL_SOCKET_PACKET_LENGTH]; + U8 m_pOutputBuffer[MAXIMAL_SOCKET_PACKET_LENGTH]; + int m_nInputBufferSize; + int m_nOutputBufferSize; + + virtual void m_fThreadAProc(void); + virtual void m_fThreadBProc(void); + public: + explicit deviceETH2UART( uint32_t nodeID ); + ~deviceETH2UART(); + virtual bool create( void ); + virtual bool validate( void ); + virtual bool sendData( uint8_t *Data, int DataSize ); + virtual bool reconnect( void ); +}; + + +#endif + diff --git a/lib/App/common/deviceNodeFactory.cpp b/lib/App/common/deviceNodeFactory.cpp new file mode 100644 index 00000000..821f2379 --- /dev/null +++ b/lib/App/common/deviceNodeFactory.cpp @@ -0,0 +1,611 @@ +#include "deviceNodeFactory.h" +#ifdef USE_MYSQL + #include "MySQL_dataBinder.h" +#else + #include "SQLite_dataBinder.h" +#endif +#include "deviceNode3D.h" +#include "deviceNode2D.h" +#include "deviceNodePTZCamControl.h" +#include "deviceNodeStaticCamControl.h" +#include "deviceNodeEthernet2Serial.h" + +#ifdef MEM_DEBUG + #include "../alg/generic/heapDebug.h" +#endif + +#define LOG( X ) m_pLog->Log( "NFAC", this, X ) +#define LOG_ERROR( X ) m_pLog->Log( "NFAC", this, _LOG_ERROR, X ) + +deviceNodeFactory *deviceNodeFactory::_instance = NULL; + +/** +* Returns the single instance of the object. +*/ +deviceNodeFactory* deviceNodeFactory::getInstance() { + if( NULL == _instance ) { + _instance = new deviceNodeFactory(); + }; + return _instance; +}; + +deviceNodeFactory::deviceNodeFactory(): basicThread(){ + m_pLog = basicLogCollection::getInstance(); +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + init(); +}; + +deviceNodeFactory::~deviceNodeFactory(){ + waitThreadEnd( true ); + unloadNodes(); + _instance = NULL; +}; + +bool deviceNodeFactory::unloadNodes( void ){ + if( m_pDBC != NULL ){ + if( m_vDeviceNodes.size() > 0 ){ + for( vectorDeviceNodes::iterator index = m_vDeviceNodes.begin(); index < m_vDeviceNodes.end(); index++ ){ + LOG(" Unload Node... BEGIN"); + switch( (*index)->getNodeType() ){ + case ARGUS_ANALOG_STATIC_CAMERA: + LOG(" Static Analog Cam"); + delete( (deviceNodeStaticCamControl*) (*index) ); + break; + case ARGUS_ANALOG_PTZ_CAMERA: + LOG(" PTZ Analog Cam"); + delete( (deviceNodePTZCamControl*) (*index) ); + break; + case ARGUS_IP_PTZ_CAMERA:{ + LOG(" PTZ IP Cam"); + delete( (deviceNodePTZCamControl*) (*index) ); + break; + }; + case ARGUS_IP_STATIC_CAMERA:{ + LOG(" Static IP Cam"); + delete( (deviceNodeStaticCamControl*) (*index) ); + break; + }; + case ARGUS_IP_UART_GATEWAY:{ + LOG(" UART Gateway"); + delete( (deviceETH2UART*) (*index) ); + break; + }; + case ARGUS_ALS_SENSOR: + case ARGUS_PLS_200_SENSOR: + case ARGUS_PLS_360_SENSOR: + case ARGUS_LFS_SENSOR:{ + LOG(" 2D LRF"); + delete( (device2DSensor*) (*index) ); + LOG(" 2D LRF done"); + break; + }; + case ARGUS_3D_SENSOR:{ + LOG(" 3D LRF"); + delete( (device3DSensor*) (*index) ); + break; + }; + }; + LOG(" Unload Node... DONE!"); + }; + m_vDeviceNodes.clear(); + m_mDeviceNodesIDS.clear(); + }; + }; + return true; +}; +/* +bool deviceNodeFactory::loadNodes( uint32_t SiteID ){ + LOG("Node Loader"); + if(m_pDBC == NULL) return false; + m_nSiteID = SiteID; + DBC_INT_LIST *tList = m_pDBC->listNodes( SiteID ); + if( tList != NULL ) { + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ){ + uint32_t id = *idx; + char msg[64]; + sprintf( msg, "Creating Node[%d]", id ); + createNode( id ); + }; + tList->clear(); + delete( tList ); + return true; + }; + return false; +}; +*/ +bool deviceNodeFactory::loadNodes(){ + if( m_pDBC == NULL ) return false; + DBC_INT_LIST *tList = m_pDBC->listNodes(); + if( tList != NULL ) { + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ) createNode((*idx)); + tList->clear(); + delete( tList ); + } +#ifdef DEBUG + else { + LOG("No Nodes Defined"); + } +#endif + return true; +}; + +bool deviceNodeFactory::reloadNodes( ){ + if(!unloadNodes()) return false; + return loadNodes( ); +}; + +bool deviceNodeFactory::reloadNode( uint32_t NodeID ){ + deleteNode( NodeID ); + deviceNode *tNode = createNode( NodeID ); + if( tNode ) { + return true; + }; + return false; +}; + +deviceNode *deviceNodeFactory::createNode( uint32_t id ){ + deviceNode *tVal = NULL; + if( m_pDBC != NULL ){ + DBC_NODE_DATA *tData = NULL; + tData = m_pDBC->getNodeData( id ); + if( tData!= NULL ) { +#ifdef DEBUG + char tB[256]; + sprintf( tB, "Node id: %d AUX id: %d", id, tData->aux_id ); + LOG( tB ); + sprintf( tB, "Node type: %d", tData->type ); + LOG( tB ); + sprintf( tB, "Node Name: %s", tData->name ); + LOG( tB ); +#endif + switch( tData->type ) { + case ARGUS_ANALOG_STATIC_CAMERA:{ +#ifdef DEBUG + LOG("Creating Analog Static Camera"); +#endif + deviceNodeStaticCamControl *tCamera; + tCamera = new deviceNodeStaticCamControl( id ); + if( tCamera ) { + LOG("Starting Service"); + tCamera->startService(); + tVal = ( deviceNode *) tCamera; + LOG("Success"); + }; + break; + }; + case ARGUS_ANALOG_PTZ_CAMERA:{ +#ifdef DEBUG + LOG("Creating Analog PTZ Camera"); +#endif + deviceNodePTZCamControl *tCamera; + tCamera = new deviceNodePTZCamControl( id ); + if( tCamera ) { + LOG("Starting Service"); + tCamera->startService(); + tVal = ( deviceNode *) tCamera; + LOG("Success"); + }; + break; + }; + case ARGUS_IP_STATIC_CAMERA:{ +#ifdef DEBUG + LOG("Creating IP Static Camera"); +#endif + deviceNodeStaticCamControl *tCamera; + tCamera = new deviceNodeStaticCamControl( id ); + if( tCamera ) { +#ifdef DEBUG + LOG("Starting Service"); +#endif + if( tCamera->startService() ){ + tVal = ( deviceNode *) tCamera; +#ifdef DEBUG + LOG("Success"); +#endif + } else { +#ifdef DEBUG + LOG_ERROR("Error Sterting Service"); +#endif + delete( tCamera ); + }; + }; + break; + }; + case ARGUS_IP_PTZ_CAMERA:{ + +#ifdef DEBUG + LOG("Creating IP PTZ Camera"); +#endif + deviceNodePTZCamControl *tCamera; + tCamera = new deviceNodePTZCamControl( id ); + if( tCamera ) { +#ifdef DEBUG + LOG("Starting Service"); +#endif + if( tCamera->startService() ){ + tVal = ( deviceNode *) tCamera; +#ifdef DEBUG + LOG("Success"); +#endif + } else { +#ifdef DEBUG + LOG_ERROR("Error Starting Service!"); +#endif + delete( tCamera ); + }; + }; + break; + }; + case ARGUS_IP_UART_GATEWAY:{ +#ifdef DEBUG + LOG("Creating Ethernet to UART Gateway"); +#endif + deviceETH2UART *tGW; + tGW = new deviceETH2UART( id ); + if ( tGW ) { + if ( tGW->create() ) { + tVal = ( deviceNode *) tGW; + } else { + delete( tGW ); + }; + }; + break; + }; + case ARGUS_IP_VIDEO_SERVER: +#ifdef DEBUG + LOG("Creating Network Video Encoder"); +#endif + break; + case ARGUS_LFS_SENSOR:{ +#ifdef DEBUG + LOG("Creating LFS Sensor"); +#endif + device2DSensor *tSensor; + tSensor = new device2DSensor( id ); + if( tSensor ) { + LOG("Success"); + tSensor->startService(); + tVal = ( deviceNode *) tSensor; + }; + break; + }; + case ARGUS_ALS_SENSOR:{ +#ifdef DEBUG + LOG("Creating ALS Sensor"); +#endif + device2DSensor *tSensor; + tSensor = new device2DSensor( id ); + if( tSensor ) { + LOG("Success"); + tSensor->startService(); + tVal = ( deviceNode *) tSensor; + }; + break; + }; + case ARGUS_PLS_200_SENSOR:{ +#ifdef DEBUG + LOG("Creating PLS200 Sensor"); +#endif + device2DSensor *tSensor; + tSensor = new device2DSensor( id ); + if( tSensor ) { + LOG("Success"); + tSensor->startService(); + tVal = ( deviceNode *) tSensor; + }; + break; + }; + case ARGUS_PLS_360_SENSOR:{ +#ifdef DEBUG + LOG("Creating PLS360 Sensor"); +#endif + device2DSensor *tSensor; + tSensor = new device2DSensor( id ); + if( tSensor ) { + LOG("Success"); + tSensor->startService(); + tVal = ( deviceNode *) tSensor; + }; + break; + }; + case ARGUS_3D_SENSOR:{ +#ifdef DEBUG + LOG("Creating 3D Sensor"); +#endif + device3DSensor *t3DRadar; + t3DRadar = new device3DSensor( id ); + if( t3DRadar ) { + LOG("Success"); + t3DRadar->startService(); + tVal = ( deviceNode *) t3DRadar; + }; + break; + }; + case ARGUS_JAMER: +#ifdef DEBUG + LOG("Creating RF Jamer"); +#endif + break; + case ARGUS_NET_PLS_200: +#ifdef DEBUG + LOG("Creating Network-PLS200 Sensor"); +#endif + break; + case ARGUS_DRONE_CONTROL: +#ifdef DEBUG + LOG("Creating Drone Controll"); +#endif + break; + }; + free(tData); + }; + }; + if( tVal != NULL ){ +#ifdef DEBUG + char tB[64]; + sprintf( tB, "Node PTR: %p", tVal ); + LOG( tB ); +#endif + m_vDeviceNodes.push_back( tVal ); + m_mDeviceNodesIDS[id] = tVal; + }; + return tVal; +}; + +void deviceNodeFactory::deleteNode( deviceNode *ptr ){ + if( ptr == NULL ) return; + // if some troubles move this to an end of the function! + for( vectorDeviceNodes::iterator index = m_vDeviceNodes.begin() ; index < m_vDeviceNodes.end(); index++ ){ + if( (*index) == ptr ) { + m_mDeviceNodesIDS.erase( ptr->getNodeID() ); + m_vDeviceNodes.erase( index ); + break; + }; + }; + switch( ptr->getNodeType() ) { + case ARGUS_ANALOG_STATIC_CAMERA: +#ifdef DEBUG + LOG("Destroying Analog Static Camera"); +#endif + break; + case ARGUS_ANALOG_PTZ_CAMERA: +#ifdef DEBUG + LOG("Destroying Analog PTZ Camera"); +#endif + break; + case ARGUS_IP_STATIC_CAMERA: +#ifdef DEBUG + LOG("Destroying Network Static Camera"); +#endif + //SLEEP(2000); + LOG("Actual Destroying Network Static Camera"); + delete((deviceNodePTZCamControl *) ptr ); + break; + case ARGUS_IP_PTZ_CAMERA: +#ifdef DEBUG + LOG("Destroying Network PTZ Camera"); +#endif + //SLEEP(2000); + delete((deviceNodePTZCamControl *) ptr ); +#ifdef DEBUG + LOG("Done Successfuly"); +#endif + break; + case ARGUS_IP_UART_GATEWAY: +#ifdef DEBUG + LOG("Destroying Ethernet to UART Gateway"); +#endif + break; + case ARGUS_IP_VIDEO_SERVER: +#ifdef DEBUG + LOG("Destroying Network Video Encoder"); +#endif + break; + case ARGUS_LFS_SENSOR: +#ifdef DEBUG + LOG("Destroying LFS Sensor"); +#endif + delete((device2DSensor *) ptr ); + break; + case ARGUS_ALS_SENSOR: +#ifdef DEBUG + LOG("Destroying ALS Sensor"); +#endif + delete((device2DSensor *) ptr ); + break; + case ARGUS_PLS_200_SENSOR: +#ifdef DEBUG + LOG("Destroying PLS200 Sensor"); +#endif + delete((device2DSensor *) ptr ); + break; + case ARGUS_PLS_360_SENSOR: +#ifdef DEBUG + LOG("Destroying PLS360 Sensor"); +#endif + delete((device2DSensor *) ptr ); + break; + case ARGUS_3D_SENSOR: +#ifdef DEBUG + LOG("Destroying 3D Sensor"); +#endif + delete((device3DSensor *) ptr ); + break; + case ARGUS_JAMER: +#ifdef DEBUG + LOG("Destroying RF Jamer"); +#endif + break; + case ARGUS_NET_PLS_200: +#ifdef DEBUG + LOG("Destroying Network-PLS200 Sensor"); +#endif + break; + case ARGUS_DRONE_CONTROL: +#ifdef DEBUG + LOG("Destroying Drone Controll"); +#endif + break; + }; +}; + +/* + @id Database ID of Node to be deleted +*/ +deviceNode *deviceNodeFactory::getNode( uint32_t id ){ + mapDeviceNode2Id::iterator it; + it = m_mDeviceNodesIDS.find( id ); + if( it != m_mDeviceNodesIDS.end() ) { + return m_mDeviceNodesIDS[id]; + }; + return NULL; +}; + +/* + @id Database ID of Node to be deleted +*/ +void deviceNodeFactory::deleteNode( uint32_t id ){ + deviceNode *tNode = getNode( id ); + deleteNode( tNode ); +}; + +bool deviceNodeFactory::validate( void ){ + return ( m_bThreadStatus < TH_ENDED ); +}; + +void deviceNodeFactory::m_fThreadProc( void ){ + if( m_pDBC == NULL ){ + m_bThreadStatus = TH_ENDED; + } else { + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { + + DBC_INT_LIST *tList = NULL; +#ifdef DEBUG + #ifdef MEM_DEBUG + size_t memStart, memEnd, memDiff; + char MEM_MSG[256]; + memStart = getCurrentRSS(); + #endif +#endif + if( m_vDeviceNodes.size() ) { + DBC_INT_LIST tL; + for( vectorDeviceNodes::iterator idx = m_vDeviceNodes.begin(); idx < m_vDeviceNodes.end(); idx++ ) tL.push_back( (*idx)->getNodeID() ); + tList = m_pDBC->listNewNodes( &tL ); + tL.clear(); + } else { + tList = m_pDBC->listNewNodes( NULL ); + }; + if( tList != NULL ) { +#ifdef DEBUG + LOG("New Nodes Added!"); +#endif + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ) createNode( *idx ); + tList->clear(); + delete( tList ); + } +#ifdef DEBUG_EXTRA + else { + LOG( "No New Nodes Added"); + } +#endif +#ifdef MEM_DEBUG + memEnd = getCurrentRSS(); + memDiff = memEnd - memStart; + sprintf(MEM_MSG,"MEM START: %d MEM DIF1: %d", memStart, memDiff ); + LOG( MEM_MSG ); +#endif + + if( m_vDeviceNodes.size() ) { + //Get Full List + tList = m_pDBC->listNodes(); + if( tList != NULL ) { + for( vectorDeviceNodes::iterator idx = m_vDeviceNodes.begin(); idx < m_vDeviceNodes.end(); idx++ ){ + bool tRemoved = true; + // Check if Removed By changes in DB + for( DBC_INT_LIST::iterator idz = tList->begin(); idz < tList->end(); idz++ ) if( (*idz) == (*idx)->getNodeID() ) tRemoved = false; + // If Not - check validation + if( !tRemoved ){ +#ifdef DEBUG_EXTRA + LOG("Node Among Active Nodes.... make Validation"); +#endif + tRemoved = !(*idx)->validate(); + }; + // If Node is Invalid - Removing + if( tRemoved ) { +#ifdef DEBUG + LOG("Node not passed Validation!"); +#endif + deleteNode((*idx)); + }; + }; + tList->clear(); + delete( tList ); + } else { +#ifdef DEUBG + LOG("All Modules Must be Deleted!"); +#endif + for( vectorDeviceNodes::iterator idx = m_vDeviceNodes.begin(); idx < m_vDeviceNodes.end(); idx++ ) deleteNode((*idx)); + m_vDeviceNodes.clear(); + m_mDeviceNodesIDS.clear(); + }; +#ifdef DEBUG_EXTRA + } else { + LOG("No Nodes to Validate"); +#endif + }; +#ifdef DEBUG + #ifdef MEM_DEBUG + memEnd = getCurrentRSS(); + memDiff = memEnd - memStart; + sprintf(MEM_MSG,"MEM START: %d MEM DIF2: %d", memStart, memDiff ); + LOG( MEM_MSG ); + #endif +#endif + // Sleep for 1 second + for( int i = ( 1000 / DEFAULT_THREAD_SLEEP_TIME ); i && ( m_bThreadStatus < TH_ENDED ); i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + }; + }; + LOG("EXIT FROM CTRL THREAD"); +}; + +uint32_t deviceNodeFactory::getNodesCount( ARGUS_NODE_TYPE type ){ + uint32_t RetVal = 0; + if( m_vDeviceNodes.size() ) for( vectorDeviceNodes::iterator index = m_vDeviceNodes.begin(); index < m_vDeviceNodes.end(); index++ ) if( (*index)->getNodeType() == type ) RetVal++; + return RetVal; +}; + +uint32_t deviceNodeFactory::fetchNodes( ARGUS_NODE_TYPE type, deviceNode **&RA ){ + uint32_t RetVal = 0; + if( RA == NULL ) { + RetVal = getNodesCount( type ); + if( RetVal > 0 ) { + RA = (deviceNode **) calloc( RetVal, sizeof(deviceNode *)); + if( RA == NULL ) return 0; + uint32_t cnt = 0; + for( vectorDeviceNodes::iterator index = m_vDeviceNodes.begin(); index < m_vDeviceNodes.end(); index++ ) { + if( (*index)->getNodeType() == type ) { + RA[cnt] = (*index); + cnt++; + }; + }; + }; + } else { + if( m_vDeviceNodes.size() ) { + for( vectorDeviceNodes::iterator index = m_vDeviceNodes.begin(); index < m_vDeviceNodes.end(); index++ ) { + if( (*index)->getNodeType() == type ) { + RA[RetVal] = (*index); + RetVal++; + }; + }; + }; + }; + return RetVal; +}; + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/common/deviceNodeFactory.h b/lib/App/common/deviceNodeFactory.h new file mode 100644 index 00000000..a2341de8 --- /dev/null +++ b/lib/App/common/deviceNodeFactory.h @@ -0,0 +1,36 @@ +#ifndef __DEVICE_NODE_FACTORY_HEADER__ +#define __DEVICE_NODE_FACTORY_HEADER__ + +#include "dataBinder.h" +#include "deviceNode.h" +#include "../components/base/basicThread.h" + + +class deviceNodeFactory: public basicThread{ + private: + basicLogCollection * m_pLog; + dataBinder * m_pDBC; + vectorDeviceNodes m_vDeviceNodes; + mapDeviceNode2Id m_mDeviceNodesIDS; + public: + static deviceNodeFactory * getInstance(); + virtual ~deviceNodeFactory(); + deviceNode * createNode( uint32_t id ); + void deleteNode( deviceNode *ptr ); + void deleteNode( uint32_t id ); + uint32_t fetchNodes( ARGUS_NODE_TYPE type, deviceNode **&RA ); + deviceNode * getNode( uint32_t id ); + uint32_t getNodesCount( ARGUS_NODE_TYPE type ); + bool loadNodes(); + bool unloadNodes( void ); + bool reloadNodes( ); + bool reloadNode( uint32_t NodeID ); + bool validate( void ); + protected: + explicit deviceNodeFactory( ); + virtual void m_fThreadProc( void ); + private: + static deviceNodeFactory * _instance; +}; + +#endif \ No newline at end of file diff --git a/lib/App/common/deviceNodePTZCamControl.cpp b/lib/App/common/deviceNodePTZCamControl.cpp new file mode 100644 index 00000000..3c50842d --- /dev/null +++ b/lib/App/common/deviceNodePTZCamControl.cpp @@ -0,0 +1,194 @@ +#include "deviceNodePTZCamControl.h" + +#define LOG( X ) deviceNode::m_pLog->Log( "PTZ_CAM", this, X ) +#define LOG_ERROR( X ) deviceNode::m_pLog->Log( "PTZ_CAM", this, _LOG_ERROR, X ) + +deviceNodePTZCamControl::deviceNodePTZCamControl( DBC_NODE_DATA *Data ): deviceNodeCamera( Data ), basicEventHandler(){ + //m_pLog = basicLogCollection::getInstance(); +/* + DBC_CAM_DATA * tData = m_pDBC->getCamData( m_sNodeData.aux_id ); + + m_fMaxRange = m_fMinHFov = m_fMaxHFov = m_fMinVFov = m_fMaxVFov = .0f; + + if( tData != NULL ) { + memcpy( &m_sCamData, tData, sizeof(DBC_CAM_DATA) ); + free( tData ); + }; + memset( &m_sCtrlData, 0, sizeof(CAMERA_CTRL_DATA) ); + if( m_sCamData.max_range == .0f ){ + m_fMaxRange = calcMaxDistance_mm( AC_imager_diag[m_sCamData.imager_type], m_sCamData.max_f, 1280 ); + } else { + m_fMaxRange = m_sCamData.max_range; + }; + m_fMinHFov = calcFOV_mm( AC_imager_width[m_sCamData.imager_type], m_sCamData.min_f ); + m_fMaxHFov = calcFOV_mm( AC_imager_width[m_sCamData.imager_type], m_sCamData.max_f ); + m_fMinVFov = calcFOV_mm( AC_imager_height[m_sCamData.imager_type], m_sCamData.min_f ); + m_fMaxVFov = calcFOV_mm( AC_imager_height[m_sCamData.imager_type], m_sCamData.max_f ); +#ifdef DEBUG + char tB[128]; + LOG("Camera Info:"); + sprintf( tB, "Maximal Range: %0.2f m. ", m_fMaxRange); + LOG(tB); + sprintf( tB, "Maximal FOVs, Horizontal: %0.2f Vertical: %0.2f", m_fMinHFov, m_fMinVFov ); + LOG(tB); + sprintf( tB, "Minimal FOVs, Horizontal: %0.2f Vertical: %0.2f", m_fMaxHFov, m_fMaxVFov ); + LOG(tB); +#endif + m_pPosition = new basicPosition( m_sCamData.lat, m_sCamData.lon, m_sCamData.alt, m_sCamData.roll, m_sCamData.pitch, m_sCamData.yaw ); + */ +}; + +deviceNodePTZCamControl::deviceNodePTZCamControl( uint32_t id ): deviceNodeCamera( id ), basicEventHandler(){ + m_sMediaSource.mediaSourceId = m_sNodeData.aux_id; + strncpy( m_sMediaSource.mediaName, m_sNodeData.name, 128 ); + m_sMediaSource.mediaName[127] = (char)0; + memset( &m_sCtrlData, 0, sizeof( CAMERA_CTRL_DATA )); +}; + +deviceNodePTZCamControl::~deviceNodePTZCamControl(){ + LOG("Destructor"); + stopService(); +}; + +bool deviceNodePTZCamControl::startService(){ + return create(); +}; + +bool deviceNodePTZCamControl::stopService(){ + return true; +}; + + + +void deviceNodePTZCamControl::dispatchEvent( EVENT_CONTAINER *E ){ + if( E == NULL ) return; + //if( !m_sCamData.online ) return; + //if( m_bBusy ) return; + switch( E->m_eClass ) { + case EVT_CLASS_SENSOR_CLD: + case EVT_CLASS_SENSOR_LGS: + case EVT_CLASS_SENSOR_LFS: + case EVT_CLASS_SENSOR_MND: + case EVT_CLASS_SENSOR_PLS_210: + case EVT_CLASS_SENSOR_PLS_360: + case EVT_CLASS_SENSOR_ALS: + case EVT_CLASS_SENSOR_3D: + case EVT_CLASS_SENSOR_ACC:{ + switch( E->m_eType ) { + case EVT_TARGET_1D: + case EVT_TARGET_2D_BLACK: + case EVT_TARGET_2D_WHITE: + case EVT_TARGET_3D_BLACK: + case EVT_TARGET_3D_WHITE: + case EVT_ROI_ACTIVE:{ + TARGET_DATA *tDATA; + tDATA = (TARGET_DATA *)E->m_pEvtData; + if( tDATA ) { +#ifdef DEBUG + LOG( "CHECK CAMERA FOV" ); +#endif + if (testFOV(tDATA->system_target)) { +#ifdef DEBUG + LOG("TARGET IN CAMERA FOV"); +#endif + if(lookAt(E->m_db_id, tDATA->system_target)){ + /* + AnyDesk 958906475 +#ifdef DEBUG + LOG("CHECK CAMERA STREAMS"); +#endif + EVENT_CONTAINER *tEVT; + DBC_INT_LIST *tStreams; + tStreams = m_pDBC->listCamMediaStreams( m_sNodeData.aux_id ); + if( tStreams!= NULL ) { + for( uint32_t idx = 0; idx < tStreams->size(); idx++ ) { + tEVT = createBasicTargetedEvent( m_nDBID, tStreams->at(idx), EVT_CLASS_VIDEO, EVT_CAPTURE_START, E->m_UUID ); + if( tEVT != NULL ) { + tEVT->m_ref_id = E->m_db_id; + m_pEvtHeap->broadcast( tEVT ); + }; + }; + delete( tStreams ); + }; + */ + }; + }; + }; + break; + }; + }; + break; + }; + case EVT_CLASS_CAMERA_CTRL:{ + /* + if( E->m_nDestinationUID == m_sCamData.node_id ) { + switch( E->m_eType ) { + case EVT_CAMERA_DM:{ + CAMERA_CTRL_DATA *tDATA = (CAMERA_CTRL_DATA *)E->m_pEvtData; + if( tDATA != NULL ) { + if( tDATA->moveMask & 0x08 == 0x08 ){ + //Relative Move cmd + if( tDATA->moveMask & 0x07 == 0 ){ + relativeStop(); + } else { + relativeMove( tDATA->spdPAN, tDATA->spdTILT, tDATA->spdZOOM ); + }; + } else { + if( tDATA->moveMask & 0xF0 != 0x00 ) { + absoluteMove( tDATA->absPAN, tDATA->absTILT, tDATA->absZOOM ); + }; + }; + }; + break; + }; + }; + } + ;*/ + break; + }; + }; +}; +bool deviceNodePTZCamControl::validate(){ +#ifdef DEBUG_EXTRA + LOG("VALIDATE"); +#endif + if( CAM_WS_END == getWM() ) return false; + // Validate Camera Settings + /*{ + DBC_CAM_DATA *tDATA = argusNetNode::m_pDBC->getCamData( m_sNodeData.aux_id ); + if( tDATA ) { + if( memcmp( &m_sCamData, tDATA, sizeof(DBC_CAM_DATA)) != 0 ){ + free( tDATA ); + LOG("Cam Settings Changed!"); + return false; + }; + free( tDATA ); + } else{ + LOG("Cam Deleted!"); + return false; + }; + }*/ + // Validate Stream - > moved to Video Encoder! + /* + { + if( m_sNodeData.aux_parameter ) { +#ifdef DEBUG_EXTRA + LOG("VALIDATE Stream"); +#endif + if( !m_bSourceConnected ) { + if( connectToStream( m_sNodeData.aux_parameter ) ) { + argusNetNode::m_pDBC->setStreamValid( m_sNodeData.aux_parameter ); + } else { + argusNetNode::m_pDBC->setStreamValid( m_sNodeData.aux_parameter, false ); + }; + } else { + validateStream(); + }; + }; + } + */ + return deviceNodeCamera::validate(); +}; + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/common/deviceNodePTZCamControl.h b/lib/App/common/deviceNodePTZCamControl.h new file mode 100644 index 00000000..6f47fa4a --- /dev/null +++ b/lib/App/common/deviceNodePTZCamControl.h @@ -0,0 +1,44 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2017. All Rights Reserved. +// Version 2.0 6/11/2019 +// Last modification: 6/11/2019 +// PROJECT: +// SUBSYSTEM: +// FILE: rgooseIPCamera.h +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// Header file of rgooseIPCamera.h +//---------------------------------------------------------------------------- +// +#ifndef __DEVICE_PTZ_CAMERA_CTRL_HEADER__ +#define __DEVICE_PTZ_CAMERA_CTRL_HEADER__ + +#include "deviceNodeCamera.h" +#include "../../components/base/basicEventHandler.h" +#include "../../components/base/basicEventHeap.h" + +//https://www.ebay.com/itm/Professional-Rolling-Makeup-Case-Bulb-Mirror-Cosmetic-Artist-Dressing-Train-Case/233264525474 + +//ffmpeg -i input.mp4 -af loudnorm=I=-23:LRA=7:tp=-2:print_format=json -f null - +//ffmpeg -i input.mp4 -af loudnorm=I=-23:LRA=7:tp=-2:measured_I=-30:measured_LRA=1.1:measured_tp=-11 04:measured_thresh=-40.21:offset=-0.47 -ar 48k -y output.mp4 + +class deviceNodePTZCamControl: public deviceNodeCamera, public basicEventHandler { + protected: + CAMERA_CTRL_DATA m_sCtrlData; + + //virtual bool relativeMove( float PanSPD, float TiltSPD, float ZoomSPD ); + //virtual bool relativeStop(); + //virtual bool absoluteMove( float PanPOS, float TiltPOS, float ZoomPOS ); + public: + explicit deviceNodePTZCamControl( uint32_t id ); + explicit deviceNodePTZCamControl( DBC_NODE_DATA *Data = NULL ); + ~deviceNodePTZCamControl(); + virtual void dispatchEvent( EVENT_CONTAINER *Evt ); + virtual bool startService(); + virtual bool stopService(); + virtual bool validate(); +}; + +#endif diff --git a/lib/App/common/deviceNodeSensor.cpp b/lib/App/common/deviceNodeSensor.cpp new file mode 100644 index 00000000..5485ce46 --- /dev/null +++ b/lib/App/common/deviceNodeSensor.cpp @@ -0,0 +1,656 @@ +#include "deviceNodeSensor.h" +#include "../../components/object/objectSystemAnchor.h" + +#include + +#define LOG( X ) deviceNode::m_pLog->Log( "NODSEN", this, X ) +#define LOG_ERROR( X ) deviceNode::m_pLog->Log( "NODSEN", this, _LOG_ERROR, X ) + +deviceNodeSensor::deviceNodeSensor( uint32_t id ):deviceNode( id ),m_oPosition(){ + m_pEventHeap = basicEventHeap::getInstance(); + switch( m_sNodeData.type ){ + case ARGUS_CLD_SENSOR: m_eEventClass = EVT_CLASS_SENSOR_CLD; break; + case ARGUS_LGS_SENSOR: m_eEventClass = EVT_CLASS_SENSOR_LGS; break; + case ARGUS_ALS_SENSOR: m_eEventClass = EVT_CLASS_SENSOR_ALS; break; + case ARGUS_LFS_SENSOR: m_eEventClass = EVT_CLASS_SENSOR_LFS; break; + case ARGUS_PLS_200_SENSOR: m_eEventClass = EVT_CLASS_SENSOR_PLS_210; break; + case ARGUS_PLS_360_SENSOR: m_eEventClass = EVT_CLASS_SENSOR_PLS_360; break; + case ARGUS_3D_SENSOR: m_eEventClass = EVT_CLASS_SENSOR_3D; break; + default: m_eEventClass = EVT_CLASS_SYSTEM; break; + }; + m_pTargetFilter = NULL; + memset( &m_sLRF_DATA, 0, sizeof(DBC_LRF_DATA)); + if( m_pDBC ){ + DBC_LRF_DATA *tDATA = m_pDBC->getLRFData(m_sNodeData.aux_id); + if( tDATA != NULL ) { + memcpy( &m_sLRF_DATA, tDATA, sizeof(DBC_LRF_DATA)); + free( tDATA ); + }; + }; + systemAnchor *SA = systemAnchor::getInstance(); + if( SA ){ + LOG("SysAnchor OK"); + if ( SA->beLocal() ) { + LOG("SysAnchor beLocal!"); + m_oPosition.setPositionXYZ( m_sLRF_DATA.x, m_sLRF_DATA.y, m_sLRF_DATA.z, 0 ); //SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + } else { + LOG("SysAnchor is Global Position System!"); + C3D_DECART LD = SA->getXYZ(); + m_oPosition.setPositionXYZ( LD.x + m_sLRF_DATA.x, LD.y + m_sLRF_DATA.y, LD.z + m_sLRF_DATA.z, SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + }; + } else { + LOG("No SysAnchor!"); + m_oPosition.setPositionXYZ( m_sLRF_DATA.x , m_sLRF_DATA.y, m_sLRF_DATA.z ); + m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + }; + m_oPosition.updateMatrix(); + +#ifdef DEBUG + char tB[128]; + sprintf( tB, "Finalized Sensor Location: Lat:%.3f Lon:%.3f Alt:%.3f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); + LOG( tB ); + sprintf( tB, "Finalized Sensor Location: x:%.3f y:%.3f z:%.3f", m_oPosition.getX(), m_oPosition.getY(), m_oPosition.getZ() ); + LOG( tB ); + sprintf( tB, "Orientation: x:%.3f y:%.3f z:%.3f", m_oPosition.getRotX_deg(), m_oPosition.getRotY_deg(), m_oPosition.getRotZ_deg() ); + LOG( tB ); +#endif + +}; + +deviceNodeSensor::deviceNodeSensor( DBC_NODE_DATA *Data ):deviceNode( Data ),m_oPosition(){ + m_pTargetFilter = NULL; + m_pLog = basicLogCollection::getInstance(); + memset( &m_sLRF_DATA, 0, sizeof(DBC_LRF_DATA)); + if( m_pDBC ){ + DBC_LRF_DATA *tDATA = m_pDBC->getLRFData(m_sNodeData.aux_id); + if( tDATA != NULL ) { + memcpy( &m_sLRF_DATA, tDATA, sizeof(DBC_LRF_DATA)); + free( tDATA ); + }; + }; + systemAnchor *SA = systemAnchor::getInstance(); + if( SA ){ + LOG("SysAnchor OK"); + if ( SA->beLocal() ) { + LOG("SysAnchor beLocal!"); + m_oPosition.setPositionXYZ( m_sLRF_DATA.x, m_sLRF_DATA.y, m_sLRF_DATA.z, 0 ); //SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + } else { + LOG("SysAnchor is Global Position System!"); + C3D_DECART LD = SA->getXYZ(); + m_oPosition.setPositionXYZ( LD.x + m_sLRF_DATA.x, LD.y + m_sLRF_DATA.y, LD.z + m_sLRF_DATA.z, SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + }; + } else { + LOG("No SysAnchor!"); + m_oPosition.setPositionXYZ( m_sLRF_DATA.x , m_sLRF_DATA.y, m_sLRF_DATA.z ); + m_oPosition.setOrientationDeg( m_sLRF_DATA.x_rot , m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + }; + m_oPosition.updateMatrix(); + +#ifdef DEBUG + char tB[128]; + sprintf( tB, "Finalized Sensor Location: Lat:%.3f Lon:%.3f Alt:%.3f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); + LOG( tB ); + sprintf( tB, "Finalized Sensor Location: x:%.3f y:%.3f z:%.3f", m_oPosition.getX(), m_oPosition.getY(), m_oPosition.getZ() ); + LOG( tB ); + sprintf( tB, "Orientation: x:%.3f y:%.3f z:%.3f", m_oPosition.getRotX_deg(), m_oPosition.getRotY_deg(), m_oPosition.getRotZ_deg() ); + LOG( tB ); +#endif +}; + + +deviceNodeSensor::~deviceNodeSensor(){ + +}; + +#define SKIP_LINE_PIXELS 28 +#define HEIGHT 512 +#define WIDTH 1024 +// scale factor -> 4/9 + +uint8_t *deviceNodeSensor::create2dDraw( uint32_t *out_size, uint32_t *th_data, size_t th_size, uint16_t max_digital, int radial_shift, CSTR tpl, bool byMinimum ){ + uint8_t *RetVal = NULL; + *out_size = 0; + LOG("C2DD"); + if( th_data != NULL && th_size != 0 ) { + if ( fileExist( tpl ) ) { + LOG(tpl); + cv::Mat tImage = cv::imread( tpl, cv::IMREAD_UNCHANGED ); + int psize = th_size / ( sizeof( uint32_t )); + float stp = 2.0f * ( M_PI / (float) psize ); + //float MR = m_sLRF_DATA.max_range; + float S = ( M_PI / 3000.0f) * (float) radial_shift; + int x0 = (tImage.cols >> 1); + int y0 = (tImage.rows >> 1); + float maxR = ((float) x0 ) * 0.98f; + LOG("C2DD - Start"); + + cv::Point pts[(psize << 1)]; + cv::Point ptt[(psize+2)]; + const cv::Point * ppt[1]; + int npp[1]; + + const cv::Point * ppz[1]; + int npz[1]; + + float rst; + + int rpt; + uint16_t RANGE = 0; + + ptt[0].x = x0; + ptt[0].y = y0; + rst = maxR / ((float)(max_digital+1)); + rpt = 1; + for( int i=0; i < psize; i++ ){ + if( byMinimum ) { + RANGE = ( th_data[i] >> 16 ) & 0xFFFF; + } else { + RANGE = th_data[i] & 0xFFFF; + }; + + float ca = 0.0 - ( S + i * stp ); + if( RANGE > 0 ){ + pts[psize+i].x = x0 + maxR * cosf( ca ); + pts[psize+i].y = y0 + maxR * sinf( ca ); + if( RANGE > max_digital ){ + pts[i].x = pts[psize+i].x; + pts[i].y = pts[psize+i].y; + } else { + float cr = (rst * RANGE); + pts[i].x = x0 + cr * cosf( ca ); + pts[i].y = y0 + cr * sinf( ca ); + }; + } else { + ptt[rpt].x = pts[psize+i].x = pts[i].x = x0 + maxR * cosf( ca ); + ptt[rpt].y = pts[psize+i].y = pts[i].y = y0 + maxR * sinf( ca ); + rpt++; + }; + }; + ppt[0] = pts; + npp[0] = ( psize<<1 ); + + ppz[0] = ptt; + npz[0] = ( rpt - 1); + + LOG("C2DD -> draw finish"); + + cv::Mat ttMOMO = cv::imread( tpl, cv::IMREAD_UNCHANGED ); + LOG("C2DD -> read tpl2 finish"); + cv::fillPoly( ttMOMO, ppt, npp, 1, cv::Scalar( 0, 128, 255, 50 ), cv::LINE_8 ); + LOG("C2DD -> poly1 finish"); + //try { + // cv::fillPoly(ttMOMO, ppz, npz, 1, cv::Scalar(0, 0, 0, 100), cv::LINE_8); + // LOG("C2DD -> poly2 finish"); + //} catch ( cv::Exception& e ) { + // LOG("C2DD -> poly2 Error!"); + // LOG( e.what() ); + //}; + cv::addWeighted( tImage, 0.5, ttMOMO, 0.5, 0.0, tImage ); + LOG("C2DD -> add img finish"); + ttMOMO.release(); + LOG("C2DD -> img release finish"); + vector compression_params; + compression_params.push_back( cv::IMWRITE_PNG_COMPRESSION ); + compression_params.push_back(9); + + + vector buf; + cv::imencode( ".png", tImage, buf, compression_params ); + tImage.release(); + LOG("C2DD -> compress finish"); + *out_size = buf.size(); + RetVal = (uint8_t *) malloc( *out_size ); + if( RetVal ) { + memcpy( RetVal, buf.data(), *out_size ); + } else *out_size =0; + buf.clear(); + }; + }; + return RetVal; +}; + +bool deviceNodeSensor::handleDeviceDraw( uint8_t kID, void *th_data, size_t th_size, bool byMinimum ){ + if( th_data == NULL ) return false; + if( th_size == 0 ) return false; + if( m_pDBC == NULL ) return false; + m_pDBC->addDeviceDraw( getNodeID(), DRAW_MODE_RAW_DATA, kID, th_data, th_size ); + /* + //Clear Old Draw + CSTR old = m_pDBC->getLRFDraw( getNodeID() ); + if ( old ) { + // delete old draw + char filename[256]; + sprintf( filename, "data/device_draws/%s_100.png", old ); + if( fileExist( filename ) ){ + unlink( filename ); + }; + sprintf( filename, "data/device_draws/%s_50.png", old ); + if( fileExist( filename ) ){ + unlink( filename ); + }; + sprintf( filename, "data/device_draws/%s_25.png", old ); + if( fileExist( filename ) ){ + unlink( filename ); + }; + sprintf( filename, "data/device_draws/%s_12.png", old ); + if( fileExist( filename ) ){ + unlink( filename ); + }; + sprintf( filename, "data/device_draws/%s_map.png", old ); + if( fileExist( filename ) ){ + unlink( filename ); + }; + free( old ); + }; +*/ + CSTR uid = getUniqID_MD5(); + if( uid == NULL ) return false; + switch( getNodeType() ){ + case ARGUS_ALS_SENSOR: + case ARGUS_LFS_SENSOR: + case ARGUS_PLS_200_SENSOR: + case ARGUS_PLS_360_SENSOR: + case ARGUS_NET_PLS_200:{ + uint32_t tSize; + uint8_t *tBuff = create2dDraw( &tSize, (uint32_t *) th_data, th_size, 1024, m_sLRF_DATA.base_shift, "data/assets/images/lfs_draw_empty_100.png" ); + if ( tBuff ) { + m_pDBC->addDeviceDraw( getNodeID(), DRAW_MODE_2D_100, kID, tBuff, tSize ); + free( tBuff ); + }; + tBuff = create2dDraw( &tSize, (uint32_t *) th_data, th_size, 512, m_sLRF_DATA.base_shift, "data/assets/images/lfs_draw_empty_50.png" ); + if ( tBuff ) { + m_pDBC->addDeviceDraw( getNodeID(), DRAW_MODE_2D_50, kID, tBuff, tSize ); + free( tBuff ); + }; + tBuff = create2dDraw( &tSize, (uint32_t *) th_data, th_size, 256, m_sLRF_DATA.base_shift, "data/assets/images/lfs_draw_empty_25.png" ); + if ( tBuff ) { + m_pDBC->addDeviceDraw( getNodeID(), DRAW_MODE_2D_25, kID, tBuff, tSize ); + free( tBuff ); + }; + tBuff = create2dDraw( &tSize, (uint32_t *) th_data, th_size, 128, m_sLRF_DATA.base_shift, "data/assets/images/lfs_draw_empty_12.png" ); + if ( tBuff ) { + m_pDBC->addDeviceDraw( getNodeID(), DRAW_MODE_2D_12, kID, tBuff, tSize ); + free( tBuff ); + }; + tBuff = create2dDraw( &tSize, (uint32_t *) th_data, th_size, 1024, m_sLRF_DATA.base_shift, "data/assets/images/2d_MAP.png" ); + if ( tBuff ) { + m_pDBC->addDeviceDraw( getNodeID(), DRAW_MODE_MAP, kID, tBuff, tSize ); + free( tBuff ); + }; + break; + }; + case ARGUS_3D_SENSOR:{ + char * emptyBG = "data/assets/images/empty_3d.png"; + thresholdNode * ptr = (thresholdNode *) th_data; + + if ( fileExist( emptyBG ) ) { + cv::Mat tImage = cv::imread( emptyBG, cv::IMREAD_UNCHANGED ); + if( tImage.rows != 512 || tImage.cols != 1024 ){ + LOG_ERROR( "Background Image wrong size (should be 1024x512)!" ); + free( uid ); + return false; + }; + + uint8_t * tMemory = tImage.data; + thresholdNode * cNode = NULL; + uint8_t * cPixel = NULL; + int pix = 0; + int mem = 0; + bool s_bit = false; + bool no_data = false; + float tVal; + bool master = ( kID < 16 ); + + for( int idx = 0; idx < ( TH_SIZE_NODES << 2 ); idx++ ) { // tik-tak + if( ( idx % 4 ) == 0 ){ + mem++; + if ( master ) { + cNode = ptr + TH_SIZE_NODES - mem - 1; + } else { + cNode = ptr + mem - 1; + }; + if( !s_bit ) s_bit = cNode->values.sbit; + if( !no_data ) no_data = ( cNode->values.cnt == 0 ); + if( !s_bit && !no_data ){ + if( byMinimum ) { + tVal = ((float)cNode->values.min) / 4096.f; + } else { + tVal = ((float)cNode->values.max) / 4096.f; + }; + }; + }; + if( ( idx % 9 ) == 0 ){ + if( mem > ( SKIP_LINE_PIXELS * TH_LINE_NODES ) ) { + cPixel = tMemory + (pix << 2); + pix++; + if( s_bit ) { // Set Red + cPixel[0] = 0x00; cPixel[1] = 0x00; cPixel[2] = 0xff; cPixel[3] = 0xff; + } else { + if( no_data ) { // Set Blue + cPixel[0] = 0xff; cPixel[1] = 0x00; cPixel[2] = 0x00; cPixel[3] = 0xff; + } else { + uint32_t tColor; + tColor = interpolate( 0x000000ff, 0xffffffff, tVal ); + cPixel[0] = ( tColor >> 24 ) & 0xFF; + cPixel[1] = ( tColor >> 16 ) & 0xFF; + cPixel[2] = ( tColor >> 8 ) & 0xFF; + cPixel[3] = tColor & 0xFF; + }; + }; + s_bit = false; + no_data = false; + }; + }; + }; + + char filename[256]; + sprintf( filename, "data/device_draws/%s_100.png", uid ); + //int RetVal = stbi_write_png( filename, 1024, 512, cSpace, tMemory, 1024 * cSpace ); + vector compression_params; + compression_params.push_back( cv::IMWRITE_PNG_COMPRESSION ); + compression_params.push_back(9); + if(! cv::imwrite( filename, tImage, compression_params ) ){ + tImage.release(); + free( uid ); + return false; + }; + tImage.release(); +#ifdef DEBUG_EXTRA + LOG("Draw Saved!"); +#endif + cv::Mat tMap( Q_SCAN_COUNT, TH_LINE_NODES, CV_8UC4 ); +#ifdef DEBUG_EXTRA + LOG("Map Creating"); +#endif + tMemory = tMap.data; + for( int j = 0; j < Q_SCAN_COUNT; j++ ){ + for( int i = 0; i < TH_LINE_NODES; i++ ){ + //cNode = ptr+(j*i); + //cNode = &ptr[ ( TH_LINE_NODES * j ) + i ]; + int ids = 0; + int idd = 0; + if ( master ) { + //cNode = ptr+makeIds( i, j , true ); + //cPixel = tMemory+( cSpace * makeIds( i, j , false )); + ids = makeIds( i, j , true ); + idd = 4 * makeIds( i, j , false ); + //cNode = ptr + ( i * j ); + //cPixel = tMemory + ( cSpace * i * j ); + } else { + //cNode = ptr+makeIds( i, j , false ); + //cPixel = tMemory+( cSpace * makeIds( i, j , false )); + ids = makeIds( i, j , false ); + idd = 4 * makeIds( i, j , false ); + }; + + cNode = ptr + ids ; + cPixel = tMemory + idd; + + if( 0 ) { // Monochrome + #ifdef CHECK_SUN_BIT + if( cNode->values.sbit ) { + cPixel[0] = 0; + } else { + cPixel[0] = (uint8_t)((((float) cNode->values.min ) * 255.f ) / 4096.f ); + }; + #else + cPixel[0] = (uint8_t)((((float) cNode->values.min ) * 255.f ) / 4096.f ); + #endif + } else { + #ifdef CHECK_SUN_BIT + if( cNode->values.sbit ) { + // Set Red + cPixel[0] = 0x00; + cPixel[1] = 0x00; + cPixel[2] = 0xff; + cPixel[3] = 0xff; + } else { + if( cNode->values.cnt == 0 ) { + // Set Blue + cPixel[0] = 0xff; + cPixel[1] = 0x00; + cPixel[2] = 0x00; + cPixel[3] = 0xff; + } else { + uint32_t tColor; + float tVal = ((float) cNode->values.min ) / 4096.f; + tColor = interpolate( 0x000000ff, 0xffffffff, tVal ); + cPixel[0] = ( tColor >> 24 ) & 0xFF; + cPixel[1] = ( tColor >> 16 ) & 0xFF; + cPixel[2] = ( tColor >> 8 ) & 0xFF; + cPixel[3] = tColor & 0xFF; + }; + }; + #else + if( cNode->values.cnt == 0 ) { + // Set Blue + cPixel[0] = 0xff; + cPixel[1] = 0x00; + cPixel[2] = 0x00; + cPixel[3] = 0xff; + } else { + uint32_t tColor; + float tVal = ((float) cNode->values.min ) / 4096.f; + tColor = interpolate( 0x000000ff, 0xffffffff, tVal ); + cPixel[0] = ( tColor >> 24 ) & 0xFF; + cPixel[1] = ( tColor >> 16 ) & 0xFF; + cPixel[2] = ( tColor >> 8 ) & 0xFF; + cPixel[3] = tColor & 0xFF; + }; + #endif + }; + }; + }; + sprintf( filename, "data/device_draws/%s_map.png", uid ); + LOG(filename); + if(! cv::imwrite( filename, tMap, compression_params ) ){ + tMap.release(); + free( uid ); + return false; + }; + tMap.release(); + m_pDBC->addLRFDraw( getNodeID(), TH_SIZE_NODES, uid, kID, 1, true ); + } else { + LOG_ERROR( "Background Image is Not Found!" ); + free( uid ); + return false; + }; + break; + }; + }; + free( uid ); + return true; +}; + +/* +#define STB_IMAGE_IMPLEMENTATION + #include "../data/stbi/stb_image.h" + #define STB_IMAGE_WRITE_IMPLEMENTATION + #include "../data/stbi/stb_image_write.h" + #undef STB_IMAGE_WRITE_IMPLEMENTATION +#undef STB_IMAGE_IMPLEMENTATION + + + +bool argus3DLIDAR::saveTHPicture( thresholdNode *ptr, CSTR uid, bool master, bool byMinimum, bool monochrome ){ + uint8_t *tMemory = NULL; + thresholdNode *cNode = NULL; + uint8_t *cPixel = NULL; + int cSpace; + + + int x, y; + tMemory = stbi_load( "data/assets/images/empty_3d.png", &x, &y, &cSpace, STBI_default ); + + if( tMemory == NULL ){ + LOG_ERROR("Draw Memory Alloc Eror!"); + return false; + }; + + if( x != 1024 || y != 512 ){ + LOG("Wrong IMG Size!"); + free( tMemory ); + return NULL; + }; + + int pix = 0; + int mem = 0; + bool s_bit = false; + bool no_data = false; + float tVal; + + for ( int idx = 0; idx < ( TH_SIZE_NODES << 2 ); idx++ ) { // tik-tak + + if( ( idx % 4 ) == 0 ){ + mem++; + if ( master ) { + cNode = ptr + TH_SIZE_NODES - mem - 1; + } else { + cNode = ptr + mem - 1; + }; + if( !s_bit ) s_bit = cNode->values.sbit; + if( !no_data ) no_data = ( cNode->values.cnt == 0 ); + if( !s_bit && !no_data ){ + if( byMinimum ) { + tVal = ((float)cNode->values.min) / 4096.f; + } else { + tVal = ((float)cNode->values.max) / 4096.f; + }; + }; + }; + + if( ( idx % 9 ) == 0 ){ + if( mem > ( SKIP_LINE_PIXELS * TH_LINE_NODES ) ) { + cPixel = tMemory + (pix << 2); + pix++; + if( s_bit ) { // Set Red + cPixel[0] = 0x00; cPixel[1] = 0xff; cPixel[2] = 0x00; cPixel[3] = 0xff; + } else { + if( no_data ) { // Set Blue + cPixel[0] = 0x00; cPixel[1] = 0x00; cPixel[2] = 0xff; cPixel[3] = 0xff; + } else { + uint32_t tColor; + tColor = interpolate( 0x000000ff, 0xffffffff, tVal ); + cPixel[0] = ( tColor >> 24 ) & 0xFF; + cPixel[1] = ( tColor >> 16 ) & 0xFF; + cPixel[2] = ( tColor >> 8 ) & 0xFF; + cPixel[3] = tColor & 0xFF; + }; + }; + s_bit = false; + no_data = false; + } + }; + }; + + char filename[256]; + sprintf( filename, "data/device_draws/%s_100.png", uid ); + int RetVal = stbi_write_png( filename, 1024, 512, cSpace, tMemory, 1024 * cSpace ); + free( tMemory ); + if( RetVal == 0 ) return false; + + if( monochrome ) { + cSpace = 1; + } else { + cSpace = 4; + }; + + tMemory = (uint8_t *) malloc( TH_SIZE_NODES * cSpace ); + if( tMemory == NULL ){ + LOG_ERROR("Map Memory Alloc Eror!"); + return false; + }; + + for (int j = 0; j < Q_SCAN_COUNT; j++) { + for ( int i = 0; i < TH_LINE_NODES; i++ ) { + //cNode = ptr+(j*i); + //cNode = &ptr[ ( TH_LINE_NODES * j ) + i ]; + int ids = 0; + int idd = 0; + if ( master ) { + //cNode = ptr+makeIds( i, j , true ); + //cPixel = tMemory+( cSpace * makeIds( i, j , false )); + ids = makeIds( i, j , true ); + idd = cSpace * makeIds( i, j , false ); + //cNode = ptr + ( i * j ); + //cPixel = tMemory + ( cSpace * i * j ); + } else { + //cNode = ptr+makeIds( i, j , false ); + //cPixel = tMemory+( cSpace * makeIds( i, j , false )); + ids = makeIds( i, j , false ); + idd = cSpace * makeIds( i, j , false ); + }; + + cNode = ptr + ids ; + cPixel = tMemory + idd; + + if( monochrome ) { +#ifdef CHECK_SUN_BIT + if( cNode->values.sbit ) { + cPixel[0] = 0; + } else { + cPixel[0] = (uint8_t)((((float) cNode->values.min ) * 255.f ) / 4096.f ); + }; +#else + cPixel[0] = (uint8_t)((((float) cNode->values.min ) * 255.f ) / 4096.f ); +#endif + } else { +#ifdef CHECK_SUN_BIT + if( cNode->values.sbit ) { + // Set Red + cPixel[0] = 0x00; + cPixel[1] = 0xff; + cPixel[2] = 0x00; + cPixel[3] = 0xff; + } else { + if( cNode->values.cnt == 0 ) { + // Set Blue + cPixel[0] = 0x00; + cPixel[1] = 0x00; + cPixel[2] = 0xff; + cPixel[3] = 0xff; + } else { + uint32_t tColor; + float tVal = ((float) cNode->values.min ) / 4096.f; + tColor = interpolate( 0x000000ff, 0xffffffff, tVal ); + cPixel[0] = ( tColor >> 24 ) & 0xFF; + cPixel[1] = ( tColor >> 16 ) & 0xFF; + cPixel[2] = ( tColor >> 8 ) & 0xFF; + cPixel[3] = tColor & 0xFF; + }; + }; +#else + if( cNode->values.cnt == 0 ) { + // Set Blue + cPixel[0] = 0x00; + cPixel[1] = 0x00; + cPixel[2] = 0xff; + cPixel[3] = 0xff; + } else { + uint32_t tColor; + float tVal = ((float) cNode->values.min ) / 4096.f; + tColor = interpolate( 0x000000ff, 0xffffffff, tVal ); + cPixel[0] = ( tColor >> 24 ) & 0xFF; + cPixel[1] = ( tColor >> 16 ) & 0xFF; + cPixel[2] = ( tColor >> 8 ) & 0xFF; + cPixel[3] = tColor & 0xFF; + }; +#endif + }; + }; + }; + + sprintf( filename, "data/device_draws/%s_map.png", uid ); + RetVal = stbi_write_png( filename, TH_LINE_NODES, Q_SCAN_COUNT, cSpace, tMemory, TH_LINE_NODES * cSpace ); + free( tMemory ); + if( RetVal == 0 ) return false; + return true; +}; +*/ + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/common/deviceNodeSensor.h b/lib/App/common/deviceNodeSensor.h new file mode 100644 index 00000000..b16e823c --- /dev/null +++ b/lib/App/common/deviceNodeSensor.h @@ -0,0 +1,106 @@ +#ifndef __ARGUS_NODE_SENSOR_HEADER__ +#define __ARGUS_NODE_SENSOR_HEADER__ + +#include "deviceNode.h" +#include "../../components/base/basicEventHeap.h" +#include "../../components/base/basicPosition.h" +#include "../../components/object/objectSystemAnchor.h" +#include "kernelEventFilter.h" + +#define ARGUS_LRF_PCMD_FULL_RESET 1 +#define ARGUS_LRF_PCMD_RESET 2 +#define ARGUS_LRF_PCMD_DRAW 3 +#define ARGUS_LRF_PCMD_GET_PROFILE 3 + +#define ARGUS_LRF_ROI_ACTIVATION 42 +#define ARGUS_LRF_PUSH_FALSE_TARGET 45 + +#define ARGUS_LRF_PCMD_SET_MASK_1 60 +#define ARGUS_LRF_PCMD_SET_MASK_2 61 +#define ARGUS_LRF_PCMD_SET_MASK_3 62 +#define ARGUS_LRF_PCMD_SET_MASK_4 63 +#define ARGUS_LRF_PCMD_SET_MASK_5 64 + +#define ARGUS_LRF_PCMD_MASK_1_ON 65 +#define ARGUS_LRF_PCMD_MASK_2_ON 66 +#define ARGUS_LRF_PCMD_MASK_3_ON 67 +#define ARGUS_LRF_PCMD_MASK_4_ON 68 +#define ARGUS_LRF_PCMD_MASK_5_ON 69 + +#define ARGUS_LRF_PCMD_MASK_1_OFF 70 +#define ARGUS_LRF_PCMD_MASK_2_OFF 71 +#define ARGUS_LRF_PCMD_MASK_3_OFF 72 +#define ARGUS_LRF_PCMD_MASK_4_OFF 73 +#define ARGUS_LRF_PCMD_MASK_5_OFF 74 + +#define ARGUS_LRF_PCMD_CLEAN_MASK_1 75 +#define ARGUS_LRF_PCMD_CLEAN_MASK_2 76 +#define ARGUS_LRF_PCMD_CLEAN_MASK_3 77 +#define ARGUS_LRF_PCMD_CLEAN_MASK_4 78 +#define ARGUS_LRF_PCMD_CLEAN_MASK_5 79 + +#define ARGUS_LRF_PCMD_SET_DP_0 100 +#define ARGUS_LRF_PCMD_SET_DP_1 101 +#define ARGUS_LRF_PCMD_SET_DP_2 102 +#define ARGUS_LRF_PCMD_SET_DP_3 103 +#define ARGUS_LRF_PCMD_UPLOAD_FILE 120 + +#define ARGUS_SYM_CMD_0 200 +#define ARGUS_SYM_CMD_1 201 +#define ARGUS_SYM_CMD_2 202 +#define ARGUS_SYM_CMD_3 203 +#define ARGUS_SYM_CMD_4 204 +#define ARGUS_SYM_CMD_5 205 +#define ARGUS_SYM_CMD_6 206 +#define ARGUS_SYM_CMD_7 207 +#define ARGUS_SYM_CMD_8 208 +#define ARGUS_SYM_CMD_9 209 +#define ARGUS_SYM_CMD_10 210 + + + +#define ARGUS_LRF_PCMD_UPDATE_ALL 255 + + +#define DRAW_MODE_RAW_DATA 0 +#define DRAW_MODE_MAP 1 +#define DRAW_MODE_3D 2 +#define DRAW_MODE_2D_100 3 +#define DRAW_MODE_2D_50 4 +#define DRAW_MODE_2D_25 5 +#define DRAW_MODE_2D_12 6 + + +#define NODE_CMD_RESET_STUDY 230 +#define NODE_CMD_FULL_RESET 235 +#define NODE_CMD_UPLOAD_SHADOW 234 +#define NODE_CMD_UPLOAD_FILE 240 +#define NODE_CMD_GET_DEVICE_DRAW 100 +#define NODE_CMD_ROI_ACTIVE 65 +#define NODE_CMD_ALARM 66 +#define NODE_CMD_UPDATE_SHADOW 67 +#define NODE_CMD_UPLOAD_SETTINGS_0 80 +#define NODE_CMD_UPLOAD_SETTINGS_1 81 +#define NODE_CMD_UPLOAD_SETTINGS_2 82 +#define NODE_CMD_UPLOAD_SETTINGS_3 83 + +class deviceNodeSensor: public deviceNode{ + protected: + DBC_LRF_DATA m_sLRF_DATA; + basicPosition m_oPosition; + basicEventHeap * m_pEventHeap; + basicEventClassID m_eEventClass; + kernelEventFilter * m_pTargetFilter; + bool handleDeviceDraw( uint8_t kID, void *th_data, size_t th_size, bool byMinimum = true ); + uint8_t * create2dDraw( uint32_t *out_size, uint32_t *th_data, size_t th_size, uint16_t max_digital, int radial_shift, CSTR tpl, bool byMinimum = true ); + public: + explicit deviceNodeSensor( uint32_t id ); + explicit deviceNodeSensor( DBC_NODE_DATA *Data ); + virtual ~deviceNodeSensor(); + virtual void simulateTarget( void ){}; +}; + + + +#endif + diff --git a/lib/App/common/deviceNodeStaticCamControl.cpp b/lib/App/common/deviceNodeStaticCamControl.cpp new file mode 100644 index 00000000..9eb24397 --- /dev/null +++ b/lib/App/common/deviceNodeStaticCamControl.cpp @@ -0,0 +1,170 @@ +#include "deviceNodeStaticCamControl.h" + +#define LOG( X ) deviceNode::m_pLog->Log( "STATIC_CAM", this, X ) +#define LOG_ERROR( X ) deviceNode::m_pLog->Log( "STATIC_CAM", this, _LOG_ERROR, X ) + +deviceNodeStaticCamControl::deviceNodeStaticCamControl( DBC_NODE_DATA *Data ): deviceNodeCamera( Data ), basicEventHandler(){ + //m_pLog = basicLogCollection::getInstance(); +/* + DBC_CAM_DATA * tData = m_pDBC->getCamData( m_sNodeData.aux_id ); + + m_fMaxRange = m_fMinHFov = m_fMaxHFov = m_fMinVFov = m_fMaxVFov = .0f; + + if( tData != NULL ) { + memcpy( &m_sCamData, tData, sizeof(DBC_CAM_DATA) ); + free( tData ); + }; + memset( &m_sCtrlData, 0, sizeof(CAMERA_CTRL_DATA) ); + if( m_sCamData.max_range == .0f ){ + m_fMaxRange = calcMaxDistance_mm( AC_imager_diag[m_sCamData.imager_type], m_sCamData.max_f, 1280 ); + } else { + m_fMaxRange = m_sCamData.max_range; + }; + m_fMinHFov = calcFOV_mm( AC_imager_width[m_sCamData.imager_type], m_sCamData.min_f ); + m_fMaxHFov = calcFOV_mm( AC_imager_width[m_sCamData.imager_type], m_sCamData.max_f ); + m_fMinVFov = calcFOV_mm( AC_imager_height[m_sCamData.imager_type], m_sCamData.min_f ); + m_fMaxVFov = calcFOV_mm( AC_imager_height[m_sCamData.imager_type], m_sCamData.max_f ); +#ifdef DEBUG + char tB[128]; + LOG("Camera Info:"); + sprintf( tB, "Maximal Range: %0.2f m. ", m_fMaxRange); + LOG(tB); + sprintf( tB, "Maximal FOVs, Horizontal: %0.2f Vertical: %0.2f", m_fMinHFov, m_fMinVFov ); + LOG(tB); + sprintf( tB, "Minimal FOVs, Horizontal: %0.2f Vertical: %0.2f", m_fMaxHFov, m_fMaxVFov ); + LOG(tB); +#endif + m_pPosition = new basicPosition( m_sCamData.lat, m_sCamData.lon, m_sCamData.alt, m_sCamData.roll, m_sCamData.pitch, m_sCamData.yaw ); + */ +}; + +deviceNodeStaticCamControl::deviceNodeStaticCamControl( uint32_t id ): deviceNodeCamera( id ), basicEventHandler() { + m_sMediaSource.mediaSourceId = m_sNodeData.aux_id; + strncpy( m_sMediaSource.mediaName, m_sNodeData.name, 128 ); + m_sMediaSource.mediaName[127] = (char)0; + memset( &m_sCtrlData, 0, sizeof( CAMERA_CTRL_DATA )); +}; + +deviceNodeStaticCamControl::~deviceNodeStaticCamControl(){ + LOG("Destructor"); + stopService(); +}; + +bool deviceNodeStaticCamControl::startService(){ + return create(); +}; + +bool deviceNodeStaticCamControl::stopService(){ + return true; +}; + +void deviceNodeStaticCamControl::dispatchEvent( EVENT_CONTAINER *E ){ + if( E == NULL ) return; + //if( !m_bSourceConnected ) return; + //if( m_bBusy ) return; + switch( E->m_eClass ) { + case EVT_CLASS_SENSOR_CLD: + case EVT_CLASS_SENSOR_LGS: + case EVT_CLASS_SENSOR_LFS: + case EVT_CLASS_SENSOR_MND: + case EVT_CLASS_SENSOR_PLS_210: + case EVT_CLASS_SENSOR_PLS_360: + case EVT_CLASS_SENSOR_ALS: + case EVT_CLASS_SENSOR_3D: + case EVT_CLASS_SENSOR_ACC:{ + switch( E->m_eType ) { + case EVT_TARGET_1D: + case EVT_TARGET_2D_BLACK: + case EVT_TARGET_2D_WHITE: + case EVT_TARGET_3D_BLACK: + case EVT_TARGET_3D_WHITE:{ + TARGET_DATA *tDATA; + tDATA = (TARGET_DATA *)E->m_pEvtData; + if( tDATA ) { +#ifdef DEBUG_EXTRA + LOG( "CHECK CAMERA FOV" ); +#endif + if (testFOV(tDATA->system_target)) { +#ifdef DEBUG_EXTRA + LOG("TARGET IN CAMERA FOV"); +#endif + makeSnap(E->m_db_id); + }; + }; + break; + }; + }; + break; + }; + case EVT_CLASS_CAMERA_CTRL:{ + /* + if( E->m_nDestinationUID == m_sCamData.node_id ) { + switch( E->m_eType ) { + case EVT_CAMERA_DM:{ + CAMERA_CTRL_DATA *tDATA = (CAMERA_CTRL_DATA *)E->m_pEvtData; + if( tDATA != NULL ) { + if( tDATA->moveMask & 0x08 == 0x08 ){ + //Relative Move cmd + if( tDATA->moveMask & 0x07 == 0 ){ + relativeStop(); + } else { + relativeMove( tDATA->spdPAN, tDATA->spdTILT, tDATA->spdZOOM ); + }; + } else { + if( tDATA->moveMask & 0xF0 != 0x00 ) { + absoluteMove( tDATA->absPAN, tDATA->absTILT, tDATA->absZOOM ); + }; + }; + }; + break; + }; + }; + } + ;*/ + break; + }; + }; +}; + +bool deviceNodeStaticCamControl::validate(){ +#ifdef DEBUG_EXTRA + LOG("VALIDATE"); +#endif + if( CAM_WS_END == getWM() ) return false; + // Validate Camera Settings + /*{ + DBC_CAM_DATA *tDATA = argusNetNode::m_pDBC->getCamData( m_sNodeData.aux_id ); + if( tDATA ) { + if( memcmp( &m_sCamData, tDATA, sizeof(DBC_CAM_DATA)) != 0 ){ + free( tDATA ); + LOG("Cam Settings Changed!"); + return false; + }; + free( tDATA ); + } else{ + LOG("Cam Deleted!"); + return false; + }; + }*/ + // Validate Stream -> Moved to Video Encooder + /* + { + if( m_sNodeData.aux_parameter ) { + //LOG("VALIDATE Stream"); + if( !m_bSourceConnected ) { + if( connectToStream( m_sNodeData.aux_parameter ) ) { + argusNetNode::m_pDBC->setStreamValid( m_sNodeData.aux_parameter ); + } else { + argusNetNode::m_pDBC->setStreamValid( m_sNodeData.aux_parameter, false ); + }; + } else { + validateStream(); + }; + }; + } + */ + return deviceNodeCamera::validate(); +}; + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/common/deviceNodeStaticCamControl.h b/lib/App/common/deviceNodeStaticCamControl.h new file mode 100644 index 00000000..d00e400a --- /dev/null +++ b/lib/App/common/deviceNodeStaticCamControl.h @@ -0,0 +1,44 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2017. All Rights Reserved. +// Version 2.0 6/11/2019 +// Last modification: 6/11/2019 +// PROJECT: +// SUBSYSTEM: +// FILE: rgooseIPCamera.h +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// Header file of rgooseIPCamera.h +//---------------------------------------------------------------------------- +// +#ifndef __DEVICE_STATIC_CAMERA_CTRL_HEADER__ +#define __DEVICE_STATIC_CAMERA_CTRL_HEADER__ + +#include "deviceNodeCamera.h" +#include "../components/base/basicEventHandler.h" +#include "../components/base/basicEventHeap.h" + +//https://www.ebay.com/itm/Professional-Rolling-Makeup-Case-Bulb-Mirror-Cosmetic-Artist-Dressing-Train-Case/233264525474 + +//ffmpeg -i input.mp4 -af loudnorm=I=-23:LRA=7:tp=-2:print_format=json -f null - +//ffmpeg -i input.mp4 -af loudnorm=I=-23:LRA=7:tp=-2:measured_I=-30:measured_LRA=1.1:measured_tp=-11 04:measured_thresh=-40.21:offset=-0.47 -ar 48k -y output.mp4 + + + + + +class deviceNodeStaticCamControl: public deviceNodeCamera, public basicEventHandler { + protected: + CAMERA_CTRL_DATA m_sCtrlData; + public: + explicit deviceNodeStaticCamControl( uint32_t id ); + explicit deviceNodeStaticCamControl( DBC_NODE_DATA *Data ); + virtual ~deviceNodeStaticCamControl(); + virtual void dispatchEvent( EVENT_CONTAINER *Evt ); + virtual bool startService(); + virtual bool stopService(); + virtual bool validate(); +}; + +#endif diff --git a/lib/App/common/hardwareManager.cpp b/lib/App/common/hardwareManager.cpp new file mode 100644 index 00000000..9eb68693 --- /dev/null +++ b/lib/App/common/hardwareManager.cpp @@ -0,0 +1,1380 @@ + +#include "hardwareManager.h" + +#include +#include +#include +#include + +#ifdef USE_MYSQL + #include "MySQL_dataBinder.h" +#else + #include "SQLite_dataBinder.h" +#endif + +//#include "rgooseKernel.h" +//#include "rgooseDBConnector.h" +#include "hardwareResourceSerialProvider.h" +#include "hardwareResourceNetworkProvider.h" +#include "hardwareResourceVideoProvider.h" +#include "../hardware/hid/hid_dc.h" +#include "../alg/generic/heapDebug.h" + +#include +#include +#include +#include +#include +#include +#include +#include + + +#define LOG( X ) m_pLog->Log( "HWM", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "HWM", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "HWM", this, _LOG_ERROR, X ); +#endif + +hardwareManager *hardwareManager::_instance = NULL; + +/** + * Returns the single instance of the object. + */ +hardwareManager* hardwareManager::getInstance( bool cold_start ) { + // check if the instance has been created yet + if( 0 == _instance ){ + // if not, then create it + _instance = new hardwareManager( cold_start ); + }; + // return the single instance + return _instance; +}; + +hardwareManager::hardwareManager( bool cold_start ){ + m_pLog = basicLogCollection::getInstance(); + //m_bHardwareEnumerated = false; + m_nServerNodeID = 0; + m_nServerID = 0; + m_nSiteID = 0; + m_nMemoryLimitHeapSize = 724288000; //524288000; //500 MB ~ 1 Hour + memset( &m_sSYS_INFO, 0, sizeof(DBC_SYS_INFO) ); + strncpy( m_sSYS_INFO.SW_INFO, _BUILD_STRING_, 128 ); + + FILE *fd = popen("/bin/uname -s -r -v -m","r"); + if( fd!= NULL ) { + fgets( m_sSYS_INFO.OS_INFO, 127, fd); + m_sSYS_INFO.OS_INFO[127] = (char)0; + trim( m_sSYS_INFO.OS_INFO ); + memset( m_sSYS_INFO.HW_INFO, 0, 128 ); + fclose( fd ); + fd = NULL; + }; + + fd = fopen("/proc/cpuinfo","r"); + if ( fd!= NULL ) { + char tBB[1024]; + bool bARM = false; + while( !feof( fd ) ) { + fgets( tBB, 1024, fd ); + trim( tBB ); + if( strcasestr(tBB, "model") != NULL ) { + if( strcasestr(tBB, "model name") != NULL ) { + if ( !bARM ) { + if( strcasestr( tBB, "ARM" ) != NULL){ + bARM = true; + } else { + CArray *tA = explode(':', tBB ); + if ( tA ) { + strncpy( m_sSYS_INFO.HW_INFO, tA->at(1), 127 ); + delete tA; + }; + break; + }; + }; + } else { + CArray *tA = explode(':', tBB ); + if ( tA ) { + strncpy( m_sSYS_INFO.HW_INFO, tA->at(1), 127 ); + delete tA; + }; + break; + }; + }; + }; + m_sSYS_INFO.HW_INFO[127] = (char)0; + trim( m_sSYS_INFO.HW_INFO ); + fclose( fd ); + fd = NULL; + }; + +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + if( m_pDBC == NULL ) { + LOG_ERROR( "Failure to get DBC Instance -> Forced HW Enumeration!" ); + enumerateHardware(); + } else { + char tB[128]; + struct rlimit rl={0}; + getrlimit( RLIMIT_STACK, &rl ); + + sprintf( tB, "Stack Size: %d", rl.rlim_cur ); //RLIM_INFINITY + LOG( tB ); + sprintf( tB, "MAX Stack Size: %d", rl.rlim_max ); + LOG( tB ); + //enumerateHardware( !cold_start ); + enumerateNIFS(); +#ifdef DEBUG + LOG("Load Ressources..."); +#endif + loadResources(); +#ifdef DEBUG + LOG("Load Resources Done"); +#endif + }; +}; + +hardwareManager::~hardwareManager(){ +#ifdef DEBUG + LOG("Destructor Begin"); +#endif + unloadResources(); +#ifdef DEBUG + LOG("Destructor End"); +#endif + _instance = NULL; +}; + +void hardwareManager::unloadResources( void ){ +#ifdef DEBUG + LOG("Unload Resources ..."); +#endif + m_mVectorProtector.lock(); + if( m_vResources.size() ) { + for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) { + switch( (*idx)->getHardwareType() ) { + case HARDWARE_UART: + case HARDWARE_IP_UART: delete( ( hardwareResourceSerialProvider*)(*idx) ); break; + case HARDWARE_NIF_LOOPBACK: + case HARDWARE_NIF_ETHERNET: + case HARDWARE_NIF_WIFI: + case HARDWARE_NIF_VIRTUAL: + case HARDWARE_NIF_TUNEL: delete( ( hardwareResourceNetwork*)(*idx) ); break; + }; + }; + m_vResources.clear(); + }; + m_mVectorProtector.unlock(); +#ifdef DEBUG + LOG("Unload Resources Done"); +#endif +}; + +void hardwareManager::loadResources( void ){ + if( m_pDBC == NULL ) return; + DBC_INT_LIST *tVal; + //tVal = m_pDBC->listResources( );//load whole site resources + tVal = m_pDBC->listResources( m_nServerNodeID );//Load Only Server Node resources + if( tVal!= NULL ) { + if( tVal->size() ) { + for (DBC_INT_LIST::iterator index = tVal->begin(); index < tVal->end(); index++) { + DBC_RESOURCE_DATA *tData = m_pDBC->getResourceData( *index ); + if( tData != NULL ) { + hardwareResource *tPtr = NULL; + switch( tData->type ){ + case HARDWARE_UART:{ +#ifdef DEBUG + LOG("Construct HW UART"); +#endif + hardwareResourceSerialProvider *tRes = new hardwareResourceSerialProvider( tData->id ); + if( tRes != NULL ) { + if( tRes->create() ) { + tPtr = ( hardwareResource *) tRes; + } else { + LOG_ERROR("Error Creating HW UART!"); + delete( tRes ); + }; + }; + break; + }; + case HARDWARE_NIF_LOOPBACK: + case HARDWARE_NIF_ETHERNET: + case HARDWARE_NIF_WIFI: + case HARDWARE_NIF_VIRTUAL: + case HARDWARE_NIF_TUNEL:{ +#ifdef DEBUG + LOG("Construct NetIF"); +#endif + hardwareResourceNetwork *tRes = new hardwareResourceNetwork( tData->id ); + if( tRes != NULL ) { + if( tRes->create() ) { + tPtr = ( hardwareResource *) tRes; + } else { + LOG_ERROR("Error Creating Network Ressource!"); + delete( tRes ); + }; + }; + break; + }; + case HARDWARE_IP_UART:{ +#ifdef DEBUG + LOG("Construct IP UART"); +#endif + hardwareResourceSerialProvider *tRes = new hardwareResourceSerialProvider( tData->id ); + if( tRes != NULL ) { + if( tRes->create() ) { + tPtr = ( hardwareResource *) tRes; + } else { + LOG_ERROR("Error Creating IP UART!"); + delete( tRes ); + }; + }; + break; + }; + case HARDWARE_ANALOG_VIDEO_IN: + case HARDWARE_DIGITAL_VIDEO_IN:{ +#ifdef DEBUG + LOG("Construct VIDEO IN"); +#endif + hardwareResourceVideoProvider *tRes = new hardwareResourceVideoProvider( tData->id ); + if( tRes != NULL ) { + if( tRes->create() ) { + tPtr = ( hardwareResource *) tRes; + } else { + LOG_ERROR("Error Creating Video IN!"); + delete( tRes ); + }; + }; + break; + }; +#ifdef DEBUG + default:{ + char tB[128]; + sprintf( tB, "Unknown Ressource[%d] Type[%d]!", *index, tData->type ); + LOG_ERROR(tB); + break; + }; +#endif + }; + if( tPtr!= NULL ) { +#ifdef DEBUG + LOG("Resource Sucessfully Created!"); +#endif + m_mVectorProtector.lock(); + m_vResources.push_back( tPtr ); + m_mVectorProtector.unlock(); + }; + } else { + LOG_ERROR("Can not fetch Resource Data from Database!"); + }; + }; +#ifdef DEBUG + } else { + LOG("Fetched Empty List!"); +#endif + }; + tVal->clear(); + delete( tVal ); +#ifdef DEBUG + } else { + LOG("Fetched NULL!"); +#endif + }; +}; + +bool hardwareManager::validate( void ){ + bool RetVal = true; + m_mVectorProtector.lock(); + if( m_vResources.size() ) { + for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) { + if( !(*idx)->validate() ) { + // recreate Resource + LOG_ERROR( "HW Resource Invalid!" ); +#ifdef DEBUG + char tB[256]; + sprintf( tB, "Info: DBID[%d] R-Type: %d Provider: %d ", (*idx)->getDbId(), (*idx)->getHardwareType(), (*idx)->getProviderType() ); + LOG( tB ); +#endif + if( !(*idx)->create()){ + LOG_ERROR( "HW Resource Creation Failure!" ); +#ifdef DEBUG + } else { + LOG("Re-Created OK"); +#endif + }; +#ifdef DEBUG_EXTRA + } else { + LOG("Resource OK!"); +#endif + }; + }; +#ifdef DEBUG_EXTRA + } else { + LOG("No Resources!"); +#endif + }; + m_mVectorProtector.unlock(); + //Mem Validator + if( m_nMemoryLimitHeapSize ) { + size_t memStat = getCurrentRSS(); +#ifdef DEBUG_EXTRA + char MEM_MSG[128]; + sprintf( MEM_MSG, "MEM: %d TARG: %d", memStat, m_nMemoryLimitHeapSize ); + LOG( MEM_MSG ); +#endif +//https://www.ebay.com/itm/274974088159? + RetVal = ( memStat < m_nMemoryLimitHeapSize ); + if ( !RetVal ) { + LOG_ERROR("Memory Consumption too BIG!"); + }; + }; + return RetVal; +}; + +int xioctl(int fh, int request, void *arg){ + int r; + do { + r = ioctl( fh, request, arg ); + } while (-1 == r && EINTR == errno); + return r; +}; + +#define CLEAR(x) memset(&(x), 0, sizeof(x)) + + +void hardwareManager::getMAC( CSTR if_name, CSTR buf ){ + char tB[128]; + FILE * fd=NULL; + if ( buf ) { + sprintf(tB, "/sys/class/net/%s/address", if_name); +#ifdef DEBUG_EXTRA + LOG( tB ); +#endif + fd=fopen(tB,"r"); + if ( fd ) { + fread( buf, 1, INET6_ADDRSTRLEN, fd ); + fclose( fd ); + buf = trim( buf ); + } else { + memset( buf, 0, INET6_ADDRSTRLEN ); + }; +#ifdef DEBUG_EXTRA + LOG( buf ); +#endif + }; +}; + +void hardwareManager::getGW( CSTR if_name, CSTR buf ){ + FILE * fd = popen( "route -n", "r" ); + char tB[1024]; + //char expBuf[1024]; + + memset( buf, 0, INET6_ADDRSTRLEN ); + + if ( fd ) { + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + if( strstr( tB, if_name ) != NULL ){ + //strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ' ', tB ); + if ( CA ) { + //for (int i=0; i< CA->size(); i++ ) { + // char tB[128]; + // trim( CA->at(i) ); + // sprintf( tB, "GW# %d: %s", i, CA->at(i) ); + // LOG( tB ); + //}; + trim( CA->at(1) ); + if( strstr(CA->at(1), "0.0.0.0") == NULL ) { + strncpy( buf, CA->at(1), INET6_ADDRSTRLEN ); + }; + delete(CA); + }; + }; + }; + }; + fclose( fd ); + }; + if( strlen( buf ) == 0 ) strncpy( buf, "0.0.0.0", INET6_ADDRSTRLEN ); +}; + +void hardwareManager::getTTyDesc( CSTR dev_name, CSTR buf ){ + FILE * fd = popen( "dmesg | grep tty", "r" ); + char tB[1024]; + //char expBuf[1024]; + + memset( buf, 0, DBC_RESOURCE_DESC_SIZE ); + + if ( fd ) { + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + if( strstr( tB, dev_name ) != NULL ){ + //strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ':', tB ); + if ( CA ) { + //for (int i=0; i< CA->size(); i++ ) { + // char tB[128]; + // trim( CA->at(i) ); + // sprintf( tB, "GW# %d: %s", i, CA->at(i) ); + // LOG( tB ); + //}; + trim( CA->at(1) ); + strncpy( buf, CA->at(1), DBC_RESOURCE_DESC_SIZE ); + buf[DBC_RESOURCE_DESC_SIZE-1]=(char)0; + delete(CA); + }; + }; + }; + }; + fclose( fd ); + }; + if( strlen( buf ) == 0 ){ + strncpy( buf, "--Unknown--", DBC_RESOURCE_DESC_SIZE ); + buf[DBC_RESOURCE_DESC_SIZE-1]=(char)0; + }; +}; + +PARSE_RESULT_NET_INTERFACES *hardwareManager::parse_neconfig( CSTR if_name ){ + PARSE_RESULT_NET_INTERFACES *tVal = NULL; + FILE *fd; + bool cConfig = false; + fd = fopen("/etc/network/interfaces","r"); + if ( fd ) { + char tB[1024]; + char expBuf[1024]; + tVal = (PARSE_RESULT_NET_INTERFACES *) malloc( sizeof(PARSE_RESULT_NET_INTERFACES)); + if ( tVal ) { + memset(tVal, 0 , sizeof(PARSE_RESULT_NET_INTERFACES)); + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ' ', expBuf ); + if( CA ) { + for( CArray::iterator idx = CA->begin(); idx < CA->end(); idx++ ) { + if((*idx)[0]=='#') break; + if(strstr((*idx), "auto")!= NULL ) if( strstr( tB, if_name )!= NULL ) tVal->enabled = true; + if(strstr((*idx), "allow-hotplug")!= NULL ) if( strstr( tB, if_name )!= NULL ) tVal->hot_plug = true; + if(strstr((*idx), "iface")!= NULL ) if( strstr( tB, if_name )!= NULL ){ + if (strstr( tB, "static") != NULL) tVal->if_static = true; + cConfig = true; + } else cConfig = false; + if(strstr((*idx), "address")!= NULL ) if( cConfig ){ + idx++; + if(strstr((*idx),"/")!= NULL ){ + int8_t sh = strstr((*idx),"/") - (*idx); + strncpy( tVal->address, (*idx), sh ); + tVal->address[sh]=(char)0; + int8_t bm = atoi( (*idx) + sh + 1 ); + union{ + uint32_t mm; + uint8_t nm[4]; + } nmu = {0}; + for ( sh = 0; sh < bm; sh++ ) nmu.mm |= (1 << sh); + sprintf(tVal->netmask, "%d.%d.%d.%d", nmu.nm[0], nmu.nm[1], nmu.nm[2], nmu.nm[3]); + } else { + strncpy( tVal->address, (*idx), INET6_ADDRSTRLEN ); + }; + }; + if(strstr((*idx), "netmask")!= NULL ) if( cConfig ){ + LOG("netMSK"); + idx++; + LOG(*idx); + strncpy(tVal->netmask, (*idx), INET6_ADDRSTRLEN); + }; + //if(strstr((*idx), "bridge_ports")!= NULL ) cMode = 6; + //if(strstr((*idx), "bridge_stp")!= NULL ) cMode = 7; + //if(strstr((*idx), "bridge_waitport")!= NULL ) cMode = 8; + //if(strstr((*idx), "bridge_fd")!= NULL ) cMode = 9; + }; + delete( CA ); + }; + }; + }; + }; + fclose( fd ); + }; +#ifdef DEBUG_EXTRA + if ( tVal ) { + if( tVal->enabled ) LOG("NIF Enabled"); else LOG("NIF Disabled"); + if (tVal->hot_plug) LOG("NIF Hot Plugable"); else LOG("NIF not Hot Plugable"); + if (tVal->if_static) LOG("Address is static"); else LOG("Address is Dynamic"); + if(strlen(tVal->address))LOG(tVal->address); + if(strlen(tVal->netmask))LOG(tVal->netmask); + }; +#endif + return tVal; +}; + +PARSE_RESULT_WIFI_SETTINGS *hardwareManager::parse_wifi( CSTR if_name ){ + PARSE_RESULT_WIFI_SETTINGS * tVal = NULL; + FILE * fd; + bool cConfig = false; + bool is_wifi = false; + + tVal = (PARSE_RESULT_WIFI_SETTINGS *) malloc( sizeof(PARSE_RESULT_WIFI_SETTINGS)); + if ( tVal ) { + memset(tVal, 0 , sizeof(PARSE_RESULT_WIFI_SETTINGS)); + fd = fopen("/etc/dnsmasq.conf","r"); + if ( fd ) { + char tB[1024]; + char expBuf[1024]; + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( '=', expBuf ); + if( CA ) { + if( CA->size() ){ + if( CA->at(0)[0] == '#' ) continue; + if( strstr(CA->at(0), "interface")!= NULL ) { + if( strstr( tB, if_name)!= NULL ) { + cConfig = true; + tVal->dhcp_enabled = true; + }; + }; + if( cConfig ){ + if ( strstr(CA->at(0), "dhcp-range")!= NULL ) { + char tT[1024]; + strncpy( tT, CA->at(1), 1024 ); + CArray *CB = explode(',', tT ); + if( CB ){ + if( CB->size() > 3 ){ + strncpy( tVal->range_start, CB->at(0), INET6_ADDRSTRLEN); + strncpy( tVal->range_stop, CB->at(1), INET6_ADDRSTRLEN); + strncpy( tVal->netmask, CB->at(2), INET6_ADDRSTRLEN); + strncpy( tVal->lease_period, CB->at(3), INET6_ADDRSTRLEN); + }; + delete( CB ); + }; + }; + }; + }; + delete( CA ); + }; + }; + }; + fclose( fd ); + }; + //Check WiFi + if( strstr(if_name,"w")!= NULL ) { + char tName[128]; + is_wifi = true; + sprintf( tName, "iwconfig %s", if_name ); + fd = popen( tName, "r" ); + if ( fd ) { + char tB[1024]; + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd ); + trim( tB ); + if (strstr(tB, "Mode") != NULL) if (strstr(tB, "Master") != NULL) tVal->access_point = true; + }; + fclose( fd ); + }; + }; + if ( tVal->access_point ) { + fd = fopen("/etc/hostapd/hostapd.conf", "r"); + if ( fd ) { + char tB[1024]; + char expBuf[1024]; + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim( tB ); + if( strlen(tB) ) { + if( tB[0]=='#' ) continue; + strncpy(expBuf, tB, 1024); + CArray *CA = explode( '=', expBuf ); + if( CA ) { + if( CA->size() ){ + if (strstr(CA->at(0), "ssid") != NULL) if (strstr(CA->at(0), "ignore_broadcast_ssid") == NULL){ + strncpy( tVal->SSID, CA->at(1), 64 ); + } else tVal->hiden_ssid = (bool) atoi(CA->at(1)); + if (strstr(CA->at(0), "wpa_passphrase") != NULL) strncpy( tVal->password, CA->at(1), 64 ); + if (strstr(CA->at(0), "country_code") != NULL) strncpy(tVal->country_code, CA->at(1), 3); + if (strstr(CA->at(0), "channel") != NULL) tVal->channel = atoi(CA->at(1)); + }; + delete( CA ); + }; + }; + }; + fclose( fd ); + }; + } else { + fd = fopen("/etc/wpa_supplicant/wpa_supplicant.conf", "r"); + if ( fd ) { + + fclose( fd ); + }; + }; + fd = fopen("/etc/rc.local","r"); + if ( fd ) { + char tB[1024]; + char expBuf[1024]; + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ' ', expBuf ); + if( CA ) { + if ( CA->size() ) { + if (CA->at(0)[0] == '#') continue; + if( strstr(CA->at(0), "iptables-restore")!= NULL ) { + char zB[1024]; + FILE *afd = fopen( CA->at(2), "r" ); + if ( afd ) { + while( !feof( afd ) ){ + fgets((CSTR)zB, 1024, afd ); + if( strstr( zB, "POSTROUTING" )!= NULL ) if( strstr( zB, "MASQUERADE" )!= NULL ) if( strstr( zB, if_name )== NULL ){ + CArray *CB = explode( ' ', zB ); + if ( CB ) { + if ( CB->size() > 3 ) { + strncpy(tVal->router_outbond, CB->at(3), INET6_ADDRSTRLEN); + }; + delete( CB ); + }; + tVal->router_enabled = true; + }; + }; + fclose(afd); + } else LOG("Error Opening Firewall Rules!"); + }; + }; + delete( CA ); + }; + }; + }; + fclose(fd); + } else LOG_ERROR("Can not open rc.local!"); +#ifdef DEBUG_EXTRA + char zz[128]; + if ( is_wifi ) { + if (tVal->access_point){ + LOG("WiFi is in AP Mode"); + sprintf( zz, "\tSSID:%s PWD:%s", tVal->SSID, tVal->password ); + LOG( zz ); + if (tVal->hiden_ssid) LOG("SSID is hidden"); + } else LOG("WiFi is in Client Mode"); + }; + if (tVal->dhcp_enabled){ + LOG("DHCP Service - Enabled"); + sprintf( zz, "\tRange: %s - %s Lease Time: %s", tVal->range_start, tVal->range_stop, tVal->lease_period ); + LOG( zz ); + } else { + LOG("DHCP Service - Disabled"); + }; + if (tVal->router_enabled){ + sprintf( zz, "Routing enabled to [%s] NIF", tVal->router_outbond ); + LOG( zz ); + } else { + LOG("Routing Disabled"); + }; +#endif + }; + return tVal; +}; + +void hardwareManager::enumerateNIFS( void ){ + struct ifaddrs * ifaddr = NULL; + char tBuffer[128]; + + //if( m_pKernel == NULL ) return; + if( m_pDBC == NULL ) return; + + if( -1 == getifaddrs(&ifaddr)) { + LOG_ERROR("No NET INTERFACES?!"); + } else { +#ifdef DEBUG + LOG("Enumerating Network Interfaces"); +#endif + struct ifaddrs * ifa; + + for( ifa = ifaddr; ifa; ifa = ifa->ifa_next ){ + char addr[INET6_ADDRSTRLEN]; + char mask[INET6_ADDRSTRLEN]; + char gw[INET6_ADDRSTRLEN]; + char bc[INET6_ADDRSTRLEN]; + char mac[INET6_ADDRSTRLEN]; + char device[INET6_ADDRSTRLEN]; + + uint32_t nif_id = 0; + uint32_t nif_aux_id = 0; + uint32_t router_id = 0; + NIF_TYPE nif_type = NIF_LOOPBACK; + NETWORK_TYPE net_type = NETWORK_IPV4; + RESOURCE_TYPE res_type = HARDWARE_NIF_LOOPBACK; + NIF_MODE nif_mode = ADDRESS_DISABLED; + +#ifdef DEBUG_EXTRA + LOG("*** Network Interface ***"); +#endif + strncpy( device, ifa->ifa_name, INET6_ADDRSTRLEN ); + strncpy( mac,"--no-mac--", INET6_ADDRSTRLEN ); +#ifdef DEBUG_EXTRA + LOG(device); +#endif + // Filter Loopback if + if( strstr( device, "lo" ) != NULL ){ + nif_type = NIF_LOOPBACK; + res_type = HARDWARE_NIF_LOOPBACK; + //Not Implemented +#ifdef DEBUG_EXTRA + LOG("Loopback Device -> SKIP"); +#endif + continue; + }; + // Filter vpn TUN if + if( strstr( device, "tun" ) != NULL ){ + nif_type = NIF_VPN_TUNEL; + res_type = HARDWARE_NIF_TUNEL; + //Not Implemented Yet +#ifdef DEBUG_EXTRA + LOG("Tunel Device -> SKIP"); +#endif + continue; + }; + if( strstr( device, "eth" ) != NULL ){ + nif_type = NIF_ETHERNET; + res_type = HARDWARE_NIF_ETHERNET; + }; + if( strstr( device, "wlan" ) != NULL ){ + nif_type = NIF_WIFI; + res_type = HARDWARE_NIF_WIFI; + }; + if( strstr( device, "wwan" ) != NULL ){ + nif_type = NIF_WAN; + res_type = HARDWARE_NIF_WAN; + }; + if( ifa->ifa_addr != NULL ){ + if (ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6) { +#ifdef DEBUG_EXTRA + LOG("No INET ADDRESSES -> SKIP"); +#endif + continue; + } + } else { +#ifdef DEBUG_EXTRA + LOG("ifa->ifa_addr is NULL -> SKIP"); +#endif + continue; + }; +#ifdef DEBUG_EXTRA + LOG("Getting Info...."); +#endif + getMAC( device, mac ); + getGW( device, gw ); +#ifdef DEBUG_EXTRA + LOG( mac ); + LOG( gw ); +#endif + PARSE_RESULT_NET_INTERFACES * tt = NULL; + PARSE_RESULT_WIFI_SETTINGS * tw = NULL; +#ifdef DEBUG_EXTRA + LOG("Parse NetConfig Info...."); +#endif + tt = parse_neconfig( device ); + if( tt ) { + if ( tt->enabled ) { + if( tt->if_static ){ + nif_mode = ADDRESS_STATIC; + } else { + nif_mode = ADDRESS_DYNAMIC; + }; + } else { + nif_mode = ADDRESS_DISABLED; + }; + } else { + LOG_ERROR("Error Parsing System NIF Settings!"); + continue; + }; +#ifdef DEBUG_EXTRA + LOG("Parse Routing/DHCP/AP Info...."); +#endif + tw = parse_wifi( device ); + if ( tw ){ +#ifdef DEBUG_EXTRA + LOG("Routing/AP Info OK!"); +#endif + if( nif_mode == ADDRESS_STATIC ) { + if( tw->dhcp_enabled ){ +#ifdef DEBUG_EXTRA + LOG("Address is Router"); +#endif + nif_mode = ADDRESS_STATIC_RAP; + }; + }; + nif_id = m_pDBC->addLocalNIF( device, mac, nif_type, nif_mode ); +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "NIF(%s) added as [%d]", device, nif_id ); + LOG( tBuffer ); +#endif + if ( nif_type == NIF_WIFI ){ + if( nif_id == 0 ){ + LOG_ERROR("Error Adding NIF in DB!"); + continue; + }; + WIFI_MODE w_mode; + if( !tt->enabled ) { + w_mode = WIFI_DISABLED; + } else { + if( tt->if_static ){ + if( tw->access_point ) { + w_mode = WIFI_IS_AP; + uint32_t outbond_id = 0; + if( tw->router_enabled ){ + outbond_id = m_pDBC->getNIF_IDbyDevice( tw->router_outbond ); + }; + if( tw->dhcp_enabled ) { +#ifdef DEBUG_EXTRA + LOG("ADD Router With DHCP"); +#endif + router_id = m_pDBC->addLocalNetworkInfrastructure(nif_id, outbond_id, true, tw->range_start, tw->range_stop, tw->netmask, tw->lease_period ); + } else { +#ifdef DEBUG_EXTRA + LOG("ADD Router ONLY"); +#endif + router_id = m_pDBC->addLocalNetworkInfrastructure( nif_id, outbond_id ); + }; +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "Router added as [%d]", router_id ); + LOG( tBuffer ); +#endif + } else { + w_mode = WIFI_CONNECTED_TO_AP; + }; + }; + }; +#ifdef DEBUG_EXTRA + LOG("ADD WiFi Record"); +#endif + nif_aux_id = m_pDBC->addLocalWiFi( nif_id, w_mode, tw->SSID, tw->password, ENCRIPTION_WPA_PSK, router_id ); + }; + if( nif_type == NIF_ETHERNET || nif_type == NIF_ETHERNET_VIRTUAL ){ + if( tt->if_static ){ + uint32_t outbond_id = 0; + nif_mode = ADDRESS_STATIC; + + if( tw->router_enabled ){ + nif_mode = ADDRESS_STATIC_RAP; + outbond_id = m_pDBC->getNIF_IDbyDevice( tw->router_outbond ); + }; + if( tw->dhcp_enabled ) { +#ifdef DEBUG_EXTRA + LOG("ADD Router With DHCP"); +#endif + router_id = m_pDBC->addLocalNetworkInfrastructure( nif_id, outbond_id, true, tw->range_start, tw->range_stop, tw->netmask, tw->lease_period ); + } else { +#ifdef DEBUG_EXTRA + LOG("ADD Router ONLY"); +#endif + router_id = m_pDBC->addLocalNetworkInfrastructure( nif_id, outbond_id ); + }; +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "Router added as [%d]", router_id ); + LOG( tBuffer ); +#endif + } else { + nif_mode = ADDRESS_DYNAMIC; + }; + }; + free(tt); + free(tw); + } else { + LOG_ERROR("Error Parsing System Router/AP Settings!"); + free(tt); + continue; + }; + + if( nif_aux_id != 0 ) { + nif_id = m_pDBC->addLocalNIF(device, mac, nif_type, nif_mode, nif_aux_id ); +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "2 NIF(%s) Updated as [%d]", device, nif_id ); + LOG( tBuffer ); +#endif + if( nif_id == 0 ) { + LOG_ERROR("Error Adding NIF in DB!"); + continue; + }; +#ifdef DEBUG_EXTRA + LOG("NIF added!"); + } else { + LOG("NIF Already added (regular Mode)!"); +#endif + }; + + + m_pDBC->addResource( /*m_nServerNodeID,*/ res_type, device, nif_id ); + if( ifa->ifa_addr->sa_family == AF_INET ){ + net_type = NETWORK_IPV4; + // create IPv4 string + struct sockaddr_in *in = (struct sockaddr_in*) ifa->ifa_addr; + inet_ntop(AF_INET, &in->sin_addr, addr, sizeof(addr)); + sprintf( mask, "%d.%d.%d.%d", + (uint8_t)ifa->ifa_netmask->sa_data[2], + (uint8_t)ifa->ifa_netmask->sa_data[3], + (uint8_t)ifa->ifa_netmask->sa_data[4], + (uint8_t)ifa->ifa_netmask->sa_data[5] + ); + sprintf( bc, "%d.%d.%d.%d", + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[4], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5] + ); + } else { // AF_INET6 + net_type = NETWORK_IPV6; + // create IPv6 string + struct sockaddr_in6 *in6 = (struct sockaddr_in6*) ifa->ifa_addr; + inet_ntop(AF_INET6, &in6->sin6_addr, addr, sizeof(addr)); + sprintf( mask, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", + (uint8_t)ifa->ifa_netmask->sa_data[2], + (uint8_t)ifa->ifa_netmask->sa_data[3], + (uint8_t)ifa->ifa_netmask->sa_data[4], + (uint8_t)ifa->ifa_netmask->sa_data[5], + (uint8_t)ifa->ifa_netmask->sa_data[6], + (uint8_t)ifa->ifa_netmask->sa_data[7], + (uint8_t)ifa->ifa_netmask->sa_data[8], + (uint8_t)ifa->ifa_netmask->sa_data[9], + (uint8_t)ifa->ifa_netmask->sa_data[10], + (uint8_t)ifa->ifa_netmask->sa_data[11], + (uint8_t)ifa->ifa_netmask->sa_data[12], + (uint8_t)ifa->ifa_netmask->sa_data[13], + (uint8_t)ifa->ifa_netmask->sa_data[14], + (uint8_t)ifa->ifa_netmask->sa_data[15], + (uint8_t)ifa->ifa_netmask->sa_data[16], + (uint8_t)ifa->ifa_netmask->sa_data[17] + ); + if( ifa->ifa_ifu.ifu_broadaddr != NULL ){ + sprintf( bc, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[4], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[6], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[7], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[8], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[9], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[10], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[11], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[12], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[13], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[14], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[15], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[16], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[17] + ); + } else { + sprintf( bc, "" ); + }; + }; + m_pDBC->addLocalNetwork( nif_id, net_type, addr, mask, gw, bc ); +#ifdef DEBUG + sprintf( tBuffer, "Detected Network Interface: %s [%s]", ifa->ifa_name, addr ); + LOG(tBuffer); +#endif + nif_id = 0; + nif_aux_id = 0; + router_id = 0; + nif_type = NIF_LOOPBACK; + net_type = NETWORK_IPV4; + res_type = HARDWARE_NIF_LOOPBACK; + nif_mode = ADDRESS_DISABLED; + }; + freeifaddrs( ifaddr ); + }; +}; + +void hardwareManager::enumerateHardware( void ){ + char tBuffer[CTEXT]; + DIR * dFD = NULL; + struct dirent * pDR = NULL; + + //ToDo: Check Ability to work without Kernel and DBC + //if( m_pKernel == NULL ) return; + if( m_pDBC == NULL ) return; +#ifdef DEBUG + LOG("HW Enumeration Started!"); +#endif + // Moved to a constructor!! + //m_nServerNodeID = m_pKernel->getServerNodeId(); + //m_nServerID = m_pKernel->getServerId(); + //m_nSiteID = m_pKernel->getSiteId(); + /* Add Network Interfaces */ + + m_pDBC->cleanResources( true ); + + enumerateNIFS(); + /* Check HID Devices */ + + struct hid_device_info * pDevs; + uint8_t DCBCount; + //Enumerate USB devices with the given IDs + pDevs = hid_enumerate( 0x16c0, 0x05df ); + if( pDevs!=NULL ){ + struct hid_device_info * pCDev = pDevs; + //Count the number of returned devices + for( DCBCount = 0; pCDev!=NULL; DCBCount++ ) pCDev = pCDev->next; + //Allocate a buffer for the relays + if( DCBCount > 0 ){ + DC_BOARD tDCB; + //Fill the relay structs + pCDev = pDevs; + for( int idx = 0; idx < DCBCount; idx++ ){ + //Save the path to this device + memset( tDCB.path, 0, MAX_PATH_LEN ); + strncpy( tDCB.path, pCDev->path, MAX_PATH_LEN ); + // The product string is USBRelayx where x is number of relays read to the \0 in case there are more than 9 + tDCB.relay_count = atoi((const char *)&pCDev->product_string[8]); + //Open it to get more details + hid_device * handle; + handle = hid_open_path( tDCB.path ); + if( handle ){ + unsigned char buf[9]; + //Get the features of the device + buf[0] = 0x01; + if( hid_get_feature_report( handle, buf, sizeof(buf)) == -1 ){ + LOG_ERROR("hid_get_feature_report"); + pCDev = pCDev->next; + hid_close( handle ); + continue; + }; + //Set the serial number (0x0 for termination) + memset( tDCB.serial, 0x0, (HID_DCR_SERIIAL_LENGTH+1) ); + memcpy( tDCB.serial, buf, HID_DCR_SERIIAL_LENGTH ); + //Byte 7 in the response contains the target_state of the relays + tDCB.state = buf[7]; + hid_close( handle ); +#ifdef DEBUG + //Output the device enumeration details if verbose is on + LOG("HID DCB Found"); + sprintf(tBuffer, " Type: %04hx::%04hx", pCDev->vendor_id, pCDev->product_id); + LOG(tBuffer); + sprintf(tBuffer, " Path: %s", pCDev->path ); + LOG(tBuffer); + sprintf(tBuffer, " Serial_number: %ls", pCDev->serial_number ); + LOG(tBuffer); + sprintf(tBuffer, " Manufacturer: %ls", pCDev->manufacturer_string); + LOG(tBuffer); + sprintf(tBuffer, " Product: %ls", pCDev->product_string); + LOG(tBuffer); + sprintf(tBuffer, " Release: %hx", pCDev->release_number); + LOG(tBuffer); + sprintf(tBuffer, " Interface: %d", pCDev->interface_number); + LOG(tBuffer); + sprintf(tBuffer, " Number of Relays = %d", tDCB.relay_count); + LOG(tBuffer); + //If debug are on, output individual relay details + for( int k = 0; k < tDCB.relay_count; k++ ){ + if( tDCB.state & 1 << k ){ + sprintf(tBuffer, " %s_%d=1", tDCB.serial, k + 1); + } else { + sprintf(tBuffer, " %s_%d=0", tDCB.serial, k + 1); + }; + LOG(tBuffer); + }; +#endif + m_pDBC->addLocalDCB( m_nSiteID, pCDev->path, tDCB.serial, tDCB.relay_count, tDCB.state ); + } else { + LOG_ERROR("unable to open HID device"); + }; + pCDev = pCDev->next; + }; + }; + hid_free_enumeration( pDevs ); + }; + + /* Add devices from DEV */ + dFD = opendir("/dev"); + if( dFD != NULL ) { + while( ( pDR = readdir( dFD ))!= NULL ){ + if( strcasestr( pDR->d_name, "video" ) == pDR->d_name ) { + createResourceVIDEO( pDR->d_name ); + continue; + }; + if( strcasestr( pDR->d_name, "ttyS" ) == pDR->d_name ){ + createResourceUART( pDR->d_name ); + continue; + }; + // RaspberyPI Hardware + if( strcasestr( pDR->d_name, "ttyAMA" ) == pDR->d_name ){ + createResourceUART( pDR->d_name ); + continue; + }; + if( strcasestr( pDR->d_name, "ttyUSB" ) == pDR->d_name ){ + createResourceUART( pDR->d_name ); + continue; + }; + }; + closedir( dFD ); + }; + //m_bHardwareEnumerated = true; + m_pDBC->updateSystemInfo( &m_sSYS_INFO ); +}; + +uint32_t hardwareManager::createResourceUART( CSTR devName ){ + uint32_t RetVal = 0; + char tBuffer[256]; + /* Enumerate BuiltIn Serial */ +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "Serial Device: %s", devName ); + LOG( tBuffer ); +#endif + char dev_name[CTEXT]; + int fd = -1; + struct serial_struct ss; + sprintf( dev_name, "/dev/%s", devName ); + fd = open( dev_name, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK ); + if (-1 == fd) { + sprintf( tBuffer, "Cannot open '%s': %d, %s\\n", dev_name, errno, strerror(errno)); + LOG_ERROR( tBuffer ); + } else { + + if ( 0 && ( -1 == xioctl(fd, TIOCGSERIAL, &ss) )){ + LOG_ERROR("TIOCGSERIAL"); + } else { +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "Serial Port[Port:0x%X IRQ:%d BB:%d Line:%d Type:%d Flags:%X]", + ss.port, + ss.irq, + ss.baud_base, + ss.line, + ss.type, + ss.flags + ); + LOG( tBuffer ); +#endif + getTTyDesc( devName, tBuffer ); + uint32_t tID = m_pDBC->addLocalUART( /*m_nServerNodeID,*/ 1, 19200, 8, 'N', 1.0f, dev_name ); + if ( tID ) { + m_pDBC->addResource( /*m_nServerNodeID,*/ HARDWARE_UART, tBuffer, tID ); + }; + }; + close(fd); + }; + return RetVal; +}; + +uint32_t hardwareManager::createResourceVIDEO( CSTR devName ){ + uint32_t RetVal = 0; + char tBuffer[256]; + /* Enumerate Video Capture */ +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "Video Source: %s", devName ); + LOG( tBuffer ); +#endif + struct v4l2_capability cap; + //struct v4l2_cropcap cropcap; + //struct v4l2_crop crop; + struct v4l2_format fmt; + char dev_name[CTEXT]; + int fd = -1; + struct stat st; + + sprintf( dev_name, "/dev/%s", devName ); + + if (-1 == stat( dev_name, &st )) { + sprintf( tBuffer, "Cannot identify '%s': %d, %s\\n", dev_name, errno, strerror(errno)); + LOG_ERROR( tBuffer ); + return 0; + }; + if (!S_ISCHR(st.st_mode)) { + sprintf( tBuffer, "%s is no devicen", dev_name); + LOG_ERROR( tBuffer ); + return 0; + }; + fd = open(dev_name, O_RDWR /* required */ | O_NONBLOCK, 0); + if (-1 == fd) { + sprintf( tBuffer, "Cannot open '%s': %d, %s\\n", dev_name, errno, strerror(errno)); + LOG_ERROR( tBuffer ); + } else { + if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) { + if (EINVAL == errno) { + sprintf( tBuffer, "%s is no V4L2 device", dev_name ); + LOG_ERROR( tBuffer ); + } else { + LOG_ERROR( "VIDIOC_QUERYCAP" ); + }; + close(fd); + return 0; + }; + if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) { +#ifdef DEBUG_EXTRA + sprintf(tBuffer, "%s is no video capture device", dev_name); + LOG_ERROR( tBuffer ); +#endif + close(fd); + return 0; + }; + CLEAR(fmt); + fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + /* Preserve original settings as set by v4l2-ctl for example */ + if (-1 == xioctl(fd, VIDIOC_G_FMT, &fmt)){ + //LOG_ERROR("VIDIOC_G_FMT"); + } else { +#ifdef DEBUG + sprintf( tBuffer, "Grabber{%s}{%s}[%dx%d]", cap.card, cap.driver, fmt.fmt.pix.width,fmt.fmt.pix.height); + LOG( tBuffer ); +#endif + uint32_t mid = m_pDBC->addLocalCam( (CSTR)cap.card, (CSTR)cap.driver, dev_name, fmt.fmt.pix.width, fmt.fmt.pix.height ); + //uint64_t mid = m_pDBC->addLocalMediaSource( m_nSiteID, dev_name, fmt.fmt.pix.width, fmt.fmt.pix.height ); + //m_pDBC->addNodeSocket( m_nServerNodeID, mid, NODE_SOCK_TYPE_ANALOG_VIDEO_GRABBER, NODE_SOCK_MODE_OUT, false, dev_name, tBuffer ); + RetVal = m_pDBC->addResource( HARDWARE_ANALOG_VIDEO_IN, dev_name, mid ); + }; + close(fd); + }; + return RetVal; +}; + +uint32_t hardwareManager::createResourceUDCB( CSTR devName ){ + uint32_t RetVal = 0; + char tBuffer[256]; + return RetVal; +}; + +bool hardwareManager::assignResource( hardwareResource *ptr ){ + LOG("ASSIGN N_HWR"); + if ( ptr == NULL ) return false; + m_mVectorProtector.lock(); + LOG("LOCKED"); + m_vResources.push_back( ptr ); + LOG("ADDED"); + m_mVectorProtector.unlock(); + return true; +}; + +bool hardwareManager::resignResource( hardwareResource *ptr ){ + LOG("RESIGN N_HWR"); + if ( ptr == NULL ) return false; + m_mVectorProtector.lock(); + LOG("LOCKED"); + if( m_vResources.size() ) { + for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) { + if( (*idx) == ptr ) { + LOG("FOUND"); + m_vResources.erase( idx ); + LOG("ERASED"); + break; + }; + }; + } else { + LOG("NO RES!"); + }; + LOG("UNLOCKED"); + m_mVectorProtector.unlock(); + return true; +}; + +hardwareResource *hardwareManager::requestResource( HARDWARE_PROVIDERS type, uint32_t id ){ + hardwareResource *RetVal = NULL; + m_mVectorProtector.lock(); + if( m_vResources.size() ) { + for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) { + +#ifdef DEBUG_EXTRA + char tB[256]; + sprintf( tB, "Check Resources RR[%d] RI[%d] ?? CR[%d] CI[%d]", type, id, (*idx)->getProviderType(), (*idx)->getDbId() ); + LOG( tB ); +#endif + if( ((*idx)->getProviderType() == type ) && ( (*idx)->getDbId() == id ) ) { + RetVal = (*idx); + break; + }; + }; + } else { + LOG("No Resources!!"); + }; + m_mVectorProtector.unlock(); + return RetVal; +}; + +DBC_INT_LIST *hardwareManager::requestResourcesByType( HARDWARE_PROVIDERS type ){ + DBC_INT_LIST *RetVal = NULL; +#ifdef DEBUG + char tBuffer[128]; + sprintf( tBuffer, "Requested Resource type: %d", type ); + LOG( tBuffer ); +#endif + m_mVectorProtector.lock(); + if( m_vResources.size() ) { +#ifdef DEBUG + LOG("Have Some Resources!"); +#endif + RetVal = new DBC_INT_LIST(); + if( RetVal ) { +#ifdef DEBUG + LOG("RetVal Created!"); +#endif + for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) { +#ifdef DEBUG + sprintf( tBuffer, "Have Resource type: %d", (*idx)->getHardwareType() ); + LOG( tBuffer ); +#endif + if( (*idx)->getProviderType() == type ) { +#ifdef DEBUG + LOG("Matched!"); +#endif + RetVal->push_back((*idx)->getDbId()); + }; + }; + } else { + LOG_ERROR("Cannot Create DBC_INT_LIST"); + }; + }; + m_mVectorProtector.unlock(); + return RetVal; +}; + +bool hardwareManager::updateSysInfo( DBC_SYS_LOAD_INFO *ptr ){ + if ( ptr == NULL) return false; + struct sysinfo SI; + struct statvfs DI; + + ptr->CPU_CORES = get_nprocs(); + + if( sysinfo( &SI ) == 0 ){ + float f_load = 100.f / (float)( ptr->CPU_CORES * ( 1 << SI_LOAD_SHIFT ) ); + ptr->cpu1 = SI.loads[0] * f_load; + ptr->cpu5 = SI.loads[1] * f_load; + ptr->cpu15 = SI.loads[2] * f_load; + ptr->T_MEM = SI.totalram; + ptr->C_MEM = SI.totalram - SI.freeram; + ptr->mem = 100.0f * (float)ptr->C_MEM / (float)ptr->T_MEM; + } else { + LOG_ERROR("Error while getting System Info!"); + }; + //const uint32_t MB = 1 << 10;//(1024 * 1024);// * 1024; + + if( statvfs("/", &DI) == 0 ){ + ptr->T_DISK = ( DI.f_blocks * (unsigned long long) DI.f_frsize ) >> 10;// / MB; + //cDISK = ( DI.f_bavail * (unsigned long long) DI.f_bsize ) >> 10;// / MB; + ptr->C_DISK = ptr->T_DISK - ( ( DI.f_bfree * (unsigned long long) DI.f_bsize ) >> 10 ); + ptr->disk = 100.0f * (float)ptr->C_DISK / (float)ptr->T_DISK; + } else { + LOG_ERROR("Error while getting Disk Info!"); + }; + + //FILE *fd = popen("","r"); + ptr->temperature = 46.7; + return m_pDBC->updateServerUtilisation( ptr ); +}; + + +#undef CLEAR +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/hardwareManager.h b/lib/App/common/hardwareManager.h new file mode 100644 index 00000000..4ca94a79 --- /dev/null +++ b/lib/App/common/hardwareManager.h @@ -0,0 +1,56 @@ +#ifndef __DFSL_HARDWARE_MANAGER_HEADER__ +#define __DFSL_HARDWARE_MANAGER_HEADER__ + +#include "../components/base/basicLogCollection.h" +#include "../components/base/basicMutex.h" +#include "hardwareResource.h" + + + +class hardwareManager{ + private: + basicLogCollection * m_pLog; + VECTOR_HW_RESOURCES m_vResources; + basicMutex m_mVectorProtector; + dataBinder * m_pDBC; + DBC_SYS_INFO m_sSYS_INFO; + uint32_t m_nServerNodeID; + uint32_t m_nServerID; // Prop of DBC + uint32_t m_nSiteID; // Prop of Kernel + + size_t m_nMemoryLimitHeapSize; + + //bool m_bHardwareEnumerated; + void loadResources( void ); + void unloadResources( void ); + + uint32_t createResourceUART( CSTR devName ); + uint32_t createResourceVIDEO( CSTR devName ); + uint32_t createResourceUDCB( CSTR devName ); + uint32_t createResourceNETWORK( CSTR devName ); + void enumerateNIFS( void ); + void getMAC( CSTR if_name, CSTR buf ); + void getGW( CSTR if_name, CSTR buf ); + void getTTyDesc( CSTR dev_name, CSTR buf ); + /* Linux System Parsers */ + PARSE_RESULT_NET_INTERFACES * parse_neconfig( CSTR if_name ); + PARSE_RESULT_WIFI_SETTINGS * parse_wifi( CSTR if_name ); + public: + virtual ~hardwareManager(); + static hardwareManager * getInstance( bool cold_start = true ); + bool validate( void ); + hardwareResource * requestResource( HARDWARE_PROVIDERS type, uint32_t id ); + DBC_INT_LIST * requestResourcesByType( HARDWARE_PROVIDERS type ); + void enumerateHardware( void ); + bool assignResource( hardwareResource *ptr ); + bool resignResource( hardwareResource *ptr ); + bool updateSysInfo( DBC_SYS_LOAD_INFO *ptr ); + private: + static hardwareManager * _instance; + explicit hardwareManager( bool cold_start ); +}; + + + +#endif + diff --git a/lib/App/common/hardwareResource.cpp b/lib/App/common/hardwareResource.cpp new file mode 100644 index 00000000..598d20fc --- /dev/null +++ b/lib/App/common/hardwareResource.cpp @@ -0,0 +1,255 @@ +#include "hardwareResource.h" + +#ifdef USE_MYSQL + #include "MySQL_dataBinder.h" +#else + #include "SQLite_dataBinder.h" +#endif + +#define LOG( X ) m_pLog->Log( "HWR", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "HWR", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "HWR", this, _LOG_ERROR, X ); +#endif + +hardwareResource::hardwareResource(): basicObject(){ + m_bValid = false; + m_pLog = basicLogCollection::getInstance(); +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + m_eProviderType = HARDWARE_PROVIDER_UNKNOWN; + memset( &m_sResourceSettings, 0, sizeof( DBC_RESOURCE_DATA )); + m_sResourceSettings.type = HARDWARE_UNKNOWN; +}; + +hardwareResource::hardwareResource( uint32_t id, HARDWARE_PROVIDERS type ): basicObject(){ + m_bValid = false; + m_pLog = basicLogCollection::getInstance(); +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + m_eProviderType = type; + if( id > 0 ){ + if( m_pDBC!=NULL ){ + DBC_RESOURCE_DATA *tData = m_pDBC->getResourceData( id ); + if( tData != NULL ) { + memcpy( &m_sResourceSettings, tData, sizeof(DBC_RESOURCE_DATA)); + free( tData ); +#ifdef DEBUG + char tBuff[256]; +#endif + switch( m_sResourceSettings.type ) { + case HARDWARE_USB_DC:{ +#ifdef DEBUG + sprintf( tBuff, "USB Dry Contact [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_DRY_CONTACT; + break; + }; + case HARDWARE_IP_VIDEO_IN:{ +#ifdef DEBUG + sprintf( tBuff, "IP Video IN [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_VIDEO; + break; + }; + case HARDWARE_IP_VIDEO_OUT:{ +#ifdef DEBUG + sprintf( tBuff, "IP Video IN [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_VIDEO; + break; + }; + case HARDWARE_IP_UART:{ +#ifdef DEBUG + sprintf( tBuff, "IP UART [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_SERIAL; + break; + }; + case HARDWARE_ANALOG_VIDEO_IN:{ +#ifdef DEBUG + sprintf( tBuff, "Analog Video IN [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_VIDEO; + break; + }; + case HARDWARE_ANALOG_VIDEO_OUT:{ +#ifdef DEBUG + sprintf( tBuff, "Analog Video IN [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_VIDEO; + break; + }; + case HARDWARE_NIF_LOOPBACK: + case HARDWARE_NIF_ETHERNET: + case HARDWARE_NIF_WIFI: + case HARDWARE_NIF_VIRTUAL: + case HARDWARE_NIF_TUNEL:{ +#ifdef DEBUG + sprintf( tBuff, "Network Interface [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_NETWORK; + break; + }; + case HARDWARE_UART:{ +#ifdef DEBUG + sprintf( tBuff, "HW UART [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_SERIAL; + break; + }; + default:{ +#ifdef DEBUG + sprintf( tBuff, "Unknown Resource Type [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_UNKNOWN; + break; + }; + }; +#ifdef DEBUG + LOG( tBuff ); +#endif + } else { + LOG_ERROR("Cannot Fetch Hardware Data from DB!"); + memset( &m_sResourceSettings, 0, sizeof( DBC_RESOURCE_DATA )); + m_sResourceSettings.id = id; + m_sResourceSettings.type = HARDWARE_UNKNOWN; + }; + } else { + LOG_ERROR("No Database Object!"); + memset( &m_sResourceSettings, 0, sizeof( DBC_RESOURCE_DATA )); + m_sResourceSettings.id = id; + m_sResourceSettings.type = HARDWARE_UNKNOWN; + }; + } else { + LOG_ERROR("Resource ID not set!"); + memset( &m_sResourceSettings, 0, sizeof( DBC_RESOURCE_DATA )); + m_sResourceSettings.id = id; + m_sResourceSettings.type = HARDWARE_UNKNOWN; + }; +}; + +hardwareResource::~hardwareResource(){ +}; + +bool hardwareResource::create( uint32_t id, HARDWARE_PROVIDERS type ){ + m_bValid = false; + m_eProviderType = type; + if( id > 0 ){ + if( m_pDBC!=NULL ){ + DBC_RESOURCE_DATA *tData = m_pDBC->getResourceData( id ); + if( tData != NULL ) { + memcpy( &m_sResourceSettings, tData, sizeof(DBC_RESOURCE_DATA)); + free( tData ); +#ifdef DEBUG + char tBuff[256]; +#endif + switch( m_sResourceSettings.type ) { + case HARDWARE_USB_DC:{ +#ifdef DEBUG + sprintf( tBuff, "USB Dry Contact [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_DRY_CONTACT; + break; + }; + case HARDWARE_IP_VIDEO_IN:{ +#ifdef DEBUG + sprintf( tBuff, "IP Video IN [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_VIDEO; + break; + }; + case HARDWARE_IP_VIDEO_OUT:{ +#ifdef DEBUG + sprintf( tBuff, "IP Video IN [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_VIDEO; + break; + }; + case HARDWARE_IP_UART:{ +#ifdef DEBUG + sprintf( tBuff, "IP UART [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_SERIAL; + break; + }; + case HARDWARE_ANALOG_VIDEO_IN:{ +#ifdef DEBUG + sprintf( tBuff, "Analog Video IN [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_VIDEO; + break; + }; + case HARDWARE_ANALOG_VIDEO_OUT:{ +#ifdef DEBUG + sprintf( tBuff, "Analog Video IN [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_VIDEO; + break; + }; + case HARDWARE_NIF_LOOPBACK: + case HARDWARE_NIF_ETHERNET: + case HARDWARE_NIF_WIFI: + case HARDWARE_NIF_VIRTUAL: + case HARDWARE_NIF_TUNEL:{ +#ifdef DEBUG + sprintf( tBuff, "Network Interface [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_NETWORK; + break; + }; + case HARDWARE_UART:{ +#ifdef DEBUG + sprintf( tBuff, "HW UART [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_SERIAL; + break; + }; + default:{ +#ifdef DEBUG + sprintf( tBuff, "Unknown Resource Type [%d] id: %d aux: %d", m_sResourceSettings.type, id, m_sResourceSettings.aux_id ); +#endif + m_eProviderType = HARDWARE_PROVIDER_UNKNOWN; + break; + }; + }; +#ifdef DEBUG + LOG( tBuff ); +#endif + } else { + LOG_ERROR("Cannot Fetch Hardware Data from DB!"); + memset( &m_sResourceSettings, 0, sizeof( DBC_RESOURCE_DATA )); + m_sResourceSettings.id = id; + m_sResourceSettings.type = HARDWARE_UNKNOWN; + }; + } else { + LOG_ERROR("No Database Object!"); + memset( &m_sResourceSettings, 0, sizeof( DBC_RESOURCE_DATA )); + m_sResourceSettings.id = id; + m_sResourceSettings.type = HARDWARE_UNKNOWN; + }; + return true; + } else { + LOG_ERROR("Resource ID not set!"); + memset( &m_sResourceSettings, 0, sizeof( DBC_RESOURCE_DATA )); + m_sResourceSettings.id = id; + m_sResourceSettings.type = HARDWARE_UNKNOWN; + }; + return false; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/hardwareResource.h b/lib/App/common/hardwareResource.h new file mode 100644 index 00000000..30755601 --- /dev/null +++ b/lib/App/common/hardwareResource.h @@ -0,0 +1,67 @@ +#ifndef __DFSL_HARDWARE_RESOURCE_HEADER__ +#define __DFSL_HARDWARE_RESOURCE_HEADER__ + +#include "../components/base/basicObject.h" +#include "../components/base/basicLogCollection.h" +#include "dataBinder.h" + +#include +#include + +#include + +#define DBC_RESOURCE_DESC_SIZE 64 + +typedef struct S_PARSE_RESULT_NET_INTERFACES{ + bool enabled; + bool if_static; + bool hot_plug; + char address[INET6_ADDRSTRLEN]; + char netmask[INET6_ADDRSTRLEN]; + char gateway[INET6_ADDRSTRLEN]; +}PARSE_RESULT_NET_INTERFACES; + +typedef struct S_PARSE_RESULT_WIFI_SETTINGS{ + char SSID[64]; + char password[64]; + WIFI_ENCRIPTION encryption; + bool access_point; + uint8_t channel; + char country_code[3]; + bool hiden_ssid; + /* Router Settings */ + bool router_enabled; + char router_outbond[INET6_ADDRSTRLEN]; + /* DHCP */ + bool dhcp_enabled; + char range_start[INET6_ADDRSTRLEN]; + char range_stop[INET6_ADDRSTRLEN]; + char netmask[INET6_ADDRSTRLEN]; + char lease_period[INET6_ADDRSTRLEN]; +}PARSE_RESULT_WIFI_SETTINGS; + + +class hardwareResource: public basicObject{ + protected: + HARDWARE_PROVIDERS m_eProviderType; + DBC_RESOURCE_DATA m_sResourceSettings; + dataBinder * m_pDBC; + basicLogCollection * m_pLog; + bool m_bValid; + public: + hardwareResource(); + hardwareResource( uint32_t id, HARDWARE_PROVIDERS type = HARDWARE_PROVIDER_UNKNOWN ); + virtual ~hardwareResource(); + virtual bool create( void ){ return false; }; + virtual bool create( uint32_t id, HARDWARE_PROVIDERS type ); + virtual bool validate( void ){ return m_bValid; }; + bool isValid( void ){ return m_bValid; }; + uint32_t getDbId( void ){ return m_sResourceSettings.aux_id; }; + RESOURCE_TYPE getHardwareType( void ){ return (RESOURCE_TYPE) m_sResourceSettings.type; }; + HARDWARE_PROVIDERS getProviderType( void ){ return m_eProviderType; }; +}; + + +typedef std::vector VECTOR_HW_RESOURCES; + +#endif \ No newline at end of file diff --git a/lib/App/common/hardwareResourceDryContactProvider.cpp b/lib/App/common/hardwareResourceDryContactProvider.cpp new file mode 100644 index 00000000..2a6c8390 --- /dev/null +++ b/lib/App/common/hardwareResourceDryContactProvider.cpp @@ -0,0 +1,24 @@ +#include "hardwareResourceDryContactProvider.h" + +#define LOG( X ) hardwareResource::m_pLog->Log( "HWR_DRYC", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + hardwareResource::m_pLog->Log( "HWR_DRYC", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) hardwareResource::m_pLog->Log( "HWR_DRYC", this, _LOG_ERROR, X ); +#endif + +hardwareResourceUSBDCB::hardwareResourceUSBDCB( uint32_t id ): hardwareResource( id, HARDWARE_PROVIDER_DRY_CONTACT ){ + +}; + +hardwareResourceUSBDCB::~hardwareResourceUSBDCB(){ + +}; + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/common/hardwareResourceDryContactProvider.h b/lib/App/common/hardwareResourceDryContactProvider.h new file mode 100644 index 00000000..f9411af4 --- /dev/null +++ b/lib/App/common/hardwareResourceDryContactProvider.h @@ -0,0 +1,11 @@ +#ifndef __DFSL_HARDWARE_RESOURCE_USB_DCB_HEADER__ +#define __DFSL_HARDWARE_RESOURCE_USB_DCB_HEADER__ +#include "hardwareResource.h" + +class hardwareResourceUSBDCB: public hardwareResource { + public: + explicit hardwareResourceUSBDCB( uint32_t id ); + virtual ~hardwareResourceUSBDCB(); +}; + +#endif \ No newline at end of file diff --git a/lib/App/common/hardwareResourceNetworkProvider.cpp b/lib/App/common/hardwareResourceNetworkProvider.cpp new file mode 100644 index 00000000..afa25aa2 --- /dev/null +++ b/lib/App/common/hardwareResourceNetworkProvider.cpp @@ -0,0 +1,115 @@ +#include "hardwareResourceNetworkProvider.h" + +#define LOG( X ) hardwareResource::m_pLog->Log( "HWR_NETWORK", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + hardwareResource::m_pLog->Log( "HWR_NETWORK", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) hardwareResource::m_pLog->Log( "HWR_NETWORK", this, _LOG_ERROR, X ); +#endif + +hardwareResourceNetwork::hardwareResourceNetwork( uint32_t id, HARDWARE_PROVIDERS type ):hardwareResource( id, type ){ + if( m_pDBC!= NULL ){ + DBC_NET_IF_DATA *tData = m_pDBC->getNIF_Data( m_sResourceSettings.aux_id ); + if( tData != NULL ) { + memcpy( &m_sNetworkData, tData, sizeof(DBC_NET_IF_DATA)); + DBC_INT_LIST *nIDS = m_pDBC->listNetworks( m_sNetworkData.id ); + if( nIDS ){ + if( nIDS->size() ){ + LOG("Hawe Network Records!"); + m_sNetworkData.networkCount = nIDS->size(); + m_sNetworkData.networks = (DBC_NETWORK_DATA **)calloc(m_sNetworkData.networkCount, sizeof(DBC_NETWORK_DATA)); + if( m_sNetworkData.networks ){ + int i = 0; + for( DBC_INT_LIST::iterator idx=nIDS->begin(); idxend(); i++, idx++){ + m_sNetworkData.networks[i] = m_pDBC->getNetworkData( *idx ); +#ifdef DEBUG + if ( m_sNetworkData.networks[i] ) { + LOG( m_sNetworkData.networks[i]->address ); + LOG( m_sNetworkData.networks[i]->netmask ); + }; +#endif + }; + m_bValid = true; + } else { + LOG_ERROR("NOMEM FOR Network Records!"); + m_sNetworkData.networkCount = 0; + }; + }; + delete( nIDS ); + }; + free( tData ); + } else { + LOG_ERROR("No Data FROM DBC!"); + memset( &m_sNetworkData, 0, sizeof(DBC_NET_IF_DATA)); + }; + } else { + LOG_ERROR("No DBC!"); + memset( &m_sNetworkData, 0, sizeof(DBC_NET_IF_DATA)); + }; +}; + +hardwareResourceNetwork::~hardwareResourceNetwork(){ + +}; + +CSTR hardwareResourceNetwork::getAddress( NETWORK_TYPE nt ){ + if( m_sNetworkData.networkCount ) { + for ( int i = 0; i < m_sNetworkData.networkCount; i++ ){ + if (m_sNetworkData.networks[i]->type == nt ) { + if(m_sNetworkData.networks[i]->address[0] != (char)0) { + return strdup( m_sNetworkData.networks[i]->address ); + }; + break; + } + }; + }; + return NULL; +}; +CSTR hardwareResourceNetwork::getBroadcast( NETWORK_TYPE nt ){ + if( m_sNetworkData.networkCount ) { + for ( int i = 0; i < m_sNetworkData.networkCount; i++ ){ + if (m_sNetworkData.networks[i]->type == nt ) { + if( m_sNetworkData.networks[i]->broadcast[0] != (char)0 ) { + return strdup( m_sNetworkData.networks[i]->broadcast ); + }; + break; + }; + }; + }; + return NULL; +}; +CSTR hardwareResourceNetwork::getMask( NETWORK_TYPE nt ){ + if( m_sNetworkData.networkCount ) { + for ( int i = 0; i < m_sNetworkData.networkCount; i++ ){ + if (m_sNetworkData.networks[i]->type == nt ) { + if( m_sNetworkData.networks[i]->netmask[0] != (char)0 ) { + return strdup( m_sNetworkData.networks[i]->netmask ); + }; + break; + }; + }; + }; + return NULL; +}; +CSTR hardwareResourceNetwork::getGateway( NETWORK_TYPE nt ){ + if( m_sNetworkData.networkCount ) { + for ( int i = 0; i < m_sNetworkData.networkCount; i++ ){ + if (m_sNetworkData.networks[i]->type == nt ) { + if (m_sNetworkData.networks[i]->gateway[0] != (char)0) { + return strdup( m_sNetworkData.networks[i]->gateway ); + }; + break; + }; + }; + }; + return NULL; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/hardwareResourceNetworkProvider.h b/lib/App/common/hardwareResourceNetworkProvider.h new file mode 100644 index 00000000..699e3efb --- /dev/null +++ b/lib/App/common/hardwareResourceNetworkProvider.h @@ -0,0 +1,19 @@ +#ifndef __DFSL_HARDWARE_RESOURCE_NETWORK_HEADER__ +#define __DFSL_HARDWARE_RESOURCE_NETWORK_HEADER__ + +#include "hardwareResource.h" + +class hardwareResourceNetwork: public hardwareResource { + private: + DBC_NET_IF_DATA m_sNetworkData; + public: + explicit hardwareResourceNetwork( uint32_t id, HARDWARE_PROVIDERS type = HARDWARE_PROVIDER_NETWORK ); + virtual ~hardwareResourceNetwork(); + CSTR getAddress( NETWORK_TYPE nt=NETWORK_IPV4 ); + CSTR getBroadcast( NETWORK_TYPE nt=NETWORK_IPV4 ); + CSTR getMask( NETWORK_TYPE nt=NETWORK_IPV4 ); + CSTR getGateway( NETWORK_TYPE nt=NETWORK_IPV4 ); + virtual bool create( void ){ return true; }; +}; + +#endif diff --git a/lib/App/common/hardwareResourceSerialProvider.cpp b/lib/App/common/hardwareResourceSerialProvider.cpp new file mode 100644 index 00000000..05c9884a --- /dev/null +++ b/lib/App/common/hardwareResourceSerialProvider.cpp @@ -0,0 +1,1140 @@ +//#define DEBUG_EXTRA +#include "hardwareResourceSerialProvider.h" +#include "../data/protocol/protocol.h" +//#include "rgooseDBConnector.h" + +#define LOG( X ) hardwareResource::m_pLog->Log( "HWR_SERIAL", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + hardwareResource::m_pLog->Log( "HWR_SERIAL", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) hardwareResource::m_pLog->Log( "HWR_SERIAL", this, _LOG_ERROR, X ); +#endif + +hardwareResourceSerialProvider::hardwareResourceSerialProvider( uint32_t dbID ) : hardwareResource( dbID, HARDWARE_PROVIDER_SERIAL ), basicTransport(), basicDualThread(){ + memset( &m_sUartData, 0, sizeof(m_sUartData)); + memset( &m_sTTY, 0, sizeof(m_sTTY)); + m_nInputBufferSize = 0; + m_nOutputBufferSize = 0; + m_iDeviceFD = -1; + m_iMasterFD = -1; +#ifdef __linux__ + m_iInFID = -1; + m_iOutFID = -1; + m_bManualRTS = false; +#endif +}; + +hardwareResourceSerialProvider::~hardwareResourceSerialProvider(){ + closePort(); + //m_pDBC->setNodeOffline( m_sResourceSettings.node_id ); +}; + +bool hardwareResourceSerialProvider::create( void ){ + if( m_pDBC!= NULL ){ + DBC_UART_DATA *tDATA = NULL; + tDATA = m_pDBC->getUartData(m_sResourceSettings.aux_id); + if( tDATA!= NULL ) { + memcpy( &m_sUartData, tDATA, sizeof(DBC_UART_DATA)); +#ifdef DEBUG + LOG( m_sUartData.path ); +#endif + free( tDATA ); + switch( m_sUartData.type ){ + case HARDWARE_UART: m_bValid = create_HW(); break; + case HARDWARE_IP_UART: m_bValid = create_SOL(); break; + }; + }; + }; + return m_bValid; +}; + +// Calculating the Check Sum +unsigned short checksum(void *b, int len){ + unsigned short *buf = (unsigned short *) b; + unsigned int sum=0; + unsigned short result; + + for ( sum = 0; len > 1; len -= 2 ) + sum += *buf++; + if ( len == 1 ) + sum += *(unsigned char*)buf; + sum = (sum >> 16) + (sum & 0xFFFF); + sum += (sum >> 16); + result = ~sum; + return result; +} + + +bool hardwareResourceSerialProvider::validate( void ){ + if( m_pDBC != NULL ){ + DBC_UART_DATA *tDATA = m_pDBC->getUartData(m_sResourceSettings.aux_id); + switch( m_sUartData.type ) { + case HARDWARE_UART:{ + //HW port is valid + if( ( m_bThreadBStatus == TH_ENDED ) && ( m_bThreadAStatus == TH_ENDED ) ) { + LOG("IO Theads are Finished!"); + m_bValid = false; + closePort(); + }; + break; + }; + case HARDWARE_IP_UART:{ + //Ping E2U device + if( m_bValid ) { + m_bValid = pingDevice(); + if( !m_bValid ){ + LOG("No Ping to Device!!"); + closePort(); + }; + }; + break; + }; + }; + #ifdef DEBUG_EXTRA + LOG("Check Settings For Changes"); + #endif + if( tDATA!= NULL ){ + bool bFlag = true; + if( strcmp(tDATA->path,m_sUartData.path)!= 0 ) bFlag = false; + if( bFlag && ( m_sUartData.speed != tDATA->speed ) ) bFlag = false; + if( bFlag && ( m_sUartData.mode != tDATA->mode ) ) bFlag = false; + if( bFlag && ( m_sUartData.port != tDATA->port ) ) bFlag = false; + if( !bFlag ) { + #ifdef DEBUG_EXTRA + LOG("Settings Has been Changed!"); + #endif + memcpy( &m_sUartData, tDATA, sizeof(DBC_UART_DATA)); + #ifdef DEBUG_EXTRA + LOG("Reconect with new settings"); + #endif + if( m_bValid ) closePort(); + switch( m_sUartData.type ){ + case HARDWARE_UART: m_bValid = create_HW(); break; + case HARDWARE_IP_UART: m_bValid = create_SOL(); break; + }; + }; + // Check If Not Connected to Connect! + if( !m_bValid ) { + #ifdef DEBUG_EXTRA + LOG("Try to Conncet"); + #endif + switch( m_sUartData.type ){ + case HARDWARE_UART: m_bValid = create_HW(); break; + case HARDWARE_IP_UART: m_bValid = create_SOL(); break; + }; + }; + free( tDATA ); + } else { + LOG_ERROR("Error Fetch DB Data!"); + }; + } else m_bValid = false; + return m_bValid; +}; + +#include +// Define the Packet Constants +// ping packet size +#define PING_PKT_S 64 + +// Automatic port number +#define PORT_NO 0 + +// Automatic port number +#define PING_SLEEP_RATE 1000000 + +// Gives the timeout delay for receiving packets +// in seconds +#define RECV_TIMEOUT 1 + +// ping packet structure +struct ping_pkt { + struct icmphdr hdr; + char msg[PING_PKT_S-sizeof(struct icmphdr)]; +}; + +bool hardwareResourceSerialProvider::pingDevice(){ + bool RetVal = false; + if( m_bValid ) { +#ifdef DEBUG_EXTRA + LOG("Pinging Device!"); +#endif + int sockfd; + int ttl_val=64, msg_count=0, i, flag=1, msg_received_count=0; + struct ping_pkt pckt; + struct sockaddr_in ping_addr; + struct sockaddr_in r_addr; + struct timeval tv_out; + + tv_out.tv_sec = 0; + tv_out.tv_usec = 300000; // 1/3 of second + + + ping_addr.sin_family = AF_INET; + ping_addr.sin_addr.s_addr = inet_addr( m_sUartData.path ); + //ping_addr.sin_port = htons( m_nPort ); + LOG( m_sUartData.path ); + + sockfd = socket( AF_INET, SOCK_RAW, IPPROTO_ICMP ); + if( sockfd < 0 ){ + LOG_ERROR("Socket file descriptor not received!"); + return false; + }; + + // set socket options at ip to TTL and value to 64, + // change to what you want by setting ttl_val + if( setsockopt( sockfd, SOL_IP, IP_TTL, &ttl_val, sizeof(ttl_val)) != 0 ){ + LOG_ERROR("Setting socket options to TTL failed!"); + shutdown( sockfd, SHUT_RDWR ); + return false; + }; + + // setting timeout of recv setting + setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv_out, sizeof tv_out ); + + // flag is whether packet was sent or not + flag=1; + + //filling packet + bzero(&pckt, sizeof(pckt)); + + pckt.hdr.type = ICMP_ECHO; + pckt.hdr.un.echo.id = getpid(); + + for ( i = 0; i < sizeof(pckt.msg)-1; i++ ) pckt.msg[i] = i+'0'; + + pckt.msg[i] = 0; + pckt.hdr.un.echo.sequence = msg_count++; + pckt.hdr.checksum = checksum(&pckt, sizeof(pckt)); + + + //SLEEP( 300 ); + + //send packet + if( sendto( sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&ping_addr, sizeof(ping_addr)) <= 0 ){ + LOG_ERROR("Packet Sending Failed!"); + shutdown( sockfd, SHUT_RDWR ); + return false; + }; + + //receive packet + socklen_t addr_len = sizeof(r_addr); + + if( recvfrom( sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&r_addr, &addr_len) <= 0 ){ + LOG_ERROR("Packet receive failed!"); + shutdown( sockfd, SHUT_RDWR ); + return false; + } else { +#ifdef DEBUG_EXTRA + LOG("Device pinged Sucessfully"); +#endif + RetVal = true; + }; + shutdown( sockfd, SHUT_RDWR ); + }; + return RetVal; +}; + +bool hardwareResourceSerialProvider::create_SOL(){ + + /* + if( m_sUartData.mode == SOL_NOT_DEFINED ) { + LOG_ERROR("No Connection Type Defined!"); + return false; + }; + */ + if( m_sUartData.port == 0 ) { + LOG_ERROR("No Port Defined!"); + return false; + }; + if( m_sUartData.speed == 0 ){ + LOG_ERROR("No Speed Defined!"); + return false; + }; + if( m_sUartData.path[0] == (char)0 ) { + LOG_ERROR("No Adress Defined!"); + return false; + }; + + switch( m_sUartData.mode ) { + case SOL_UDP_CLIENT:{ +#ifdef DEBUG + LOG("PORT IS CLIENT - Create UDP Server"); +#endif +#ifdef __linux__ + // Creating socket file descriptor + if ( (m_iDeviceFD = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) { + LOG_ERROR("UDP Socket Creation Failed!"); + return false; + }; + fcntl( m_iDeviceFD, F_SETFL, O_NONBLOCK); + // Filling server information + struct sockaddr_in tServerAddr; + memset( &tServerAddr, 0, sizeof(tServerAddr) ); + tServerAddr.sin_family = AF_INET; // IPv4 + tServerAddr.sin_addr.s_addr = INADDR_ANY; + tServerAddr.sin_port = htons( m_sUartData.port ); + + // Bind the socket with the server address + if ( bind( m_iDeviceFD, (const struct sockaddr *)&tServerAddr, sizeof(tServerAddr)) < 0 ){ + LOG_ERROR("UDP Bind Failed"); + return false; + }; +#else + WSADATA wsaData; + // Initialize Winsock version 2.2 + char tBuff[128]; + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { + sprintf(tBuff, "WSAStartup failed with error %ld", WSAGetLastError()); + LOG_ERROR(tBuff); + return false; + } else { + sprintf(tBuff, "The Winsock DLL status is %s.", wsaData.szSystemStatus); + LOG(tBuff); + }; + // Set up a SOCKADDR_IN structure that will tell bind that we + // want to receive datagrams from all interfaces using port 5150. + // The IPv4 family + ReceiverAddr.sin_family = AF_INET; + // Port no. 5150 + ReceiverAddr.sin_port = htons( m_nPort ); + // From all interface (0.0.0.0) + ReceiverAddr.sin_addr.s_addr = htonl(INADDR_ANY); + // Associate the address information with the socket using bind. + // At this point you can receive datagrams on your bound socket. + if( bind(m_sSocket, (SOCKADDR*)&ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR ){ + sprintf( tBuff, "Server: bind() failed!Error : %ld.", WSAGetLastError()); + // Close the socket + closesocket(m_sSocket); + // Do the clean up + WSACleanup(); + // and exit with error + LOG_ERROR(tBuff); + return false; + } else { + LOG("UDP Server: bind() is OK!"); + }; + // Some info on the receiver side... + SOCKADDR_IN tAddr; + int tLen = sizeof(SOCKADDR_IN); + getsockname(m_sSocket, (SOCKADDR*)&tAddr, &tLen); + sprintf( tBuff, "Receiving IP(s) used : %s", inet_ntoa(tAddr.sin_addr)); + LOG(tBuff); + sprintf(tBuff,"Receiving port used : %d", htons(tAddr.sin_port)); + LOG(tBuff); + SelectTiming = recvfromTimeOutUDP(m_sSocket, 10, 0); +#endif + break; + }; + case SOL_TCP_CLIENT:{ +#ifdef DEBUG + LOG("PORT IS CLIENT - Create TCP Server"); +#endif + break; + }; + case SOL_UDP_SERVER:{ +#ifdef DEBUG + LOG("PORT IS SERVER - Create UDP Client"); +#endif +#ifdef __linux__ + // Creating socket file descriptor + if ( (m_iDeviceFD = socket( AF_INET, SOCK_DGRAM, 0)) < 0 ) { + LOG_ERROR("Socket Creation Failed!"); + return false; + }; + fcntl( m_iDeviceFD, F_SETFL, O_NONBLOCK ); + + // Filling server information + struct sockaddr_in tServerAddr; + memset( &tServerAddr, 0, sizeof(tServerAddr) ); + tServerAddr.sin_family = AF_INET; + tServerAddr.sin_addr.s_addr = INADDR_ANY; + tServerAddr.sin_port = htons( m_sUartData.port ); +#else + +#endif + break; + }; + case SOL_TCP_SERVER:{ +#ifdef DEBUG + LOG("PORT IS SERVER - Create TCP Client"); +#endif + // socket create and varification + m_iDeviceFD = socket( AF_INET, SOCK_STREAM, 0 ); + if( m_iDeviceFD == -1) { + LOG_ERROR("Socket creation failed!"); + return false; + } +#ifdef DEBUG + else LOG("Socket successfully created"); +#endif + + + // assign IP, PORT + struct sockaddr_in tServerAddr; + memset( &tServerAddr, 0, sizeof(tServerAddr) ); + tServerAddr.sin_family = AF_INET; + tServerAddr.sin_addr.s_addr = inet_addr( m_sUartData.path ); + tServerAddr.sin_port = htons( m_sUartData.port ); + + // connect the client socket to server socket + if( connect( m_iDeviceFD, (struct sockaddr *)&tServerAddr, sizeof(tServerAddr) ) !=0 ){ + char cBuffer[128]; + sprintf(cBuffer,"ERROR connect to [%s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno) ); + LOG_ERROR( cBuffer ); + return false; + } +#ifdef DEBUG + else LOG("Connected to the server"); +#endif + + // Set non-blocking + int arg; + if( (arg = fcntl( m_iDeviceFD, F_GETFL, NULL)) < 0) { + char tBuf[128]; + sprintf( tBuf, "Error fcntl(..., F_GETFL) (%s)", strerror(errno)); + LOG_ERROR( tBuf ); + return false; + }; + arg |= O_NONBLOCK; + if( fcntl( m_iDeviceFD, F_SETFL, arg) < 0) { + char tBuf[128]; + sprintf( tBuf, "Error fcntl(..., F_SETFL) (%s)", strerror(errno)); + LOG_ERROR( tBuf ); + return false; + }; + setConnectionStatus( CS_CONNECTED ); + break; + }; + }; + return init(); +}; + +bool hardwareResourceSerialProvider::create_HW(){ + char MsgBuffer[CLOG]; + + if( m_eConnectionStatus == CS_CONNECTED ){ + LOG_ERROR( "TRYING TO CONNECT ON OPENED PORT!" ); + return false; + }; + //if( m_bInitComplete ) { + // LOG_ERROR( "TRYING TO CREATE CREATED PORT!" ); + // return false; + //}; +#ifdef __linux__ + int result; + /* Open File Descriptor */ + //m_iFID = open( DevicePath, O_RDWR| O_NONBLOCK | O_NDELAY ); + #ifdef USE_WIRINGPI + if( strstr( m_sUartData.path, "USB" ) == NULL ){ + #ifdef DEBUG + LOG("MANUAL RTS CTL"); + #endif + m_bManualRTS = true; + wiringPiSetup(); + //Set RTS Pin + pinMode( 0, OUTPUT ); + } else { + #ifdef DEBUG + LOG("NO MANUAL RTS CTL"); + #endif + m_bManualRTS = false; + }; + #else + #ifdef DEBUG + LOG("NO MANUAL RTS CTL"); + #endif + m_bManualRTS = false; + #endif + + do{ + m_iInFID = open( m_sUartData.path, O_RDONLY | O_NONBLOCK | O_NDELAY ); + } while( m_iInFID == -1 && errno == EINTR ); + + if( m_iInFID == -1 ){ + LOG_ERROR("Can not open Input Stream"); + return false; + }; + + do{ + result = fcntl( m_iInFID, F_SETFL, O_NONBLOCK ); + }while( result == -1 && errno == EINTR ); + + if( result == -1 ){ + int const error = errno; + do{ + result = close( m_iInFID ); + }while( result == -1 && errno == EINTR ); + errno = error; + sprintf( MsgBuffer, "Error %d openning port: %s", errno, strerror (errno) ); + LOG_ERROR( MsgBuffer ); + return false; + }; + + do{ + m_iOutFID = open( m_sUartData.path, O_WRONLY | O_NDELAY ); + }while( m_iOutFID == -1 && errno == EINTR); + + if( m_iOutFID == -1 ){ + LOG_ERROR("Can not open Output Stream"); + return false; + }; + + + /* *** Configure Port *** */ + memset( &m_sTTY, 0, sizeof( m_sTTY ) ); + + /* Error Handling */ + do{ + result = tcgetattr( m_iInFID, &m_sTTY ); + }while( result == -1 && errno == EINTR ); + + if( result == -1 ){ + int const error = errno; + do{ + result = close( m_iInFID ); + }while( result == -1 && errno == EINTR ); + errno = error; + sprintf( MsgBuffer, "Error %d from tcgetattr: %s", errno, strerror (errno) ); + LOG_ERROR( MsgBuffer ); + return false; + }; + + /* Set Baud Rate */ + int RetVal = 0; + switch( m_sUartData.speed ){ + case 4000000: cfsetspeed (&m_sTTY, B4000000 ); break; + case 3500000: cfsetspeed (&m_sTTY, B3500000 ); break; + case 3000000: cfsetspeed (&m_sTTY, B3000000 ); break; + case 2500000: cfsetspeed (&m_sTTY, B2500000 ); break; + case 2000000: cfsetspeed (&m_sTTY, B2000000 ); break; + case 1500000: cfsetspeed (&m_sTTY, B1500000 ); break; + case 1152000: cfsetspeed (&m_sTTY, B1152000 ); break; + case 1000000: cfsetspeed (&m_sTTY, B1000000 ); break; + case 921600: cfsetspeed (&m_sTTY, B921600 ); break; + case 460800: cfsetspeed (&m_sTTY, B460800 ); break; + case 230400: cfsetspeed (&m_sTTY, B230400 ); break; + case 115200: cfsetspeed (&m_sTTY, B115200 ); break; + case 19200: cfsetspeed (&m_sTTY, B19200 ); break; + case 9600: cfsetspeed (&m_sTTY, B9600 ); break; + default:{ + close( m_iInFID ); + close( m_iOutFID ); + sprintf( MsgBuffer, "Error cannot set speed as [%d] bod", m_sUartData.speed ); + LOG_ERROR( MsgBuffer ); + return false; + }; + }; + if( RetVal == 0 ) { +#ifdef DEBUG + sprintf( MsgBuffer, "speed set to [%d] bod", m_sUartData.speed ); + LOG( MsgBuffer ); +#endif + } else { + RetVal = cfgetispeed( &m_sTTY ); + sprintf( MsgBuffer, "Error cannot set speed as [%d] bod. Current is: %d bod. ", m_sUartData.speed, RetVal ); + LOG_ERROR( MsgBuffer ); + return false; + }; + + + /* Setting other Port Stuff */ + + m_sTTY.c_cflag &= ~PARENB; // Make 8n1 + m_sTTY.c_cflag &= ~CSTOPB; + m_sTTY.c_cflag &= ~CSIZE; + m_sTTY.c_cflag |= CS8; + m_sTTY.c_cflag &= ~CRTSCTS; // no flow control + // + m_sTTY.c_iflag &= ~(INLCR | ICRNL); // fixing 0x0D->0x0A + // + m_sTTY.c_lflag = 0; // no signaling chars, no echo, no canonical processing + m_sTTY.c_oflag = 0; // no remapping, no delays + m_sTTY.c_cc[VMIN] = 0; // read doesn't block + m_sTTY.c_cc[VTIME] = 5; // 0.5 seconds read timeout + + m_sTTY.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines + m_sTTY.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl + m_sTTY.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw + m_sTTY.c_oflag &= ~OPOST; // make raw + + /* Flush Port, then applies attributes */ + tcflush( m_iOutFID, TCIFLUSH ); + + do{ + result = tcsetattr( m_iOutFID, TCSANOW, &m_sTTY ); + }while( result == -1 && errno == EINTR ); + if( result == -1 ){ + int const error = errno; + do{ + result = close( m_iOutFID ); + }while( result == -1 && errno == EINTR ); + errno = error; + sprintf( MsgBuffer, "Error %d from tcsetattr: %s", errno, strerror (errno) ); + LOG_ERROR( MsgBuffer ); + return false; + }; + + do{ + result = tcsetattr( m_iInFID, TCSANOW, &m_sTTY ); + }while( result == -1 && errno == EINTR ); + if( result == -1 ){ + int const error = errno; + do{ + result = close( m_iInFID ); + }while( result == -1 && errno == EINTR ); + errno = error; + sprintf( MsgBuffer, "Error %d from tcsetattr: %s", errno, strerror (errno) ); + LOG_ERROR( MsgBuffer ); + return false; + }; +#else // Linux + m_ioFID = CreateFile( (LPCSTR)m_sDevicePath, + GENERIC_READ | GENERIC_WRITE, + 0UL, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, + //FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, + NULL ); + + if (m_ioFID == INVALID_HANDLE_VALUE){ + setConnectionStatus(CS_DISCONNECTED); + sprintf(MsgBuffer, "Port [%s] Open Failed Err: %d", m_sDevicePath, GetLastError()); + LOG_ERROR(MsgBuffer); + return false; + }; + // Initialize the DCBlength member. + PortDCB.DCBlength = sizeof(DCB); + // Get the default port setting information. + GetCommState(m_ioFID, &PortDCB); + // Change the DCB structure settings + /* + PortDCB.fBinary = TRUE; // Binary mode; no EOF check + PortDCB.fParity = NOPARITY; // Enable parity checking + PortDCB.fDsrSensitivity = FALSE; // DSR sensitivity + PortDCB.fErrorChar = FALSE; // Disable error replacement + PortDCB.fOutxDsrFlow = FALSE; // No DSR output flow control + PortDCB.fAbortOnError = FALSE; // Do not abort reads/writes on error + PortDCB.fNull = FALSE; // Disable null stripping + PortDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx + PortDCB.BaudRate = Speed; + PortDCB.StopBits = ONESTOPBIT; + */ + PortDCB.BaudRate = Speed; + PortDCB.ByteSize = 8; + PortDCB.Parity = NOPARITY; + PortDCB.StopBits = ONESTOPBIT; + PortDCB.EvtChar = 0; + PortDCB.fParity = (PortDCB.Parity != NOPARITY); + PortDCB.fOutxCtsFlow = FALSE; + PortDCB.fOutxDsrFlow = FALSE; + PortDCB.fDtrControl = DTR_CONTROL_DISABLE; + PortDCB.fDsrSensitivity = FALSE; + PortDCB.fOutX = FALSE; + PortDCB.fInX = FALSE; + PortDCB.fErrorChar = FALSE; + PortDCB.fNull = FALSE; + // dcb.fRtsControl = RTS_CONTROL_DISABLE; + PortDCB.fRtsControl = RTS_CONTROL_ENABLE; + // dcb.fRtsControl = RTS_CONTROL_TOGGLE; // specially for PROMAG USB->RS485 converter + PortDCB.fAbortOnError = FALSE; + PortDCB.fBinary = TRUE; + PortDCB.fTXContinueOnXoff = TRUE; + //Re-configure the port with the new DCB structure. + if (!SetCommState(m_ioFID, &PortDCB)) { + sprintf(MsgBuffer, "Port [%s] Could not create the read thread.(SetCommState Failed)", m_sDevicePath); + LOG_ERROR(MsgBuffer); + CloseHandle(m_ioFID); + return false; + }; + + COMMTIMEOUTS CommTimeouts; + // Retrieve the time-out parameters for all read and write operations + GetCommTimeouts(m_ioFID, &CommTimeouts); + /* + CommTimeouts.ReadIntervalTimeout = 20; + CommTimeouts.ReadTotalTimeoutMultiplier = 10; + CommTimeouts.ReadTotalTimeoutConstant = 100; + CommTimeouts.WriteTotalTimeoutMultiplier = 10; + CommTimeouts.WriteTotalTimeoutConstant = 100; + */ + CommTimeouts.ReadIntervalTimeout = 20UL; + CommTimeouts.ReadTotalTimeoutMultiplier = 1UL; + CommTimeouts.ReadTotalTimeoutConstant = 5UL; + CommTimeouts.WriteTotalTimeoutMultiplier = 1UL; + CommTimeouts.WriteTotalTimeoutConstant = 1UL; + // Set the time-out parameters for all read and write operations on the port. + if (!SetCommTimeouts(m_ioFID, &CommTimeouts)){ + sprintf(MsgBuffer, "Port [%s] Could not create the read thread.(SetCommTimeouts Failed)", m_sDevicePath); + LOG_ERROR(MsgBuffer); + CloseHandle(m_ioFID); + return false; + }; + + // Clear the port of any existing data. + if (PurgeComm(m_ioFID, PURGE_TXCLEAR | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_RXABORT ) == 0){ + sprintf(MsgBuffer, "Port [%s] Clearing The Port Failed", m_sDevicePath); + LOG_ERROR(MsgBuffer); + CloseHandle(m_ioFID); + return false; + }; + + EscapeCommFunction(m_ioFID, SETRTS); + EscapeCommFunction(m_ioFID, SETDTR); + //Set DataTerminalReady 1 +#endif + setConnectionStatus( CS_CONNECTED ); + if( init() ) { +#ifdef DEBUG + sprintf( MsgBuffer,"Init %s [%d] OK", m_sUartData.path, m_sUartData.speed ); + LOG( MsgBuffer ); +#endif + return true; + } else { + LOG_ERROR("HW INIT Failure!"); + }; + return false; +}; + +bool hardwareResourceSerialProvider::closePort(){ + char tBuff[128]; + + setConnectionStatus( CS_DISCONNECTED ); + + if( m_bThreadAStatus != TH_PRE_INIT && m_bThreadBStatus != TH_PRE_INIT ){ + uninit(); + }; + switch( m_sUartData.type ) { + case HARDWARE_UART:{ + break; + }; + case HARDWARE_IP_UART:{ + if( m_iDeviceFD != -1 ) { + switch( m_sUartData.mode ) { + case SOL_UDP_CLIENT: + case SOL_TCP_CLIENT: + case SOL_UDP_SERVER: { + #ifdef __linux__ + close( m_iDeviceFD ); + #else + // When your application is finished receiving datagrams close the socket. + LOG("Server: Finished receiving.Closing the listening socket..."); + if( closesocket(m_sSocket) != 0 ){ + sprintf(tBuff, "closesocket() failed!Error code : %ld", WSAGetLastError()); + LOG_ERROR(tBuff); + } else { + LOG("closesocket() is OK..."); + }; + // When your application is finished call WSACleanup. + LOG("Server: Cleaning up..."); + if (WSACleanup() != 0) { + sprintf(tBuff, "WSACleanup() failed!Error code : %ld", WSAGetLastError()); + LOG_ERROR(tBuff); + } else { + LOG("WSACleanup() is OK"); + }; + #endif + break; + }; + case SOL_TCP_SERVER:{ + close( m_iDeviceFD ); + break; + }; + }; + m_iDeviceFD = -1; + }; + break; + }; + }; + return true; +}; + +void hardwareResourceSerialProvider::m_fThreadAProc(void){ + int index; + int RetVal; + m_bThreadAStatus = TH_WORKING; +#ifdef DEBUG + LOG("Sender Thread Started!"); +#endif + while (m_bThreadAStatus < TH_ENDED) { + m_mBufferProtectorMutex.lock(); + if( m_nOutputBufferSize > 0 ){ + index = 0; + while ((index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED)){ +#ifdef DEBUG_EXTRA + char TT[64]; + sprintf( TT, "Have %d Bytes to send!", m_nOutputBufferSize ); + LOG( TT ); +#endif + RetVal = sendBlock( m_pOutputBuffer + index, m_nOutputBufferSize - index ); + if( RetVal > 0 ){ + index += RetVal; + } else { + //if 0 or -(error) + if( RetVal == 0 ){ + usleep( 100 ); + } else { + setConnectionStatus( CS_DISCONNECTED ); + m_nOutputBufferSize = 0; + m_bThreadBStatus = TH_ENDED; + m_bThreadAStatus = TH_ENDED; + LOG_ERROR("Connection Droped on Sending Data"); + }; + }; + }; + m_nOutputBufferSize = 0; + m_mBufferProtectorMutex.unlock(); + } else { + m_mBufferProtectorMutex.unlock(); + SLEEP(5); + }; + }; +}; + +void hardwareResourceSerialProvider::m_fThreadBProc(void){ + m_bThreadBStatus = TH_WORKING; + int RetVal; +#ifdef DEBUG + LOG("Recipient Thread Started!"); +#endif + while( m_bThreadBStatus < TH_ENDED ){ + RetVal = recptBlock( m_pInputBuffer, &m_nInputBufferSize); + if( RetVal == -1 ){ + setConnectionStatus(CS_DISCONNECTED); + m_nInputBufferSize = 0; + //if(!getStatus()) { + m_bThreadBStatus = TH_ENDED; + m_bThreadAStatus = TH_ENDED; + //} else SLEEP(100); + LOG_ERROR("Connection Droped on Reception Data"); + } else if( m_nInputBufferSize > 0 ){ + do{ + m_mQueueProtectorMutex.lock(); + if( m_vParsers.size() ){ + for (parseQueue::iterator index = m_vParsers.begin(); index != m_vParsers.end(); index++) (*index)->parse(m_pInputBuffer, m_nInputBufferSize); + m_nInputBufferSize = 0; + m_mQueueProtectorMutex.unlock(); + } else { + m_nInputBufferSize = 0; + m_mQueueProtectorMutex.unlock(); +#ifdef DEBUG_EXTRA + LOG_ERROR("Try to parse data but No Parsers Assigned!"); +#endif + SLEEP(100); + }; + } while( ( m_vParsers.size() == 0 ) && ( m_bThreadBStatus < TH_ENDED ) && ( m_bThreadBStatus < TH_ENDED ) ); + } else { + SLEEP(5); + }; + }; +}; + +bool hardwareResourceSerialProvider::sendData( uint8_t *Data, int DataSize ){ + if( m_bThreadAStatus != TH_WORKING ) { + if( m_bThreadAStatus < TH_WORKING ) { + LOG_ERROR("Trying to Send Data Before Thread is Started!"); + } else { + LOG_ERROR("Trying to Send Data After Thread is Dead!"); + } + return false; + }; + m_mBufferProtectorMutex.lock(); + if (m_nOutputBufferSize + DataSize > MAXIMAL_SOCKET_PACKET_LENGTH ){ + m_mBufferProtectorMutex.unlock(); + LOG_ERROR("Data Too BIG"); + return false; + }; + memcpy(m_pOutputBuffer + m_nOutputBufferSize, Data, DataSize); + m_nOutputBufferSize += DataSize; + m_mBufferProtectorMutex.unlock(); + return true; +}; + +bool hardwareResourceSerialProvider::reconnect( void ){ + closePort(); + switch( m_sUartData.type ){ + case HARDWARE_UART: m_bValid = create_HW(); break; + case HARDWARE_IP_UART: m_bValid = create_SOL(); break; + }; + return m_bValid; +}; + +int hardwareResourceSerialProvider::recptBlock( unsigned char *Buffer, int *BufferLength ){ + +#ifdef __linux__ + int RetVal = 0; +#else + DWORD RetVal = 0; +#endif + + if( m_eConnectionStatus == CS_CONNECTED ){ + switch( m_sUartData.type ) { + case HARDWARE_UART:{ +#ifdef __linux__ + do{ + RetVal = read( m_iInFID, Buffer, MAXIMAL_SERIAL_PACKET_LENGTH ); + if( RetVal == -1 && errno == EINTR && m_bThreadAStatus == TH_WORKING ) SLEEP(1); + } while (RetVal == -1 && errno == EINTR && m_bThreadAStatus == TH_WORKING ); +#else //Windows + OVERLAPPED osReader = {0}; + if( !ReadFile(m_ioFID, Buffer, MAXIMAL_SERIAL_PACKET_LENGTH, &RetVal, &osReader) ){ + if (GetLastError() != ERROR_IO_PENDING){ // read not delayed? + char tBuffer[256]; + sprintf(tBuffer, "Communication Error %d!", GetLastError()); + LOG_ERROR(tBuffer); + // Error in communications; report it. + return -1; + } +#ifdef DEBUG_SERIAL_COMMUNICATION + else { + //fWaitingOnRead = TRUE; + LOG("WREAD!"); + } +#endif + ; + } +#ifdef DEBUG_SERIAL_COMMUNICATION + else { + // read completed immediately + LOG("IMREAD!"); + + } +#endif + ; +#endif // Linux + break; + }; + case HARDWARE_IP_UART:{ //SOL +#ifdef __linux__ + if( m_iDeviceFD > -1 ) { + struct sockaddr ClientAddress; + socklen_t addr_len = sizeof( ClientAddress ); //len is value/resuslt + //RetVal = recvfrom( m_nSocketFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_WAITALL, ( struct sockaddr *) &m_sClientAddr, &addr_len ); + RetVal = recvfrom( m_iDeviceFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_DONTWAIT, ( struct sockaddr *) &ClientAddress, &addr_len ); + if( RetVal < 1 ){ + if( errno!=EAGAIN && errno!=EINTR ) { + LOG_ERROR("Peer Closes Connection!"); + shutdown( m_iDeviceFD, 2 ); + close( m_iDeviceFD ); + *BufferLength = 0; + m_iDeviceFD = -1; + setConnectionStatus( CS_DISCONNECTED ); + return -1; + }; + }; + + } else { + LOG_ERROR("Not Connected!"); + *BufferLength = 0; + setConnectionStatus( CS_DISCONNECTED ); + return -1; + }; +#else + switch ( m_eType ) { + case SOL_UDP_CLIENT: + case SOL_TCP_CLIENT: + case SOL_UDP_SERVER: { + SOCKADDR_IN tAddr; + int tLen = sizeof(SOCKADDR_IN); + RetVal = recvfrom( m_sSocket, (char*)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, 0, (struct sockaddr*) &tAddr, &tLen); + if (RetVal == SOCKET_ERROR){ + char cBuffer[165]; + sprintf(cBuffer,"recvfrom() failed with error code : %d", WSAGetLastError()); + LOG_ERROR(cBuffer); + }; + break; + }; + }; +#endif + break; + }; // End of SOL + }; + } else { + if( m_sUartData.type == HARDWARE_IP_UART ) { + //make prep for connection SOL_TCP_SERVER + if( m_sUartData.mode == SOL_TCP_CLIENT ){ + //ACCEPT + struct sockaddr ClientAddress; + socklen_t size = (socklen_t) sizeof( struct sockaddr_in ); + //int ClientSocket; + m_iDeviceFD = accept( m_iMasterFD, &ClientAddress, &size ); + if( m_iDeviceFD < 0 ) { + setConnectionStatus( CS_DISCONNECTED ); + LOG_ERROR("Connection Accept Failure!"); + return -1; + }; + } else { + LOG_ERROR("RCPT ON not connected!"); + shutdown( m_iDeviceFD, 2 ); + close( m_iDeviceFD ); + *BufferLength = 0; + m_iDeviceFD = -1; + setConnectionStatus( CS_DISCONNECTED ); + return -1; + }; + } +#ifdef DEBUG + else LOG( "Port is not Ready to Receive" ) +#endif + ; + return -1; // Exit after unsuccess reconnect + }; + + if( RetVal > 0 ){ +#ifdef DEBUG_SERIAL_COMMUNICATION + char MsgBuffer[CLOG]; + if( RetVal > 1 || RetVal == 0 ) { + sprintf( MsgBuffer, "Received %d bytes", RetVal ); + } else { + sprintf( MsgBuffer, "Received 1 byte"); + }; + LOG( MsgBuffer ); + for (int i = 0; i < RetVal; i++) { + sprintf(MsgBuffer, "<0x%02X", Buffer[i]); + LOG(MsgBuffer); + }; +#endif + *BufferLength = RetVal; + return RetVal; + }; + + *BufferLength = 0; + + if (RetVal == -1) return 0; + + if (RetVal == 0){ + errno = 0; + return 0; + }; + + /* r < -1, should never happen. */ + errno = EIO; + return 0; +}; + +void hardwareResourceSerialProvider::setRTS( uint8_t Val ){ + #ifdef USE_WIRINGPI + if ( Val ) { + //Use RTS GPIO + digitalWrite( 0, HIGH ); + } else { + digitalWrite( 0, LOW ); + }; + #endif +}; + +#include + +int hardwareResourceSerialProvider::sendBlock(unsigned char* Data, int DataSize) { +#ifdef __linux__ + int RetVal = 0; +#else + DWORD RetVal = 0; +#endif + + if( m_eConnectionStatus== CS_CONNECTED ){ + switch( m_sUartData.type ) { + case HARDWARE_UART:{ +#ifdef __linux__ + // setRTS( 1 ); + do{ + #ifdef USE_WIRINGPI + if( m_bManualRTS ) digitalWrite( 0, HIGH ); + #endif + RetVal = write( m_iOutFID, Data, DataSize); + if( m_bManualRTS ){ + uint8_t lsr; + do { + int r = ioctl( m_iOutFID, TIOCSERGETLSR, &lsr ); + } while (!(lsr & TIOCSER_TEMT)); + #ifdef USE_WIRINGPI + digitalWrite( 0, LOW); + #endif + }; + if( RetVal == DataSize ){ + usleep( 10 ); + }; + } while (RetVal == -1 && (errno == EINTR || errno == EWOULDBLOCK) && m_bThreadAStatus == TH_WORKING ); + //if( m_bManualRTS ) setRTS( 0 ); +#else + WriteFile(m_ioFID, Data, DataSize, &RetVal, NULL); +#endif +#ifdef DEBUG_EXTRA + char MsgBuffer[CLOG]; + sprintf( MsgBuffer, "Sent %d byte(s) of %d", RetVal, DataSize ); + LOG( MsgBuffer ); + #ifdef DEBUG_SERIAL_COMMUNICATION + for( int i = 0; i < DataSize; i++ ){ + sprintf( MsgBuffer, ">0x%02X", Data[i] ); + LOG( MsgBuffer ); + }; + #endif +#endif + break; + }; + case HARDWARE_IP_UART:{ +#ifdef __linux__ + if( m_iDeviceFD > -1 ){ + + #ifdef DEBUG_EXTRA + char cBuffer[256]; + sprintf(cBuffer, "Write into Port %d bytes", DataSize); + LOG(cBuffer); + #endif + struct sockaddr ClientAddress; + socklen_t addr_len = sizeof(ClientAddress); + RetVal = sendto( m_iDeviceFD, (const char*)Data, DataSize, MSG_CONFIRM, (const struct sockaddr*) &ClientAddress, addr_len); + + if ((RetVal == -1) && (errno != EINTR) && (errno != EWOULDBLOCK)) { + LOG_ERROR("Error acures while writing data into the Socket"); + shutdown( m_iDeviceFD, 2); + close( m_iDeviceFD); + m_iDeviceFD = -1; + setConnectionStatus(CS_DISCONNECTED); + return -1; + }; + + if (RetVal < 0) RetVal = 0; + + #ifdef DEBUG_EXTRA + sprintf(cBuffer, "Bytes Sent: %ld", RetVal); + LOG(cBuffer); + #ifdef DEBUG_SERIAL_COMMUNICATION + for(int zz=0; zz < RetVal; zz++ ) { + sprintf(cBuffer, "SD: 0x%02X", (uint8_t)Data[zz]); + LOG(cBuffer); + }; + #endif + #endif + + } else { + LOG_ERROR("Not Connected!"); + //m_bConnected = false; + setConnectionStatus(CS_DISCONNECTED); + return -1; + }; +#else // Windows + if (sendto( m_sSocket, (char *)Data, DataSize, 0, (struct sockaddr*) &ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR) { + char cBuffer[256]; + sprintf(cBuffer, "sendto() failed with error code : %d", WSAGetLastError()); + LOG_ERROR( cBuffer ); + return -1; + }; +#endif + break; + }; + }; + } else { +#ifdef DEBUG_EXTRA + LOG( "Port is not Ready to Send" ); +#endif + return -1; + }; + return RetVal; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/hardwareResourceSerialProvider.h b/lib/App/common/hardwareResourceSerialProvider.h new file mode 100644 index 00000000..42e7f65d --- /dev/null +++ b/lib/App/common/hardwareResourceSerialProvider.h @@ -0,0 +1,77 @@ +#ifndef __DFSL_HARDWARE_SERIAL_PROVIDER_HEADER__ +#define __DFSL_HARDWARE_SERIAL_PROVIDER_HEADER__ + +#include "hardwareResource.h" +#include "../components/base/basicTransport.h" +#include "../components/base/basicDualThread.h" + +#include // standard input / output functions +#include +#include // string function definitions +#include // File control definitions +#include // Error number definitions +#ifdef __linux__ + #include // UNIX standard function definitions + #include // POSIX terminal control definitions + #ifdef __arm__ + #ifdef RASPI_HARDWARE + #define USE_WIRINGPI + #include + #endif + #endif +#endif + + +#ifdef DEBUG_EXTRA + #define DEBUG_SERIAL_COMMUNICATION +#endif + +#ifndef MAXIMAL_SOCKET_PACKET_LENGTH + #define MAXIMAL_SOCKET_PACKET_LENGTH 102400 +#endif + +#ifndef MAXIMAL_SERIAL_PACKET_LENGTH + #define MAXIMAL_SERIAL_PACKET_LENGTH MAXIMAL_SOCKET_PACKET_LENGTH +#endif + +class hardwareResourceSerialProvider: public hardwareResource, public basicTransport, public basicDualThread { + private: + DBC_UART_DATA m_sUartData; + + int m_iDeviceFD; + int m_iMasterFD; +#ifdef __linux__ + struct termios m_sTTY; + int m_iInFID; + int m_iOutFID; + bool m_bManualRTS; + void setRTS( uint8_t Val ); +#else + DCB PortDCB; + HANDLE m_ioFID; +#endif + bool pingDevice(); + bool create_SOL(); + bool create_HW(); + bool closePort(); + int sendBlock(unsigned char *Data, int DataSize); + int recptBlock(unsigned char *Buffer, int *BufferLength); + protected: + U8 m_pInputBuffer[MAXIMAL_SOCKET_PACKET_LENGTH]; + U8 m_pOutputBuffer[MAXIMAL_SOCKET_PACKET_LENGTH]; + int m_nInputBufferSize; + int m_nOutputBufferSize; + + virtual void m_fThreadAProc(void); + virtual void m_fThreadBProc(void); + public: + explicit hardwareResourceSerialProvider( uint32_t dbID ); + virtual ~hardwareResourceSerialProvider(); + virtual bool create( void ); + virtual bool validate( void ); + virtual bool sendData( uint8_t *Data, int DataSize ); + virtual bool reconnect( void ); +}; + +#endif + diff --git a/lib/App/common/hardwareResourceVideoProvider.cpp b/lib/App/common/hardwareResourceVideoProvider.cpp new file mode 100644 index 00000000..cd27110d --- /dev/null +++ b/lib/App/common/hardwareResourceVideoProvider.cpp @@ -0,0 +1,48 @@ +#include "hardwareResourceVideoProvider.h" + +#define LOG( X ) hardwareResource::m_pLog->Log( "HWR_VIDEO", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + hardwareResource::m_pLog->Log( "HWR_VIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) hardwareResource::m_pLog->Log( "HWR_VIDEO", this, _LOG_ERROR, X ); +#endif + +hardwareResourceVideoProvider::hardwareResourceVideoProvider( uint32_t id, HARDWARE_PROVIDERS type ):hardwareResource( id, type ){ + if( m_pDBC!= NULL ){ + DBC_MEDIA_STREAM_DATA *tData = m_pDBC->getMediaStreamData( m_sResourceSettings.aux_id ); + if( tData != NULL ) { + memcpy( &m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA)); +#ifdef DEBUG + +#endif + free( tData ); + } else { + memset( &m_sStreamData, 0, sizeof(DBC_MEDIA_STREAM_DATA)); + }; + } else { + memset( &m_sStreamData, 0, sizeof(DBC_MEDIA_STREAM_DATA)); + }; +}; + +hardwareResourceVideoProvider::~hardwareResourceVideoProvider(){ + m_pDBC->setStreamValid( m_sStreamData.id, false ); +}; + +bool hardwareResourceVideoProvider::create( void ){ + LOG("Creating Local Video Source!"); + if( m_pDBC->updateLocalCam( m_sStreamData.source_id ) ){ + LOG("Cam Updated!"); + return m_pDBC->setStreamValid( m_sStreamData.id ); + }; + LOG("Cam NOT! Updated!"); + return false; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/hardwareResourceVideoProvider.h b/lib/App/common/hardwareResourceVideoProvider.h new file mode 100644 index 00000000..fab7fea5 --- /dev/null +++ b/lib/App/common/hardwareResourceVideoProvider.h @@ -0,0 +1,15 @@ +#ifndef __DFSL_HARDWARE_RESOURCE_VIDEO_HEADER__ +#define __DFSL_HARDWARE_RESOURCE_VIDEO_HEADER__ + +#include "hardwareResource.h" + +class hardwareResourceVideoProvider: public hardwareResource { + private: + DBC_MEDIA_STREAM_DATA m_sStreamData; + public: + explicit hardwareResourceVideoProvider( uint32_t id, HARDWARE_PROVIDERS type = HARDWARE_PROVIDER_VIDEO ); + virtual ~hardwareResourceVideoProvider(); + virtual bool create( void ); +}; + +#endif \ No newline at end of file diff --git a/lib/App/common/kernelEventFilter.cpp b/lib/App/common/kernelEventFilter.cpp new file mode 100644 index 00000000..db883367 --- /dev/null +++ b/lib/App/common/kernelEventFilter.cpp @@ -0,0 +1,27 @@ +#include "kernelEventFilter.h" + +kernelEventFilter::kernelEventFilter( uint32_t id, TARGET_FILTER_TYPE type ){ + m_nDBID = id; + //m_pDBC = argusDBC::getInstance(); + m_bActive = false; + m_bFilterType = type; + //if( m_pDBC != NULL ) { + //DBC_NODE_DATA *tData = NULL; + //tData = m_pDBC->getNodeData( m_nDBID ); + //if( tData != NULL ) { + // memcpy( &m_sNodeData , tData, sizeof(DBC_NODE_DATA)); + // free( tData ); + //} else { + // memset( &m_sNodeData , 0, sizeof(DBC_NODE_DATA)); + // m_sNodeData.type = ARGUS_UNKNOWN; + // m_sNodeData.node_id = id; + //}; + //} else { + //memset( &m_sNodeData , 0, sizeof(DBC_NODE_DATA)); + //m_sNodeData.type = ARGUS_UNKNOWN; + //m_sNodeData.node_id = id; + //}; +}; + +kernelEventFilter::~kernelEventFilter(){ +}; diff --git a/lib/App/common/kernelEventFilter.h b/lib/App/common/kernelEventFilter.h new file mode 100644 index 00000000..4e7a4ab4 --- /dev/null +++ b/lib/App/common/kernelEventFilter.h @@ -0,0 +1,33 @@ +#ifndef __KERNEL_EVENT_FILTER_HEADER__ +#define __KERNEL_EVENT_FILTER_HEADER__ + +#include "../../components/base/basicEvent.h" +#include "../../components/base/basicPosition.h" +#include "dataBinder.h" + +typedef enum E_TARGET_FILTER_TYPE{ + TF_UDEFINED_FILTER = 0, + TF_AUTHORISED_PEOPLE_FILTER = 1, + TF_LA_METRO_TRAIN_FILTER = 2 +}TARGET_FILTER_TYPE; + +class kernelEventFilter{ + protected: + uint32_t m_nDBID; + uint8_t m_bFilterType; + bool m_bActive; + public: + explicit kernelEventFilter( uint32_t id, TARGET_FILTER_TYPE type = TF_UDEFINED_FILTER ); + virtual ~kernelEventFilter(); + virtual bool validateTarget( uint32_t DevID, TARGET_DATA *ptr ){ return true; }; + virtual bool initFilter(){ return true; }; + virtual bool stopFilter(){ return true; }; + uint32_t getID(){ return m_nDBID; }; + uint8_t getType(){ return m_bFilterType; }; + bool pause(); + bool resume(); +}; + +typedef vector vectorKernelEventFilters; + +#endif \ No newline at end of file diff --git a/lib/App/common/kernelEventFilterAPF.cpp b/lib/App/common/kernelEventFilterAPF.cpp new file mode 100644 index 00000000..b8bfc15f --- /dev/null +++ b/lib/App/common/kernelEventFilterAPF.cpp @@ -0,0 +1,226 @@ +#include "kernelEventFilterAPF.h" + +#ifdef USE_MYSQL + #include "MySQL_dataBinder.h" +#else + #include "SQLite_dataBinder.h" +#endif + + +#define LOG( X ) m_pLog->Log( "APF", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "APF", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "APF", this, _LOG_ERROR, X ); +#endif + +kernelEventFilterAPF::kernelEventFilterAPF( uint32_t id ):kernelEventFilter( id, TF_AUTHORISED_PEOPLE_FILTER ), basicThread() { + m_iSocketFD = -1; + m_pLog = basicLogCollection::getInstance(); + m_pPosition = new basicPosition(); + m_fDeltaX = 0.5f; + m_fDeltaY = 0.5f; + m_fDeltaZ = 1.0f; +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + memset( &m_Settings, 0, sizeof(DBC_APF_DATA)); + DBC_APF_DATA *tData = m_pDBC->getAPFData( m_nDBID ); + if( tData != NULL ) { + memcpy( &m_Settings, tData, sizeof(DBC_APF_DATA)); + free( tData ); + }; +}; + +kernelEventFilterAPF::~kernelEventFilterAPF(){ + LOG("Stoping Filter!"); + stopFilter(); +}; + +bool kernelEventFilterAPF::initFilter(){ +#ifdef DEBUG + LOG("Init Started"); +#endif + struct sockaddr_in servaddr; + + // Creating socket file descriptor + if(( m_iSocketFD = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ){ + LOG_ERROR("socket creation failed"); + return false; + }; + memset(&servaddr, 0, sizeof(servaddr)); + + // Filling server information + servaddr.sin_family = AF_INET; // IPv4 + servaddr.sin_addr.s_addr = INADDR_ANY; + servaddr.sin_port = htons( m_Settings.port ); + + // Bind the socket with the server address + if( bind(m_iSocketFD, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0 ){ + LOG_ERROR( "bind failed" ); + return false; + }; + +#ifdef DEBUG + LOG("UDP PORT LISTEN"); +#endif + if( m_pPosition ) { + m_pPosition->setPositionDeg( m_Settings.lat, m_Settings.lon, m_Settings.alt, m_Settings.roll, m_Settings.pitch, m_Settings.yaw, 0.f ); + return init(); + }; + LOG_ERROR( "POSITION ERROR!" ); + stopFilter(); + return false; +}; + +bool kernelEventFilterAPF::stopFilter(){ + if( m_bActive ) { + m_bActive = false; + + int tSocketFD = -1; + struct sockaddr_in servaddr; + // Creating socket file descriptor + if(( tSocketFD = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0 ){ + LOG_ERROR("socket creation failed"); + return false; + }; + memset(&servaddr, 0, sizeof(servaddr)); + + // Filling server information + servaddr.sin_family = AF_INET; // IPv4 + servaddr.sin_addr.s_addr = INADDR_ANY; + servaddr.sin_port = htons( m_Settings.port ); + char *message="shutdown:"; + int slen=sizeof( servaddr ); + if( sendto( tSocketFD, message, strlen(message), 0 , (struct sockaddr *) &servaddr, slen) == -1 ){ + LOG_ERROR("Failure to Send Shutdown Command!"); + }; + }; + + waitThreadEnd( true ); + + if( m_iSocketFD > -1 ){ + shutdown( m_iSocketFD, 2 ); + }; + if( m_vBounds.size() ) { + for( V_BOUNDS::iterator idx = m_vBounds.begin(); idx < m_vBounds.end(); idx++ ) { + free( *idx ); + }; + m_vBounds.clear(); + }; + return true; +}; + +bool kernelEventFilterAPF::validateTarget( uint32_t DevID, TARGET_DATA *ptr ){ + if( m_bActive ) { + if( m_vBounds.size() > 0 ) { + for( V_BOUNDS::iterator idx = m_vBounds.begin(); idx < m_vBounds.end(); idx++ ) { + bool X,Y,Z; +#ifdef DEBUG + char tBuf[100]; + // COMP: -41.34x-9.50x-6.18 <> -41.78x-8.50x-15.87 + sprintf( tBuf,"COMP: %0.2fx%0.2fx%0.2f <> %0.2fx%0.2fx%0.2f", ptr->system_target.x, ptr->system_target.y, ptr->system_target.z, (*idx)->position.x, (*idx)->position.y, (*idx)->position.z ); + LOG( tBuf ); +#endif + X = ( ptr->system_target.x < (*idx)->position.x+m_fDeltaX ) && ( ptr->system_target.x > (*idx)->position.x-m_fDeltaX ); + Y = ( ptr->system_target.y < (*idx)->position.y+m_fDeltaY ) && ( ptr->system_target.y > (*idx)->position.y-m_fDeltaY ); + Z = ( ptr->system_target.z < (*idx)->position.z+m_fDeltaZ ) && ( ptr->system_target.z > (*idx)->position.z-m_fDeltaZ ); + if( X && Y && Z ) return false; + }; + }; + }; + return true; +}; + +APF_BOUNDARY *kernelEventFilterAPF::getBoxByID( CSTR id ){ + if( m_vBounds.size() ) { + for( V_BOUNDS::iterator idx = m_vBounds.begin(); idx < m_vBounds.end(); idx++ ) { + if( strstr( (*idx)->idc, id )!= NULL ){ + return (*idx); + }; + }; + }; + return NULL; +}; +void kernelEventFilterAPF::m_fThreadProc( void ){ + struct sockaddr_in CA; + socklen_t caLen; + int dLen; + char inBuff[1024]; + + caLen = sizeof(CA); + memset(&CA, 0, caLen); + m_bActive = true; + m_bThreadStatus = TH_WORKING; + while (m_bThreadStatus < TH_ENDED) { + memset( inBuff, 0, 1024 ); + if( m_bActive ){ + dLen = recvfrom( m_iSocketFD, (char *)inBuff, 1024, MSG_WAITALL, ( struct sockaddr *) &CA, &caLen ); + } else { + m_bThreadStatus = TH_ENDED; +#ifdef DEBUG + LOG( "Filter deactivated!"); +#endif + continue; + }; + if( dLen < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR( "RECV error!"); + continue; + }; + //char tB[128]; + //LOG( inBuff ); + //sprintf( tB, "Received %d Bytes", dLen ); + //LOG( tB ); + if( strstr( inBuff, "display:" ) != NULL ) { + CSTR PACK = inBuff+8; + CArray *Parts; + if( m_pPosition == NULL ) continue; + Parts = explode( ',', PACK ); + if( Parts != NULL ) { + APF_BOUNDARY * tBOX; + tBOX = getBoxByID( (*Parts)[1] ); + if( tBOX == NULL ) { + tBOX = (APF_BOUNDARY *) malloc( sizeof(APF_BOUNDARY)); + memset( tBOX, 0, sizeof(APF_BOUNDARY) ); + strncpy( tBOX->idc, (*Parts)[1], 16 ); + m_vBounds.push_back( tBOX ); + }; + systemAnchor* tSystem = systemAnchor::getInstance(); + if( tSystem != NULL ) { + C3D_DECART tDecart; + //C3D_SPH_DEGREES + C3D_SPH_RADIANS tSpherical; + tDecart.x = atof( (*Parts)[6] );//Y + tDecart.y = atof( (*Parts)[5] );//X + tDecart.z = atof( (*Parts)[7] );//Z + decart2spherical( tDecart, tSpherical ); + tSystem->convertToSystem( m_pPosition, tSpherical, tBOX->position ); + m_pDBC->updateAFPBox( m_nDBID, (*Parts)[1], tDecart.x, tDecart.y, tDecart.z ); + } else { + LOG_ERROR("No SYSTEM ANCHOR!"); + } + delete( Parts ); + }; + }; + if( strstr( inBuff, "shutdown:" ) != NULL ){ + m_bThreadStatus = TH_ENDED; +#ifdef DEBUG + LOG( "Shutdown Requested!"); +#endif + continue; + }; + SLEEP( 2 ); + }; +}; + + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/kernelEventFilterAPF.h b/lib/App/common/kernelEventFilterAPF.h new file mode 100644 index 00000000..be73c3eb --- /dev/null +++ b/lib/App/common/kernelEventFilterAPF.h @@ -0,0 +1,41 @@ +#ifndef __KERNEL_EVENT_FILTER_APF_HEADER__ +#define __KERNEL_EVENT_FILTER_APF_HEADER__ + +#include "kernelEventFilter.h" +#include "../../components/object/objectSystemAnchor.h" +#include "../../components/base/basicThread.h" + +#include "dataBinder.h" + +typedef struct S_APF_BOUNDARY{ + char idc[16]; + C3D_DECART position; +}APF_BOUNDARY; + +typedef vector V_BOUNDS; + +class kernelEventFilterAPF: public kernelEventFilter, public basicThread{ + private: + basicLogCollection * m_pLog; + basicPosition * m_pPosition; + int m_iSocketFD; + V_BOUNDS m_vBounds; + DBC_APF_DATA m_Settings; + dataBinder * m_pDBC; + /* CUBE DEFENITION IN METERS */ + float m_fDeltaX; + float m_fDeltaY; + float m_fDeltaZ; + + APF_BOUNDARY * getBoxByID( CSTR id ); + protected: + virtual void m_fThreadProc( void ); + public: + explicit kernelEventFilterAPF( uint32_t id ); + virtual ~kernelEventFilterAPF(); + virtual bool initFilter(); + virtual bool stopFilter(); + virtual bool validateTarget( uint32_t DevID, TARGET_DATA *ptr ); +}; + +#endif diff --git a/lib/App/common/kernelModule.cpp b/lib/App/common/kernelModule.cpp new file mode 100644 index 00000000..176b85b1 --- /dev/null +++ b/lib/App/common/kernelModule.cpp @@ -0,0 +1,38 @@ +#include "kernelModule.h" + +#ifdef USE_MYSQL + #include "MySQL_dataBinder.h" +#else + #include "SQLite_dataBinder.h" +#endif + +kernelModule::kernelModule( uint32_t id, KERNEL_MODULE_TYPE type ): basicEventHandler(), basicObject(){ + m_pLog = basicLogCollection::getInstance(); +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + //m_pKernel = argusKernel::getInstance(); + m_eType = type; + m_nDBID = id; + m_bDetached = false; + m_bEnabled = false; + m_nDBAUXID = 0; + + // Clear Events flags + if( m_pDBC ) { + DBC_MODULE_DATA *tData = NULL; + tData = m_pDBC->getModuleData( m_nDBID ); + if( tData ) { + m_nDBAUXID = tData->aux_id; + m_bEnabled = tData->enabled; + free( tData ); + }; + }; + for( int i = 0; i < EVT_COUNT; i++ ) m_bEvtFlags[i] = false; +}; + +kernelModule::~kernelModule(){ +}; + diff --git a/lib/App/common/kernelModule.h b/lib/App/common/kernelModule.h new file mode 100644 index 00000000..d1bdd5c7 --- /dev/null +++ b/lib/App/common/kernelModule.h @@ -0,0 +1,58 @@ +#ifndef __DFSL_KERNEL_MODULE_HEADER__ +#define __DFSL_KERNEL_MODULE_HEADER__ + +#include + +#include "../../components/base/basicObject.h" +#include "../../components/base/basicEngine.h" +#include "../../components/base/basicEventHandler.h" +#include "../../components/base/basicLogCollection.h" +#include "dataBinder.h" + + +typedef enum E_KERNEL_MODULE_TYPE{ + KERNEL_MODULE_UNKNOWN = 0, + //KERNEL_MODULE_ZLMEDIA = 1, + KERNEL_MODULE_DCBUSB = 1, + KERNEL_MODULE_KAFKA = 2, + KERNEL_MODULE_GPS = 3, + KERNEL_MODULE_NETWORK = 4, + KERNEL_MODULE_FLYHUNTER = 5, + KERNEL_MODULE_SSDP_ANONCE = 6, + KERNEL_MODULE_ONVIF_OBSERVER = 7, + KERNEL_MODULE_EMBED_VIDEO = 8, + KERNEL_MODULE_MODEM_MANAGER = 9 +}KERNEL_MODULE_TYPE; + +class kernelModule: public basicEventHandler, basicObject{ + protected: + basicLogCollection * m_pLog; + dataBinder * m_pDBC; + uint32_t m_nDBID; + uint32_t m_nDBAUXID; + bool m_bEnabled; + bool m_bDetached; + bool m_bEvtFlags[EVT_COUNT]; + KERNEL_MODULE_TYPE m_eType; + public: + explicit kernelModule( uint32_t id, KERNEL_MODULE_TYPE type = KERNEL_MODULE_UNKNOWN ); + virtual ~kernelModule(); + uint32_t getId() const { return m_nDBID; }; + uint32_t getAuxId() const { return m_nDBAUXID; }; + KERNEL_MODULE_TYPE getType() const { return m_eType; }; + bool isDetached() const { return m_bDetached; }; + bool isAttached() const { return !m_bDetached; }; + bool isEnabled() const { return m_bEnabled;}; + virtual bool reloadSettings(){ return false; }; + void setAttached( bool b=true ){ m_bDetached = !b; }; + void setDetached( bool b=true ){ m_bDetached = b; }; + virtual bool startService(){ return false; }; + virtual bool stopService( bool force = false ){ return true; }; + virtual bool validate(){ return false; }; + virtual void dispatchEvent( EVENT_CONTAINER *Evt ){}; +}; + +typedef std::vector vectorKernelModules; + +#endif + diff --git a/lib/App/common/kernelModuleEmbedVideo.cpp b/lib/App/common/kernelModuleEmbedVideo.cpp new file mode 100644 index 00000000..e889ceea --- /dev/null +++ b/lib/App/common/kernelModuleEmbedVideo.cpp @@ -0,0 +1,2211 @@ +#include "kernelModuleEmbedVideo.h" +//#include "rgooseHardwareResourceNetworkProvider.h" +//#include "mojoKernel.h" +#include "../alg/generic/base64.h" + +#include "../data/media/video/videoAVLIBSource.h" +#include "../data/media/video/videoLive555AVLibSource.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* MIN() */ +#include +#include + + +#define STORAGE_DIR_MODE 0x1FF +#define STORAGE_FILE_MODE 0x1B6 + + +#define LOG( X ) kernelModule::m_pLog->Log( "MOD_EVIDEO", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + kernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) kernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, X ); +#endif + +#define TLOG( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, X ) +#ifdef DEBUG + #define TLOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, X ); +#endif + +enum { + WEBRTC_REQ_SIGNIN = 0, + WEBRTC_REQ_WAIT = 1, + WEBRTC_REQ_SIGNOUT = 2, + WEBRTC_REQ_MESSAGE = 3 +}; + +static const char* kRequestPaths[] = { "/stream", "/sign_in", "/wait", "/sign_out", "/message" }; + +//buffer_data bd[1]={0}; + +kernelModuleEmbedVideo::kernelModuleEmbedVideo( uint32_t moduleID ): kernelModule( moduleID, KERNEL_MODULE_EMBED_VIDEO ), basicThread(){ + m_pEventHeap = basicEventHeap::getInstance(); + if( m_pDBC ){ + DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); + if( tDATA ) { + memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); + free( tDATA ); + } else { + memset( &m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); + m_sEmbedVideoData.port = 8972; + }; + } else { + LOG_ERROR( "DB Error!" ); + }; + n_pNoSignalData = NULL; + m_nNoSignalSize = 0; + char tBuff[1024]; + sprintf( m_pBaseSavePath, "%s/data/reports", getcwd(tBuff, 1024) ); +#ifdef DEBUG + char tB[64]; + sprintf( tB, "Web Streams Port: %d", m_sEmbedVideoData.port ); + LOG( tB ); + sprintf( tB, "Frame: [%dx%d]", m_sEmbedVideoData.width, m_sEmbedVideoData.height ); + LOG( tB ); + if( m_sEmbedVideoData.show_ts ) LOG("Show TimeStamp"); + if( m_sEmbedVideoData.show_label ) LOG("Show Label"); + if( m_sEmbedVideoData.show_logo ) LOG("Show Logo"); +#endif + if( m_sEmbedVideoData.show_logo ){ + LOG( m_sEmbedVideoData.logo_md5 ); + char tPath[MAX_PATH]; + sprintf( tPath, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5 ); + if( !fileExist( tPath ) ){ + LOG_ERROR("Logo File Missed!"); + m_sEmbedVideoData.show_logo = false; + } +#ifdef DEBUG + else LOG("Logo File is OK"); +#endif + ; + }; +}; + +kernelModuleEmbedVideo::~kernelModuleEmbedVideo(){ + m_bEnabled = false; + waitThreadEnd( true ); + if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes +#ifdef DEBUG + char tB[200]; + sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() ); + LOG( tB ); + +#endif + for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) pthread_cancel( (*index)->m_hThreadHandle ); + m_vHandlersPool.clear(); + }; +#ifdef DEBUG + LOG("No More Client Handlers!"); +#endif + if( m_mapHANDLERS.size() ){ + for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) delete( (*idx).second ); + m_mapHANDLERS.clear(); + }; + if( m_mapCAPTURES.size() ) m_mapCAPTURES.clear(); + if( m_mapMATS.size() ) m_mapMATS.clear(); + if( n_pNoSignalData ) free(n_pNoSignalData); +}; + +static const char * ht_head = "HTTP/1.1 200 OK\r\n" + "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" + "Pragma: no-cache\r\n" + "MIME-version: 1.0\r\n" + "Connection: close\r\n" + //"Keep-Alive: timeout=5, max=1\r\n" + //"Connection: Keep-Alive\r\n" + //"Content-Type: video/mp4\r\n" + "Content-Transfer-Encoding: BINARY\r\n" + //"Transfer-Encoding: chunked\r\n" + "Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n" + "\r\n"; +static const char * ht_abort = "HTTP/1.1 404 OK\r\n" + "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" + "Pragma: no-cache\r\n" + "Connection: close\r\n\r\n"; +static const char * ht_no_signal = "HTTP/1.1 200 OK\r\n" + "MIME-version: 1.0\r\n" + "Connection: close\r\n" + "Content-Transfer-Encoding: BINARY\r\n" + //"Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n\r\n" + "Content-Type: image/jpeg\r\nContent-length: %d\r\n\r\n"; + +void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ + + + WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; + kernelModuleEmbedVideo * MODULE = CTX->ModulePtr; + uint32_t msgSize; + uint8_t tBuf[FILESTREAMBUFFERSZ]; + int retVal; + + if( CTX ) { + char mesg[1024]; + size_t RecvSize; + struct pollfd pfd[1]; + char cGetURI[1024]; + bool m_bDeflatePerMessage = false; + bool m_pInit; + +#ifdef DEBUG_EXTRA + pid_t pid = gettid(); + char pidBuf[16]; + sprintf( pidBuf, "pid:%d", pid); + TLOG( pidBuf ); +#endif + + pfd->fd = CTX->m_iSocketFID; + pfd->events = POLLIN | POLLHUP; + + while( CTX->bValid ) { + if( !CTX->initDone ){ + int RetVal; + char * reqline[256]; + RetVal = poll( pfd, 1, 1000 ); + if( RetVal <= 0 ){ + if ( EINTR == errno ) continue; + TLOG_ERROR("Unrecoverable error"); + CTX->bValid = false; + continue; + }; + memset( mesg, 0, sizeof(mesg) ); + + RetVal = recv( CTX->m_iSocketFID, mesg, sizeof(mesg), 0 ); + + if ( RetVal <= 0 ) { + sprintf( mesg, "web recv() error: %s", strerror(errno)); + TLOG_ERROR( mesg ); + CTX->bValid = false; + continue; + }; +#ifdef DEBUG_EXTRA + TLOG( mesg ); +#endif + + uint32_t index = 0; + reqline[index] = strtok( mesg, "\n" ); + if( strncmp( reqline[index], "GET", 3 ) == 0 ) { + char * pPartURI; + char * pPartPROTO; + pPartURI = strstr( reqline[index], " " ); + if( pPartURI != NULL ) { + pPartURI++; + pPartPROTO = strstr( pPartURI, " " ); + pPartPROTO++; + int URILen = pPartPROTO - pPartURI; + strncpy( cGetURI, pPartURI, URILen ); + cGetURI[URILen] = (char)0; + if(strncmp( pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp( pPartPROTO, "HTTP/1.1", 8) != 0) { + TLOG_ERROR("No HTTP version supplied in request!"); + if( write( CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0 ){ + sprintf( mesg, "Failed returning status 400 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + }; + CTX->bValid = false; + continue; + }; + }; +#ifdef DEBUG_EXTRA + TLOG( cGetURI ); +#endif + }; + + if( strncmp( cGetURI, "/stream", 7 ) == 0 ) { + uint32_t tStreamID = 0; + CSTR tP; + if( tP = strstr( cGetURI, "?" ) ) { + CSTR tB; + tP++; + if( tB = strstr( tP, "id=" ) ) { + tStreamID = atoi( tB+3 ); + }; + }; + if( tStreamID ) { +#ifdef DEBUG_EXTRA + char tB[64]; + sprintf(tB,"StremID: %d", tStreamID ); + TLOG( tB ); +#endif + if( CTX->ModulePtr->registerForMediaStream( tStreamID, CTX ) ){ + // Send Header + if( send( CTX->m_iSocketFID, ht_head, strlen(ht_head), 0 ) < 0 ){ +#ifdef DEBUG_EXTRA + sprintf( mesg, "Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); +#endif + CTX->bValid = false; + }; + CTX->initDone = true; + continue; + } +#ifdef DEBUG_EXTRA + else { + TLOG("Stream id Not Online"); + } +#endif + ; + } +#ifdef DEBUG_EXTRA + else TLOG("No Stream ID") +#endif + ; + }; + if( CTX->ModulePtr->n_pNoSignalData ) { + //Send Dummy Picture + sprintf( mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSize ); + send( CTX->m_iSocketFID, mesg, strlen(mesg), 0 ); + send( CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0 ); + send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 ); +#ifdef DEBUG_EXTRA + TLOG("Sent No Signal Image!"); +#endif + } else { + // Send 404 Header + send( CTX->m_iSocketFID, ht_abort, strlen(ht_abort), 0 ); +#ifdef DEBUG_EXTRA + TLOG("Aborted!"); +#endif + }; + CTX->bValid = false; + continue; + } else { + /* + retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t)); + if( retVal == -1 ){ + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[1]!"); + CTX->bValid = false; + continue; + }; + if( msgSize < FILESTREAMBUFFERSZ ) { + retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize ); + } else { + TLOG_ERROR("Data too Big in Pipe Transfer!"); + CTX->bValid = false; + continue; + }; + if( retVal == -1 ){ + //free( tBuf ); + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[2]!"); + CTX->bValid = false; + continue; + }; + */ + /**************/ + CTX->ModulePtr->m_mEncodedProtector.lock(); + if( CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size() ) { + msgSize = CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size(); + if( msgSize < FILESTREAMBUFFERSZ ) { + memcpy( tBuf, CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].data(), msgSize ); + CTX->ModulePtr->m_mEncodedProtector.unlock(); + } else { + CTX->ModulePtr->m_mEncodedProtector.unlock(); + TLOG_ERROR("Data too Big in Pipe Transfer!"); + CTX->bValid = false; + continue; + }; + } else { + CTX->ModulePtr->m_mEncodedProtector.unlock(); + if( CTX->ModulePtr->n_pNoSignalData ){ + msgSize = CTX->ModulePtr->m_nNoSignalSize; + memcpy( tBuf, CTX->ModulePtr->n_pNoSignalData, msgSize ); + } else { + TLOG_ERROR("Data too Big in Pipe Transfer!"); + CTX->bValid = false; + continue; + }; + }; + /*********/ + sprintf( mesg, "--MPFrame\r\nContent-type: image/jpeg\r\nContent-length: %d\r\n\r\n", msgSize ); + if( send( CTX->m_iSocketFID, mesg, strlen( mesg ), 0 )< 0 ){ +#ifdef DEBUG_EXTRA + sprintf( mesg, "[1]Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); +#endif + CTX->bValid = false; + continue; + }; + if( send( CTX->m_iSocketFID, tBuf, msgSize, 0 ) < 0 ){ +#ifdef DEBUG_EXTRA + sprintf( mesg, "[2]Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); +#endif + CTX->bValid = false; + continue; + }; + if( send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 )< 0 ){ +#ifdef DEBUG_EXTRA + sprintf( mesg, "[3]Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); +#endif + CTX->bValid = false; + continue; + }; + SLEEP( 80 ); + }; + }; + }; + CTX->bValid = false; +#ifdef DEBUG_EXTRA + TLOG("WEB Client Handler Ended!"); +#endif + close( CTX->m_iEncoderPipe[0] ); + shutdown( CTX->m_iSocketFID, SHUT_RDWR); + close( CTX->m_iSocketFID ); + //pthread_exit( NULL ); + return NULL; +}; + +void kernelModuleEmbedVideo::m_fThreadProc( void ){ + if( !m_bEnabled ) { +#ifdef DEBUG + LOG("Module is Disabled!"); +#endif + return; + }; +#ifdef DEBUG + LOG("Module Started!"); +#endif + struct pollfd pfd[1]; + pfd->fd = m_nSocketDescriptor; + pfd->events = POLLIN | POLLHUP; + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { + if( !m_bEnabled ) { + m_bThreadStatus = TH_ENDED; + continue; + }; + int RetVal = poll( pfd, 1, 1000 ); + if( RetVal < 0 ){ + if( EINTR == errno ) continue; + LOG_ERROR("Unrecoverable error"); + m_bThreadStatus = TH_ENDED; + continue; + }; + // Handle Connections + if( RetVal != 0 ){ + if ( pfd[0].revents & POLLIN ) { +#ifdef DEBUG_EXTRA + LOG("Handle New Client"); +#endif + int tSID = accept( pfd[0].fd, NULL, NULL); + if( tSID < 0 ){ + char tBuf[CTEXT]; + sprintf(tBuf, "Accept() error: %s", strerror(errno)); + LOG_ERROR(tBuf); + } else { +#ifdef DEBUG_EXTRA + LOG("Accept OK"); +#endif + WEB_CLIENT_CTX *tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX)); + if( tCTX ) { +#ifdef DEBUG_EXTRA + LOG("CTX OK"); +#endif + WEB_HANDLER *tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER)); + if( tHANDLER ) { +#ifdef DEBUG_EXTRA + LOG("HANDLER OK"); +#endif + memset( tCTX, 0, sizeof(WEB_CLIENT_CTX) ); + memset( tHANDLER, 0, sizeof(WEB_HANDLER) ); + tCTX->m_iSocketFID = tSID; + tCTX->m_iEncoderPipe[0] = -1; + tCTX->m_iEncoderPipe[1] = -1; + tCTX->mediaStreamId = 0; + tCTX->bValid = true; + tCTX->ModulePtr = this; +#ifdef DEBUG_EXTRA + LOG("Before Thread Create"); +#endif + int RetVal = pthread_create( &tHANDLER->m_hThreadHandle, NULL, webClientProc, ( void * ) tCTX ); + if( RetVal == -1 ) { + free(tCTX); + free(tHANDLER); + LOG_ERROR("Thread Creation Faled."); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + } else { + tHANDLER->CTX = tCTX; + m_mHandlersProtector.lock(); + m_vHandlersPool.push_back( tHANDLER ); + m_mHandlersProtector.unlock(); +#ifdef DEBUG_EXTRA + LOG("Handler Pushed to a Pool"); +#endif + }; + } else { //https://stackoverflow.com/questions/18545077/image-fullscreen-on-click + free(tCTX); + LOG_ERROR("CL_HANDLER Mem Allocation Failure!"); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + }; + } else { + LOG_ERROR("CL_CTX Mem Allocation Failure!"); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + }; + }; + }; + }; + // Handle Dead Clients + if( m_vHandlersPool.size() ) { + for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) { + if( !( (*idx)->CTX->bValid ) ) { + pthread_join( (*idx)->m_hThreadHandle, NULL ); + //close( (*idx)->CTX->m_iEncoderPipe[0] ); + close( (*idx)->CTX->m_iEncoderPipe[1] ); + free( (*idx)->CTX ); + free( (*idx) ); + m_mHandlersProtector.lock(); + m_vHandlersPool.erase(idx); + m_mHandlersProtector.unlock(); +#ifdef DEBUG_EXTRA + LOG("Web Handler Ripped!"); +#endif + }; + }; + + }; + // validate active streams ? + + SLEEP( 50 ); + }; +}; + +#define ENABLE_SOCKOPT(sd, level, opt) \ + do { \ + int val = 1; \ + if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \ + warn("Failed enabling %s for web service", #opt); \ + } while (0); + + +bool kernelModuleEmbedVideo::startService(){ + m_bEnabled = true; + //Create NoSignal Image + cv::Mat tMat( m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3 ); + cv::rectangle( tMat, cv::Point( 0, 0 ), cv::Point( m_sEmbedVideoData.width, m_sEmbedVideoData.height ), cv::Scalar( 255, 0, 0 ), cv::FILLED ); + cv::putText( tMat, "NO SIGNAL", cv::Point( 10, 30 ), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar( 0, 255, 255 ), 3 ); + if( m_sEmbedVideoData.show_logo ) { + int a_x, a_y; + if( m_sEmbedVideoData.logo_x < 0 ) { + a_x = m_sEmbedVideoData.width + m_sEmbedVideoData.logo_x - m_sEmbedVideoData.logo_w; + if( a_x < 0 ) a_x = 0; + } else a_x = m_sEmbedVideoData.logo_x; + if( ( a_x + m_sEmbedVideoData.logo_w ) > m_sEmbedVideoData.width ) a_x = m_sEmbedVideoData.width - m_sEmbedVideoData.logo_w; + if( m_sEmbedVideoData.logo_y < 0 ) { + a_y = m_sEmbedVideoData.height + m_sEmbedVideoData.logo_y - m_sEmbedVideoData.logo_h; + if( a_y < 0 ) a_y = 0; + } else a_y = m_sEmbedVideoData.logo_y; + if( ( a_y + m_sEmbedVideoData.logo_h ) > m_sEmbedVideoData.height ) a_y = m_sEmbedVideoData.height - m_sEmbedVideoData.logo_h; + if( ( a_x > -1 ) && ( a_y > -1 ) ) { + char tName[256]; + m_sEmbedVideoData.logo_x = a_x; + m_sEmbedVideoData.logo_y = a_y; + sprintf( tName, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5 ); + cv::Mat T = cv::imread( tName, cv::IMREAD_UNCHANGED ); + if( T.cols > 0 ) { + cv::Mat mask; + vector layers; +#ifdef DEBUG + LOG("Logo Loaded OK"); +#endif + cv::split( T, layers); // seperate channels + cv::Mat rgb[3] = { layers[0], layers[1], layers[2] }; + mask = layers[3]; // png's alpha channel used as mask + cv::merge( rgb, 3, T ); // put together the RGB channels, now transp insn't transparent + + cv::resize( T, m_mLogoPic, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC ); + cv::resize( mask, m_mLogoMask, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC ); + + cv::Rect roi(cv::Point( m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y ), cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h )); + cv::Mat destinationROI = tMat( roi ); + m_mLogoPic.copyTo( destinationROI, m_mLogoMask ); + //m_sEmbedVideoData.show_logo = false; + } else { + LOG("Logo Disabled - No Picture is Loaded"); + m_sEmbedVideoData.show_logo = false; + }; + } else { + LOG("Logo Disabled - Wrong Coords"); + m_sEmbedVideoData.show_logo = false; + }; + LOG("Logo Draw OK"); + }; + + try{ + vector compression_params; + //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + //compression_params.push_back(9); + compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); + compression_params.push_back( m_sEmbedVideoData.compression_quality ); + vector buf; + cv::imencode( ".jpg", tMat, buf, compression_params ); + m_nNoSignalSize = buf.size(); + n_pNoSignalData = (uint8_t *) malloc( m_nNoSignalSize ); + if( n_pNoSignalData ) { + memcpy( n_pNoSignalData, buf.data(), m_nNoSignalSize ); + } else m_nNoSignalSize =0; + buf.clear(); + } catch (cv::Exception & e) { + LOG_ERROR(e.msg.c_str()); + }; + + // Socket + struct sockaddr sa; + struct sockaddr_in *sin; + memset(&sa, 0, sizeof(struct sockaddr)); + sa.sa_family = AF_INET; + sin = (struct sockaddr_in *)&sa; + sin->sin_addr.s_addr = htonl( INADDR_ANY ); + sin->sin_port = htons( m_sEmbedVideoData.port ); + + m_nSocketDescriptor = socket( sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); + if( m_nSocketDescriptor == -1 ){ + LOG_ERROR("Failed creating ACC socket"); + return false; + }; + ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEADDR); +#ifdef SO_REUSEPORT + ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEPORT); +#endif + if( bind( m_nSocketDescriptor, &sa, sizeof(sa)) < 0 ){ + LOG_ERROR("Failed binding Socket"); + close( m_nSocketDescriptor ); + return false; + } else { + LOG("Bind Socessfull"); + }; + if( listen( m_nSocketDescriptor, 10) != 0 ){ + LOG_ERROR("Failed setting web listen backlog"); + close( m_nSocketDescriptor ); + return false; + } else { + LOG("Listen OK"); + }; + LOG("Start Thread"); + m_bEnabled = init(); + return m_bEnabled; +}; + +bool kernelModuleEmbedVideo::stopService( bool force ){ + m_bEnabled = false; + m_bDetached = uninit(); +#ifdef DEBUG + LOG("Service Thread ended!"); +#endif + if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes +#ifdef DEBUG + char tB[200]; + sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() ); + LOG( tB ); + +#endif + for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) { + if( force ) { +#ifdef DEBUG + LOG("Force Client Handler to Stop!"); +#endif + pthread_cancel( (*index)->m_hThreadHandle ); + } else { +#ifdef DEBUG + LOG("Waiting Client Handler to End!"); +#endif + pthread_join( (*index)->m_hThreadHandle, NULL ); + } + }; + m_vHandlersPool.clear(); + }; +#ifdef DEBUG + LOG("No More Client Handlers!"); +#endif + if( m_mapCAPTURES.size() ){ + m_mapCAPTURES.clear(); + //for( mapSTREAMCAPS::iterator idx = m_mapCAPTURES.begin(); idx < m_mapCAPTURES.end(); idx++ ) { + //}; + }; + if( m_mapMATS.size() ){ + m_mapMATS.clear(); + //for( mapSTREAMMAPS::iterator idx = m_mapMATS.begin(); idx < m_mapMATS.end(); idx++ ) { + //}; + }; + if ( n_pNoSignalData ) { + free( n_pNoSignalData ); + n_pNoSignalData = NULL; + m_nNoSignalSize = 0; + }; + return m_bDetached; +}; + +bool kernelModuleEmbedVideo::reloadSettings(){ + LOG("Reload Service"); + if( m_pDBC ){ + DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); + if( tDATA ) { + if( stopService() ){ + LOG("Stoped!"); + memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); + free( tDATA ); + LOG("Starting..."); + return startService(); + } else { + free( tDATA ); + }; + }; + }; + return false; +}; + +bool kernelModuleEmbedVideo::validate(){ + bool RetVal = true; + if( m_pDBC ){ + DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); + if( tDATA ) { + if( memcmp( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)) != 0 ){ + free( tDATA ); + LOG("Module Settings Changed!"); + return reloadSettings(); + }; + free( tDATA ); + } else { + RetVal = false; + }; + if ( RetVal ) { + DBC_INT_LIST *tList = m_pDBC->listMediaStreams(0, LIST_VALID_RECORDS); + if ( tList != NULL ) { + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ){ + if( !registerStream( *idx ) ){ + RetVal = false; + break; + }; + }; + delete ( tList ); + }; + }; + if ( RetVal ) { + for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) { + if ( !(*idx).second->validate() ) { + RetVal = false; + }; + }; + }; + } else { + LOG_ERROR( "DB Error!" ); + RetVal = false; + }; + return RetVal; +}; + +bool kernelModuleEmbedVideo::registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ){ + if( CTX ){ + if( id ){ + //Check if its Valid! + DBC_MEDIA_STREAM_DATA *tSD = m_pDBC->getMediaStreamData( id ); + if( tSD ) { + //if( !tSD->valid ) { + // free( tSD ); + // return false; + //}; + free( tSD ); + //if( pipe( CTX->m_iEncoderPipe ) == -1 ){ + // CTX->bValid = false; + // return false; + //}; + CTX->mediaStreamId = id; + return true; + }; + }; + } else LOG_ERROR("Client Context error!"); + return false; +}; + +void kernelModuleEmbedVideo::dispatchEvent( EVENT_CONTAINER *Evt ){ + if( Evt ) { + switch( Evt->m_eClass ) { + case EVT_CLASS_IMAGE: + case EVT_CLASS_VIDEO:{ + switch( Evt->m_eType ) { + case EVT_CAPTURE_START:{ +#ifdef DEBUG + LOG("Capture Event"); +#endif + if( Evt->m_ref_id && Evt->m_db_id ){ + uint32_t tPicID = saveStreamPicture( Evt->m_ref_id ); + if( tPicID ){ + // + //m_pDBC->addPictureEvent( Evt->m_db_id, tPicID ); + } else { +#ifdef DEBUG + LOG_ERROR("No Picture is Saved!"); +#endif + }; + } else { +#ifdef DEBUG + LOG_ERROR("No Stream ID or Event ID in Event Data!"); +#endif + }; + break; + }; + }; + break; + }; + case EVT_CLASS_CAMERA_CTRL:{ + switch ( Evt->m_eType ) { + case EVT_CAMERA_MOVE_TO:{ + uint32_t sid = m_pDBC->getNodeAuxParam( Evt->m_nSourceNodeID ); + if ( sid ) { + mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find(sid); + if( hnd != m_mapHANDLERS.end() ){ + (*hnd).second->triggerCamMove(); + }; + } + break; + }; + case EVT_CAMERA_ON_POSITION:{ +#ifdef DEBUG + LOG("Cam On Position After Event -> Capture Picture"); +#endif + DBC_SNAPSHOT_DATA *tData = (DBC_SNAPSHOT_DATA *) Evt->m_pEvtData; + if( tData ){ + if( !saveStreamPicture( tData ) ) LOG_ERROR("Save Error!"); + tData->assoc_event_ids.clear(); + delete( tData ); + Evt->m_pEvtData = NULL; + } else LOG_ERROR("No Evt Data!"); + break; + }; + }; + break; + }; + }; + }; +}; +//https://www.ps2-home.com/forum/viewtopic.php?t=98 +//https://www.mikekohn.net/software/playstation2.php + +bool kernelModuleEmbedVideo::saveStreamPicture( DBC_SNAPSHOT_DATA *ptr ){ + + if( ptr == NULL ) return false; + + if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){ + LOG("Saving Picture!"); + if( ptr->assoc_event_ids.size() ){ + if( m_mapCAPTURES.find( ptr->stream_id ) != m_mapCAPTURES.end() ){ + m_mPictureProtector.lock(); + ptr->data = (uint8_t *) malloc( m_mapCAPTURES[ptr->stream_id].size() ); + if( ptr->data ){ + ptr->data_size = m_mapCAPTURES[ptr->stream_id].size(); + memcpy( ptr->data, m_mapCAPTURES[ptr->stream_id].data(), ptr->data_size ); + m_mPictureProtector.unlock(); + CSTR MD5 = MD5Binary( ptr->data, ptr->data_size ); + if( MD5 ){ + strncpy( ptr->md5, MD5, 32 ); + free( MD5 ); + if( !m_pDBC->addPicture( ptr, "jpg" ) ) LOG_ERROR("Database Error to consume capture!"); + } else LOG_ERROR("no MD5 Hash!"); + free( ptr->data ); + } else { + m_mPictureProtector.unlock(); + LOG_ERROR("No memory to allocate!"); + }; +#ifdef DEBUG + } else { + LOG("No apropriate Stream Found!"); +#endif + }; + }; + }; + if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO ){ + LOG("Saving Video!"); + if( ptr->assoc_event_ids.size() ){ + mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find( ptr->stream_id ); + if( hnd != m_mapHANDLERS.end() ){ + uint32_t db_id; + uint32_t cfrm; + if( (*hnd).second->triggerEvent( db_id, cfrm ) ){ + for( DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++ ){ + m_pDBC->addVideoEvent( (*idx), db_id, cfrm ); + }; + }; + }; + }; + }; + return true; +}; + +bool kernelModuleEmbedVideo::saveStreamPicture( uint32_t id ){ + if( !id ) return false; + if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){ + if( m_mapCAPTURES.find(id) != m_mapCAPTURES.end() ){ + FILE * tFD; + m_mPictureProtector.lock(); + size_t tBufferSize = m_mapCAPTURES[id].size(); + uint8_t * tBuffer = (uint8_t *) malloc( tBufferSize ); + if( tBuffer ){ + memcpy( tBuffer, m_mapCAPTURES[id].data(), tBufferSize ); + m_mPictureProtector.unlock(); + CSTR MD5 = MD5Binary( tBuffer, tBufferSize ); + if( MD5 ){ + char tFileName[MAX_PATH]; + if( generateSavePicPath( MD5, tFileName ) ){ + FILE *fd = fopen( tFileName, "wb+" ); + if( fd ){ + fwrite(tBuffer, 1, tBufferSize, fd ); + fclose(fd); + chown( tFileName, "nobody", "nogroup" ); + //retVal = m_pDBC->addPicture( id, MD5, "jpg" ); + } else LOG_ERROR("Can not open picture file!"); + } else LOG_ERROR("Can not generate file name!"); + free(MD5); + } else LOG_ERROR("no MD5 Hash!"); + free(tBuffer); + } else { + m_mPictureProtector.unlock(); + LOG_ERROR("no memory to allocate!"); + }; + }; + } + return true; +}; + +int kernelModuleEmbedVideo::getWidh( void ){ + if( m_sEmbedVideoData.width ) return m_sEmbedVideoData.width; + return -1; +}; + +int kernelModuleEmbedVideo::getHeight( void ){ + if( m_sEmbedVideoData.height ) return m_sEmbedVideoData.height; + return -1; +}; + +bool kernelModuleEmbedVideo::generateSavePicPath( CSTR MD5, CSTR Output ){ + if( MD5 == NULL ) return false; + if( Output == NULL ) return false; + if( !fileExist( m_pBaseSavePath ) ) { + LOG_ERROR("No Base Picture Save Path Defined!"); + return false; + }; + if( strlen(MD5) < 4 ) return false; + char test[MAX_PATH]; + sprintf( test, "%s/%c%c", m_pBaseSavePath, MD5[0], MD5[1] ); + if( !fileExist( test ) ) { +#ifdef __linux__ + mkdir( test, STORAGE_DIR_MODE ); +#else + _mkdir( test ); +#endif + chown( test, "nobody", "nogroup" ); + }; + sprintf( test, "%s/%c%c/%c%c", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3] ); + if( !fileExist( test ) ) { +#ifdef __linux__ + mkdir( test, STORAGE_DIR_MODE ); +#else + _mkdir( test ); +#endif + chown( test, "nobody", "nogroup" ); + }; + sprintf( Output, "%s/%c%c/%c%c/%s.jpg", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3], MD5 ); + return true; +}; + +bool kernelModuleEmbedVideo::registerStream( uint32_t streamID ){ + //Check if stream is not allready exists + //for ( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ){ + // if ( (*idx)->CTX->mediaStreamId == streamID ) return true; + //}; + + try { + streamHandler * tData = m_mapHANDLERS.at( streamID ); + if( tData!= NULL ) return true; + } catch (const std::out_of_range& oor ) { + //std::cerr << "Out of Range error: " << oor.what() << '\n'; + m_mapHANDLERS[streamID] = new streamHandler( this ); + if ( m_mapHANDLERS[streamID] != NULL ) return m_mapHANDLERS[streamID]->create( m_pDBC, streamID ); + }; + return false; +}; + +bool kernelModuleEmbedVideo::unregisterStream( uint32_t streamID ){ + return true; +}; + +#undef LOG +#undef LOG_ERROR + +#define LOG( X ) streamHandler::m_pLog->Log( "MEV_STR", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, X ); +#endif + + +streamHandler::streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_pMaster( ptr ), m_eWM( M ), basicMediaDestination() { + m_pLog = basicLogCollection::getInstance( ); + memset( &m_sStreamData, 0, sizeof( DBC_MEDIA_STREAM_DATA ) ); + m_pSource = NULL; + m_bEvtMarkerCounter = 0; + m_bCamMoveCounter = 0; +#ifdef EVE_ENABLE_VIDEO + m_nPreAlarmFrames = 0; + m_nPostAlarmFrames = 0; + m_nSegAFrameCounter = 0; + m_nSegBFrameCounter = 0; + m_nGlobalFrameCounter = 0; + m_nVideoRegisteredDBID = 0; + m_nSegAShiftFrames = 0; + m_nSegBShiftFrames = 0; + m_nSegASkippedFrames = m_nSegBSkippedFrames = 0; + m_nSegmentLimitFrames = 0; + m_nHardLimitFrames = 0; + m_bActiveEncoderStream = 0; + m_bSegAActive = false; + m_bSegADelete = true; + m_bSegBActive = false; + m_bSegBDelete = true; + m_bCOP = 0; +#endif //EVE_ENABLE_VIDEO +}; + +streamHandler::~streamHandler(){ + LOG("DESTRUCT!"); + if ( m_sStreamData.id ) { + if (m_pMaster != NULL) m_pMaster->unregisterStream(m_sStreamData.id); + if ( m_pSource != NULL ) { + switch( m_sStreamData.source_type[0] ) { + case 'D': delete( ( videoLIVE555Source *) m_pSource ); break; + case 'A': delete( ( videoAVLIBSource *) m_pSource ); break; + }; + }; +#ifdef EVE_ENABLE_VIDEO + closeAll(); +#endif //EVE_ENABLE_VIDEO + }; + +}; + +bool streamHandler::create( dataBinder *ptr, uint32_t stremID ){ + if ( ptr == NULL ) return false; + m_pDBC = ptr; + if (stremID) { + DBC_MEDIA_STREAM_DATA *tData = m_pDBC->getMediaStreamData( stremID ); + if ( tData ) { + memcpy( &m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA)); + free(tData); + DBC_CAM_DATA *tCAM = m_pDBC->getCamData( m_sStreamData.source_id ); + if( tCAM ){ + CSTR tNAM = m_pDBC->getNodeName( tCAM->node_id ); + m_sSourceDesc.mediaStreamId = stremID; + m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; + if ( tNAM!= NULL ) { + strncpy(m_sSourceDesc.mediaName, tNAM, 127 ); + m_sSourceDesc.mediaName[127] = (char)0; + free( tNAM ); + } else { + sprintf(m_sSourceDesc.mediaName, "No Name Cam"); + }; + + switch( m_sStreamData.source_type[0] ) { + case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource( &m_sSourceDesc ); break; + case 'D': m_pSource = (basicMediaSource *) new videoLIVE555Source( &m_sSourceDesc ); break; + }; + if( m_pSource != NULL ) { + char tMRL[1024]; + #ifdef DEBUG + LOG("Source OK"); + #endif + int tW = m_pMaster->getWidh(); + int tH = m_pMaster->getHeight(); + int pix = -1; + bool in_16_9 = (((m_sStreamData.width*100) / m_sStreamData.height ) > 140 ); + bool out_16_9 = (((tW*100) / tH ) > 140 ); + //if( tW > 0 ){ + // //m_pSource->setProportionalByWidth( tW ); + // m_pSource->setSize( tW, tH ); + //}; + if( in_16_9 != out_16_9 ){ + if( in_16_9 ){ + tH = ((( tW * 1000 ) / 16 ) * 9 ) / 1000; + } else { + tW = ((( tH * 1000 ) / 3 ) * 4 ) / 1000; + }; + }; + //export PATH=/usr/sbin:$PATH + if (strncmp( m_sStreamData.mrl_proto, "v4l2", 4) == 0) { + sprintf( tMRL, m_sStreamData.mrl ); + } else { + sprintf( tMRL, "%s://%s:%s@%s:%d%s", m_sStreamData.mrl_proto, tCAM->username, tCAM->password, tCAM->ip, m_sStreamData.mrl_port, m_sStreamData.mrl ); + }; + LOG( tMRL ); + if( m_pSource->_open( tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH ) ){ + if( !m_pSource->attachDestination( this ) ){ + delete( m_pSource ); + m_pSource = NULL; + } else { +#ifdef DEBUG + LOG("Source is Connected to Output."); +#endif + }; + } else { + LOG_ERROR("Can not Open Video Source!"); + delete( m_pSource ); + m_pSource = NULL; + }; + } else { + LOG_ERROR("Video Source Stream Failure!"); + }; + free( tCAM ); + } else { + LOG_ERROR("Error Getting CAM Data!"); + m_pSource = NULL; + return false; + }; + }; + }; + + if( m_pSource ){ +#ifdef EVE_ENABLE_VIDEO + return initVideoOutput(); +#else + return true; +#endif // EVE_ENABLE_VIDEO + }; + + return false; +}; + +bool streamHandler::pushFrame( AVFrame *Frame, void* src){ + if( m_pMaster == NULL ) return false; + MEDIA_SOURCE_DESC *tMD = (MEDIA_SOURCE_DESC *)src; + if( tMD ) { + }; + return true; +}; + +bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ + if( m_pMaster == NULL ) return false; + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + char tBuffer[128]; + if( tMD ) { + float mK, oK; + cv::Rect ROI; + + m_pMaster->m_mPictureProtector.lock(); + + if( m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0 ) { + LOG("First Frame Enqueued"); + sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId ); + LOG( tBuffer ); + + m_pMaster->m_mapMATS[tMD->mediaStreamId].create( + m_pMaster->m_sEmbedVideoData.height, + m_pMaster->m_sEmbedVideoData.width, + CV_8UC3 + ); + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Point( 0, 0 ), + cv::Point( + m_pMaster->m_sEmbedVideoData.height, + m_pMaster->m_sEmbedVideoData.width + ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + }; +#ifdef USE_SCALING_IN + oK = ((float)m_pMaster->m_sEmbedVideoData.height )/ ((float)m_pMaster->m_sEmbedVideoData.width); + mK = ((float)Frame.rows )/ ((float)Frame.cols); + //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK ); + if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) { + ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; + ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; + ROI.x = (int) 0; + ROI.y = (int) 0; + } else { + if( mK < oK ) { + ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; + ROI.height = (int) (((float)m_pMaster->m_sEmbedVideoData.width) * mK ); + ROI.x = (int) 0; + ROI.y = (int)( m_pMaster->m_sEmbedVideoData.height - ROI.height ) >> 1; + } else { + ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; + ROI.width = (int) (((float)m_pMaster->m_sEmbedVideoData.height) / mK ); + ROI.y = (int) 0; + ROI.x = (int) ( m_pMaster->m_sEmbedVideoData.width - ROI.width ) >> 1; + }; + }; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); + cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR ); +#else + if(( m_pMaster->m_sEmbedVideoData.height==Frame.rows )&&( m_pMaster->m_sEmbedVideoData.width==Frame.cols )){ + Frame.copyTo( m_pMaster->m_mapMATS[tMD->mediaStreamId] ); + } else { + //Mat dst_roi = dst(Rect(left, top, src.cols, src.rows)); + //src.copyTo(dst_roi); + + if (m_pMaster->m_sEmbedVideoData.width == Frame.cols ) { + ROI.width = Frame.cols; + ROI.height = Frame.rows; + ROI.x = 0; + ROI.y = ( m_pMaster->m_sEmbedVideoData.height - Frame.rows ) >> 1; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); + Frame.copyTo(mROI); + } else { + ROI.width = Frame.cols; + ROI.height = Frame.rows; + ROI.x = ( m_pMaster->m_sEmbedVideoData.width - Frame.cols ) >> 1; + ROI.y = 0; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); + Frame.copyTo(mROI); + }; + }; +#endif + if ( m_bCamMoveCounter > m_bEvtMarkerCounter ) { + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Rect( 10, 10, 20, 20 ), + cv::Scalar( m_bCamMoveCounter, 0, 0 ), + cv::FILLED + ); + m_bCamMoveCounter -=4; + if ( m_bCamMoveCounter < 4 ) m_bCamMoveCounter = 0; + } else { + if ( m_bEvtMarkerCounter ) { + m_bCamMoveCounter = 0; + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Rect( 10, 10, 20, 20 ), + cv::Scalar( 0, 0, m_bEvtMarkerCounter ), + cv::FILLED + ); + m_bEvtMarkerCounter -=4; + if ( m_bEvtMarkerCounter < 4 ) m_bEvtMarkerCounter = 0; + }; + }; + if (m_pMaster->m_sEmbedVideoData.show_label) { + time_t t = time( NULL ); + struct tm * tmp = gmtime( &t ); + if( tmp ){ + char tsb[64]; + if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){ + + sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb ); + int baseline=0; + cv::Size textSize = cv::getTextSize( tBuffer, + m_pMaster->m_sEmbedVideoData.label_font_face, + m_pMaster->m_sEmbedVideoData.label_font_scale, + m_pMaster->m_sEmbedVideoData.label_font_thickness, + &baseline + ); + int x = m_pMaster->m_sEmbedVideoData.label_x; + int y = m_pMaster->m_sEmbedVideoData.label_y; + if( x < 0 ) { + x = m_pMaster->m_sEmbedVideoData.width+x-textSize.width; + }; + if( y < 0 ) { + y = m_pMaster->m_sEmbedVideoData.height+y-baseline;// + }; + if( !m_pMaster->m_sEmbedVideoData.label_transperant ) { + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + }; + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( x, y ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face, + m_pMaster->m_sEmbedVideoData.label_font_scale, + cv::Scalar( 0, 255, 0 ), + m_pMaster->m_sEmbedVideoData.label_font_thickness, + m_pMaster->m_sEmbedVideoData.label_line_type + ); + }; + }; + } else { + if( m_pMaster->m_sEmbedVideoData.show_ts ){ + time_t t = time( NULL ); + struct tm * tmp = gmtime( &t ); + if( tmp ){ + if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){ + uint8_t shift_x = 0; + uint8_t shift_y = 15; + if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) { + if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { + shift_y = 15; + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x, + m_pMaster->m_sEmbedVideoData.ts_y + ), + cv::Point( 490, 60 ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + } else { + shift_y = 23; + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x, + m_pMaster->m_sEmbedVideoData.ts_y + ), + cv::Point( 490, 60 ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + }; + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 255, 255 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + } else { + if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { + shift_y = 15; + } else { + shift_y = 23; + }; + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 255, 255 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + } + }; + }; + }; + }; + if( m_pMaster->m_sEmbedVideoData.show_logo ){ + cv::Rect roi( + cv::Point( + m_pMaster->m_sEmbedVideoData.logo_x, + m_pMaster->m_sEmbedVideoData.logo_y + ), + cv::Size( + m_pMaster->m_sEmbedVideoData.logo_w, + m_pMaster->m_sEmbedVideoData.logo_h + ) + ); + cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi ); + m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask ); + }; + + vector compression_params; + //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + //compression_params.push_back(9); + compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); + compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality ); + + m_pMaster->m_mEncodedProtector.lock(); + + m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear(); + cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params ); + m_pMaster->m_mEncodedProtector.unlock(); + +#ifdef EVE_ENABLE_VIDEO + // encode Video Stream + + + //m_nPreAlarmFrames + //m_nPostAlarmFrames + //m_nNoAlarmSegmentFrames + //m_nSegmentLimitFrames + //m_nHardLimitFrames + + if ( m_bSegAActive || m_bSegBActive ) { + m_mFrameCounterProtector.lock(); + + if( m_bSegAActive ){ + do { + //In Any Case Close Stream if it Long enough + if( m_nSegAFrameCounter > m_nHardLimitFrames ){ + LOG("HardLimit Reached!(A)"); + closeSegmentA(); + break; + }; + if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){ + if ( !m_bSegBActive ){ + LOG("Start Alt!(A)"); + openSegmentB(); + }; + }; + if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && !m_bActiveEncoderStream ){ + LOG("Swap Active!(A)"); + swapActiveStreams(); + break; + }; + } while ( 0 ); + }; + + if( m_bSegBActive ) { + do { + //In Any Case Close Stream if it Long enough + if( m_nSegBFrameCounter > m_nHardLimitFrames ){ + LOG("HardLimit Reached!(B)"); + closeSegmentB(); + break; + }; + if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){ + if ( !m_bSegAActive ){ + LOG("Start Alt!(B)"); + openSegmentA(); + }; + }; + if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && m_bActiveEncoderStream ){ + LOG("Swap Active!(B)"); + swapActiveStreams(); + break; + }; + } while ( 0 ); + }; + + m_mFrameCounterProtector.unlock(); + + ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER)); + if ( tData ) { + tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize(); + tData->linesize[1] = 0; + tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; + tData->size = tData->linesize[0]*tData->rows; + tData->data[1] = NULL; + tData->data[0] = (uint8_t *)malloc( tData->size ); + if ( tData->data[0] ) { + memcpy( tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size ); + m_mEncodingQueueProtector.lock(); + m_qEncodingQueue.push( tData ); + m_mEncodingQueueProtector.unlock(); + } else { + LOG_ERROR("MAT_CPY malloc Error!"); + free( tData ); + }; + } else LOG_ERROR("ENC_BUF malloc Error!"); + }; +#endif // EVE_ENABLE_VIDEO + m_pMaster->m_mPictureProtector.unlock(); + } else { + LOG_ERROR("No PayLoad!"); + }; + return true; +}; + +void streamHandler::closeSegmentA( void ){ + m_mCurrentOperationProtector.lock(); + if ( m_bCOP == 0 ) m_bCOP = 0x01; + m_mCurrentOperationProtector.unlock(); + LOG("Closing Stream A"); +}; + +void streamHandler::closeSegmentB( void ){ + m_mCurrentOperationProtector.lock(); + if ( m_bCOP == 0 ) m_bCOP = 0x02; + m_mCurrentOperationProtector.unlock(); + LOG("Closing Stream B"); +}; + +void streamHandler::closeAll(){ + waitThreadEnd( true ); + avcodec_send_frame( m_pCodecCtx, NULL ); + int ret = 0; + AVPacket *avp = av_packet_alloc(); + if ( avp ) { + do { + av_packet_unref( avp ); + ret = avcodec_receive_packet( m_pCodecCtx, avp ); + if ( !ret ) { + if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp ); + if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp ); + }; + } while ( !ret ); + av_packet_unref( avp ); + av_packet_free( &avp ); + }; + if ( m_bSegAActive ) { + av_write_trailer(m_pFormatCtxA); + avformat_close_input( &m_pFormatCtxA ); + m_bSegAActive = false; + }; + if ( m_bSegBActive ) { + av_write_trailer(m_pFormatCtxB); + avformat_close_input( &m_pFormatCtxB ); + m_bSegBActive = false; + }; +}; + +bool streamHandler::openSegmentA( void ){ + if( !m_bSegAActive ){ + CSTR tAM = getUniqID_MD5(); + if ( tAM ) { + sprintf( m_cSegNameA, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER ); + strncpy( m_cSegMD5A, tAM, 32 ); + m_cSegMD5A[32] = (char)0; + free( tAM ); + #ifdef DEBUG + LOG("Opening Stream A"); + LOG(m_cSegNameA); + char tB[128]; + sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts ); + LOG( tB ); + sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration ); + LOG( tB ); + #endif + m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1; + if (m_pVideoStrA->nb_frames) { + m_pVideoStrA->nb_frames = 0; + m_pVideoStrA->start_time = 0; + m_pVideoStrA->first_dts = 0; + m_pFormatCtxA->start_time = 0; + }; + if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) { + LOG_ERROR("Could not open output file."); + return m_bSegAActive; + }; + if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){ + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegAActive; + }; + //m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter = 0; + m_nSegAShiftFrames = 0; + m_bSegAActive = true; + m_bSegADelete = true; + //m_mFrameCounterProtector.unlock(); + #ifdef DEBUG + LOG("Stream A Opened"); + #endif + }; + }; + return m_bSegAActive; +}; + +bool streamHandler::openSegmentB( void ){ + if( !m_bSegBActive ){ + CSTR tAM = getUniqID_MD5(); + if ( tAM ) { + sprintf( m_cSegNameB, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER ); + strncpy( m_cSegMD5B, tAM, 32 ); + m_cSegMD5B[32] = (char)0; + free( tAM ); + #ifdef DEBUG + LOG("Opening Stream B"); + LOG(m_cSegNameB); + char tB[128]; + sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts ); + LOG( tB ); + sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration ); + LOG( tB ); + #endif + m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1; + if (m_pVideoStrB->nb_frames) { + m_pVideoStrB->nb_frames = 0; + m_pVideoStrB->start_time = 0; + m_pVideoStrB->first_dts = 0; + m_pFormatCtxB->start_time = 0; + }; + if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){ + LOG_ERROR("Could not open output file."); + return m_bSegBActive; + }; + if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){ + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegBActive; + }; + //m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter = 0; + m_nSegBShiftFrames = 0; + m_bSegBActive = true; + m_bSegBDelete = true; + //m_mFrameCounterProtector.unlock(); + #ifdef DEBUG + LOG("Stream B Opened"); + #endif + }; + }; + return m_bSegBActive; +}; + +bool streamHandler::initVideoOutput(){ + m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; + m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; + m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000; + m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000; + + if( !initLibAV() ) return false; + + m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL ); + + if ( m_pFormat == NULL ) { + LOG_ERROR("Out VideoFormat Not Found!"); + return false; +#ifdef DEBUG + } else { + LOG("Output video Format"); + LOG( VIDEO_OUTPUT_CONTAINER ); +#endif + }; + + if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("Format CTX A alloc error!"); + av_free( m_pFormat ); + return false; + } else { + av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 ); + m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("Format CTX B alloc error!"); + avformat_free_context( m_pFormatCtxA ); + //av_free( m_pFormat ); + return false; + } else { + av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 ); + m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC ); + if( m_pVideoCodec == NULL ){ + LOG_ERROR("Out VideoCodec Not Found!"); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + //av_free( m_pFormat ); + return false; +#ifdef DEBUG + } else { + LOG("Out Video Codec Found"); +#endif + }; + + m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec ); + if ( m_pCodecCtx == NULL){ + LOG_ERROR("Out VideoCodec Context Memory Allocation Error"); + av_free( m_pVideoCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + //av_free( m_pFormat ); + return false; +#ifdef DEBUG + } else { + LOG("Out Codec Context3 Allocated"); +#endif + }; + + m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec ); + if ( m_pVideoStrA == NULL){ + LOG_ERROR("VideoStream A Not Created!"); + avcodec_free_context( &m_pCodecCtx ); + av_free( m_pCodecCtx ); + av_free( m_pVideoCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + //av_free( m_pFormat ); + return false; +#ifdef DEBUG + } else { + LOG("VideoStream A is Created"); +#endif + }; + + m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec ); + if ( m_pVideoStrB == NULL){ + LOG_ERROR("VideoStream B Not Created!"); + avcodec_free_context( &m_pCodecCtx ); + av_free( m_pCodecCtx ); + av_free( m_pVideoCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + av_free( m_pFormat ); + return false; +#ifdef DEBUG + } else { + LOG("VideoStream B is Created"); +#endif + }; + + m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE; + //m_pCodecCtx->thread_count = 1; + //m_pCodecCtx->bit_rate_tolerance = 1; + //m_pCodecCtx->global_quality = 100; + //m_pCodecCtx->compression_level = 2; + m_pCodecCtx->max_b_frames=1; + m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecCtx->time_base.num = 1; + m_pCodecCtx->time_base.den = m_sStreamData.fps; + m_pCodecCtx->framerate.num = m_sStreamData.fps; + m_pCodecCtx->framerate.den = 1; + + //https://pastebin.com/yG37YhWW + + //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec + //G@ avcodec encode NALU mp4 + +#if (LIBAVCODEC_VERSION_MAJOR > 54) + m_pCodecCtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); +#endif + m_pFormatOpts = NULL; + + // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate + + if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){ +#ifdef DEBUG + LOG("Begin Options!"); +#endif + //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html + //Set format's privater options, to be passed to avformat_write_header() + + /* + + mp4 muxer AVOptions: + -movflags E..... MOV muxer flags (default 0) + rtphint E..... Add RTP hint tracks + empty_moov E..... Make the initial moov atom empty (not supported by QuickTime) + frag_keyframe E..... Fragment at video keyframes + separate_moof E..... Write separate moof/mdat atoms for each track + frag_custom E..... Flush fragments on caller requests + isml E..... Create a live smooth streaming feed (for pushing to a publishing point) + faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file + omit_tfhd_offset E..... Omit the base data offset in tfhd atoms + delay_moov ?? + -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0) + -rtpflags E..... RTP muxer flags (default 0) + latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC + rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263 + skip_rtcp E..... Don't send RTCP sender reports + h264_mode0 E..... Use mode 0 for H264 in RTP + send_bye E..... Send RTCP BYE packets when finishing + -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1) + -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1) + -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1) + -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0) + -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0) + -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0) + -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0) + -use_editlist E..... use edit list (from -1 to 1) (default -1) + -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0) + + + */ + if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){ + LOG_ERROR( "av_dict_set movflags!"); +#ifdef DEBUG + } else { + LOG("MOV FLAG SET!"); +#endif + }; + + //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ + // LOG_ERROR( "av_dict_set live!" ); + //}; + + //default brand is "isom", which fails on some devices + if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){ + LOG_ERROR( "av_dict_set brand!" ); + }; + //m_pCodecCtx->max_b_frames = 1; + //m_pCodecCtx->level = 31; + + m_pCodecCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames + /// P-frames, generated by referencing data from prev and future frames. + /// [Compression up, CPU usage up] + /// [use 3/gop] + m_pCodecCtx->max_b_frames = 5; + + /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. + /// [use 3–5 ref per P] + m_pCodecCtx->refs = 3; + + /// Compression efficiency (slower -> better quality + higher cpu%) + /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow] + /// Set this option to "ultrafast" is critical for realtime encoding + av_opt_set( m_pCodecCtx->priv_data, "preset", "ultrafast", 0); + //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); + //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); + + + /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy + /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding + av_opt_set( m_pCodecCtx->priv_data, "crf", "32", 0); + + /// Change settings based upon the specifics of input + /// [psnr, ssim, grain, zerolatency, fastdecode, animation] + /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet. + av_opt_set( m_pCodecCtx->priv_data, "tune", "zerolatency", 0); + + /// Disable b-pyramid. CLI options for this is "-b-pyramid 0" + /// Because Quicktime (ie. iOS) doesn't support this option + av_opt_set( m_pCodecCtx->priv_data, "b-pyramid", "0", 0 ); +#ifdef DEBUG + LOG("End Options!"); +#endif + } else { + if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + }; + + + + + const AVRational dst_fps = { m_sStreamData.fps, 1 }; + +#ifdef DEBUG + char TB[129]; + sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den ); + LOG(TB); +#endif + + m_pVideoStrA->time_base = m_pCodecCtx->time_base; + m_pVideoStrB->time_base = m_pCodecCtx->time_base; + + + //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec ); + + //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width; + //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height; + //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + + //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec ); + + //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width; + //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height; + //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + + //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + + avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecCtx ); + //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata; + //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecCtx ); + //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata; + //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + if ( avcodec_is_open( m_pCodecCtx ) == 0 ) { + LOG("output codec context is closed, opening"); + if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) { + LOG_ERROR("Error opening2 encoder"); + return false; +#ifdef DEBUG + } else { + LOG("output codec context is opened"); + }; +#endif +#ifdef DEBUG + } else { + LOG("output codec context is already opened"); +#endif + }; + m_pConvertCtx = sws_getContext( + m_pMaster->m_sEmbedVideoData.width, + m_pMaster->m_sEmbedVideoData.height, + AV_PIX_FMT_BGR24, + m_pMaster->m_sEmbedVideoData.width, + m_pMaster->m_sEmbedVideoData.height, + VIDEO_OUTPUT_PIX_FMT, + SWS_FAST_BILINEAR, + NULL, + NULL, + NULL + ); + if ( m_pConvertCtx == NULL ) { + return false; + } + m_pAVFrame = av_frame_alloc(); + if ( m_pAVFrame == NULL ) { + return false; + }; + m_pOutBuffer = (uint8_t *)av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, BUFFER_ALIGN)); + if( m_pOutBuffer == NULL ) { + return false; + }; + m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width; + m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height; + m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT; + //av_frame_get_buffer( m_pAVFrame, 0 ); + av_image_fill_arrays ( m_pAVFrame->data, m_pAVFrame->linesize, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, 1 ); + + //av_frame_make_writable( m_pAVFrame ); + + return init(); +}; + +//encoding thread + +void streamHandler::m_fThreadProc( void ){ + AVPacket mPacket; + int bGotPacket; + int rVal = 0; + char tB[128]; + + av_init_packet( &mPacket ); + while( m_bThreadStatus != TH_ENDED ){ + //At the begining All streams are closed --> try to Open + if( m_bThreadStatus < TH_WORKING ){ + if( !openSegmentA() ){ + m_bThreadStatus = TH_ENDED; + continue; + }; + //if( !openSegmentB() ){ + // m_bThreadStatus = TH_ENDED; + // continue; + //}; + m_bThreadStatus = TH_WORKING; + continue; + }; + + m_mEncodingQueueProtector.lock(); + if ( m_qEncodingQueue.size() ) { + ENCODING_BUFFER *tData = m_qEncodingQueue.front(); + if( tData ){ + //av_frame_make_writable( m_pAVFrame ); + sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize ); + free( tData->data[0] ); + free( tData ); + m_qEncodingQueue.pop(); + /* + + + AV_PICTURE_TYPE_NONE Undefined. + AV_PICTURE_TYPE_I Intra. + AV_PICTURE_TYPE_P Predicted. + AV_PICTURE_TYPE_B Bi-dir predicted. + AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4. + AV_PICTURE_TYPE_SI Switching Intra. + AV_PICTURE_TYPE_SP Switching Predicted. + AV_PICTURE_TYPE_BI BI type. + + + */ + if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) { + m_pAVFrame->key_frame = 1; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I; + } else { + m_pAVFrame->key_frame = 0; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE; + }; + m_pAVFrame->pts = m_nGlobalFrameCounter + 1; + + rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame ); + m_mFrameCounterProtector.lock(); + m_nGlobalFrameCounter++; + if ( m_bSegAActive ) m_nSegAFrameCounter++; + if ( m_bSegBActive ) m_nSegBFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + m_mEncodingQueueProtector.unlock(); + } else { + m_mEncodingQueueProtector.unlock(); + // If No Encode Job -> Test Commands! + m_mCurrentOperationProtector.lock(); + switch ( m_bCOP ) { + case 0x01:{ + m_bSegAActive = false; + if ( !m_bSegADelete ) { + av_write_trailer( m_pFormatCtxA ); + avio_close( m_pFormatCtxA->pb ); +#ifdef DEBUG + LOG("Stream A is Closed"); +#endif + } else { +#ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer( m_pFormatCtxA ); +#endif + avio_close( m_pFormatCtxA->pb ); +#ifndef EVE_DONT_DELETE_SEGMENTS + unlink( m_cSegNameA ); +#endif +#ifdef DEBUG + LOG("Stream A is Deleted!"); +#endif + }; + break; + }; + case 0x02:{ + m_bSegBActive = false; + if ( !m_bSegBDelete ) { + av_write_trailer( m_pFormatCtxB ); + avio_close( m_pFormatCtxB->pb ); +#ifdef DEBUG + LOG("Stream B is Closed"); +#endif + } else { +#ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer( m_pFormatCtxB ); +#endif + avio_close( m_pFormatCtxB->pb ); +#ifndef EVE_DONT_DELETE_SEGMENTS + unlink( m_cSegNameB ); +#endif +#ifdef DEBUG + LOG("Stream B is Deleted!"); +#endif + }; + break; + }; + }; + m_bCOP = 0; + m_mCurrentOperationProtector.unlock(); + }; + do { + mPacket.data = NULL; + mPacket.size = 0; + rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket ); + if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){ + break; + } else if( rVal < 0 ){ + LOG_ERROR( "Error during encoding " ); + m_bThreadStatus = TH_ENDED; + break; + }; + if( !rVal ){ + if ( m_bSegAActive ) { + mPacket.stream_index = m_pVideoStrA->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + //mPacket.pts = AV_NOPTS_VALUE; + //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + mPacket.dts = mPacket.pts; + int rc = av_write_frame( m_pFormatCtxA, &mPacket ); + if( rc < 0 ){ + //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output A!"); + av_strerror( rc, tB, 128 ); + LOG_ERROR( tB ); + break; //continue (changed since embed into do-while) + }; + }; + if ( m_bSegBActive ) { + mPacket.stream_index = m_pVideoStrB->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + //mPacket.pts = AV_NOPTS_VALUE; + //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); + mPacket.dts = mPacket.pts; + int rc = av_write_frame( m_pFormatCtxB, &mPacket); + if( rc < 0 ) { + //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR( "Trouble with Video Output B!" ); + av_strerror( rc, tB, 128 ); + LOG_ERROR( tB ); + break; //continue (changed since embed into do-while) + }; + }; + av_packet_unref( &mPacket ); + }; + } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED ); + }; +#ifdef DEBUG + LOG("Encoder Loop Ended!"); +#endif + if ( m_bSegAActive ) { + m_bSegAActive = false; + av_write_trailer( m_pFormatCtxA ); + avio_close( m_pFormatCtxA->pb ); + }; + if ( m_bSegBActive ) { + m_bSegBActive = false; + av_write_trailer( m_pFormatCtxB ); + avio_close( m_pFormatCtxB->pb ); + }; +#ifdef DEBUG + LOG("Encoder Streams are Closed!"); +#endif +}; + +void streamHandler::swapActiveStreams( void ){ + //m_mFrameCounterProtector.lock(); + if ( !m_bActiveEncoderStream ) { + m_bActiveEncoderStream = 1; + m_nVideoRegisteredDBID = 0; + // No need to continue Stream A if no Events + if ( m_bSegADelete ) closeSegmentA(); + } else { + m_bActiveEncoderStream = 0; + m_nVideoRegisteredDBID = 0; + // No need to continue Stream B if no Events + if ( m_bSegBDelete ) closeSegmentB(); + }; + //m_mFrameCounterProtector.unlock(); +}; + +bool streamHandler::triggerEvent( uint32_t &dbid, uint32_t &frame ){ + m_mFrameCounterProtector.lock(); + // To Mark Events Frames + m_bEvtMarkerCounter = 255; + + if ( m_nVideoRegisteredDBID == 0 ) { + LOG("New Event!"); + PF_TIMESTAMP ts; + getPFTS( &ts ); + if ( !m_bActiveEncoderStream ) { // Stream A is Active + m_nVideoRegisteredDBID = m_pDBC->addVideoRecord( + m_sStreamData.id, + m_cSegMD5A, + VIDEO_OUTPUT_CONTAINER, + ts.seconds, + ts.milliseconds, + m_sStreamData.fps + ); + m_bSegADelete = false; + m_nSegAShiftFrames = frame = m_nSegAFrameCounter; + } else { // Stream B is Active + m_nVideoRegisteredDBID = m_pDBC->addVideoRecord( + m_sStreamData.id, + m_cSegMD5B, + VIDEO_OUTPUT_CONTAINER, + ts.seconds, + ts.milliseconds, + m_sStreamData.fps + ); + m_bSegBDelete = false; + m_nSegBShiftFrames = frame = m_nSegBFrameCounter; + }; + }; + if ( m_nVideoRegisteredDBID == 0 ) return false; + dbid = m_nVideoRegisteredDBID; + LOG("Event Registered!"); + m_mFrameCounterProtector.unlock(); + return true; +}; + +bool streamHandler::triggerCamMove( void ){ + m_bCamMoveCounter = 255; + return true; +}; + +bool streamHandler::validate( void ){ + if ( m_pSource ) +#ifdef EVE_ENABLE_VIDEO + if( m_bThreadStatus < TH_ENDED ) +#endif + return true; + + return false; +}; + +#undef LOG +#undef LOG_ERROR +#undef TLOG +#undef TLOG_ERROR diff --git a/lib/App/common/kernelModuleEmbedVideo.h b/lib/App/common/kernelModuleEmbedVideo.h new file mode 100644 index 00000000..0f819cb9 --- /dev/null +++ b/lib/App/common/kernelModuleEmbedVideo.h @@ -0,0 +1,319 @@ +#ifndef __KERNEL_MODULE_EMBED_VIDEO_HEADER__ +#define __KERNEL_MODULE_EMBED_VIDEO_HEADER__ +#include "kernelModule.h" +#include "../components/base/basicMutex.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" +//#include "../data/media/video/videoAVLIBDestination.h" +#include "../components/base/basicMediaSource.h" +#include "../components/base/basicMediaDestination.h" + +class kernelModuleEmbedVideo; + +#define FILESTREAMBUFFERSZ 1048576 + +#define EVE_ENABLE_VIDEO + + + +//#define USE_SCALING_IN + + +#ifdef EVE_ENABLE_VIDEO + +//#define EVE_DONT_DELETE_SEGMENTS + +/* Video CODECS */ +#define VC_VPX 0 +#define VC_X264 1 +#define VC_MP4 2 +#define VC_MJPEG 3 +#define VC_FLV 4 + +/* Video FORMATS */ +#define VF_WEBM 0 +#define VF_MP4 1 +#define VF_MP3 2 +#define VF_AAC 3 +#define VF_OGG 4 +#define VF_MJPEG 5 +#define VF_FLV 6 + +/* Encoder PROFILES */ +#define VP_ULTRAFAST 0 +#define VP_VERYFAST 1 +#define VP_FAST 2 +#define VP_MEDIUM 3 +#define VP_SLOW 4 +#define VP_VERYSLOW 5 +#define VP_ULTRASLOW 6 + +#define VO_MJPEG 1 +#define VO_MPEG4 2 +#define VO_H264 3 +#define VO_H265 4 +#define VO_FLV 5 + +//#define VIDEO_OUTPUT VO_MJPEG +//#define VIDEO_OUTPUT VO_MPEG4 +#define VIDEO_OUTPUT VO_H264 +//#define VIDEO_OUTPUT VO_H265 +//#define VIDEO_OUTPUT VO_FLV + +//#define VIDEO_OUTPUT_WIDTH 640 //1920 +//#define VIDEO_OUTPUT_HEIGHT 480 //1080 +//#define VIDEO_OUTPUT_FPS 10 +//#define VIDEO_OUTPUT_GOP 15 + +#if( LIBAVCODEC_VERSION_MAJOR < 54 ) + #define VIDEO_OUTPUT_CODEC CODEC_ID_MJPEG + #define VIDEO_OUTPUT_PIX_FMT PIX_FMT_YUVJ422P +#else + #if VIDEO_OUTPUT == VO_MJPEG + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MJPEG + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUVJ422P + #define VIDEO_OUTPUT_CONTAINER_LONG "mpeg" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "webm" + #elif VIDEO_OUTPUT == VO_MPEG4 + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MPEG4 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif VIDEO_OUTPUT == VO_H264 + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H264 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif VIDEO_OUTPUT == VO_H265 + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H265 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif VIDEO_OUTPUT == VO_FLV + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_FLV1 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_CONTAINER_LONG "flv" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "flv" + #endif +#endif + +#endif //EVE_ENABLE_VIDEO + +typedef struct S_buffer_data { + uint8_t * buf; + int size; + uint8_t * ptr; + size_t room; ///< size left in the buffer +} buffer_data; + +#define NR_COLORS 4 +#define AVIO_BUFFER_SIZE 4096 +#define BD_BUFFER_SIZE 1024 + +class streamHandler; + +typedef struct S_WEB_CLIENT_CTX{ + int m_iSocketFID; + int m_iEncoderPipe[2]; + bool bValid; + bool initDone; + bool headerIsSent; + uint32_t mediaStreamId; + streamHandler * m_pHandler; + kernelModuleEmbedVideo * ModulePtr; +}WEB_CLIENT_CTX; + + +typedef struct S_WEB_HANDLER{ + DWORD m_dwThreadID; +#ifdef __linux__ + pthread_t m_hThreadHandle; +#else + HANDLE m_hThreadHandle; +#endif + WEB_CLIENT_CTX * CTX; +}WEB_HANDLER; + +typedef vector vectorHANDLERS; + + +//typedef vector vectorSTREAMS; + +typedef struct S_STREAM_CAP{ + uint32_t stream_id; + uint32_t buffer_size; + uint8_t picture_buffer; +}STREAM_CAP; + +typedef struct S_VIDEO_EVT{ + uint32_t dbid; + uint32_t frame; +}VIDEO_EVT; + +typedef vector compressedFRAME; +typedef map mapSTREAMCAPS; +typedef map mapSTREAMMAPS; + +#define PRE_ALARM_TIME_MILSECONDS 2000 // 2 sec +#define POST_ALARM_TIME_MILSECONDS 2000 // 2 sec +#define ENCODING_SEGMENT_MILSECONDS 50000 // 50 sec +#define ENCODING_SEGMENT_LIMIT_MILSECONDS 60000 // 1 minute +//#define ENCODING_SEGMENT_LIMIT_MILSECONDS 900000 // 15 minute + +#define EVE_OUTPUT_PICTURES 1 +#define EVE_OUTPUT_VIDEO 2 +#define EVE_OUTPUT_PIC_AND_VID 3 + +#ifdef EVE_ENABLE_VIDEO + + typedef struct S_ENCODING_BUFFER{ + int linesize[2]; + int rows; + uint8_t * data[2]; + size_t size; + }ENCODING_BUFFER; + + typedef std::queue Q_ENCODING_BUFFER; + +#endif +class streamHandler: + public basicMediaDestination +#ifdef EVE_ENABLE_VIDEO + , public basicThread +#endif +{ + private: + basicLogCollection * m_pLog; + basicMediaSource * m_pSource; + MEDIA_SOURCE_DESC m_sSourceDesc; + char m_cSourceType; + DBC_MEDIA_STREAM_DATA m_sStreamData; + basicMutex m_mProtector; + kernelModuleEmbedVideo * m_pMaster; + uint8_t m_bEvtMarkerCounter; + uint8_t m_bCamMoveCounter; + dataBinder * m_pDBC; + MS_WORK_MODE m_eWM; + +#ifdef EVE_ENABLE_VIDEO + basicMutex m_mFrameCounterProtector; + uint32_t m_nPreAlarmFrames; + uint32_t m_nPostAlarmFrames; + uint32_t m_nGlobalFrameCounter; + uint32_t m_nVideoRegisteredDBID; + uint32_t m_nSegAFrameCounter; + uint32_t m_nSegBFrameCounter; + uint32_t m_nSegAShiftFrames; + uint32_t m_nSegBShiftFrames; + uint32_t m_nSegASkippedFrames; + uint32_t m_nSegBSkippedFrames; + uint32_t m_nSegmentLimitFrames; + uint32_t m_nHardLimitFrames; + uint8_t m_bActiveEncoderStream; + bool m_bSegAActive; + bool m_bSegADelete; + bool m_bSegBActive; + bool m_bSegBDelete; + basicMutex m_mCurrentOperationProtector; + uint8_t m_bCOP; + char m_cSegNameA[128]; + char m_cSegMD5A[33]; + char m_cSegNameB[128]; + char m_cSegMD5B[33]; + // encoding video stuff + AVCodec * m_pVideoCodec; + AVCodecContext * m_pCodecCtx; + SwsContext * m_pConvertCtx; + AVFrame * m_pAVFrame; + uint8_t * m_pOutBuffer; + // File Context 2 units + AVOutputFormat * m_pFormat; + AVFormatContext * m_pFormatCtxA; + AVFormatContext * m_pFormatCtxB; + AVStream * m_pVideoStrA; + AVStream * m_pVideoStrB; + //common output options + AVDictionary * m_pFormatOpts; + + basicMutex m_mEncodingQueueProtector; + Q_ENCODING_BUFFER m_qEncodingQueue; + + bool openSegmentA( void ); + void closeSegmentA( void ); + bool openSegmentB( void ); + void closeSegmentB( void ); + void swapActiveStreams( void ); + void closeAll(); + bool initVideoOutput(); + protected: + void m_fThreadProc( void ); +#endif //EVE_ENABLE_VIDEO + + public: + explicit streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M = MS_MODE_DECODE_FRAMES ); + virtual ~streamHandler(); + bool create( dataBinder *ptr, uint32_t stremID ); + /* from Media Destination */ + virtual bool pushFrame( AVFrame *Frame, void* src = NULL); + //virtual void pushFrame( cv::Mat* Frame, void* src = NULL); + virtual bool pushFrame( cv::Mat &Frame, void* src = NULL); + bool triggerEvent( uint32_t &dbid, uint32_t &frame ); + bool triggerCamMove( void ); + bool validate( void ); +}; + +typedef map mapSTREAMHANDLERS; + +class kernelModuleEmbedVideo: public kernelModule, /*public basicMediaDestination,*/ public basicThread { + private: + basicEventHeap * m_pEventHeap; + static void * webClientProc( void *ptr ); + int m_nSocketDescriptor; + basicMutex m_mHandlersProtector; + basicMutex m_mPictureProtector; + basicMutex m_mEncodedProtector; + vectorHANDLERS m_vHandlersPool; + DBC_MODULE_EMBED_VIDEO_DATA m_sEmbedVideoData; + mapSTREAMCAPS m_mapCAPTURES; + mapSTREAMMAPS m_mapMATS; + mapSTREAMHANDLERS m_mapHANDLERS; + uint8_t * n_pNoSignalData; + uint32_t m_nNoSignalSize; + cv::Mat m_mLogoPic; + cv::Mat m_mLogoMask; + char m_pBaseSavePath[PATH_MAX]; + bool registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ); + bool saveStreamPicture( uint32_t id ); + bool saveStreamPicture( DBC_SNAPSHOT_DATA *ptr ); + bool generateSavePicPath( CSTR MD5, CSTR Output ); + protected: + /* From Basic Thread */ + virtual void m_fThreadProc( void ); + public: + explicit kernelModuleEmbedVideo( uint32_t moduleID ); + ~kernelModuleEmbedVideo(); + /* From Kernel Module */ + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); + /* from Media Destination * / + virtual bool pushFrame( AVFrame *Frame, void* src = NULL); + //virtual void pushFrame( cv::Mat* Frame, void* src = NULL); + virtual bool pushFrame( cv::Mat &Frame, void* src = NULL); + /* Module Specific Functionality */ + int getWidh( void ); + int getHeight( void ); + bool registerStream( uint32_t streamID ); + bool unregisterStream( uint32_t streamID ); + + friend class streamHandler; + +}; +#endif diff --git a/lib/App/common/kernelModuleFactory.cpp b/lib/App/common/kernelModuleFactory.cpp new file mode 100644 index 00000000..9970b001 --- /dev/null +++ b/lib/App/common/kernelModuleFactory.cpp @@ -0,0 +1,397 @@ +#include "kernelModuleFactory.h" +#include "kernelModuleUSBRelay.h" +#include "kernelModuleKafka.h" +#include "kernelModuleFlyHunter.h" +#include "kernelModuleSSDP.h" +#include "kernelModuleOnvifObserver.h" +#include "kernelModuleEmbedVideo.h" +#include "kernelModuleModemManager.h" + +#ifdef MEM_DEBUG + #include "../alg/generic/heapDebug.h" +#endif + +#ifdef USE_MYSQL + #include "MySQL_dataBinder.h" +#else + #include "SQLite_dataBinder.h" +#endif + +#define LOG( X ) m_pLog->Log( "MFAC", this, X ) +#define LOG_ERROR( X ) m_pLog->Log( "MFAC", this, _LOG_ERROR, X ) + +kernelModuleFactory * kernelModuleFactory::_instance = NULL; + +/** +* Returns the single instance of the object. +*/ +kernelModuleFactory* kernelModuleFactory::getInstance( uint32_t InstanceID ) { + if( NULL == _instance) { + _instance = new kernelModuleFactory( InstanceID ); + }; + return _instance; +}; + +kernelModuleFactory::kernelModuleFactory( uint32_t InstanceID ):basicThread(){ + m_nInstanceID = InstanceID; + m_bInitialValidatioonDone = false; + m_pLog = basicLogCollection::getInstance(); +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + init(); +}; + +kernelModuleFactory::~kernelModuleFactory(){ + waitThreadEnd( true ); + shutdownServices( true ); + _instance = NULL; +}; + +void kernelModuleFactory::shutdownServices( bool force ){ +#ifdef DEBUG + LOG("shutdownServices"); +#endif + m_mModulesProtector.lock(); + if( m_vKernelModules.size() > 0 ){ + for( vectorKernelModules::iterator index = m_vKernelModules.begin(); index < m_vKernelModules.end(); index++ ){ +#ifdef DEBUG + char tB[128]; + switch( (*index)->getType() ){ + //case KERNEL_MODULE_ZLMEDIA: sprintf( tB, "Stop Service of ZlMedia Module" ); break; + case KERNEL_MODULE_DCBUSB: sprintf( tB, "Stop Service of DCUSB Module" ); break; + case KERNEL_MODULE_KAFKA: sprintf( tB, "Stop Service of KAFKA Module" ); break; + case KERNEL_MODULE_GPS: sprintf( tB, "Stop Service of GPS Module" ); break; + case KERNEL_MODULE_NETWORK: sprintf( tB, "Stop Service of Network Module" ); break; + case KERNEL_MODULE_FLYHUNTER: sprintf( tB, "Stop Service of FlyHunter Module" ); break; + case KERNEL_MODULE_SSDP_ANONCE: sprintf( tB, "Stop Service of SSDP Module" ); break; + case KERNEL_MODULE_ONVIF_OBSERVER: sprintf( tB, "Stop Service of OnVif Observer Module" ); break; + case KERNEL_MODULE_EMBED_VIDEO: sprintf( tB, "Stop Service of EmbedVideo Module" ); break; + case KERNEL_MODULE_MODEM_MANAGER: sprintf( tB, "Stop Service of Modem Manager Module" ); break; + default: sprintf( tB, "Stop Service of UNKNOWN[%d] Module", (*index)->getType() ); break; + }; + LOG( tB ); +#endif + // (*index)->stopService( force ); +#ifdef DEBUG + LOG("Done"); +#endif + deleteModule( (*index) ); +#ifdef DEBUG + LOG("Module is Deleted"); +#endif + }; + m_vKernelModules.clear(); + }; + m_mModulesProtector.unlock(); +#ifdef DEBUG + LOG("Done shutdownServices"); +#endif +}; + +bool kernelModuleFactory::loadModules(){ + DBC_INT_LIST *tList = NULL; + if( m_pDBC == NULL ) return false; + tList = m_pDBC->listModules(); + if( tList != NULL ) { + if( tList->size() ) { +#ifdef DEBUG + char tB[128]; + sprintf( tB, "Have %d Modules to create!", tList->size() ); + LOG( tB ); +#endif + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ) createModule( *idx ); + tList->clear(); + } +#ifdef DEBUG + else { + LOG("No Modules Defined"); + } +#endif + delete( tList ); + } +#ifdef DEBUG + else { + LOG("No Modules Defined"); + } +#endif + return true; +}; + +kernelModule *kernelModuleFactory::createModule( int id ){ + kernelModule *tVal = NULL; + if( m_pDBC != NULL ){ + DBC_MODULE_DATA *tData = NULL; + + tData = m_pDBC->getModuleData( id ); + if( tData!= NULL ) { + switch( tData->type ) { + case KERNEL_MODULE_DCBUSB: +#ifdef DEBUG + LOG("Creating Dry Contact USB Module"); +#endif + tVal = new kernelModuleUSBRelay( tData->module_id ); + + break; + case KERNEL_MODULE_KAFKA: +#ifdef DEBUG + LOG("Creating KAFKA Module"); +#endif + tVal = new kernelModuleKafka( tData->module_id ); + break; + case KERNEL_MODULE_FLYHUNTER: +#ifdef DEBUG + LOG("Creating Fly Hunter Module"); +#endif + tVal = new kernelModuleFlyHunter( tData->module_id ); + break; + case KERNEL_MODULE_SSDP_ANONCE: +#ifdef DEBUG + LOG("Creating SSDP Announcer Module"); +#endif + tVal = new kernelModuleSSDPAnnouncer( tData->module_id ); + break; + case KERNEL_MODULE_ONVIF_OBSERVER: +#ifdef DEBUG + LOG("Creating OnVif Observer Module"); +#endif + if ( m_pDBC->isLocal() ) { + tVal = new kernelModuleOnvifObserver(tData->module_id); +#ifdef DEBUG + } else { + LOG("Module is Disabled Since Remote Database!"); +#endif + }; + break; + case KERNEL_MODULE_EMBED_VIDEO: +#ifdef DEBUG + LOG("Creating Embed Video Module"); +#endif + if ( m_pDBC->isLocal() ){ + tVal = new kernelModuleEmbedVideo( tData->module_id ); +#ifdef DEBUG + } else { + LOG("Module is Disabled Since Remote Database!"); +#endif + }; + break; + case KERNEL_MODULE_MODEM_MANAGER: +#ifdef DEBUG + LOG("Creating Modem Manager Module"); +#endif + tVal = new kernelModuleModemManager( tData->module_id ); + break; + }; + free(tData); + } else { + LOG_ERROR("No Module Data Fetched!"); + }; + } else { + LOG_ERROR("No Database Object Assigned!"); + }; + if( tVal != NULL ){ + tVal->startService(); + m_mModulesProtector.lock(); + m_vKernelModules.push_back( tVal ); + m_mModulesProtector.unlock(); + }; + return tVal; +}; + +void kernelModuleFactory::deleteModule( kernelModule *M ){ + if( M ) { + M->stopService( true ); + switch( M->getType() ) { + case KERNEL_MODULE_DCBUSB: delete( (kernelModuleUSBRelay*) M ); break; + case KERNEL_MODULE_KAFKA: delete( (kernelModuleKafka*) M ); break; + case KERNEL_MODULE_FLYHUNTER: delete( (kernelModuleFlyHunter*) M ); break; + case KERNEL_MODULE_SSDP_ANONCE: delete( (kernelModuleSSDPAnnouncer*) M ); break; + case KERNEL_MODULE_ONVIF_OBSERVER: delete( (kernelModuleOnvifObserver*) M ); break; + case KERNEL_MODULE_EMBED_VIDEO: delete( (kernelModuleEmbedVideo*) M ); break; + case KERNEL_MODULE_MODEM_MANAGER: delete( (kernelModuleModemManager*) M ); break; + }; + }; +}; + +void kernelModuleFactory::deleteModule( int id ){ + if( m_vKernelModules.size() > id ) { + deleteModule( m_vKernelModules.at( id ) ); + m_vKernelModules.erase( m_vKernelModules.begin() + id ); + m_vKernelModules.shrink_to_fit(); + }; +}; + +uint32_t kernelModuleFactory::getModulesCount( KERNEL_MODULE_TYPE t ){ + uint32_t cnt = 0; + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + for( int i=0; i < m_vKernelModules.size(); i++ ) { + if( m_vKernelModules.at(i)->getType() == t ) cnt++; + }; + }; + m_mModulesProtector.unlock(); + return cnt; +}; + +uint32_t kernelModuleFactory::fetchModules( KERNEL_MODULE_TYPE t, kernelModule**&RA ){ + uint32_t cnt = getModulesCount( t ); + RA = NULL; + if( cnt > 0 ) { + RA = ( kernelModule** ) calloc( cnt, sizeof( kernelModule* ) ); + if( RA!= NULL ) { + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + uint32_t idx = 0; + for( int i=0; i < m_vKernelModules.size(); i++ ) { + if( m_vKernelModules.at(i)->getType() == t ) { + RA[idx] = m_vKernelModules.at(i); + idx++; + }; + }; + }; + m_mModulesProtector.unlock(); + } else cnt = 0; + }; + return cnt; +}; + +kernelModule *kernelModuleFactory::getModule( uint32_t id ){ + kernelModule *RetVal = NULL; + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + for( vectorKernelModules::iterator idx = m_vKernelModules.begin(); idx < m_vKernelModules.end(); idx++ ){ + if( (*idx)->getId() == id ) { + RetVal = (*idx); + break; + }; + }; + }; + m_mModulesProtector.unlock(); + return RetVal; +}; + +kernelModule *kernelModuleFactory::getModule( KERNEL_MODULE_TYPE t, uint32_t id ){ + kernelModule *RetVal = NULL; + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + for( vectorKernelModules::iterator idx = m_vKernelModules.begin(); idx < m_vKernelModules.end(); idx++ ){ + if( id ){ + if( ( (*idx)->getType() == t ) && ( (*idx)->getId() == id ) ){ + RetVal = (*idx); + break; + }; + } else { + if( (*idx)->getType() == t ){ + RetVal = (*idx); + break; + }; + }; + }; + }; + m_mModulesProtector.unlock(); + return RetVal; +}; + +bool kernelModuleFactory::validate( void ){ + return ( m_bThreadStatus < TH_ENDED ); +}; + +void kernelModuleFactory::m_fThreadProc( void ){ + if( m_pDBC == NULL) { + m_bThreadStatus = TH_ENDED; + } else { + DBC_INT_LIST *tList = NULL; +#ifdef MEM_DEBUG + size_t memStart, memEnd, memDiff; + char MEM_MSG[256]; +#endif + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { +#ifdef MEM_DEBUG + memStart = getCurrentRSS(); +#endif + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + DBC_INT_LIST tL; + for( int cm = 0; cm < m_vKernelModules.size(); cm++ ) tL.push_back( m_vKernelModules.at(cm)->getId() ); + tList = m_pDBC->listNewModules( &tL ); + tL.clear(); + } else { + tList = m_pDBC->listNewModules( NULL ); + }; + m_mModulesProtector.unlock(); + if( tList != NULL ) { +#ifdef DEBUG + LOG("New Modules Exists!"); +#endif + for( int index=0; index< tList->size(); index++) createModule(tList->at(index)); + tList->clear(); + delete( tList ); + }; +#ifdef MEM_DEBUG + memEnd = getCurrentRSS(); + memDiff = memEnd - memStart; + sprintf(MEM_MSG,"MEM START: %d MEM DIF1: %d", memStart, memDiff ); + LOG( MEM_MSG ); +#endif + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + //Get Full List + //tList = NULL; + tList = m_pDBC->listModules(); + if( tList != NULL ) { + int cm = 0; + while( cm < m_vKernelModules.size() ) { + //check if module removed + bool tRemoved = true; + for( int lm = 0; lm < tList->size(); lm++ ) { + if( tList->at(lm) == m_vKernelModules.at( cm )->getId() ) { + tRemoved = false; + break; + }; + }; + if( !tRemoved ) { + // validate module + m_vKernelModules.at( cm )->validate(); + cm++; + } else { +#ifdef DEBUG + LOG("Delete Module!"); +#endif + deleteModule( cm ); + }; + }; + tList->clear(); + delete( tList ); + } else { +#ifdef DEBUG + LOG("All Modules Must be Deleted!"); +#endif + while( m_vKernelModules.size() ) deleteModule( 0 ); + }; + } +#ifdef DEBUG_EXTRA + else { + LOG("No Modules to Validate!"); + } +#endif + ; + m_mModulesProtector.unlock(); +#ifdef MEM_DEBUG + memEnd = getCurrentRSS(); + memDiff = memEnd - memStart; + sprintf(MEM_MSG,"MEM START: %d MEM DIF2: %d", memStart, memDiff ); + LOG( MEM_MSG ); +#endif + if( !m_bInitialValidatioonDone ) m_bInitialValidatioonDone = true; + for( int i = ( 5000 / DEFAULT_THREAD_SLEEP_TIME ); i && ( m_bThreadStatus < TH_ENDED ); i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + }; + }; +}; +//--enable-gpl --enable-libx264 --enable-nonfree --extra-ldflags=-latomic --enable-omx --enable-omx-rpi +//-rtsp_transport tcp + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/common/kernelModuleFactory.h b/lib/App/common/kernelModuleFactory.h new file mode 100644 index 00000000..8610a742 --- /dev/null +++ b/lib/App/common/kernelModuleFactory.h @@ -0,0 +1,40 @@ +#ifndef __KERNEL_MODULE_FACTORY_HEADER__ +#define __KERNEL_MODULE_FACTORY_HEADER__ + +#include "../components/base/basicThread.h" +#include "../components/base/basicMutex.h" +#include "kernelModule.h" +#include "dataBinder.h" + + + +class kernelModuleFactory: public basicThread{ + private: + basicLogCollection * m_pLog; + dataBinder * m_pDBC; + uint32_t m_nInstanceID; + vectorKernelModules m_vKernelModules; + basicMutex m_mModulesProtector; + bool m_bInitialValidatioonDone; + void deleteModule( kernelModule * ); + public: + static kernelModuleFactory * getInstance( uint32_t InstanceID = 0 ); + virtual ~kernelModuleFactory(); + kernelModule * createModule( int id ); + void deleteModule( int id ); + kernelModule * getModule( uint32_t id ); + kernelModule * getModule( KERNEL_MODULE_TYPE t, uint32_t id = 0 ); + uint32_t getModulesCount( KERNEL_MODULE_TYPE t ); + uint32_t fetchModules( KERNEL_MODULE_TYPE, kernelModule**&RA ); + bool loadModules( void ); + bool validate( void ); + void shutdownServices( bool force = false ); + bool isValidationDone( void ){ return m_bInitialValidatioonDone; }; + protected: + explicit kernelModuleFactory( uint32_t InstanceID ); + virtual void m_fThreadProc( void ); + private: + static kernelModuleFactory * _instance; +}; + +#endif \ No newline at end of file diff --git a/lib/App/common/kernelModuleFlyHunter.cpp b/lib/App/common/kernelModuleFlyHunter.cpp new file mode 100644 index 00000000..3969b274 --- /dev/null +++ b/lib/App/common/kernelModuleFlyHunter.cpp @@ -0,0 +1,474 @@ +#include "kernelModuleFlyHunter.h" + +#define LOG( X ) kernelModule::m_pLog->Log( "MOD_FH", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + kernelModule::m_pLog->Log( "MOD_FH", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) kernelModule::m_pLog->Log( "MOD_FH", this, _LOG_ERROR, X ); +#endif + +kernelModuleFlyHunter::kernelModuleFlyHunter( uint32_t ModuleID ): kernelModule( ModuleID, KERNEL_MODULE_FLYHUNTER ), basicThread(){ + memset( &m_sCurrentMission, 0, sizeof(FH_MISSION_DATA) ); + memset( &m_sCurrentlocation, 0 , sizeof(C3D_WGS84_LOC)); + m_pProtocol = NULL; + m_bEnabled = false; + m_bDroneStatus = FH_STATUS_NONE; + m_bWorkingMode = FH_WM_NONE; + m_pEventHeap = basicEventHeap::getInstance(); +}; + +kernelModuleFlyHunter::~kernelModuleFlyHunter(){ + m_bEnabled = false; + waitThreadEnd( true ); + if( m_pProtocol!= NULL ) delete( m_pProtocol ); +}; + +bool kernelModuleFlyHunter::startService(){ + LOG("Starting Service!"); + if( m_bEnabled ) return false; + DBC_FH_DATA *tData = m_pDBC->getFlyHunterData( m_nDBAUXID ); + if( tData == NULL ) return false; + m_sGCSlocation.lat = tData->lat; + m_sGCSlocation.lon = tData->lon; + m_sGCSlocation.alt = tData->alt; + + m_bWorkingMode = FH_WM_NONE; +#ifdef SIMULATE_FH + m_bDroneStatus = FH_STATUS_INIT; + m_bEnabled = true; + m_fStepLat = 0.0f; + m_fStepLon = 0.0f; + m_fStepAlt = 0.0f; + return init(); +#else + m_pProtocol = new protocolMAVLINK(); + if( m_pProtocol!= NULL ) { + m_bDroneStatus = FH_STATUS_INIT; + if( m_pProtocol->create() ) { + m_bEnabled = true; + return init(); + }; + }; +#endif + return false; +}; + +bool kernelModuleFlyHunter::stopService( bool force ){ + return true; +}; + +void kernelModuleFlyHunter::m_fThreadProc(){ + m_bThreadStatus = TH_WORKING; + if( !m_bEnabled ) { + m_bThreadStatus = TH_ENDED; +#ifdef DEBUG + LOG("Module is Disabled!"); +#endif + }; +#ifdef DEBUG + LOG("Module Started!"); +#endif + while( m_bThreadStatus < TH_ENDED ) { + switch( m_bWorkingMode ) { + case FH_WM_CANCELING:{ + m_bWorkingMode = FH_WM_FTL; +#ifdef SIMULATE_FH + m_nSymTO = SIMULATE_FH_FTL_TO; +#endif + break; + }; + case FH_WM_MISSION_FLIGHT:{ + +#ifndef SIMULATE_FH + //IF landed + // Must be Provided comparation + if( m_sGCSlocation.lat == m_sCurrentlocation.lat && m_sGCSlocation.lon == m_sCurrentlocation.lon ){ +#else + if( m_nSymTO ){ + m_nSymTO --; + + m_sCurrentlocation.lat = m_sCurrentlocation.lat + m_fStepLat; + m_sCurrentlocation.lon = m_sCurrentlocation.lon + m_fStepLon; + m_sCurrentlocation.alt = m_sCurrentlocation.alt + m_fStepAlt; + + } else { +#endif + EVENT_CONTAINER * newEvt = NULL; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sCurrentlocation, sizeof(C3D_WGS84_LOC)); + switch( m_sCurrentMission.type ) { + case FH_WM_OBSERVE: + LOG("OBSERVE Mission"); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_DEST_REACHED, NULL, NULL, evtData ); + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; + break; + case FH_WM_JAMING: + LOG("JAMING Mission"); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_JAMER_ON, NULL, NULL, evtData ); + m_bWorkingMode = FH_WM_JAMING; + m_nJamingTO = m_nJamingTO; + break; + case FH_WM_INTERCEPT: + LOG("INTERCEPT Mission"); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_INTERCEPT_BEGIN, NULL, NULL, evtData ); + m_bWorkingMode = FH_WM_INTERCEPT; +#ifdef SIMULATE_FH + m_nSymTO = SIMULATE_FH_INTERCEPT; +#endif + break; + default: + LOG("No Mission Type SET!!"); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_DEST_REACHED, NULL, NULL, evtData ); + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; + }; + if( newEvt ) { + // Propogate Event + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + }; + break; + }; + case FH_WM_INTERCEPT:{ +#ifndef SIMULATE_FH + //IF landed + // Must be Provided comparation + //if( m_sGCSlocation.lat == m_sCurrentlocation.lat && m_sGCSlocation.lon == m_sCurrentlocation.lon ){ +#else + if( m_nSymTO ){ + m_nSymTO --; + } else { + float R = RAND_MAX / rand(); +#endif + EVENT_CONTAINER * newEvt = NULL; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sCurrentlocation, sizeof(C3D_WGS84_LOC)); +#ifdef SIMULATE_FH + if( R > 0.5 ) { + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_INTERCEPT_OK, NULL, NULL, evtData ); + } else { + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_INTERCEPT_NOK, NULL, NULL, evtData ); + }; +#endif + if( newEvt ) { + // Propogate Event + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; + }; + }; + break; + }; + case FH_WM_JAMING:{ + if( m_nJamingTO ) { + if( m_nJamingTO == 1 ) { + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sCurrentlocation, sizeof(C3D_WGS84_LOC)); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_JAMER_OFF, NULL, NULL, evtData ); + if( newEvt ) { + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; +#ifndef SIMULATE_FH + m_pProtocol->broadcastSetBaseMode( POSHOLD ); +#endif + }; + m_nJamingTO--; + } else { + //If Accedently entering in this mode! + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; +#ifndef SIMULATE_FH + m_pProtocol->broadcastSetBaseMode( POSHOLD ); +#endif + }; + break; + }; + case FH_WM_HOOVERING:{ + // Just Hold Position FH_HOOVERING_INTERVAL seconds + if( m_nHooveringTO ) { + if( m_nHooveringTO == 1 ) { + // No New Assigns -> Going Home +#ifndef SIMULATE_FH + m_pProtocol->broadcastSetBaseMode( RTL ); +#else + m_nSymTO = SIMULATE_FH_FTL_TO; + m_fStepLat = ( m_sGCSlocation.lat - m_sCurrentlocation.lat ) / m_nSymTO; + m_fStepLon = ( m_sGCSlocation.lon - m_sCurrentlocation.lon ) / m_nSymTO; + m_fStepAlt = ( m_sGCSlocation.alt - m_sCurrentlocation.alt ) / m_nSymTO; +#endif + m_bWorkingMode = FH_WM_FTL; + + }; + m_nHooveringTO--; + }; + break; + }; + case FH_WM_EMERGENCY_FTL: + case FH_WM_FTL:{ +#ifndef SIMULATE_FH + //IF landed + // Must be Provided comparation + if( m_sGCSlocation.lat == m_sCurrentlocation.lat && m_sGCSlocation.lon == m_sCurrentlocation.lon ){ +#else + if( m_nSymTO ){ + m_nSymTO --; + + m_sCurrentlocation.lat = m_sCurrentlocation.lat + m_fStepLat; + m_sCurrentlocation.lon = m_sCurrentlocation.lon + m_fStepLon; + m_sCurrentlocation.alt = m_sCurrentlocation.alt + m_fStepAlt; + + } else { +#endif + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sGCSlocation, sizeof(C3D_WGS84_LOC)); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_LANDED, NULL, NULL, evtData ); + if( newEvt ) { + // Propogate Event + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + // Turn Off Motors +#ifndef SIMULATE_FH + if( m_pProtocol->broadcastArm( false ) ){ + // Stop Chakalaka!! + m_bDroneStatus = FH_STATUS_PREARM; + m_bWorkingMode = FH_WM_NONE; + }; +#else + m_bDroneStatus = FH_STATUS_PREARM; + m_bWorkingMode = FH_WM_NONE; +#endif + }; + break; + }; + }; + + switch( m_bDroneStatus ) { + case FH_STATUS_INIT:{ +#ifndef SIMULATE_FH + if( m_pProtocol->broadcastProtocolVersionReq() ){ + m_bDroneStatus = FH_STATUS_CONNECT; + } else SLEEP ( 1000 ); +#else + m_bDroneStatus = FH_STATUS_PREARM; +#endif + break; + }; + case FH_STATUS_PREARM:{ + if( m_bWorkingMode > FH_WM_FTL ) { +#ifndef SIMULATE_FH + // Turn On Motors + if( m_pProtocol->broadcastArm( true ) ){ + //Run Chakalaka!! + m_bDroneStatus = FH_STATUS_ARMED; + m_bWorkingMode = FH_WM_START_FLIGHT; + }; +#else + m_bDroneStatus = FH_STATUS_ARMED; + m_bWorkingMode = FH_WM_START_FLIGHT; +#endif + }; + break; + }; + case FH_STATUS_ARMED:{ +#ifndef SIMULATE_FH + // Lift Up + if( m_pProtocol->broadcastTakeoff( 10.0f ) ){ + m_bDroneStatus = FH_STATUS_FLYING; + }; +#else + m_bDroneStatus = FH_STATUS_FLYING; +#endif + break; + }; + case FH_STATUS_FLYING:{ + if( m_bWorkingMode == FH_WM_START_FLIGHT ){ +#ifndef SIMULATE_FH + if( m_pProtocol->setTargetPosition( m_sCurrentMission.location.lat, m_sCurrentMission.location.lon, m_sCurrentMission.location.alt, 0 ) ){ + m_bWorkingMode = FH_WM_MISSION_FLIGHT; + }; +#else + m_bWorkingMode = FH_WM_MISSION_FLIGHT; + m_nSymTO = SIMULATE_FH_FLY; + + m_sCurrentlocation.lat = m_sGCSlocation.lat; + m_sCurrentlocation.lon = m_sGCSlocation.lon; + m_sCurrentlocation.alt = m_sGCSlocation.alt; + + m_fStepLat = ( m_sCurrentMission.location.lat - m_sGCSlocation.lat ) / m_nSymTO; + m_fStepLon = ( m_sCurrentMission.location.lon - m_sGCSlocation.lon ) / m_nSymTO; + m_fStepAlt = ( m_sCurrentMission.location.alt - m_sGCSlocation.alt ) / m_nSymTO; +#endif + }; + //Update Position to other components + if( m_nWayPointTO ) { + m_nWayPointTO --; + }; + if( m_nWayPointTO == 0 ){ + m_nWayPointTO = FH_WAYPOINT_UPDATE_INTERVAL; + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sCurrentlocation, sizeof(C3D_WGS84_LOC)); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_WAYPOINT, NULL, NULL, evtData ); + if( newEvt ) { + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + }; + break; + }; + };// Drone Status Switch +#ifdef SIMULATE_FH + SLEEP( 1000 ); +#endif + }; +}; + +void kernelModuleFlyHunter::dispatchEvent(EVENT_CONTAINER *Evt){ + if(!m_bEnabled) { + LOG("Module Disabled!"); + return; + } + if( Evt == NULL ) return; + switch( Evt->m_eClass ){ + case EVT_CLASS_EXTERNAL_CMD:{ + switch( Evt->m_eType ) { + case EVT_FH_MISSION_BEGIN:{ + if( + ( ( m_bDroneStatus == FH_STATUS_PREARM ) && ( m_bWorkingMode == FH_WM_NONE ) ) || + ( ( ( m_bDroneStatus == FH_STATUS_ARMED ) && ( ( m_bWorkingMode == FH_WM_HOOVERING ) || ( m_bWorkingMode == FH_WM_FTL ) ) ) ) + ){ + FH_CTRL_DATA * tData = (FH_CTRL_DATA *) Evt->m_pEvtData; + DBC_EVT_RECORD * tEVT = m_pDBC->getEventByUUID( tData->targetUUID ); + if( tEVT ) { + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + evtData->location.lat = tEVT->lat; + evtData->location.lon = tEVT->lon; + evtData->location.alt = tEVT->alt; + sprintf( evtData->missionID, tData->evtUUID ); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_FLY_TO, NULL, NULL, evtData ); + if( newEvt ) { + memcpy( &m_sCurrentMission, evtData, sizeof(FH_MISSION_DATA) ); + m_sCurrentMission.type = FH_WM_INTERCEPT; + m_bWorkingMode = FH_WM_MISSION_BEGIN; + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + free( tEVT ); + } else { + // Not Found In Database + }; + } else { +#ifdef DEBUG + LOG("BUSY!"); + char tB[128]; + sprintf( tB, "DS: %02d WM: %02d", m_bDroneStatus, m_bWorkingMode ); + LOG( tB ); +#endif + if( Evt->m_pEvtData!= NULL ) { + FH_CTRL_DATA * tEData = (FH_CTRL_DATA *) Evt->m_pEvtData; + FH_CTRL_DATA * tNData = (FH_CTRL_DATA *) malloc(sizeof(FH_CTRL_DATA)); + if( tNData != NULL ) { + EVENT_CONTAINER * tEvt; + memcpy(tNData, tEData, sizeof(FH_CTRL_DATA)); + tEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_BUSY, NULL, NULL, tNData ); + if( tEvt!= NULL ) { + m_pEventHeap->broadcast( tEvt ); + } else { + free( tNData ); + }; + }; + }; + }; + break; + }; + case EVT_FH_JAMING_BEGIN:{ // FH_CTRL_DATA + if( m_bWorkingMode == FH_WM_MISSION_FLIGHT || m_bWorkingMode == FH_WM_HOOVERING || m_bWorkingMode == FH_WM_FTL ){ + FH_CTRL_DATA * tData = (FH_CTRL_DATA *) Evt->m_pEvtData; + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_JAMER_ON, NULL, NULL, evtData ); + if( newEvt ) { + m_bWorkingMode = FH_WM_JAMING; + m_sCurrentMission.type = FH_WM_JAMING; + m_nJamingTO = tData->param; + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + } else { + // No Jaming When No Mission is assigned + if( Evt->m_pEvtData!= NULL ) { + FH_CTRL_DATA * tEData = (FH_CTRL_DATA *) Evt->m_pEvtData; + FH_CTRL_DATA * tNData = (FH_CTRL_DATA *) malloc(sizeof(FH_CTRL_DATA)); + if( tNData != NULL ) { + EVENT_CONTAINER * tEvt; + memcpy(tNData, tEData, sizeof(FH_CTRL_DATA)); + tEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_BUSY, NULL, NULL, tNData ); + if( tEvt!= NULL ) { + m_pEventHeap->broadcast( tEvt ); + } else { + free( tNData ); + }; + }; + }; + }; + break; + }; + case EVT_FH_CANCEL_ACTION:{ + m_bWorkingMode = FH_WM_CANCELING; + break; + }; + }; // Case Class + break; + }; + }; +}; + +bool kernelModuleFlyHunter::reloadSettings(){ + return true; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/kernelModuleFlyHunter.h b/lib/App/common/kernelModuleFlyHunter.h new file mode 100644 index 00000000..45b36d36 --- /dev/null +++ b/lib/App/common/kernelModuleFlyHunter.h @@ -0,0 +1,73 @@ +#ifndef __KERNEL_MODULE_FLY_HUNTER_HEADER__ +#define __KERNEL_MODULE_FLY_HUNTER_HEADER__ +#include "kernelModule.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" + +#include "../data/protocol/protocolMAVLINK.h" + +#define SIMULATE_FH + +#ifdef SIMULATE_FH +#define SIMULATE_FH_FLY 40 +#define SIMULATE_FH_INTERCEPT 30 +#define SIMULATE_FH_FTL_TO 40 +#endif + +typedef enum E_FH_STATUS{ + FH_STATUS_NONE = 0, + FH_STATUS_INIT = 1, + FH_STATUS_CONNECT = 2, + FH_STATUS_READ_DATA = 3, + FH_STATUS_ERROR = 4, + FH_STATUS_PREARM = 5, + FH_STATUS_ARMED = 6, + FH_STATUS_FLYING = 7 +}FH_STATUS; + +typedef enum E_FH_WM{ + FH_WM_NONE = 0, + FH_WM_CANCELING = 1, + FH_WM_HOOVERING = 2, + FH_WM_FTL = 3, + FH_WM_MISSION_BEGIN = 4, + FH_WM_START_FLIGHT = 5, + FH_WM_MISSION_FLIGHT = 6, + FH_WM_INTERCEPT = 7, + FH_WM_JAMING = 8, + FH_WM_OBSERVE = 9, + FH_WM_EMERGENCY_FTL = 10 +}FH_WM; + +#define FH_WAYPOINT_UPDATE_INTERVAL 15 +#define FH_HOOVERING_INTERVAL 25 + +class kernelModuleFlyHunter: public kernelModule, public basicThread { + private: + basicEventHeap * m_pEventHeap; + FH_MISSION_DATA m_sCurrentMission; + FH_WM m_bWorkingMode; + FH_STATUS m_bDroneStatus; + uint16_t m_nJamingTO; + uint16_t m_nWayPointTO; + uint16_t m_nHooveringTO; +#ifdef SIMULATE_FH + uint16_t m_nSymTO; + float m_fStepLat; + float m_fStepLon; + float m_fStepAlt; +#endif + C3D_WGS84_LOC m_sCurrentlocation; + C3D_WGS84_LOC m_sGCSlocation; + protocolMAVLINK * m_pProtocol; + protected: + virtual void m_fThreadProc( void ); + public: + explicit kernelModuleFlyHunter( uint32_t oduleID ); + ~kernelModuleFlyHunter(); + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); +}; +#endif diff --git a/lib/App/common/kernelModuleKafka.cpp b/lib/App/common/kernelModuleKafka.cpp new file mode 100644 index 00000000..aad5fe6a --- /dev/null +++ b/lib/App/common/kernelModuleKafka.cpp @@ -0,0 +1,760 @@ +#include "kernelModuleKafka.h" +//#include "mojoKernel.h" +#include "../hardware/soc/general/3DLRF.h" +#include "../data/json/json_tool.h" +#include +#include +#include +#include + +#define LOG( X ) kernelModule::m_pLog->Log( "MOD_KAFKA", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + kernelModule::m_pLog->Log( "MOD_KAFKA", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) kernelModule::m_pLog->Log( "MOD_KAFKA", this, _LOG_ERROR, X ); +#endif + +kernelModuleKafka::kernelModuleKafka( uint32_t ModuleID ): kernelModule( ModuleID, KERNEL_MODULE_KAFKA ){ + m_pProtocol = NULL; + m_bConsumerEnabled = false; + m_pEventHeap = basicEventHeap::getInstance(); + partition = 0; //RdKafka::Topic::PARTITION_UA; + //start_offset = RdKafka::Topic::OFFSET_END;// OFFSET_BEGINNING; + start_offset = 0;//RdKafka::Topic::OFFSET_BEGINNING; + //start_offset = RdKafka::Topic::OFFSET_STORED; + + memset( m_sServerIP, 0 ,48 ); + CSTR TVAL = NULL;//m_pKernel->getServerIp(); + if ( TVAL ) { + strncpy( m_sServerIP, TVAL, 48 ); + free( TVAL ); + } else { + LOG_ERROR("Error Get Argus Server IP!"); + strncpy( m_sServerIP, "192.168.0.127", 48 ); + }; + memset( m_sServerName, 0, 48 ); + TVAL = NULL;//m_pKernel->getServerName(); + if ( TVAL ) { + strncpy( m_sServerName, TVAL, 48 ); + free( TVAL ); + } else { + LOG_ERROR("Error Get Argus Server Name!"); + strncpy( m_sServerName, "Argus Server", 48 ); + }; + + m_pEvtTemplates = (KAFKA_TEMPLATE***) calloc(EVT_CLASS_COUNT, sizeof(KAFKA_TEMPLATE**)); + if( m_pEvtTemplates!= NULL ) { + memset( m_pEvtTemplates, 0, EVT_CLASS_COUNT * sizeof(KAFKA_TEMPLATE**)); + } else LOG_ERROR("EVT Templates Memory Allocation Error!"); + /* + Do it in Kernel!! + if ( m_pKernel!= NULL ) { + argusHardwareManager *tHWM = m_pKernel->getHardwareManager(); + if( tHWM != NULL ) { + DBC_INT_LIST *rIDS = tHWM->requestResourcesByType( ARGUS_HARDWARE_PROVIDER_NETWORK ); + if( rIDS != NULL ) { + for( DBC_INT_LIST::iterator idx = rIDS->begin(); idx < rIDS->end(); idx++ ){ + argusHardwareResourceNetwork *tRES = (argusHardwareResourceNetwork *) tHWM->requestResource( ARGUS_HARDWARE_PROVIDER_NETWORK, *idx ); + if( tRES != NULL ) { + m_pServerIP = tRES->getAddress(); + break; + } else { + LOG_ERROR("Cannot Get Resource!"); + }; + }; + delete( rIDS ); + } else { + LOG("No Networks Detected!"); + m_bEnabled = false; + }; + } else { + LOG_ERROR("No HW Manager"); + }; + } else { + LOG_ERROR("No Kernel"); + }; + */ +}; + +kernelModuleKafka::~kernelModuleKafka(){ + + m_bEnabled = false; + + waitThreadEnd( true ); + + if( m_pProtocol!= NULL ) { + delete( m_pProtocol ); + }; + + if( m_pEvtTemplates!= NULL ) { + for(int i=0; i < EVT_CLASS_COUNT; i++ ) { + if( m_pEvtTemplates[i] != NULL ){ + for( int j=0; j< EVT_COUNT; j++ ) { + if( m_pEvtTemplates[i][j] != NULL ){ + if( m_pEvtTemplates[i][j]->tpl ) free( m_pEvtTemplates[i][j]->tpl ); + free( m_pEvtTemplates[i][j] ); + }; + }; + free( m_pEvtTemplates[i] ); + }; + }; + free( m_pEvtTemplates ); + }; +}; +/* Periodical Job Handler */ +void kernelModuleKafka::m_fThreadProc( void ){ +#ifdef SIMULATOR + float sim_Az = 0.f; + float sim_El = 20.f; + float sim_Ran = 80.35f; + float tr_Az_step = 0.3f; + uint32_t src = 128; +#endif +#ifdef DEBUG + LOG("Pereodical Jobs Started"); +#endif + m_bThreadStatus = TH_WORKING; + if( !m_bEnabled ) { + m_bThreadStatus = TH_ENDED; +#ifdef DEBUG + LOG("Module is Disabled!"); +#endif + }; + while( m_bThreadStatus < TH_ENDED ) { + m_llTicks ++;//= getMilliseconds(); + if( m_llTicks % 20 == 0 ) { // each 2 seconds +#ifdef SIMULATOR + sim_Az += tr_Az_step; + for(int i=0; i < EVT_CLASS_COUNT; i++ ) { + if( m_pEvtTemplates[i] != NULL ){ + for( int j=0; j< EVT_COUNT; j++ ) { + if( m_pEvtTemplates[i][j] != NULL ){ + CSTR tpl; + CSTR ts; + CSTR uuid; + char LON[10]; + char LAT[10]; + char AZ[10]; + char EL[10]; + char RN[10]; + float lat = 32.906153575029926; + float lon = 35.09629379621815; + sprintf( AZ, "%.3f", sim_Az+(0.6/RAND_MAX)*rand()); + sprintf( EL, "%.3f", sim_El+(0.6/RAND_MAX)*rand()); + sprintf( RN, "%.3f", sim_Ran+(0.6/RAND_MAX)*rand()); + sprintf( LAT, "%.10f", lat+(0.00006/RAND_MAX)*rand() ); + sprintf( LON, "%.10f", lon+(0.00006/RAND_MAX)*rand() ); + uuid = getUniqID_UUID(); + ts = getTimeStamp(); + src = i; + tpl = buildTemplate( m_pEvtTemplates[i][j]->tpl, src, ts, uuid, AZ, RN, EL, LAT, LON ); + if( tpl ) { + m_pProtocol->issuePost( m_pEvtTemplates[i][j]->topic, tpl, strlen( tpl ) ); + free( tpl ); + }; + if( uuid ) free( uuid ); + if( ts ) free( ts ); + }; + }; + }; + }; +#endif + }; + if( m_bConsumerEnabled ) { + for( uint8_t idx = 0; idx < EVT_COUNT; idx++ ) { + if( m_pEvtTemplates[EVT_CLASS_EXTERNAL_CMD][idx] != NULL ){ + char BUF[1024]; + int len; + if( m_pProtocol->receivePost( m_pEvtTemplates[EVT_CLASS_EXTERNAL_CMD][idx]->topic, partition, start_offset, BUF, len ) ){ + if( len > 0 ) { + start_offset++; +#ifdef DEBUG + char ttt[64]; + LOG(" HAVE MESSAGE "); + sprintf( ttt, " MSG Len: %d", len ); + LOG( ttt ); +#endif + if( len > 0 ){ + LOG ( BUF ); + try{ + Json::Value root; +#ifdef OLD_WAY_JSON + Json::Reader reader; + if( !reader.parse( BUF, root ) ){ + LOG_ERROR( "Error parsing the string" ); + } else { +#else + JSONCPP_STRING err; + Json::CharReaderBuilder builder; + const std::unique_ptr reader(builder.newCharReader()); + if (!reader->parse(BUF, BUF + len, &root, &err)) { + LOG_ERROR( "Error parsing the string" ); + LOG_ERROR( err.c_str() ); + } else { +#endif + + if (root.size()) { + FH_CTRL_DATA * tData; + basicEventTypeID evtID = EVT_NOINIT; + Json::Value tVal; + tData =(FH_CTRL_DATA *)malloc( sizeof(FH_CTRL_DATA)); + if( tData ) { + memset( tData, 0, sizeof(FH_CTRL_DATA)); + tVal = root["id"]; + + if (!tVal.isNull()) { + #ifdef DEBUG + LOG(tVal.asString().c_str()); + #endif + sprintf( tData->cmdUUID, "%s", tVal.asString().c_str() ); + }; + tVal = root["action"]; + if (!tVal.isNull()) { + #ifdef DEBUG + LOG( tVal.asString().c_str() ); + #endif + if ( strcasecmp(tVal.asString().c_str(), "intercept_target") == 0) { + evtID = EVT_FH_MISSION_BEGIN; + }; + if ( strcasecmp(tVal.asString().c_str(), "jam_target") == 0) { + tData->param = atoi( tVal.asString().c_str()+10 ); + if( tData->param == 0 ) { + tData->param = FH_DEFAULT_JAMING_TIME; + }; + evtID = EVT_FH_JAMING_BEGIN; + }; + if ( strcasecmp(tVal.asString().c_str(), "cancel") == 0) { + evtID = EVT_FH_CANCEL_ACTION; + }; + }; + tVal = root["event_id"]; + if (!tVal.isNull()) { + #ifdef DEBUG + LOG( tVal.asString().c_str() ); + #endif + sprintf( tData->evtUUID, "%s", tVal.asString().c_str() ); + }; + tVal = root["target_id"]; + if (!tVal.isNull()) { + #ifdef DEBUG + LOG( tVal.asString().c_str() ); + #endif + sprintf( tData->targetUUID, "%s", tVal.asString().c_str() ); + }; + if( evtID ) { + EVENT_CONTAINER * tEVT; + tEVT = createBasicEvent( 0, EVT_CLASS_EXTERNAL_CMD, evtID, NULL, NULL, tData ); + if( tEVT ) { + m_pEventHeap->broadcast( tEVT ); + } else { + free( tData ); + }; + } else { + free( tData ); + }; + }; + }; + }; + } catch( exception e ){ + LOG_ERROR("EXCEPTION"); + }; + }; + }; + }; + }; + }; + }; + SLEEP(100); + }; +}; + +bool kernelModuleKafka::startService(){ + if(!m_bEnabled) return false; + if( reloadSettings() ) { + if( m_pSettings!= NULL ){ + m_pProtocol = new protocolKAFKA( m_pSettings ); + if( m_pProtocol->init() ){ + return init(); + }; + }; + }; + return false; +}; + +bool kernelModuleKafka::stopService( bool force ){ + waitThreadEnd( true ); + return true; +}; + +bool kernelModuleKafka::reloadSettings(){ + if( m_pDBC==NULL ) return false; + if(! m_bEnabled) return false; + m_pSettings = m_pDBC->getSettingsKAFKA( m_nDBAUXID ); + if( m_pSettings != NULL ) { + if( m_pEvtTemplates != NULL ) { + // Clear Templates + for(int i = 0; i < EVT_CLASS_COUNT; i++ ){ + for(int j = 0; j < EVT_COUNT; j++ ){ + if( m_pEvtTemplates[i] != NULL ){ + if( m_pEvtTemplates[i][j] != NULL ){ + if( m_pEvtTemplates[i][j]->tpl ) free( m_pEvtTemplates[i][j]->tpl ); + free( m_pEvtTemplates[i][j] ); + m_pEvtTemplates[i][j] = NULL; + }; + }; + }; + free( m_pEvtTemplates[i] ); + m_pEvtTemplates[i] = NULL; + }; + for(int i = 0; i < EVT_CLASS_COUNT; i++ ){ + for(int j = 0; j < EVT_COUNT; j++ ){ + KAFKA_TEMPLATE * tT; + tT = m_pDBC->getKafkaTemplateForEvent( m_nDBAUXID, i, j ); + if( tT != NULL ) { + if( m_pEvtTemplates[i]== NULL ) { + m_pEvtTemplates[i]=(KAFKA_TEMPLATE**)calloc(EVT_COUNT,sizeof(KAFKA_TEMPLATE*)); + memset( m_pEvtTemplates[i], 0, EVT_COUNT * sizeof(KAFKA_TEMPLATE*)); + if( i == EVT_CLASS_EXTERNAL_CMD ) { + m_bConsumerEnabled = true; + }; + }; + m_pEvtTemplates[i][j] = tT; + }; + }; + }; + }; + return true; + }; + return false; +}; +CSTR kernelModuleKafka::buildTemplate( + CSTR tpl, + uint32_t source_id, + CSTR ts, + CSTR uuid, + CSTR az, + CSTR range, + CSTR width, + CSTR el, + CSTR lat, + CSTR lon, + CSTR alt, + CSTR extID, + CSTR src_Name, + CSTR src_IP, + CSTR src_lat, + CSTR src_lon, + CSTR src_alt, + CSTR src_rot_x, + CSTR src_rot_y, + CSTR src_rot_z +){ + CSTR ct1, ct2; + char sid[64]; + if( tpl ) { + sprintf( sid, "%d", source_id ); + ct1 = strReplace( tpl, KAFKA_TPL_SUBST_ID, sid ); + if( ct1 ) { + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_TS, ts ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + if( uuid ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_UUID, uuid ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( az ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_AZ, az ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( range ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_RANGE, range ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( width ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_WIDTH, width ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( el ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_EL, el ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( lat ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_LAT, lat ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( lon ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_LON, lon ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( alt ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_ALT, alt ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( extID ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_EXEVTD, extID ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_Name ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_NAME, src_Name ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_IP ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_IP, src_IP ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_lat ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_LAT, src_lat ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_lon ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_LON, src_lon ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_alt ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_ALT, src_alt ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_rot_x ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_ROT_X, src_rot_x ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_rot_y ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_ROT_Y, src_rot_y ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_rot_z ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_ROT_Z, src_rot_z ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + //Finalaze Message by System Wide Data + // UUID + CSTR TVAL = getUniqID_UUID(); + if ( TVAL != NULL ) { + ct2 = strReplace(ct1, KAFKA_TPL_SUBST_MSG_UUID, TVAL ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + free( TVAL ); + } else { + LOG_ERROR("Error Generate Message UUID!"); + }; + // Server IP + + ct2 = strReplace(ct1, KAFKA_TPL_SUBST_SRV_IP, m_sServerIP ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + // Server Name + ct2 = strReplace(ct1, KAFKA_TPL_SUBST_SRV_NAME, m_sServerName ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + return ct1; + }; + } + return NULL; +}; + +void kernelModuleKafka::dispatchEvent( EVENT_CONTAINER *Evt ){ + if( Evt == NULL ) return; + if( !m_bEnabled ) return; +#ifdef DEBUG + char tBuffer[256]; + sprintf( tBuffer, "Event Class %d Type %d ", Evt->m_eClass , Evt->m_eType ); + LOG( tBuffer ); +#endif + if( m_pEvtTemplates[ Evt->m_eClass ]!= NULL ) { + // We have defined Channel for that class Events + // Skip Event Handling by flags + if( !m_bEvtFlags[ Evt->m_eType ] ){ +#ifdef DEBUG + //LOG("Disabled By FLAG!"); +#endif + //return; + } + // Hadle Event + CSTR tDATA = NULL; + if( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ] != NULL ) { + switch( Evt->m_eType ) { + case EVT_TARGET_2D_BLACK: + case EVT_TARGET_2D_WHITE:{ + TARGET_DATA * tTARGET = ( TARGET_DATA *) Evt->m_pEvtData; + if(tTARGET!=NULL){ + char AZ[10]; + char RA[10]; + char WID[10]; + + char LAT[10]; + char LON[10]; + char ALT[10]; + + char SLAT[10]; + char SLON[10]; + char SALT[10]; + char SROT_X[10]; + char SROT_Y[10]; + char SROT_Z[10]; + char SNAME[64]; + char TS[64]; + + sprintf( AZ,"%0.3f", tTARGET->local_target.fi ); + sprintf( RA,"%0.3f", tTARGET->local_target.r ); + sprintf( WID,"%0.3f", tTARGET->area ); + sprintf( LAT,"%0.6f", tTARGET->global_target.lat ); + sprintf( LON,"%0.6f", tTARGET->global_target.lon ); + sprintf( ALT,"%0.6f", tTARGET->global_target.alt ); + sprintf( TS, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", + ( Evt->sTS.tm_year+1900), + (Evt->sTS.tm_mon+1), + Evt->sTS.tm_mday, + Evt->sTS.tm_hour, + Evt->sTS.tm_min, + Evt->sTS.tm_sec, + (Evt->m_UMSTS%1000) + ); + sprintf( SLAT,"%0.6f", tTARGET->source_position.lat ); + sprintf( SLON,"%0.6f", tTARGET->source_position.lon ); + sprintf( SALT,"%0.6f", tTARGET->source_position.alt ); + + sprintf( SROT_X,"%0.6f", tTARGET->source_orient.rot_x ); + sprintf( SROT_Y,"%0.6f", tTARGET->source_orient.rot_y ); + sprintf( SROT_Z,"%0.6f", tTARGET->source_orient.rot_z ); + CSTR tN = m_pDBC->getNodeName( Evt->m_nSourceNodeID ); + if ( tN ) { + strncpy( SNAME, tN, 64 ); + free( tN ); + } else { + strncpy(SNAME, "Noname-Laser-Detector", 64); + }; + tDATA = buildTemplate( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ]->tpl, + Evt->m_nSourceNodeID, + TS, + Evt->m_UUID, + AZ, + RA, + WID, + NULL, + LAT, + LON, + ALT, + NULL, + SNAME, + m_sServerIP, + SLAT, + SLON, + SALT, + SROT_X, + SROT_Y, + SROT_Z + ); + }; + break; + }; + case EVT_TARGET_3D_BLACK: + case EVT_TARGET_3D_WHITE:{ + TARGET_DATA * tTARGET = ( TARGET_DATA *) Evt->m_pEvtData; + if(tTARGET!=NULL){ + char AZ[10]; + char EL[10]; + char RA[10]; + char WID[10]; + char LAT[10]; + char LON[10]; + char ALT[10]; + + char SLAT[10]; + char SLON[10]; + char SALT[10]; + char SROT_X[10]; + char SROT_Y[10]; + char SROT_Z[10]; + + char SIP[16]; + char SNAME[64]; + + char TS[64]; + sprintf( AZ,"%0.3f", tTARGET->local_target.fi ); + sprintf( EL,"%0.3f", tTARGET->local_target.tetta ); + sprintf( RA,"%0.3f", tTARGET->local_target.r ); + sprintf( WID,"%0.3f", tTARGET->area ); + sprintf( LAT,"%0.6f", tTARGET->global_target.lat ); + sprintf( LON,"%0.6f", tTARGET->global_target.lon ); + sprintf( ALT,"%0.6f", tTARGET->global_target.alt ); + sprintf( TS, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", + ( Evt->sTS.tm_year+1900), + (Evt->sTS.tm_mon+1), + Evt->sTS.tm_mday, + Evt->sTS.tm_hour, + Evt->sTS.tm_min, + Evt->sTS.tm_sec, + (Evt->m_UMSTS%1000) + ); + sprintf( SLAT,"%0.6f", tTARGET->source_position.lat ); + sprintf( SLON,"%0.6f", tTARGET->source_position.lon ); + sprintf( SALT,"%0.6f", tTARGET->source_position.alt ); + + sprintf( SROT_X,"%0.6f", tTARGET->source_orient.rot_x ); + sprintf( SROT_Y,"%0.6f", tTARGET->source_orient.rot_y ); + sprintf( SROT_Z,"%0.6f", tTARGET->source_orient.rot_z ); + CSTR tN = m_pDBC->getNodeName( Evt->m_nSourceNodeID ); + if ( tN ) { + strncpy( SNAME, tN, 64 ); + free( tN ); + } else { + strncpy(SNAME, "Noname-Laser-Detector", 64); + }; + + if ( 0 ) { + strncpy( SIP, tN, 16 ); + free( tN ); + } else { + strncpy(SIP, "192.168.1.24", 16); + }; + + tDATA = buildTemplate( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ]->tpl, + Evt->m_nSourceNodeID, + TS, + Evt->m_UUID, + AZ, + RA, + WID, + EL, + LAT, + LON, + ALT, + NULL, + SNAME, + SIP, + SLAT, + SLON, + SALT, + SROT_X, + SROT_Y, + SROT_Z + ); + }; + break; + }; + case EVT_FH_JAMER_ON: + case EVT_FH_JAMER_OFF: + case EVT_FH_FLY_TO: + case EVT_FH_WAYPOINT: + case EVT_FH_INTERCEPT_OK: + case EVT_FH_INTERCEPT_NOK: + case EVT_FH_BUSY: + case EVT_FH_LANDED:{ + FH_MISSION_DATA * tPOINT=(FH_MISSION_DATA *) Evt->m_pEvtData; + if( tPOINT ) { + char TS[64]; + char LAT[10]; + char LON[10]; + char ALT[10]; + sprintf( LAT,"%0.6f", tPOINT->location.lat ); + sprintf( LON,"%0.6f", tPOINT->location.lon ); + sprintf( ALT,"%0.6f", tPOINT->location.alt ); + sprintf( TS, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", + ( Evt->sTS.tm_year+1900), + (Evt->sTS.tm_mon+1), + Evt->sTS.tm_mday, + Evt->sTS.tm_hour, + Evt->sTS.tm_min, + Evt->sTS.tm_sec, + (Evt->m_UMSTS%1000) + ); + tDATA = buildTemplate( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ]->tpl, + Evt->m_nSourceNodeID, + TS, + Evt->m_UUID, + NULL, + NULL, + NULL, + NULL, + LAT, + LON, + ALT, + tPOINT->missionID + ); + }; + break; + }; + default:{ + break; + }; + }; + if( tDATA!= NULL ) { +#ifdef KAFKA_DUMMY_SEND + LOG( tDATA ); +#else + m_pProtocol->issuePost( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ]->topic, tDATA, strlen( tDATA ) ); +#endif + } else { + LOG_ERROR("Cant Build Template!"); + }; + }; + }; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/kernelModuleKafka.h b/lib/App/common/kernelModuleKafka.h new file mode 100644 index 00000000..f58a5e9c --- /dev/null +++ b/lib/App/common/kernelModuleKafka.h @@ -0,0 +1,86 @@ +#ifndef __KERNEL_KAFKA_MODULE_HEADERS__ +#define __KERNEL_KAFKA_MODULE_HEADERS__ + + +#include "kernelModule.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" +#include "../data/protocol/protocolKAFKA.h" + +//#define SIMULATOR +//#define KAFKA_DUMMY_SEND + +#define KAFKA_TPL_SUBST_ID "%%ID%%" +#define KAFKA_TPL_SUBST_UUID "%%UUID%%" +#define KAFKA_TPL_SUBST_TS "%%TIMESTAMP%%" +#define KAFKA_TPL_SUBST_AZ "%%AZIMUTH%%" +#define KAFKA_TPL_SUBST_RANGE "%%RANGE%%" +#define KAFKA_TPL_SUBST_EL "%%ELEVATION%%" +#define KAFKA_TPL_SUBST_WIDTH "%%WIDTH%%" +#define KAFKA_TPL_SUBST_LON "%%LON%%" +#define KAFKA_TPL_SUBST_LAT "%%LAT%%" +#define KAFKA_TPL_SUBST_ALT "%%ALT%%" +#define KAFKA_TPL_SUBST_EXEVTD "%%EXEVTID%%" +#define KAFKA_TPL_SUBST_SRC_LON "%%SRC_LON%%" +#define KAFKA_TPL_SUBST_SRC_LAT "%%SRC_LAT%%" +#define KAFKA_TPL_SUBST_SRC_ALT "%%SRC_ALT%%" +#define KAFKA_TPL_SUBST_SRC_ROT_X "%%SRC_ROT_X%%" +#define KAFKA_TPL_SUBST_SRC_ROT_Y "%%SRC_ROT_Y%%" +#define KAFKA_TPL_SUBST_SRC_ROT_Z "%%SRC_ROT_Z%%" +#define KAFKA_TPL_SUBST_SRC_IP "%%SRC_IP%%" +#define KAFKA_TPL_SUBST_SRV_IP "%%SRV_IP%%" +#define KAFKA_TPL_SUBST_SRV_NAME "%%SRV_NAME%%" +#define KAFKA_TPL_SUBST_SRC_NAME "%%SRC_NAME%%" +#define KAFKA_TPL_SUBST_MSG_UUID "%%MUID%%" + + +#define FH_DEFAULT_JAMING_TIME 10 + +class kernelModuleKafka: public kernelModule, public basicThread { + private: + KAFKA_SETTINGS *m_pSettings; + protocolKAFKA *m_pProtocol; + bool m_bConsumerEnabled; + basicEventHeap *m_pEventHeap; + KAFKA_TEMPLATE ***m_pEvtTemplates; + + int32_t partition; + int64_t start_offset; + char m_sServerIP[48]; + char m_sServerName[48]; + unsigned long long m_llTicks; + CSTR buildTemplate( CSTR tpl, + uint32_t source_id, + CSTR ts, + CSTR uuid = NULL, + CSTR az = NULL, + CSTR range = NULL, + CSTR width = NULL, + CSTR el = NULL, + CSTR lat = NULL, + CSTR lon = NULL, + CSTR alt = NULL, + CSTR extID = NULL, + CSTR src_Name = NULL, + CSTR src_IP = NULL, + CSTR src_lat = NULL, + CSTR src_lon = NULL, + CSTR src_alt = NULL, + CSTR src_rot_x = NULL, + CSTR src_rot_y = NULL, + CSTR src_rot_z = NULL + ); + protected: + virtual void m_fThreadProc( void ); + public: + explicit kernelModuleKafka( uint32_t ModuleID ); + virtual ~kernelModuleKafka(); + + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); +}; + + +#endif diff --git a/lib/App/common/kernelModuleModemManager.cpp b/lib/App/common/kernelModuleModemManager.cpp new file mode 100644 index 00000000..5ea37a15 --- /dev/null +++ b/lib/App/common/kernelModuleModemManager.cpp @@ -0,0 +1,324 @@ +#include "kernelModuleModemManager.h" +#include "../../components/base/basicFunctionality.h" + +#define LOG( X ) kernelModule::m_pLog->Log( "MOD_MODEM", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + kernelModule::m_pLog->Log( "MOD_MODEM", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) kernelModule::m_pLog->Log( "MOD_MODEM", this, _LOG_ERROR, X ); +#endif + + +kernelModuleModemManager::kernelModuleModemManager( uint32_t moduleID ): kernelModule( moduleID, KERNEL_MODULE_MODEM_MANAGER ), basicThread(){ + LOG("Creating!"); + if( checkCmdExists("mmcli") > 0 ){ + //Modem Manager Exists + LOG("Manager OK!"); + }; +}; + +kernelModuleModemManager::~kernelModuleModemManager(){ + +}; + +bool kernelModuleModemManager::reloadSettings(){ + return true; +}; + +bool kernelModuleModemManager::startService(){ + return true; +}; + +bool kernelModuleModemManager::stopService( bool force ){ + return true; +}; + +void kernelModuleModemManager::m_fThreadProc( void ){ + +}; + +void kernelModuleModemManager::dispatchEvent(EVENT_CONTAINER *Evt){ +}; + +bool kernelModuleModemManager::validate(){ + DBC_MODEM_DATA *tDATA = getModemInfo( 0 ); + if ( tDATA ) { + free( tDATA ); + }; + return true; +}; + + +void parseModemsInSystem(){ + "mmcli --list-modems"; + +}; + +typedef enum E_CFG_TAG_ID{ + CFG_GENERAL = 0, + CFG_HARDWARE = 1, + CFG_SYSTEM, + CFG_STATUS, + CFG_MODES, + CFG_BANDS, + CFG_IP, + CFG_EPS, + CFG_3GPP, + CFG_SIM, + CFG_BEARER, + CFG_COUNT +}CFG_TAG_ID; + +const CSTR cfg_tags[]={ + "General", + "Hardware", + "System", + "Status", + "Modes", + "Bands", + "IP", + "3GPP EPS", + "3GPP", + "SIM", + "Bearer" +}; + +DBC_MODEM_DATA *kernelModuleModemManager::getModemInfo( uint32_t modem_id ){ + char tB[1024]; + char expBuf[1024]; + FILE * fd = NULL; + CFG_TAG_ID cMode = CFG_GENERAL; + DBC_MODEM_DATA * retVal = (DBC_MODEM_DATA *)malloc(sizeof(DBC_MODEM_DATA)); + + if ( retVal != NULL ) { + memset( retVal, 0 , sizeof(DBC_MODEM_DATA)); + sprintf( tB, "mmcli --modem=%d", modem_id ); + fd = popen( tB, "r"); + if (fd!= NULL ) { + retVal->modem_id = modem_id; + while ( !feof( fd )) { + fgets( (CSTR)tB, 1024, fd ); + trim( tB ); + if( strstr(tB, "error:" ) != NULL){ + free( retVal ); + retVal = NULL; + break; + }; + LOG(tB); + strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ':', expBuf ); + if( CA ){ + if( CA->size() ){ + for( int ii = CFG_GENERAL; ii < CFG_COUNT; ii++ ){ + if( strstr( CA->at(0), cfg_tags[ii] ) != NULL ){ + cMode = (CFG_TAG_ID) ii; + break; + }; + }; + switch( cMode ){ + case CFG_GENERAL:{ + //LOG("GEN"); + if ( strstr( CA->at(0), "device id") != NULL ) { + trim(CA->at(1)); + strncpy( retVal->dbus_dev_id, CA->at(1), 64 ); + retVal->dbus_dev_id[64] = (char)0; + break; + }; + break; + }; + case CFG_HARDWARE:{ + //LOG("HW"); + if ( strstr( tB, "manufacturer") != NULL ) { + trim(CA->at(1)); + strncpy( retVal->hw_manufac, CA->at(1), 64); + retVal->hw_manufac[64] = (char)0; + break; + }; + if ( strstr( tB, "model") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->hw_model, CA->at(1), 64); + retVal->hw_model[64] = (char)0; + break; + }; + if ( strstr( tB, "h/w revision") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->hw_revision, CA->at(1), 64); + retVal->hw_revision[64] = (char)0; + break; + }; + if ( strstr( tB, "revision") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->hw_version, CA->at(1), 32); + retVal->hw_revision[32] = (char)0; + break; + }; + if ( strstr( tB, "equipment id") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->hw_id, CA->at(1), 32); + retVal->hw_id[32] = (char)0; + break; + }; + break; + }; + case CFG_SYSTEM:{ + //LOG("SYS"); + if ( strstr( tB, "ports") != NULL ) { + trim(CA->at(1)); + CArray *CZ = explode( ':', CA->at(1) ); + if ( CZ ) { + int CP = 0; + for (int z=0; z< CZ->size(); z++) { + if ( strstr(CZ->at(z),"(at)")!= NULL ) { + if (CP == 0 ) { + retVal->at_uart_id = 1;//getUartIdByDevice(); + } else { + retVal->at_uart_id_aux = 2; + }; + CP++; + }; + if (CP == 2) break; + }; + delete( CZ ); + }; + break; + }; + break; + }; + case CFG_STATUS:{ + //LOG("STAT"); + if ( strstr( tB, "power state") != NULL ) { + if ( strstr(CA->at(1),"on") ) { + retVal->power[0] = 'E'; + retVal->power[1]=(char)0; + } else { + retVal->power[0] = 'D'; + retVal->power[1]=(char)0; + }; + break; + }; + if ( strstr( tB, "state") != NULL ) { + if ( strstr(CA->at(1),"registered") ) { + retVal->status[0]='R'; + retVal->status[1]=(char)0; + } else { + }; + break; + }; + if ( strstr( tB, "access tech") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->conmection_tech, CA->at(1), 5); + retVal->conmection_tech[5] = (char)0; + break; + }; + if ( strstr( tB, "signal quality") != NULL ) { + trim(CA->at(1)); + retVal->signal = atoi(CA->at(1)); + break; + }; + break; + }; + case CFG_MODES:{ + //LOG("MOD"); + //if ( strstr( CA->at(0), "current") != NULL ) { + // trim(CA->at(1)); + // strncpy( retVal->hw_manufac, CA->at(1), 64); + // retVal->hw_manufac[64] = (char)0; + // break; + //}; + break; + }; + case CFG_IP:{ + //LOG("IP"); + break; + }; + case CFG_EPS:{ + //LOG("EPS"); + break; + }; + case CFG_3GPP:{ + // LOG("3GPP"); + if ( strstr( tB, "imei") != NULL ) { + trim(CA->at(1)); + strncpy( retVal->imei, CA->at(1), 16); + retVal->imei[16] = (char)0; + break; + }; + if ( strstr( tB, "operator id") != NULL ) { + trim(CA->at(1)); + retVal->operator_id = atoi(CA->at(1)); + break; + }; + if ( strstr( tB, "registration") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->registration, CA->at(1), 64); + retVal->registration[64] = (char)0; + break; + }; + break; + }; + case CFG_SIM:{ + // LOG("SIM"); + break; + }; + case CFG_BEARER:{ + // LOG("BEAR"); + break; + }; + //default: LOG("UNK"); + }; + } else { + LOG("No CA Parts!"); + }; + delete( CA ); + } else { + LOG("No CA!"); + }; + }; + fclose(fd); + }; + }; +#ifdef DEBUG_EXTRA + if ( retVal ) { + char ttB[256]; + sprintf(ttB, "Modem ID: [%d]", retVal->modem_id); + LOG(ttB); + sprintf(ttB, "Modem HW Manufac: [%s]", retVal->hw_manufac); + LOG(ttB); + sprintf(ttB, "Modem HW Model: [%s]", retVal->hw_model); + LOG(ttB); + sprintf(ttB, "Modem HW id: [%s]", retVal->hw_id); + LOG(ttB); + sprintf(ttB, "Modem Revision id: [%s]", retVal->hw_revision); + LOG(ttB); + sprintf(ttB, "Modem Revision Version: [%s]", retVal->hw_version); + LOG(ttB); + sprintf(ttB, "Modem DBus id: [%s]", retVal->dbus_dev_id); + LOG(ttB); + sprintf(ttB, "Modem IMEI: [%s]", retVal->imei); + LOG(ttB); + sprintf(ttB, "Modem Access Tech: [%s]", retVal->conmection_tech); + LOG(ttB); + sprintf(ttB, "Modem Operator: [%d]", retVal->operator_id); + LOG(ttB); + sprintf(ttB, "Modem Power: [%s]", retVal->power); + LOG(ttB); + sprintf(ttB, "Modem Registration: [%s]", retVal->registration); + LOG(ttB); + sprintf(ttB, "Modem Signal Power: [%d%%]", retVal->signal); + LOG(ttB); + sprintf(ttB, "Modem Status: [%s]", retVal->status); + LOG(ttB); + }; +#endif + return retVal; +}; + +#undef LOG +#undef LOG_ERROR + + + diff --git a/lib/App/common/kernelModuleModemManager.h b/lib/App/common/kernelModuleModemManager.h new file mode 100644 index 00000000..a9394027 --- /dev/null +++ b/lib/App/common/kernelModuleModemManager.h @@ -0,0 +1,24 @@ +#ifndef __KERNEL_MODULE_MODEM_MANAGER_HEADER__ +#define __KERNEL_MODULE_MODEM_MANAGER_HEADER__ + +#include "kernelModule.h" +#include "../../components/base/basicThread.h" + +class kernelModuleModemManager: public kernelModule, public basicThread { + private: + DBC_MODEM_DATA * getModemInfo( uint32_t modem_id ); + protected: + /* From Basic Thread */ + virtual void m_fThreadProc( void ); + public: + explicit kernelModuleModemManager( uint32_t moduleID ); + ~kernelModuleModemManager(); + /* From Kernel Module */ + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); +}; + +#endif diff --git a/lib/App/common/kernelModuleOnvifObserver.cpp b/lib/App/common/kernelModuleOnvifObserver.cpp new file mode 100644 index 00000000..93602bb4 --- /dev/null +++ b/lib/App/common/kernelModuleOnvifObserver.cpp @@ -0,0 +1,603 @@ +#include "kernelModuleOnvifObserver.h" +#include "hardwareManager.h" +#include "hardwareResourceNetworkProvider.h" + +#define SEARCH_REQUEST_STRING "uuid:84ede3de-7dec-11d0-c360-f01234567890urn:schemas-xmlsoap-org:ws:2005:04:discoveryhttp://schemas.xmlsoap.org/ws/2005/04/discovery/Probedn:NetworkVideoTransmitter" +#define SEARCH_REQUEST_STRING2323 "\n" \ + "\n" \ + "\n" \ + "urn:uuid:ac9823ee-6813-498c-8c1b-6272a22353f7\n" \ + "\n" \ + "http ://schemas.xmlsoap.org/ws/2005/04/discovery/Probe\n" \ + "\n" \ + "urn:schemas-xmlsoap-org:ws:2005:04:discovery\n" \ + "\n" \ + "\n" \ + "\n" \ + "ssdp:any\n" \ + "\n" \ + "\n" \ + "\r\n\r\n" +#define HTTP_OK "200 OK" + +/****************************************************************** +** Action Defines * +*******************************************************************/ +#define HTTP_HEADER_ACTION "POST %s HTTP/1.1\r\n" \ + "HOST: %s:%u\r\n" \ + "SOAPACTION:\"%s#%s\"\r\n" \ + "CONTENT-TYPE: text/xml ; charset=\"utf-8\"\r\n"\ + "Content-Length: %d \r\n\r\n" + +#define SOAP_ACTION "\r\n" \ + "\r\n" \ + "\r\n" \ + "\r\n%s" \ + "\r\n" \ + "\r\n" \ + "\r\n" + +#define PORT_MAPPING_LEASE_TIME "63072000" //two year + +#define ADD_PORT_MAPPING_PARAMS "\r\n" \ + "%u\r\n"\ + "%s\r\n" \ + "%u\r\n"\ + "%s\r\n" \ + "1\r\n" \ + "%s\r\n" \ + "" \ + PORT_MAPPING_LEASE_TIME \ + "\r\n" + + + +#define LOG( X ) kernelModule::m_pLog->Log( "MOD_ONVIF", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + kernelModule::m_pLog->Log( "MOD_ONVIF", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) kernelModule::m_pLog->Log( "MOD_ONVIF", this, _LOG_ERROR, X ); +#endif + + +kernelModuleOnvifObserver::kernelModuleOnvifObserver( uint32_t ModuleID ): kernelModule( ModuleID, KERNEL_MODULE_ONVIF_OBSERVER ), basicThread(){ + m_bEnabled = false; + m_pEventHeap = basicEventHeap::getInstance(); + + m_bCurrentNIF = 0; + m_bProbeIsActive = false; + m_bDetached = false; +#ifdef __linux__ + m_bWSAOK = true; +#else + m_bWSAOK = false; + WORD wVersionRequested; + WSADATA wsaData; + int err; + wVersionRequested = MAKEWORD(2, 2); + err = WSAStartup(wVersionRequested, &wsaData); + if (err != 0){ + LOG_ERROR("WSAStartup failed with error"); + } else m_bWSAOK = true; +#endif +}; + +kernelModuleOnvifObserver::~kernelModuleOnvifObserver(){ + if( !m_bDetached ) stopService( true ); +}; + +bool kernelModuleOnvifObserver::startService(){ + LOG("Starting Service!"); + if( !m_bWSAOK ) return false; + m_bEnabled = reloadSettings(); + return init(); +}; + +bool kernelModuleOnvifObserver::stopService( bool force ){ + m_bEnabled = false; + if( !m_bDetached ) m_bDetached = uninit(); + if( m_bDetached ) { + //Clear Results + m_mResultProtector.lock(); + if (m_vResultPool.size()){ // Clear structures + for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){ + free(*index); + }; + m_vResultPool.clear(); + }; + m_mResultProtector.unlock(); + }; + return m_bDetached; +}; + +/* +#include +#include +#include +#include +#include +#include +#include +#include +#include +// Join multicast group, support both IPv4 and IPv6. * @param sockfd socket descripter * @param grp sockaddr * @param grplen sockaddr length * @return 0:on success; non-zero:on failed +static int mcast_join(int sockfd, const struct sockaddr *grp, socklen_t grplen){ + + #if MCAST_JOIN_GROUP + struct group_req req; + req.gr_interface = 0; + if (grplen > sizeof(req.gr_group)) { + errno = EINVAL; + return -1; + } + memcpy(&req.gr_group, grp, grplen); + return (setsockopt(sockfd, IPPROTO_IP, MCAST_JOIN_GROUP, &req, sizeof(req))); +#else + switch (grp->sa_family) { + case AF_INET: { + struct ip_mreq mreq; + struct ifreq ifreq; + memcpy(&mreq.imr_multiaddr, &((const struct sockaddr_in *) grp)->sin_addr, sizeof(struct in_addr)); + mreq.imr_interface.s_addr = htonl(INADDR_ANY); + return (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, + &mreq, sizeof(mreq))); + } + #ifdef IPV6 + #ifndef IPV6_JOIN_GROUP // APIv0 compatibility + #define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP + #endif + case AF_INET6: { + struct ipv6_mreq mreq6; + memcpy(&mreq6.ipv6mr_multiaddr, &((const struct sockaddr_in6 *) grp)->sin6_addr, sizeof(struct in6_addr)); + mreq6.ipv6mr_interface = 0; + return (setsockopt(sockfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq6, sizeof(mreq6))); + } + #endif + default: + errno = EAFNOSUPPORT; + return -1; + } +#endif +}; + +int main(int argc, char **argv){ + + int fd = socket(AF_INET, SOCK_DGRAM, 0); + struct sockaddr_in grp; + bzero(&grp, sizeof(grp)); + grp.sin_family = AF_INET; + grp.sin_addr.s_addr = inet_addr("224.0.0.1");; + if (mcast_join(fd, (struct sockaddr*)(&grp), sizeof(grp))) + perror("Join multicast group failed"); +} + +*/ + + +void kernelModuleOnvifObserver::m_fThreadProc(){ + int socketFD; + int RetVal; + struct sockaddr_in r_address; + bool bOptVal; + int bOptLen; + int iOptLen; + uint16_t bCounterTO = 600; // 3 second + char rBuffer[MAX_BUFF_SIZE]; +#ifdef DEBUG + char tB[128]; + LOG("Module Started!"); +#endif + m_bDetached = false; + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { + if ( m_bEnabled ) { + if ( m_bProbeIsActive ) { + if( socketFD > -1 ){ + if( bCounterTO-- ){ + memset( rBuffer, 0, MAX_BUFF_SIZE ); +#ifdef DEBUG + struct sockaddr src_addr; + socklen_t addrlen = sizeof( src_addr ); + RetVal = recvfrom( socketFD, rBuffer, MAX_BUFF_SIZE, 0, &src_addr, &addrlen ); + if ( RetVal > -1 ) { + sprintf(tB, "(%d){%d}MSG[%d] from %s", bCounterTO, socketFD, RetVal, inet_ntoa(((struct sockaddr_in *)&src_addr)->sin_addr)); + LOG( tB ); + }; +#else //http://192.168.200.127/axis-cgi/com/ptz.cgi?info=1&camera=1 + RetVal = recvfrom( socketFD, rBuffer, MAX_BUFF_SIZE, 0, NULL, NULL ); +#endif + if ((RetVal == -1) && /*(errno != EAGAIN) &&*/ (errno != EINTR) && (errno != EWOULDBLOCK)) { + LOG_ERROR("Error acures while reading UDP package"); + close( socketFD ); + m_bProbeIsActive = false; + continue; // Error ocured but continue to next address + }; + if( RetVal < 1 ){ + //LOG("SLEEP"); + SLEEP(DEFAULT_THREAD_SLEEP_TIME); + continue; // No Data - wait to next time + }; + OBSERVER_RESULT *tResult = parseXML( rBuffer ); + if ( tResult ) { + m_mResultProtector.lock(); + m_vResultPool.push_back( tResult ); + m_mResultProtector.unlock(); +#ifdef DEBUG + LOG("Probe Finished!"); +#endif + } else { +#ifdef DEBUG + LOG("Probe Finished with unrecognized data!"); +#endif + }; + continue; //To Fetch Another responces + } else { +#ifdef DEBUG + LOG("Probe Finished By Timeout!"); +#endif + }; +#ifdef __linux__ + close(socketFD); +#else + closesocket(socketFD); +#endif + }; + m_bProbeIsActive = false; + //Sleep 5 minutes if done all scans + if ( m_bCurrentNIF == 0 ){ + for( int i=12000; i, m_bThreadStatus < TH_ENDED; i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + }; + } else { + // start new probe; + m_mNIFMUTEX.lock(); + if ( m_vNIFIPS.size() ) { +#ifdef DEBUG + sprintf( tB, "Starting probe on %s address", m_vNIFIPS.at(m_bCurrentNIF) ); + LOG( tB ); +#endif + socketFD = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); + if( socketFD > -1 ){ + CSTR send_buff = (CSTR)SEARCH_REQUEST_STRING; + r_address.sin_family = AF_INET; + r_address.sin_port = htons(HTTPMU_HOST_PORT); + r_address.sin_addr.s_addr = inet_addr(m_vNIFIPS.at(m_bCurrentNIF)); + bOptVal = true; +#ifdef DEBUG + LOG("Set Broadcast Flag"); +#endif + RetVal = setsockopt( socketFD, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen ); + struct group_req req; + req.gr_interface = 0; + memcpy( &req.gr_group, &r_address, sizeof(r_address)); +#ifdef DEBUG + LOG("Join Broadcast Group"); +#endif + RetVal = setsockopt( socketFD, IPPROTO_IP, MCAST_JOIN_GROUP, (char*)&req, sizeof(req) ); + //The broadcast address to be used may be determined by issuing an ioctl() with the SIOCGIFBRDADDR request. + + if ( RetVal > -1 ) { + LOG_ERROR("Setting Socked as Broadcasted Error!"); + }; + + // + struct sockaddr_in tServerAddr; + memset( &tServerAddr, 0, sizeof(tServerAddr) ); + tServerAddr.sin_family = AF_INET; // IPv4 + tServerAddr.sin_addr.s_addr = inet_addr( "0.0.0.0" ); //INADDR_ANY; + tServerAddr.sin_port = htons(rand( 20000, 40000)); + + // Bind the socket with the server address + RetVal = bind( socketFD, (const struct sockaddr *)&tServerAddr, sizeof(tServerAddr)); + if ( RetVal > -1 ) { + LOG_ERROR("Bind Socked Error!"); + }; +#ifdef DEBUG + LOG("Sending Probe Request"); +#endif + RetVal = sendto( socketFD, send_buff, strlen(send_buff), 0, (struct sockaddr*)&r_address, sizeof(struct sockaddr_in)); + if ( RetVal > -1 ) { +#ifdef DEBUG + sprintf( tB, "Sent %d Bytes of %d", RetVal, strlen(send_buff) ); + LOG( tB ); +#endif + +#ifdef __linux__ + fcntl( socketFD, F_SETFL, fcntl( socketFD, F_GETFL, 0) | O_NONBLOCK ); +#else + u_long val = 1; + ioctlsocket( socketFD, FIONBIO, &val );//none block +#endif + bCounterTO = 600; + m_bProbeIsActive = true; + } else { +#ifdef DEBUG + // Failure to send probe package + LOG_ERROR("Error in sending Probe Request"); +#endif +#ifdef __linux__ + close(socketFD); +#else + closesocket(socketFD); +#endif + }; + }; + m_bCurrentNIF++; + if ( m_bCurrentNIF == m_vNIFIPS.size() ) m_bCurrentNIF = 0; + }; + m_mNIFMUTEX.unlock(); + }; + } else { + //Sleep 3 Sec. + for( int i=300; i, m_bThreadStatus < TH_ENDED; i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + }; + }; + m_bDetached = true; +}; + +void kernelModuleOnvifObserver::dispatchEvent(EVENT_CONTAINER *Evt){ + if(!m_bEnabled) { +#ifdef DEBUG + LOG("Module Disabled!"); +#endif + return; + } + if( Evt == NULL ) return; + +}; + +bool kernelModuleOnvifObserver::reloadSettings(){ + m_mNIFMUTEX.lock(); + if( m_vNIFIPS.size() ) { + for ( vectorCSTR::iterator idx=m_vNIFIPS.begin(); idx < m_vNIFIPS.end(); idx++ ) free(*idx); + m_vNIFIPS.clear(); + }; + m_mNIFMUTEX.unlock(); + +#ifdef DEBUG + LOG("Check IPS"); +#endif + hardwareManager *tHWM = hardwareManager::getInstance(); + if( tHWM != NULL ) { +#ifdef DEBUG + LOG("Check IPS 11"); +#endif + DBC_INT_LIST *rIDS = tHWM->requestResourcesByType( HARDWARE_PROVIDER_NETWORK ); + if( rIDS != NULL ) { +#ifdef DEBUG + LOG("Check IPS 22"); +#endif + for( DBC_INT_LIST::iterator idx = rIDS->begin(); idx < rIDS->end(); idx++ ){ +#ifdef DEBUG + LOG("Check IPS 33"); +#endif + hardwareResourceNetwork *tRES = ( hardwareResourceNetwork *) tHWM->requestResource( HARDWARE_PROVIDER_NETWORK, *idx ); + if( tRES != NULL ) { +#ifdef DEBUG + LOG("Have NIF Resource"); +#endif + CSTR BC = tRES->getBroadcast(); + if( BC!= NULL ) { +#ifdef DEBUG + LOG("Have BC Address"); + LOG(BC); +#endif + m_mNIFMUTEX.lock(); + m_vNIFIPS.push_back( BC ); + m_mNIFMUTEX.unlock(); +#ifdef DEBUG + LOG("NIF defined"); +#endif + } +#ifdef DEBUG + else { + LOG("NO BC Address"); + } +#endif + ; + } else { + LOG_ERROR("Cannot Get Resource!"); + }; + }; + delete( rIDS ); + } else { + LOG("No Networks Detected!"); + m_bEnabled = false; + }; + } else { + LOG_ERROR("No HW Manager"); + }; +#ifdef DEBUG + LOG("Default Probe"); + LOG( HTTPMU_HOST_ADDRESS ); +#endif + CSTR tBC = (CSTR) malloc(16); + if ( tBC ) { + sprintf(tBC, HTTPMU_HOST_ADDRESS ); + m_mNIFMUTEX.lock(); + m_vNIFIPS.push_back( tBC ); + m_mNIFMUTEX.unlock(); + } else { + LOG_ERROR("Malloc Error!"); + }; + return true; +}; + +OBSERVER_RESULT *kernelModuleOnvifObserver::parseXML( CSTR data ){ + OBSERVER_RESULT *retVal = NULL; + if( data!=NULL ){ + XMLResults tParseResults; + XMLNode response = XMLNode::parseString( data, "root", &tParseResults ); + if( tParseResults.error ){ + char tBuffer[CTEXT]; + sprintf( tBuffer, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); + LOG_ERROR( tBuffer ); + } else { + if( response.isEmpty() ){ + LOG_ERROR("The device descripe XML file is not a valid XML file. Cann't find root element."); + } else { +#ifdef DEBUG + LOG("Probe XML parsed"); +#endif + XMLNode Body = response.getChildNode( "Body", 0 ); + if(!Body.isEmpty()){ + LOG("Have Body elm"); + XMLNode ProbeMatches = Body.getChildNode("ProbeMatches", 0);//EndpointReference + if(!ProbeMatches.isEmpty()) { + LOG("Have ProbeMathes elm"); + int matches = ProbeMatches.nChildNode(); + for(int index=0;indexsize(); j++) { + if( strlen(tArr->at(j)) > 10 ) { + sprintf(retVal->RefID,"%s",tArr->at(j)); + break; + }; + }; + tArr->clear(); + delete(tArr); + + }; + }; + } + { + XMLNode node = ProbeMatch.getChildNode("Types", 0); + if( !node.isEmpty() ){ + char tBuf[CLOG]; + sprintf(tBuf,"%s", node.getText(0)); + CArray *tArr; + tArr = explode(' ',tBuf); + sprintf(retVal->Type,"%s",tArr->at(0)); + tArr->clear(); + delete(tArr); + } + } + { + XMLNode node = ProbeMatch.getChildNode("Scopes", 0); + char tBuf[CLOG]; + sprintf( tBuf,"%s", node.getText(0) ); + CArray *tArr = explode(' ',tBuf); + if( tArr->size() > 0 ) { + for( int index = 0; index < tArr->size(); index++){ + char *tPtr; + if( tPtr = strstr( tArr->at(index), "mac/" ) ){ + sprintf(retVal->MAC,"%s",tPtr+4); + }; + if( tPtr = strstr( tArr->at(index), "hardware/" ) ){ + sprintf(retVal->Hardware,"%s",tPtr+9); + }; + if( tPtr = strstr( tArr->at(index), "name/" ) ){ + sprintf(retVal->Name,"%s",tPtr+5); + }; + if (tPtr = strstr(tArr->at(index), "MAC/")) { + sprintf(retVal->MAC, "%s", tPtr + 4); + }; + if (tPtr = strstr(tArr->at(index), "HARDWARE/")) { + sprintf(retVal->Hardware, "%s", tPtr + 9); + }; + if (tPtr = strstr(tArr->at(index), "NAME/")) { + sprintf(retVal->Name, "%s", tPtr + 5); + }; + }; + tArr->clear(); + }; + delete(tArr); + } + { + XMLNode node = ProbeMatch.getChildNode("XAddrs", 0); + char tBuf[CLOG]; + sprintf(tBuf,"%s", node.getText(0)); + CArray *tArr; + tArr = explode(' ',tBuf); + if( tArr->size() > 0 ) { + for(int index=0; index < tArr->size(); index++) { + if( strstr( tArr->at(index), "[" ) != NULL ){ + // IPv6 + } else{ + // IPv4 + sprintf(retVal->XAddrs,"%s",tArr->at(0)); + }; + }; + tArr->clear(); + }; + delete(tArr); + } + }; + }; + }; + }; + }; + }; + }; + }; + return retVal; +}; + + +bool kernelModuleOnvifObserver::validate(){ + m_mResultProtector.lock(); + if( m_vResultPool.size() ){ // Clear structures + for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){ +#ifdef DEBUG + char tBuffer[256]; + sprintf( tBuffer, "Found Camwera [%s] %s", (*index)->XAddrs, (*index)->RefID ); + LOG( tBuffer ); +#endif + uint32_t cid = m_pDBC->getCamId( (*index)->RefID ); //isCameraListed( DiscoverResults->at(index)->RefID ); + if( cid ) { +#ifdef DEBUG + sprintf( tBuffer, "Camera is Listed as %d", cid ); + LOG( tBuffer ); +#endif + m_pDBC->updateIPCam( cid, (*index)->XAddrs );// DiscoverResults->at(index)); + } else { + // Uncknown camera - no checking +#ifdef DEBUG + LOG("Camera is Not Listed"); +#endif + m_pDBC->addIPCam( (*index) ); + }; + free(*index); + } + m_vResultPool.clear(); +#ifdef DEBUG_EXTRA + LOG("Clear Structs Done!"); +#endif + } else { +#ifdef DEBUG_EXTRA + LOG("No Online IP Cameras in Network"); +#endif + }; + m_mResultProtector.unlock(); + return true; +}; + + + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/common/kernelModuleOnvifObserver.h b/lib/App/common/kernelModuleOnvifObserver.h new file mode 100644 index 00000000..13a3adfe --- /dev/null +++ b/lib/App/common/kernelModuleOnvifObserver.h @@ -0,0 +1,94 @@ +#ifndef __KERNEL_MODULE_ONVIF_OBSERVER_HEADER__ +#define __KERNEL_MODULE_ONVIF_OBSERVER_HEADER__ + +#include +#include +#include +#include +#include + +#include "kernelModule.h" +#include "../../data/protocol/xmlParser.h" +#include "../../components/base/basicThread.h" +#include "../../components/base/basicMutex.h" +#include "../../components/base/basicEventHeap.h" +#include "../../components/base/basicFunctionality.h" + +#pragma warning(disable: 4251) + +#define HTTPMU_HOST_ADDRESS "239.255.255.250" +#define HTTPMU_HOST_PORT 3702 + + +//#define DEBUG_ONVIF_PRINTOUT_MESSAGES + +#define DEFAULT_HTTP_PORT 80 + +typedef std::vector vectorOBSERVER_RESULT; + +class kernelModuleOnvifObserver; + +typedef struct S_PROBE_CTX{ + int AddressID; + char IpAddress[16]; + int Port; + int socketFD; + char buff[MAX_BUFF_SIZE + 1]; + CSTR send_buff; + CSTR recv_buff; + struct sockaddr_in r_address; + bool bOptVal; + int bOptLen; + int iOptLen; + int RetVal; + int index; + bool isFinished; + kernelModuleOnvifObserver * observer; +}PROBE_CTX; + +typedef struct S_OBSERVER_CTX{ + DWORD m_dwThreadID; +#ifdef __linux__ + pthread_t m_hThreadHandle; +#else + HANDLE m_hThreadHandle; +#endif + PROBE_CTX * context; +}OBSERVER_CTX; + +typedef std::vector vectorOBSERVER_CTX; + + +class kernelModuleOnvifObserver: public kernelModule, public basicThread { + private: + basicEventHeap * m_pEventHeap; + //enumeratorInfo m_vLocalDevices; + //localIpAddresses m_vIpAddresses; + + vectorOBSERVER_RESULT m_vResultPool; + basicMutex m_mResultProtector; + basicMutex m_mNIFMUTEX; + vectorCSTR m_vNIFIPS; + bool m_bProbeIsActive; + bool m_bWSAOK; + uint8_t m_bCurrentNIF; + + //PROBE_CTX * init_PROBE_CTX( CSTR ADR, int ID ); + //bool loadAssignedSources(void); + //bool startProbe( CSTR IP, int ID ); + //static void * probeThreadProc(void *); + OBSERVER_RESULT * parseXML( CSTR data ); + protected: + virtual void m_fThreadProc( void ); + + public: + explicit kernelModuleOnvifObserver( uint32_t moduleID ); + ~kernelModuleOnvifObserver(); + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); +}; + +#endif diff --git a/lib/App/common/kernelModuleSSDP.cpp b/lib/App/common/kernelModuleSSDP.cpp new file mode 100644 index 00000000..61ef1586 --- /dev/null +++ b/lib/App/common/kernelModuleSSDP.cpp @@ -0,0 +1,1041 @@ +#include "kernelModuleSSDP.h" + +#define LOG( X ) kernelModule::m_pLog->Log( "MOD_SSDP", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + kernelModule::m_pLog->Log( "MOD_SSDP", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) kernelModule::m_pLog->Log( "MOD_SSDP", this, _LOG_ERROR, X ); +#endif + +#define ENABLE_SOCKOPT(sd, level, opt) \ + do { \ + int val = 1; \ + if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \ + warn("Failed enabling %s for web service", #opt); \ + } while (0); +#define XML_TEMPLATE "\r\n" \ + "\r\n" \ + " \r\n" \ + " 1\r\n" \ + " 0\r\n" \ + " \r\n" \ + " \r\n" \ + " urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n" \ + " %s\r\n" \ + " %s\r\n" \ + " %s\r\n" \ + " uuid:%s\r\n" \ + " %s\r\n" \ + " \r\n" \ + "\r\n" \ + "\r\n" + +#define XML_TEMPLATE_HEAD "\r\n" \ + "\r\n" \ + " \r\n" \ + " 1\r\n" \ + " 0\r\n" \ + " \r\n" +#define XML_TEMPLATE_DEVICE_HEAD_WITH_BASE_URL "%s\r\n \r\n" +#define XML_TEMPLATE_DEVICE_HEAD_NO_BASE_URL " \r\n" +#define XML_TEMPLATE_TAIL " \r\n\r\n\r\n" + + +kernelModuleSSDPAnnouncer::kernelModuleSSDPAnnouncer( uint32_t ModuleID ) : kernelModule( ModuleID, KERNEL_MODULE_SSDP_ANONCE ){ + m_iSocketFID = -1; + m_nRefreshTime = REFRESH_INTERVAL; + m_nNotifyTime = NOTIFY_INTERVAL; + m_sTimeOut = CACHE_TIMEOUT; + m_lInterfaceLinks = LIST_HEAD_INITIALIZER(); + m_bUseWebService = true; + m_nWebPort = LOCATION_PORT; + memset( supported_types,0,SSDP_MAX_SUPPORTED_TYPES * sizeof(char *)); + supported_types[0] = SSDP_ST_ALL; + supported_types[1] = "upnp:rootdevice"; + supported_types[2] = (char *)malloc(64); + supported_types[3] = (char *)malloc(64); + supported_types[4] = "urn:schemas-upnp-org:service:DFSL:1"; + gethostname(m_sHostName, sizeof(m_sHostName)); + + m_sIcons.size = 0; + m_sIcons.array = NULL; + m_sServices.size = 0; + m_sServices.array = NULL; + /// + /// + /// + sprintf(supported_types[2],"urn:schemas-upnp-org:device:InternetGatewayDevice:1"); + uuidgen(); + sprintf( supported_types[3],"uuid:%s", m_sUUID ); + sprintf( m_pXMLTEMPLATE, XML_TEMPLATE ); +}; + +kernelModuleSSDPAnnouncer::~kernelModuleSSDPAnnouncer(){ + if( m_iSocketFID != -1 ) close_socket(); + if(supported_types[2]!= NULL) free(supported_types[2]); + if(supported_types[3]!= NULL) free(supported_types[3]); + if(m_sServices.size) free(m_sServices.array); + if(m_sIcons.size) free(m_sIcons.array); +}; + +void kernelModuleSSDPAnnouncer::dispatchEvent( EVENT_CONTAINER *Evt ){ + +}; + +bool kernelModuleSSDPAnnouncer::reloadSettings(){ + return false; +}; +bool kernelModuleSSDPAnnouncer::startService(){ + if( m_bUseWebService ) web_init( m_nWebPort ); + m_iSocketFID = multicast_init(); + if( m_iSocketFID < 0 ){ + LOG_ERROR("Failed creating multicast socket"); + return false; + }; + return init(); +}; +bool kernelModuleSSDPAnnouncer::stopService( bool force ){ + + return true; +}; +bool kernelModuleSSDPAnnouncer::validate(){ + return true; +}; + +void kernelModuleSSDPAnnouncer::compose_xml( CSTR peerIP ){ + char * cPtr; + char tBuf[1024]; + sprintf( m_pXMLTEMPLATE, XML_TEMPLATE_HEAD); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + if( strlen(m_sBaseURL)){ + sprintf(cPtr,XML_TEMPLATE_DEVICE_HEAD_WITH_BASE_URL,m_sBaseURL); + } else { + sprintf(cPtr,XML_TEMPLATE_DEVICE_HEAD_NO_BASE_URL); + }; + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(cPtr," %s\r\n", m_sDeviceType ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + if(strlen(m_sDeviceName)) { + sprintf(cPtr," %s\r\n",m_sDeviceName); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + if(strlen(m_sManufacturer)) { + sprintf(cPtr," %s\r\n",m_sManufacturer); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + if(strlen(m_sManufacturerURL)) { + sprintf(cPtr," %s\r\n",m_sManufacturerURL); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + if(strlen(m_sModelDescription)) { + sprintf(cPtr," %s\r\n",m_sModelDescription); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + if(strlen(m_sModelName)) { + sprintf(cPtr," %s\r\n",m_sModelName); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + if(strlen(m_sModelNumber)) { + sprintf(cPtr," %s\r\n",m_sModelNumber); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + if(strlen(m_sModelSite)) { + sprintf(cPtr," %s\r\n",m_sModelSite); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + if(strlen(m_sDeviceSerial)) { + sprintf(cPtr," %s\r\n",m_sDeviceSerial); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + sprintf(cPtr," uuid:%s\r\n",m_sUUID); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + if(strlen(m_sUniversalProductCode)) { + sprintf(cPtr," %s\r\n",m_sUniversalProductCode); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + sprintf(tBuf, m_sDevicePresentationURL, peerIP ); + sprintf(cPtr," %s\r\n",tBuf); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + if(m_sIcons.size) { + sprintf(cPtr," \r\n"); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + for(int index=0; index < m_sIcons.size; index++) { + sprintf(cPtr," \r\n"); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(cPtr," image/%s\r\n", m_sIcons.array[index].format ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(cPtr," %d\r\n", m_sIcons.array[index].width ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(cPtr," %d\r\n", m_sIcons.array[index].height ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(cPtr," %d\r\n", m_sIcons.array[index].depth ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(tBuf, m_sIcons.array[index].url, peerIP); + sprintf(cPtr," %s\r\n", tBuf ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(cPtr," \r\n"); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + sprintf(cPtr," \r\n"); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + if(m_sServices.size) { + sprintf(cPtr," \r\n"); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + for(int index=0; index < m_sServices.size; index++) { + sprintf(cPtr," \r\n"); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(cPtr," %s\r\n", m_sServices.array[index].type ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(cPtr," %s\r\n", m_sServices.array[index].id ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(tBuf, m_sServices.array[index].desc, peerIP); + sprintf(cPtr," %s\r\n", tBuf ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(tBuf, m_sServices.array[index].ctrl, peerIP); + sprintf(cPtr," %s\r\n", tBuf ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(tBuf, m_sServices.array[index].evt, peerIP); + sprintf(cPtr," %s\r\n", tBuf ); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + sprintf(cPtr," \r\n"); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + sprintf(cPtr," \r\n"); + cPtr = m_pXMLTEMPLATE+strlen(m_pXMLTEMPLATE); + }; + sprintf(cPtr,XML_TEMPLATE_TAIL); + + // FILE *fd; + // fd = fopen("test.xml","a+"); + // fprintf(fd, m_pXMLTEMPLATE ); + // fprintf(fd, "-----------------------\r\n"); + // fclose(fd); +}; + +/* Find interface in same subnet as sa */ +struct ifsock *kernelModuleSSDPAnnouncer::find_outbound(struct sockaddr *sa){ + in_addr_t cand; + struct ifsock * ifs; + struct sockaddr_in * addr = (struct sockaddr_in *)sa; + + cand = addr->sin_addr.s_addr; + LIST_FOREACH(ifs, &m_lInterfaceLinks, link) { + in_addr_t a, m; + a = ifs->addr.sin_addr.s_addr; + m = ifs->mask.sin_addr.s_addr; + if (a == htonl(INADDR_ANY) || m == htonl(INADDR_ANY)) continue; + if ((a & m) == (cand & m)) return ifs; + }; + return NULL; +}; +/* Exact match, must be same ifaddr as sa */ +struct ifsock *kernelModuleSSDPAnnouncer::find_iface(struct sockaddr *sa){ + struct ifsock * ifs; + struct sockaddr_in * addr = (struct sockaddr_in *)sa; + + if (!sa) return NULL; + LIST_FOREACH(ifs, &m_lInterfaceLinks, link) { + if (ifs->addr.sin_addr.s_addr == addr->sin_addr.s_addr) return ifs; + }; + return NULL; +}; + +int kernelModuleSSDPAnnouncer::open_socket(char *ifname, struct sockaddr *addr, int port){ + int sd, val, rc; + char loop; + char tBuf[CTEXT]; + struct ip_mreqn mreq; + struct sockaddr_in sin, *address = (struct sockaddr_in *)addr; + + sd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (sd < 0) return -1; + sin.sin_family = AF_INET; + sin.sin_port = htons(port); + sin.sin_addr = address->sin_addr; + if( bind(sd, (struct sockaddr *)&sin, sizeof(sin)) < 0 ){ + close(sd); + sprintf(tBuf,"Failed binding to %s:%d: %s", inet_ntoa(address->sin_addr), port, strerror(errno)); + LOG_ERROR(tBuf); + return -1; + }; +#if 0 + ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEADDR); +#ifdef SO_REUSEPORT + ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEPORT); +#endif +#endif + memset(&mreq, 0, sizeof(mreq)); + mreq.imr_address = address->sin_addr; + mreq.imr_multiaddr.s_addr = inet_addr(MC_SSDP_GROUP); + if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))) { + close(sd); + sprintf(tBuf,"Failed joining group %s: %s", MC_SSDP_GROUP, strerror(errno)); + LOG_ERROR(tBuf); + return -1; + }; + val = 2; /* Default 2, but should be configurable */ + rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL, &val, sizeof(val)); + if (rc < 0) { + close(sd); + sprintf(tBuf,"Failed setting multicast TTL: %s", strerror(errno)); + LOG_ERROR(tBuf); + return -1; + }; + + loop = 0; + rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); + if (rc < 0) { + close(sd); + sprintf(tBuf,"Failed disabing multicast loop: %s", strerror(errno)); + LOG_ERROR(tBuf); + return -1; + }; + + rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, &address->sin_addr, sizeof(address->sin_addr)); + if (rc < 0) { + close(sd); + sprintf(tBuf,"Failed setting multicast interface: %s", strerror(errno)); + LOG_ERROR(tBuf); + return -1; + }; +#ifdef DEBUG + sprintf(tBuf,"Adding new interface %s with address %s", ifname, inet_ntoa(address->sin_addr)); + LOG(tBuf); +#endif + return sd; +}; + +int kernelModuleSSDPAnnouncer::close_socket(void){ + int ret = 0; + struct ifsock * ifs, *tmp; + + LIST_FOREACH_SAFE(ifs, &m_lInterfaceLinks, link, tmp) { + LIST_REMOVE(ifs, link); + if (ifs->out != -1) + ret |= close(ifs->out); + else + ret |= close(ifs->in); + free(ifs); + }; + return ret; +}; + +int kernelModuleSSDPAnnouncer::filter_addr(struct sockaddr *sa){ + struct ifsock *ifs; + struct sockaddr_in *sin = (struct sockaddr_in *)sa; + + if (!sa) return 1; + if (sa->sa_family != AF_INET) return 1; + if (sin->sin_addr.s_addr == htonl(INADDR_ANY)) return 1; + if (sin->sin_addr.s_addr == htonl(INADDR_LOOPBACK)) return 1; + ifs = find_outbound(sa); + if (ifs) { + if (ifs->addr.sin_addr.s_addr != htonl(INADDR_ANY)) return 1; + }; + return 0; +}; + +int kernelModuleSSDPAnnouncer::filter_iface(char *ifname, char *iflist[], size_t num){ + size_t i; +#ifdef DEBUG + char tBuf[CTEXT]; +#endif + if (!num) { + LOG_ERROR("No interfaces to filter, using all with an IP address."); + return 0; + }; +#ifdef DEBUG + sprintf( tBuf, "Filter %s? Comparing %zd entries ...", ifname, num ); + LOG(tBuf); +#endif + for (i = 0; i < num; i++) { +#ifdef DEBUG + sprintf( tBuf, "Filter %s? Comparing with %s ...", ifname, iflist[i]); + LOG(tBuf); +#endif + if (!strcmp(ifname, iflist[i])) return 0; + }; + return 1; +}; + +void kernelModuleSSDPAnnouncer::compose_addr(struct sockaddr_in *sin, char *group, int port){ + memset(sin, 0, sizeof(*sin)); + sin->sin_family = AF_INET; + sin->sin_port = htons(port); + sin->sin_addr.s_addr = inet_addr(group); +} + +void kernelModuleSSDPAnnouncer::compose_response(char *type, char *host, char *buf, size_t len){ + char usn[256]; + char date[42]; + char uuid[64]; + time_t now; + + sprintf(uuid,"uuid:%s",m_sUUID); + /* RFC1123 date, as specified in RFC2616 */ + now = time(NULL); + strftime(date, sizeof(date), "%a, %d %b %Y %T %Z", gmtime(&now)); + + if (type) { + if (!strcmp(type, uuid)) + type = NULL; + else + snprintf(usn, sizeof(usn), "%s::%s", uuid, type); + } + + if( !type ) strncpy(usn, uuid, sizeof(usn)); + + snprintf(buf, len, "HTTP/1.1 200 OK\r\n" + "Server: %s\r\n" + "Date: %s\r\n" + "Location: http://%s:%d%s\r\n" + "ST: %s\r\n" + "EXT: \r\n" + "USN: %s\r\n" + "Cache-Control: max-age=%d\r\n" + "\r\n", + m_sServerName, + date, + host, LOCATION_PORT, LOCATION_DESC, + type, + usn, + CACHE_TIMEOUT); +} + +void kernelModuleSSDPAnnouncer::compose_search(char *type, char *buf, size_t len){ + snprintf(buf, len, "M-SEARCH * HTTP/1.1\r\n" + "Host: %s:%d\r\n" + "MAN: \"ssdp:discover\"\r\n" + "MX: 1\r\n" + "ST: %s\r\n" + "User-Agent: %s\r\n" + "\r\n", + MC_SSDP_GROUP, MC_SSDP_PORT, + type, + m_sServerName); +} + +void kernelModuleSSDPAnnouncer::compose_notify(char *type, char *host, char *buf, size_t len){ + char usn[CTEXT]; + + if( type ){ + if (!strcmp(type, SSDP_ST_ALL)){ + type = NULL; + } else{ + snprintf(usn, sizeof(usn), "uuid:%s::%s", m_sUUID, type); + }; + }; + + if( !type ){ + type = usn; + sprintf(usn,"uuid:%s",m_sUUID); + }; + + snprintf(buf, len, "NOTIFY * HTTP/1.1\r\n" + "Host: %s:%d\r\n" + "Server: %s\r\n" + "Location: http://%s:%d%s\r\n" + "NT: %s\r\n" + "NTS: ssdp:alive\r\n" + "USN: %s\r\n" + "Cache-Control: max-age=%d\r\n" + "\r\n", + MC_SSDP_GROUP, MC_SSDP_PORT, + m_sServerName, + host, LOCATION_PORT, LOCATION_DESC, + type, + usn, + CACHE_TIMEOUT); +}; + +size_t pktlen(unsigned char *buf) +{ + size_t hdr = sizeof(struct udphdr); + + return strlen((char *)buf + hdr) + hdr; +} + +void kernelModuleSSDPAnnouncer::send_search(struct ifsock *ifs, char *type){ + ssize_t num; + char buf[MAX_PKT_SIZE]; + struct sockaddr dest; + + memset(buf, 0, sizeof(buf)); + compose_search(type, buf, sizeof(buf)); + compose_addr((struct sockaddr_in *)&dest, MC_SSDP_GROUP, MC_SSDP_PORT); +#ifdef DEBUG + LOG("Sending M-SEARCH ..."); +#endif + num = sendto(ifs->out, buf, strlen(buf), 0, &dest, sizeof(struct sockaddr_in)); + if( num < 0 ) LOG_ERROR("Failed sending SSDP M-SEARCH"); +}; + +void kernelModuleSSDPAnnouncer::send_message(struct ifsock *ifs, char *type, struct sockaddr *sa ){ + int s; + size_t i, len, note = 0; + ssize_t num; + char host[NI_MAXHOST]; + char buf[MAX_PKT_SIZE]; + char tBuf[CTEXT]; + struct sockaddr dest; + struct sockaddr_in * sin = (struct sockaddr_in *)sa; + + gethostname(m_sHostName, sizeof(m_sHostName)); + s = getnameinfo((struct sockaddr *)&ifs->addr, sizeof(struct sockaddr_in), host, sizeof(host), NULL, 0, NI_NUMERICHOST); + if (s) { + sprintf( tBuf, "Failed getnameinfo(): %s", gai_strerror(s)); + LOG_ERROR(tBuf); + return; + }; + + if (ifs->addr.sin_addr.s_addr == htonl(INADDR_ANY)) return; + if (ifs->out == -1) return; + + if (!strcmp(type, SSDP_ST_ALL)) type = NULL; + + memset(buf, 0, sizeof(buf)); + if (sin){ + compose_response(type, host, buf, sizeof(buf)); + } else { + compose_notify(type, host, buf, sizeof(buf)); + }; + + if (!sin) { + note = 1; + compose_addr((struct sockaddr_in *)&dest, MC_SSDP_GROUP, MC_SSDP_PORT); + sin = (struct sockaddr_in *)&dest; + }; + +#ifdef DEBUG + sprintf( tBuf, "Sending %s from %s ...", !note ? "reply" : "notify", host); + LOG(tBuf); +#endif + + num = sendto(ifs->out, buf, strlen(buf), 0, (const sockaddr*)sin, sizeof(struct sockaddr_in)); + if (num < 0){ + sprintf(tBuf, "Failed sending SSDP %s, type: %s: %s", !note ? "reply" : "notify", type, strerror(errno)); + LOG_ERROR(tBuf); + }; +}; + +void kernelModuleSSDPAnnouncer::ssdp_recv(int sd){ + ssize_t len; + struct sockaddr sa; + socklen_t salen; + char buf[MAX_PKT_SIZE + 1]; + char tBuf[CTEXT]; + + memset(buf, 0, sizeof(buf)); + len = recvfrom(sd, buf, sizeof(buf) - 1, MSG_DONTWAIT, &sa, &salen); + if (len > 0) { + if (sa.sa_family != AF_INET) return; + if (strstr(buf, "M-SEARCH *")){ + char *ptr, *type; + struct ifsock *ifs; + struct sockaddr_in *sin = (struct sockaddr_in *)&sa; + + ifs = find_outbound(&sa); + if (!ifs) { + sprintf( tBuf, "No matching socket for client %s", inet_ntoa(sin->sin_addr)); + LOG_ERROR(tBuf); + return; + }; +#ifdef DEBUG + sprintf( tBuf, "Matching socket for client %s", inet_ntoa(sin->sin_addr)); + LOG(tBuf); +#endif + type = strcasestr(buf, "\r\nST:"); + if (!type) { +#ifdef DEBUG + sprintf( tBuf, "No Search Type (ST:) found in M-SEARCH *, assuming " SSDP_ST_ALL); + LOG(tBuf); +#endif + type = SSDP_ST_ALL; + send_message(ifs, type, &sa); + return; + } + + type = strchr(type, ':'); + if (!type) return; + type++; + while (isspace(*type)) type++; + + ptr = strstr(type, "\r\n"); + if (!ptr) return; + *ptr = 0; + int index = 0; + while(supported_types[index]){ + if (!strcmp(supported_types[index], type)) { +#ifdef DEBUG + sprintf( tBuf, "M-SEARCH * ST: %s from %s port %d", type, inet_ntoa(sin->sin_addr), ntohs(sin->sin_port)); + LOG(tBuf); +#endif + send_message(ifs, type, &sa); + return; + }; + index++; + }; +#ifdef DEBUG + sprintf( tBuf, "M-SEARCH * for unsupported ST: %s from %s", type, inet_ntoa(sin->sin_addr)); + LOG(tBuf); +#endif + }; + }; +}; + +void kernelModuleSSDPAnnouncer::web_recv(int sd){ + int client; + char ifname[CTEXT] = "UNKNOWN"; + char tBuf[CTEXT]; + client = accept(sd, NULL, NULL); + if (client < 0) { + sprintf(tBuf, "accept() error: %s", strerror(errno)); + LOG_ERROR(tBuf); + return; + }; + if (!stream_peek(client, tBuf, CTEXT)) { + sprintf(tBuf, "Failed resolving client interface: %s", strerror(errno)); + LOG_ERROR(tBuf); + return; + }; + respond(client, tBuf ); + shutdown(client, SHUT_RDWR); + close(client); +}; + +int kernelModuleSSDPAnnouncer::multicast_init(void){ + int sd; + struct sockaddr sa; + struct sockaddr_in * sin = (struct sockaddr_in *) &sa; + char tBuf[CTEXT]; + + sd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (sd < 0) { + sprintf(tBuf, "Failed opening multicast socket: %s", strerror(errno)); + LOG_ERROR( tBuf ); + return -1; + }; + memset( &sa, 0, sizeof(struct sockaddr) ); + sin->sin_family = AF_INET; + sin->sin_addr.s_addr = inet_addr(MC_SSDP_GROUP); + sin->sin_port = htons(MC_SSDP_PORT); + if (bind(sd, &sa, sizeof(*sin)) < 0) { + close(sd); + sprintf(tBuf, "Failed binding to %s:%d: %s", inet_ntoa(sin->sin_addr), MC_SSDP_PORT, strerror(errno)); + LOG_ERROR( tBuf ); + return -1; + } + register_socket( sd, -1, &sa, NULL, SOC_HANDLER_SSDP ); + return sd; +}; + +int kernelModuleSSDPAnnouncer::multicast_join( int sd, struct sockaddr *sa ){ + struct ip_mreqn mreq; + struct sockaddr_in * sin = (struct sockaddr_in *)sa; + char tBuf[CTEXT]; + + memset(&mreq, 0, sizeof(struct ip_mreqn)); + mreq.imr_address = sin->sin_addr; + mreq.imr_multiaddr.s_addr = inet_addr(MC_SSDP_GROUP); + if( setsockopt( sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(struct ip_mreqn))){ + if (EADDRINUSE == errno) return 0; + sprintf(tBuf, "Failed joining group %s: %s", MC_SSDP_GROUP, strerror(errno)); + LOG_ERROR( tBuf ); + return -1; + }; + return 0; +}; + +void kernelModuleSSDPAnnouncer::mark(void){ + struct ifsock * ifs; + LIST_FOREACH(ifs, &m_lInterfaceLinks, link) { + if (ifs->out != -1){ + ifs->stale = 1; + }else{ + ifs->stale = 0; + }; + }; +}; + +bool kernelModuleSSDPAnnouncer::sweep(void){ + bool modified = false; + struct ifsock * ifs, *tmp; +#ifdef DEBUG + char tBuf[CTEXT]; +#endif + + LIST_FOREACH_SAFE(ifs, &m_lInterfaceLinks, link, tmp) { + if (!ifs->stale) continue; + modified = true; +#ifdef DEBUG + sprintf( tBuf, "Removing stale ifs %s", inet_ntoa(ifs->addr.sin_addr)); + LOG( tBuf ); +#endif + LIST_REMOVE(ifs, link); + close(ifs->out); + free(ifs); + }; + return modified; +}; + +bool kernelModuleSSDPAnnouncer::ssdp_init( int inSo ){ + bool modified; + size_t i; + struct ifaddrs * ifaddrs, *ifa; + char tBuf[CTEXT]; +#ifdef DEBUG + LOG("Updating interfaces ..."); +#endif + if (getifaddrs(&ifaddrs) < 0) { + sprintf( tBuf, "Failed getifaddrs(): %s", strerror(errno)); + LOG_ERROR( tBuf ); + return false; + }; + /* Mark all outbound interfaces as stale */ + mark(); + /* First pass, clear stale marker from exact matches */ + for (ifa = ifaddrs; ifa; ifa = ifa->ifa_next) { + struct ifsock *ifs; + /* Do we already have it? */ + ifs = find_iface(ifa->ifa_addr); + if (ifs) { + ifs->stale = 0; + continue; + }; + }; + /* Clean out any stale interface addresses */ + modified = sweep(); + /* Second pass, add new ones */ + for (ifa = ifaddrs; ifa; ifa = ifa->ifa_next) { + int sd; + /* Interface filtering, optional command line argument */ + //if ( filter_iface(ifa->ifa_name, iflist, num) ) { +#ifdef DEBUG + // sprintf( tBuf, "Skipping %s, not in iflist.", ifa->ifa_name); + // LOG(tBuf); +#endif + // continue; + //}; + /* Do we have another in the same subnet? */ + if (filter_addr(ifa->ifa_addr)) continue; + sd = open_socket(ifa->ifa_name, ifa->ifa_addr, MC_SSDP_PORT); + if (sd < 0) continue; + multicast_join( inSo, ifa->ifa_addr ); + if ( !register_socket( inSo, sd, ifa->ifa_addr, ifa->ifa_netmask, SOC_HANDLER_SSDP )) { + close(sd); + break; + }; + modified = true; + }; + freeifaddrs(ifaddrs); + return modified; +}; + +void kernelModuleSSDPAnnouncer::handle_message(int sd){ + struct ifsock *ifs; + LIST_FOREACH(ifs, &m_lInterfaceLinks, link) { + if( ifs->in != sd ) continue; + switch(ifs->type){ + case SOC_HANDLER_SSDP: ssdp_recv(sd); break; + case SOC_HANDLER_WEB: web_recv(sd); break; + }; + }; +}; + +void kernelModuleSSDPAnnouncer::m_fThreadProc( void ){ + time_t tCurrentTime = 0; + time_t rtmo = 0; + time_t itmo = 0; + pid_t pid = gettid(); + char pidBuf[16]; + sprintf(pidBuf,"pid:%d", pid); + //LOG(pidBuf); + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { + tCurrentTime = time(NULL); + if( rtmo <= tCurrentTime ) { + if( ssdp_init( m_iSocketFID ) ) announce( 1 ); + rtmo = tCurrentTime + m_nRefreshTime; + }; + if( itmo <= tCurrentTime ) { + announce( 0 ); + itmo = tCurrentTime + m_nNotifyTime; + }; + time_t tmo = MIN( rtmo, itmo ); + int num = 1, timeout; + size_t ifnum = 0; + struct pollfd pfd[MAX_NUM_IFACES]; + struct ifsock *ifs; + + LIST_FOREACH(ifs, &m_lInterfaceLinks, link) { + if (ifs->out != -1) continue; + pfd[ifnum].fd = ifs->in; + pfd[ifnum].events = POLLIN | POLLHUP; + ifnum++; + }; + while( m_bThreadStatus < TH_ENDED ) { + size_t i; + timeout = tmo - time(NULL); + if ( timeout < 0 ) break; + num = poll(pfd, ifnum, timeout * 1000); + if( num < 0 ){ + if (EINTR == errno) break; + LOG_ERROR("Unrecoverable error"); + m_bThreadStatus = TH_ENDED; + }; + if( num == 0 ) break; + for( i = 0; num > 0 && i < ifnum; i++ ){ + if (pfd[i].revents & POLLIN) { + handle_message(pfd[i].fd); + num--; + }; + }; + }; + SLEEP(50); + }; +}; + +void kernelModuleSSDPAnnouncer::announce(int mod){ + struct ifsock *ifs; +#ifdef DEBUG + char tBuf[CTEXT]; + sprintf( tBuf, "Sending SSDP Announce:[%d] ...", mod); + LOG( tBuf ); +#endif + LIST_FOREACH(ifs, &m_lInterfaceLinks, link) { + if (mod && !ifs->mod) continue; + ifs->mod = 0; +// send_search(ifs, "upnp:rootdevice"); + int index = 0; + while( supported_types[index] ) { + /* UUID sent in SSDP_ST_ALL, first announce */ + if( index == 3 ){ // filter uuid announce + index++; + continue; + }; + send_message(ifs, supported_types[index], NULL); + index++; + }; + }; +}; + + +/* https://en.wikipedia.org/wiki/Universally_unique_identifier */ + +void kernelModuleSSDPAnnouncer::uuidgen(void){ + FILE * fp; + char buf[CTEXT]; +#ifdef DEBUG + char tBuf[CTEXT]; +#endif + const char * file = _PATH_VARDB PACKAGE_NAME ".cache"; + fp = fopen(file, "r"); + + if (!fp) { + fp = fopen(file, "w"); + if (!fp){ + sprintf( buf, "Cannot create UUID cache, %s: %s", file, strerror(errno)); + LOG_ERROR( buf ); + }; +generate: + srand(time(NULL)); + snprintf( buf, 42, "%8.8x-%4.4x-%4.4x-%4.4x-%6.6x%6.6x", + rand() & 0xFFFFFFFF, + rand() & 0xFFFF, + (rand() & 0x0FFF) | 0x4000, /* M 4 MSB version => version 4 */ + (rand() & 0x1FFF) | 0x8000, /* N: 3 MSB variant => variant 1 */ + rand() & 0xFFFFFF, rand() & 0xFFFFFF + ); + if (fp) { +#ifdef DEBUG + sprintf( tBuf, "Creating new UUID cache file, %s", file); + LOG( tBuf ); +#endif + fprintf(fp, "%s\n", buf); + fclose(fp); + }; + } else { +#ifdef DEBUG + sprintf( tBuf, "Cache file [%s] is Ok", file); + LOG( tBuf ); +#endif + if (!fgets(buf, sizeof(buf), fp)) { + fclose(fp); + goto generate; + } + buf[strlen(buf) - 1] = 0; + fclose(fp); + }; + strcpy( m_sUUID, buf ); +#ifdef DEBUG + sprintf( tBuf, "URN: %s", m_sUUID ); + LOG( tBuf ); +#endif +}; + +bool kernelModuleSSDPAnnouncer::web_init( int port ){ + int sd; + struct sockaddr sa; + struct sockaddr_in *sin; + + memset(&sa, 0, sizeof(struct sockaddr)); + sa.sa_family = AF_INET; + sin = (struct sockaddr_in *)&sa; + sin->sin_addr.s_addr = htonl(INADDR_ANY); + sin->sin_port = htons( port ); + + sd = socket(sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); + if( sd == -1 ){ + LOG_ERROR("Failed creating web socket"); + return false; + }; + ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEADDR); +#ifdef SO_REUSEPORT + ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEPORT); +#endif + if( bind(sd, &sa, sizeof(sa)) < 0 ){ + LOG_ERROR("Failed binding web socket"); + close(sd); + return false; + }; + if( listen(sd, 10) != 0 ){ + LOG_ERROR("Failed setting web listen backlog"); + close(sd); + return false; + }; + register_socket(sd, -1, &sa, NULL, SOC_HANDLER_WEB); + return true; +}; + +bool kernelModuleSSDPAnnouncer::register_socket(int in, int out, struct sockaddr *addr, struct sockaddr *mask, SOC_HANDLER_TYPE type ){ + struct ifsock * ifs; + struct sockaddr_in * address = (struct sockaddr_in *)addr; + struct sockaddr_in * netmask = (struct sockaddr_in *)mask; + char tBuf[CTEXT]; + + ifs = (struct ifsock *) malloc(sizeof(struct ifsock)); + if ( ifs==NULL ) { + char *host = inet_ntoa(address->sin_addr); + sprintf( tBuf, "Failed registering host %s socket: %s", host, strerror(errno)); + LOG_ERROR( tBuf ); + return false; + }; + memset( ifs, 0 , sizeof(struct ifsock)); + ifs->in = in; + ifs->out = out; + ifs->mod = 1; + ifs->addr = *address; + ifs->type = type; + if( mask != NULL ) ifs->mask = *netmask; + + LIST_INSERT_HEAD(&m_lInterfaceLinks, ifs, link); + return true; +}; + +/* Peek into SOCK_STREAM on accepted client socket to figure out inbound interface */ +bool kernelModuleSSDPAnnouncer::stream_peek(int sd, char *ifname, int size ){ + struct ifaddrs * ifaddr, *ifa; + struct sockaddr_in sin; + + socklen_t len = sizeof(struct sockaddr_in); + + if (-1 == getsockname(sd, (struct sockaddr *)&sin, &len)) return false; + + if (-1 == getifaddrs(&ifaddr)) return false; + + for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { + size_t len = sizeof(struct in_addr); + struct sockaddr_in * iin; + if (!ifa->ifa_addr) continue; + if (ifa->ifa_addr->sa_family != AF_INET) continue; + iin = (struct sockaddr_in *)ifa->ifa_addr; + if (!memcmp(&sin.sin_addr, &iin->sin_addr, len)) { + //strncpy(ifname, ifa->ifa_addr->sa_data, size ); + unsigned char A,B,C,D; + D = ( iin->sin_addr.s_addr >> 24) & 0xFF; + C = ( iin->sin_addr.s_addr >> 16) & 0xFF; + B = ( iin->sin_addr.s_addr >> 8) & 0xFF; + A = ( iin->sin_addr.s_addr >> 0) & 0xFF; + sprintf( ifname, "%d.%d.%d.%d", A, B, C, D ); + break; + }; + }; + freeifaddrs(ifaddr); + return true; +}; + +void kernelModuleSSDPAnnouncer::respond(int sd, char *ifname){ + struct pollfd pfd = { + .fd = sd, + .events = POLLIN, + }; + char *head = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/xml\r\n" + "Connection: close\r\n" + "\r\n"; + char hostname[64], url[128] = "http://191.168.0.111/"; + char mesg[1024], *reqline[3]; + int rc, rcvd, fd, bytes_read; + + /* Check for early disconnect or client timeout */ + rc = poll(&pfd, 1, 1000); + if (rc <= 0) goto error; + memset(mesg, 0, sizeof(mesg)); + rcvd = recv(sd, mesg, sizeof(mesg), 0); + if (rcvd <= 0) { + sprintf( mesg, "web recv() error: %s", strerror(errno)); + LOG_ERROR(mesg); + goto error; + }; +#ifdef DEBUG + LOG("HTTP request handler!"); +#endif + reqline[0] = strtok(mesg, " \t\n"); + if (strncmp(reqline[0], "GET", 4) == 0) { + reqline[1] = strtok(NULL, " \t"); + reqline[2] = strtok(NULL, " \t\n"); + if (strncmp(reqline[2], "HTTP/1.0", 8) != 0 && strncmp(reqline[2], "HTTP/1.1", 8) != 0) { + if (write(sd, "HTTP/1.1 400 Bad Request\r\n", 26) < 0){ + sprintf( mesg, "Failed returning status 400 to client: %s", strerror(errno)); + LOG_ERROR(mesg); + }; + goto error; + }; + + /* XXX: Add support for icon as well */ + if (!strstr(reqline[1], LOCATION_DESC)) { + if (write(sd, "HTTP/1.1 404 Not Found\r\n", 24) < 0){ + sprintf( mesg, "Failed returning status 404 to client: %s", strerror(errno)); + LOG_ERROR(mesg); + }; + goto error; + }; + + gethostname(hostname, sizeof(hostname)); +#ifdef DEBUG + LOG("Sending XML reply ..."); +#endif + if( ifname!= NULL && strlen( ifname ) > 0 ) { + compose_xml( ifname ); + send(sd, head, strlen(head), 0); + snprintf(mesg, sizeof(mesg), m_pXMLTEMPLATE ); + if (send(sd, mesg, strlen(mesg), 0) < 0){ + sprintf( mesg, "Failed sending file to client: %s", strerror(errno)); + LOG_ERROR(mesg); + }; + } + }; +error: + shutdown(sd, SHUT_RDWR); + close(sd); +}; + + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/common/kernelModuleSSDP.h b/lib/App/common/kernelModuleSSDP.h new file mode 100644 index 00000000..ee9d6f32 --- /dev/null +++ b/lib/App/common/kernelModuleSSDP.h @@ -0,0 +1,211 @@ +#ifndef __KERNEL_MODULE_SSDP_ANNOUNCER_HEADER__ +#define __KERNEL_MODULE_SSDP_ANNOUNCER_HEADER__ +#include "kernelModule.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* MIN() */ +#include +#include +#include +#include +#include +#define gettid() syscall(SYS_gettid) + +#define SSDP_TAG_DEVICE_SERVER_STRING "SERVER_STRING" +#define SSDP_TAG_DEVICE_FRIENDLY_NAME "DEVICE_FRIENDLY_NAME" +#define SSDP_TAG_DEVICE_TYPE "DEVICE_TYPE" +#define SSDP_TAG_DEVICE_BASE_URL "BASE_URL" +#define SSDP_TAG_AUX_WEB_SERVICE "AUX_WEB_SERVICE" +#define SSDP_TAG_DEVICE_MANUFACTURER "MANUFACTURER" +#define SSDP_TAG_DEVICE_MANUFACTURER_URL "MANUFACTURER_URL" +#define SSDP_TAG_DEVICE_MODEL_NAME "MODEL_NAME" +#define SSDP_TAG_DEVICE_MODEL_NUMBER "MODEL_NUMBER" +#define SSDP_TAG_DEVICE_MODEL_DESCRIPTION "MODEL_DESCRIPTION" +#define SSDP_TAG_DEVICE_MODEL_URL "MODEL_URL" +#define SSDP_TAG_DEVICE_SERIAL "DEVICE_SERIAL_NUMBER" +#define SSDP_TAG_DEVICE_UUID "DEVICE_UUID" +#define SSDP_TAG_DEVICE_UPC "DEVICE_UPC" +#define SSDP_TAG_DEVICE_ICONS "ICONS" +#define SSDP_TAG_DEVICE_ICON_IMAGE_FORMAT "FORMAT" +#define SSDP_TAG_DEVICE_ICON_WIDTH "WIDTH" +#define SSDP_TAG_DEVICE_ICON_HEIGHT "HEIGHT" +#define SSDP_TAG_DEVICE_ICON_DEPTH "DEPTH" +#define SSDP_TAG_DEVICE_ICON_URL "URL" +#define SSDP_TAG_DEVICE_SERVICES "SERVICES" +#define SSDP_TAG_DEVICE_SERVICE_TYPE "TYPE" +#define SSDP_TAG_DEVICE_SERVICE_ID "ID" +#define SSDP_TAG_DEVICE_SERVICE_DESC_URL "DESCRIPTION_URL" +#define SSDP_TAG_DEVICE_SERVICE_CTRL_URL "CONTROL_URL" +#define SSDP_TAG_DEVICE_SERVICE_EVTS_URL "EVENTS_URL" +#define SSDP_TAG_DEVICE_PRESENTATION_URL "PRESENTATION_URL" + + +typedef struct S_SSDP_ICON_DATA{ + char format[6]; + int width; + int height; + int depth; + char url[128]; +}SSDP_ICON_DATA; + +typedef struct S_SSDP_SERVICE_DATA{ + char type[128]; + char id[64]; + char desc[128]; + char ctrl[128]; + char evt[128]; +}SSDP_SERVICE_DATA; + +typedef struct S_SSDP_ICON_STORAGE{ + SSDP_ICON_DATA * array; + int size; +}SSDP_ICON_STORAGE; + +typedef struct S_SSDP_SERVICE_STORAGE{ + SSDP_SERVICE_DATA * array; + int size; +}SSDP_SERVICE_STORAGE; + +/* Notify should be less than half the cache timeout */ +#define NOTIFY_INTERVAL 300 +#define REFRESH_INTERVAL 600 +#define CACHE_TIMEOUT 1800 +#define MAX_NUM_IFACES 100 +#define MAX_PKT_SIZE 2000 +#define SSDP_MAX_SUPPORTED_TYPES 10 +#define MC_SSDP_GROUP "239.255.255.250" +#define MC_SSDP_PORT 1900 +#define LOCATION_PORT (MC_SSDP_PORT + 1) +#define LOCATION_DESC "/description.xml" +#define PACKAGE_NAME "Argus" +#define PACKAGE_VERSION "1.0.5" +#define MODEL "Server" +#define MANUFACTURER "Toogler(ltd)" + +#define SSDP_ST_ALL "ssdp:all" + +#define SERVER_STRING "POSIX UPnP/1.0 " PACKAGE_NAME "/" PACKAGE_VERSION + +typedef enum E_SOC_HANDLER_TYPE{ + SOC_HANDLER_SSDP = 0, + SOC_HANDLER_WEB = 1 +}SOC_HANDLER_TYPE; + +struct ifsock { + LIST_ENTRY(ifsock) link; + int stale; + int mod; + /* + * Sockets for inbound and outbound + * + * - The inbound is the multicast socket, shared between all ifaces + * - The outbound is bound to the iface address and a random port + */ + int in, out; + /* Interface address and netmask */ + struct sockaddr_in addr; + struct sockaddr_in mask; + SOC_HANDLER_TYPE type; +}; + +class kernelModuleSSDPAnnouncer: public kernelModule, public basicThread { + private: + int m_iSocketFID; + LIST_HEAD(, ifsock) m_lInterfaceLinks; + struct sockaddr_in * address; + struct sockaddr_in * netmask; + + SSDP_ICON_STORAGE m_sIcons; + SSDP_SERVICE_STORAGE m_sServices; + + /***/ + char m_sDeviceType[64]; + char m_sServerName[128]; + char m_sDeviceName[64]; + char m_sDeviceSerial[64]; + char m_sDevicePresentationURL[128]; + char m_sUniversalProductCode[42]; + char m_sUUID[42]; + char m_sHostName[64]; + char m_sManufacturer[64]; + char m_sBaseURL[128]; + char m_sManufacturerURL[128]; + char m_sModelName[64]; + char m_sModelNumber[64]; + char m_sModelSite[128]; + char m_sModelDescription[128]; + + + bool m_bUseWebService; + uint16_t m_nWebPort; + time_t m_sTimeOut; + time_t m_nRefreshTime; + time_t m_nNotifyTime; + char * supported_types[SSDP_MAX_SUPPORTED_TYPES]; + char m_pXMLTEMPLATE[4096]; + struct ifsock * find_outbound( struct sockaddr *sa ); + struct ifsock * find_iface( struct sockaddr *sa ); + + int multicast_init(void); + int multicast_join( int sd, struct sockaddr *sa ); + + //int register_socket(int in, int out, struct sockaddr *addr, struct sockaddr *mask, void (*cb)(int sd) ); + bool register_socket(int in, int out, struct sockaddr *addr, struct sockaddr *mask, SOC_HANDLER_TYPE type ); + void announce( int mod ); + + int open_socket(char *ifname, struct sockaddr *addr, int port); + int close_socket(void); + + int filter_addr(struct sockaddr *sa); + int filter_iface(char *ifname, char *iflist[], size_t num); + + void compose_addr(struct sockaddr_in *sin, char *group, int port); + void compose_response(char *type, char *host, char *buf, size_t len); + void compose_search(char *type, char *buf, size_t len); + void compose_notify(char *type, char *host, char *buf, size_t len); + void compose_xml( CSTR peerIP ); + + void uuidgen(void); + bool web_init( int PortID ); + bool ssdp_init(int inSo ); + + void send_search( struct ifsock *ifs, char *type ); + void send_message( struct ifsock *ifs, char *type, struct sockaddr *sa ); + void ssdp_recv(int sd); + void web_recv(int sd); + bool stream_peek(int sd, char *ifname, int size ); + void respond(int sd, char *ifname); + void handle_message(int sd); + void mark(void); + bool sweep(void); + protected: + virtual void m_fThreadProc( void ); + public: + explicit kernelModuleSSDPAnnouncer( uint32_t moduleID ); + ~kernelModuleSSDPAnnouncer(); + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); +}; +#endif diff --git a/lib/App/common/kernelModuleUSBRelay.cpp b/lib/App/common/kernelModuleUSBRelay.cpp new file mode 100644 index 00000000..c084a7b0 --- /dev/null +++ b/lib/App/common/kernelModuleUSBRelay.cpp @@ -0,0 +1,317 @@ +#include +#include +#include +#include +#include +#include +#include +#include "kernelModuleUSBRelay.h" + +#define LOG( X ) kernelModule::m_pLog->Log( "MOD_USBDC", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + kernelModule::m_pLog->Log( "MOD_USBDC", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) kernelModule::m_pLog->Log( "MOD_USBDC", this, _LOG_ERROR, X ); +#endif + + +//Global variables +unsigned short vendor_id = 0x16c0; +unsigned short product_id = 0x05df; +relay_board *relay_boards = 0; +int relay_board_count = 0; +int i, k; + +//Private function prototypes +static int get_board_features(relay_board *board, hid_device *handle); + +/** + * Enumerate all possible relay devices in the system + */ +int enumerate_relay_boards(const char *product, int verbose, int debug){ + char *vendor; + int result = 0; + struct hid_device_info *devs, *cur_dev; + + //If we were given a product code, use it + if (product != NULL) + { + vendor = strsep((char **)&product, ":"); + if (vendor && *vendor) + { + vendor_id = strtol(vendor, NULL, 16); + } + if (product && *product) + { + product_id = strtol(product, NULL, 16); + } + } + + //Enumerate USB devices with the given IDs + devs = hid_enumerate(vendor_id, product_id); + + //Count the number of returned devices + cur_dev = devs; + + for (relay_board_count = 0; cur_dev != NULL; relay_board_count++) + { + cur_dev = cur_dev->next; + } + + //Allocate a buffer for the relays + if (relay_board_count > 0) + { + relay_boards = (relay_board *) malloc((relay_board_count) * sizeof(relay_board)); + + //Fill the relay structs + cur_dev = devs; + for (i = 0; i < relay_board_count; i++) + { + //Save the path to this device + relay_boards[i].path = (char *) malloc(strlen(cur_dev->path)+1); + memcpy(relay_boards[i].path, cur_dev->path, strlen(cur_dev->path) + 1); + + // The product string is USBRelayx where x is number of relays read to the \0 in case there are more than 9 + relay_boards[i].relay_count = atoi((const char *)&cur_dev->product_string[8]); + + //Open it to get more details + hid_device *handle; + handle = hid_open_path(cur_dev->path); + if (handle) + { + result = get_board_features(&relay_boards[i], handle); + hid_close(handle); + } + else + { + perror("unable to open device\n"); + result = -1; + } + + //Output the device enumeration details if verbose is on + if (verbose) + { + fprintf(stderr, "Device Found\n type: %04hx %04hx\n path: %s\n serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number); + fprintf(stderr, "\n"); + fprintf(stderr, " Manufacturer: %ls\n", cur_dev->manufacturer_string); + fprintf(stderr, " Product: %ls\n", cur_dev->product_string); + fprintf(stderr, " Release: %hx\n", cur_dev->release_number); + fprintf(stderr, " Interface: %d\n", cur_dev->interface_number); + + fprintf(stderr, " Number of Relays = %d\n", relay_boards[i].relay_count); + + //If verbose and debug are on, output individual relay details + if (debug) + { + for (k = 0; k < relay_boards[i].relay_count; k++) + { + if (relay_boards[i].state & 1 << k) + { + printf("%s_%d=1\n", relay_boards[i].serial, k + 1); + } + else + { + printf("%s_%d=0\n", relay_boards[i].serial, k + 1); + } + } + } + } + cur_dev = cur_dev->next; + } + } + hid_free_enumeration(devs); + return result; +} + +/** + * Command a relay at a particular /dev path to switch to a given state + */ +int operate_relay(const char *serial, unsigned char relay, unsigned char target_state) +{ + unsigned char buf[9]; // 1 extra byte for the report ID + int res = -1; + hid_device *handle; + + relay_board *board = find_board(serial); + if (board != NULL && relay >0 && relay <= board->relay_count) + { + handle = hid_open_path(board->path); + + if (handle) + { + buf[0] = 0x0; //report number + buf[1] = target_state; + buf[2] = relay; + buf[3] = 0x00; + buf[4] = 0x00; + buf[5] = 0x00; + buf[6] = 0x00; + buf[7] = 0x00; + buf[8] = 0x00; + res = hid_write(handle, buf, sizeof(buf)); + } + else + { + res = -1; + } + + if (res > 0) + { + //Update our relay status + res = get_board_features(board, handle); + } + else + { + fprintf(stderr, "Unable to write()\n"); + fprintf(stderr, "Error: %ls\n", hid_error(handle)); + } + + hid_close(handle); + } + + return (res); +} + +int set_serial(const char *serial, char *newserial) +{ + unsigned char buf[9]; // 1 extra byte for the report ID + int res = -1; + hid_device *handle; + + relay_board *board = find_board(serial); + if (board != NULL) + { + handle = hid_open_path(board->path); + + if (handle) + { + buf[0] = 0x0; //report number + buf[1] = CMD_SET_SERIAL; + buf[2] = newserial[0]; + buf[3] = newserial[1]; + buf[4] = newserial[2]; + buf[5] = newserial[3]; + buf[6] = newserial[4]; + buf[7] = 0x00; + buf[8] = 0x00; + res = hid_write(handle, buf, sizeof(buf)); + } + else + { + res = -1; + } + + if (res > 0) + { + //Update our copy of the serial number + res = get_board_features(board, handle); + } + else + { + fprintf(stderr, "Unable to write()\n"); + fprintf(stderr, "Error: %ls\n", hid_error(handle)); + } + hid_close(handle); + } + + return (res); +} + +/** + * Find a board path given a relay board serial + */ +relay_board *find_board(const char *serial) +{ + for (i = 0; i < relay_board_count; i++) + { + if (strcmp(relay_boards[i].serial, serial) == 0) + { + return &relay_boards[i]; + } + } + return NULL; +} + +/** + * Return the count of relay boards + */ +int get_relay_board_count() +{ + return relay_board_count; +} + +/** + * Return the actual relay_board structs + */ +relay_board *get_relay_boards() +{ + return relay_boards; +} + +/** + * Return all allocated resources and perform any other cleanup + */ +void shutdown() +{ + + /* Free static HIDAPI objects. */ + hid_exit(); + + for (i = 0; i < relay_board_count; i++) + { + free(relay_boards[i].path); + } + if (relay_board_count > 0) + { + free(relay_boards); + } +} + +//Private functions + +/** + * Load the board serial and relay status + * This intentionally reuses a handle as it's meant to be called by the + * other functions while they have one already open + */ +static int get_board_features(relay_board *board, hid_device *handle) +{ + unsigned char buf[9]; + //Get the features of the device + buf[0] = 0x01; + int ret = hid_get_feature_report(handle, buf, sizeof(buf)); + if (ret == -1) + { + perror("hid_get_feature_report\n"); + } + + //Set the serial number (0x0 for termination) + memset(board->serial, 0x0, sizeof(board->serial)); + memcpy(board->serial, buf, Serial_Length); + + //Byte 7 in the response contains the target_state of the relays + board->state = buf[7]; + + return ret; +} + + +kernelModuleUSBRelay::kernelModuleUSBRelay( uint32_t ModuleID ) : kernelModule( ModuleID, KERNEL_MODULE_DCBUSB ){ + +}; + +kernelModuleUSBRelay::~kernelModuleUSBRelay(){ +}; + +void kernelModuleUSBRelay::dispatchEvent( EVENT_CONTAINER *Evt ){ + +}; + + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/common/kernelModuleUSBRelay.h b/lib/App/common/kernelModuleUSBRelay.h new file mode 100644 index 00000000..725e618a --- /dev/null +++ b/lib/App/common/kernelModuleUSBRelay.h @@ -0,0 +1,40 @@ +#ifndef __KERNEL_USB_RELAY_MODULE_HEADER__ +#define __KERNEL_USB_RELAY_MODULE_HEADER__ + +#include "kernelModule.h" + +//Configuration +#define CMD_ON 0xff +#define CMD_OFF 0xfd +#define CMD_SET_SERIAL 0xfa + +#define Serial_Length 6 // 5+1 for the \0 string terminator + +//Struct for relay boards +typedef struct S_relay_board { + char serial[Serial_Length]; + unsigned char relay_count; + unsigned char state; + char *path; +} relay_board; + +int enumerate_relay_boards( const char *product, int verbose, int debug); +int operate_relay( const char *path,unsigned char relay, unsigned char state); +int set_serial( const char *path,char *newserial); +relay_board *find_board( const char *serial); +int get_relay_board_count( void); +relay_board* get_relay_boards(void); +void shutdown(void); + +class kernelModuleUSBRelay: public kernelModule { + private: + relay_board m_sBoardDef; + uint32_t m_nNO_CONFIG; + uint32_t m_nCURRENT_STATE; + uint32_t m_aCHANNEL_CONFIGS[32]; + public: + explicit kernelModuleUSBRelay( uint32_t ModuleID ); + virtual ~kernelModuleUSBRelay(); + virtual void dispatchEvent( EVENT_CONTAINER *Evt ); +}; +#endif \ No newline at end of file diff --git a/lib/App/common/kernelPrototype.cpp b/lib/App/common/kernelPrototype.cpp new file mode 100644 index 00000000..d83ae7e0 --- /dev/null +++ b/lib/App/common/kernelPrototype.cpp @@ -0,0 +1,96 @@ +#include "kernelPrototype.h" + +#ifdef USE_MYSQL + #include "MySQL_dataBinder.h" +#else + #include "SQLite_dataBinder.h" +#endif + +#define LOG( X ) kernelPrototype::m_pLog->Log( "KRNL", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG234[256];\ + sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + kernelPrototype::m_pLog->Log( "KRNL", this, _LOG_ERROR, _tBfrErrMSG234 );\ + } +#else + #define LOG_ERROR( X ) kernelPrototype::m_pLog->Log( "KRNL", this, _LOG_ERROR, X ); +#endif + +kernelPrototype *kernelPrototype::_instance = NULL; +kernelPrototype *kernelPrototype::getInstance(){ + return _instance; +}; + +kernelPrototype::kernelPrototype( config_setting_t *ptr ): m_mWMProtector(){ + m_pLog = basicLogCollection::getInstance(); + m_pEventHeap = basicEventHeap::getInstance(); + m_pSettings = basicSettingsProvider::getInstance()->getSubNode( ptr, "KERNEL" ); +#ifdef USE_MYSQL + m_pDBC = mysqlDBC::getInstance(); +#else + m_pDBC = sqliteDBC::getInstance(); +#endif + m_pHardwareManager = NULL; + m_pModuleFactory = NULL; + m_pNodeFactory = NULL; + m_bExitCause = EXIT_CODE_KERNEL_CLEAR; + m_bWM = WM_KERNEL_PROTOTYPE_INIT; + kernelPrototype::_instance = this; +}; + +kernelPrototype::~kernelPrototype(){ +}; + +void kernelPrototype::setWM( uint8_t mode ){ + m_mWMProtector.lock(); + m_bWM = mode; + m_mWMProtector.unlock(); +}; + +void kernelPrototype::setExitCause( uint8_t code ){ + m_mWMProtector.lock(); + m_bExitCause = code; + m_mWMProtector.unlock(); +}; + +uint8_t kernelPrototype::getWM( void ){ + m_mWMProtector.lock(); + uint8_t rV = m_bWM; + m_mWMProtector.unlock(); + return rV; +}; + +uint8_t kernelPrototype::getExitCause(){ + return m_bExitCause; +}; + +void kernelPrototype::WaitFinish( bool Force ){ + if( Force ){ +#ifdef DEBUG + LOG( "Forced Exit" ); +#endif + } else { +#ifdef DEBUG + LOG( "Start Waiting for Thread to End (usually at MAIN)." ); +#endif + }; + waitThreadEnd( Force ); +}; + +kernelEventFilter *kernelPrototype::getFilter( uint32_t id ){ + kernelEventFilter *RetVal = NULL; + if( m_vTargetFilters.size() > 0 ) { + for( vectorKernelEventFilters::iterator idx = m_vTargetFilters.begin(); idx < m_vTargetFilters.end(); idx++ ){ + if( (*idx)->getID() == id ) { + RetVal = (*idx); + break; + }; + }; + }; + return RetVal; +}; + + +#undef LOG +#undef LOG_ERROR \ No newline at end of file diff --git a/lib/App/common/kernelPrototype.h b/lib/App/common/kernelPrototype.h new file mode 100644 index 00000000..d2d6190b --- /dev/null +++ b/lib/App/common/kernelPrototype.h @@ -0,0 +1,63 @@ +#ifndef __DFSL_KERNEL_PROTOTYPE_HEADER__ +#define __DFSL_KERNEL_PROTOTYPE_HEADER__ + +#include "../../components/base/basicThread.h" +#include "../../components/base/basicMutex.h" +#include "../../components/base/basicMutex.h" +#include "../../components/base/basicEventHeap.h" +#include "../../components/base/basicLogCollection.h" +#include "../../components/base/basicSettingsProvider.h" +#include "hardwareManager.h" +#include "kernelModuleFactory.h" +#include "deviceNodeFactory.h" +#include "kernelEventFilter.h" + + +#define WM_KERNEL_PROTOTYPE_INIT 0 + + +#define EXIT_CODE_KERNEL_CLEAR 0 +#define EXIT_CODE_RELOAD_SERVICES 1 +#define EXIT_CODE_RESTART_OS 2 +#define EXIT_CODE_FACTORY_RESET 3 +#define EXIT_CODE_DETECT_HARDWARE 4 + + +class kernelPrototype: public basicThread { + private: + /* Internal */ + basicMutex m_mWMProtector; + uint8_t m_bExitCause; + uint8_t m_bWM; + static kernelPrototype * _instance; + protected: + /* basic */ + basicLogCollection * m_pLog; + basicEventHeap * m_pEventHeap; + config_setting_t * m_pSettings; + /* Special */ + dataBinder * m_pDBC; + hardwareManager * m_pHardwareManager; + kernelModuleFactory * m_pModuleFactory; + deviceNodeFactory * m_pNodeFactory; + vectorKernelEventFilters m_vTargetFilters; + /* func */ + virtual void m_fThreadProc( void ){}; + //hiden constructor -> the object cannot be used directly! + explicit kernelPrototype( config_setting_t *ptr ); + void setWM( uint8_t mode ); + void setExitCause( uint8_t mode ); + public: + virtual ~kernelPrototype(); + virtual bool create(){ return false; }; + uint8_t getExitCause(); + static kernelPrototype * getInstance(); + uint8_t getWM( void ); + //uint32_t getInstanceID(); + //hardwareManager * getHardwareManager(){ return m_pHardwareManager; }; + //kernelModuleFactory * getModuleFactory(); + kernelEventFilter * getFilter( uint32_t id ); + void WaitFinish( bool Force = false ); +}; + +#endif \ No newline at end of file diff --git a/lib/App/mojo/mojoBackend.cpp b/lib/App/mojo/mojoBackend.cpp new file mode 100644 index 00000000..a0b88fc4 --- /dev/null +++ b/lib/App/mojo/mojoBackend.cpp @@ -0,0 +1,476 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2022. All Rights Reserved. +// Version 2.0 11/18/2022 +// Last modification: 11/18/2022 +// PROJECT: +// SUBSYSTEM: +// FILE: LRF_Server.cpp +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// Header file of mojoBackend.cpp +//---------------------------------------------------------------------------- +// + +#include "mojoBackend.h" + +#ifdef USE_MYSQL + #include "../common/MySQL_dataBinder.h" +#else + #include "../common/SQLite_dataBinder.h" +#endif + +typedef enum { + ST_NONE = -1, + ST_SN = 0, + ST_BIND_ADDRESS, + ST_BIND_PORT, + ST_PID_FILE, + ST_LOG_FILE, + ST_LOG_ENABLE, + ST_INTERACTIVE, + ST_SMS_ENABLE, + ST_EMAIL_ENABLE, + ST_SMS_PROVIDER, + ST_DATABASE_SERVER, + ST_DATABASE_USER, + ST_DATABASE_PASSWORD, + ST_DATABASE_NAME, + ST_SOCKET_NAME +} SETTING_TYPE; + +CSTR m_pSetting[] = { + (CSTR)"SN", + (CSTR)"BIND_ADDRESS", + (CSTR)"BIND_PORT", + (CSTR)"PID_FILE", + (CSTR)"LOG_FILE" , + (CSTR)"LOG_ENABLED", + (CSTR)"INTERACTIVE", + (CSTR)"SMS_ENABLE", + (CSTR)"EMAIL_ENABLE", + (CSTR)"SMS_PROVIDER", + (CSTR)"DATABASE_SERVER", + (CSTR)"DATABASE_USER", + (CSTR)"DATABASE_PASSWORD", + (CSTR)"DATABASE_NAME", + (CSTR)"SOCKET_NAME" +}; + +// Global Variables + +CSTR gsCFG_ADDRESS; +uint16_t guCFG_PORT = DEFAULT_SERVER_PORT; +CSTR gsCFG_LICENSE; +CSTR gsCFG_DB_SERVER; +CSTR gsCFG_DB_NAME; +CSTR gsCFG_DB_USER; +CSTR gsCFG_DB_PASSWORD; +CSTR gsCFG_PID_FILE = (CSTR) DEFAULT_SERVER_PID_FILE; +SOFTWARE_INFO gsSOFT_INFO; +bool gbCFG_MASTER_ROLE = true; + +bool gModule_GeoFence_Enabled = true; +bool gModule_SMS_Enabled = false; +bool gModule_Email_Enabled = false; +bool gSignal_Handler_Enabled = true; + +#define LOG( X ) m_pLog->Log( "main", 0, X ) +#define LOG_ERROR( X ) m_pLog->Log( "main", 0, _LOG_ERROR, X ) + +mojoKernel * Kernel = NULL; +basicLogCollection * m_pLog = NULL; +basicSettingsProvider * SettingsProvider = NULL; +config_setting_t * Settings = NULL; + +#ifdef USE_MYSQL + mysqlDBC * DBC = NULL; +#else + sqliteDBC * DBC = NULL; +#endif + + +void (*old_kill_handler_9)(int); +void (*old_kill_handler_15)(int); + +void signal_kill_handler( int SIG ){ + if( Kernel!= NULL ){ + if( gSignal_Handler_Enabled ){ + m_pLog->Log("SIG", 0, _LOG_DEBUG, "Shutdown Service by Signal" ); + Kernel->setStatus( TH_ENDED ); // Closing all Connections; + } else { + m_pLog->Log("SIG", 0, _LOG_DEBUG, "Shutdown Signal Handler Disabled" ); + }; + }; +}; + +int main( int argc, char *argv[] ){ + + bool WBG; // Working Background + bool FLE; // File Logging Engine + bool SSE; // Server Statistics Engine + bool NDC; // No Default Configuration + CSTR FLE_NAME; + CSTR DCF_NAME; + CSTR SSP_NAME; + + // default init + WBG = true; + FLE = true; + FLE_NAME = (CSTR) DEFAULT_SERVER_LOG_FILE; + SSE = true; + NDC = true; + DCF_NAME = (CSTR) DEFAULT_SERVER_CONFIG_PATH; + SSP_NAME = (CSTR) DEFAULT_SERVER_SOCKET_PATH; + gsSOFT_INFO.SW_BUILD_DATE = UNIX_TIMESTAMP; + gsSOFT_INFO.DATA_VALID = false; + gsSOFT_INFO.SW_MODE_FLAGS = 0 +#ifdef SKIP_TARGET_LOG + | SW_INFO_NO_TARGET_LOG +#endif +#ifdef HIBERNATE_ENABLE + | SW_INFO_HIBERNATE_ENA +#endif +#ifdef TGD + | SW_INFO_TGD_MOTORS + #ifdef TGD_VERSION_2 + | SW_INFO_TGD_VER_2 + #endif +#endif +#ifdef ENCODER_8192 + | SW_INFO_EU_PROJECT +#endif +#ifdef NO_BLACK_TARGETS + | SW_INFO_NO_BLACK_TARGETS +#endif +#ifndef NO_MOTORS + | SW_INFO_MOTOR_CTRL_ENA +#endif +#ifdef THREADED_FLIP + | SW_INFO_THREAD_FLIP +#endif +#ifndef PRU_SLAVE + | SW_INFO_FLAG_MASTER +#endif +#ifdef DEBUG + | SW_INFO_DEBUG_MODE +#endif + ; + + + // Reading Config + if( argc > 1 ){ + for( int i = 0; i < argc; i++ ){ + switch( argv[i][0] ){ + case '-': + case '\\': + case '/':{ + switch( argv[i][1] ){ + case 'h': case 'H': case 'v': case 'V': case '?':{ + printf( "Dr Frucht Systems Mojo Module\n"); + printf( "Software version <%s>\n", VERSION_NUMBER ); + printf( " -h -H This Message\n" ); + printf( " -i -I Interactive Mode\n" ); + return 0; + break; + }; + case 'i': case 'I':{ + WBG = false; + break; + }; + case 'c': case 'C':{ + DCF_NAME = (CSTR) malloc( MAX_PATH_LEN ); + sprintf( DCF_NAME, "%s", argv[i+1] ); + break; + }; + }; + break; + }; + }; + }; + }; + if ( fileExist( DCF_NAME ) ){ + NDC = false; + } else { + DCF_NAME = (CSTR) DEFAULT_SERVER_CONFIG_FILE; + if( fileExist( DCF_NAME ) ){ + NDC = false; + }; + } + if ( !NDC ){ + // read serial number + FILE *pFile = fopen( DCF_NAME, "rt" ); + printf("Trying open file %s\n", DCF_NAME ); + if( pFile != NULL ){ + char pLine[1024]; + while( fgets( pLine, 1024, pFile ) ){ + SETTING_TYPE eType = ST_NONE; + CSTR pTemp = NULL; + for( int i = 0; i < sizeof( m_pSetting ) / sizeof( *m_pSetting ); i++ ){ + pTemp = strstr( pLine, m_pSetting[i] ); + if( pTemp ){ + eType = (SETTING_TYPE)i; + pTemp = strstr( pTemp, "=" ); + if( pTemp ) pTemp = strtok( pTemp + 1, " \t\n\r" ); + break; + }; + }; + + if( eType == ST_NONE || !pTemp ) continue; + + switch( eType ){ + case ST_SN:{ + gsCFG_LICENSE = (CSTR) malloc(strlen( pTemp )); + //memcpy( gsCFG_LICENSE, pTemp, strlen( pTemp ) ); + sprintf( gsCFG_LICENSE, "%s", pTemp ); + break; + }; + case ST_BIND_ADDRESS:{ + gsCFG_ADDRESS = (CSTR) malloc(strlen( pTemp )); + sprintf( gsCFG_ADDRESS, "%s", pTemp ); + break; + }; + case ST_BIND_PORT:{ + guCFG_PORT = ( uint16_t ) atoi( pTemp ); + break; + }; + case ST_PID_FILE:{ + gsCFG_PID_FILE = (CSTR) malloc(strlen( pTemp )); + sprintf( gsCFG_PID_FILE, "%s", pTemp ); + break; + }; + case ST_LOG_FILE:{ + FLE_NAME = (CSTR) malloc(strlen( pTemp )); + sprintf( FLE_NAME, "%s", pTemp ); + break; + }; + case ST_INTERACTIVE:{ + WBG = (atoi( pTemp ))? false: true; + break; + }; + case ST_SMS_ENABLE:{ + gModule_SMS_Enabled = (bool)atoi( pTemp ); + break; + }; + case ST_EMAIL_ENABLE:{ + gModule_Email_Enabled = (bool)atoi( pTemp ); + break; + }; + case ST_SMS_PROVIDER:{ + break; + }; + case ST_DATABASE_SERVER:{ + gsCFG_DB_SERVER = (CSTR) malloc(strlen( pTemp )); + sprintf( gsCFG_DB_SERVER, "%s", pTemp ); + break; + }; + case ST_DATABASE_USER:{ + gsCFG_DB_USER = (CSTR) malloc(strlen( pTemp )); + sprintf( gsCFG_DB_USER, "%s", pTemp ); + break; + }; + case ST_DATABASE_PASSWORD:{ + gsCFG_DB_PASSWORD = (CSTR) malloc(strlen( pTemp )); + sprintf( gsCFG_DB_PASSWORD, "%s", pTemp ); + break; + }; + case ST_DATABASE_NAME:{ + gsCFG_DB_NAME = (CSTR) malloc(strlen( pTemp )); + sprintf( gsCFG_DB_NAME, "%s", pTemp ); + break; + }; + case ST_SOCKET_NAME:{ + SSP_NAME = (CSTR) malloc(strlen( pTemp )); + sprintf( SSP_NAME, "%s", pTemp ); + break; + }; + }; + }; + fclose( pFile ); + } else { + NDC = true; + }; + }; + + + + if( NDC ){//Default config + gsCFG_LICENSE = (CSTR) "FRUCHT_DEMO_LICENSE"; + gsCFG_DB_SERVER = (CSTR) "localhost"; + gsCFG_ADDRESS = gsCFG_DB_SERVER; + gsCFG_DB_NAME = (CSTR) "tgdos"; + gsCFG_DB_USER = (CSTR) "tgdos"; + gsCFG_DB_PASSWORD = (CSTR) "NoGud4U@"; + }; + + + // Demonizing or not + if( WBG ){ + printf( "Dr Frucht Systems Mojo Module ver. %s\n", VERSION_NUMBER ); + printf( "Configuration Applied:\n"); + printf( " Service Established %s at %d\n", gsCFG_ADDRESS, guCFG_PORT ); + printf( " PID File: %s\n", gsCFG_PID_FILE ); + printf( " Log File: %s\n", FLE_NAME ); + printf( " License: %s\n", gsCFG_LICENSE ); + printf( " Database Server: %s Database: %s\n", gsCFG_DB_SERVER, gsCFG_DB_NAME ); + if( NDC ){ + printf( " No configuration file (%s) supplied.\n", DCF_NAME); + } else { + printf( " Configuration read from: %s\n", DCF_NAME ); + }; + + //Demonizing + pid_t pid, sid; + sync(); + close( STDIN_FILENO ); + close( STDOUT_FILENO ); + close( STDERR_FILENO ); + + pid = fork(); + if( pid < 0 ){ + return pid; + }; + if( pid > 0 ){ + return 0; + }; + //umask(0); + sid = setsid(); + if (sid < 0) { + return sid; + }; + + pid = fork(); + if( pid < 0 ){ + return pid; + }; + if( pid > 0 ){ + FILE *pPIDF = fopen( gsCFG_PID_FILE, "w+" ); + if( pPIDF ){ + fprintf( pPIDF, "%d\n", pid ); + fclose( pPIDF ); + } + return 0; + }; + }; + + + //Block Some Signals + //sigset_t signal_mask; + //sigfillset( &signal_mask ); + //sigaddset(&signal_mask, SIGUSR1); + //pthread_sigmask( SIG_BLOCK, &signal_mask, NULL ); + + // Clear to start Service + m_pLog = basicLogCollection::getInstance( _LOG_LVL_TIME_PTR ); + m_pLog->setLogLevel( _LOG_ERROR ); // Most Silent Mode + + if ( FLE ){// Init File Logging Engine + m_pLog->addHandler((basicLoggingService *) new objectFileLoggingService( FLE_NAME )); + }; + + if ( !WBG ){// Init Curses class to handle UI + //m_pLog->addHandler((_Core_Logging_Service *) new _Core_CLUI()); + }; + + SettingsProvider = basicSettingsProvider::getInstance( DCF_NAME ); + Settings = SettingsProvider->getSubNode( NULL, "GENERAL" ); + + uint8_t ExitCode = 0; + bool SSDP_ENABLE = false; + config_setting_t * pSetting = NULL; + + if(!config_setting_lookup_bool( Settings, "SSDP_ENABLE", (int*) &SSDP_ENABLE )){ + pSetting = config_setting_add( Settings, "SSDP_ENABLE", CONFIG_TYPE_BOOL ); + SSDP_ENABLE = true; + config_setting_set_bool( pSetting, SSDP_ENABLE ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Manufacturer not set - using default"); + }; + + SettingsProvider->validate(); + +#ifdef USE_MYSQL + DBC = mysqlDBC::getInstance( Settings ); +#else + DBC = sqliteDBC::getInstance( Settings ); +#endif + if( DBC ) { + if(!DBC->connect()){ + delete( DBC ); + LOG_ERROR( "++++ DB ERROR ++++" ); + unlink( gsCFG_PID_FILE ); + LOG( "PID File Deleted" ); + delete( m_pLog ); + return -1; + }; + }; + + // Start Loop of Restarted Kernel + do{ + ExitCode = 0; + Kernel = mojoKernel::getInstance( Settings );//HWManager ); + + if( Kernel == NULL ) { + // Aborting Work + LOG_ERROR( "++++ Kernel failed to born ++++" ); + unlink( gsCFG_PID_FILE ); + LOG( "PID File Deleted" ); + delete( m_pLog ); + return -1; + }; + //Loop till some Restart action + if( Kernel != NULL ){ + LOG( "++++ Server Started ++++" ); + if ( !Kernel->create( ) ){ + LOG_ERROR("Kernel create failure!"); + } else { + //Install Signal Listeners + old_kill_handler_15 = signal( 15, signal_kill_handler ); + old_kill_handler_9 = signal( 9, signal_kill_handler ); + // Waiting for Worker to Shut Down + Kernel->WaitFinish( false ); + ExitCode = Kernel->getExitCause(); + signal( 9, old_kill_handler_9 ); + signal( 15, old_kill_handler_15 ); + }; + delete( Kernel ); + LOG( "++++ Server Ended ++++" ); + }; + + if( ExitCode == EXIT_CODE_FACTORY_RESET ){ + CSTR tNAME = DBC->getDataParam( 0 ); + CSTR tUSER = DBC->getDataParam( 1 ); + CSTR tGROUP = DBC->getDataParam( 2 ); + delete( DBC ); + if ( tNAME != NULL ) { + LOG("FACTORY RESET ISSUED!"); + if( !fileExist( "data/factory.db" ) ){ + LOG_ERROR( "++++ No Factory Backup ++++" ); + } else { + if ( fileExist( tNAME ) ) { + LOG("Replace Working DB by Factory Clean one!"); + unlink( tNAME ); + } else { + LOG("No Old DB! Just copy Factory Clean one!"); + }; + fileCopy( "data/factory.db", tNAME ); + }; + free( tNAME ); + } else { + LOG_ERROR( "++++ No DB File Assigned ++++" ); + }; + ExitCode = 0; + }; + + } while( ExitCode > 0 ); + + unlink( gsCFG_PID_FILE ); + LOG( "PID File Deleted" ); + delete( m_pLog ); + return 0; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/mojo/mojoBackend.h b/lib/App/mojo/mojoBackend.h new file mode 100644 index 00000000..e4ac52bf --- /dev/null +++ b/lib/App/mojo/mojoBackend.h @@ -0,0 +1,29 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2016. All Rights Reserved. +// Version 2.0 7/20/2017 +// Last modification: 7/20/2017 +// PROJECT: +// SUBSYSTEM: +// FILE: LRF_Server.h +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// Header file of LRF_Server.h +//---------------------------------------------------------------------------- +// +#ifndef __LA_MOJO_SERVER_HEADER__ +#define __LA_MOJO_SERVER_HEADER__ + +#include +#include +#include + +#include "../../components/base/basicSettings.h" +#include "../../components/base/basicLogCollection.h" +#include "../../components/base/basicMemoryOperation.h" +#include "../../components/object/objectFileLoggingService.h" +#include "mojoKernel.h" + + +#endif diff --git a/lib/App/mojo/mojoDBConnector.cpp b/lib/App/mojo/mojoDBConnector.cpp new file mode 100644 index 00000000..287063b3 --- /dev/null +++ b/lib/App/mojo/mojoDBConnector.cpp @@ -0,0 +1,264 @@ +#include "mojoDBConnector.h" + +#define LOG( X ) m_pLog->Log( "MDBC", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "MDBC", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "MDBC", this, _LOG_ERROR, X ); +#endif + +mojoDBC *mojoDBC::_instance = NULL; + +/** + * Returns the single instance of the object. + */ +mojoDBC *mojoDBC::getInstance( config_setting_t * Settings ) { + // check if the instance has been created yet + if( 0 == _instance ){ + // if not, then create it + _instance = new mojoDBC( Settings ); + }; + // return the single instance + return _instance; +}; + + +mojoDBC::mojoDBC( config_setting_t * Settings ){ + m_pLog = basicLogCollection::getInstance(); + m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "DATABASE" ); + m_bIsConnected = false; + m_bIsServerLocal = true; + m_pDataStorage = NULL; + m_pDataMemory = NULL; +}; + +mojoDBC::~mojoDBC(){ + if ( m_pDataStorage ) delete( m_pDataStorage ); + if ( m_pDataMemory ) delete( m_pDataMemory ); + _instance = NULL; +}; + +bool mojoDBC::connect( void ){ + if ( m_pSettings == NULL) return false; + bool bRecreateMemStructures = false; + config_setting_t * pSetting; + const char * tBuff; + //Disconnect if Connected + m_bIsConnected = false; + char web_access_user[64]; + char web_access_group[64]; + + //Apply New Config +#ifdef DEBUG + LOG( "Reading DB Settings ... " ); +#endif + if(!config_setting_lookup_string(m_pSettings, "DATA_FILE_NAME", (const char**)&tBuff )){ + pSetting = config_setting_add(m_pSettings, "DATA_FILE_NAME", CONFIG_TYPE_STRING); + sprintf( m_pDbFile, "data/mysqlitedb.db" ); + config_setting_set_string( pSetting, m_pDbFile ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Data Storage not set - using default"); + } else { + sprintf( m_pDbFile, tBuff ); + }; + if(!config_setting_lookup_string(m_pSettings, "WEB_ACCESS_USER", (const char**)&tBuff )){ + pSetting = config_setting_add(m_pSettings, "WEB_ACCESS_USER", CONFIG_TYPE_STRING); + sprintf( web_access_user, "www-data" ); + config_setting_set_string( pSetting, web_access_user ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Web Access User not set - using default"); + } else { + sprintf( web_access_user, tBuff ); + }; + if(!config_setting_lookup_string(m_pSettings, "WEB_ACCESS_GROUP", (const char**)&tBuff )){ + pSetting = config_setting_add(m_pSettings, "WEB_ACCESS_GROUP", CONFIG_TYPE_STRING); + sprintf( web_access_group, "www-data" ); + config_setting_set_string( pSetting, web_access_group ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Web Access Group not set - using default"); + } else { + sprintf( web_access_group, tBuff ); + }; + if( !fileExist( DB_SHMEM_POINT )) { + bRecreateMemStructures = true; + mkdir( DB_SHMEM_POINT, 0775 );// S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH ); + chown( DB_SHMEM_POINT, web_access_user, web_access_group ); //To make Accessed from PHP + chmod( DB_SHMEM_POINT, 0775 ); + }; + if (!config_setting_lookup_string(m_pSettings, "DATA_MEMORY_NAME", (const char **)&tBuff)) { + pSetting = config_setting_add(m_pSettings, "DATA_MEMORY_NAME", CONFIG_TYPE_STRING); + sprintf( m_pDbMemory, "mem_db.db" ); + config_setting_set_string( pSetting, m_pDbMemory ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Memory Storage not set - using default"); + }; + sprintf( m_pDbMemory, "%s/%s", DB_SHMEM_POINT, tBuff ); + basicSettingsProvider::getInstance()->validate(); + + // Kill Connection if any + if ( m_pDataStorage ) delete( m_pDataStorage ); + if ( m_pDataMemory ) delete( m_pDataMemory ); + +#ifdef DEBUG + LOG( m_pDbFile ); +#endif + // Create New Connections + m_pDataStorage = new SQLite_Connector(); + if ( m_pDataStorage ) { + if( m_pDataStorage->Connect( m_pDbFile, 0, true ) ){ +#ifdef DEBUG + LOG("DB File Opened"); +#endif + chown( m_pDbFile, web_access_user, web_access_group ); + chmod( m_pDbFile, 0775 ); + } else{ + LOG_ERROR("Cannot Connect to DB File"); + delete( m_pDataStorage ); + m_pDataStorage = NULL; + LOG("Storage Deleted!"); + return false; + }; + }; +#ifdef DEBUG + LOG( m_pDbMemory ); +#endif + if( !fileExist( m_pDbMemory )) { + bRecreateMemStructures = true; + }; + m_pDataMemory = new SQLite_Connector(); + if ( m_pDataMemory ) { + if( m_pDataMemory->Connect( m_pDbMemory, 0, true ) ){ +#ifdef DEBUG + LOG("DB Memory Opened"); +#endif + chown( m_pDbMemory, web_access_user, web_access_group ); + chmod( m_pDbMemory, 0775 ); + if ( bRecreateMemStructures ) initMemDB(); + } else{ + LOG_ERROR("Cannot Connect to DB Memory"); + delete( m_pDataStorage ); + delete( m_pDataMemory ); + m_pDataStorage = NULL; + m_pDataMemory = NULL; + return false; + }; + }; + m_bIsConnected = true; + return m_bIsConnected; +}; + +void mojoDBC::initMemDB( void ){ + +m_pDataMemory->Query("CREATE TABLE \"nodes_qcq\" ( \ + \"id\" INTEGER NOT NULL,\ + \"node_id\" INTEGER NOT NULL,\ + \"cmd\" INTEGER NOT NULL,\ + \"status\" INTEGER DEFAULT 0,\ + \"parameter\" TEXT,\ + PRIMARY KEY(\"id\" AUTOINCREMENT)\ +);"); + +m_pDataMemory->Query("CREATE TABLE \"servers\" (\ +\"id\" INTEGER NOT NULL,\ + \"online\" INTEGER DEFAULT 0,\ + \"ts\" INTEGER DEFAULT 0,\ + \"version_string\" TEXT,\ + \"identity\" TEXT,\ + \"pid\" INTEGER DEFAULT 0,\ + \"cpu_cores\" INTEGER DEFAULT 0.0,\ + \"stat_cpu1\" REAL DEFAULT 0.0,\ + \"stat_cpu5\" REAL DEFAULT 0.0,\ + \"stat_cpu15\" REAL DEFAULT 0.0,\ + \"stat_mem\" REAL DEFAULT 0.0,\ + \"stat_disk\" REAL DEFAULT 0.0,\ + \"val_mem_tottal\" INTEGER DEFAULT 0,\ + \"val_mem_current\" INTEGER DEFAULT 0,\ + \"val_disk_tottal\" INTEGER DEFAULT 0,\ + \"val_disk_current\" INTEGER DEFAULT 0,\ + \"temp0\" REAL DEFAULT 0.0,\ + PRIMARY KEY(\"id\" AUTOINCREMENT)\ +);"); + +}; + + +DBC_PUSHED_CMD *mojoDBC::getNodePushedCMD( uint32_t NodeID ){ + DBC_PUSHED_CMD * RetVal = NULL; + if ( m_bIsConnected ) { + char QS[MAX_PATH]; + AAssoc * result; + sprintf( QS, "select * FROM `nodes_qcq` WHERE `node_id`=%d AND `status`=0 ORDER BY `id` LIMIT 1", NodeID ); + result = m_pDataMemory->Query( QS ); + if ( result ) { + if( result->size() > 0 ) { + RetVal = (DBC_PUSHED_CMD*)malloc(sizeof(DBC_PUSHED_CMD)); + if( RetVal ) { + Assoc * cArr; + Assoc::iterator it; + + memset( RetVal, 0, sizeof(DBC_PUSHED_CMD)); + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + RetVal->id = atoi( it->second.c_str() ); + }; + it = cArr->find("cmd"); + if( it != cArr->end() ){ + RetVal->CMD = atoi( it->second.c_str() ); + }; + it = cArr->find("parameter"); + if( it != cArr->end() ){ + strncpy( RetVal->PARAM, it->second.c_str(), 256 ); + RetVal->PARAM[255] = (char)0; + }; + }; + }; + }; + m_pDataMemory->deleteResult( result ); + }; + return RetVal; +}; + +bool mojoDBC::updateNodePushedCMD( uint32_t CmdID, uint8_t status ){ + if ( m_bIsConnected ) { + char QS[MAX_PATH]; + sprintf( QS, "UPDATE `nodes_qcq` SET `status`=%d WHERE `id`=%d ", status, CmdID ); + return m_pDataMemory->SilentQuery( QS ); + }; + return false; +}; + +bool mojoDBC::cleanNodePushedCMD( void ){ + if ( m_bIsConnected ) { + return m_pDataMemory->SilentQuery( "DELETE FROM `nodes_qcq` WHERE `status` > 200" ); + }; + return false; +}; + + + +/******************************************************************** + * * + * Slow DB Functions * + * * + ********************************************************************/ + +DBC_NET_IF_DATA *mojoDBC::getNIF_Data( uint32_t ID ){ + +}; +uint32_t mojoDBC::getNIF_ID( CSTR key ){ + +}; +uint32_t mojoDBC::getNIF_IDbyDevice( CSTR device ){ + +}; + + + +#undef LOG +#undef LOG_ERROR \ No newline at end of file diff --git a/lib/App/mojo/mojoDBConnector.h b/lib/App/mojo/mojoDBConnector.h new file mode 100644 index 00000000..c62fa301 --- /dev/null +++ b/lib/App/mojo/mojoDBConnector.h @@ -0,0 +1,202 @@ +#ifndef __MOJO_DATABASE_CONNECTOR_HEADER__ +#define __MOJO_DATABASE_CONNECTOR_HEADER__ + +#include "../components/base/basicSettingsProvider.h" +#include "../data/sqlite/sqlite_class.h" +#include "../alg/generic/md5.h" +#include "../alg/lgs/mask.h" +#include "../../rgoose/rgooseTypes.h" + +#define DB_SHMEM_POINT "/dev/shm/argus" + + +class mojoDBC{ + private: + basicLogCollection * m_pLog; + config_setting_t * m_pSettings; + SQLite_Connector * m_pDataStorage; + SQLite_Connector * m_pDataMemory; + bool m_bIsConnected; + bool m_bIsServerLocal; + bool m_bRecreateMemStructures; + char m_pDbFile[CLOG]; + char m_pDbMemory[CLOG]; + char m_pDbUsername[CLOG]; + char m_pDbPassword[CLOG]; + char m_pDbDatabase[CLOG]; + void initMemDB( void ); + public: + static mojoDBC * getInstance( config_setting_t * Settings = NULL ); + virtual ~mojoDBC(); + /* Functionality */ + bool connect( void ); + bool isLocal( void ) const { return m_bIsServerLocal; }; + + //SET GLOBAL tmp_table_size = 1024 * 1024 * 1024 * 2; + //SET GLOBAL max_heap_table_size = 1024 * 1024 * 1024 * 2; + //SELECT @@max_heap_table_size; + //SHOW VARIABLES LIKE 'max_heap_table_size'; + + + + + + uint32_t addEvent( uint32_t SRC, CSTR UUID, uint32_t tss, uint32_t tsms, uint8_t evt_type, uint8_t k_id=0, uint16_t dig_r=0, float EL=.0f, float AZ=.0f, float RANGE=.0f, float AREA=.0f, float lat=.0f, float lon=.0f, float alt=.0f, uint32_t RefID=0, CSTR RefUUID=NULL ); + bool addDeviceDraw( uint32_t DBID, uint8_t type, uint8_t lrf, void *th_data, uint32_t th_size ); + + bool addLRFDraw( uint32_t DBID, uint32_t SIZE, CSTR ID, uint8_t kID =0, uint8_t type = 0, bool rendered = false ); + uint32_t addLRFMask( uint32_t devID, uint8_t lrfID = 0, uint8_t layerID = 0 ); + uint32_t addLRFMaskPolygone( uint32_t maskID, uint8_t r, uint8_t g, uint8_t b ); + bool addLRFMaskPolygonePoint( uint32_t polyID, int16_t x, int16_t y ); + + //bool addIPCam( uint32_t SiteID, resultWoWo *tPtr ); + bool addIPCam( uint32_t SiteID, OBSERVER_RESULT *tPtr ); + uint32_t addLocalMediaSource( uint32_t SiteID, CSTR path, uint32_t width, uint32_t height ); + uint32_t addLocalDCB( uint32_t SiteID, CSTR PATH, CSTR SERIAL, uint8_t CNT, uint32_t status ); + uint32_t addLocalUART( uint32_t NodeID, uint8_t utype, uint32_t speed, uint8_t bit, char parity, float stop_bit, CSTR PATH, uint8_t mode=0, uint16_t port=0 ); + uint32_t addLocalNIF( CSTR device, CSTR mac, ARGUS_NIF_TYPE dtype, ARGUS_NIF_MODE dmode, uint32_t aux_id = 0 ); + uint32_t addLocalNetwork( uint32_t NIF_ID, ARGUS_NETWORK_TYPE net_type, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ); + uint32_t addLocalNetworkInfrastructure( uint32_t NIF_ID, uint32_t OUTBOUND_NIF, bool ena_dhcp=false, CSTR BRANG=NULL, CSTR ERANG=NULL, CSTR MASK=NULL, CSTR LEASE_TIME=NULL ); + uint32_t addLocalWiFi( uint32_t NIF_ID, ARGUS_WIFI_MODE mode, CSTR SSID, CSTR password, ARGUS_WIFI_ENCRIPTION encryption, uint32_t router_id=0 ); + bool addNotification( uint32_t MSG_ID, uint8_t DIS_LVL = 0, uint32_t OBJ_ID=0 ); + bool addPicture( DBC_SNAPSHOT_DATA *ptr, CSTR ext ); + + //bool addPictureEvent( uint32_t evtID, uint32_t pictureoID ); + uint32_t addResource( uint32_t NodeID, uint8_t type, CSTR devName, uint32_t auxID = 0 ); + uint32_t addUploadFile( uint32_t NodeID, CSTR uid, CSTR fileName ); + + bool addVideoEvent( uint32_t evtID, uint32_t videoID, uint32_t clen ); + uint32_t addVideoRecord( uint32_t streamID, CSTR md5, CSTR ext, uint32_t ts, uint32_t tsms, uint32_t fps ); + + bool cleanResources( uint32_t ServerNodeID, bool all = false ); + bool cleanLRFMask( uint32_t maskID, bool deleteMask = false ); + bool cleanNodeEvents( uint32_t NodeID, bool all = false ); + bool cleanEvents2PictureBinding( uint32_t PicID ); + bool cleanEvents2VideoBinding( uint32_t PicID ); + bool cleanNodePushedCMD( void ); + + + void lazyEventArchiver( uint32_t DalayTime = 10 ); + DBC_INT_LIST * listCamMediaStreams( uint32_t CAMID ); + DBC_INT_LIST * listStreamCapPictures( uint32_t StreamID, uint32_t cnt ); + DBC_INT_LIST * listDetectionProfileIDs( uint32_t nodeID ); + DBC_INT_LIST * listDetectionProfiles( uint32_t nodeID ); + DBC_INT_LIST * listFilters( uint32_t ServerID ); + DBC_INT_LIST * listLRFMaskVertexes( uint32_t MaskID ); + DBC_INT_LIST * listLRFMaskVertexPoints( uint32_t VertexID ); + DBC_INT_LIST * listMediaServerStreams( uint32_t SiteId, uint32_t MediaServerID, uint8_t listingType = LIST_ALL_RECORDS ); + DBC_INT_LIST * listMediaStreams( uint32_t SiteId, uint8_t listingType = LIST_ALL_RECORDS ); + DBC_INT_LIST * listModules( uint32_t ServerID ); + DBC_INT_LIST * listNetworks( uint32_t nif_id ); + DBC_INT_LIST * listNewModules( uint32_t ServerID, DBC_INT_LIST * old_ids ); + + DBC_INT_LIST * listNewNodes( uint32_t SiteID, uint32_t ServerID, DBC_INT_LIST * old_ids ); + DBC_INT_LIST * listNodes( uint32_t SiteID, uint32_t ServerID, bool all = false ); + //DBC_INT_LIST * listSockets( uint32_t NodeID ); + DBC_INT_LIST * listResources( uint32_t NodeID = 0 ); + simplePolygone * loadLRFMaskVertex( uint32_t vid ); + + bool getAllCamRecords( uint32_t SiteID, vectorCamRecords &VR ); + DBC_APF_DATA * getAPFData( uint32_t APFID ); + DBC_CAM_DATA * getCamData( uint32_t CamID ); + uint32_t getCamId( CSTR UUID ); + + bool getConnectionStatus(void){return m_bIsConnected;}; + DBC_CAP_DATA * getCamCapPictureData( uint32_t PicID ); + DBC_EVT_RECORD * getEventByUUID( CSTR UUID ); + DBC_MODULE_EMBED_VIDEO_DATA * getEmbedVideoData( uint32_t ID ); + DBC_FH_DATA * getFlyHunterData( uint32_t ID ); + int getIPCamCount( uint32_t SiteID ); + KAFKA_TEMPLATE * getKafkaTemplateForEvent( uint32_t ModuleID, uint32_t ClassID, uint32_t EventID ); + //bool getLastEvents( vectorEventRecords &VR, uint32_t tss, uint32_t tsms ); + DBC_LRF_DATA * getLRFData( uint32_t ID ); + uint8_t getLRFDataStatus( uint32_t ID ); + PLGS_2D_PARAMETERS getLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master ); + CSTR getLRFDraw( uint32_t DBID ); + uint32_t getLRFMaskID( uint32_t deviceID, uint8_t lrfID = 0, uint8_t layer = 0 ); + DBC_MEDIA_STREAM_DATA * getMediaStreamData( uint32_t ID ); + DBC_MEDIA_SERVER_DATA * getMediaServerData( uint32_t ID ); + DBC_MEDIA_SERVER_STREAM_DATA * getMediaServerStreamData( uint32_t ID ); + DBC_MEDIA_SERVER_STREAM_DATA * getMediaServerStreamDataBySource( uint32_t ID ); + DBC_MODULE_DATA * getModuleData( uint32_t ID ); + CSTR getNodeName( uint32_t NodeID ); + uint32_t getNodeAuxParam( uint32_t NodeID ); + uint32_t getNodeAuxID( uint32_t NodeID ); + DBC_NETWORK_DATA * getNetworkData( uint32_t net_id ); + uint32_t getNetworkInfrastructureID( uint32_t nif_id ); + DBC_NET_IF_DATA * getNIF_Data( uint32_t ID ); + uint32_t getNIF_ID( CSTR key ); + uint32_t getNIF_IDbyDevice( CSTR device ); + DBC_NODE_DATA * getNodeData( uint32_t ID ); + + DBC_PUSHED_CMD * getNodePushedCMD( uint32_t NodeID ); + DBC_PUSHED_CMD * getActivePushedCMD( uint32_t NodeID ); + DBC_PUSHED_CMD * getPushedCMD( uint32_t CmdID ); + + //uint32_t getNodeSocketID( uint32_t NodeID, uint32_t auxID, uint8_t SocketType, CSTR path ); + DBC_RESOURCE_DATA * getResourceData( uint32_t ResourceID ); + uint32_t getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID ); + uint32_t getServerID( CSTR identity ); + uint32_t getServerNode( uint32_t SID ); + KAFKA_SETTINGS * getSettingsKAFKA( uint32_t NodeID ); + DBC_SITE_DATA * getSiteData( uint32_t ID ); + //DBC_SOCKET_DATA * getSocketData( uint32_t ID ); + DBC_TARGET_FLITER_DATA * getTargetFilterData( uint32_t ID ); + DBC_UART_DATA * getUartData( uint32_t UartID ); + uint32_t getUartID( uint32_t NodeID, uint8_t Type, CSTR path ); + uint32_t getWiFi_ID( uint32_t nif_id ); + bool fillShadow2D( uint32_t ID, SHADOW & SH ); + + void deleteCamCapPicture( uint32_t PicID ); + void deleteNode( uint32_t NodeID ); + void deleteCamera( uint32_t CamID ); + void deleteConnections( uint32_t NodeID ); + void deleteNodeEvents( uint32_t NodeID ); + void deleteMediaStream( uint32_t MediaID ); + void deleteNIF( uint32_t NifID ); + void deleteNIS( uint32_t NisID ); + void deleteResource( uint32_t ResourceID ); + void deleteSensor( uint32_t SensorID ); + void deleteUART( uint32_t UARTID ); + + void finalizeVideoRecord( uint32_t videoID, uint32_t clen ); + + void registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_t *ServID, uint32_t *ServNode ); + void unregisterServer( uint32_t ServerID, uint32_t NodeID ); + + bool transferEvtToArchive( uint32_t SECONDS = ONE_DAY_HISTORY ); + + + + bool setNodeOnline( uint32_t NodeID, uint8_t status=ARGUS_NODE_STATUS_WORK ); + bool setNodeOffline( uint32_t NodeID ); + bool setOnlineStatus( bool Status ); + bool setLRFDetectionProfile( uint32_t lrfID, uint8_t profileID ); + bool setLRFDataStatus( uint32_t lrfID, uint8_t ST ); + bool setLRFAltSerial( uint32_t lrfID, CSTR Serial ); + bool setLRFAltVerison( uint32_t lrfID, CSTR version ); + bool setLRFMaskStatus( uint32_t maskID, bool status ); + bool setStreamValid( uint32_t streamID, bool status = true ); + //bool syncEventArchive( void ); ALTER TABLE table_name AUTO_INCREMENT = start_value; + bool update3DRuntimeStatus( uint32_t lrfID, ALG_RUN_STATUS *ptr ); + bool updateAFPBox( uint32_t filterID, CSTR Tag, float x, float y, float z ); + bool updateCamRange( uint32_t camID, float range ); + bool updateIPCam( uint32_t SiteID, CSTR uuid, CSTR Addr ); + bool updateIPCam( uint32_t SiteID, uint32_t CamID, CSTR Addr ); + bool updateLRFSerial( uint32_t lrfID, CSTR Serial ); + bool updateLRFVerison( uint32_t lrfID, CSTR version ); + bool updateLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master, uint16_t nOrder, uint16_t nOffset, uint16_t nDelta, uint16_t nWidth, uint16_t nFlip, uint16_t nSun, uint8_t bSST, uint32_t GP=0, uint32_t spikes=0 ); + bool updateMediaServerStream( uint32_t id, CSTR mrl=NULL, CSTR key = NULL ); + bool updateNetworkNode( bool OnlineStatus ); + bool updateNodePushedCMD( uint32_t CmdID, uint8_t status ); + bool updateResourceAUX( uint32_t ResID, uint32_t AUX ); + bool updateServerUtilisation( uint32_t ServerID, uint32_t nCores, float cpu1, float cpu5, float cpu15, float mem, float disk, uint64_t dtsize, uint64_t dcsize, uint64_t mtsize, uint64_t mcsize ); + private: + static mojoDBC * _instance; + explicit mojoDBC( config_setting_t * Settings ); +}; + + + + +#endif //__MOJO_DATABASE_CONNECTOR_HEADER__ diff --git a/lib/App/mojo/mojoHardwareManager.cpp b/lib/App/mojo/mojoHardwareManager.cpp new file mode 100644 index 00000000..cf734197 --- /dev/null +++ b/lib/App/mojo/mojoHardwareManager.cpp @@ -0,0 +1,916 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2017. All Rights Reserved. +// Version 2.0 7/20/2017 +// Last modification: 7/20/2017 +// PROJECT: +// SUBSYSTEM: +// FILE: mojoHardwareManager.cpp +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// Header file of mojoHardwareManager.cpp +//---------------------------------------------------------------------------- +// + +#include "mojoHardwareManager.h" +#include "../hardware/hid/hid_dc.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#define LOG( X ) m_pLog->Log( "MHWM", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "MHWM", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "MHWM", this, _LOG_ERROR, X ); +#endif + + +mojoHardwareManager *mojoHardwareManager::_instance = NULL; + +/** + * Returns the single instance of the object. + */ +mojoHardwareManager *mojoHardwareManager::getInstance( config_setting_t * Settings ) { + // check if the instance has been created yet + if( 0 == _instance ){ + // if not, then create it + _instance = new mojoHardwareManager( Settings ); + }; + // return the single instance + return _instance; +}; + + +// Constructor implementation +mojoHardwareManager::mojoHardwareManager( config_setting_t *SNode ){ + m_pLog = basicLogCollection::getInstance(); + m_pSettingsProvider = basicSettingsProvider::getInstance(); + m_nMemoryLimitHeapSize = 0; + if( m_pSettingsProvider ) { + m_pSettings = m_pSettingsProvider->getSubNode( SNode, "HARDWARE_MANAGER" ); + if( m_pSettingsProvider->isCompromised() ) { + m_pSettingsProvider->validate(); + }; + } else { + m_pSettings = NULL; + }; + + m_pDBC = mojoDBC::getInstance(); + + char tB[128]; + struct rlimit rl={0}; + getrlimit( RLIMIT_STACK, &rl ); + sprintf( tB, "Stack Size: %d", rl.rlim_cur ); //RLIM_INFINITY + LOG( tB ); + sprintf( tB, "MAX Stack Size: %d", rl.rlim_max ); + LOG( tB ); + m_bInitOK = false; +}; + +mojoHardwareManager::~mojoHardwareManager(){ + _instance = NULL; +}; + +bool mojoHardwareManager::validate(){ + bool RetVal = true; + //Mem Validator + if( m_nMemoryLimitHeapSize ) { + size_t memStat = getCurrentRSS(); +#ifdef DEBUG_EXTRA + char MEM_MSG[128]; + sprintf( MEM_MSG, "MEM: %d TARG: %d", memStat, m_nMemoryLimitHeapSize ); + LOG( MEM_MSG ); +#endif + RetVal = ( memStat < m_nMemoryLimitHeapSize ); + if ( !RetVal ) { + LOG_ERROR("Memory Consumption too BIG!"); + }; + }; + return RetVal; +}; + +int xioctl(int fh, int request, void *arg){ + int r; + do { + r = ioctl( fh, request, arg ); + } while (-1 == r && EINTR == errno); + return r; +}; + +#define CLEAR(x) memset(&(x), 0, sizeof(x)) + + + +void mojoHardwareManager::getMAC( CSTR if_name, CSTR buf ){ + char tB[128]; + FILE * fd=NULL; + if ( buf ) { + sprintf(tB, "/sys/class/net/%s/address", if_name); +#ifdef DEBUG + LOG( tB ); +#endif + fd=fopen(tB,"r"); + if ( fd ) { + fread( buf, 1, INET6_ADDRSTRLEN, fd ); + fclose( fd ); + buf = trim( buf ); + } else { + memset( buf, 0, INET6_ADDRSTRLEN ); + }; +#ifdef DEBUG + LOG( buf ); +#endif + }; +}; + +void mojoHardwareManager::getGW( CSTR if_name, CSTR buf ){ + FILE * fd = popen( "route -n", "r" ); + char tB[1024]; + //char expBuf[1024]; + + memset( buf, 0, INET6_ADDRSTRLEN ); + + if ( fd ) { + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + if( strstr( tB, if_name ) != NULL ){ + //strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ' ', tB ); + if ( CA ) { + //for (int i=0; i< CA->size(); i++ ) { + // char tB[128]; + // trim( CA->at(i) ); + // sprintf( tB, "GW# %d: %s", i, CA->at(i) ); + // LOG( tB ); + //}; + trim( CA->at(1) ); + if( strstr(CA->at(1), "0.0.0.0") == NULL ) { + strncpy( buf, CA->at(1), INET6_ADDRSTRLEN ); + }; + delete(CA); + }; + }; + }; + }; + fclose( fd ); + }; + if( strlen( buf ) == 0 ) strncpy( buf, "0.0.0.0", INET6_ADDRSTRLEN ); +}; + +void mojoHardwareManager::getTTyDesc( CSTR dev_name, CSTR buf ){ + FILE * fd = popen( "dmesg | grep tty", "r" ); + char tB[1024]; + //char expBuf[1024]; + + memset( buf, 0, DBC_RESOURCE_DESC_SIZE ); + + if ( fd ) { + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + if( strstr( tB, dev_name ) != NULL ){ + //strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ':', tB ); + if ( CA ) { + //for (int i=0; i< CA->size(); i++ ) { + // char tB[128]; + // trim( CA->at(i) ); + // sprintf( tB, "GW# %d: %s", i, CA->at(i) ); + // LOG( tB ); + //}; + trim( CA->at(1) ); + strncpy( buf, CA->at(1), DBC_RESOURCE_DESC_SIZE ); + buf[DBC_RESOURCE_DESC_SIZE-1]=(char)0; + delete(CA); + }; + }; + }; + }; + fclose( fd ); + }; + if( strlen( buf ) == 0 ){ + strncpy( buf, "--Unknown--", DBC_RESOURCE_DESC_SIZE ); + buf[DBC_RESOURCE_DESC_SIZE-1]=(char)0; + }; +}; + +PARSE_RESULT_NET_INTERFACES *mojoHardwareManager::parse_neconfig( CSTR if_name ){ + PARSE_RESULT_NET_INTERFACES *tVal = NULL; + FILE *fd; + bool cConfig = false; + fd = fopen("/etc/network/interfaces","r"); + if ( fd ) { + char tB[1024]; + char expBuf[1024]; + tVal = (PARSE_RESULT_NET_INTERFACES *) malloc( sizeof(PARSE_RESULT_NET_INTERFACES)); + if ( tVal ) { + memset(tVal, 0 , sizeof(PARSE_RESULT_NET_INTERFACES)); + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ' ', expBuf ); + if( CA ) { + for( CArray::iterator idx = CA->begin(); idx < CA->end(); idx++ ) { + if((*idx)[0]=='#') break; + if(strstr((*idx), "auto")!= NULL ) if( strstr( tB, if_name )!= NULL ) tVal->enabled = true; + if(strstr((*idx), "allow-hotplug")!= NULL ) if( strstr( tB, if_name )!= NULL ) tVal->hot_plug = true; + if(strstr((*idx), "iface")!= NULL ) if( strstr( tB, if_name )!= NULL ){ + if (strstr( tB, "static") != NULL) tVal->if_static = true; + cConfig = true; + } else cConfig = false; + if(strstr((*idx), "address")!= NULL ) if( cConfig ){ + idx++; + if(strstr((*idx),"/")!= NULL ){ + int8_t sh = strstr((*idx),"/") - (*idx); + strncpy( tVal->address, (*idx), sh ); + tVal->address[sh]=(char)0; + int8_t bm = atoi( (*idx) + sh + 1 ); + union{ + uint32_t mm; + uint8_t nm[4]; + } nmu = {0}; + for ( sh = 0; sh < bm; sh++ ) nmu.mm |= (1 << sh); + sprintf(tVal->netmask, "%d.%d.%d.%d", nmu.nm[0], nmu.nm[1], nmu.nm[2], nmu.nm[3]); + } else { + strncpy( tVal->address, (*idx), INET6_ADDRSTRLEN ); + }; + }; + if(strstr((*idx), "netmask")!= NULL ) if( cConfig ){ + LOG("netMSK"); + idx++; + LOG(*idx); + strncpy(tVal->netmask, (*idx), INET6_ADDRSTRLEN); + }; + //if(strstr((*idx), "bridge_ports")!= NULL ) cMode = 6; + //if(strstr((*idx), "bridge_stp")!= NULL ) cMode = 7; + //if(strstr((*idx), "bridge_waitport")!= NULL ) cMode = 8; + //if(strstr((*idx), "bridge_fd")!= NULL ) cMode = 9; + }; + delete( CA ); + }; + }; + }; + }; + fclose( fd ); + }; +#ifdef DEBUG + if ( tVal ) { + if( tVal->enabled ) LOG("NIF Enabled"); else LOG("NIF Disabled"); + if (tVal->hot_plug) LOG("NIF Hot Plugable"); else LOG("NIF not Hot Plugable"); + if (tVal->if_static) LOG("Address is static"); else LOG("Address is Dynamic"); + if(strlen(tVal->address))LOG(tVal->address); + if(strlen(tVal->netmask))LOG(tVal->netmask); + }; +#endif + return tVal; +}; + +PARSE_RESULT_WIFI_SETTINGS *mojoHardwareManager::parse_wifi( CSTR if_name ){ + PARSE_RESULT_WIFI_SETTINGS *tVal = NULL; + FILE *fd; + bool cConfig = false; + + tVal = (PARSE_RESULT_WIFI_SETTINGS *) malloc( sizeof(PARSE_RESULT_WIFI_SETTINGS)); + if ( tVal ) { + memset(tVal, 0 , sizeof(PARSE_RESULT_WIFI_SETTINGS)); + fd = fopen("/etc/dnsmasq.conf","r"); + if ( fd ) { + char tB[1024]; + char expBuf[1024]; + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( '=', expBuf ); + if( CA ) { + if( CA->size() ){ + if( CA->at(0)[0] == '#' ) continue; + if( strstr(CA->at(0), "interface")!= NULL ) { + if( strstr( tB, if_name)!= NULL ) { + cConfig = true; + tVal->dhcp_enabled = true; + }; + }; + if( cConfig ){ + if ( strstr(CA->at(0), "dhcp-range")!= NULL ) { + char tT[1024]; + strncpy( tT, CA->at(1), 1024 ); + CArray *CB = explode(',', tT ); + if( CB ){ + if( CB->size() > 3 ){ + strncpy( tVal->range_start, CB->at(0), INET6_ADDRSTRLEN); + strncpy( tVal->range_stop, CB->at(1), INET6_ADDRSTRLEN); + strncpy( tVal->netmask, CB->at(2), INET6_ADDRSTRLEN); + strncpy( tVal->lease_period, CB->at(3), INET6_ADDRSTRLEN); + }; + delete( CB ); + }; + }; + }; + }; + delete( CA ); + }; + }; + }; + fclose( fd ); + }; + //Check WiFi + if( strstr(if_name,"w")!= NULL ) { + char tName[128]; + sprintf( tName, "iwconfig %s", if_name ); + fd = popen( tName, "r" ); + if ( fd ) { + char tB[1024]; + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd ); + trim( tB ); + if (strstr(tB, "Mode") != NULL) if (strstr(tB, "Master") != NULL) tVal->access_point = true; + }; + fclose( fd ); + }; + }; + if ( tVal->access_point ) { + fd = fopen("/etc/hostapd/hostapd.conf", "r"); + if ( fd ) { + char tB[1024]; + char expBuf[1024]; + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim( tB ); + if( strlen(tB) ) { + if( tB[0]=='#' ) continue; + strncpy(expBuf, tB, 1024); + CArray *CA = explode( '=', expBuf ); + if( CA ) { + if( CA->size() ){ + if (strstr(CA->at(0), "ssid") != NULL) if (strstr(CA->at(0), "ignore_broadcast_ssid") == NULL){ + strncpy( tVal->SSID, CA->at(1), 64 ); + } else tVal->hiden_ssid = (bool) atoi(CA->at(1)); + if (strstr(CA->at(0), "wpa_passphrase") != NULL) strncpy( tVal->password, CA->at(1), 64 ); + if (strstr(CA->at(0), "country_code") != NULL) strncpy(tVal->country_code, CA->at(1), 3); + if (strstr(CA->at(0), "channel") != NULL) tVal->channel = atoi(CA->at(1)); + }; + delete( CA ); + }; + }; + }; + fclose( fd ); + }; + } else { + fd = fopen("/etc/wpa_supplicant/wpa_supplicant.conf", "r"); + if ( fd ) { + + fclose( fd ); + }; + }; + fd = fopen("/etc/rc.local","r"); + if ( fd ) { + char tB[1024]; + char expBuf[1024]; + while (!feof(fd)) { + fgets((CSTR)tB, 1024, fd); + trim((CSTR)tB); + if( strlen(tB) ) { + strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ' ', expBuf ); + if( CA ) { + if ( CA->size() ) { + if (CA->at(0)[0] == '#') continue; + if( strstr(CA->at(0), "iptables-restore")!= NULL ) { + char zB[1024]; + FILE *afd = fopen( CA->at(2), "r" ); + if ( afd ) { + while( !feof( afd ) ){ + fgets((CSTR)zB, 1024, afd ); + if( strstr( zB, "POSTROUTING" )!= NULL ) if( strstr( zB, "MASQUERADE" )!= NULL ) if( strstr( zB, if_name )== NULL ){ + CArray *CB = explode( ' ', zB ); + if ( CB ) { + if ( CB->size() > 3 ) { + strncpy(tVal->router_outbond, CB->at(3), INET6_ADDRSTRLEN); + }; + delete( CB ); + }; + tVal->router_enabled = true; + }; + }; + fclose(afd); + } else LOG("Error Opening Firewall Rules!"); + }; + }; + delete( CA ); + }; + }; + }; + fclose(fd); + } else LOG_ERROR("Can not open rc.local!"); + }; +#ifdef DEBUG + if ( tVal ) { + if (tVal->access_point) LOG("AP Mode"); else LOG("WiFi Mode"); + LOG(tVal->SSID); + if (tVal->hiden_ssid) LOG("SSID is hidden"); + LOG(tVal->password); + if (tVal->dhcp_enabled){ + LOG("DHCP Service"); + LOG(tVal->range_start); + LOG(tVal->range_stop); + LOG(tVal->lease_period); + } else LOG("DHCP Disabled"); + if (tVal->router_enabled){ + LOG("Routing Enabled"); + LOG( tVal->router_outbond ); + } else LOG("Routing Disabled"); + }; +#endif + return tVal; +}; + +void mojoHardwareManager::enumerateNIFS( void ){ + struct ifaddrs * ifaddr = NULL; + char tBuffer[128]; + + //if( m_pKernel == NULL ) return; + if( m_pDBC == NULL ) return; + + if( -1 == getifaddrs(&ifaddr)) { + LOG_ERROR("No NET INTERFACES?!"); + } else { +#ifdef DEBUG + LOG("Enumerating Network Interfaces"); +#endif + struct ifaddrs * ifa; + + for( ifa = ifaddr; ifa; ifa = ifa->ifa_next ){ + char addr[INET6_ADDRSTRLEN]; + char mask[INET6_ADDRSTRLEN]; + char gw[INET6_ADDRSTRLEN]; + char bc[INET6_ADDRSTRLEN]; + char mac[INET6_ADDRSTRLEN]; + char device[INET6_ADDRSTRLEN]; + + uint32_t nif_id = 0; + uint32_t nif_aux_id = 0; + uint32_t router_id = 0; + ARGUS_NIF_TYPE nif_type = NIF_LOOPBACK; + ARGUS_NETWORK_TYPE net_type = NETWORK_IPV4; + ARGUS_RESOURCE_TYPE res_type = ARGUS_HARDWARE_NIF_LOOPBACK; + ARGUS_NIF_MODE nif_mode = ADDRESS_DISABLED; +#ifdef DEBUG_EXTRA + LOG("NIF ***"); +#endif + strncpy( device, ifa->ifa_name, INET6_ADDRSTRLEN ); + strncpy( mac,"--no-mac--", INET6_ADDRSTRLEN ); + // Filter Loopback if + if( strstr( device, "lo" ) != NULL ){ + nif_type = NIF_LOOPBACK; + res_type = ARGUS_HARDWARE_NIF_LOOPBACK; + //Not Implemented + continue; + }; + // Filter vpn TUN if + if( strstr( device, "tun" ) != NULL ){ + nif_type = NIF_VPN_TUNEL; + res_type = ARGUS_HARDWARE_NIF_TUNEL; + //Not Implemented Yet + continue; + }; + if( strstr( device, "eth" ) != NULL ){ + LOG(device); + nif_type = NIF_ETHERNET; + res_type = ARGUS_HARDWARE_NIF_ETHERNET; + }; + if( strstr( device, "wlan" ) != NULL ){ + LOG(device); + nif_type = NIF_WIFI; + res_type = ARGUS_HARDWARE_NIF_WIFI; + }; + if( strstr( device, "wwan" ) != NULL ){ + LOG(device); + nif_type = NIF_WAN; + res_type = ARGUS_HARDWARE_NIF_WAN; + }; + if( ifa->ifa_addr != NULL ){ + if (ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6) { + LOG("CONT"); + continue; + } + } else { + LOG("ifa->ifa_addr is NULL"); + continue; + }; + LOG("GETMAC"); + getMAC( device, mac ); + getGW( device, gw ); + LOG( mac ); + LOG( gw ); + PARSE_RESULT_NET_INTERFACES * tt = NULL; + PARSE_RESULT_WIFI_SETTINGS * tw = NULL; + tt = parse_neconfig( device ); + tw = parse_wifi( device ); + if( tt ) { + if ( tt->enabled ) { + if( tt->if_static ){ + nif_mode = ADDRESS_STATIC; + } else { + nif_mode = ADDRESS_DYNAMIC; + }; + } else { + nif_mode = ADDRESS_DISABLED; + }; + } else { + LOG_ERROR("Error Parsing System NIF Settings!"); + continue; + }; + if ( tw ){ + if( nif_mode == ADDRESS_STATIC ) { + if (tw->dhcp_enabled) { + nif_mode = ADDRESS_STATIC_RAP; + }; + }; + if ( nif_type == NIF_WIFI ){ + nif_id = m_pDBC->addLocalNIF( device, mac, nif_type, nif_mode ); + if( nif_id == 0 ) continue; + ARGUS_WIFI_MODE w_mode; + if( !tt->enabled ) { + w_mode = WIFI_DISABLED; + } else { + if (tt->if_static) { + if( tw->access_point ) { + w_mode = WIFI_IS_AP; + uint32_t outbond_id = 0; + if( tw->router_enabled ){ + outbond_id = m_pDBC->getNIF_IDbyDevice( tw->router_outbond ); + }; + if( tw->dhcp_enabled ) { + router_id = m_pDBC->addLocalNetworkInfrastructure(nif_id, outbond_id, true, tw->range_start, tw->range_stop, tw->netmask, tw->lease_period ); + } else { + router_id = m_pDBC->addLocalNetworkInfrastructure(nif_id, outbond_id ); + }; + } else { + w_mode = WIFI_CONNECTED_TO_AP; + }; + }; + }; + nif_aux_id = m_pDBC->addLocalWiFi(nif_id, w_mode, tw->SSID, tw->password, ENCRIPTION_WPA_PSK, router_id ); + }; + if( nif_type == NIF_ETHERNET || nif_type == NIF_ETHERNET_VIRTUAL ){ + + }; + free(tt); + free(tw); + } else { + LOG_ERROR("Error Parsing System Router/AP Settings!"); + free(tt); + continue; + }; + nif_id = m_pDBC->addLocalNIF( device, mac, nif_type, nif_mode, nif_aux_id ); + if( nif_id == 0 ) continue; + + LOG("NIF added!"); + m_pDBC->addResource( 1, res_type, device, nif_id ); + if(ifa->ifa_addr->sa_family == AF_INET){ + net_type = NETWORK_IPV4; + // create IPv4 string + struct sockaddr_in *in = (struct sockaddr_in*) ifa->ifa_addr; + inet_ntop(AF_INET, &in->sin_addr, addr, sizeof(addr)); + sprintf( mask, "%d.%d.%d.%d", + (uint8_t)ifa->ifa_netmask->sa_data[2], + (uint8_t)ifa->ifa_netmask->sa_data[3], + (uint8_t)ifa->ifa_netmask->sa_data[4], + (uint8_t)ifa->ifa_netmask->sa_data[5] + ); + sprintf( bc, "%d.%d.%d.%d", + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[4], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5] + ); + } else { // AF_INET6 + net_type = NETWORK_IPV6; + // create IPv6 string + struct sockaddr_in6 *in6 = (struct sockaddr_in6*) ifa->ifa_addr; + inet_ntop(AF_INET6, &in6->sin6_addr, addr, sizeof(addr)); + sprintf( mask, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", + (uint8_t)ifa->ifa_netmask->sa_data[2], + (uint8_t)ifa->ifa_netmask->sa_data[3], + (uint8_t)ifa->ifa_netmask->sa_data[4], + (uint8_t)ifa->ifa_netmask->sa_data[5], + (uint8_t)ifa->ifa_netmask->sa_data[6], + (uint8_t)ifa->ifa_netmask->sa_data[7], + (uint8_t)ifa->ifa_netmask->sa_data[8], + (uint8_t)ifa->ifa_netmask->sa_data[9], + (uint8_t)ifa->ifa_netmask->sa_data[10], + (uint8_t)ifa->ifa_netmask->sa_data[11], + (uint8_t)ifa->ifa_netmask->sa_data[12], + (uint8_t)ifa->ifa_netmask->sa_data[13], + (uint8_t)ifa->ifa_netmask->sa_data[14], + (uint8_t)ifa->ifa_netmask->sa_data[15], + (uint8_t)ifa->ifa_netmask->sa_data[16], + (uint8_t)ifa->ifa_netmask->sa_data[17] + ); + if( ifa->ifa_ifu.ifu_broadaddr != NULL ){ + sprintf( bc, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[4], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[6], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[7], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[8], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[9], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[10], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[11], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[12], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[13], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[14], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[15], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[16], + (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[17] + ); + } else { + sprintf( bc, "" ); + }; + }; + m_pDBC->addLocalNetwork( nif_id, net_type, addr, mask, gw, bc ); +#ifdef DEBUG + sprintf( tBuffer, "Detected Network Interface: %s [%s]", ifa->ifa_name, addr ); + LOG(tBuffer); +#endif + }; + freeifaddrs( ifaddr ); + }; +}; + +void mojoHardwareManager::enumerateHardware( void ){ + char tBuffer[CTEXT]; + DIR * dFD = NULL; + struct dirent * pDR = NULL; + + //ToDo: Check Ability to work without Kernel and DBC + //if( m_pKernel == NULL ) return; + if( m_pDBC == NULL ) return; +#ifdef DEBUG + LOG("HW Enumeration Started!"); +#endif + // Moved to a constructor!! + //m_nServerNodeID = m_pKernel->getServerNodeId(); + //m_nServerID = m_pKernel->getServerId(); + //m_nSiteID = m_pKernel->getSiteId(); + /* Add Network Interfaces */ + + m_pDBC->cleanResources( 1, true ); + + enumerateNIFS(); + /* Check HID Devices */ + + struct hid_device_info * pDevs; + uint8_t DCBCount; + //Enumerate USB devices with the given IDs + pDevs = hid_enumerate( 0x16c0, 0x05df ); + if( pDevs!=NULL ){ + struct hid_device_info * pCDev = pDevs; + //Count the number of returned devices + for( DCBCount = 0; pCDev!=NULL; DCBCount++ ) pCDev = pCDev->next; + //Allocate a buffer for the relays + if( DCBCount > 0 ){ + DC_BOARD tDCB; + //Fill the relay structs + pCDev = pDevs; + for( int idx = 0; idx < DCBCount; idx++ ){ + //Save the path to this device + memset( tDCB.path, 0, MAX_PATH_LEN ); + strncpy( tDCB.path, pCDev->path, MAX_PATH_LEN ); + // The product string is USBRelayx where x is number of relays read to the \0 in case there are more than 9 + tDCB.relay_count = atoi((const char *)&pCDev->product_string[8]); + //Open it to get more details + hid_device * handle; + handle = hid_open_path( tDCB.path ); + if( handle ){ + unsigned char buf[9]; + //Get the features of the device + buf[0] = 0x01; + if( hid_get_feature_report( handle, buf, sizeof(buf)) == -1 ){ + LOG_ERROR("hid_get_feature_report"); + pCDev = pCDev->next; + hid_close( handle ); + continue; + }; + //Set the serial number (0x0 for termination) + memset( tDCB.serial, 0x0, (HID_DCR_SERIIAL_LENGTH+1) ); + memcpy( tDCB.serial, buf, HID_DCR_SERIIAL_LENGTH ); + //Byte 7 in the response contains the target_state of the relays + tDCB.state = buf[7]; + hid_close( handle ); +#ifdef DEBUG + //Output the device enumeration details if verbose is on + LOG("HID DCB Found"); + sprintf(tBuffer, " Type: %04hx::%04hx", pCDev->vendor_id, pCDev->product_id); + LOG(tBuffer); + sprintf(tBuffer, " Path: %s", pCDev->path ); + LOG(tBuffer); + sprintf(tBuffer, " Serial_number: %ls", pCDev->serial_number ); + LOG(tBuffer); + sprintf(tBuffer, " Manufacturer: %ls", pCDev->manufacturer_string); + LOG(tBuffer); + sprintf(tBuffer, " Product: %ls", pCDev->product_string); + LOG(tBuffer); + sprintf(tBuffer, " Release: %hx", pCDev->release_number); + LOG(tBuffer); + sprintf(tBuffer, " Interface: %d", pCDev->interface_number); + LOG(tBuffer); + sprintf(tBuffer, " Number of Relays = %d", tDCB.relay_count); + LOG(tBuffer); + //If debug are on, output individual relay details + for( int k = 0; k < tDCB.relay_count; k++ ){ + if( tDCB.state & 1 << k ){ + sprintf(tBuffer, " %s_%d=1", tDCB.serial, k + 1); + } else { + sprintf(tBuffer, " %s_%d=0", tDCB.serial, k + 1); + }; + LOG(tBuffer); + }; +#endif + m_pDBC->addLocalDCB( 1, pCDev->path, tDCB.serial, tDCB.relay_count, tDCB.state ); + } else { + LOG_ERROR("unable to open HID device"); + }; + pCDev = pCDev->next; + }; + }; + hid_free_enumeration( pDevs ); + }; + + /* Add devices from DEV */ + dFD = opendir("/dev"); + if( dFD != NULL ) { + while( ( pDR = readdir( dFD ))!= NULL ){ + if( strcasestr( pDR->d_name, "video" ) == pDR->d_name ) { + createResourceVIDEO( pDR->d_name ); + continue; + }; + if( strcasestr( pDR->d_name, "ttyS" ) == pDR->d_name ){ + createResourceUART( pDR->d_name ); + continue; + }; + // RaspberyPI Hardware + if( strcasestr( pDR->d_name, "ttyAMA" ) == pDR->d_name ){ + createResourceUART( pDR->d_name ); + continue; + }; + if( strcasestr( pDR->d_name, "ttyUSB" ) == pDR->d_name ){ + createResourceUART( pDR->d_name ); + continue; + }; + }; + closedir( dFD ); + }; + //m_bHardwareEnumerated = true; +}; + +uint32_t mojoHardwareManager::createResourceUART( CSTR devName ){ + uint32_t RetVal = 0; + char tBuffer[256]; + /* Enumerate BuiltIn Serial */ +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "Serial Device: %s", devName ); + LOG( tBuffer ); +#endif + char dev_name[CTEXT]; + int fd = -1; + struct serial_struct ss; + sprintf( dev_name, "/dev/%s", devName ); + fd = open( dev_name, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK ); + if (-1 == fd) { + sprintf( tBuffer, "Cannot open '%s': %d, %s\\n", dev_name, errno, strerror(errno)); + LOG_ERROR( tBuffer ); + } else { + + if ( 0 && ( -1 == xioctl(fd, TIOCGSERIAL, &ss) )){ + LOG_ERROR("TIOCGSERIAL"); + } else { +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "Serial Port[Port:0x%X IRQ:%d BB:%d Line:%d Type:%d Flags:%X]", + ss.port, + ss.irq, + ss.baud_base, + ss.line, + ss.type, + ss.flags + ); + LOG( tBuffer ); +#endif + getTTyDesc( devName, tBuffer ); + uint32_t tID = m_pDBC->addLocalUART( 1, 1, 19200, 8, 'N', 1.0f, dev_name ); + if ( tID ) { + m_pDBC->addResource( 1, ARGUS_HARDWARE_UART, tBuffer, tID ); + }; + }; + close(fd); + }; + return RetVal; +}; + +uint32_t mojoHardwareManager::createResourceVIDEO( CSTR devName ){ + uint32_t RetVal = 0; + char tBuffer[256]; + /* Enumerate Video Capture */ +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "Video Source: %s", devName ); + LOG( tBuffer ); +#endif + struct v4l2_capability cap; + //struct v4l2_cropcap cropcap; + //struct v4l2_crop crop; + struct v4l2_format fmt; + char dev_name[CTEXT]; + int fd = -1; + struct stat st; + + sprintf( dev_name, "/dev/%s", devName ); + + if (-1 == stat( dev_name, &st )) { + sprintf( tBuffer, "Cannot identify '%s': %d, %s\\n", dev_name, errno, strerror(errno)); + LOG_ERROR( tBuffer ); + return 0; + }; + if (!S_ISCHR(st.st_mode)) { + sprintf( tBuffer, "%s is no devicen", dev_name); + LOG_ERROR( tBuffer ); + return 0; + }; + fd = open(dev_name, O_RDWR /* required */ | O_NONBLOCK, 0); + if (-1 == fd) { + sprintf( tBuffer, "Cannot open '%s': %d, %s\\n", dev_name, errno, strerror(errno)); + LOG_ERROR( tBuffer ); + } else { + if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) { + if (EINVAL == errno) { + sprintf( tBuffer, "%s is no V4L2 device", dev_name ); + LOG_ERROR( tBuffer ); + } else { + LOG_ERROR( "VIDIOC_QUERYCAP" ); + }; + close(fd); + return 0; + }; + if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) { +#ifdef DEBUG_EXTRA + sprintf(tBuffer, "%s is no video capture device", dev_name); + LOG_ERROR( tBuffer ); +#endif + close(fd); + return 0; + }; + CLEAR(fmt); + fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + /* Preserve original settings as set by v4l2-ctl for example */ + if (-1 == xioctl(fd, VIDIOC_G_FMT, &fmt)){ + //LOG_ERROR("VIDIOC_G_FMT"); + } else { +#ifdef DEBUG_EXTRA + sprintf( tBuffer, "Grabber[%dx%d]",fmt.fmt.pix.width,fmt.fmt.pix.height); + LOG( tBuffer ); +#endif + uint64_t mid = m_pDBC->addLocalMediaSource( 1, dev_name, fmt.fmt.pix.width, fmt.fmt.pix.height ); + //m_pDBC->addNodeSocket( m_nServerNodeID, mid, ARGUS_NODE_SOCK_TYPE_ANALOG_VIDEO_GRABBER, ARGUS_NODE_SOCK_MODE_OUT, false, dev_name, tBuffer ); + RetVal = m_pDBC->addResource( 1, ARGUS_HARDWARE_ANALOG_VIDEO_IN, dev_name, mid ); + }; + close(fd); + }; + return RetVal; +}; + +uint32_t mojoHardwareManager::createResourceUDCB( CSTR devName ){ + uint32_t RetVal = 0; + char tBuffer[256]; + return RetVal; +}; +/* +killWifi(){ + ifconfig wlan0 down + ifconfig wlan0 up + iw dev wlan0 station dump +} +*/ + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/mojo/mojoHardwareManager.h b/lib/App/mojo/mojoHardwareManager.h new file mode 100644 index 00000000..6174b8c5 --- /dev/null +++ b/lib/App/mojo/mojoHardwareManager.h @@ -0,0 +1,163 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2017. All Rights Reserved. +// Version 2.0 7/20/2017 +// Last modification: 7/20/2017 +// PROJECT: +// SUBSYSTEM: +// FILE: LRF_HardwareManager.h +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// Header file of LRF_HardwareManager.h +//---------------------------------------------------------------------------- +// + +#ifndef __MOJO_HARDWAREMANAGER_H_INCL__ +#define __MOJO_HARDWAREMANAGER_H_INCL__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../../components/base/basicLogCollection.h" +#include "../../components/base/basicSettingsProvider.h" +#include "../../components/base/basicEventHeap.h" +#include "../../alg/lgs/detectorStructures.h" +#include "../../alg/generic/heapDebug.h" +#include "../../rgoose/rgooseTypes.h" +#include "mojoDBConnector.h" + + +#define IGNORE_PRU_FLIP +#define IGNORE_PRU_SCAN + +#define AM355X_SIGN_ZONE (0x44E10000) +#define AM355X_SIGN_VAL (0x00000000) + +#define AM437X_SIGN_ZONE (0x44E10000) +#define AM437X_SIGN_VAL (0x4F000100) + +typedef enum{ + SOC_UNKNOWN = 0, + SOC_AM335X = 1, + SOC_AM437X = 2 +} E_SOC_TYPE; + +typedef enum eDataStatuses{ + BUFFER_UNDERRUN = -1, + BUFFER_EMPTY = 0, + BUFFER_OK = 1 +} E_DATA_STATUS; + + +#define HWM_SETTINGS_ROLE "MASTER_ROLE" +#define HWM_SETTINGS_TH_DUMP "DUMP_TH_ON_DISK" +#define HWM_SETTINGS_CTRL_V_MOTOR "VERTICAL_MOTOR_CTRL" +#define HWM_SETTINGS_CTRL_H_MOTOR "HORIZONTAL_MOTOR_CTRL" +#define HWM_SETTINGS_V_MOTOR_SETPOINT "VERTICAL_ENC_FREQ" +#define HWM_SETTINGS_H_MOTOR_SETPOINT "HORIZONTAL_ENC_FREQ" +#define HWM_SETTINGS_V_PULSES_INTERLEAVE "LRF_PULSES_INTERLEAVE" +#define HWM_SETTINGS_LRF_ENABLED "LRF_ENABLED" +#define HWM_SETTINGS_SYM_ENABLED "SIMULATION_ENABLED" +#define HWM_SETTINGS_SYM_FREQ "SIMULATION_FREQ" +#define HWM_SETTINGS_AUTOSTART_ENABLED "MOTORS_AUTOSTART" +#define HWM_SETTINGS_AUTO_TH_GENERATE "TH_GENERATED_BY_PRU" +#define HWM_SETTINGS_TH_OFFSET "TH_OFFSET" +#define HWM_SETTINGS_TH_ORDER "TH_ORDER" +#define HWM_SETTINGS_TH_DELTA "TH_DELTA" +#define HWM_SETTINGS_TH_FLIP_SIZE "TH_FLIP" +#define HWM_SETTINGS_TH_SPIKE_SIZE "TH_SPIKE_SIZE" +#define HWM_SETTINGS_TH_GOOD_POINTS "TH_GOOD_POINTS" +#define HWM_SETTINGS_SIG_SYMULATOR "SIG_SYM_ENABLE" +#define HWM_SETTINGS_CAN_CONTROL_ENABLE "CAN_BUS_ENABLE" +#define HWM_SETTINGS_CAN_BUS_ID "CAN_BUS_ID" +#define HWM_SETTINGS_CAN_MY_ID "CAN_MY_ID" +#define HWM_SETTINGS_CAN_TGZ_ID "CAN_TGZ_ID" +#define HWM_SETTINGS_LRF_PRF "LRF_PRF" +#define HWM_SETTINGS_Q_TO_B_BOUNCE "QB_BOUNCE" +#define HWM_SETTINGS_SUNBIT "SUNBIT_ENABLE" +#define HWM_SETTINGS_B_SHIFT "BASE_SHIFT" +#define HWM_SETTINGS_Q_SHIFT "MIRROR_SHIFT" +#define HWM_SETTINGS_DENCITY "SCAN_DENCITY" + +#define DBC_RESOURCE_DESC_SIZE 64 + + +typedef struct S_PARSE_RESULT_NET_INTERFACES{ + bool enabled; + bool if_static; + bool hot_plug; + char address[INET6_ADDRSTRLEN]; + char netmask[INET6_ADDRSTRLEN]; + char gateway[INET6_ADDRSTRLEN]; +}PARSE_RESULT_NET_INTERFACES; + +typedef struct S_PARSE_RESULT_WIFI_SETTINGS{ + char SSID[64]; + char password[64]; + ARGUS_WIFI_ENCRIPTION encryption; + bool access_point; + uint8_t channel; + char country_code[3]; + bool hiden_ssid; + /* Router Settings */ + bool router_enabled; + char router_outbond[INET6_ADDRSTRLEN]; + /* DHCP */ + bool dhcp_enabled; + char range_start[INET6_ADDRSTRLEN]; + char range_stop[INET6_ADDRSTRLEN]; + char netmask[INET6_ADDRSTRLEN]; + char lease_period[INET6_ADDRSTRLEN]; +}PARSE_RESULT_WIFI_SETTINGS; + + +/** + * Class to talk with Hardware via MemMap + * + * @author gagua + */ +class mojoHardwareManager { + private: + /* General System Variables*/ + + basicLogCollection * m_pLog; + config_setting_t * m_pSettings; + basicSettingsProvider * m_pSettingsProvider; + uint32_t m_nMemoryLimitHeapSize; + mojoDBC * m_pDBC; + bool m_bInitOK; + + uint32_t createResourceUART( CSTR devName ); + uint32_t createResourceVIDEO( CSTR devName ); + uint32_t createResourceUDCB( CSTR devName ); + uint32_t createResourceNETWORK( CSTR devName ); + void enumerateNIFS( void ); + void getMAC( CSTR if_name, CSTR buf ); + void getGW( CSTR if_name, CSTR buf ); + void getTTyDesc( CSTR dev_name, CSTR buf ); + /* Linux System Parsers */ + PARSE_RESULT_NET_INTERFACES * parse_neconfig( CSTR if_name ); + PARSE_RESULT_WIFI_SETTINGS * parse_wifi( CSTR if_name ); + protected: + static mojoHardwareManager * _instance; + // Constructor + explicit mojoHardwareManager( config_setting_t *SNode ); + public: + static mojoHardwareManager * getInstance( config_setting_t *SNode = NULL ); + // Destructor + virtual ~mojoHardwareManager(); + void enumerateHardware( void ); + bool validate(); +}; + +#endif // __LRF_HARDWAREMANAGER_H_INCL__ diff --git a/lib/App/mojo/mojoKernel.cpp b/lib/App/mojo/mojoKernel.cpp new file mode 100644 index 00000000..e2cde229 --- /dev/null +++ b/lib/App/mojo/mojoKernel.cpp @@ -0,0 +1,390 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2022. All Rights Reserved. +// Version 1.0 11/19/2022 +// Last modification: 11/19/2022 +// PROJECT: +// SUBSYSTEM: +// FILE: mojoKernel.cpp +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// LRF_Kernel.cpp +//---------------------------------------------------------------------------- +// + +#include "mojoKernel.h" +#include "../data/json/json_tool.h" +#include +#include +#include +#include + +#include "../common/kernelEventFilterAPF.h" + + +#define LOG( X ) kernelPrototype::m_pLog->Log( "KRNL", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG234[256];\ + sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + kernelPrototype::m_pLog->Log( "KRNL", this, _LOG_ERROR, _tBfrErrMSG234 );\ + } +#else + #define LOG_ERROR( X ) kernelPrototype::m_pLog->Log( "KRNL", this, _LOG_ERROR, X ); +#endif + +mojoKernel *mojoKernel::_instance = NULL; + +mojoKernel *mojoKernel::getInstance( config_setting_t *ptr ){ + if ( _instance == NULL ) { + _instance = new mojoKernel( ptr ); + }; + return _instance; +}; + +mojoKernel::mojoKernel( config_setting_t *ptr ):kernelPrototype( ptr ){ + m_pEventHeap = basicEventHeap::getInstance(); + memset( &m_sSysInfo, 0, sizeof( DBC_SYS_LOAD_INFO )); + m_pShadow = NULL; + m_pSystemAnchor = NULL; + setWM( WM_NONE ); +}; + + +mojoKernel::~mojoKernel(){ + WaitFinish( true ); +#ifdef DEBUG + LOG(" Deleting Node Factory..."); +#endif + //if( m_pNodeFactory != NULL ) delete( m_pNodeFactory ); +#ifdef DEBUG + LOG(" Deleting Module Factory..."); +#endif + if( m_pModuleFactory != NULL ) delete( m_pModuleFactory ); +#ifdef DEBUG + LOG(" Deleting Target Filters..."); +#endif + unloadFilters(); + + if( EXIT_CODE_KERNEL_CLEAR == getExitCause() ) { +#ifdef DEBUG + LOG("Unregister Server"); +#endif + m_pDBC->unregisterServer(); +#ifdef DEBUG + //LOG("Close DataBase Connection..."); +#endif + //if( m_pDBC != NULL ) delete( m_pDBC );//Deleting in Backend + //m_pDBC = NULL; + } else { + if( EXIT_CODE_DETECT_HARDWARE == getExitCause() ) { +#ifdef DEBUG + LOG("HW PNP Detection Requested..."); +#endif + //m_pDBC->updateNodePushedCMD( tCMD->id, 30 ); + m_pHardwareManager->enumerateHardware(); + //m_pDBC->updateNodePushedCMD( tCMD->id, 60 ); + }; +#ifdef DEBUG + //LOG("Close DataBase Connection..."); +#endif + //if( m_pDBC != NULL ) delete( m_pDBC ); + //m_pDBC = NULL; + }; + delete( m_pHardwareManager ); + _instance = NULL; +}; + +bool mojoKernel::create(){ + if( m_pSettings != NULL ) { + config_setting_t * pSetting; + int tVal; + const char * tBuf; + char tBuffer[128]; + LOG("Getting Settings ..."); + if( !config_setting_lookup_string( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, &tBuf ) ){ + char * tVar; + char * tTS; + tTS = getTStr(NULL); + tVar = MD5String(tTS); + free(tTS); + sprintf( m_sIdentity, tVar ); + pSetting = config_setting_add( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, CONFIG_TYPE_STRING ); + config_setting_set_string( pSetting, tVar ); + free( tVar ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Server Identity not defined - generating new!"); + } else { + sprintf( m_sIdentity, tBuf ); + sprintf( tBuffer, "Server Identity Read From Settings: %s", tBuf ); + LOG( tBuffer ); + }; + if( !config_setting_lookup_int( m_pSettings, MOJO_KERNEL_TAG_SITE_ID, &tVal ) ){ + tVal = m_nInstanceID = 1; + pSetting = config_setting_add( m_pSettings, MOJO_KERNEL_TAG_SITE_ID, CONFIG_TYPE_INT ); + config_setting_set_int( pSetting, tVal ); + basicSettingsProvider::getInstance()->compromise(); + LOG("Site ID not defined - using [1] as number!"); + } else { + m_nInstanceID = tVal; + sprintf( tBuffer, "App Instance ID Read From Settings: %d", m_nInstanceID ); + LOG( tBuffer ); + }; + } else { + LOG_ERROR("Failed Read Config Settings!"); + return false; + }; + basicSettingsProvider::getInstance()->validate(); + + LOG("Register Server ... "); + m_pDBC->registerServer( m_nInstanceID, m_sIdentity, getpid(), &m_nServerID, &m_nServerNodeID ); + char tBuffer[128]; + sprintf( tBuffer,"Server Registered as [%d] nodeID[%d]",m_nServerID, m_nServerNodeID ); + LOG( tBuffer ); + + DBC_SITE_DATA *tSiteData = m_pDBC->getSiteData( m_nInstanceID ); + + if( tSiteData ) { + C3D_WGS84_LOC t; + t.lat = tSiteData->lat; + t.lon = tSiteData->lon; + t.alt = tSiteData->alt; + m_pSystemAnchor = systemAnchor::getInstance( tSiteData->SH, &t, tSiteData->local_binding ); + free( tSiteData ); + } else { + LOG_ERROR("Error Loading Site DATA!"); + C3D_WGS84_LOC t; + t.lat = 0; + t.lon = 0; + t.alt = 0; + m_pSystemAnchor = systemAnchor::getInstance( false, &t, true ); + }; + + m_pHardwareManager = hardwareManager::getInstance(); + + loadFilters(); + + m_pModuleFactory = kernelModuleFactory::getInstance( m_nInstanceID ); + if( !m_pModuleFactory ) { + LOG_ERROR("Module Factory Failure!"); + return false; + }; + //Autoloading Modules + //if( !m_pModuleFactory->loadModules() ){ + // LOG_ERROR("Modules Loading Failure!"); + // return false; + //}; + m_pNodeFactory = deviceNodeFactory::getInstance(); + if( !m_pNodeFactory ){ + LOG_ERROR("Node Factory Failure!"); + return false; + }; + return init(); +}; + +void mojoKernel::m_fThreadProc( void ){ + time_t tTimeTSeconds = 0; + m_bThreadStatus = TH_WORKING; + while ( m_bThreadStatus < TH_ENDED ) { + m_tTimeTSeconds = time( NULL ); + //Each Second + if( m_tTimeTSeconds != tTimeTSeconds ){ + tTimeTSeconds = m_tTimeTSeconds; + + m_pHardwareManager->updateSysInfo( &m_sSysInfo ); + + DBC_PUSHED_CMD * tCMD = m_pDBC->getNodePushedCMD( m_nServerNodeID ); //Kernel + if( tCMD != NULL ) { + m_pDBC->updateNodePushedCMD( tCMD->id, DBC_CMD_STARTED ); + switch( tCMD->CMD ){ + case CMD_KRNL_RELOAD:{ + LOG("Reload Mojo Node!"); + m_bThreadStatus = TH_ENDED; + setExitCause( EXIT_CODE_RELOAD_SERVICES ); + break; + }; + case CMD_KRNL_RESTART:{ + LOG("Restart Mojo Node!"); + m_bThreadStatus = TH_ENDED; + setExitCause( EXIT_CODE_KERNEL_CLEAR ); + break; + }; + case CMD_KRNL_FACTORY_RESET:{ + LOG("Restart Mojo -> Factory Reset!"); + m_bThreadStatus = TH_ENDED; + setExitCause( EXIT_CODE_FACTORY_RESET ); + break; + }; + case CMD_NODES_RELOAD:{ + //if( m_pNodeFactory != NULL ) { + // m_pNodeFactory->reloadNodes( m_nSiteID ); + //}; + break; + }; + case CMD_NODE_RELOAD:{ + uint32_t tNodeID = atoi( tCMD->PARAM ); + //if( m_pNodeFactory != NULL ) { + // m_pNodeFactory->reloadNode( tNodeID ); + //}; + break; + }; + case CMD_KRNL_PNP:{ + if( m_pHardwareManager!= NULL ) { + LOG_ERROR( "Restart and Detect HardWare!" ); + // Must be shutdowned all service that uses hardware prior to detection! + // m_pHardwareManager->enumerateHardware(); + m_bThreadStatus = TH_ENDED; + setExitCause( EXIT_CODE_DETECT_HARDWARE ); // Go -> Detect Hardware in BACKEND + }; + break; + }; + case CMD_KRNL_SYNC_TIME:{ + uint32_t uts = atoi( tCMD->PARAM ); + if( uts ){ + time_t ts = (time_t)uts; + if( stime( &ts ) == 0 ){ + // Restert Server; + m_bThreadStatus = TH_ENDED; + setExitCause( EXIT_CODE_KERNEL_CLEAR ); + }; + }; + break; + }; + case CMD_KRNL_SYSTEM_TASK:{ + /* + try{ + Json::Value root; + JSONCPP_STRING err; + Json::CharReaderBuilder builder; + + int len = strlen( tCMD->PARAM ); + + if ( len ) { + const std::unique_ptr reader(builder.newCharReader()); + if (!reader->parse( tCMD->PARAM, tCMD->PARAM + len, &root, &err)) { + LOG_ERROR( "Error parsing the string" ); + LOG_ERROR( err.c_str() ); + } else { + if (root.size()) { + Json::Value tVal; + + tVal = root["action"]; + if (!tVal.isNull()) { + LOG( tVal.asString().c_str() ); + //SYS_COMMAND_ENUMERATOR tENUM = SYS_CMD_NONE; + CSTR pTemp = NULL; + SYS_COMMAND_ENUMERATOR eType = SYS_CMD_NONE; + for( int i = 0; i < 4; i++ ){ + pTemp = (CSTR) strstr( tVal.asString().c_str(), SYS_COMANDS_SCRIPTS[i] ); + if( pTemp ){ + eType = (SYS_COMMAND_ENUMERATOR)i; + break; + }; + }; + if( eType != SYS_CMD_NONE ){ + switch( eType ){ + case SYS_CMD_REBOOT: { + int rv = system("./scripts/linux/reboot_system.sh"); + if( rv == -1 ) { + LOG_ERROR("Error issuing System Command!"); + } else { + m_bThreadStatus = TH_ENDED; + m_bExitCause = 0; + }; + break; + }; + case SYS_CMD_SET_STATIC:{ + tVal = root["nif_id"]; + if (!tVal.isNull()) { + LOG( tVal.asString().c_str() ); + }; + break; + }; + }; + }; + }; + }; + }; + }; + } catch (exception e) { + m_pDBC->updateNodePushedCMD( tCMD->id, DBC_CMD_FINISHED_ERROR ); + LOG_ERROR("EXCEPTION"); + }; + */ + break; + }; + }; + free( tCMD ); + }; + m_pDBC->cleanNodePushedCMD(); + + }; + SLEEP(SLEEP_KERNEL_INTERVAL); + }; +}; + +void mojoKernel::loadFilters(){ + if( m_pDBC == NULL ) return; + DBC_INT_LIST *tList = m_pDBC->listFilters( m_nServerID ); + if( tList != NULL ) { + if( tList->size() > 0 ) { + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ) { + DBC_TARGET_FLITER_DATA *tData = NULL; + tData = m_pDBC->getTargetFilterData( (*idx) ); + if( tData != NULL ) { + switch( tData->type ) { + case TF_AUTHORISED_PEOPLE_FILTER: { + kernelEventFilterAPF *tFilter = new kernelEventFilterAPF( tData->aux_id ); + if( tFilter != NULL ) { + if( tFilter->initFilter() ){ + m_vTargetFilters.push_back( (kernelEventFilter*) tFilter ); + } else { + delete( tFilter ); + }; + }; + break; + }; + }; + free( tData ); + }; + }; + tList->clear(); + }; + delete( tList ); +#ifdef DEBUG + } else { + LOG("No Target Filters Assigned!"); +#endif + }; +}; + +void mojoKernel::unloadFilters(){ + if( m_vTargetFilters.size() > 0 ) { +#ifdef DEBUG + LOG("Have Filters to Unload"); +#endif + for( vectorKernelEventFilters::iterator idx = m_vTargetFilters.begin(); idx < m_vTargetFilters.end(); idx++ ){ + switch( (*idx)->getType() ) { + case TF_AUTHORISED_PEOPLE_FILTER:{ + delete( (kernelEventFilterAPF*)(*idx) ); + break; + }; + default:{ + char tBuffer[64]; + sprintf( tBuffer, "Unknown Filter: %d", (*idx)->getType() ); + LOG( tBuffer ); + }; + }; + }; + m_vTargetFilters.clear(); + LOG("Unload Filters Done!"); +#ifdef DEBUG + } else { + LOG("No Filters to Unload!"); +#endif + }; +}; + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/mojo/mojoKernel.h b/lib/App/mojo/mojoKernel.h new file mode 100644 index 00000000..643b0a67 --- /dev/null +++ b/lib/App/mojo/mojoKernel.h @@ -0,0 +1,81 @@ +//---------------------------------------------------------------------------- +// Dr.Frucht Systems Ltd. +// Copyright © 2000-2022. All Rights Reserved. +// Version 1.0 11/19/2022 +// Last modification: 11/19/2022 +// PROJECT: +// SUBSYSTEM: +// FILE: mojoKernel.h +// AUTHOR: gagua +// OVERVIEW +// ~~~~~~~~ +// Header file of mojoKernel.cpp +//---------------------------------------------------------------------------- +// + +#ifndef __MOJO_KERNEL_H_INCL__ +#define __MOJO_KERNEL_H_INCL__ + +#define LA_METRO 1 + +#include "../../components/base/basicThread.h" +#include "../../components/base/basicSettingsProvider.h" +#include "../../components/base/basicEventHeap.h" +#include "../../components/object/objectSystemAnchor.h" +#include "../../alg/lgs/detectorStructures.h" +#include "../../alg/lgs/detector.h" +#include "../../alg/lgs/mask.h" +#include "../../alg/generic/md5.h" + +#include "../common/kernelPrototype.h" + +#define MAX_CYCLE_COUNTER_VALUE 0xFFFFFFFF; +#define SLEEP_KERNEL_INTERVAL 10 // 10 millisecond +#define TIME_SYNC_INTERVAL 900000 // 15 minute(s) in 1 millisecond units +#define STATUS_OK_INTERVAL 2000 // 2 Sec in 1 millisecond units + + +#define KNL_SETTINGS_DETECTOR_WIDTH "DETECTOR_WIDTH" +#define KNL_SETTINGS_FILTER_KERNELS "ENABLED_LRF" +#define KNL_SETTINGS_DETECTOR_SST "DETECTOR_SST" +//#define KNL_SETTINGS_V_MOTOR_SETPOINT "VERTICAL_ENC_FREQ" + +#define MOJO_KERNEL_TAG_SITE_ID "SITE_ID" +#define MOJO_KERNEL_TAG_SERVER_IDENTITY "IDENTITY" +/** + * LRF_Kernel class - manages communication between client + * handlers and PRU cores bseide of Event management. + * + * + * @author gagua + */ +class mojoKernel: public kernelPrototype{ + private: + basicEventHeap * m_pEventHeap; + ShadowMask * m_pShadow; + time_t m_tTimeTSeconds; + DBC_SYS_LOAD_INFO m_sSysInfo; + char m_sIdentity[128]; + uint32_t m_nInstanceID; + uint32_t m_nServerID; + uint32_t m_nServerNodeID; + systemAnchor * m_pSystemAnchor; + +#ifdef LA_METRO + +#endif + void loadFilters(); + void unloadFilters(); + static mojoKernel * _instance; + protected: + virtual void m_fThreadProc( void ); + // Constructor + explicit mojoKernel( config_setting_t *ptr ); + public: + static mojoKernel * getInstance( config_setting_t *ptr = NULL ); + // Destructor + virtual ~mojoKernel(); + virtual bool create(); +}; + +#endif // __MOJJO_KERNEL_H_INCL__ diff --git a/lib/App/mojo/rgooseModule.cpp b/lib/App/mojo/rgooseModule.cpp new file mode 100644 index 00000000..adf11ca8 --- /dev/null +++ b/lib/App/mojo/rgooseModule.cpp @@ -0,0 +1,28 @@ +#include "rgooseModule.h" + +argusKernelModule::argusKernelModule( uint32_t id, ARGUS_MODULE_TYPE param ): basicEventHandler(), basicObject(){ + m_pLog = basicLogCollection::getInstance(); + m_pDBC = mojoDBC::getInstance(); + m_pKernel = mojoKernel::getInstance(); + m_eType = param; + m_nDBID = id; + m_bDetached = false; + m_bEnabled = false; + m_nDBAUXID = 0; + + // Clear Events flags + if( m_pDBC ) { + DBC_MODULE_DATA *tData = NULL; + tData = m_pDBC->getModuleData( m_nDBID ); + if( tData ) { + m_nDBAUXID = tData->aux_id; + m_bEnabled = tData->enabled; + free( tData ); + }; + }; + for( int i = 0; i < EVT_COUNT; i++ ) m_bEvtFlags[i] = false; +}; + +argusKernelModule::~argusKernelModule(){ +}; + diff --git a/lib/App/mojo/rgooseModule.h b/lib/App/mojo/rgooseModule.h new file mode 100644 index 00000000..fb3d6d34 --- /dev/null +++ b/lib/App/mojo/rgooseModule.h @@ -0,0 +1,57 @@ +#ifndef __ARGUS_MODULE_HEADER__ +#define __ARGUS_MODULE_HEADER__ + +#include "../components/base/basicObject.h" +#include "../components/base/basicEventHandler.h" +#include "../components/base/basicLogCollection.h" +#include "mojoKernel.h" +#include "mojoDBConnector.h" + + +typedef enum E_ARGUS_MODULE_TYPE{ + ARGUS_MODULE_UNKNOWN = 0, + ARGUS_MODULE_DCBUSB = 1, + ARGUS_MODULE_KAFKA = 2, + ARGUS_MODULE_GPS = 3, + ARGUS_MODULE_NETWORK = 4, + ARGUS_MODULE_FLYHUNTER = 5, + ARGUS_MODULE_SSDP_ANONCE = 6, + ARGUS_MODULE_ONVIF_OBSERVER = 7, + ARGUS_MODULE_EMBED_VIDEO = 8, + ARGUS_MODULE_MODEM_MANAGER = 9 +}ARGUS_MODULE_TYPE; + +class argusKernel; + +class argusKernelModule: public basicEventHandler, basicObject{ + protected: + basicLogCollection * m_pLog; + mojoDBC * m_pDBC; + uint32_t m_nDBID; + uint32_t m_nDBAUXID; + mojoKernel * m_pKernel; + bool m_bEnabled; + bool m_bDetached; + bool m_bEvtFlags[EVT_COUNT]; + public: + ARGUS_MODULE_TYPE m_eType; + explicit argusKernelModule( uint32_t id, ARGUS_MODULE_TYPE param = ARGUS_MODULE_UNKNOWN ); + virtual ~argusKernelModule(); + uint32_t getId() const { return m_nDBID; }; + uint32_t getAuxId() const { return m_nDBAUXID; }; + ARGUS_MODULE_TYPE getType() const { return m_eType; }; + bool isDetached() const { return m_bDetached; }; + bool isAttached() const { return !m_bDetached; }; + bool isEnabled() const { return m_bEnabled;}; + virtual bool reloadSettings(){ return false; }; + void setAttached( bool b=true ){ m_bDetached = !b; }; + void setDetached( bool b=true ){ m_bDetached = b; }; + virtual bool startService(){ return false; }; + virtual bool stopService( bool force = false ){ return true; }; + virtual bool validate(){ return false; }; + virtual void dispatchEvent( EVENT_CONTAINER *Evt ){}; +}; + + +#endif + diff --git a/lib/App/mojo/rgooseModuleEmbedVideo - Copy.cpp b/lib/App/mojo/rgooseModuleEmbedVideo - Copy.cpp new file mode 100644 index 00000000..c14f240e --- /dev/null +++ b/lib/App/mojo/rgooseModuleEmbedVideo - Copy.cpp @@ -0,0 +1,1464 @@ +#include "rgooseModuleEmbedVideo.h" +#include "rgooseHardwareResourceNetworkProvider.h" +#include "../alg/generic/base64.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* MIN() */ +#include +#include + + +#define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, X ); +#endif + +#define TLOG( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, X ) +#define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, X ) + +enum { + WEBRTC_REQ_SIGNIN = 0, + WEBRTC_REQ_WAIT = 1, + WEBRTC_REQ_SIGNOUT = 2, + WEBRTC_REQ_MESSAGE = 3 +}; + +static const char* kRequestPaths[] = { "/sign_in", "/wait", "/sign_out", "/message" }; + +//buffer_data bd[1]={0}; + +argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_EMBED_VIDEO ), basicMediaDestination(), basicThread(){ + m_pEventHeap = basicEventHeap::getInstance(); +}; + +argusModuleEmbedVideo::~argusModuleEmbedVideo(){ + m_bEnabled = false; + stopService(); +}; + + +static int write_packet(void *opaque, uint8_t *buf, int buf_size) { + STREAM_CTX *CTX = (STREAM_CTX *)opaque; + buffer_data *bd = CTX->buffer; + TLOG("WRD"); + while( buf_size > bd->room ){ + int64_t offset = bd->ptr - bd->buf; + bd->buf = (uint8_t *) av_realloc_f( bd->buf, 2, bd->size ); + if (!bd->buf) + return AVERROR(ENOMEM); + bd->size *= 2; + bd->ptr = bd->buf + offset; + bd->room = bd->size - offset; + } + char tB[200]; + sprintf( tB, "write packet pkt_size:%d used_buf_size:%zu buf_size:%zu buf_room:%zu\n", buf_size, bd->ptr-bd->buf, bd->size, bd->room ); + TLOG( tB ); + memcpy(bd->ptr, buf, buf_size); + bd->ptr += buf_size; + bd->room -= buf_size; + + //free(buf); + return buf_size; +}; + +int argusModuleEmbedVideo::write_module_packet( void *opaque, uint8_t *buf, int buf_size ){ + STREAM_CTX *CTX = (STREAM_CTX *)opaque; + if( CTX->bHeaderIsReady ){ + uint32_t pSize = buf_size; + CTX->ModulePtr->m_mHandlersProtector.lock(); + for( vectorHANDLERS::iterator idx = CTX->ModulePtr->m_vHandlersPool.begin(); + idx < CTX->ModulePtr->m_vHandlersPool.end(); + idx++ ) + { + if( (*idx)->CTX->bValid ) { + if( (*idx)->CTX->STREAM->mediaStreamId == id ) { + write( (*idx)->CTX->m_iEncoderPipe[0], &pSize, sizeof(uint32_t)); + }; + }; + }; + CTX->ModulePtr->m_mHandlersProtector.unlock(); + } else { + CTX->header_size = buf_size; + CTX->header = (uint8_t*)av_malloc( buf_size ); + if( CTX->header== NULL ) return AVERROR(ENOMEM); + memcpy( CTX->header, buf, buf_size ); + CTX->bHeaderIsReady = true; + char tB[200]; + sprintf( tB, "write packet pkt_size:%d", buf_size ); + TLOG( tB ); + }; + return buf_size; +}; + +int argusModuleEmbedVideo::write_client_packet( void *opaque, uint8_t *buf, int buf_size ){ + STREAM_CTX *CTX = (STREAM_CTX *)opaque; + if( CTX->bHeaderIsReady ){ + + } else { + CTX->header_size = buf_size; + CTX->header = (uint8_t*)av_malloc( buf_size ); + if( CTX->header== NULL ) return AVERROR(ENOMEM); + memcpy( CTX->header, buf, buf_size ); + CTX->bHeaderIsReady = true; + char tB[200]; + sprintf( tB, "write packet pkt_size:%d", buf_size ); + TLOG( tB ); + }; + return buf_size; +}; + +void argusModuleEmbedVideo::encode_module_video( STREAM_CTX *CTX, AVFrame *DATA ){ + int ret; + if( DATA ) { + ret = avcodec_send_frame( CTX->video_ctx, DATA ); + } else { + ret = avcodec_send_frame( CTX->video_ctx, NULL ); + }; + if( ret < 0 ){ + TLOG_ERROR("Error sending a video frame for encoding"); + return; + }; + while( ret >= 0 ){ + AVPacket *pkt = NULL; + pkt = (AVPacket *) av_malloc( sizeof(AVPacket) ); + if( pkt ) { + av_init_packet( pkt ); + ret = avcodec_receive_packet( CTX->video_ctx, pkt ); + if( ret == AVERROR(EAGAIN) || ret == AVERROR_EOF ){ + av_packet_unref( pkt ); + av_free( pkt ); + return; + } else if( ret < 0 ){ + TLOG_ERROR("Error during video encoding"); + av_free( pkt ); + return; + }; + pkt->stream_index = CTX->video_stream->index; + av_packet_rescale_ts( pkt, CTX->video_ctx->time_base, CTX->video_stream->time_base ); + av_write_frame( CTX->ofmt_ctx, pkt ); + av_packet_unref( pkt ); + av_free( pkt ); + } + }; +}; + +void argusModuleEmbedVideo::encode_client_video( STREAM_CTX *CTX, AVPacket *pkt ){ + if( pkt ) { + pkt->stream_index = CTX->ts; + CTX->ts++; + av_packet_rescale_ts( pkt, CTX->video_ctx->time_base, CTX->video_stream->time_base ); + av_write_frame( CTX->ofmt_ctx, pkt ); + av_packet_unref( pkt ); + }; +}; + +#ifndef _NOAUDIO_ +void argusModuleEmbedVideo::encode_audio( STREAM_CTX *CTX, AVFrame *DATA ){ + int ret; + if( DATA ) { + ret = avcodec_send_frame( CTX->audio_ctx, CTX->audio_frame ); + } else { + ret = avcodec_send_frame( CTX->audio_ctx, NULL ); + }; + if( ret < 0 ){ + TLOG_ERROR("Error sending a audio frame for encoding"); + return; + }; + while( ret >= 0 ){ + ret = avcodec_receive_packet( CTX->audio_ctx, CTX->pkt ); + if( ret == AVERROR(EAGAIN) || ret == AVERROR_EOF ){ + av_packet_unref( CTX->pkt ); + return; + } else if( ret < 0 ){ + TLOG_ERROR("Error during audio encoding"); + return; + }; + CTX->pkt->stream_index = CTX->audio_stream->index; + av_packet_rescale_ts( CTX->pkt, CTX->audio_ctx->time_base, CTX->audio_stream->time_base); + av_write_frame( CTX->ofmt_ctx, CTX->pkt ); + av_packet_unref( CTX->pkt ); + }; +}; +#endif + +void argusModuleEmbedVideo::add_video_frame( STREAM_CTX *CTX ){ + if( CTX->InputMat ){ + if( CTX->video_sws_ctx ) { + int linesize[2] = {0}; + const uint8_t * dataPTR[2] = {0}; + + linesize[0] = CTX->InputMat->cols*3; + linesize[1] = 0; + + dataPTR[0] = (uint8_t *)CTX->InputMat->data; + dataPTR[1] = NULL; + + av_frame_make_writable( CTX->video_frame ); + + sws_scale( CTX->video_sws_ctx, + dataPTR, + linesize, + 0, + CTX->InputMat->rows, + CTX->video_frame->data, + CTX->video_frame->linesize + ); + CTX->video_frame->pts = CTX->ts; + CTX->ts++; + encode_module_video( CTX, CTX->video_frame ); + }; + }; +}; + + +bool argusModuleEmbedVideo::write_header( STREAM_CTX *CTX ) { + int ret = avformat_write_header( CTX->ofmt_ctx, NULL); + if (ret < 0) { + //printf(stderr, "Error occurred: %s\n", av_err2str(ret)); + TLOG_ERROR("Error occurred when opening output file"); + return false; + }; + return CTX->bHeaderIsReady = true; +}; + +void argusModuleEmbedVideo::cleanSTREAM_CTX( STREAM_CTX *&CTX ){ + if( CTX!= NULL ) { + /*video*/ + if( CTX->video_stream ){ + + }; + if( CTX->video_frame ){ + }; + if( CTX->video_ctx ) { + avcodec_close( CTX->video_ctx ); + avcodec_free_context( &CTX->video_ctx ); + }; + if( CTX->video_codec ){ + av_freep( CTX->video_codec ); + }; + /*audio*/ + + /*container*/ + if( CTX->ofmt_ctx ){ + if( CTX->ofmt_ctx->oformat ) av_freep( CTX->ofmt_ctx->oformat ); + avformat_free_context( CTX->ofmt_ctx ); + }; + if( CTX->avio_ctx ){ + av_freep(&CTX->avio_ctx->buffer); + av_freep(CTX->avio_ctx); + }; + if( CTX->avio_ctx_buffer ) av_freep( CTX->avio_ctx_buffer ); + /*output*/ + if( CTX->buffer ) { + if( CTX->buffer->buf ) av_free( CTX->buffer->buf ); + av_free(CTX->buffer); + }; + av_freep( CTX ); + }; +}; + +bool argusModuleEmbedVideo::open_client_video( STREAM_CTX *&CTX, int w, int h, int fps, int br, int codec_idx, int format_idx ){ + const char* formats[] = {"webm", "mp4", "mp3", "aac", "ogg", "mjpeg", "flv" }; + const char* codecs[] = { "libvpx", "libx264", "mp4", "mjpeg", "flv" }; + if( CTX == NULL ) { + CTX = (STREAM_CTX *) av_mallocz(sizeof(STREAM_CTX)); + }; + + if( CTX!= NULL ) { + if( CTX->have_video ) return false; + TLOG("Creating Video Stream"); + AVOutputFormat* of = av_guess_format(formats[format_idx], 0, 0); + if( of == NULL ) { + cleanSTREAM_CTX( CTX ); + return false; + }; + TLOG("Format Guess OK"); + CTX->buffer = (buffer_data *) av_mallocz(sizeof(buffer_data)); + if( CTX->buffer == NULL ) { + cleanSTREAM_CTX( CTX ); + return false; + }; + TLOG("Buffer OK"); + CTX->buffer->room = CTX->buffer->size = BD_BUFFER_SIZE; + CTX->buffer->ptr = CTX->buffer->buf = (uint8_t *) av_malloc( CTX->buffer->size ); + if( !CTX->buffer->buf ) { + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Buffer OK"); + CTX->avio_ctx_buffer_size = AVIO_BUFFER_SIZE; + CTX->avio_ctx_buffer = (uint8_t *) av_malloc(CTX->avio_ctx_buffer_size); + if( !CTX->avio_ctx_buffer ){ + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVIO Buffer OK"); + CTX->avio_ctx = avio_alloc_context( + CTX->avio_ctx_buffer, + CTX->avio_ctx_buffer_size, + 1, + &CTX, + NULL, + &write_client_packet, + NULL //&seek + ); + if( !CTX->avio_ctx ){ + cleanSTREAM_CTX( CTX ); + return NULL; + } + TLOG("AVIO CTX OK"); + if( avformat_alloc_output_context2(&CTX->ofmt_ctx, of, NULL, NULL) < 0 ){ + TLOG_ERROR( "Could not create output context" ); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVFormat CTX OK"); + CTX->video_codec = avcodec_find_encoder_by_name(codecs[codec_idx]); + if( !CTX->video_codec ){ + char tB[100]; + sprintf( tB,"Codec '%s' not found", codecs[codec_idx] ); + TLOG_ERROR( tB ); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec OK"); + CTX->video_ctx = avcodec_alloc_context3( CTX->video_codec ); + if( !CTX->video_ctx ) { + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec CTX OK"); + CTX->video_ctx->width = w; + CTX->video_ctx->height = h; + CTX->video_ctx->time_base.num = 1; + CTX->video_ctx->time_base.den = fps; + CTX->video_ctx->bit_rate = br; + CTX->video_ctx->gop_size = 10; + if( codec_idx == 3 ) { + CTX->video_ctx->pix_fmt = AV_PIX_FMT_YUVJ422P; + } else { + CTX->video_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + CTX->video_ctx->max_b_frames = 1; + }; + if( avcodec_open2( CTX->video_ctx, CTX->video_codec, NULL ) < 0 ){ + TLOG_ERROR("couldnt open codec"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec Open OK"); + CTX->video_stream = avformat_new_stream( CTX->ofmt_ctx, NULL); + if( !CTX->video_stream ){ + TLOG_ERROR("error making stream"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVStream OK"); + CTX->ofmt_ctx->pb = CTX->avio_ctx; + CTX->ofmt_ctx->flags |= AVFMT_FLAG_CUSTOM_IO; + + CTX->ofmt_ctx->oformat = of; + CTX->video_stream->codec->codec_tag = 0; + + CTX->video_stream->time_base = CTX->video_ctx->time_base; + CTX->video_stream->id = CTX->ofmt_ctx->nb_streams-1; + + avcodec_parameters_from_context( CTX->video_stream->codecpar, CTX->video_ctx ); + + CTX->frame_idx = 0; + CTX->have_video = true; + + TLOG("STREAM OK"); + return true; + }; + return false; +}; + +bool argusModuleEmbedVideo::open_module_video( STREAM_CTX *&CTX, int w, int h, int fps, int br, int preset_idx, int codec_idx, int format_idx ){ + const char* formats[] = {"webm", "mp4", "mp3", "aac", "ogg", "mjpeg", "flv" }; + const char* codecs[] = { "libvpx", "libx264", "mp4", "mjpeg", "flv" }; + const char *presets[] = { "ultrafast", "veryfast", "fast", "medium", "slow", "veryslow" }; + if( CTX == NULL ) { + CTX = (STREAM_CTX *) av_mallocz( sizeof(STREAM_CTX)); + }; + + if( CTX!= NULL ) { + + if( CTX->have_video ) return false; + TLOG("Creating Video Stream"); + AVOutputFormat* of = av_guess_format(formats[format_idx], 0, 0); + if( of == NULL ) { + cleanSTREAM_CTX( CTX ); + return false; + }; + TLOG("Format Guess OK"); + CTX->buffer = (buffer_data *) av_mallocz(sizeof(buffer_data)); + if( CTX->buffer == NULL ) { + cleanSTREAM_CTX( CTX ); + return false; + }; + TLOG("Buffer OK"); + CTX->buffer->room = CTX->buffer->size = BD_BUFFER_SIZE; + CTX->buffer->ptr = CTX->buffer->buf = (uint8_t *) av_malloc( CTX->buffer->size ); + if( !CTX->buffer->buf ) { + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Buffer OK"); + CTX->avio_ctx_buffer_size = AVIO_BUFFER_SIZE; + CTX->avio_ctx_buffer = (uint8_t *) av_malloc(CTX->avio_ctx_buffer_size); + if( !CTX->avio_ctx_buffer ){ + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVIO Buffer OK"); + CTX->avio_ctx = avio_alloc_context( + CTX->avio_ctx_buffer, + CTX->avio_ctx_buffer_size, + 1, + &CTX, + NULL, + &write_module_packet, + NULL //&seek + ); + if( !CTX->avio_ctx ){ + cleanSTREAM_CTX( CTX ); + return NULL; + } + TLOG("AVIO CTX OK"); + if( avformat_alloc_output_context2(&CTX->ofmt_ctx, of, NULL, NULL) < 0 ){ + TLOG_ERROR( "Could not create output context" ); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVFormat CTX OK"); + CTX->video_codec = avcodec_find_encoder_by_name(codecs[codec_idx]); + if( !CTX->video_codec ){ + char tB[100]; + sprintf( tB,"Codec '%s' not found", codecs[codec_idx] ); + TLOG_ERROR( tB ); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec OK"); + CTX->video_ctx = avcodec_alloc_context3( CTX->video_codec ); + if( !CTX->video_ctx ) { + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec CTX OK"); + CTX->video_ctx->width = w; + CTX->video_ctx->height = h; + CTX->video_ctx->time_base.num = 1; + CTX->video_ctx->time_base.den = fps; + CTX->video_ctx->bit_rate = br; + CTX->video_ctx->gop_size = 10; + if( codec_idx == 3 ) { + CTX->video_ctx->pix_fmt = AV_PIX_FMT_YUVJ422P; + } else { + CTX->video_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + CTX->video_ctx->max_b_frames = 1; + }; + + av_opt_set( CTX->video_ctx->priv_data, "preset", presets[preset_idx], 0 ); + if( avcodec_open2( CTX->video_ctx, CTX->video_codec, NULL ) < 0 ){ + TLOG_ERROR("couldnt open codec"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Codec Open OK"); + + // Frame initalization + CTX->video_frame = av_frame_alloc(); + if( !CTX->video_frame ) { + TLOG_ERROR("couldnt alloc frame"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("Video Frame OK"); + CTX->video_frame->format = CTX->video_ctx->pix_fmt; + CTX->video_frame->width = w; + CTX->video_frame->height = h; + av_frame_get_buffer( CTX->video_frame, 0 ); + + CTX->video_stream = avformat_new_stream( CTX->ofmt_ctx, NULL); + if( !CTX->video_stream ){ + TLOG_ERROR("error making stream"); + cleanSTREAM_CTX( CTX ); + return NULL; + }; + TLOG("AVStream OK"); + CTX->ofmt_ctx->pb = CTX->avio_ctx; + CTX->ofmt_ctx->flags |= AVFMT_FLAG_CUSTOM_IO; + + CTX->ofmt_ctx->oformat = of; + CTX->video_stream->codec->codec_tag = 0; + + CTX->video_stream->time_base = CTX->video_ctx->time_base; + CTX->video_stream->id = CTX->ofmt_ctx->nb_streams-1; + + avcodec_parameters_from_context( CTX->video_stream->codecpar, CTX->video_ctx ); + + CTX->frame_idx = 0; + CTX->have_video = 1; + + TLOG("STREAM OK"); + return true; + }; + return false; +}; + +uint8_t *argusModuleEmbedVideo::close_stream( STREAM_CTX *CTX, int* size ){ + if( CTX->have_video ) encode_module_video( CTX, NULL ); +#ifndef _NOAUDIO_ + if( CTX->have_audio ) encode_audio( CTX, NULL ); +#endif + + av_write_trailer( CTX->ofmt_ctx ); + /* + avformat_free_context(ofmt_ctx); + + if (have_video) { + avcodec_free_context(&video_ctx); + av_frame_free(&video_frame); + } + + if (have_audio) { + avcodec_free_context(&audio_ctx); + av_frame_free(&audio_frame); + swr_free(&audio_swr_ctx); + free(audio_buffer_right); + free(audio_buffer_left); + } + + av_freep(&avio_ctx->buffer); + av_free(avio_ctx); + */ + *size = CTX->buffer->size - CTX->buffer->room; + return CTX->buffer->buf; +}; + +//void free_buffer(){ +// av_free(bd.buf); +//} +#ifndef _NOAUDIO_ +bool argusModuleEmbedVideo::alloc_audio_frame( STREAM_CTX *CTX ){ + if( CTX->audio_frame ){ + av_freep( CTX->audio_frame ); + }; + CTX->audio_frame = av_frame_alloc(); + if( !CTX->audio_frame ){ + TLOG_ERROR("Error allocating an audio frame"); + return false; + }; + CTX->audio_frame->format = CTX->audio_ctx->sample_fmt; + CTX->audio_frame->channel_layout = CTX->audio_ctx->channel_layout; + CTX->audio_frame->sample_rate = CTX->audio_ctx->sample_rate; + CTX->audio_frame->nb_samples = CTX->audio_ctx->frame_size; + if( av_frame_get_buffer( CTX->audio_frame, 4 ) < 0 ){ + TLOG_ERROR("Error allocating an audio buffer"); + return false; + }; + return true; +}; + +int argusModuleEmbedVideo::check_sample_fmt(const AVCodec *codec, enum AVSampleFormat sample_fmt){ + const enum AVSampleFormat *p = codec->sample_fmts; + while (*p != AV_SAMPLE_FMT_NONE) { + if (*p == sample_fmt) + return 1; + p++; + } + return 0; +}; + +void argusModuleEmbedVideo::add_audio_frame( STREAM_CTX *CTX, float* left, float* right, int size ){ + if( size + CTX->audio_buffer_size > CTX->max_audio_buffer_size ){ + CTX->audio_buffer_left = (float *)realloc(CTX->audio_buffer_left, (size + CTX->audio_buffer_size) * sizeof(float)); + CTX->audio_buffer_right = (float *)realloc(CTX->audio_buffer_right, (size + CTX->audio_buffer_size) * sizeof(float)); + } + + memcpy( CTX->audio_buffer_left + CTX->audio_buffer_size, left, size * sizeof(float) ); + memcpy( CTX->audio_buffer_right + CTX->audio_buffer_size, right, size * sizeof(float) ); + CTX->audio_buffer_size += size; + int count = 0, ret; + + while( CTX->audio_buffer_size > CTX->audio_frame->nb_samples ){ + if( av_frame_make_writable( CTX->audio_frame ) < 0){ + TLOG_ERROR("Error: add audio frame!"); + return; + }; + + CTX->audio_frame->data[0] = (uint8_t *) CTX->audio_buffer_left; + CTX->audio_frame->data[1] = (uint8_t *) CTX->audio_buffer_right; + + CTX->dst_nb_samples = av_rescale_rnd ( + swr_get_delay( CTX->audio_swr_ctx, CTX->audio_ctx->sample_rate ) + CTX->audio_frame->nb_samples, + CTX->src_sample_rate, + CTX->audio_ctx->sample_rate, + AV_ROUND_UP + ); + + if( swr_convert ( + CTX->audio_swr_ctx, + CTX->audio_frame->data, + CTX->dst_nb_samples, + (const uint8_t **)CTX->audio_frame->data, + CTX->audio_frame->nb_samples + )< 0){ + TLOG_ERROR("error converting \n"); + return; + }; + + CTX->audio_frame->pts = av_rescale_q( + CTX->audio_frame_bytes, + (AVRational){ 1, CTX->audio_ctx->sample_rate }, + CTX->audio_ctx->time_base + ); + + CTX->audio_frame_bytes += CTX->dst_nb_samples; + encode_audio( CTX, CTX->audio_frame ); + //Shift array buffer + memcpy( CTX->audio_buffer_left, CTX->audio_buffer_left + CTX->audio_frame->nb_samples, CTX->audio_buffer_size*sizeof(float)); + memcpy( CTX->audio_buffer_right, CTX->audio_buffer_right + CTX->audio_frame->nb_samples, CTX->audio_buffer_size*sizeof(float)); + CTX->audio_buffer_size -= CTX->audio_frame->nb_samples; + }; +}; + +bool argusModuleEmbedVideo::open_audio( STREAM_CTX *&CTX, int sample_rate, int nr_channels, int bit_rate, int codec_idx ){ + const AVCodecID codecs[] = { AV_CODEC_ID_OPUS, AV_CODEC_ID_AAC, AV_CODEC_ID_MP3 }; + if( CTX == NULL ) { + CTX = (STREAM_CTX *) av_mallocz( sizeof(STREAM_CTX)); + }; + if( CTX!= NULL ) { + if( CTX->have_audio ) return false; + CTX->src_sample_rate = sample_rate; + CTX->src_bit_rate = bit_rate; + CTX->src_nr_channels = nr_channels; + + + + CTX->audio_codec = avcodec_find_encoder(codecs[codec_idx]); + if( !CTX->audio_codec ){ + TLOG_ERROR("error making audio codec context"); + cleanSTREAM_CTX( CTX ); + return false; + }; + + CTX->audio_stream = avformat_new_stream( CTX->ofmt_ctx, NULL); + CTX->audio_stream->id = CTX->ofmt_ctx->nb_streams-1; + CTX->audio_ctx = avcodec_alloc_context3( CTX->audio_codec ); + CTX->audio_ctx->bit_rate = bit_rate; + CTX->audio_ctx->sample_rate = sample_rate; + if( CTX->audio_codec->supported_samplerates ){ + CTX->audio_ctx->sample_rate = CTX->audio_codec->supported_samplerates[0]; + for( int i = 0; CTX->audio_codec->supported_samplerates[i]; i++ ){ + if( CTX->audio_codec->supported_samplerates[i] == sample_rate ) CTX->audio_ctx->sample_rate = sample_rate; + }; + }; + CTX->audio_ctx->channels = nr_channels; + CTX->audio_ctx->channel_layout = AV_CH_LAYOUT_STEREO; + if( CTX->audio_codec->channel_layouts ){ + CTX->audio_ctx->channel_layout = CTX->audio_codec->channel_layouts[0]; + for( int i = 0; CTX->audio_codec->channel_layouts[i]; i++ ){ + if( CTX->audio_codec->channel_layouts[i] == AV_CH_LAYOUT_STEREO ) CTX->audio_ctx->channel_layout = AV_CH_LAYOUT_STEREO; + }; + }; + + CTX->audio_ctx->channels = av_get_channel_layout_nb_channels( CTX->audio_ctx->channel_layout ); + CTX->audio_ctx->sample_fmt = CTX->audio_codec->sample_fmts[0]; + CTX->audio_stream->time_base = (AVRational){1, CTX->audio_ctx->sample_rate}; + + if( avcodec_open2( CTX->audio_ctx, CTX->audio_codec, NULL ) < 0 ){ + TLOG_ERROR("Could not open audio codec" ); + cleanSTREAM_CTX( CTX ); + return false; + }; + + if(!alloc_audio_frame( CTX )){ + TLOG_ERROR("Could not alloc audio frame" ); + cleanSTREAM_CTX( CTX ); + return false; + }; + + if( avcodec_parameters_from_context( CTX->audio_stream->codecpar, CTX->audio_ctx ) < 0 ){ + TLOG_ERROR("Could not copy the stream parameters"); + cleanSTREAM_CTX( CTX ); + return false; + }; + + CTX->audio_swr_ctx = swr_alloc(); + if( !CTX->audio_swr_ctx ){ + TLOG_ERROR("Could not allocate resampler context"); + cleanSTREAM_CTX( CTX ); + return false; + }; + + av_opt_set_int (CTX->audio_swr_ctx, "in_channel_count", nr_channels, 0); + av_opt_set_int (CTX->audio_swr_ctx, "in_sample_rate", sample_rate, 0); + av_opt_set_sample_fmt(CTX->audio_swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0); + av_opt_set_int (CTX->audio_swr_ctx, "out_channel_count", CTX->audio_ctx->channels, 0); + av_opt_set_int (CTX->audio_swr_ctx, "out_sample_rate", CTX->audio_ctx->sample_rate, 0); + av_opt_set_sample_fmt(CTX->audio_swr_ctx, "out_sample_fmt", CTX->audio_ctx->sample_fmt, 0); + + if( swr_init( CTX->audio_swr_ctx ) < 0 ){ + TLOG_ERROR("Failed to initialize the resampling context"); + return false; + }; + + if( !CTX->pkt ) CTX->pkt = av_packet_alloc(); + + if( !CTX->pkt ){ + return false; + }; + + CTX->audio_buffer_size = CTX->audio_frame_bytes = 0; + CTX->audio_buffer_left = (float *)malloc(sample_rate * sizeof(float)); + CTX->audio_buffer_right = (float *)malloc(sample_rate * sizeof(float)); + CTX->max_audio_buffer_size = sample_rate; + + CTX->have_audio = 1; + return true; + }; + return false; +}; +#endif // _NOAUDIO_ + + +static int IOWriteFunc( void *opaque, uint8_t *buf, int buf_size ){ + WEB_CLIENT_CTX *CTX = (WEB_CLIENT_CTX *)opaque; + TLOG("-chunk-"); + if( CTX ) { + if( CTX->m_iSocketFID > -1 ){ + char mesg[128]; + sprintf( mesg, "%x\r\n", buf_size ); + if( send( CTX->m_iSocketFID, mesg, strlen(mesg), 0 ) < 0 ){ + sprintf( mesg, "Failed sending 1 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + CTX->bValid = false; + return -1; + }; + if( send( CTX->m_iSocketFID, buf, buf_size, 0 ) < 0 ){ + sprintf( mesg, "Failed sending 1 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + CTX->bValid = false; + return -1; + }; + if( send( CTX->m_iSocketFID, "\r\n", 2, 0 ) < 0 ){ + sprintf( mesg, "Failed sending 1 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + CTX->bValid = false; + return -1; + }; + return buf_size; + }; + }; + return -1; +}; + +void *argusModuleEmbedVideo::webClientProc( void *ptr ){ + static char *head = "HTTP/1.1 200 OK\r\n" + "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" + "Pragma: no-cache\r\n" + "MIME-version: 1.0\r\n" + "Connection: close\r\n" + "Content-Type: video/mp4\r\n" + "Content-Transfer-Encoding: BINARY\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"; + WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; + argusModuleEmbedVideo * MODULE = CTX->ModulePtr; + STREAM_CTX * STREAM = NULL; + + if( CTX ) { + char mesg[1024]; + size_t RecvSize; + struct pollfd pfd[1]; + char cGetURI[1024]; + bool m_bDeflatePerMessage = false; + bool m_pInit; + +#ifdef DEBUG_EXTRA + pid_t pid = gettid(); + char pidBuf[16]; + sprintf( pidBuf, "pid:%d", pid); + TLOG( pidBuf ); +#endif + + pfd->fd = CTX->m_iSocketFID; + pfd->events = POLLIN | POLLHUP; + + while( CTX->bValid ) { + if( !CTX->initDone ){ + int RetVal; + char * reqline[256]; + RetVal = poll( pfd, 1, 1000 ); + if( RetVal <= 0 ){ + if ( EINTR == errno ) continue; + TLOG_ERROR("Unrecoverable error"); + CTX->bValid = false; + continue; + }; + memset( mesg, 0, sizeof(mesg) ); + + RetVal = recv( CTX->m_iSocketFID, mesg, sizeof(mesg), 0 ); + + if ( RetVal <= 0 ) { + sprintf( mesg, "web recv() error: %s", strerror(errno)); + TLOG_ERROR( mesg ); + CTX->bValid = false; + continue; + }; + //TLOG( mesg ); + + uint32_t index = 0; + reqline[index] = strtok( mesg, "\n" ); + if( strncmp( reqline[index], "GET", 3 ) == 0 ) { + char * pPartURI; + char * pPartPROTO; + pPartURI = strstr( reqline[index], " " ); + if( pPartURI != NULL ) { + pPartURI++; + pPartPROTO = strstr( pPartURI, " " ); + pPartPROTO++; + int URILen = pPartPROTO - pPartURI; + strncpy( cGetURI, pPartURI, URILen ); + cGetURI[URILen] = (char)0; + if(strncmp( pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp( pPartPROTO, "HTTP/1.1", 8) != 0) { + TLOG_ERROR("No HTTP version supplied in request!"); + if( write( CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0 ){ + sprintf( mesg, "Failed returning status 400 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + }; + CTX->bValid = false; + continue; + }; + }; + TLOG( cGetURI ); + }; + // parse rest of request + while( ( reqline[++index] = strtok( NULL, "\n" ) )!= NULL ) { + if( strncmp( reqline[index], "Connection:", 11 ) == 0 ) { + char * pPart; + pPart = strcasestr( reqline[index], "Upgrade" ); + if( pPart != NULL ) { + TLOG("Upgrade Mode ON"); + //bUpgradeMode = true; + }; + }; + if( strncmp( reqline[index], "Upgrade:", 8 ) == 0 ) { + /* + if( bUpgradeMode ) { + char * pPart; + pPart = strcasestr( reqline[index], "websocket" ); + if( pPart != NULL ) { + TLOG("WebSocket Mode ON"); + //bWebSocketMode = true; + }; + }; + */ + }; + if( strncmp( reqline[index], "Sec-WebSocket-Version:", 22 ) == 0 ) { + char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + char tBuf[CTEXT]; + //nWebSocketVersion = atoi(pPart+1); + sprintf( tBuf,"Web Socket Version: %d", 0 );//nWebSocketVersion ); + TLOG( tBuf ); + }; + }; + if( strncmp( reqline[index], "Sec-WebSocket-Key:", 18 ) == 0 ) { + /*char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + char tGenStr[256]; + unsigned char * tBase64; + size_t nBase64; + int kLen; + unsigned char hash[SHA_DIGEST_LENGTH]; // == 20 + pPart++; + kLen = strstr(pPart,"\r") - pPart; + strncpy(cWSKey,pPart,kLen); + cWSKey[kLen]=(char)0; + TLOG( cWSKey ); + sprintf( tGenStr, "%s%s", cWSKey, ws_guid ); + SHA1( (const unsigned char*)tGenStr, strlen(tGenStr), hash ); + tBase64 = base64_encode( hash, SHA_DIGEST_LENGTH, &nBase64 ); + strncpy( cWSRep, (const char*)tBase64, nBase64 ); + free( tBase64 ); + cWSRep[nBase64] = (char)0; + TLOG( cWSRep ); + }; + */ + }; + if( strncmp( reqline[index], "Sec-WebSocket-Protocol:", 23 ) == 0 ) { + char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + // Check for protos + }; + }; + if( strncmp( reqline[index], "Sec-WebSocket-Extensions:", 25 ) == 0 ) { + char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + pPart++; + if(strncmp( pPart, "permessage-deflate", 18 ) == 0 ) { + m_bDeflatePerMessage = true; + TLOG("Using Deflate"); + }; + }; + }; + if( strncmp( reqline[index],"Accept-Encoding:", 16 ) == 0 ){ + char * pPart; + pPart = strstr( reqline[index], " " ); + if( pPart != NULL ) { + pPart++; + if(strncmp( pPart, "gzip, deflate", 13 ) == 0 ) { + m_bDeflatePerMessage = true; + TLOG("Using Deflate"); + }; + }; + }; + }; + // Send Header + if( send( CTX->m_iSocketFID, head, strlen(head), 0 ) < 0 ){ + sprintf( mesg, "Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + CTX->bValid = false; + }; + + if( CTX->ModulePtr->registerForMediaStream( 0, CTX ) ) { + if( !CTX->ModulePtr->open_client_video( + CTX->STREAM, + VIDEO_OUTPUT_WIDTH, + VIDEO_OUTPUT_HEIGHT, + VIDEO_OUTPUT_FPS, + VIDEO_OUTPUT_BITRATE, + VC_MJPEG, + VF_MJPEG + ) ){ + TLOG_ERROR("Cannot ctreate VIDEO STREAM!"); + CTX->bValid = false; + break; + }; + TLOG("Header"); + CTX->ModulePtr->write_header( STREAM ); + TLOG("After Header"); + CTX->initDone = true; + }; + continue; + } else { + uint32_t msgSize; + int retVal; + retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t)); + if( retVal == -1 ){ + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[1]!"); + CTX->bValid = false; + break; + }; + if( CTX->pkt == NULL ){ + CTX->pkt = (AVPacket *) av_mallocz(sizeof(AVPacket)); + } else { + // Data cleared in Encoder procedure + //av_freep( CTX->pkt->data ); + //av_packet_unref( CTX->pkt ); + }; + retVal = read( CTX->m_iEncoderPipe[0], CTX->pkt, sizeof(AVPacket)); + if( retVal == -1 ){ + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[2]!"); + CTX->bValid = false; + break; + }; + CTX->pkt->data = (uint8_t *)av_malloc( CTX->pkt->size ); + if( CTX->pkt->data ){ + retVal = read( CTX->m_iEncoderPipe[0], CTX->pkt->data, CTX->pkt->size ); + if( retVal == -1 ){ + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[3]!"); + CTX->bValid = false; + break; + }; + CTX->ModulePtr->encode_client_video( CTX->STREAM, CTX->pkt ); + } else { + TLOG_ERROR("Pack Memory Allocation Error!"); + CTX->bValid = false; + break; + }; + }; + }; + }; + TLOG("Client Handler Ended!"); + shutdown( CTX->m_iSocketFID, SHUT_RDWR); + close( CTX->m_iSocketFID ); + CTX->bValid = false; + //pthread_exit( NULL ); + return NULL; +}; + +void argusModuleEmbedVideo::destroy( WEB_CLIENT_CTX *&ptr ){ + if( ptr != NULL ){ + if( ptr->pkt ){ + av_packet_unref( ptr->pkt ); + av_freep( ptr->pkt ); + }; + //if( ptr->StreamBuffer ) av_freep( ptr->StreamBuffer ); + //if( ptr->outputFrame ) av_freep( ptr->outputFrame ); + free( ptr ); + ptr = NULL; + }; +}; + +void argusModuleEmbedVideo::m_fThreadProc( void ){ + if( !m_bEnabled ) { +#ifdef DEBUG + LOG("Module is Disabled!"); +#endif + return; + }; +#ifdef DEBUG + LOG("Module Started!"); +#endif + struct pollfd pfd[1]; + pfd->fd = m_nSocketDescriptor; + pfd->events = POLLIN | POLLHUP; + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { + if( !m_bEnabled ) { + m_bThreadStatus = TH_ENDED; + continue; + }; + int RetVal = poll( pfd, 1, 1000 ); + if( RetVal < 0 ){ + if( EINTR == errno ) continue; + LOG_ERROR("Unrecoverable error"); + m_bThreadStatus = TH_ENDED; + continue; + }; + // Handle Connections + if( RetVal != 0 ){ + if ( pfd[0].revents & POLLIN ) { + LOG("Handle New Client"); + int tSID = accept( pfd[0].fd, NULL, NULL); + if( tSID < 0 ){ + char tBuf[CTEXT]; + sprintf(tBuf, "Accept() error: %s", strerror(errno)); + LOG_ERROR(tBuf); + } else { + LOG("Accept OK"); + WEB_CLIENT_CTX *tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX)); + if( tCTX ) { + LOG("CTX OK"); + WEB_HANDLER *tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER)); + if( tHANDLER ) { + LOG("HANDLER OK"); + memset( tCTX, 0, sizeof(WEB_CLIENT_CTX) ); + memset( tHANDLER, 0, sizeof(WEB_HANDLER) ); + tCTX->m_iSocketFID = tSID; + //tCTX->m_iEncoderPipe[0] = -1; + //tCTX->m_iEncoderPipe[1] = -1; + tCTX->bValid = true; + tCTX->ModulePtr = this; + LOG("Before Thread Create"); + int RetVal = pthread_create( &tHANDLER->m_hThreadHandle, NULL, webClientProc, ( void * ) tCTX ); + if( RetVal == -1 ) { + free(tCTX); + free(tHANDLER); + LOG_ERROR("Thread Creation Faled."); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + } else { + tHANDLER->CTX = tCTX; + LOG("After Thread Create"); + m_vHandlersPool.push_back( tHANDLER ); + LOG("Handler Pushed to a Pool"); + }; + } else { + free(tCTX); + LOG_ERROR("CL_HANDLER Mem Allocation Failure!"); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + }; + } else { + LOG_ERROR("CL_CTX Mem Allocation Failure!"); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + }; + }; + }; + }; + // Handle Dead Clients + if( m_vHandlersPool.size() ) { + for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) { + if( !( (*idx)->CTX->bValid ) ) { +#ifdef DEBUG + LOG("Web Handler Ripped!"); +#endif + pthread_join( (*idx)->m_hThreadHandle, NULL ); + destroy( (*idx)->CTX ); + free( (*idx) ); + m_vHandlersPool.erase(idx); + }; + }; + }; + SLEEP( 50 ); + }; +}; + +#define ENABLE_SOCKOPT(sd, level, opt) \ + do { \ + int val = 1; \ + if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \ + warn("Failed enabling %s for web service", #opt); \ + } while (0); + + +bool argusModuleEmbedVideo::startService(){ + LOG("Create"); + //if( m_nListenPort == 0 && ListenPort == 0 ) return false; + //m_nListenPort = ListenPort; + struct sockaddr sa; + struct sockaddr_in *sin; + + memset(&sa, 0, sizeof(struct sockaddr)); + sa.sa_family = AF_INET; + sin = (struct sockaddr_in *)&sa; + sin->sin_addr.s_addr = htonl( INADDR_ANY ); + sin->sin_port = htons( 8972 ); + + m_nSocketDescriptor = socket( sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); + if( m_nSocketDescriptor == -1 ){ + LOG_ERROR("Failed creating ACC socket"); + return false; + }; + ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEADDR); +#ifdef SO_REUSEPORT + ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEPORT); +#endif + if( bind( m_nSocketDescriptor, &sa, sizeof(sa)) < 0 ){ + LOG_ERROR("Failed binding Socket"); + close( m_nSocketDescriptor ); + return false; + } else { + LOG("Bind Socessfull"); + }; + if( listen( m_nSocketDescriptor, 10) != 0 ){ + LOG_ERROR("Failed setting web listen backlog"); + close( m_nSocketDescriptor ); + return false; + } else { + LOG("Listen OK"); + }; + createStream( 0 ); + return init(); +}; + +bool argusModuleEmbedVideo::stopService(){ + waitThreadEnd( true ); + /* + if( m_vThreads.size() ) { // Kill-Wait Started Probes +#ifdef DEBUG + LOG("Have to Wait Probes!"); +#endif + for( vectorOBSERVER_CTX::iterator index = m_vThreads.begin(); index < m_vThreads.end(); index++ ) { + pthread_join( (*index)->m_hThreadHandle, NULL ); + }; + m_vThreads.clear(); + }; +#ifdef DEBUG + LOG("No More Probes!"); +#endif + if (m_vResultPool.size()){ // Clear structures + for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){ + free(*index); + }; + m_vResultPool.clear(); + }; +#ifdef DEBUG + LOG("Data is Cleared!"); +#endif +*/ + return true; +}; + +bool argusModuleEmbedVideo::reloadSettings(){ + + return true; +}; + +void argusModuleEmbedVideo::dispatchEvent(EVENT_CONTAINER *Evt){ +}; + +bool argusModuleEmbedVideo::validate(){ + // Scan Active Streams And Create + if( m_pDBC ) { + DBC_INT_LIST *IDS = m_pDBC->listMediaStreams( 1 ,LIST_VALID_RECORDS ); + if( IDS ) { + for( DBC_INT_LIST::iterator idx = IDS->begin(); idx < IDS->end(); idx++ ) { + if( !createStream((*idx)) ) LOG_ERROR( "STREAM Creation Failure!" ); + }; + delete( IDS ); + }; + }; + return true; +}; + +void argusModuleEmbedVideo::pushFrame(AVFrame *Frame, void* src){ + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + if( tMD ) { + }; +}; + +void argusModuleEmbedVideo::pushFrame(cv::Mat* Frame, void* src){ + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + if( tMD ) { + + for( vectorSTREAMS::iterator idx = m_vRegisteredStreams.begin(); idx < m_vRegisteredStreams.end(); idx++ ) { + if( (*idx)->mediaStreamId == tMD->mediaStreamId ) { + + break; + }; + }; + }; +}; + +bool argusModuleEmbedVideo::registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ){ + if( CTX ){ + if( id ){ + if( pipe( CTX->m_iEncoderPipe ) == -1 ){ + CTX->bValid = false; + return false; + }; + CTX->STREAM = (STREAM_CTX *) av_mallocz(sizeof(STREAM_CTX)); + if( CTX->STREAM ) { + CTX->STREAM->mediaStreamId = id; + + return true; + } else { + close( CTX->m_iEncoderPipe[0] ); CTX->m_iEncoderPipe[0] = -1; + close( CTX->m_iEncoderPipe[1] ); CTX->m_iEncoderPipe[1] = -1; + LOG_ERROR("STREAM memory allocation error!"); + CTX->bValid = false; + return false; + }; + } +#ifdef DEBUG + else { + CTX->bValid = true; + CTX->STREAM = (STREAM_CTX *) av_mallocz(sizeof(STREAM_CTX)); + if( CTX->STREAM ) { + CTX->STREAM->mediaStreamId = 0; + }; + return true; + } +#endif + ; + } else LOG_ERROR("Client Context error!"); + return false; +}; + +bool argusModuleEmbedVideo::registerStream( MEDIA_SOURCE_DESC *ptr ){ + if( ptr ){ + if( m_vRegisteredStreams.size() ){ + bool found = false; + m_mStreamsProtector.lock(); + for( vectorSTREAMS::iterator idx = m_vRegisteredStreams.begin(); idx < m_vRegisteredStreams.end(); idx++ ) { + if( (*idx)->mediaStreamId == ptr->mediaStreamId ) { + found = true; + break; + }; + }; + m_mStreamsProtector.unlock(); + if( !found ) return createStream( ptr->mediaStreamId ); + } else { + return createStream( ptr->mediaStreamId ); + }; + }; + return false; +}; + +bool argusModuleEmbedVideo::unregisterStream( MEDIA_SOURCE_DESC *ptr ){ + if( ptr ){ + if( m_vRegisteredStreams.size() ){ + m_mStreamsProtector.lock(); + for( vectorSTREAMS::iterator idx = m_vRegisteredStreams.begin(); idx < m_vRegisteredStreams.end(); idx++ ) { + if( (*idx)->mediaStreamId == ptr->mediaStreamId ) { + //destroyStream((*idx)); + m_vRegisteredStreams.erase( idx ); + m_mStreamsProtector.unlock(); + return true; + }; + }; + m_mStreamsProtector.unlock(); + }; + }; + return false; +}; + +bool argusModuleEmbedVideo::createStream( uint32_t id ){ + DBC_MEDIA_STREAM_DATA *tDATA = NULL; + bool retVal = false; + if( m_vRegisteredStreams.size() ){ + m_mStreamsProtector.lock(); + for( vectorSTREAMS::iterator idx = m_vRegisteredStreams.begin(); idx < m_vRegisteredStreams.end(); idx++ ) if( (*idx)->mediaStreamId == id ) return true; + m_mStreamsProtector.unlock(); + }; + if( m_pDBC ) { + tDATA = m_pDBC->getMediaStreamData( id ); + if( tDATA ) { + STREAM_CTX *CTX = (STREAM_CTX*) av_mallocz(sizeof(STREAM_CTX)); + if( CTX ) { + CTX->ModulePtr = this; + CTX->mediaStreamId = id; + initLibAV(); + if( open_module_video( + CTX, + VIDEO_OUTPUT_WIDTH, + VIDEO_OUTPUT_HEIGHT, + VIDEO_OUTPUT_FPS, + VIDEO_OUTPUT_BITRATE, + VP_FAST, + VC_MJPEG, + VF_MJPEG + ) ){ + CTX->InputMat = new cv::Mat( VIDEO_OUTPUT_HEIGHT, VIDEO_OUTPUT_WIDTH, CV_8UC3 ); + if( CTX->InputMat == NULL ) { + TLOG_ERROR("Cannot ctreate cv::Mat for encoder!"); + free( tDATA ); + cleanSTREAM_CTX( CTX ); + return false; + }; +#ifdef DEBUG + LOG("cv::Mat Created"); +#endif + cv::rectangle( *CTX->InputMat, cv::Point( 0, 0 ), cv::Point( VIDEO_OUTPUT_WIDTH, VIDEO_OUTPUT_HEIGHT ), cv::Scalar( 255, 0, 0 ), cv::FILLED ); + if( write_header( CTX ) ){ +#ifdef DEBUG + LOG( "Header SENT" ); +#endif + CTX->video_sws_ctx = sws_getContext( + tDATA->width, + tDATA->height, + AV_PIX_FMT_BGR24, + VIDEO_OUTPUT_WIDTH, + VIDEO_OUTPUT_HEIGHT, + VIDEO_OUTPUT_PIX_FMT, + SWS_BICUBIC, + NULL, + NULL, + NULL + ); + if( CTX->video_sws_ctx == NULL ){ + char buffer[200]; + sprintf( buffer, "Failed to get SWS CTX [%dx%d]{%04X} ---> [%dx%d]{%04X} by (%d)", + tDATA->width, + tDATA->height, + AV_PIX_FMT_BGR24, + VIDEO_OUTPUT_WIDTH, + VIDEO_OUTPUT_HEIGHT, + VIDEO_OUTPUT_PIX_FMT, + SWS_BICUBIC + ); + LOG_ERROR( buffer ); + free( tDATA ); + cleanSTREAM_CTX( CTX ); + return false; + }; +#ifdef DEBUG + LOG("Finish Preparing SWS"); +#endif + CTX->video_frame = av_frame_alloc(); + if( CTX->video_frame == NULL ){ + LOG_ERROR("Error Create AVFrame!"); + free( tDATA ); + cleanSTREAM_CTX( CTX ); + return false; + }; +#ifdef DEBUG + LOG("Frame Created"); +#endif + CTX->video_frame->width = VIDEO_OUTPUT_WIDTH; + CTX->video_frame->height = VIDEO_OUTPUT_HEIGHT; + CTX->video_frame->format = VIDEO_OUTPUT_PIX_FMT; + uint8_t *tBuff = (uint8_t *) av_malloc( + av_image_get_buffer_size( + (AVPixelFormat)CTX->video_frame->format, + CTX->video_frame->width, + CTX->video_frame->height, + BUFFER_ALIGN + ) + ); + if( tBuff == NULL) { + TLOG_ERROR("Error Allocate Buffer for AVFrame!"); + free( tDATA ); + cleanSTREAM_CTX( CTX ); + return false; + }; +#ifdef DEBUG + LOG("Buffer Created"); +#endif + avpicture_fill( + (AVPicture *)CTX->video_frame, + tBuff, + (AVPixelFormat)CTX->video_frame->format, + CTX->video_frame->width, + CTX->video_frame->height + ); + TLOG("Finish Preparing output AVFrame"); + m_mStreamsProtector.lock(); + m_vRegisteredStreams.push_back( CTX ); + m_mStreamsProtector.unlock(); +#ifdef DEBUG + LOG("STREAM Created"); +#endif + retVal = true; + } else { + cleanSTREAM_CTX( CTX ); + }; + } else { + cleanSTREAM_CTX( CTX ); + }; + }; + free( tDATA ); + }; + }; + return retVal; +}; + + +#undef LOG +#undef LOG_ERROR +#undef TLOG +#undef TLOG_ERROR diff --git a/lib/App/mojo/rgooseModuleEmbedVideo - Copy.h b/lib/App/mojo/rgooseModuleEmbedVideo - Copy.h new file mode 100644 index 00000000..691d0f8e --- /dev/null +++ b/lib/App/mojo/rgooseModuleEmbedVideo - Copy.h @@ -0,0 +1,225 @@ +#ifndef __ARGUS_MODULE_EMBED_VIDEO_HEADER__ +#define __ARGUS_MODULE_EMBED_VIDEO_HEADER__ +#include "rgooseModule.h" +#include "../components/base/basicMutex.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" +//#include "../data/media/video/videoAVLIBDestination.h" +#include "../components/base/basicMediaDestination.h" + +class argusModuleEmbedVideo; + +#define FILESTREAMBUFFERSZ 1048576 + +/* Video CODECS */ +#define VC_VPX 0 +#define VC_X264 1 +#define VC_MP4 2 +#define VC_MJPEG 3 +#define VC_FLV 4 + +/* Video FORMATS */ +#define VF_WEBM 0 +#define VF_MP4 1 +#define VF_MP3 2 +#define VF_AAC 3 +#define VF_OGG 4 +#define VF_MJPEG 5 +#define VF_FLV 6 + +/* Encoder PROFILES */ +#define VP_ULTRAFAST 0 +#define VP_VERYFAST 1 +#define VP_FAST 2 +#define VP_MEDIUM 3 +#define VP_SLOW 4 +#define VP_VERYSLOW 5 +#define VP_ULTRASLOW 6 + +#define VIDEO_OUTPUT VO_MJPEG +//#define VIDEO_OUTPUT VO_MPEG4 +//#define VIDEO_OUTPUT VO_H264 +//#define VIDEO_OUTPUT VO_FLV + +#define VIDEO_OUTPUT_WIDTH 1920 +#define VIDEO_OUTPUT_HEIGHT 1080 +#define VIDEO_OUTPUT_FPS 10 +#define VIDEO_OUTPUT_GOP 30 + +#if( LIBAVCODEC_VERSION_MAJOR < 54 ) + //#define VIDEO_OUTPUT_CODEC CODEC_ID_MJPEG + //#define VIDEO_OUTPUT_PIX_FMT PIX_FMT_YUVJ422P +#else + //#if( VIDEO_OUTPUT == VO_MJPEG ) + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MJPEG + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUVJ422P + #define VIDEO_OUTPUT_CONTAINER_LONG "mjpeg" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "mjpeg" + /* + #endif + #if( VIDEO_OUTPUT == VO_MPEG4 ) + + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MPEG4 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_BITRATE 100000000 + #define VIDEO_OUTPUT_CONTAINER "mp4" + //* + #endif + #if( VIDEO_OUTPUT == VO_H264 ) + //* / + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H264 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 100000000 + #define VIDEO_OUTPUT_CONTAINER_LONG "matroska" + #define VIDEO_OUTPUT_CONTAINER "mkv" + /* + #endif + #if( VIDEO_OUTPUT == VO_FLV ) + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_FLV1 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "flv" + #endif + */ +#endif + +typedef struct S_buffer_data { + uint8_t * buf; + int size; + uint8_t * ptr; + size_t room; ///< size left in the buffer +} buffer_data; + +#define NR_COLORS 4 +#define AVIO_BUFFER_SIZE 4096 +#define BD_BUFFER_SIZE 1024 + +typedef struct S_STREAM_CTX{ + argusModuleEmbedVideo * ModulePtr; + uint32_t mediaStreamId; + AVFormatContext * ofmt_ctx; + + + AVIOContext * avio_ctx; + uint8_t * avio_ctx_buffer; + size_t avio_ctx_buffer_size; + buffer_data * buffer; + + + /* VIDEO */ + AVStream * video_stream; + struct SwsContext * video_sws_ctx; + AVCodecContext * video_ctx; + AVCodec * video_codec; + AVFrame * video_frame; + + /* For Encoding */ + cv::Mat * InputMat; + AVFrame * outputFrame; + + int64_t ts; + uint32_t frame_idx; + int have_video; + bool bHeaderIsReady; + uint8_t * header; + uint32_t header_size; +#ifndef _NOAUDIO_ + /* AUDIO */ + AVStream * audio_stream; + AVCodecContext * audio_ctx; + AVCodec * audio_codec; + struct SwrContext * audio_swr_ctx; + AVFrame * audio_frame; + int have_audio; + uint32_t audio_buffer_size; + float * audio_buffer_left; + float * audio_buffer_right; + uint32_t max_audio_buffer_size; + int src_sample_rate; + int src_bit_rate; + int src_nr_channels; + int dst_nb_samples; + int audio_frame_bytes; +#endif +}STREAM_CTX; + + +typedef struct S_WEB_CLIENT_CTX{ + int m_iSocketFID; + int m_iEncoderPipe[2]; + AVPacket * pkt; + + bool bValid; + + bool initDone; + bool headerIsSent; + + argusModuleEmbedVideo * ModulePtr; + STREAM_CTX * STREAM; +}WEB_CLIENT_CTX; + + +typedef struct S_WEB_HANDLER{ + DWORD m_dwThreadID; +#ifdef __linux__ + pthread_t m_hThreadHandle; +#else + HANDLE m_hThreadHandle; +#endif + WEB_CLIENT_CTX * CTX; +}WEB_HANDLER; + +typedef vector vectorHANDLERS; +typedef vector vectorSTREAMS; + +class argusModuleEmbedVideo: public argusKernelModule, public basicMediaDestination, public basicThread { + private: + basicEventHeap * m_pEventHeap; + static void * webClientProc( void *ptr ); + //static int write_packet( void *opaque, uint8_t *buf, int buf_size ); + int m_nSocketDescriptor; + basicMutex m_mHandlersProtector; + vectorHANDLERS m_vHandlersPool; + basicMutex m_mStreamsProtector; + vectorSTREAMS m_vRegisteredStreams; + bool registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ); + bool write_header( STREAM_CTX *CTX ); + bool createStream( uint32_t id ); + bool open_client_video( STREAM_CTX *&CTX, int w, int h, int fps, int br, int codec_idx, int format_idx ); + bool open_module_video( STREAM_CTX *&CTX, int w, int h, int fps, int br, int preset_idx, int codec_idx, int format_idx ); + static int write_module_packet( void *opaque, uint8_t *buf, int buf_size ); + static int write_client_packet( void *opaque, uint8_t *buf, int buf_size ); + void encode_module_video( STREAM_CTX *CTX, AVFrame *DATA ); + void encode_client_video( STREAM_CTX *CTX, AVPacket *pkt ); + void add_video_frame( STREAM_CTX *CTX ); + void destroy( WEB_CLIENT_CTX *&ptr ); + void cleanSTREAM_CTX( STREAM_CTX *&CTX ); + uint8_t * close_stream( STREAM_CTX *CTX, int* size ); +#ifndef _NOAUDIO_ + void encode_audio( STREAM_CTX *CTX, AVFrame *DATA ); + bool alloc_audio_frame( STREAM_CTX *CTX ); + int check_sample_fmt(const AVCodec *codec, enum AVSampleFormat sample_fmt ); + void add_audio_frame( STREAM_CTX *CTX, float* left, float* right, int size ); + bool open_audio( STREAM_CTX *&CTX, int sample_rate, int nr_channels, int bit_rate, int codec_idx ); +#endif + protected: + /* From Basic Thread */ + virtual void m_fThreadProc( void ); + public: + explicit argusModuleEmbedVideo( uint32_t moduleID ); + ~argusModuleEmbedVideo(); + /* From Kernel Module */ + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService(); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); + bool registerStream( MEDIA_SOURCE_DESC *ptr ); + bool unregisterStream( MEDIA_SOURCE_DESC *ptr ); + /* from Media Destination */ + virtual void pushFrame(AVFrame *Frame, void* src = NULL); + virtual void pushFrame(cv::Mat* Frame, void* src = NULL); +}; +#endif diff --git a/lib/App/mojo/rgooseModuleEmbedVideo.cpp b/lib/App/mojo/rgooseModuleEmbedVideo.cpp new file mode 100644 index 00000000..287f2222 --- /dev/null +++ b/lib/App/mojo/rgooseModuleEmbedVideo.cpp @@ -0,0 +1,2208 @@ +#include "rgooseModuleEmbedVideo.h" +//#include "rgooseHardwareResourceNetworkProvider.h" +#include "mojoKernel.h" +#include "../alg/generic/base64.h" + +#include "../data/media/video/videoAVLIBSource.h" +#include "../data/media/video/videoLive555AVLibSource.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* MIN() */ +#include +#include + + +#define STORAGE_DIR_MODE 0x1FF +#define STORAGE_FILE_MODE 0x1B6 + + +#define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, X ); +#endif + +#define TLOG( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, X ) +#ifdef DEBUG + #define TLOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, X ); +#endif + +enum { + WEBRTC_REQ_SIGNIN = 0, + WEBRTC_REQ_WAIT = 1, + WEBRTC_REQ_SIGNOUT = 2, + WEBRTC_REQ_MESSAGE = 3 +}; + +static const char* kRequestPaths[] = { "/stream", "/sign_in", "/wait", "/sign_out", "/message" }; + +//buffer_data bd[1]={0}; + +argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_EMBED_VIDEO ), basicThread(){ + m_pEventHeap = basicEventHeap::getInstance(); + if( m_pDBC ){ + DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); + if( tDATA ) { + memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); + free( tDATA ); + } else { + memset( &m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) ); + m_sEmbedVideoData.port = 8972; + }; + } else { + LOG_ERROR( "DB Error!" ); + }; + n_pNoSignalData = NULL; + m_nNoSignalSize = 0; + char tBuff[1024]; + sprintf( m_pBaseSavePath, "%s/data/reports", getcwd(tBuff, 1024) ); +#ifdef DEBUG + char tB[64]; + sprintf( tB, "Web Streams Port: %d", m_sEmbedVideoData.port ); + LOG( tB ); + sprintf( tB, "Frame: [%dx%d]", m_sEmbedVideoData.width, m_sEmbedVideoData.height ); + LOG( tB ); + if( m_sEmbedVideoData.show_ts ) LOG("Show TimeStamp"); + if( m_sEmbedVideoData.show_label ) LOG("Show Label"); + if( m_sEmbedVideoData.show_logo ) LOG("Show Logo"); +#endif + if( m_sEmbedVideoData.show_logo ){ + LOG( m_sEmbedVideoData.logo_md5 ); + char tPath[MAX_PATH]; + sprintf( tPath, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5 ); + if( !fileExist( tPath ) ){ + LOG_ERROR("Logo File Missed!"); + m_sEmbedVideoData.show_logo = false; + } +#ifdef DEBUG + else LOG("Logo File is OK"); +#endif + ; + }; +}; + +argusModuleEmbedVideo::~argusModuleEmbedVideo(){ + m_bEnabled = false; + waitThreadEnd( true ); + if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes +#ifdef DEBUG + char tB[200]; + sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() ); + LOG( tB ); + +#endif + for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) pthread_cancel( (*index)->m_hThreadHandle ); + m_vHandlersPool.clear(); + }; +#ifdef DEBUG + LOG("No More Client Handlers!"); +#endif + if( m_mapHANDLERS.size() ){ + for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) delete( (*idx).second ); + m_mapHANDLERS.clear(); + }; + if( m_mapCAPTURES.size() ) m_mapCAPTURES.clear(); + if( m_mapMATS.size() ) m_mapMATS.clear(); + if( n_pNoSignalData ) free(n_pNoSignalData); +}; + +static const char * ht_head = "HTTP/1.1 200 OK\r\n" + "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" + "Pragma: no-cache\r\n" + "MIME-version: 1.0\r\n" + "Connection: close\r\n" + //"Keep-Alive: timeout=5, max=1\r\n" + //"Connection: Keep-Alive\r\n" + //"Content-Type: video/mp4\r\n" + "Content-Transfer-Encoding: BINARY\r\n" + //"Transfer-Encoding: chunked\r\n" + "Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n" + "\r\n"; +static const char * ht_abort = "HTTP/1.1 404 OK\r\n" + "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n" + "Pragma: no-cache\r\n" + "Connection: close\r\n\r\n"; +static const char * ht_no_signal = "HTTP/1.1 200 OK\r\n" + "MIME-version: 1.0\r\n" + "Connection: close\r\n" + "Content-Transfer-Encoding: BINARY\r\n" + //"Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n\r\n" + "Content-Type: image/jpeg\r\nContent-length: %d\r\n\r\n"; + +void *argusModuleEmbedVideo::webClientProc( void *ptr ){ + + + WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr; + argusModuleEmbedVideo * MODULE = CTX->ModulePtr; + uint32_t msgSize; + uint8_t tBuf[FILESTREAMBUFFERSZ]; + int retVal; + + if( CTX ) { + char mesg[1024]; + size_t RecvSize; + struct pollfd pfd[1]; + char cGetURI[1024]; + bool m_bDeflatePerMessage = false; + bool m_pInit; + +#ifdef DEBUG_EXTRA + pid_t pid = gettid(); + char pidBuf[16]; + sprintf( pidBuf, "pid:%d", pid); + TLOG( pidBuf ); +#endif + + pfd->fd = CTX->m_iSocketFID; + pfd->events = POLLIN | POLLHUP; + + while( CTX->bValid ) { + if( !CTX->initDone ){ + int RetVal; + char * reqline[256]; + RetVal = poll( pfd, 1, 1000 ); + if( RetVal <= 0 ){ + if ( EINTR == errno ) continue; + TLOG_ERROR("Unrecoverable error"); + CTX->bValid = false; + continue; + }; + memset( mesg, 0, sizeof(mesg) ); + + RetVal = recv( CTX->m_iSocketFID, mesg, sizeof(mesg), 0 ); + + if ( RetVal <= 0 ) { + sprintf( mesg, "web recv() error: %s", strerror(errno)); + TLOG_ERROR( mesg ); + CTX->bValid = false; + continue; + }; +#ifdef DEBUG_EXTRA + TLOG( mesg ); +#endif + + uint32_t index = 0; + reqline[index] = strtok( mesg, "\n" ); + if( strncmp( reqline[index], "GET", 3 ) == 0 ) { + char * pPartURI; + char * pPartPROTO; + pPartURI = strstr( reqline[index], " " ); + if( pPartURI != NULL ) { + pPartURI++; + pPartPROTO = strstr( pPartURI, " " ); + pPartPROTO++; + int URILen = pPartPROTO - pPartURI; + strncpy( cGetURI, pPartURI, URILen ); + cGetURI[URILen] = (char)0; + if(strncmp( pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp( pPartPROTO, "HTTP/1.1", 8) != 0) { + TLOG_ERROR("No HTTP version supplied in request!"); + if( write( CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0 ){ + sprintf( mesg, "Failed returning status 400 to client: %s", strerror(errno)); + TLOG_ERROR(mesg); + }; + CTX->bValid = false; + continue; + }; + }; +#ifdef DEBUG_EXTRA + TLOG( cGetURI ); +#endif + }; + + if( strncmp( cGetURI, "/stream", 7 ) == 0 ) { + uint32_t tStreamID = 0; + CSTR tP; + if( tP = strstr( cGetURI, "?" ) ) { + CSTR tB; + tP++; + if( tB = strstr( tP, "id=" ) ) { + tStreamID = atoi( tB+3 ); + }; + }; + if( tStreamID ) { +#ifdef DEBUG_EXTRA + char tB[64]; + sprintf(tB,"StremID: %d", tStreamID ); + TLOG( tB ); +#endif + if( CTX->ModulePtr->registerForMediaStream( tStreamID, CTX ) ){ + // Send Header + if( send( CTX->m_iSocketFID, ht_head, strlen(ht_head), 0 ) < 0 ){ +#ifdef DEBUG_EXTRA + sprintf( mesg, "Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); +#endif + CTX->bValid = false; + }; + CTX->initDone = true; + continue; + } +#ifdef DEBUG_EXTRA + else { + TLOG("Stream id Not Online"); + } +#endif + ; + } +#ifdef DEBUG_EXTRA + else TLOG("No Stream ID") +#endif + ; + }; + if( CTX->ModulePtr->n_pNoSignalData ) { + //Send Dummy Picture + sprintf( mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSize ); + send( CTX->m_iSocketFID, mesg, strlen(mesg), 0 ); + send( CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0 ); + send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 ); +#ifdef DEBUG_EXTRA + TLOG("Sent No Signal Image!"); +#endif + } else { + // Send 404 Header + send( CTX->m_iSocketFID, ht_abort, strlen(ht_abort), 0 ); +#ifdef DEBUG_EXTRA + TLOG("Aborted!"); +#endif + }; + CTX->bValid = false; + continue; + } else { + /* + retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t)); + if( retVal == -1 ){ + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[1]!"); + CTX->bValid = false; + continue; + }; + if( msgSize < FILESTREAMBUFFERSZ ) { + retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize ); + } else { + TLOG_ERROR("Data too Big in Pipe Transfer!"); + CTX->bValid = false; + continue; + }; + if( retVal == -1 ){ + //free( tBuf ); + if( errno == EAGAIN || errno == EWOULDBLOCK ){ + continue; + }; + TLOG_ERROR("Pipe Communication Error[2]!"); + CTX->bValid = false; + continue; + }; + */ + /**************/ + CTX->ModulePtr->m_mEncodedProtector.lock(); + if( CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size() ) { + msgSize = CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size(); + if( msgSize < FILESTREAMBUFFERSZ ) { + memcpy( tBuf, CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].data(), msgSize ); + CTX->ModulePtr->m_mEncodedProtector.unlock(); + } else { + CTX->ModulePtr->m_mEncodedProtector.unlock(); + TLOG_ERROR("Data too Big in Pipe Transfer!"); + CTX->bValid = false; + continue; + }; + } else { + CTX->ModulePtr->m_mEncodedProtector.unlock(); + if( CTX->ModulePtr->n_pNoSignalData ){ + msgSize = CTX->ModulePtr->m_nNoSignalSize; + memcpy( tBuf, CTX->ModulePtr->n_pNoSignalData, msgSize ); + } else { + TLOG_ERROR("Data too Big in Pipe Transfer!"); + CTX->bValid = false; + continue; + }; + }; + /*********/ + sprintf( mesg, "--MPFrame\r\nContent-type: image/jpeg\r\nContent-length: %d\r\n\r\n", msgSize ); + if( send( CTX->m_iSocketFID, mesg, strlen( mesg ), 0 )< 0 ){ +#ifdef DEBUG_EXTRA + sprintf( mesg, "[1]Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); +#endif + CTX->bValid = false; + continue; + }; + if( send( CTX->m_iSocketFID, tBuf, msgSize, 0 ) < 0 ){ +#ifdef DEBUG_EXTRA + sprintf( mesg, "[2]Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); +#endif + CTX->bValid = false; + continue; + }; + if( send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 )< 0 ){ +#ifdef DEBUG_EXTRA + sprintf( mesg, "[3]Failed sending file to client: %s", strerror(errno)); + TLOG_ERROR(mesg); +#endif + CTX->bValid = false; + continue; + }; + SLEEP( 80 ); + }; + }; + }; + CTX->bValid = false; +#ifdef DEBUG_EXTRA + TLOG("WEB Client Handler Ended!"); +#endif + close( CTX->m_iEncoderPipe[0] ); + shutdown( CTX->m_iSocketFID, SHUT_RDWR); + close( CTX->m_iSocketFID ); + //pthread_exit( NULL ); + return NULL; +}; + +void argusModuleEmbedVideo::m_fThreadProc( void ){ + if( !m_bEnabled ) { +#ifdef DEBUG + LOG("Module is Disabled!"); +#endif + return; + }; +#ifdef DEBUG + LOG("Module Started!"); +#endif + struct pollfd pfd[1]; + pfd->fd = m_nSocketDescriptor; + pfd->events = POLLIN | POLLHUP; + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { + if( !m_bEnabled ) { + m_bThreadStatus = TH_ENDED; + continue; + }; + int RetVal = poll( pfd, 1, 1000 ); + if( RetVal < 0 ){ + if( EINTR == errno ) continue; + LOG_ERROR("Unrecoverable error"); + m_bThreadStatus = TH_ENDED; + continue; + }; + // Handle Connections + if( RetVal != 0 ){ + if ( pfd[0].revents & POLLIN ) { +#ifdef DEBUG_EXTRA + LOG("Handle New Client"); +#endif + int tSID = accept( pfd[0].fd, NULL, NULL); + if( tSID < 0 ){ + char tBuf[CTEXT]; + sprintf(tBuf, "Accept() error: %s", strerror(errno)); + LOG_ERROR(tBuf); + } else { +#ifdef DEBUG_EXTRA + LOG("Accept OK"); +#endif + WEB_CLIENT_CTX *tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX)); + if( tCTX ) { +#ifdef DEBUG_EXTRA + LOG("CTX OK"); +#endif + WEB_HANDLER *tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER)); + if( tHANDLER ) { +#ifdef DEBUG_EXTRA + LOG("HANDLER OK"); +#endif + memset( tCTX, 0, sizeof(WEB_CLIENT_CTX) ); + memset( tHANDLER, 0, sizeof(WEB_HANDLER) ); + tCTX->m_iSocketFID = tSID; + tCTX->m_iEncoderPipe[0] = -1; + tCTX->m_iEncoderPipe[1] = -1; + tCTX->mediaStreamId = 0; + tCTX->bValid = true; + tCTX->ModulePtr = this; +#ifdef DEBUG_EXTRA + LOG("Before Thread Create"); +#endif + int RetVal = pthread_create( &tHANDLER->m_hThreadHandle, NULL, webClientProc, ( void * ) tCTX ); + if( RetVal == -1 ) { + free(tCTX); + free(tHANDLER); + LOG_ERROR("Thread Creation Faled."); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + } else { + tHANDLER->CTX = tCTX; + m_mHandlersProtector.lock(); + m_vHandlersPool.push_back( tHANDLER ); + m_mHandlersProtector.unlock(); +#ifdef DEBUG_EXTRA + LOG("Handler Pushed to a Pool"); +#endif + }; + } else { //https://stackoverflow.com/questions/18545077/image-fullscreen-on-click + free(tCTX); + LOG_ERROR("CL_HANDLER Mem Allocation Failure!"); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + }; + } else { + LOG_ERROR("CL_CTX Mem Allocation Failure!"); + shutdown( tSID, SHUT_RDWR ); + close( tSID ); + }; + }; + }; + }; + // Handle Dead Clients + if( m_vHandlersPool.size() ) { + for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) { + if( !( (*idx)->CTX->bValid ) ) { + pthread_join( (*idx)->m_hThreadHandle, NULL ); + //close( (*idx)->CTX->m_iEncoderPipe[0] ); + close( (*idx)->CTX->m_iEncoderPipe[1] ); + free( (*idx)->CTX ); + free( (*idx) ); + m_mHandlersProtector.lock(); + m_vHandlersPool.erase(idx); + m_mHandlersProtector.unlock(); +#ifdef DEBUG_EXTRA + LOG("Web Handler Ripped!"); +#endif + }; + }; + + }; + // validate active streams ? + + SLEEP( 50 ); + }; +}; + +#define ENABLE_SOCKOPT(sd, level, opt) \ + do { \ + int val = 1; \ + if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \ + warn("Failed enabling %s for web service", #opt); \ + } while (0); + + +bool argusModuleEmbedVideo::startService(){ + m_bEnabled = true; + //Create NoSignal Image + cv::Mat tMat( m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3 ); + cv::rectangle( tMat, cv::Point( 0, 0 ), cv::Point( m_sEmbedVideoData.width, m_sEmbedVideoData.height ), cv::Scalar( 255, 0, 0 ), cv::FILLED ); + cv::putText( tMat, "NO SIGNAL", cv::Point( 10, 30 ), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar( 0, 255, 255 ), 3 ); + if( m_sEmbedVideoData.show_logo ) { + int a_x, a_y; + if( m_sEmbedVideoData.logo_x < 0 ) { + a_x = m_sEmbedVideoData.width + m_sEmbedVideoData.logo_x - m_sEmbedVideoData.logo_w; + if( a_x < 0 ) a_x = 0; + } else a_x = m_sEmbedVideoData.logo_x; + if( ( a_x + m_sEmbedVideoData.logo_w ) > m_sEmbedVideoData.width ) a_x = m_sEmbedVideoData.width - m_sEmbedVideoData.logo_w; + if( m_sEmbedVideoData.logo_y < 0 ) { + a_y = m_sEmbedVideoData.height + m_sEmbedVideoData.logo_y - m_sEmbedVideoData.logo_h; + if( a_y < 0 ) a_y = 0; + } else a_y = m_sEmbedVideoData.logo_y; + if( ( a_y + m_sEmbedVideoData.logo_h ) > m_sEmbedVideoData.height ) a_y = m_sEmbedVideoData.height - m_sEmbedVideoData.logo_h; + if( ( a_x > -1 ) && ( a_y > -1 ) ) { + char tName[256]; + m_sEmbedVideoData.logo_x = a_x; + m_sEmbedVideoData.logo_y = a_y; + sprintf( tName, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5 ); + cv::Mat T = cv::imread( tName, cv::IMREAD_UNCHANGED ); + if( T.cols > 0 ) { + cv::Mat mask; + vector layers; +#ifdef DEBUG + LOG("Logo Loaded OK"); +#endif + cv::split( T, layers); // seperate channels + cv::Mat rgb[3] = { layers[0], layers[1], layers[2] }; + mask = layers[3]; // png's alpha channel used as mask + cv::merge( rgb, 3, T ); // put together the RGB channels, now transp insn't transparent + + cv::resize( T, m_mLogoPic, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC ); + cv::resize( mask, m_mLogoMask, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC ); + + cv::Rect roi(cv::Point( m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y ), cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h )); + cv::Mat destinationROI = tMat( roi ); + m_mLogoPic.copyTo( destinationROI, m_mLogoMask ); + //m_sEmbedVideoData.show_logo = false; + } else { + LOG("Logo Disabled - No Picture is Loaded"); + m_sEmbedVideoData.show_logo = false; + }; + } else { + LOG("Logo Disabled - Wrong Coords"); + m_sEmbedVideoData.show_logo = false; + }; + LOG("Logo Draw OK"); + }; + + try{ + vector compression_params; + //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + //compression_params.push_back(9); + compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); + compression_params.push_back( m_sEmbedVideoData.compression_quality ); + vector buf; + cv::imencode( ".jpg", tMat, buf, compression_params ); + m_nNoSignalSize = buf.size(); + n_pNoSignalData = (uint8_t *) malloc( m_nNoSignalSize ); + if( n_pNoSignalData ) { + memcpy( n_pNoSignalData, buf.data(), m_nNoSignalSize ); + } else m_nNoSignalSize =0; + buf.clear(); + } catch (cv::Exception & e) { + LOG_ERROR(e.msg.c_str()); + }; + + // Socket + struct sockaddr sa; + struct sockaddr_in *sin; + memset(&sa, 0, sizeof(struct sockaddr)); + sa.sa_family = AF_INET; + sin = (struct sockaddr_in *)&sa; + sin->sin_addr.s_addr = htonl( INADDR_ANY ); + sin->sin_port = htons( m_sEmbedVideoData.port ); + + m_nSocketDescriptor = socket( sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); + if( m_nSocketDescriptor == -1 ){ + LOG_ERROR("Failed creating ACC socket"); + return false; + }; + ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEADDR); +#ifdef SO_REUSEPORT + ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEPORT); +#endif + if( bind( m_nSocketDescriptor, &sa, sizeof(sa)) < 0 ){ + LOG_ERROR("Failed binding Socket"); + close( m_nSocketDescriptor ); + return false; + } else { + LOG("Bind Socessfull"); + }; + if( listen( m_nSocketDescriptor, 10) != 0 ){ + LOG_ERROR("Failed setting web listen backlog"); + close( m_nSocketDescriptor ); + return false; + } else { + LOG("Listen OK"); + }; + LOG("Start Thread"); + m_bEnabled = init(); + return m_bEnabled; +}; + +bool argusModuleEmbedVideo::stopService( bool force ){ + m_bEnabled = false; + m_bDetached = uninit(); +#ifdef DEBUG + LOG("Service Thread ended!"); +#endif + if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes +#ifdef DEBUG + char tB[200]; + sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() ); + LOG( tB ); + +#endif + for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) { + if( force ) { +#ifdef DEBUG + LOG("Force Client Handler to Stop!"); +#endif + pthread_cancel( (*index)->m_hThreadHandle ); + } else { +#ifdef DEBUG + LOG("Waiting Client Handler to End!"); +#endif + pthread_join( (*index)->m_hThreadHandle, NULL ); + } + }; + m_vHandlersPool.clear(); + }; +#ifdef DEBUG + LOG("No More Client Handlers!"); +#endif + if( m_mapCAPTURES.size() ){ + m_mapCAPTURES.clear(); + //for( mapSTREAMCAPS::iterator idx = m_mapCAPTURES.begin(); idx < m_mapCAPTURES.end(); idx++ ) { + //}; + }; + if( m_mapMATS.size() ){ + m_mapMATS.clear(); + //for( mapSTREAMMAPS::iterator idx = m_mapMATS.begin(); idx < m_mapMATS.end(); idx++ ) { + //}; + }; + if ( n_pNoSignalData ) { + free( n_pNoSignalData ); + n_pNoSignalData = NULL; + m_nNoSignalSize = 0; + }; + return m_bDetached; +}; + +bool argusModuleEmbedVideo::reloadSettings(){ + LOG("Reload Service"); + if( m_pDBC ){ + DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); + if( tDATA ) { + if( stopService() ){ + LOG("Stoped!"); + memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)); + free( tDATA ); + LOG("Starting..."); + return startService(); + } else { + free( tDATA ); + }; + }; + }; + return false; +}; + +bool argusModuleEmbedVideo::validate(){ + bool RetVal = true; + if( m_pDBC ){ + DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID ); + if( tDATA ) { + if( memcmp( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)) != 0 ){ + free( tDATA ); + LOG("Module Settings Changed!"); + return reloadSettings(); + }; + free( tDATA ); + } else { + RetVal = false; + }; + if ( RetVal ) { + DBC_INT_LIST *tList = m_pDBC->listMediaStreams(0, LIST_VALID_RECORDS); + if ( tList != NULL ) { + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ){ + if( !registerStream( *idx ) ){ + RetVal = false; + break; + }; + }; + delete ( tList ); + }; + }; + if ( RetVal ) { + for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) { + if ( !(*idx).second->validate() ) { + RetVal = false; + }; + }; + }; + } else { + LOG_ERROR( "DB Error!" ); + RetVal = false; + }; + return RetVal; +}; + +bool argusModuleEmbedVideo::registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ){ + if( CTX ){ + if( id ){ + //Check if its Valid! + DBC_MEDIA_STREAM_DATA *tSD = m_pDBC->getMediaStreamData( id ); + if( tSD ) { + //if( !tSD->valid ) { + // free( tSD ); + // return false; + //}; + free( tSD ); + //if( pipe( CTX->m_iEncoderPipe ) == -1 ){ + // CTX->bValid = false; + // return false; + //}; + CTX->mediaStreamId = id; + return true; + }; + }; + } else LOG_ERROR("Client Context error!"); + return false; +}; + +void argusModuleEmbedVideo::dispatchEvent( EVENT_CONTAINER *Evt ){ + if( Evt ) { + switch( Evt->m_eClass ) { + case EVT_CLASS_IMAGE: + case EVT_CLASS_VIDEO:{ + switch( Evt->m_eType ) { + case EVT_CAPTURE_START:{ +#ifdef DEBUG + LOG("Capture Event"); +#endif + if( Evt->m_ref_id && Evt->m_db_id ){ + uint32_t tPicID = saveStreamPicture( Evt->m_ref_id ); + if( tPicID ){ + // + //m_pDBC->addPictureEvent( Evt->m_db_id, tPicID ); + } else { +#ifdef DEBUG + LOG_ERROR("No Picture is Saved!"); +#endif + }; + } else { +#ifdef DEBUG + LOG_ERROR("No Stream ID or Event ID in Event Data!"); +#endif + }; + break; + }; + }; + break; + }; + case EVT_CLASS_CAMERA_CTRL:{ + switch ( Evt->m_eType ) { + case EVT_CAMERA_MOVE_TO:{ + uint32_t sid = m_pDBC->getNodeAuxParam( Evt->m_nSourceNodeID ); + if ( sid ) { + mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find(sid); + if( hnd != m_mapHANDLERS.end() ){ + (*hnd).second->triggerCamMove(); + }; + } + break; + }; + case EVT_CAMERA_ON_POSITION:{ +#ifdef DEBUG + LOG("Cam On Position After Event -> Capture Picture"); +#endif + DBC_SNAPSHOT_DATA *tData = (DBC_SNAPSHOT_DATA *) Evt->m_pEvtData; + if( tData ){ + if( !saveStreamPicture( tData ) ) LOG_ERROR("Save Error!"); + tData->assoc_event_ids.clear(); + delete( tData ); + Evt->m_pEvtData = NULL; + } else LOG_ERROR("No Evt Data!"); + break; + }; + }; + break; + }; + }; + }; +}; +//https://www.ps2-home.com/forum/viewtopic.php?t=98 +//https://www.mikekohn.net/software/playstation2.php + +bool argusModuleEmbedVideo::saveStreamPicture( DBC_SNAPSHOT_DATA *ptr ){ + + if( ptr == NULL ) return false; + + if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){ + LOG("Saving Picture!"); + if( ptr->assoc_event_ids.size() ){ + if( m_mapCAPTURES.find( ptr->stream_id ) != m_mapCAPTURES.end() ){ + m_mPictureProtector.lock(); + ptr->data = (uint8_t *) malloc( m_mapCAPTURES[ptr->stream_id].size() ); + if( ptr->data ){ + ptr->data_size = m_mapCAPTURES[ptr->stream_id].size(); + memcpy( ptr->data, m_mapCAPTURES[ptr->stream_id].data(), ptr->data_size ); + m_mPictureProtector.unlock(); + CSTR MD5 = MD5Binary( ptr->data, ptr->data_size ); + if( MD5 ){ + strncpy( ptr->md5, MD5, 32 ); + free( MD5 ); + if( !m_pDBC->addPicture( ptr, "jpg" ) ) LOG_ERROR("Database Error to consume capture!"); + } else LOG_ERROR("no MD5 Hash!"); + free( ptr->data ); + } else { + m_mPictureProtector.unlock(); + LOG_ERROR("No memory to allocate!"); + }; +#ifdef DEBUG + } else { + LOG("No apropriate Stream Found!"); +#endif + }; + }; + }; + if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO ){ + LOG("Saving Video!"); + if( ptr->assoc_event_ids.size() ){ + mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find( ptr->stream_id ); + if( hnd != m_mapHANDLERS.end() ){ + uint32_t db_id; + uint32_t cfrm; + if( (*hnd).second->triggerEvent( db_id, cfrm ) ){ + for( DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++ ){ + m_pDBC->addVideoEvent( (*idx), db_id, cfrm ); + }; + }; + }; + }; + }; + return true; +}; + +bool argusModuleEmbedVideo::saveStreamPicture( uint32_t id ){ + if( !id ) return false; + if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){ + if( m_mapCAPTURES.find(id) != m_mapCAPTURES.end() ){ + FILE * tFD; + m_mPictureProtector.lock(); + size_t tBufferSize = m_mapCAPTURES[id].size(); + uint8_t * tBuffer = (uint8_t *) malloc( tBufferSize ); + if( tBuffer ){ + memcpy( tBuffer, m_mapCAPTURES[id].data(), tBufferSize ); + m_mPictureProtector.unlock(); + CSTR MD5 = MD5Binary( tBuffer, tBufferSize ); + if( MD5 ){ + char tFileName[MAX_PATH]; + if( generateSavePicPath( MD5, tFileName ) ){ + FILE *fd = fopen( tFileName, "wb+" ); + if( fd ){ + fwrite(tBuffer, 1, tBufferSize, fd ); + fclose(fd); + chown( tFileName, "nobody", "nogroup" ); + //retVal = m_pDBC->addPicture( id, MD5, "jpg" ); + } else LOG_ERROR("Can not open picture file!"); + } else LOG_ERROR("Can not generate file name!"); + free(MD5); + } else LOG_ERROR("no MD5 Hash!"); + free(tBuffer); + } else { + m_mPictureProtector.unlock(); + LOG_ERROR("no memory to allocate!"); + }; + }; + } + return true; +}; + +int argusModuleEmbedVideo::getWidh( void ){ + if( m_sEmbedVideoData.width ) return m_sEmbedVideoData.width; + return -1; +}; + +int argusModuleEmbedVideo::getHeight( void ){ + if( m_sEmbedVideoData.height ) return m_sEmbedVideoData.height; + return -1; +}; + +bool argusModuleEmbedVideo::generateSavePicPath( CSTR MD5, CSTR Output ){ + if( MD5 == NULL ) return false; + if( Output == NULL ) return false; + if( !fileExist( m_pBaseSavePath ) ) { + LOG_ERROR("No Base Picture Save Path Defined!"); + return false; + }; + if( strlen(MD5) < 4 ) return false; + char test[MAX_PATH]; + sprintf( test, "%s/%c%c", m_pBaseSavePath, MD5[0], MD5[1] ); + if( !fileExist( test ) ) { +#ifdef __linux__ + mkdir( test, STORAGE_DIR_MODE ); +#else + _mkdir( test ); +#endif + chown( test, "nobody", "nogroup" ); + }; + sprintf( test, "%s/%c%c/%c%c", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3] ); + if( !fileExist( test ) ) { +#ifdef __linux__ + mkdir( test, STORAGE_DIR_MODE ); +#else + _mkdir( test ); +#endif + chown( test, "nobody", "nogroup" ); + }; + sprintf( Output, "%s/%c%c/%c%c/%s.jpg", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3], MD5 ); + return true; +}; + +bool argusModuleEmbedVideo::registerStream( uint32_t streamID ){ + //Check if stream is not allready exists + //for ( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ){ + // if ( (*idx)->CTX->mediaStreamId == streamID ) return true; + //}; + + try { + streamHandler * tData = m_mapHANDLERS.at( streamID ); + if( tData!= NULL ) return true; + } catch (const std::out_of_range& oor ) { + //std::cerr << "Out of Range error: " << oor.what() << '\n'; + m_mapHANDLERS[streamID] = new streamHandler( this ); + if ( m_mapHANDLERS[streamID] != NULL ) return m_mapHANDLERS[streamID]->create( streamID ); + }; + return false; +}; + +bool argusModuleEmbedVideo::unregisterStream( uint32_t streamID ){ + return true; +}; + +#undef LOG +#undef LOG_ERROR + +#define LOG( X ) streamHandler::m_pLog->Log( "MEV_STR", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, X ); +#endif + + +streamHandler::streamHandler( argusModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_pMaster( ptr ), m_eWM( M ), basicMediaDestination() { + m_pLog = basicLogCollection::getInstance( ); + memset( &m_sStreamData, 0, sizeof( DBC_MEDIA_STREAM_DATA ) ); + m_pSource = NULL; + m_bEvtMarkerCounter = 0; + m_bCamMoveCounter = 0; +#ifdef EVE_ENABLE_VIDEO + m_nPreAlarmFrames = 0; + m_nPostAlarmFrames = 0; + m_nSegAFrameCounter = 0; + m_nSegBFrameCounter = 0; + m_nGlobalFrameCounter = 0; + m_nVideoRegisteredDBID = 0; + m_nSegAShiftFrames = 0; + m_nSegBShiftFrames = 0; + m_nSegASkippedFrames = m_nSegBSkippedFrames = 0; + m_nSegmentLimitFrames = 0; + m_nHardLimitFrames = 0; + m_bActiveEncoderStream = 0; + m_bSegAActive = false; + m_bSegADelete = true; + m_bSegBActive = false; + m_bSegBDelete = true; + m_bCOP = 0; +#endif //EVE_ENABLE_VIDEO +}; + +streamHandler::~streamHandler(){ + LOG("DESTRUCT!"); + if ( m_sStreamData.id ) { + if (m_pMaster != NULL) m_pMaster->unregisterStream(m_sStreamData.id); + if ( m_pSource != NULL ) { + switch( m_sStreamData.source_type[0] ) { + case 'D': delete( ( videoLIVE555Source *) m_pSource ); break; + case 'A': delete( ( videoAVLIBSource *) m_pSource ); break; + }; + }; +#ifdef EVE_ENABLE_VIDEO + closeAll(); +#endif //EVE_ENABLE_VIDEO + }; + +}; + +bool streamHandler::create( uint32_t stremID ){ + if( stremID ) { + DBC_MEDIA_STREAM_DATA *tData = mojoDBC::getInstance()->getMediaStreamData( stremID ); + if ( tData ) { + memcpy( &m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA)); + free(tData); + DBC_CAM_DATA *tCAM = mojoDBC::getInstance()->getCamData( m_sStreamData.source_id ); + if( tCAM ){ + CSTR tNAM = mojoDBC::getInstance()->getNodeName( tCAM->node_id ); + m_sSourceDesc.mediaStreamId = stremID; + m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; + if ( tNAM!= NULL ) { + strncpy(m_sSourceDesc.mediaName, tNAM, 127 ); + m_sSourceDesc.mediaName[127] = (char)0; + free( tNAM ); + } else { + sprintf(m_sSourceDesc.mediaName, "No Name Cam"); + }; + + switch( m_sStreamData.source_type[0] ) { + case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource( &m_sSourceDesc ); break; + case 'D': m_pSource = (basicMediaSource *) new videoLIVE555Source( &m_sSourceDesc ); break; + }; + if( m_pSource != NULL ) { + char tMRL[1024]; + #ifdef DEBUG + LOG("Source OK"); + #endif + int tW = m_pMaster->getWidh(); + int tH = m_pMaster->getHeight(); + int pix = -1; + bool in_16_9 = (((m_sStreamData.width*100) / m_sStreamData.height ) > 140 ); + bool out_16_9 = (((tW*100) / tH ) > 140 ); + //if( tW > 0 ){ + // //m_pSource->setProportionalByWidth( tW ); + // m_pSource->setSize( tW, tH ); + //}; + if( in_16_9 != out_16_9 ){ + if( in_16_9 ){ + tH = ((( tW * 1000 ) / 16 ) * 9 ) / 1000; + } else { + tW = ((( tH * 1000 ) / 3 ) * 4 ) / 1000; + }; + }; + if (strncmp( m_sStreamData.mrl_proto, "v4l2", 4) == 0) { + sprintf( tMRL, m_sStreamData.mrl ); + } else { + sprintf( tMRL, "%s://%s:%s@%s:%d%s", m_sStreamData.mrl_proto, tCAM->username, tCAM->password, tCAM->ip, m_sStreamData.mrl_port, m_sStreamData.mrl ); + }; + LOG( tMRL ); + if( m_pSource->_open( tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH ) ){ + if( !m_pSource->attachDestination( this ) ){ + delete( m_pSource ); + m_pSource = NULL; + } else { +#ifdef DEBUG + LOG("Source is Connected to Output."); +#endif + }; + } else { + LOG_ERROR("Can not Open Video Source!"); + delete( m_pSource ); + m_pSource = NULL; + }; + } else { + LOG_ERROR("Video Source Stream Failure!"); + }; + free( tCAM ); + } else { + LOG_ERROR("Error Getting CAM Data!"); + m_pSource = NULL; + return false; + }; + }; + }; + + if( m_pSource ){ +#ifdef EVE_ENABLE_VIDEO + return initVideoOutput(); +#else + return true; +#endif // EVE_ENABLE_VIDEO + }; + + return false; +}; + +bool streamHandler::pushFrame( AVFrame *Frame, void* src){ + if( m_pMaster == NULL ) return false; + MEDIA_SOURCE_DESC *tMD = (MEDIA_SOURCE_DESC *)src; + if( tMD ) { + }; + return true; +}; + +bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ + if( m_pMaster == NULL ) return false; + MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; + char tBuffer[128]; + if( tMD ) { + float mK, oK; + cv::Rect ROI; + + m_pMaster->m_mPictureProtector.lock(); + + if( m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0 ) { + LOG("First Frame Enqueued"); + sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId ); + LOG( tBuffer ); + + m_pMaster->m_mapMATS[tMD->mediaStreamId].create( + m_pMaster->m_sEmbedVideoData.height, + m_pMaster->m_sEmbedVideoData.width, + CV_8UC3 + ); + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Point( 0, 0 ), + cv::Point( + m_pMaster->m_sEmbedVideoData.height, + m_pMaster->m_sEmbedVideoData.width + ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + }; +#ifdef USE_SCALING_IN + oK = ((float)m_pMaster->m_sEmbedVideoData.height )/ ((float)m_pMaster->m_sEmbedVideoData.width); + mK = ((float)Frame.rows )/ ((float)Frame.cols); + //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK ); + if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) { + ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; + ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; + ROI.x = (int) 0; + ROI.y = (int) 0; + } else { + if( mK < oK ) { + ROI.width = (int) m_pMaster->m_sEmbedVideoData.width; + ROI.height = (int) (((float)m_pMaster->m_sEmbedVideoData.width) * mK ); + ROI.x = (int) 0; + ROI.y = (int)( m_pMaster->m_sEmbedVideoData.height - ROI.height ) >> 1; + } else { + ROI.height = (int) m_pMaster->m_sEmbedVideoData.height; + ROI.width = (int) (((float)m_pMaster->m_sEmbedVideoData.height) / mK ); + ROI.y = (int) 0; + ROI.x = (int) ( m_pMaster->m_sEmbedVideoData.width - ROI.width ) >> 1; + }; + }; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); + cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR ); +#else + if(( m_pMaster->m_sEmbedVideoData.height==Frame.rows )&&( m_pMaster->m_sEmbedVideoData.width==Frame.cols )){ + Frame.copyTo( m_pMaster->m_mapMATS[tMD->mediaStreamId] ); + } else { + //Mat dst_roi = dst(Rect(left, top, src.cols, src.rows)); + //src.copyTo(dst_roi); + + if (m_pMaster->m_sEmbedVideoData.width == Frame.cols ) { + ROI.width = Frame.cols; + ROI.height = Frame.rows; + ROI.x = 0; + ROI.y = ( m_pMaster->m_sEmbedVideoData.height - Frame.rows ) >> 1; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); + Frame.copyTo(mROI); + } else { + ROI.width = Frame.cols; + ROI.height = Frame.rows; + ROI.x = ( m_pMaster->m_sEmbedVideoData.width - Frame.cols ) >> 1; + ROI.y = 0; + cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI ); + Frame.copyTo(mROI); + }; + }; +#endif + if ( m_bCamMoveCounter > m_bEvtMarkerCounter ) { + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Rect( 10, 10, 20, 20 ), + cv::Scalar( m_bCamMoveCounter, 0, 0 ), + cv::FILLED + ); + m_bCamMoveCounter -=4; + if ( m_bCamMoveCounter < 4 ) m_bCamMoveCounter = 0; + } else { + if ( m_bEvtMarkerCounter ) { + m_bCamMoveCounter = 0; + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Rect( 10, 10, 20, 20 ), + cv::Scalar( 0, 0, m_bEvtMarkerCounter ), + cv::FILLED + ); + m_bEvtMarkerCounter -=4; + if ( m_bEvtMarkerCounter < 4 ) m_bEvtMarkerCounter = 0; + }; + }; + if (m_pMaster->m_sEmbedVideoData.show_label) { + time_t t = time( NULL ); + struct tm * tmp = gmtime( &t ); + if( tmp ){ + char tsb[64]; + if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){ + + sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb ); + int baseline=0; + cv::Size textSize = cv::getTextSize( tBuffer, + m_pMaster->m_sEmbedVideoData.label_font_face, + m_pMaster->m_sEmbedVideoData.label_font_scale, + m_pMaster->m_sEmbedVideoData.label_font_thickness, + &baseline + ); + int x = m_pMaster->m_sEmbedVideoData.label_x; + int y = m_pMaster->m_sEmbedVideoData.label_y; + if( x < 0 ) { + x = m_pMaster->m_sEmbedVideoData.width+x-textSize.width; + }; + if( y < 0 ) { + y = m_pMaster->m_sEmbedVideoData.height+y-baseline;// + }; + if( !m_pMaster->m_sEmbedVideoData.label_transperant ) { + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + }; + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( x, y ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face, + m_pMaster->m_sEmbedVideoData.label_font_scale, + cv::Scalar( 0, 255, 0 ), + m_pMaster->m_sEmbedVideoData.label_font_thickness, + m_pMaster->m_sEmbedVideoData.label_line_type + ); + }; + }; + } else { + if( m_pMaster->m_sEmbedVideoData.show_ts ){ + time_t t = time( NULL ); + struct tm * tmp = gmtime( &t ); + if( tmp ){ + if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){ + uint8_t shift_x = 0; + uint8_t shift_y = 15; + if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) { + if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { + shift_y = 15; + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x, + m_pMaster->m_sEmbedVideoData.ts_y + ), + cv::Point( 490, 60 ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + } else { + shift_y = 23; + cv::rectangle( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x, + m_pMaster->m_sEmbedVideoData.ts_y + ), + cv::Point( 490, 60 ), + cv::Scalar( 0, 0, 0 ), + cv::FILLED + ); + }; + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 255, 255 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + } else { + if( m_pMaster->m_sEmbedVideoData.ts_font_face ) { + shift_y = 15; + } else { + shift_y = 23; + }; + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2 + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 0, 0 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + cv::putText( + m_pMaster->m_mapMATS[tMD->mediaStreamId], + tBuffer, + cv::Point( + m_pMaster->m_sEmbedVideoData.ts_x + shift_x, + m_pMaster->m_sEmbedVideoData.ts_y + shift_y + ), + (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face, + m_pMaster->m_sEmbedVideoData.ts_font_scale, + cv::Scalar( 0, 255, 255 ), + m_pMaster->m_sEmbedVideoData.ts_font_thickness, + m_pMaster->m_sEmbedVideoData.ts_line_type + ); + } + }; + }; + }; + }; + if( m_pMaster->m_sEmbedVideoData.show_logo ){ + cv::Rect roi( + cv::Point( + m_pMaster->m_sEmbedVideoData.logo_x, + m_pMaster->m_sEmbedVideoData.logo_y + ), + cv::Size( + m_pMaster->m_sEmbedVideoData.logo_w, + m_pMaster->m_sEmbedVideoData.logo_h + ) + ); + cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi ); + m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask ); + }; + + vector compression_params; + //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + //compression_params.push_back(9); + compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); + compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality ); + + m_pMaster->m_mEncodedProtector.lock(); + + m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear(); + cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params ); + m_pMaster->m_mEncodedProtector.unlock(); + +#ifdef EVE_ENABLE_VIDEO + // encode Video Stream + + + //m_nPreAlarmFrames + //m_nPostAlarmFrames + //m_nNoAlarmSegmentFrames + //m_nSegmentLimitFrames + //m_nHardLimitFrames + + if ( m_bSegAActive || m_bSegBActive ) { + m_mFrameCounterProtector.lock(); + + if( m_bSegAActive ){ + do { + //In Any Case Close Stream if it Long enough + if( m_nSegAFrameCounter > m_nHardLimitFrames ){ + LOG("HardLimit Reached!(A)"); + closeSegmentA(); + break; + }; + if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){ + if ( !m_bSegBActive ){ + LOG("Start Alt!(A)"); + openSegmentB(); + }; + }; + if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && !m_bActiveEncoderStream ){ + LOG("Swap Active!(A)"); + swapActiveStreams(); + break; + }; + } while ( 0 ); + }; + + if( m_bSegBActive ) { + do { + //In Any Case Close Stream if it Long enough + if( m_nSegBFrameCounter > m_nHardLimitFrames ){ + LOG("HardLimit Reached!(B)"); + closeSegmentB(); + break; + }; + if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){ + if ( !m_bSegAActive ){ + LOG("Start Alt!(B)"); + openSegmentA(); + }; + }; + if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && m_bActiveEncoderStream ){ + LOG("Swap Active!(B)"); + swapActiveStreams(); + break; + }; + } while ( 0 ); + }; + + m_mFrameCounterProtector.unlock(); + + ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER)); + if ( tData ) { + tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize(); + tData->linesize[1] = 0; + tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; + tData->size = tData->linesize[0]*tData->rows; + tData->data[1] = NULL; + tData->data[0] = (uint8_t *)malloc( tData->size ); + if ( tData->data[0] ) { + memcpy( tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size ); + m_mEncodingQueueProtector.lock(); + m_qEncodingQueue.push( tData ); + m_mEncodingQueueProtector.unlock(); + } else { + LOG_ERROR("MAT_CPY malloc Error!"); + free( tData ); + }; + } else LOG_ERROR("ENC_BUF malloc Error!"); + }; +#endif // EVE_ENABLE_VIDEO + m_pMaster->m_mPictureProtector.unlock(); + } else { + LOG_ERROR("No PayLoad!"); + }; + return true; +}; + +void streamHandler::closeSegmentA( void ){ + m_mCurrentOperationProtector.lock(); + if ( m_bCOP == 0 ) m_bCOP = 0x01; + m_mCurrentOperationProtector.unlock(); + LOG("Closing Stream A"); +}; + +void streamHandler::closeSegmentB( void ){ + m_mCurrentOperationProtector.lock(); + if ( m_bCOP == 0 ) m_bCOP = 0x02; + m_mCurrentOperationProtector.unlock(); + LOG("Closing Stream B"); +}; + +void streamHandler::closeAll(){ + waitThreadEnd( true ); + avcodec_send_frame( m_pCodecCtx, NULL ); + int ret = 0; + AVPacket *avp = av_packet_alloc(); + if ( avp ) { + do { + av_packet_unref( avp ); + ret = avcodec_receive_packet( m_pCodecCtx, avp ); + if ( !ret ) { + if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp ); + if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp ); + }; + } while ( !ret ); + av_packet_unref( avp ); + av_packet_free( &avp ); + }; + if ( m_bSegAActive ) { + av_write_trailer(m_pFormatCtxA); + avformat_close_input( &m_pFormatCtxA ); + m_bSegAActive = false; + }; + if ( m_bSegBActive ) { + av_write_trailer(m_pFormatCtxB); + avformat_close_input( &m_pFormatCtxB ); + m_bSegBActive = false; + }; +}; + +bool streamHandler::openSegmentA( void ){ + if( !m_bSegAActive ){ + CSTR tAM = getUniqID_MD5(); + if ( tAM ) { + sprintf( m_cSegNameA, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER ); + strncpy( m_cSegMD5A, tAM, 32 ); + m_cSegMD5A[32] = (char)0; + free( tAM ); + #ifdef DEBUG + LOG("Opening Stream A"); + LOG(m_cSegNameA); + char tB[128]; + sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts ); + LOG( tB ); + sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration ); + LOG( tB ); + #endif + m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1; + if (m_pVideoStrA->nb_frames) { + m_pVideoStrA->nb_frames = 0; + m_pVideoStrA->start_time = 0; + m_pVideoStrA->first_dts = 0; + m_pFormatCtxA->start_time = 0; + }; + if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) { + LOG_ERROR("Could not open output file."); + return m_bSegAActive; + }; + if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){ + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegAActive; + }; + //m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter = 0; + m_nSegAShiftFrames = 0; + m_bSegAActive = true; + m_bSegADelete = true; + //m_mFrameCounterProtector.unlock(); + #ifdef DEBUG + LOG("Stream A Opened"); + #endif + }; + }; + return m_bSegAActive; +}; + +bool streamHandler::openSegmentB( void ){ + if( !m_bSegBActive ){ + CSTR tAM = getUniqID_MD5(); + if ( tAM ) { + sprintf( m_cSegNameB, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER ); + strncpy( m_cSegMD5B, tAM, 32 ); + m_cSegMD5B[32] = (char)0; + free( tAM ); + #ifdef DEBUG + LOG("Opening Stream B"); + LOG(m_cSegNameB); + char tB[128]; + sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts ); + LOG( tB ); + sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration ); + LOG( tB ); + #endif + m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1; + if (m_pVideoStrB->nb_frames) { + m_pVideoStrB->nb_frames = 0; + m_pVideoStrB->start_time = 0; + m_pVideoStrB->first_dts = 0; + m_pFormatCtxB->start_time = 0; + }; + if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){ + LOG_ERROR("Could not open output file."); + return m_bSegBActive; + }; + if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){ + LOG_ERROR("Error occurred when writing header to output file."); + return m_bSegBActive; + }; + //m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter = 0; + m_nSegBShiftFrames = 0; + m_bSegBActive = true; + m_bSegBDelete = true; + //m_mFrameCounterProtector.unlock(); + #ifdef DEBUG + LOG("Stream B Opened"); + #endif + }; + }; + return m_bSegBActive; +}; + +bool streamHandler::initVideoOutput(){ + m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; + m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; + m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000; + m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000; + + if( !initLibAV() ) return false; + + m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL ); + + if ( m_pFormat == NULL ) { + LOG_ERROR("Out VideoFormat Not Found!"); + return false; +#ifdef DEBUG + } else { + LOG("Output video Format"); + LOG( VIDEO_OUTPUT_CONTAINER ); +#endif + }; + + if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("Format CTX A alloc error!"); + av_free( m_pFormat ); + return false; + } else { + av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 ); + m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) { + LOG_ERROR("Format CTX B alloc error!"); + avformat_free_context( m_pFormatCtxA ); + //av_free( m_pFormat ); + return false; + } else { + av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 ); + m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT; + }; + + m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC ); + if( m_pVideoCodec == NULL ){ + LOG_ERROR("Out VideoCodec Not Found!"); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + //av_free( m_pFormat ); + return false; +#ifdef DEBUG + } else { + LOG("Out Video Codec Found"); +#endif + }; + + m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec ); + if ( m_pCodecCtx == NULL){ + LOG_ERROR("Out VideoCodec Context Memory Allocation Error"); + av_free( m_pVideoCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + //av_free( m_pFormat ); + return false; +#ifdef DEBUG + } else { + LOG("Out Codec Context3 Allocated"); +#endif + }; + + m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec ); + if ( m_pVideoStrA == NULL){ + LOG_ERROR("VideoStream A Not Created!"); + avcodec_free_context( &m_pCodecCtx ); + av_free( m_pCodecCtx ); + av_free( m_pVideoCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + //av_free( m_pFormat ); + return false; +#ifdef DEBUG + } else { + LOG("VideoStream A is Created"); +#endif + }; + + m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec ); + if ( m_pVideoStrB == NULL){ + LOG_ERROR("VideoStream B Not Created!"); + avcodec_free_context( &m_pCodecCtx ); + av_free( m_pCodecCtx ); + av_free( m_pVideoCodec ); + avformat_free_context( m_pFormatCtxA ); + avformat_free_context( m_pFormatCtxB ); + av_free( m_pFormat ); + return false; +#ifdef DEBUG + } else { + LOG("VideoStream B is Created"); +#endif + }; + + m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC; + m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO; + m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE; + //m_pCodecCtx->thread_count = 1; + //m_pCodecCtx->bit_rate_tolerance = 1; + //m_pCodecCtx->global_quality = 100; + //m_pCodecCtx->compression_level = 2; + m_pCodecCtx->max_b_frames=1; + m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width; + m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height; + m_pCodecCtx->time_base.num = 1; + m_pCodecCtx->time_base.den = m_sStreamData.fps; + m_pCodecCtx->framerate.num = m_sStreamData.fps; + m_pCodecCtx->framerate.den = 1; + + //https://pastebin.com/yG37YhWW + + //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec + //G@ avcodec encode NALU mp4 + +#if (LIBAVCODEC_VERSION_MAJOR > 54) + m_pCodecCtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC ); +#endif + m_pFormatOpts = NULL; + + // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate + + if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){ +#ifdef DEBUG + LOG("Begin Options!"); +#endif + //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html + //Set format's privater options, to be passed to avformat_write_header() + + /* + + mp4 muxer AVOptions: + -movflags E..... MOV muxer flags (default 0) + rtphint E..... Add RTP hint tracks + empty_moov E..... Make the initial moov atom empty (not supported by QuickTime) + frag_keyframe E..... Fragment at video keyframes + separate_moof E..... Write separate moof/mdat atoms for each track + frag_custom E..... Flush fragments on caller requests + isml E..... Create a live smooth streaming feed (for pushing to a publishing point) + faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file + omit_tfhd_offset E..... Omit the base data offset in tfhd atoms + delay_moov ?? + -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0) + -rtpflags E..... RTP muxer flags (default 0) + latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC + rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263 + skip_rtcp E..... Don't send RTCP sender reports + h264_mode0 E..... Use mode 0 for H264 in RTP + send_bye E..... Send RTCP BYE packets when finishing + -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1) + -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1) + -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1) + -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0) + -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0) + -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0) + -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0) + -use_editlist E..... use edit list (from -1 to 1) (default -1) + -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0) + + + */ + if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){ + LOG_ERROR( "av_dict_set movflags!"); +#ifdef DEBUG + } else { + LOG("MOV FLAG SET!"); +#endif + }; + + //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){ + // LOG_ERROR( "av_dict_set live!" ); + //}; + + //default brand is "isom", which fails on some devices + if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){ + LOG_ERROR( "av_dict_set brand!" ); + }; + //m_pCodecCtx->max_b_frames = 1; + //m_pCodecCtx->level = 31; + + m_pCodecCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames + /// P-frames, generated by referencing data from prev and future frames. + /// [Compression up, CPU usage up] + /// [use 3/gop] + m_pCodecCtx->max_b_frames = 5; + + /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video. + /// [use 3–5 ref per P] + m_pCodecCtx->refs = 3; + + /// Compression efficiency (slower -> better quality + higher cpu%) + /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow] + /// Set this option to "ultrafast" is critical for realtime encoding + av_opt_set( m_pCodecCtx->priv_data, "preset", "ultrafast", 0); + //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 ); + //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 ); + + + /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy + /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding + av_opt_set( m_pCodecCtx->priv_data, "crf", "32", 0); + + /// Change settings based upon the specifics of input + /// [psnr, ssim, grain, zerolatency, fastdecode, animation] + /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet. + av_opt_set( m_pCodecCtx->priv_data, "tune", "zerolatency", 0); + + /// Disable b-pyramid. CLI options for this is "-b-pyramid 0" + /// Because Quicktime (ie. iOS) doesn't support this option + av_opt_set( m_pCodecCtx->priv_data, "b-pyramid", "0", 0 ); +#ifdef DEBUG + LOG("End Options!"); +#endif + } else { + if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + }; + + + + + const AVRational dst_fps = { m_sStreamData.fps, 1 }; + +#ifdef DEBUG + char TB[129]; + sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den ); + LOG(TB); +#endif + + m_pVideoStrA->time_base = m_pCodecCtx->time_base; + m_pVideoStrB->time_base = m_pCodecCtx->time_base; + + + //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec ); + + //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width; + //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height; + //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + + //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec ); + + //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width; + //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height; + //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps); + m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps; + + //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + + avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecCtx ); + //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata; + //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecCtx ); + //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT; + //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata; + //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size; + + if ( avcodec_is_open( m_pCodecCtx ) == 0 ) { + LOG("output codec context is closed, opening"); + if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) { + LOG_ERROR("Error opening2 encoder"); + return false; +#ifdef DEBUG + } else { + LOG("output codec context is opened"); + }; +#endif +#ifdef DEBUG + } else { + LOG("output codec context is already opened"); +#endif + }; + m_pConvertCtx = sws_getContext( + m_pMaster->m_sEmbedVideoData.width, + m_pMaster->m_sEmbedVideoData.height, + AV_PIX_FMT_BGR24, + m_pMaster->m_sEmbedVideoData.width, + m_pMaster->m_sEmbedVideoData.height, + VIDEO_OUTPUT_PIX_FMT, + SWS_FAST_BILINEAR, + NULL, + NULL, + NULL + ); + if ( m_pConvertCtx == NULL ) { + return false; + } + m_pAVFrame = av_frame_alloc(); + if ( m_pAVFrame == NULL ) { + return false; + }; + m_pOutBuffer = (uint8_t *)av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, BUFFER_ALIGN)); + if( m_pOutBuffer == NULL ) { + return false; + }; + m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width; + m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height; + m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT; + //av_frame_get_buffer( m_pAVFrame, 0 ); + av_image_fill_arrays ( m_pAVFrame->data, m_pAVFrame->linesize, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, 1 ); + + //av_frame_make_writable( m_pAVFrame ); + + return init(); +}; + +//encoding thread + +void streamHandler::m_fThreadProc( void ){ + AVPacket mPacket; + int bGotPacket; + int rVal = 0; + char tB[128]; + + av_init_packet( &mPacket ); + while( m_bThreadStatus != TH_ENDED ){ + //At the begining All streams are closed --> try to Open + if( m_bThreadStatus < TH_WORKING ){ + if( !openSegmentA() ){ + m_bThreadStatus = TH_ENDED; + continue; + }; + //if( !openSegmentB() ){ + // m_bThreadStatus = TH_ENDED; + // continue; + //}; + m_bThreadStatus = TH_WORKING; + continue; + }; + + m_mEncodingQueueProtector.lock(); + if ( m_qEncodingQueue.size() ) { + ENCODING_BUFFER *tData = m_qEncodingQueue.front(); + if( tData ){ + //av_frame_make_writable( m_pAVFrame ); + sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize ); + free( tData->data[0] ); + free( tData ); + m_qEncodingQueue.pop(); + /* + + + AV_PICTURE_TYPE_NONE Undefined. + AV_PICTURE_TYPE_I Intra. + AV_PICTURE_TYPE_P Predicted. + AV_PICTURE_TYPE_B Bi-dir predicted. + AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4. + AV_PICTURE_TYPE_SI Switching Intra. + AV_PICTURE_TYPE_SP Switching Predicted. + AV_PICTURE_TYPE_BI BI type. + + + */ + if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) { + m_pAVFrame->key_frame = 1; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I; + } else { + m_pAVFrame->key_frame = 0; + m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE; + }; + m_pAVFrame->pts = m_nGlobalFrameCounter + 1; + + rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame ); + m_mFrameCounterProtector.lock(); + m_nGlobalFrameCounter++; + if ( m_bSegAActive ) m_nSegAFrameCounter++; + if ( m_bSegBActive ) m_nSegBFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; + m_mEncodingQueueProtector.unlock(); + } else { + m_mEncodingQueueProtector.unlock(); + // If No Encode Job -> Test Commands! + m_mCurrentOperationProtector.lock(); + switch ( m_bCOP ) { + case 0x01:{ + m_bSegAActive = false; + if ( !m_bSegADelete ) { + av_write_trailer( m_pFormatCtxA ); + avio_close( m_pFormatCtxA->pb ); +#ifdef DEBUG + LOG("Stream A is Closed"); +#endif + } else { +#ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer( m_pFormatCtxA ); +#endif + avio_close( m_pFormatCtxA->pb ); +#ifndef EVE_DONT_DELETE_SEGMENTS + unlink( m_cSegNameA ); +#endif +#ifdef DEBUG + LOG("Stream A is Deleted!"); +#endif + }; + break; + }; + case 0x02:{ + m_bSegBActive = false; + if ( !m_bSegBDelete ) { + av_write_trailer( m_pFormatCtxB ); + avio_close( m_pFormatCtxB->pb ); +#ifdef DEBUG + LOG("Stream B is Closed"); +#endif + } else { +#ifdef EVE_DONT_DELETE_SEGMENTS + av_write_trailer( m_pFormatCtxB ); +#endif + avio_close( m_pFormatCtxB->pb ); +#ifndef EVE_DONT_DELETE_SEGMENTS + unlink( m_cSegNameB ); +#endif +#ifdef DEBUG + LOG("Stream B is Deleted!"); +#endif + }; + break; + }; + }; + m_bCOP = 0; + m_mCurrentOperationProtector.unlock(); + }; + do { + mPacket.data = NULL; + mPacket.size = 0; + rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket ); + if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){ + break; + } else if( rVal < 0 ){ + LOG_ERROR( "Error during encoding " ); + m_bThreadStatus = TH_ENDED; + break; + }; + if( !rVal ){ + if ( m_bSegAActive ) { + mPacket.stream_index = m_pVideoStrA->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + //mPacket.pts = AV_NOPTS_VALUE; + //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + mPacket.dts = mPacket.pts; + int rc = av_write_frame( m_pFormatCtxA, &mPacket ); + if( rc < 0 ){ + //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Trouble with Video Output A!"); + av_strerror( rc, tB, 128 ); + LOG_ERROR( tB ); + break; //continue (changed since embed into do-while) + }; + }; + if ( m_bSegBActive ) { + mPacket.stream_index = m_pVideoStrB->index; + mPacket.duration = 1; + mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base ); + //mPacket.pts = AV_NOPTS_VALUE; + //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base ); + mPacket.dts = mPacket.pts; + int rc = av_write_frame( m_pFormatCtxB, &mPacket); + if( rc < 0 ) { + //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) { + m_bThreadStatus = TH_ENDED; + LOG_ERROR( "Trouble with Video Output B!" ); + av_strerror( rc, tB, 128 ); + LOG_ERROR( tB ); + break; //continue (changed since embed into do-while) + }; + }; + av_packet_unref( &mPacket ); + }; + } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED ); + }; +#ifdef DEBUG + LOG("Encoder Loop Ended!"); +#endif + if ( m_bSegAActive ) { + m_bSegAActive = false; + av_write_trailer( m_pFormatCtxA ); + avio_close( m_pFormatCtxA->pb ); + }; + if ( m_bSegBActive ) { + m_bSegBActive = false; + av_write_trailer( m_pFormatCtxB ); + avio_close( m_pFormatCtxB->pb ); + }; +#ifdef DEBUG + LOG("Encoder Streams are Closed!"); +#endif +}; + +void streamHandler::swapActiveStreams( void ){ + //m_mFrameCounterProtector.lock(); + if ( !m_bActiveEncoderStream ) { + m_bActiveEncoderStream = 1; + m_nVideoRegisteredDBID = 0; + // No need to continue Stream A if no Events + if ( m_bSegADelete ) closeSegmentA(); + } else { + m_bActiveEncoderStream = 0; + m_nVideoRegisteredDBID = 0; + // No need to continue Stream B if no Events + if ( m_bSegBDelete ) closeSegmentB(); + }; + //m_mFrameCounterProtector.unlock(); +}; + +bool streamHandler::triggerEvent( uint32_t &dbid, uint32_t &frame ){ + m_mFrameCounterProtector.lock(); + // To Mark Events Frames + m_bEvtMarkerCounter = 255; + + if ( m_nVideoRegisteredDBID == 0 ) { + LOG("New Event!"); + PF_TIMESTAMP ts; + getPFTS( &ts ); + if ( !m_bActiveEncoderStream ) { // Stream A is Active + m_nVideoRegisteredDBID = mojoDBC::getInstance()->addVideoRecord( + m_sStreamData.id, + m_cSegMD5A, + VIDEO_OUTPUT_CONTAINER, + ts.seconds, + ts.milliseconds, + m_sStreamData.fps + ); + m_bSegADelete = false; + m_nSegAShiftFrames = frame = m_nSegAFrameCounter; + } else { // Stream B is Active + m_nVideoRegisteredDBID = mojoDBC::getInstance()->addVideoRecord( + m_sStreamData.id, + m_cSegMD5B, + VIDEO_OUTPUT_CONTAINER, + ts.seconds, + ts.milliseconds, + m_sStreamData.fps + ); + m_bSegBDelete = false; + m_nSegBShiftFrames = frame = m_nSegBFrameCounter; + }; + }; + if ( m_nVideoRegisteredDBID == 0 ) return false; + dbid = m_nVideoRegisteredDBID; + LOG("Event Registered!"); + m_mFrameCounterProtector.unlock(); + return true; +}; + +bool streamHandler::triggerCamMove( void ){ + m_bCamMoveCounter = 255; + return true; +}; + +bool streamHandler::validate( void ){ + if ( m_pSource ) +#ifdef EVE_ENABLE_VIDEO + if( m_bThreadStatus < TH_ENDED ) +#endif + return true; + + return false; +}; + +#undef LOG +#undef LOG_ERROR +#undef TLOG +#undef TLOG_ERROR diff --git a/lib/App/mojo/rgooseModuleEmbedVideo.h b/lib/App/mojo/rgooseModuleEmbedVideo.h new file mode 100644 index 00000000..4215e4ea --- /dev/null +++ b/lib/App/mojo/rgooseModuleEmbedVideo.h @@ -0,0 +1,320 @@ +#ifndef __ARGUS_MODULE_EMBED_VIDEO_HEADER__ +#define __ARGUS_MODULE_EMBED_VIDEO_HEADER__ +#include "rgooseModule.h" +#include "../components/base/basicMutex.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" +//#include "../data/media/video/videoAVLIBDestination.h" +#include "../components/base/basicMediaSource.h" +#include "../components/base/basicMediaDestination.h" + +class argusModuleEmbedVideo; + +#define FILESTREAMBUFFERSZ 1048576 + +#define EVE_ENABLE_VIDEO + + + +//#define USE_SCALING_IN + + +#ifdef EVE_ENABLE_VIDEO + +//#define EVE_DONT_DELETE_SEGMENTS + +/* Video CODECS */ +#define VC_VPX 0 +#define VC_X264 1 +#define VC_MP4 2 +#define VC_MJPEG 3 +#define VC_FLV 4 + +/* Video FORMATS */ +#define VF_WEBM 0 +#define VF_MP4 1 +#define VF_MP3 2 +#define VF_AAC 3 +#define VF_OGG 4 +#define VF_MJPEG 5 +#define VF_FLV 6 + +/* Encoder PROFILES */ +#define VP_ULTRAFAST 0 +#define VP_VERYFAST 1 +#define VP_FAST 2 +#define VP_MEDIUM 3 +#define VP_SLOW 4 +#define VP_VERYSLOW 5 +#define VP_ULTRASLOW 6 + +#define VO_MJPEG 1 +#define VO_MPEG4 2 +#define VO_H264 3 +#define VO_H265 4 +#define VO_FLV 5 + +//#define VIDEO_OUTPUT VO_MJPEG +//#define VIDEO_OUTPUT VO_MPEG4 +#define VIDEO_OUTPUT VO_H264 +//#define VIDEO_OUTPUT VO_H265 +//#define VIDEO_OUTPUT VO_FLV + +//#define VIDEO_OUTPUT_WIDTH 640 //1920 +//#define VIDEO_OUTPUT_HEIGHT 480 //1080 +//#define VIDEO_OUTPUT_FPS 10 +//#define VIDEO_OUTPUT_GOP 15 + +#if( LIBAVCODEC_VERSION_MAJOR < 54 ) + #define VIDEO_OUTPUT_CODEC CODEC_ID_MJPEG + #define VIDEO_OUTPUT_PIX_FMT PIX_FMT_YUVJ422P +#else + #if VIDEO_OUTPUT == VO_MJPEG + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MJPEG + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUVJ422P + #define VIDEO_OUTPUT_CONTAINER_LONG "mpeg" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "webm" + #elif VIDEO_OUTPUT == VO_MPEG4 + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_MPEG4 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif VIDEO_OUTPUT == VO_H264 + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H264 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif VIDEO_OUTPUT == VO_H265 + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_H265 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER_LONG "mp4" + #define VIDEO_OUTPUT_CONTAINER "mp4" + #elif VIDEO_OUTPUT == VO_FLV + #define VIDEO_OUTPUT_CODEC AV_CODEC_ID_FLV1 + #define VIDEO_OUTPUT_PIX_FMT AV_PIX_FMT_YUV420P + #define VIDEO_OUTPUT_CONTAINER_LONG "flv" + #define VIDEO_OUTPUT_BITRATE 4000000 + #define VIDEO_OUTPUT_CONTAINER "flv" + #endif +#endif + +#endif //EVE_ENABLE_VIDEO + +typedef struct S_buffer_data { + uint8_t * buf; + int size; + uint8_t * ptr; + size_t room; ///< size left in the buffer +} buffer_data; + +#define NR_COLORS 4 +#define AVIO_BUFFER_SIZE 4096 +#define BD_BUFFER_SIZE 1024 + +class streamHandler; + +typedef struct S_WEB_CLIENT_CTX{ + int m_iSocketFID; + int m_iEncoderPipe[2]; + bool bValid; + bool initDone; + bool headerIsSent; + uint32_t mediaStreamId; + streamHandler * m_pHandler; + argusModuleEmbedVideo * ModulePtr; +}WEB_CLIENT_CTX; + + +typedef struct S_WEB_HANDLER{ + DWORD m_dwThreadID; +#ifdef __linux__ + pthread_t m_hThreadHandle; +#else + HANDLE m_hThreadHandle; +#endif + WEB_CLIENT_CTX * CTX; +}WEB_HANDLER; + +typedef vector vectorHANDLERS; + + +//typedef vector vectorSTREAMS; + +typedef struct S_STREAM_CAP{ + uint32_t stream_id; + uint32_t buffer_size; + uint8_t picture_buffer; +}STREAM_CAP; + +typedef struct S_VIDEO_EVT{ + uint32_t dbid; + uint32_t frame; +}VIDEO_EVT; + +typedef vector compressedFRAME; +typedef map mapSTREAMCAPS; +typedef map mapSTREAMMAPS; + +class argusModuleEmbedVideo; + +#define PRE_ALARM_TIME_MILSECONDS 2000 // 2 sec +#define POST_ALARM_TIME_MILSECONDS 2000 // 2 sec +#define ENCODING_SEGMENT_MILSECONDS 50000 // 50 sec +#define ENCODING_SEGMENT_LIMIT_MILSECONDS 60000 // 1 minute +//#define ENCODING_SEGMENT_LIMIT_MILSECONDS 900000 // 15 minute + +#define EVE_OUTPUT_PICTURES 1 +#define EVE_OUTPUT_VIDEO 2 +#define EVE_OUTPUT_PIC_AND_VID 3 + +#ifdef EVE_ENABLE_VIDEO + + typedef struct S_ENCODING_BUFFER{ + int linesize[2]; + int rows; + uint8_t * data[2]; + size_t size; + }ENCODING_BUFFER; + + typedef std::queue Q_ENCODING_BUFFER; + +#endif +class streamHandler: + public basicMediaDestination +#ifdef EVE_ENABLE_VIDEO + , public basicThread +#endif +{ + private: + basicLogCollection * m_pLog; + basicMediaSource * m_pSource; + MEDIA_SOURCE_DESC m_sSourceDesc; + char m_cSourceType; + DBC_MEDIA_STREAM_DATA m_sStreamData; + basicMutex m_mProtector; + argusModuleEmbedVideo * m_pMaster; + uint8_t m_bEvtMarkerCounter; + uint8_t m_bCamMoveCounter; + MS_WORK_MODE m_eWM; + +#ifdef EVE_ENABLE_VIDEO + basicMutex m_mFrameCounterProtector; + uint32_t m_nPreAlarmFrames; + uint32_t m_nPostAlarmFrames; + uint32_t m_nGlobalFrameCounter; + uint32_t m_nVideoRegisteredDBID; + uint32_t m_nSegAFrameCounter; + uint32_t m_nSegBFrameCounter; + uint32_t m_nSegAShiftFrames; + uint32_t m_nSegBShiftFrames; + uint32_t m_nSegASkippedFrames; + uint32_t m_nSegBSkippedFrames; + uint32_t m_nSegmentLimitFrames; + uint32_t m_nHardLimitFrames; + uint8_t m_bActiveEncoderStream; + bool m_bSegAActive; + bool m_bSegADelete; + bool m_bSegBActive; + bool m_bSegBDelete; + basicMutex m_mCurrentOperationProtector; + uint8_t m_bCOP; + char m_cSegNameA[128]; + char m_cSegMD5A[33]; + char m_cSegNameB[128]; + char m_cSegMD5B[33]; + // encoding video stuff + AVCodec * m_pVideoCodec; + AVCodecContext * m_pCodecCtx; + SwsContext * m_pConvertCtx; + AVFrame * m_pAVFrame; + uint8_t * m_pOutBuffer; + // File Context 2 units + AVOutputFormat * m_pFormat; + AVFormatContext * m_pFormatCtxA; + AVFormatContext * m_pFormatCtxB; + AVStream * m_pVideoStrA; + AVStream * m_pVideoStrB; + //common output options + AVDictionary * m_pFormatOpts; + + basicMutex m_mEncodingQueueProtector; + Q_ENCODING_BUFFER m_qEncodingQueue; + + bool openSegmentA( void ); + void closeSegmentA( void ); + bool openSegmentB( void ); + void closeSegmentB( void ); + void swapActiveStreams( void ); + void closeAll(); + bool initVideoOutput(); + protected: + void m_fThreadProc( void ); +#endif //EVE_ENABLE_VIDEO + + public: + explicit streamHandler( argusModuleEmbedVideo *ptr, MS_WORK_MODE M = MS_MODE_DECODE_FRAMES ); + virtual ~streamHandler(); + bool create( uint32_t stremID ); + /* from Media Destination */ + virtual bool pushFrame( AVFrame *Frame, void* src = NULL); + //virtual void pushFrame( cv::Mat* Frame, void* src = NULL); + virtual bool pushFrame( cv::Mat &Frame, void* src = NULL); + bool triggerEvent( uint32_t &dbid, uint32_t &frame ); + bool triggerCamMove( void ); + bool validate( void ); +}; + +typedef map mapSTREAMHANDLERS; + +class argusModuleEmbedVideo: public argusKernelModule, /*public basicMediaDestination,*/ public basicThread { + private: + basicEventHeap * m_pEventHeap; + static void * webClientProc( void *ptr ); + int m_nSocketDescriptor; + basicMutex m_mHandlersProtector; + basicMutex m_mPictureProtector; + basicMutex m_mEncodedProtector; + vectorHANDLERS m_vHandlersPool; + DBC_MODULE_EMBED_VIDEO_DATA m_sEmbedVideoData; + mapSTREAMCAPS m_mapCAPTURES; + mapSTREAMMAPS m_mapMATS; + mapSTREAMHANDLERS m_mapHANDLERS; + uint8_t * n_pNoSignalData; + uint32_t m_nNoSignalSize; + cv::Mat m_mLogoPic; + cv::Mat m_mLogoMask; + char m_pBaseSavePath[PATH_MAX]; + bool registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ); + bool saveStreamPicture( uint32_t id ); + bool saveStreamPicture( DBC_SNAPSHOT_DATA *ptr ); + bool generateSavePicPath( CSTR MD5, CSTR Output ); + protected: + /* From Basic Thread */ + virtual void m_fThreadProc( void ); + public: + explicit argusModuleEmbedVideo( uint32_t moduleID ); + ~argusModuleEmbedVideo(); + /* From Kernel Module */ + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); + /* from Media Destination * / + virtual bool pushFrame( AVFrame *Frame, void* src = NULL); + //virtual void pushFrame( cv::Mat* Frame, void* src = NULL); + virtual bool pushFrame( cv::Mat &Frame, void* src = NULL); + /* Module Specific Functionality */ + int getWidh( void ); + int getHeight( void ); + bool registerStream( uint32_t streamID ); + bool unregisterStream( uint32_t streamID ); + + friend class streamHandler; + +}; +#endif diff --git a/lib/App/mojo/rgooseModuleFactory.cpp b/lib/App/mojo/rgooseModuleFactory.cpp new file mode 100644 index 00000000..dbb6e540 --- /dev/null +++ b/lib/App/mojo/rgooseModuleFactory.cpp @@ -0,0 +1,386 @@ +#include "rgooseModuleFactory.h" +#include "rgooseModuleUSBRelay.h" +#include "rgooseModuleKafka.h" +#include "rgooseModuleFlyHunter.h" +#include "rgooseModuleSSDP.h" +#include "rgooseModuleOnvifObserver.h" +#include "rgooseModuleEmbedVideo.h" +#include "rgooseModuleModemManager.h" + +#ifdef MEM_DEBUG + #include "../alg/generic/heapDebug.h" +#endif + +#define LOG( X ) m_pLog->Log( "MFAC", this, X ) +#define LOG_ERROR( X ) m_pLog->Log( "MFAC", this, _LOG_ERROR, X ) + +argusModuleFactory * argusModuleFactory::_instance = NULL; + +/** +* Returns the single instance of the object. +*/ +argusModuleFactory* argusModuleFactory::getInstance( uint32_t ServerID ) { + if( NULL == _instance) { + if( ServerID ) { + _instance = new argusModuleFactory( ServerID ); + }; + }; + return _instance; +}; + +argusModuleFactory::argusModuleFactory( uint32_t ServerID ):basicThread(){ + m_nServerID = ServerID; + m_bInitialValidatioonDone = false; + m_pLog = basicLogCollection::getInstance(); + m_pDBC = mojoDBC::getInstance(); + init(); +}; + +argusModuleFactory::~argusModuleFactory(){ + waitThreadEnd( true ); + shutdownServices( true ); + _instance = NULL; +}; + +void argusModuleFactory::shutdownServices( bool force ){ +#ifdef DEBUG + LOG("shutdownServices"); +#endif + m_mModulesProtector.lock(); + if( m_vKernelModules.size() > 0 ){ + for( vectorKernelModules::iterator index = m_vKernelModules.begin(); index < m_vKernelModules.end(); index++ ){ +#ifdef DEBUG + char tB[128]; + switch( (*index)->getType() ){ + case ARGUS_MODULE_DCBUSB: sprintf( tB, "Stop Service of DCUSB Module" ); break; + case ARGUS_MODULE_KAFKA: sprintf( tB, "Stop Service of KAFKA Module" ); break; + case ARGUS_MODULE_GPS: sprintf( tB, "Stop Service of GPS Module" ); break; + case ARGUS_MODULE_NETWORK: sprintf( tB, "Stop Service of Network Module" ); break; + case ARGUS_MODULE_FLYHUNTER: sprintf( tB, "Stop Service of FlyHunter Module" ); break; + case ARGUS_MODULE_SSDP_ANONCE: sprintf( tB, "Stop Service of SSDP Module" ); break; + case ARGUS_MODULE_ONVIF_OBSERVER: sprintf( tB, "Stop Service of OnVif Observer Module" ); break; + case ARGUS_MODULE_EMBED_VIDEO: sprintf( tB, "Stop Service of EmbedVideo Module" ); break; + case ARGUS_MODULE_MODEM_MANAGER: sprintf( tB, "Stop Service of Modem Manager Module" ); break; + default: sprintf( tB, "Stop Service of UNKNOWN[%d] Module", (*index)->getType() ); break; + }; + LOG( tB ); +#endif + (*index)->stopService( force ); +#ifdef DEBUG + LOG("Done"); +#endif + deleteModule( (*index) ); +#ifdef DEBUG + LOG("Module is Deleted"); +#endif + }; + m_vKernelModules.clear(); + }; + m_mModulesProtector.unlock(); +#ifdef DEBUG + LOG("Done shutdownServices"); +#endif +}; + +bool argusModuleFactory::loadModules( uint32_t ServerID ){ + DBC_INT_LIST *tList = NULL; + + if(m_pDBC == NULL) return false; + m_nServerID = ServerID; + tList = m_pDBC->listModules( m_nServerID ); + if( tList != NULL ) { + if( tList->size() ) { + for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ) createModule( *idx ); + tList->clear(); + } +#ifdef DEBUG + else { + LOG("No Modules Defined"); + } +#endif + delete( tList ); + } +#ifdef DEBUG + else { + LOG("No Modules Defined"); + } +#endif + return true; +}; + +argusKernelModule *argusModuleFactory::createModule( int id ){ + argusKernelModule *tVal = NULL; + if( m_pDBC != NULL ){ + DBC_MODULE_DATA *tData = NULL; + + tData = m_pDBC->getModuleData( id ); + if( tData!= NULL ) { + switch( tData->type ) { + case ARGUS_MODULE_DCBUSB: +#ifdef DEBUG + LOG("Creating Dry Contact USB Module"); +#endif + tVal = new argusModuleUSBRelay( tData->module_id ); + + break; + case ARGUS_MODULE_KAFKA: +#ifdef DEBUG + LOG("Creating KAFKA Module"); +#endif + tVal = new argusModuleKafka( tData->module_id ); + break; + case ARGUS_MODULE_FLYHUNTER: +#ifdef DEBUG + LOG("Creating Fly Hunter Module"); +#endif + tVal = new argusModuleFlyHunter( tData->module_id ); + break; + case ARGUS_MODULE_SSDP_ANONCE: +#ifdef DEBUG + LOG("Creating SSDP Announcer Module"); +#endif + tVal = new argusModuleSSDPAnnouncer( tData->module_id ); + break; + case ARGUS_MODULE_ONVIF_OBSERVER: +#ifdef DEBUG + LOG("Creating OnVif Observer Module"); +#endif + if ( m_pDBC->isLocal() ) { + tVal = new argusModuleOnvifObserver(tData->module_id); +#ifdef DEBUG + } else { + LOG("Module is Disabled Since Remote Database!"); +#endif + }; + break; + case ARGUS_MODULE_EMBED_VIDEO: +#ifdef DEBUG + LOG("Creating Embed Video Module"); +#endif + if ( m_pDBC->isLocal() ){ + tVal = new argusModuleEmbedVideo( tData->module_id ); +#ifdef DEBUG + } else { + LOG("Module is Disabled Since Remote Database!"); +#endif + }; + break; + case ARGUS_MODULE_MODEM_MANAGER: +#ifdef DEBUG + LOG("Creating Modem Manager Module"); +#endif + tVal = new argusModuleModemManager( tData->module_id ); + break; + }; + free(tData); + } else { + LOG_ERROR("No Module Data Fetched!"); + }; + } else { + LOG_ERROR("No Database Object Assigned!"); + }; + if( tVal != NULL ){ + tVal->startService(); + m_mModulesProtector.lock(); + m_vKernelModules.push_back( tVal ); + m_mModulesProtector.unlock(); + }; + return tVal; +}; + +void argusModuleFactory::deleteModule( argusKernelModule *M ){ + if( M ) { + switch( M->getType() ) { + case ARGUS_MODULE_DCBUSB: delete( (argusModuleUSBRelay*) M ); break; + case ARGUS_MODULE_KAFKA: delete( (argusModuleKafka*) M ); break; + case ARGUS_MODULE_FLYHUNTER: delete( (argusModuleFlyHunter*) M ); break; + case ARGUS_MODULE_SSDP_ANONCE: delete( (argusModuleSSDPAnnouncer*) M ); break; + case ARGUS_MODULE_ONVIF_OBSERVER: delete( (argusModuleOnvifObserver*) M ); break; + case ARGUS_MODULE_EMBED_VIDEO: delete( (argusModuleEmbedVideo*) M ); break; + case ARGUS_MODULE_MODEM_MANAGER: delete( (argusModuleModemManager*) M ); break; + }; + }; +}; + +void argusModuleFactory::deleteModule( int id ){ + m_mModulesProtector.lock(); + if( m_vKernelModules.size() > id ) { + deleteModule( m_vKernelModules.at( id ) ); + m_vKernelModules.erase( m_vKernelModules.begin() + id ); + m_vKernelModules.shrink_to_fit(); + }; + m_mModulesProtector.unlock(); +}; + +uint32_t argusModuleFactory::getModulesCount( ARGUS_MODULE_TYPE t ){ + uint32_t cnt = 0; + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + for( int i=0; i < m_vKernelModules.size(); i++ ) { + if( m_vKernelModules.at(i)->getType() == t ) cnt++; + }; + }; + m_mModulesProtector.unlock(); + return cnt; +}; + +uint32_t argusModuleFactory::fetchModules( ARGUS_MODULE_TYPE t, argusKernelModule**&RA ){ + uint32_t cnt = getModulesCount( t ); + RA = NULL; + if( cnt > 0 ) { + RA = ( argusKernelModule** ) calloc( cnt, sizeof( argusKernelModule* ) ); + if( RA!= NULL ) { + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + uint32_t idx = 0; + for( int i=0; i < m_vKernelModules.size(); i++ ) { + if( m_vKernelModules.at(i)->getType() == t ) { + RA[idx] = m_vKernelModules.at(i); + idx++; + }; + }; + }; + m_mModulesProtector.unlock(); + } else cnt = 0; + }; + return cnt; +}; + +argusKernelModule *argusModuleFactory::getModule( uint32_t id ){ + argusKernelModule *RetVal = NULL; + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + for( vectorKernelModules::iterator idx = m_vKernelModules.begin(); idx < m_vKernelModules.end(); idx++ ){ + if( (*idx)->getId() == id ) { + RetVal = (*idx); + break; + }; + }; + }; + m_mModulesProtector.unlock(); + return RetVal; +}; + +argusKernelModule *argusModuleFactory::getModule( ARGUS_MODULE_TYPE t, uint32_t id ){ + argusKernelModule *RetVal = NULL; + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + for( vectorKernelModules::iterator idx = m_vKernelModules.begin(); idx < m_vKernelModules.end(); idx++ ){ + if( id ){ + if( ( (*idx)->getType() == t ) && ( (*idx)->getId() == id ) ){ + RetVal = (*idx); + break; + }; + } else { + if( (*idx)->getType() == t ){ + RetVal = (*idx); + break; + }; + }; + }; + }; + m_mModulesProtector.unlock(); + return RetVal; +}; + +bool argusModuleFactory::validate( void ){ + return ( m_bThreadStatus < TH_ENDED ); +}; + +void argusModuleFactory::m_fThreadProc( void ){ + if( m_pDBC == NULL) { + m_bThreadStatus = TH_ENDED; + } else { + DBC_INT_LIST *tList = NULL; +#ifdef MEM_DEBUG + size_t memStart, memEnd, memDiff; + char MEM_MSG[256]; +#endif + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { +#ifdef MEM_DEBUG + memStart = getCurrentRSS(); +#endif + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + DBC_INT_LIST tL; + for( int cm = 0; cm < m_vKernelModules.size(); cm++ ) tL.push_back( m_vKernelModules.at(cm)->getId() ); + tList = m_pDBC->listNewModules( m_nServerID, &tL ); + tL.clear(); + } else { + tList = m_pDBC->listNewModules( m_nServerID, NULL ); + }; + m_mModulesProtector.unlock(); + if( tList != NULL ) { +#ifdef DEBUG + LOG("New Modules Exists!"); +#endif + for( int index=0; index< tList->size(); index++) createModule(tList->at(index)); + tList->clear(); + delete( tList ); + }; +#ifdef MEM_DEBUG + memEnd = getCurrentRSS(); + memDiff = memEnd - memStart; + sprintf(MEM_MSG,"MEM START: %d MEM DIF1: %d", memStart, memDiff ); + LOG( MEM_MSG ); +#endif + m_mModulesProtector.lock(); + if( m_vKernelModules.size() ) { + //Get Full List + //tList = NULL; + tList = m_pDBC->listModules( m_nServerID ); + if( tList != NULL ) { + int cm = 0; + while( cm < m_vKernelModules.size() ) { + //check if module removed + bool tRemoved = true; + for( int lm = 0; lm < tList->size(); lm++ ) { + if( tList->at(lm) == m_vKernelModules.at( cm )->getId() ) { + tRemoved = false; + break; + }; + }; + if( !tRemoved ) { + // validate module + m_vKernelModules.at( cm )->validate(); + cm++; + } else { +#ifdef DEBUG + LOG("Delete Module!"); +#endif + deleteModule( cm ); + }; + }; + tList->clear(); + delete( tList ); + } else { +#ifdef DEBUG + LOG("All Modules Must be Deleted!"); +#endif + while( m_vKernelModules.size() ) deleteModule( 0 ); + }; + } +#ifdef DEBUG_EXTRA + else { + LOG("No Modules to Validate!"); + } +#endif + ; + m_mModulesProtector.unlock(); +#ifdef MEM_DEBUG + memEnd = getCurrentRSS(); + memDiff = memEnd - memStart; + sprintf(MEM_MSG,"MEM START: %d MEM DIF2: %d", memStart, memDiff ); + LOG( MEM_MSG ); +#endif + if( !m_bInitialValidatioonDone ) m_bInitialValidatioonDone = true; + for( int i = ( 5000 / DEFAULT_THREAD_SLEEP_TIME ); i && ( m_bThreadStatus < TH_ENDED ); i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + }; + }; +}; +//--enable-gpl --enable-libx264 --enable-nonfree --extra-ldflags=-latomic --enable-omx --enable-omx-rpi +//-rtsp_transport tcp + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/mojo/rgooseModuleFactory.h b/lib/App/mojo/rgooseModuleFactory.h new file mode 100644 index 00000000..f288ea16 --- /dev/null +++ b/lib/App/mojo/rgooseModuleFactory.h @@ -0,0 +1,40 @@ +#ifndef __ARGUS_MODULE_FACTORY_HEADER__ +#define __ARGUS_MODULE_FACTORY_HEADER__ + +#include +#include "rgooseModule.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicMutex.h" + +typedef std::vector vectorKernelModules; + +class argusModuleFactory: public basicThread{ + private: + basicLogCollection * m_pLog; + mojoDBC * m_pDBC; + uint32_t m_nServerID; + vectorKernelModules m_vKernelModules; + basicMutex m_mModulesProtector; + bool m_bInitialValidatioonDone; + void deleteModule( argusKernelModule * ); + public: + static argusModuleFactory * getInstance( uint32_t ServerID = 0 ); + virtual ~argusModuleFactory(); + argusKernelModule * createModule( int id ); + void deleteModule( int id ); + argusKernelModule * getModule( uint32_t id ); + argusKernelModule * getModule( ARGUS_MODULE_TYPE t, uint32_t id = 0 ); + uint32_t getModulesCount( ARGUS_MODULE_TYPE t ); + uint32_t fetchModules( ARGUS_MODULE_TYPE, argusKernelModule**&RA ); + bool loadModules( uint32_t ServerID = 0 ); + bool validate( void ); + void shutdownServices( bool force = false ); + bool isValidationDone( void ){ return m_bInitialValidatioonDone; }; + protected: + explicit argusModuleFactory( uint32_t ServerID ); + virtual void m_fThreadProc( void ); + private: + static argusModuleFactory * _instance; +}; + +#endif \ No newline at end of file diff --git a/lib/App/mojo/rgooseModuleFlyHunter.cpp b/lib/App/mojo/rgooseModuleFlyHunter.cpp new file mode 100644 index 00000000..2965a21f --- /dev/null +++ b/lib/App/mojo/rgooseModuleFlyHunter.cpp @@ -0,0 +1,474 @@ +#include "rgooseModuleFlyHunter.h" + +#define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_FH", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + argusKernelModule::m_pLog->Log( "MOD_FH", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_FH", this, _LOG_ERROR, X ); +#endif + +argusModuleFlyHunter::argusModuleFlyHunter( uint32_t ModuleID ): argusKernelModule( ModuleID, ARGUS_MODULE_FLYHUNTER ), basicThread(){ + memset( &m_sCurrentMission, 0, sizeof(FH_MISSION_DATA) ); + memset( &m_sCurrentlocation, 0 , sizeof(C3D_WGS84_LOC)); + m_pProtocol = NULL; + m_bEnabled = false; + m_bDroneStatus = FH_STATUS_NONE; + m_bWorkingMode = FH_WM_NONE; + m_pEventHeap = basicEventHeap::getInstance(); +}; + +argusModuleFlyHunter::~argusModuleFlyHunter(){ + m_bEnabled = false; + waitThreadEnd( true ); + if( m_pProtocol!= NULL ) delete( m_pProtocol ); +}; + +bool argusModuleFlyHunter::startService(){ + LOG("Starting Service!"); + if( m_bEnabled ) return false; + DBC_FH_DATA *tData = m_pDBC->getFlyHunterData( m_nDBAUXID ); + if( tData == NULL ) return false; + m_sGCSlocation.lat = tData->lat; + m_sGCSlocation.lon = tData->lon; + m_sGCSlocation.alt = tData->alt; + + m_bWorkingMode = FH_WM_NONE; +#ifdef SIMULATE_FH + m_bDroneStatus = FH_STATUS_INIT; + m_bEnabled = true; + m_fStepLat = 0.0f; + m_fStepLon = 0.0f; + m_fStepAlt = 0.0f; + return init(); +#else + m_pProtocol = new protocolMAVLINK(); + if( m_pProtocol!= NULL ) { + m_bDroneStatus = FH_STATUS_INIT; + if( m_pProtocol->create() ) { + m_bEnabled = true; + return init(); + }; + }; +#endif + return false; +}; + +bool argusModuleFlyHunter::stopService( bool force ){ + return true; +}; + +void argusModuleFlyHunter::m_fThreadProc(){ + m_bThreadStatus = TH_WORKING; + if( !m_bEnabled ) { + m_bThreadStatus = TH_ENDED; +#ifdef DEBUG + LOG("Module is Disabled!"); +#endif + }; +#ifdef DEBUG + LOG("Module Started!"); +#endif + while( m_bThreadStatus < TH_ENDED ) { + switch( m_bWorkingMode ) { + case FH_WM_CANCELING:{ + m_bWorkingMode = FH_WM_FTL; +#ifdef SIMULATE_FH + m_nSymTO = SIMULATE_FH_FTL_TO; +#endif + break; + }; + case FH_WM_MISSION_FLIGHT:{ + +#ifndef SIMULATE_FH + //IF landed + // Must be Provided comparation + if( m_sGCSlocation.lat == m_sCurrentlocation.lat && m_sGCSlocation.lon == m_sCurrentlocation.lon ){ +#else + if( m_nSymTO ){ + m_nSymTO --; + + m_sCurrentlocation.lat = m_sCurrentlocation.lat + m_fStepLat; + m_sCurrentlocation.lon = m_sCurrentlocation.lon + m_fStepLon; + m_sCurrentlocation.alt = m_sCurrentlocation.alt + m_fStepAlt; + + } else { +#endif + EVENT_CONTAINER * newEvt = NULL; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sCurrentlocation, sizeof(C3D_WGS84_LOC)); + switch( m_sCurrentMission.type ) { + case FH_WM_OBSERVE: + LOG("OBSERVE Mission"); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_DEST_REACHED, NULL, NULL, evtData ); + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; + break; + case FH_WM_JAMING: + LOG("JAMING Mission"); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_JAMER_ON, NULL, NULL, evtData ); + m_bWorkingMode = FH_WM_JAMING; + m_nJamingTO = m_nJamingTO; + break; + case FH_WM_INTERCEPT: + LOG("INTERCEPT Mission"); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_INTERCEPT_BEGIN, NULL, NULL, evtData ); + m_bWorkingMode = FH_WM_INTERCEPT; +#ifdef SIMULATE_FH + m_nSymTO = SIMULATE_FH_INTERCEPT; +#endif + break; + default: + LOG("No Mission Type SET!!"); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_DEST_REACHED, NULL, NULL, evtData ); + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; + }; + if( newEvt ) { + // Propogate Event + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + }; + break; + }; + case FH_WM_INTERCEPT:{ +#ifndef SIMULATE_FH + //IF landed + // Must be Provided comparation + //if( m_sGCSlocation.lat == m_sCurrentlocation.lat && m_sGCSlocation.lon == m_sCurrentlocation.lon ){ +#else + if( m_nSymTO ){ + m_nSymTO --; + } else { + float R = RAND_MAX / rand(); +#endif + EVENT_CONTAINER * newEvt = NULL; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sCurrentlocation, sizeof(C3D_WGS84_LOC)); +#ifdef SIMULATE_FH + if( R > 0.5 ) { + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_INTERCEPT_OK, NULL, NULL, evtData ); + } else { + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_INTERCEPT_NOK, NULL, NULL, evtData ); + }; +#endif + if( newEvt ) { + // Propogate Event + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; + }; + }; + break; + }; + case FH_WM_JAMING:{ + if( m_nJamingTO ) { + if( m_nJamingTO == 1 ) { + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sCurrentlocation, sizeof(C3D_WGS84_LOC)); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_JAMER_OFF, NULL, NULL, evtData ); + if( newEvt ) { + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; +#ifndef SIMULATE_FH + m_pProtocol->broadcastSetBaseMode( POSHOLD ); +#endif + }; + m_nJamingTO--; + } else { + //If Accedently entering in this mode! + m_bWorkingMode = FH_WM_HOOVERING; + m_nHooveringTO = FH_HOOVERING_INTERVAL; +#ifndef SIMULATE_FH + m_pProtocol->broadcastSetBaseMode( POSHOLD ); +#endif + }; + break; + }; + case FH_WM_HOOVERING:{ + // Just Hold Position FH_HOOVERING_INTERVAL seconds + if( m_nHooveringTO ) { + if( m_nHooveringTO == 1 ) { + // No New Assigns -> Going Home +#ifndef SIMULATE_FH + m_pProtocol->broadcastSetBaseMode( RTL ); +#else + m_nSymTO = SIMULATE_FH_FTL_TO; + m_fStepLat = ( m_sGCSlocation.lat - m_sCurrentlocation.lat ) / m_nSymTO; + m_fStepLon = ( m_sGCSlocation.lon - m_sCurrentlocation.lon ) / m_nSymTO; + m_fStepAlt = ( m_sGCSlocation.alt - m_sCurrentlocation.alt ) / m_nSymTO; +#endif + m_bWorkingMode = FH_WM_FTL; + + }; + m_nHooveringTO--; + }; + break; + }; + case FH_WM_EMERGENCY_FTL: + case FH_WM_FTL:{ +#ifndef SIMULATE_FH + //IF landed + // Must be Provided comparation + if( m_sGCSlocation.lat == m_sCurrentlocation.lat && m_sGCSlocation.lon == m_sCurrentlocation.lon ){ +#else + if( m_nSymTO ){ + m_nSymTO --; + + m_sCurrentlocation.lat = m_sCurrentlocation.lat + m_fStepLat; + m_sCurrentlocation.lon = m_sCurrentlocation.lon + m_fStepLon; + m_sCurrentlocation.alt = m_sCurrentlocation.alt + m_fStepAlt; + + } else { +#endif + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sGCSlocation, sizeof(C3D_WGS84_LOC)); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_LANDED, NULL, NULL, evtData ); + if( newEvt ) { + // Propogate Event + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + // Turn Off Motors +#ifndef SIMULATE_FH + if( m_pProtocol->broadcastArm( false ) ){ + // Stop Chakalaka!! + m_bDroneStatus = FH_STATUS_PREARM; + m_bWorkingMode = FH_WM_NONE; + }; +#else + m_bDroneStatus = FH_STATUS_PREARM; + m_bWorkingMode = FH_WM_NONE; +#endif + }; + break; + }; + }; + + switch( m_bDroneStatus ) { + case FH_STATUS_INIT:{ +#ifndef SIMULATE_FH + if( m_pProtocol->broadcastProtocolVersionReq() ){ + m_bDroneStatus = FH_STATUS_CONNECT; + } else SLEEP ( 1000 ); +#else + m_bDroneStatus = FH_STATUS_PREARM; +#endif + break; + }; + case FH_STATUS_PREARM:{ + if( m_bWorkingMode > FH_WM_FTL ) { +#ifndef SIMULATE_FH + // Turn On Motors + if( m_pProtocol->broadcastArm( true ) ){ + //Run Chakalaka!! + m_bDroneStatus = FH_STATUS_ARMED; + m_bWorkingMode = FH_WM_START_FLIGHT; + }; +#else + m_bDroneStatus = FH_STATUS_ARMED; + m_bWorkingMode = FH_WM_START_FLIGHT; +#endif + }; + break; + }; + case FH_STATUS_ARMED:{ +#ifndef SIMULATE_FH + // Lift Up + if( m_pProtocol->broadcastTakeoff( 10.0f ) ){ + m_bDroneStatus = FH_STATUS_FLYING; + }; +#else + m_bDroneStatus = FH_STATUS_FLYING; +#endif + break; + }; + case FH_STATUS_FLYING:{ + if( m_bWorkingMode == FH_WM_START_FLIGHT ){ +#ifndef SIMULATE_FH + if( m_pProtocol->setTargetPosition( m_sCurrentMission.location.lat, m_sCurrentMission.location.lon, m_sCurrentMission.location.alt, 0 ) ){ + m_bWorkingMode = FH_WM_MISSION_FLIGHT; + }; +#else + m_bWorkingMode = FH_WM_MISSION_FLIGHT; + m_nSymTO = SIMULATE_FH_FLY; + + m_sCurrentlocation.lat = m_sGCSlocation.lat; + m_sCurrentlocation.lon = m_sGCSlocation.lon; + m_sCurrentlocation.alt = m_sGCSlocation.alt; + + m_fStepLat = ( m_sCurrentMission.location.lat - m_sGCSlocation.lat ) / m_nSymTO; + m_fStepLon = ( m_sCurrentMission.location.lon - m_sGCSlocation.lon ) / m_nSymTO; + m_fStepAlt = ( m_sCurrentMission.location.alt - m_sGCSlocation.alt ) / m_nSymTO; +#endif + }; + //Update Position to other components + if( m_nWayPointTO ) { + m_nWayPointTO --; + }; + if( m_nWayPointTO == 0 ){ + m_nWayPointTO = FH_WAYPOINT_UPDATE_INTERVAL; + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + memcpy( &evtData->location, &m_sCurrentlocation, sizeof(C3D_WGS84_LOC)); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_WAYPOINT, NULL, NULL, evtData ); + if( newEvt ) { + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + }; + break; + }; + };// Drone Status Switch +#ifdef SIMULATE_FH + SLEEP( 1000 ); +#endif + }; +}; + +void argusModuleFlyHunter::dispatchEvent(EVENT_CONTAINER *Evt){ + if(!m_bEnabled) { + LOG("Module Disabled!"); + return; + } + if( Evt == NULL ) return; + switch( Evt->m_eClass ){ + case EVT_CLASS_EXTERNAL_CMD:{ + switch( Evt->m_eType ) { + case EVT_FH_MISSION_BEGIN:{ + if( + ( ( m_bDroneStatus == FH_STATUS_PREARM ) && ( m_bWorkingMode == FH_WM_NONE ) ) || + ( ( ( m_bDroneStatus == FH_STATUS_ARMED ) && ( ( m_bWorkingMode == FH_WM_HOOVERING ) || ( m_bWorkingMode == FH_WM_FTL ) ) ) ) + ){ + FH_CTRL_DATA * tData = (FH_CTRL_DATA *) Evt->m_pEvtData; + DBC_EVT_RECORD * tEVT = m_pDBC->getEventByUUID( tData->targetUUID ); + if( tEVT ) { + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + evtData->location.lat = tEVT->lat; + evtData->location.lon = tEVT->lon; + evtData->location.alt = tEVT->alt; + sprintf( evtData->missionID, tData->evtUUID ); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_FLY_TO, NULL, NULL, evtData ); + if( newEvt ) { + memcpy( &m_sCurrentMission, evtData, sizeof(FH_MISSION_DATA) ); + m_sCurrentMission.type = FH_WM_INTERCEPT; + m_bWorkingMode = FH_WM_MISSION_BEGIN; + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + free( tEVT ); + } else { + // Not Found In Database + }; + } else { +#ifdef DEBUG + LOG("BUSY!"); + char tB[128]; + sprintf( tB, "DS: %02d WM: %02d", m_bDroneStatus, m_bWorkingMode ); + LOG( tB ); +#endif + if( Evt->m_pEvtData!= NULL ) { + FH_CTRL_DATA * tEData = (FH_CTRL_DATA *) Evt->m_pEvtData; + FH_CTRL_DATA * tNData = (FH_CTRL_DATA *) malloc(sizeof(FH_CTRL_DATA)); + if( tNData != NULL ) { + EVENT_CONTAINER * tEvt; + memcpy(tNData, tEData, sizeof(FH_CTRL_DATA)); + tEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_BUSY, NULL, NULL, tNData ); + if( tEvt!= NULL ) { + m_pEventHeap->broadcast( tEvt ); + } else { + free( tNData ); + }; + }; + }; + }; + break; + }; + case EVT_FH_JAMING_BEGIN:{ // FH_CTRL_DATA + if( m_bWorkingMode == FH_WM_MISSION_FLIGHT || m_bWorkingMode == FH_WM_HOOVERING || m_bWorkingMode == FH_WM_FTL ){ + FH_CTRL_DATA * tData = (FH_CTRL_DATA *) Evt->m_pEvtData; + EVENT_CONTAINER * newEvt; + FH_MISSION_DATA * evtData = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); + if( evtData ){ + memcpy( evtData, &m_sCurrentMission, sizeof(FH_MISSION_DATA)); + newEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_JAMER_ON, NULL, NULL, evtData ); + if( newEvt ) { + m_bWorkingMode = FH_WM_JAMING; + m_sCurrentMission.type = FH_WM_JAMING; + m_nJamingTO = tData->param; + m_pEventHeap->broadcast( newEvt ); + } else { + free( evtData ); + }; + }; + } else { + // No Jaming When No Mission is assigned + if( Evt->m_pEvtData!= NULL ) { + FH_CTRL_DATA * tEData = (FH_CTRL_DATA *) Evt->m_pEvtData; + FH_CTRL_DATA * tNData = (FH_CTRL_DATA *) malloc(sizeof(FH_CTRL_DATA)); + if( tNData != NULL ) { + EVENT_CONTAINER * tEvt; + memcpy(tNData, tEData, sizeof(FH_CTRL_DATA)); + tEvt = createBasicEvent( getAuxId(), EVT_CLASS_FLY_HUNTER, EVT_FH_BUSY, NULL, NULL, tNData ); + if( tEvt!= NULL ) { + m_pEventHeap->broadcast( tEvt ); + } else { + free( tNData ); + }; + }; + }; + }; + break; + }; + case EVT_FH_CANCEL_ACTION:{ + m_bWorkingMode = FH_WM_CANCELING; + break; + }; + }; // Case Class + break; + }; + }; +}; + +bool argusModuleFlyHunter::reloadSettings(){ + return true; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/mojo/rgooseModuleFlyHunter.h b/lib/App/mojo/rgooseModuleFlyHunter.h new file mode 100644 index 00000000..f2e03dea --- /dev/null +++ b/lib/App/mojo/rgooseModuleFlyHunter.h @@ -0,0 +1,73 @@ +#ifndef __ARGUS_MODULE_FLY_HUNTER_HEADER__ +#define __ARGUS_MODULE_FLY_HUNTER_HEADER__ +#include "rgooseModule.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" + +#include "../data/protocol/protocolMAVLINK.h" + +#define SIMULATE_FH + +#ifdef SIMULATE_FH +#define SIMULATE_FH_FLY 40 +#define SIMULATE_FH_INTERCEPT 30 +#define SIMULATE_FH_FTL_TO 40 +#endif + +typedef enum E_FH_STATUS{ + FH_STATUS_NONE = 0, + FH_STATUS_INIT = 1, + FH_STATUS_CONNECT = 2, + FH_STATUS_READ_DATA = 3, + FH_STATUS_ERROR = 4, + FH_STATUS_PREARM = 5, + FH_STATUS_ARMED = 6, + FH_STATUS_FLYING = 7 +}FH_STATUS; + +typedef enum E_FH_WM{ + FH_WM_NONE = 0, + FH_WM_CANCELING = 1, + FH_WM_HOOVERING = 2, + FH_WM_FTL = 3, + FH_WM_MISSION_BEGIN = 4, + FH_WM_START_FLIGHT = 5, + FH_WM_MISSION_FLIGHT = 6, + FH_WM_INTERCEPT = 7, + FH_WM_JAMING = 8, + FH_WM_OBSERVE = 9, + FH_WM_EMERGENCY_FTL = 10 +}FH_WM; + +#define FH_WAYPOINT_UPDATE_INTERVAL 15 +#define FH_HOOVERING_INTERVAL 25 + +class argusModuleFlyHunter: public argusKernelModule, public basicThread { + private: + basicEventHeap * m_pEventHeap; + FH_MISSION_DATA m_sCurrentMission; + FH_WM m_bWorkingMode; + FH_STATUS m_bDroneStatus; + uint16_t m_nJamingTO; + uint16_t m_nWayPointTO; + uint16_t m_nHooveringTO; +#ifdef SIMULATE_FH + uint16_t m_nSymTO; + float m_fStepLat; + float m_fStepLon; + float m_fStepAlt; +#endif + C3D_WGS84_LOC m_sCurrentlocation; + C3D_WGS84_LOC m_sGCSlocation; + protocolMAVLINK * m_pProtocol; + protected: + virtual void m_fThreadProc( void ); + public: + explicit argusModuleFlyHunter( uint32_t oduleID ); + ~argusModuleFlyHunter(); + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); +}; +#endif diff --git a/lib/App/mojo/rgooseModuleKafka.cpp b/lib/App/mojo/rgooseModuleKafka.cpp new file mode 100644 index 00000000..d62a1857 --- /dev/null +++ b/lib/App/mojo/rgooseModuleKafka.cpp @@ -0,0 +1,760 @@ +#include "rgooseModuleKafka.h" +#include "mojoKernel.h" +#include "../hardware/soc/general/3DLRF.h" +#include "../data/json/json_tool.h" +#include +#include +#include +#include + +#define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_KAFKA", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + argusKernelModule::m_pLog->Log( "MOD_KAFKA", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_KAFKA", this, _LOG_ERROR, X ); +#endif + +argusModuleKafka::argusModuleKafka( uint32_t ModuleID ): argusKernelModule( ModuleID, ARGUS_MODULE_KAFKA ){ + m_pProtocol = NULL; + m_bConsumerEnabled = false; + m_pEventHeap = basicEventHeap::getInstance(); + partition = 0; //RdKafka::Topic::PARTITION_UA; + //start_offset = RdKafka::Topic::OFFSET_END;// OFFSET_BEGINNING; + start_offset = 0;//RdKafka::Topic::OFFSET_BEGINNING; + //start_offset = RdKafka::Topic::OFFSET_STORED; + + memset( m_sServerIP, 0 ,48 ); + CSTR TVAL = NULL;//m_pKernel->getServerIp(); + if ( TVAL ) { + strncpy( m_sServerIP, TVAL, 48 ); + free( TVAL ); + } else { + LOG_ERROR("Error Get Argus Server IP!"); + strncpy( m_sServerIP, "192.168.0.127", 48 ); + }; + memset( m_sServerName, 0, 48 ); + TVAL = NULL;//m_pKernel->getServerName(); + if ( TVAL ) { + strncpy( m_sServerName, TVAL, 48 ); + free( TVAL ); + } else { + LOG_ERROR("Error Get Argus Server Name!"); + strncpy( m_sServerName, "Argus Server", 48 ); + }; + + m_pEvtTemplates = (KAFKA_TEMPLATE***) calloc(EVT_CLASS_COUNT, sizeof(KAFKA_TEMPLATE**)); + if( m_pEvtTemplates!= NULL ) { + memset( m_pEvtTemplates, 0, EVT_CLASS_COUNT * sizeof(KAFKA_TEMPLATE**)); + } else LOG_ERROR("EVT Templates Memory Allocation Error!"); + /* + Do it in Kernel!! + if ( m_pKernel!= NULL ) { + argusHardwareManager *tHWM = m_pKernel->getHardwareManager(); + if( tHWM != NULL ) { + DBC_INT_LIST *rIDS = tHWM->requestResourcesByType( ARGUS_HARDWARE_PROVIDER_NETWORK ); + if( rIDS != NULL ) { + for( DBC_INT_LIST::iterator idx = rIDS->begin(); idx < rIDS->end(); idx++ ){ + argusHardwareResourceNetwork *tRES = (argusHardwareResourceNetwork *) tHWM->requestResource( ARGUS_HARDWARE_PROVIDER_NETWORK, *idx ); + if( tRES != NULL ) { + m_pServerIP = tRES->getAddress(); + break; + } else { + LOG_ERROR("Cannot Get Resource!"); + }; + }; + delete( rIDS ); + } else { + LOG("No Networks Detected!"); + m_bEnabled = false; + }; + } else { + LOG_ERROR("No HW Manager"); + }; + } else { + LOG_ERROR("No Kernel"); + }; + */ +}; + +argusModuleKafka::~argusModuleKafka(){ + + m_bEnabled = false; + + waitThreadEnd( true ); + + if( m_pProtocol!= NULL ) { + delete( m_pProtocol ); + }; + + if( m_pEvtTemplates!= NULL ) { + for(int i=0; i < EVT_CLASS_COUNT; i++ ) { + if( m_pEvtTemplates[i] != NULL ){ + for( int j=0; j< EVT_COUNT; j++ ) { + if( m_pEvtTemplates[i][j] != NULL ){ + if( m_pEvtTemplates[i][j]->tpl ) free( m_pEvtTemplates[i][j]->tpl ); + free( m_pEvtTemplates[i][j] ); + }; + }; + free( m_pEvtTemplates[i] ); + }; + }; + free( m_pEvtTemplates ); + }; +}; +/* Periodical Job Handler */ +void argusModuleKafka::m_fThreadProc( void ){ +#ifdef SIMULATOR + float sim_Az = 0.f; + float sim_El = 20.f; + float sim_Ran = 80.35f; + float tr_Az_step = 0.3f; + uint32_t src = 128; +#endif +#ifdef DEBUG + LOG("Pereodical Jobs Started"); +#endif + m_bThreadStatus = TH_WORKING; + if( !m_bEnabled ) { + m_bThreadStatus = TH_ENDED; +#ifdef DEBUG + LOG("Module is Disabled!"); +#endif + }; + while( m_bThreadStatus < TH_ENDED ) { + m_llTicks ++;//= getMilliseconds(); + if( m_llTicks % 20 == 0 ) { // each 2 seconds +#ifdef SIMULATOR + sim_Az += tr_Az_step; + for(int i=0; i < EVT_CLASS_COUNT; i++ ) { + if( m_pEvtTemplates[i] != NULL ){ + for( int j=0; j< EVT_COUNT; j++ ) { + if( m_pEvtTemplates[i][j] != NULL ){ + CSTR tpl; + CSTR ts; + CSTR uuid; + char LON[10]; + char LAT[10]; + char AZ[10]; + char EL[10]; + char RN[10]; + float lat = 32.906153575029926; + float lon = 35.09629379621815; + sprintf( AZ, "%.3f", sim_Az+(0.6/RAND_MAX)*rand()); + sprintf( EL, "%.3f", sim_El+(0.6/RAND_MAX)*rand()); + sprintf( RN, "%.3f", sim_Ran+(0.6/RAND_MAX)*rand()); + sprintf( LAT, "%.10f", lat+(0.00006/RAND_MAX)*rand() ); + sprintf( LON, "%.10f", lon+(0.00006/RAND_MAX)*rand() ); + uuid = getUniqID_UUID(); + ts = getTimeStamp(); + src = i; + tpl = buildTemplate( m_pEvtTemplates[i][j]->tpl, src, ts, uuid, AZ, RN, EL, LAT, LON ); + if( tpl ) { + m_pProtocol->issuePost( m_pEvtTemplates[i][j]->topic, tpl, strlen( tpl ) ); + free( tpl ); + }; + if( uuid ) free( uuid ); + if( ts ) free( ts ); + }; + }; + }; + }; +#endif + }; + if( m_bConsumerEnabled ) { + for( uint8_t idx = 0; idx < EVT_COUNT; idx++ ) { + if( m_pEvtTemplates[EVT_CLASS_EXTERNAL_CMD][idx] != NULL ){ + char BUF[1024]; + int len; + if( m_pProtocol->receivePost( m_pEvtTemplates[EVT_CLASS_EXTERNAL_CMD][idx]->topic, partition, start_offset, BUF, len ) ){ + if( len > 0 ) { + start_offset++; +#ifdef DEBUG + char ttt[64]; + LOG(" HAVE MESSAGE "); + sprintf( ttt, " MSG Len: %d", len ); + LOG( ttt ); +#endif + if( len > 0 ){ + LOG ( BUF ); + try{ + Json::Value root; +#ifdef OLD_WAY_JSON + Json::Reader reader; + if( !reader.parse( BUF, root ) ){ + LOG_ERROR( "Error parsing the string" ); + } else { +#else + JSONCPP_STRING err; + Json::CharReaderBuilder builder; + const std::unique_ptr reader(builder.newCharReader()); + if (!reader->parse(BUF, BUF + len, &root, &err)) { + LOG_ERROR( "Error parsing the string" ); + LOG_ERROR( err.c_str() ); + } else { +#endif + + if (root.size()) { + FH_CTRL_DATA * tData; + basicEventTypeID evtID = EVT_NOINIT; + Json::Value tVal; + tData =(FH_CTRL_DATA *)malloc( sizeof(FH_CTRL_DATA)); + if( tData ) { + memset( tData, 0, sizeof(FH_CTRL_DATA)); + tVal = root["id"]; + + if (!tVal.isNull()) { + #ifdef DEBUG + LOG(tVal.asString().c_str()); + #endif + sprintf( tData->cmdUUID, "%s", tVal.asString().c_str() ); + }; + tVal = root["action"]; + if (!tVal.isNull()) { + #ifdef DEBUG + LOG( tVal.asString().c_str() ); + #endif + if ( strcasecmp(tVal.asString().c_str(), "intercept_target") == 0) { + evtID = EVT_FH_MISSION_BEGIN; + }; + if ( strcasecmp(tVal.asString().c_str(), "jam_target") == 0) { + tData->param = atoi( tVal.asString().c_str()+10 ); + if( tData->param == 0 ) { + tData->param = FH_DEFAULT_JAMING_TIME; + }; + evtID = EVT_FH_JAMING_BEGIN; + }; + if ( strcasecmp(tVal.asString().c_str(), "cancel") == 0) { + evtID = EVT_FH_CANCEL_ACTION; + }; + }; + tVal = root["event_id"]; + if (!tVal.isNull()) { + #ifdef DEBUG + LOG( tVal.asString().c_str() ); + #endif + sprintf( tData->evtUUID, "%s", tVal.asString().c_str() ); + }; + tVal = root["target_id"]; + if (!tVal.isNull()) { + #ifdef DEBUG + LOG( tVal.asString().c_str() ); + #endif + sprintf( tData->targetUUID, "%s", tVal.asString().c_str() ); + }; + if( evtID ) { + EVENT_CONTAINER * tEVT; + tEVT = createBasicEvent( 0, EVT_CLASS_EXTERNAL_CMD, evtID, NULL, NULL, tData ); + if( tEVT ) { + m_pEventHeap->broadcast( tEVT ); + } else { + free( tData ); + }; + } else { + free( tData ); + }; + }; + }; + }; + } catch( exception e ){ + LOG_ERROR("EXCEPTION"); + }; + }; + }; + }; + }; + }; + }; + SLEEP(100); + }; +}; + +bool argusModuleKafka::startService(){ + if(!m_bEnabled) return false; + if( reloadSettings() ) { + if( m_pSettings!= NULL ){ + m_pProtocol = new protocolKAFKA( m_pSettings ); + if( m_pProtocol->init() ){ + return init(); + }; + }; + }; + return false; +}; + +bool argusModuleKafka::stopService( bool force ){ + waitThreadEnd( true ); + return true; +}; + +bool argusModuleKafka::reloadSettings(){ + if( m_pDBC==NULL ) return false; + if(! m_bEnabled) return false; + m_pSettings = m_pDBC->getSettingsKAFKA( m_nDBAUXID ); + if( m_pSettings != NULL ) { + if( m_pEvtTemplates != NULL ) { + // Clear Templates + for(int i = 0; i < EVT_CLASS_COUNT; i++ ){ + for(int j = 0; j < EVT_COUNT; j++ ){ + if( m_pEvtTemplates[i] != NULL ){ + if( m_pEvtTemplates[i][j] != NULL ){ + if( m_pEvtTemplates[i][j]->tpl ) free( m_pEvtTemplates[i][j]->tpl ); + free( m_pEvtTemplates[i][j] ); + m_pEvtTemplates[i][j] = NULL; + }; + }; + }; + free( m_pEvtTemplates[i] ); + m_pEvtTemplates[i] = NULL; + }; + for(int i = 0; i < EVT_CLASS_COUNT; i++ ){ + for(int j = 0; j < EVT_COUNT; j++ ){ + KAFKA_TEMPLATE * tT; + tT = m_pDBC->getKafkaTemplateForEvent( m_nDBAUXID, i, j ); + if( tT != NULL ) { + if( m_pEvtTemplates[i]== NULL ) { + m_pEvtTemplates[i]=(KAFKA_TEMPLATE**)calloc(EVT_COUNT,sizeof(KAFKA_TEMPLATE*)); + memset( m_pEvtTemplates[i], 0, EVT_COUNT * sizeof(KAFKA_TEMPLATE*)); + if( i == EVT_CLASS_EXTERNAL_CMD ) { + m_bConsumerEnabled = true; + }; + }; + m_pEvtTemplates[i][j] = tT; + }; + }; + }; + }; + return true; + }; + return false; +}; +CSTR argusModuleKafka::buildTemplate( + CSTR tpl, + uint32_t source_id, + CSTR ts, + CSTR uuid, + CSTR az, + CSTR range, + CSTR width, + CSTR el, + CSTR lat, + CSTR lon, + CSTR alt, + CSTR extID, + CSTR src_Name, + CSTR src_IP, + CSTR src_lat, + CSTR src_lon, + CSTR src_alt, + CSTR src_rot_x, + CSTR src_rot_y, + CSTR src_rot_z +){ + CSTR ct1, ct2; + char sid[64]; + if( tpl ) { + sprintf( sid, "%d", source_id ); + ct1 = strReplace( tpl, KAFKA_TPL_SUBST_ID, sid ); + if( ct1 ) { + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_TS, ts ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + if( uuid ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_UUID, uuid ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( az ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_AZ, az ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( range ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_RANGE, range ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( width ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_WIDTH, width ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( el ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_EL, el ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( lat ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_LAT, lat ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( lon ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_LON, lon ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( alt ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_ALT, alt ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( extID ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_EXEVTD, extID ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_Name ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_NAME, src_Name ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_IP ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_IP, src_IP ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_lat ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_LAT, src_lat ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_lon ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_LON, src_lon ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_alt ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_ALT, src_alt ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_rot_x ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_ROT_X, src_rot_x ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_rot_y ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_ROT_Y, src_rot_y ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + if( src_rot_z ){ + ct2 = strReplace( ct1, KAFKA_TPL_SUBST_SRC_ROT_Z, src_rot_z ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + }; + //Finalaze Message by System Wide Data + // UUID + CSTR TVAL = getUniqID_UUID(); + if ( TVAL != NULL ) { + ct2 = strReplace(ct1, KAFKA_TPL_SUBST_MSG_UUID, TVAL ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + free( TVAL ); + } else { + LOG_ERROR("Error Generate Message UUID!"); + }; + // Server IP + + ct2 = strReplace(ct1, KAFKA_TPL_SUBST_SRV_IP, m_sServerIP ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + // Server Name + ct2 = strReplace(ct1, KAFKA_TPL_SUBST_SRV_NAME, m_sServerName ); + if( ct2 ) { + free( ct1 ); + ct1 = ct2; + }; + return ct1; + }; + } + return NULL; +}; + +void argusModuleKafka::dispatchEvent( EVENT_CONTAINER *Evt ){ + if( Evt == NULL ) return; + if( !m_bEnabled ) return; +#ifdef DEBUG + char tBuffer[256]; + sprintf( tBuffer, "Event Class %d Type %d ", Evt->m_eClass , Evt->m_eType ); + LOG( tBuffer ); +#endif + if( m_pEvtTemplates[ Evt->m_eClass ]!= NULL ) { + // We have defined Channel for that class Events + // Skip Event Handling by flags + if( !m_bEvtFlags[ Evt->m_eType ] ){ +#ifdef DEBUG + //LOG("Disabled By FLAG!"); +#endif + //return; + } + // Hadle Event + CSTR tDATA = NULL; + if( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ] != NULL ) { + switch( Evt->m_eType ) { + case EVT_TARGET_2D_BLACK: + case EVT_TARGET_2D_WHITE:{ + TARGET_DATA * tTARGET = ( TARGET_DATA *) Evt->m_pEvtData; + if(tTARGET!=NULL){ + char AZ[10]; + char RA[10]; + char WID[10]; + + char LAT[10]; + char LON[10]; + char ALT[10]; + + char SLAT[10]; + char SLON[10]; + char SALT[10]; + char SROT_X[10]; + char SROT_Y[10]; + char SROT_Z[10]; + char SNAME[64]; + char TS[64]; + + sprintf( AZ,"%0.3f", tTARGET->local_target.fi ); + sprintf( RA,"%0.3f", tTARGET->local_target.r ); + sprintf( WID,"%0.3f", tTARGET->area ); + sprintf( LAT,"%0.6f", tTARGET->global_target.lat ); + sprintf( LON,"%0.6f", tTARGET->global_target.lon ); + sprintf( ALT,"%0.6f", tTARGET->global_target.alt ); + sprintf( TS, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", + ( Evt->sTS.tm_year+1900), + (Evt->sTS.tm_mon+1), + Evt->sTS.tm_mday, + Evt->sTS.tm_hour, + Evt->sTS.tm_min, + Evt->sTS.tm_sec, + (Evt->m_UMSTS%1000) + ); + sprintf( SLAT,"%0.6f", tTARGET->source_position.lat ); + sprintf( SLON,"%0.6f", tTARGET->source_position.lon ); + sprintf( SALT,"%0.6f", tTARGET->source_position.alt ); + + sprintf( SROT_X,"%0.6f", tTARGET->source_orient.rot_x ); + sprintf( SROT_Y,"%0.6f", tTARGET->source_orient.rot_y ); + sprintf( SROT_Z,"%0.6f", tTARGET->source_orient.rot_z ); + CSTR tN = m_pDBC->getNodeName( Evt->m_nSourceNodeID ); + if ( tN ) { + strncpy( SNAME, tN, 64 ); + free( tN ); + } else { + strncpy(SNAME, "Noname-Laser-Detector", 64); + }; + tDATA = buildTemplate( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ]->tpl, + Evt->m_nSourceNodeID, + TS, + Evt->m_UUID, + AZ, + RA, + WID, + NULL, + LAT, + LON, + ALT, + NULL, + SNAME, + m_sServerIP, + SLAT, + SLON, + SALT, + SROT_X, + SROT_Y, + SROT_Z + ); + }; + break; + }; + case EVT_TARGET_3D_BLACK: + case EVT_TARGET_3D_WHITE:{ + TARGET_DATA * tTARGET = ( TARGET_DATA *) Evt->m_pEvtData; + if(tTARGET!=NULL){ + char AZ[10]; + char EL[10]; + char RA[10]; + char WID[10]; + char LAT[10]; + char LON[10]; + char ALT[10]; + + char SLAT[10]; + char SLON[10]; + char SALT[10]; + char SROT_X[10]; + char SROT_Y[10]; + char SROT_Z[10]; + + char SIP[16]; + char SNAME[64]; + + char TS[64]; + sprintf( AZ,"%0.3f", tTARGET->local_target.fi ); + sprintf( EL,"%0.3f", tTARGET->local_target.tetta ); + sprintf( RA,"%0.3f", tTARGET->local_target.r ); + sprintf( WID,"%0.3f", tTARGET->area ); + sprintf( LAT,"%0.6f", tTARGET->global_target.lat ); + sprintf( LON,"%0.6f", tTARGET->global_target.lon ); + sprintf( ALT,"%0.6f", tTARGET->global_target.alt ); + sprintf( TS, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", + ( Evt->sTS.tm_year+1900), + (Evt->sTS.tm_mon+1), + Evt->sTS.tm_mday, + Evt->sTS.tm_hour, + Evt->sTS.tm_min, + Evt->sTS.tm_sec, + (Evt->m_UMSTS%1000) + ); + sprintf( SLAT,"%0.6f", tTARGET->source_position.lat ); + sprintf( SLON,"%0.6f", tTARGET->source_position.lon ); + sprintf( SALT,"%0.6f", tTARGET->source_position.alt ); + + sprintf( SROT_X,"%0.6f", tTARGET->source_orient.rot_x ); + sprintf( SROT_Y,"%0.6f", tTARGET->source_orient.rot_y ); + sprintf( SROT_Z,"%0.6f", tTARGET->source_orient.rot_z ); + CSTR tN = m_pDBC->getNodeName( Evt->m_nSourceNodeID ); + if ( tN ) { + strncpy( SNAME, tN, 64 ); + free( tN ); + } else { + strncpy(SNAME, "Noname-Laser-Detector", 64); + }; + + if ( 0 ) { + strncpy( SIP, tN, 16 ); + free( tN ); + } else { + strncpy(SIP, "192.168.1.24", 16); + }; + + tDATA = buildTemplate( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ]->tpl, + Evt->m_nSourceNodeID, + TS, + Evt->m_UUID, + AZ, + RA, + WID, + EL, + LAT, + LON, + ALT, + NULL, + SNAME, + SIP, + SLAT, + SLON, + SALT, + SROT_X, + SROT_Y, + SROT_Z + ); + }; + break; + }; + case EVT_FH_JAMER_ON: + case EVT_FH_JAMER_OFF: + case EVT_FH_FLY_TO: + case EVT_FH_WAYPOINT: + case EVT_FH_INTERCEPT_OK: + case EVT_FH_INTERCEPT_NOK: + case EVT_FH_BUSY: + case EVT_FH_LANDED:{ + FH_MISSION_DATA * tPOINT=(FH_MISSION_DATA *) Evt->m_pEvtData; + if( tPOINT ) { + char TS[64]; + char LAT[10]; + char LON[10]; + char ALT[10]; + sprintf( LAT,"%0.6f", tPOINT->location.lat ); + sprintf( LON,"%0.6f", tPOINT->location.lon ); + sprintf( ALT,"%0.6f", tPOINT->location.alt ); + sprintf( TS, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", + ( Evt->sTS.tm_year+1900), + (Evt->sTS.tm_mon+1), + Evt->sTS.tm_mday, + Evt->sTS.tm_hour, + Evt->sTS.tm_min, + Evt->sTS.tm_sec, + (Evt->m_UMSTS%1000) + ); + tDATA = buildTemplate( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ]->tpl, + Evt->m_nSourceNodeID, + TS, + Evt->m_UUID, + NULL, + NULL, + NULL, + NULL, + LAT, + LON, + ALT, + tPOINT->missionID + ); + }; + break; + }; + default:{ + break; + }; + }; + if( tDATA!= NULL ) { +#ifdef KAFKA_DUMMY_SEND + LOG( tDATA ); +#else + m_pProtocol->issuePost( m_pEvtTemplates[ Evt->m_eClass ][ Evt->m_eType ]->topic, tDATA, strlen( tDATA ) ); +#endif + } else { + LOG_ERROR("Cant Build Template!"); + }; + }; + }; +}; + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/mojo/rgooseModuleKafka.h b/lib/App/mojo/rgooseModuleKafka.h new file mode 100644 index 00000000..e91662ad --- /dev/null +++ b/lib/App/mojo/rgooseModuleKafka.h @@ -0,0 +1,86 @@ +#ifndef __RGOOSE_KAFKA_MODULE_HEADERS__ +#define __RGOOSE_KAFKA_MODULE_HEADERS__ + + +#include "rgooseModule.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" +#include "../data/protocol/protocolKAFKA.h" + +//#define SIMULATOR +//#define KAFKA_DUMMY_SEND + +#define KAFKA_TPL_SUBST_ID "%%ID%%" +#define KAFKA_TPL_SUBST_UUID "%%UUID%%" +#define KAFKA_TPL_SUBST_TS "%%TIMESTAMP%%" +#define KAFKA_TPL_SUBST_AZ "%%AZIMUTH%%" +#define KAFKA_TPL_SUBST_RANGE "%%RANGE%%" +#define KAFKA_TPL_SUBST_EL "%%ELEVATION%%" +#define KAFKA_TPL_SUBST_WIDTH "%%WIDTH%%" +#define KAFKA_TPL_SUBST_LON "%%LON%%" +#define KAFKA_TPL_SUBST_LAT "%%LAT%%" +#define KAFKA_TPL_SUBST_ALT "%%ALT%%" +#define KAFKA_TPL_SUBST_EXEVTD "%%EXEVTID%%" +#define KAFKA_TPL_SUBST_SRC_LON "%%SRC_LON%%" +#define KAFKA_TPL_SUBST_SRC_LAT "%%SRC_LAT%%" +#define KAFKA_TPL_SUBST_SRC_ALT "%%SRC_ALT%%" +#define KAFKA_TPL_SUBST_SRC_ROT_X "%%SRC_ROT_X%%" +#define KAFKA_TPL_SUBST_SRC_ROT_Y "%%SRC_ROT_Y%%" +#define KAFKA_TPL_SUBST_SRC_ROT_Z "%%SRC_ROT_Z%%" +#define KAFKA_TPL_SUBST_SRC_IP "%%SRC_IP%%" +#define KAFKA_TPL_SUBST_SRV_IP "%%SRV_IP%%" +#define KAFKA_TPL_SUBST_SRV_NAME "%%SRV_NAME%%" +#define KAFKA_TPL_SUBST_SRC_NAME "%%SRC_NAME%%" +#define KAFKA_TPL_SUBST_MSG_UUID "%%MUID%%" + + +#define FH_DEFAULT_JAMING_TIME 10 + +class argusModuleKafka: public argusKernelModule, public basicThread { + private: + KAFKA_SETTINGS *m_pSettings; + protocolKAFKA *m_pProtocol; + bool m_bConsumerEnabled; + basicEventHeap *m_pEventHeap; + KAFKA_TEMPLATE ***m_pEvtTemplates; + + int32_t partition; + int64_t start_offset; + char m_sServerIP[48]; + char m_sServerName[48]; + unsigned long long m_llTicks; + CSTR buildTemplate( CSTR tpl, + uint32_t source_id, + CSTR ts, + CSTR uuid = NULL, + CSTR az = NULL, + CSTR range = NULL, + CSTR width = NULL, + CSTR el = NULL, + CSTR lat = NULL, + CSTR lon = NULL, + CSTR alt = NULL, + CSTR extID = NULL, + CSTR src_Name = NULL, + CSTR src_IP = NULL, + CSTR src_lat = NULL, + CSTR src_lon = NULL, + CSTR src_alt = NULL, + CSTR src_rot_x = NULL, + CSTR src_rot_y = NULL, + CSTR src_rot_z = NULL + ); + protected: + virtual void m_fThreadProc( void ); + public: + explicit argusModuleKafka( uint32_t ModuleID ); + virtual ~argusModuleKafka(); + + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); +}; + + +#endif diff --git a/lib/App/mojo/rgooseModuleModemManager.cpp b/lib/App/mojo/rgooseModuleModemManager.cpp new file mode 100644 index 00000000..1362517b --- /dev/null +++ b/lib/App/mojo/rgooseModuleModemManager.cpp @@ -0,0 +1,323 @@ +#include "rgooseModuleModemManager.h" + +#define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_MODEM", this, X ) +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + argusKernelModule::m_pLog->Log( "MOD_MODEM", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_MODEM", this, _LOG_ERROR, X ); +#endif + + +argusModuleModemManager::argusModuleModemManager( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_MODEM_MANAGER ), basicThread(){ + LOG("Creating!"); + if( checkCmdExists("mmcli") > 0 ){ + //Modem Manager Exists + LOG("Manager OK!"); + }; +}; + +argusModuleModemManager::~argusModuleModemManager(){ + +}; + +bool argusModuleModemManager::reloadSettings(){ + return true; +}; + +bool argusModuleModemManager::startService(){ + return true; +}; + +bool argusModuleModemManager::stopService( bool force ){ + return true; +}; + +void argusModuleModemManager::m_fThreadProc( void ){ + +}; + +void argusModuleModemManager::dispatchEvent(EVENT_CONTAINER *Evt){ +}; + +bool argusModuleModemManager::validate(){ + DBC_MODEM_DATA *tDATA = getModemInfo( 0 ); + if ( tDATA ) { + free( tDATA ); + }; + return true; +}; + + +void parseModemsInSystem(){ + "mmcli --list-modems"; + +}; + +typedef enum E_CFG_TAG_ID{ + CFG_GENERAL = 0, + CFG_HARDWARE = 1, + CFG_SYSTEM, + CFG_STATUS, + CFG_MODES, + CFG_BANDS, + CFG_IP, + CFG_EPS, + CFG_3GPP, + CFG_SIM, + CFG_BEARER, + CFG_COUNT +}CFG_TAG_ID; + +const CSTR cfg_tags[]={ + "General", + "Hardware", + "System", + "Status", + "Modes", + "Bands", + "IP", + "3GPP EPS", + "3GPP", + "SIM", + "Bearer" +}; + +DBC_MODEM_DATA *argusModuleModemManager::getModemInfo( uint32_t modem_id ){ + char tB[1024]; + char expBuf[1024]; + FILE * fd = NULL; + CFG_TAG_ID cMode = CFG_GENERAL; + DBC_MODEM_DATA * retVal = (DBC_MODEM_DATA *)malloc(sizeof(DBC_MODEM_DATA)); + + if ( retVal != NULL ) { + memset( retVal, 0 , sizeof(DBC_MODEM_DATA)); + sprintf( tB, "mmcli --modem=%d", modem_id ); + fd = popen( tB, "r"); + if (fd!= NULL ) { + retVal->modem_id = modem_id; + while ( !feof( fd )) { + fgets( (CSTR)tB, 1024, fd ); + trim( tB ); + if( strstr(tB, "error:" ) != NULL){ + free( retVal ); + retVal = NULL; + break; + }; + LOG(tB); + strncpy( expBuf, tB, 1024 ); + CArray *CA = explode( ':', expBuf ); + if( CA ){ + if( CA->size() ){ + for( int ii = CFG_GENERAL; ii < CFG_COUNT; ii++ ){ + if( strstr( CA->at(0), cfg_tags[ii] ) != NULL ){ + cMode = (CFG_TAG_ID) ii; + break; + }; + }; + switch( cMode ){ + case CFG_GENERAL:{ + //LOG("GEN"); + if ( strstr( CA->at(0), "device id") != NULL ) { + trim(CA->at(1)); + strncpy( retVal->dbus_dev_id, CA->at(1), 64 ); + retVal->dbus_dev_id[64] = (char)0; + break; + }; + break; + }; + case CFG_HARDWARE:{ + //LOG("HW"); + if ( strstr( tB, "manufacturer") != NULL ) { + trim(CA->at(1)); + strncpy( retVal->hw_manufac, CA->at(1), 64); + retVal->hw_manufac[64] = (char)0; + break; + }; + if ( strstr( tB, "model") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->hw_model, CA->at(1), 64); + retVal->hw_model[64] = (char)0; + break; + }; + if ( strstr( tB, "h/w revision") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->hw_revision, CA->at(1), 64); + retVal->hw_revision[64] = (char)0; + break; + }; + if ( strstr( tB, "revision") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->hw_version, CA->at(1), 32); + retVal->hw_revision[32] = (char)0; + break; + }; + if ( strstr( tB, "equipment id") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->hw_id, CA->at(1), 32); + retVal->hw_id[32] = (char)0; + break; + }; + break; + }; + case CFG_SYSTEM:{ + //LOG("SYS"); + if ( strstr( tB, "ports") != NULL ) { + trim(CA->at(1)); + CArray *CZ = explode( ':', CA->at(1) ); + if ( CZ ) { + int CP = 0; + for (int z=0; z< CZ->size(); z++) { + if ( strstr(CZ->at(z),"(at)")!= NULL ) { + if (CP == 0 ) { + retVal->at_uart_id = 1;//getUartIdByDevice(); + } else { + retVal->at_uart_id_aux = 2; + }; + CP++; + }; + if (CP == 2) break; + }; + delete( CZ ); + }; + break; + }; + break; + }; + case CFG_STATUS:{ + //LOG("STAT"); + if ( strstr( tB, "power state") != NULL ) { + if ( strstr(CA->at(1),"on") ) { + retVal->power[0] = 'E'; + retVal->power[1]=(char)0; + } else { + retVal->power[0] = 'D'; + retVal->power[1]=(char)0; + }; + break; + }; + if ( strstr( tB, "state") != NULL ) { + if ( strstr(CA->at(1),"registered") ) { + retVal->status[0]='R'; + retVal->status[1]=(char)0; + } else { + }; + break; + }; + if ( strstr( tB, "access tech") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->conmection_tech, CA->at(1), 5); + retVal->conmection_tech[5] = (char)0; + break; + }; + if ( strstr( tB, "signal quality") != NULL ) { + trim(CA->at(1)); + retVal->signal = atoi(CA->at(1)); + break; + }; + break; + }; + case CFG_MODES:{ + //LOG("MOD"); + //if ( strstr( CA->at(0), "current") != NULL ) { + // trim(CA->at(1)); + // strncpy( retVal->hw_manufac, CA->at(1), 64); + // retVal->hw_manufac[64] = (char)0; + // break; + //}; + break; + }; + case CFG_IP:{ + //LOG("IP"); + break; + }; + case CFG_EPS:{ + //LOG("EPS"); + break; + }; + case CFG_3GPP:{ + // LOG("3GPP"); + if ( strstr( tB, "imei") != NULL ) { + trim(CA->at(1)); + strncpy( retVal->imei, CA->at(1), 16); + retVal->imei[16] = (char)0; + break; + }; + if ( strstr( tB, "operator id") != NULL ) { + trim(CA->at(1)); + retVal->operator_id = atoi(CA->at(1)); + break; + }; + if ( strstr( tB, "registration") != NULL ) { + trim(CA->at(1)); + strncpy(retVal->registration, CA->at(1), 64); + retVal->registration[64] = (char)0; + break; + }; + break; + }; + case CFG_SIM:{ + // LOG("SIM"); + break; + }; + case CFG_BEARER:{ + // LOG("BEAR"); + break; + }; + //default: LOG("UNK"); + }; + } else { + LOG("No CA Parts!"); + }; + delete( CA ); + } else { + LOG("No CA!"); + }; + }; + fclose(fd); + }; + }; +#ifdef DEBUG_EXTRA + if ( retVal ) { + char ttB[256]; + sprintf(ttB, "Modem ID: [%d]", retVal->modem_id); + LOG(ttB); + sprintf(ttB, "Modem HW Manufac: [%s]", retVal->hw_manufac); + LOG(ttB); + sprintf(ttB, "Modem HW Model: [%s]", retVal->hw_model); + LOG(ttB); + sprintf(ttB, "Modem HW id: [%s]", retVal->hw_id); + LOG(ttB); + sprintf(ttB, "Modem Revision id: [%s]", retVal->hw_revision); + LOG(ttB); + sprintf(ttB, "Modem Revision Version: [%s]", retVal->hw_version); + LOG(ttB); + sprintf(ttB, "Modem DBus id: [%s]", retVal->dbus_dev_id); + LOG(ttB); + sprintf(ttB, "Modem IMEI: [%s]", retVal->imei); + LOG(ttB); + sprintf(ttB, "Modem Access Tech: [%s]", retVal->conmection_tech); + LOG(ttB); + sprintf(ttB, "Modem Operator: [%d]", retVal->operator_id); + LOG(ttB); + sprintf(ttB, "Modem Power: [%s]", retVal->power); + LOG(ttB); + sprintf(ttB, "Modem Registration: [%s]", retVal->registration); + LOG(ttB); + sprintf(ttB, "Modem Signal Power: [%d%%]", retVal->signal); + LOG(ttB); + sprintf(ttB, "Modem Status: [%s]", retVal->status); + LOG(ttB); + }; +#endif + return retVal; +}; + +#undef LOG +#undef LOG_ERROR + + + diff --git a/lib/App/mojo/rgooseModuleModemManager.h b/lib/App/mojo/rgooseModuleModemManager.h new file mode 100644 index 00000000..f58f8b04 --- /dev/null +++ b/lib/App/mojo/rgooseModuleModemManager.h @@ -0,0 +1,24 @@ +#ifndef __ARGUS_MODULE_MODEM_MANAGER_HEADER__ +#define __ARGUS_MODULE_MODEM_MANAGER_HEADER__ + +#include "rgooseModule.h" +#include "../components/base/basicThread.h" + +class argusModuleModemManager: public argusKernelModule, public basicThread { + private: + DBC_MODEM_DATA * getModemInfo( uint32_t modem_id ); + protected: + /* From Basic Thread */ + virtual void m_fThreadProc( void ); + public: + explicit argusModuleModemManager( uint32_t moduleID ); + ~argusModuleModemManager(); + /* From Kernel Module */ + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); +}; + +#endif diff --git a/lib/App/mojo/rgooseModuleOnvifObserver.cpp b/lib/App/mojo/rgooseModuleOnvifObserver.cpp new file mode 100644 index 00000000..91878943 --- /dev/null +++ b/lib/App/mojo/rgooseModuleOnvifObserver.cpp @@ -0,0 +1,602 @@ +#include "rgooseModuleOnvifObserver.h" +#include "mojoKernel.h" +//#include "rgooseHardwareResourceNetworkProvider.h" + +#define SEARCH_REQUEST_STRING "uuid:84ede3de-7dec-11d0-c360-f01234567890urn:schemas-xmlsoap-org:ws:2005:04:discoveryhttp://schemas.xmlsoap.org/ws/2005/04/discovery/Probedn:NetworkVideoTransmitter" +#define SEARCH_REQUEST_STRING2323 "\n" \ + "\n" \ + "\n" \ + "urn:uuid:ac9823ee-6813-498c-8c1b-6272a22353f7\n" \ + "\n" \ + "http ://schemas.xmlsoap.org/ws/2005/04/discovery/Probe\n" \ + "\n" \ + "urn:schemas-xmlsoap-org:ws:2005:04:discovery\n" \ + "\n" \ + "\n" \ + "\n" \ + "ssdp:any\n" \ + "\n" \ + "\n" \ + "\r\n\r\n" +#define HTTP_OK "200 OK" + +/****************************************************************** +** Action Defines * +*******************************************************************/ +#define HTTP_HEADER_ACTION "POST %s HTTP/1.1\r\n" \ + "HOST: %s:%u\r\n" \ + "SOAPACTION:\"%s#%s\"\r\n" \ + "CONTENT-TYPE: text/xml ; charset=\"utf-8\"\r\n"\ + "Content-Length: %d \r\n\r\n" + +#define SOAP_ACTION "\r\n" \ + "\r\n" \ + "\r\n" \ + "\r\n%s" \ + "\r\n" \ + "\r\n" \ + "\r\n" + +#define PORT_MAPPING_LEASE_TIME "63072000" //two year + +#define ADD_PORT_MAPPING_PARAMS "\r\n" \ + "%u\r\n"\ + "%s\r\n" \ + "%u\r\n"\ + "%s\r\n" \ + "1\r\n" \ + "%s\r\n" \ + "" \ + PORT_MAPPING_LEASE_TIME \ + "\r\n" + + + +#define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_ONVIF", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + argusKernelModule::m_pLog->Log( "MOD_ONVIF", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_ONVIF", this, _LOG_ERROR, X ); +#endif + + +argusModuleOnvifObserver::argusModuleOnvifObserver( uint32_t ModuleID ): argusKernelModule( ModuleID, ARGUS_MODULE_ONVIF_OBSERVER ), basicThread(){ + m_bEnabled = false; + m_pEventHeap = basicEventHeap::getInstance(); + + m_bCurrentNIF = 0; + m_bProbeIsActive = false; + m_bDetached = false; +#ifdef __linux__ + m_bWSAOK = true; +#else + m_bWSAOK = false; + WORD wVersionRequested; + WSADATA wsaData; + int err; + wVersionRequested = MAKEWORD(2, 2); + err = WSAStartup(wVersionRequested, &wsaData); + if (err != 0){ + LOG_ERROR("WSAStartup failed with error"); + } else m_bWSAOK = true; +#endif +}; + +argusModuleOnvifObserver::~argusModuleOnvifObserver(){ + if( !m_bDetached ) stopService( true ); +}; + +bool argusModuleOnvifObserver::startService(){ + LOG("Starting Service!"); + if( !m_bWSAOK ) return false; + m_bEnabled = reloadSettings(); + return init(); +}; + +bool argusModuleOnvifObserver::stopService( bool force ){ + m_bEnabled = false; + if( !m_bDetached ) m_bDetached = uninit(); + if( m_bDetached ) { + //Clear Results + m_mResultProtector.lock(); + if (m_vResultPool.size()){ // Clear structures + for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){ + free(*index); + }; + m_vResultPool.clear(); + }; + m_mResultProtector.unlock(); + }; + return m_bDetached; +}; + +void argusModuleOnvifObserver::m_fThreadProc(){ + int socketFD; + int RetVal; + struct sockaddr_in r_address; + bool bOptVal; + int bOptLen; + int iOptLen; + uint16_t bCounterTO = 600; // 3 second + char rBuffer[MAX_BUFF_SIZE]; +#ifdef DEBUG + char tB[128]; + LOG("Module Started!"); +#endif + m_bDetached = false; + m_bThreadStatus = TH_WORKING; + while( m_bThreadStatus < TH_ENDED ) { + if ( m_bEnabled ) { + if ( m_bProbeIsActive ) { + if( socketFD > -1 ){ + if( bCounterTO-- ){ + memset( rBuffer, 0, MAX_BUFF_SIZE ); +#ifdef DEBUG_EXTRA + struct sockaddr src_addr; + socklen_t addrlen = sizeof( src_addr ); + RetVal = recvfrom( socketFD, rBuffer, MAX_BUFF_SIZE, 0, &src_addr, &addrlen ); + if ( RetVal > -1 ) { + sprintf(tB, "(%d){%d}MSG[%d] from %s", bCounterTO, socketFD, RetVal, inet_ntoa(((struct sockaddr_in *)&src_addr)->sin_addr)); + LOG( tB ); + }; +#else //http://192.168.200.127/axis-cgi/com/ptz.cgi?info=1&camera=1 + RetVal = recvfrom( socketFD, rBuffer, MAX_BUFF_SIZE, 0, NULL, NULL ); +#endif + if ((RetVal == -1) && /*(errno != EAGAIN) &&*/ (errno != EINTR) && (errno != EWOULDBLOCK)) { + LOG_ERROR("Error acures while reading UDP package"); + close( socketFD ); + m_bProbeIsActive = false; + continue; // Error ocured but continue to next address + }; + if( RetVal < 1 ){ + //LOG("SLEEP"); + SLEEP(DEFAULT_THREAD_SLEEP_TIME); + continue; // No Data - wait to next time + }; + OBSERVER_RESULT *tResult = parseXML( rBuffer ); + if ( tResult ) { + m_mResultProtector.lock(); + m_vResultPool.push_back( tResult ); + m_mResultProtector.unlock(); +#ifdef DEBUG + LOG("Probe Finished!"); +#endif + } else { +#ifdef DEBUG + LOG("Probe Finished with unrecognized data!"); +#endif + }; + continue; //To Fetch Another responces + } else { +#ifdef DEBUG + LOG("Probe Finished By Timeout!"); +#endif + }; +#ifdef __linux__ + close(socketFD); +#else + closesocket(socketFD); +#endif + }; + m_bProbeIsActive = false; + //Sleep 5 minutes if done all scans + if ( m_bCurrentNIF == 0 ){ + for( int i=12000; i, m_bThreadStatus < TH_ENDED; i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + }; + } else { + // start new probe; + m_mNIFMUTEX.lock(); + if ( m_vNIFIPS.size() ) { +#ifdef DEBUG + sprintf( tB, "Starting probe on %s address", m_vNIFIPS.at(m_bCurrentNIF) ); + LOG( tB ); +#endif + socketFD = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); + if( socketFD > -1 ){ + CSTR send_buff = (CSTR)SEARCH_REQUEST_STRING; + r_address.sin_family = AF_INET; + r_address.sin_port = htons(HTTPMU_HOST_PORT); + r_address.sin_addr.s_addr = inet_addr(m_vNIFIPS.at(m_bCurrentNIF)); + bOptVal = true; +#ifdef DEBUG_EXTRA + LOG("Set Broadcast Flag"); +#endif + RetVal = setsockopt( socketFD, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen ); + struct group_req req; + req.gr_interface = 0; + memcpy( &req.gr_group, &r_address, sizeof(r_address)); + RetVal = setsockopt( socketFD, IPPROTO_IP, MCAST_JOIN_GROUP, (char*)&req, sizeof(req) ); +/* +#include +#include +#include +#include +#include +#include +#include +#include +#include +// Join multicast group, support both IPv4 and IPv6. * @param sockfd socket descripter * @param grp sockaddr * @param grplen sockaddr length * @return 0:on success; non-zero:on failed +static int mcast_join(int sockfd, const struct sockaddr *grp, socklen_t grplen){ + + #if MCAST_JOIN_GROUP + struct group_req req; + req.gr_interface = 0; + if (grplen > sizeof(req.gr_group)) { + errno = EINVAL; + return -1; + } + memcpy(&req.gr_group, grp, grplen); + return (setsockopt(sockfd, IPPROTO_IP, MCAST_JOIN_GROUP, &req, sizeof(req))); +#else + switch (grp->sa_family) { + case AF_INET: { + struct ip_mreq mreq; + struct ifreq ifreq; + memcpy(&mreq.imr_multiaddr, &((const struct sockaddr_in *) grp)->sin_addr, sizeof(struct in_addr)); + mreq.imr_interface.s_addr = htonl(INADDR_ANY); + return (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, + &mreq, sizeof(mreq))); + } + #ifdef IPV6 + #ifndef IPV6_JOIN_GROUP // APIv0 compatibility + #define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP + #endif + case AF_INET6: { + struct ipv6_mreq mreq6; + memcpy(&mreq6.ipv6mr_multiaddr, &((const struct sockaddr_in6 *) grp)->sin6_addr, sizeof(struct in6_addr)); + mreq6.ipv6mr_interface = 0; + return (setsockopt(sockfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq6, sizeof(mreq6))); + } + #endif + default: + errno = EAFNOSUPPORT; + return -1; + } +#endif +}; + +int main(int argc, char **argv){ + + int fd = socket(AF_INET, SOCK_DGRAM, 0); + struct sockaddr_in grp; + bzero(&grp, sizeof(grp)); + grp.sin_family = AF_INET; + grp.sin_addr.s_addr = inet_addr("224.0.0.1");; + if (mcast_join(fd, (struct sockaddr*)(&grp), sizeof(grp))) + perror("Join multicast group failed"); +} + +*/ + + //The broadcast address to be used may be determined by issuing an ioctl() with the SIOCGIFBRDADDR request. + + if ( RetVal > -1 ) { + LOG_ERROR("Setting Socked as Broadcasted Error!"); + }; + + // + struct sockaddr_in tServerAddr; + memset( &tServerAddr, 0, sizeof(tServerAddr) ); + tServerAddr.sin_family = AF_INET; // IPv4 + tServerAddr.sin_addr.s_addr = inet_addr( "0.0.0.0" ); //INADDR_ANY; + tServerAddr.sin_port = htons(rand( 20000, 40000)); + + // Bind the socket with the server address + RetVal = bind( socketFD, (const struct sockaddr *)&tServerAddr, sizeof(tServerAddr)); + if ( RetVal > -1 ) { + LOG_ERROR("Bind Socked Error!"); + }; +#ifdef DEBUG_EXTRA + LOG("Sending Probe Request"); +#endif + RetVal = sendto( socketFD, send_buff, strlen(send_buff), 0, (struct sockaddr*)&r_address, sizeof(struct sockaddr_in)); + if ( RetVal > -1 ) { +#ifdef DEBUG_EXTRA + sprintf( tB, "Sent %d Bytes of %d", RetVal, strlen(send_buff) ); + LOG( tB ); +#endif + +#ifdef __linux__ + fcntl( socketFD, F_SETFL, fcntl( socketFD, F_GETFL, 0) | O_NONBLOCK ); +#else + u_long val = 1; + ioctlsocket( socketFD, FIONBIO, &val );//none block +#endif + bCounterTO = 600; + m_bProbeIsActive = true; + } else { +#ifdef DEBUG + // Failure to send probe package + LOG_ERROR("Error in sending Probe Request"); +#endif +#ifdef __linux__ + close(socketFD); +#else + closesocket(socketFD); +#endif + }; + }; + m_bCurrentNIF++; + if ( m_bCurrentNIF == m_vNIFIPS.size() ) m_bCurrentNIF = 0; + }; + m_mNIFMUTEX.unlock(); + }; + } else { + //Sleep 3 Sec. + for( int i=300; i, m_bThreadStatus < TH_ENDED; i-- ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); + }; + }; + m_bDetached = true; +}; + +void argusModuleOnvifObserver::dispatchEvent(EVENT_CONTAINER *Evt){ + if(!m_bEnabled) { +#ifdef DEBUG + LOG("Module Disabled!"); +#endif + return; + } + if( Evt == NULL ) return; + +}; + +bool argusModuleOnvifObserver::reloadSettings(){ + m_mNIFMUTEX.lock(); + if( m_vNIFIPS.size() ) { + for ( vectorCSTR::iterator idx=m_vNIFIPS.begin(); idx < m_vNIFIPS.end(); idx++ ) free(*idx); + m_vNIFIPS.clear(); + }; + m_mNIFMUTEX.unlock(); + if( m_pKernel != NULL ){ +#ifdef DEBUG + LOG("Check IPS"); +#endif + argusHardwareManager *tHWM = m_pKernel->getHardwareManager(); + if( tHWM != NULL ) { +#ifdef DEBUG + LOG("Check IPS 11"); +#endif + DBC_INT_LIST *rIDS = tHWM->requestResourcesByType( ARGUS_HARDWARE_PROVIDER_NETWORK ); + if( rIDS != NULL ) { +#ifdef DEBUG + LOG("Check IPS 22"); +#endif + for( DBC_INT_LIST::iterator idx = rIDS->begin(); idx < rIDS->end(); idx++ ){ +#ifdef DEBUG + LOG("Check IPS 33"); +#endif + argusHardwareResourceNetwork *tRES = (argusHardwareResourceNetwork *) tHWM->requestResource( ARGUS_HARDWARE_PROVIDER_NETWORK, *idx ); + if( tRES != NULL ) { +#ifdef DEBUG + LOG("Have NIF Resource"); +#endif + CSTR BC = tRES->getBroadcast(); + if( BC!= NULL ) { +#ifdef DEBUG + LOG("Have BC Address"); + LOG(BC); +#endif + m_mNIFMUTEX.lock(); + m_vNIFIPS.push_back( BC ); + m_mNIFMUTEX.unlock(); +#ifdef DEBUG + LOG("NIF defined"); +#endif + } +#ifdef DEBUG + else { + LOG("NO BC Address"); + } +#endif + ; + } else { + LOG_ERROR("Cannot Get Resource!"); + }; + }; + delete( rIDS ); + } else { + LOG("No Networks Detected!"); + m_bEnabled = false; + }; + } else { + LOG_ERROR("No HW Manager"); + }; + } else { + LOG_ERROR("Kernel Not Assigned!" ); + }; +#ifdef DEBUG + LOG("Default Probe"); + LOG( HTTPMU_HOST_ADDRESS ); +#endif + CSTR tBC = (CSTR) malloc(16); + if ( tBC ) { + sprintf(tBC, HTTPMU_HOST_ADDRESS ); + m_mNIFMUTEX.lock(); + m_vNIFIPS.push_back( tBC ); + m_mNIFMUTEX.unlock(); + } else { + LOG_ERROR("Malloc Error!"); + }; + return true; +}; + +OBSERVER_RESULT *argusModuleOnvifObserver::parseXML( CSTR data ){ + OBSERVER_RESULT *retVal = NULL; + if( data!=NULL ){ + XMLResults tParseResults; + XMLNode response = XMLNode::parseString( data, "root", &tParseResults ); + if( tParseResults.error ){ + char tBuffer[CTEXT]; + sprintf( tBuffer, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); + LOG_ERROR( tBuffer ); + } else { + if( response.isEmpty() ){ + LOG_ERROR("The device descripe XML file is not a valid XML file. Cann't find root element."); + } else { +#ifdef DEBUG + LOG("Probe XML parsed"); +#endif + XMLNode Body = response.getChildNode( "Body", 0 ); + if(!Body.isEmpty()){ + LOG("Have Body elm"); + XMLNode ProbeMatches = Body.getChildNode("ProbeMatches", 0);//EndpointReference + if(!ProbeMatches.isEmpty()) { + LOG("Have ProbeMathes elm"); + int matches = ProbeMatches.nChildNode(); + for(int index=0;indexsize(); j++) { + if( strlen(tArr->at(j)) > 10 ) { + sprintf(retVal->RefID,"%s",tArr->at(j)); + break; + }; + }; + tArr->clear(); + delete(tArr); + + }; + }; + } + { + XMLNode node = ProbeMatch.getChildNode("Types", 0); + if( !node.isEmpty() ){ + char tBuf[CLOG]; + sprintf(tBuf,"%s", node.getText(0)); + CArray *tArr; + tArr = explode(' ',tBuf); + sprintf(retVal->Type,"%s",tArr->at(0)); + tArr->clear(); + delete(tArr); + } + } + { + XMLNode node = ProbeMatch.getChildNode("Scopes", 0); + char tBuf[CLOG]; + sprintf( tBuf,"%s", node.getText(0) ); + CArray *tArr = explode(' ',tBuf); + if( tArr->size() > 0 ) { + for( int index = 0; index < tArr->size(); index++){ + char *tPtr; + if( tPtr = strstr( tArr->at(index), "mac/" ) ){ + sprintf(retVal->MAC,"%s",tPtr+4); + }; + if( tPtr = strstr( tArr->at(index), "hardware/" ) ){ + sprintf(retVal->Hardware,"%s",tPtr+9); + }; + if( tPtr = strstr( tArr->at(index), "name/" ) ){ + sprintf(retVal->Name,"%s",tPtr+5); + }; + if (tPtr = strstr(tArr->at(index), "MAC/")) { + sprintf(retVal->MAC, "%s", tPtr + 4); + }; + if (tPtr = strstr(tArr->at(index), "HARDWARE/")) { + sprintf(retVal->Hardware, "%s", tPtr + 9); + }; + if (tPtr = strstr(tArr->at(index), "NAME/")) { + sprintf(retVal->Name, "%s", tPtr + 5); + }; + }; + tArr->clear(); + }; + delete(tArr); + } + { + XMLNode node = ProbeMatch.getChildNode("XAddrs", 0); + char tBuf[CLOG]; + sprintf(tBuf,"%s", node.getText(0)); + CArray *tArr; + tArr = explode(' ',tBuf); + if( tArr->size() > 0 ) { + for(int index=0; index < tArr->size(); index++) { + if( strstr( tArr->at(index), "[" ) != NULL ){ + // IPv6 + } else{ + // IPv4 + sprintf(retVal->XAddrs,"%s",tArr->at(0)); + }; + }; + tArr->clear(); + }; + delete(tArr); + } + }; + }; + }; + }; + }; + }; + }; + }; + return retVal; +}; + + +bool argusModuleOnvifObserver::validate(){ + m_mResultProtector.lock(); + if( m_vResultPool.size() ){ // Clear structures + for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){ +#ifdef DEBUG + char tBuffer[256]; + sprintf( tBuffer, "Found Camwera [%s] %s", (*index)->XAddrs, (*index)->RefID ); + LOG( tBuffer ); +#endif + uint32_t cid = m_pDBC->getCamId( (*index)->RefID ); //isCameraListed( DiscoverResults->at(index)->RefID ); + if( cid ) { +#ifdef DEBUG + sprintf( tBuffer, "Camera is Listed as %d", cid ); + LOG( tBuffer ); +#endif + m_pDBC->updateIPCam( m_pKernel->getSiteId(), cid, (*index)->XAddrs );// DiscoverResults->at(index)); + } else { + // Uncknown camera - no checking +#ifdef DEBUG + LOG("Camera is Not Listed"); +#endif + m_pDBC->addIPCam( m_pKernel->getSiteId(), (*index) ); + }; + free(*index); + } + m_vResultPool.clear(); +#ifdef DEBUG_EXTRA + LOG("Clear Structs Done!"); +#endif + } else { +#ifdef DEBUG_EXTRA + LOG("No Online IP Cameras in Network"); +#endif + }; + m_mResultProtector.unlock(); + return true; +}; + + + +#undef LOG +#undef LOG_ERROR + diff --git a/lib/App/mojo/rgooseModuleOnvifObserver.h b/lib/App/mojo/rgooseModuleOnvifObserver.h new file mode 100644 index 00000000..bfae3834 --- /dev/null +++ b/lib/App/mojo/rgooseModuleOnvifObserver.h @@ -0,0 +1,88 @@ +#ifndef __ARGUS_MODULE_ONVIF_OBSERVER_HEADER__ +#define __ARGUS_MODULE_ONVIF_OBSERVER_HEADER__ + +#include "../data/protocol/xmlParser.h" +#include "rgooseModule.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicMutex.h" +#include "../components/base/basicEventHeap.h" + + +#pragma warning(disable: 4251) + +#define HTTPMU_HOST_ADDRESS "239.255.255.250" +#define HTTPMU_HOST_PORT 3702 + + +//#define DEBUG_ONVIF_PRINTOUT_MESSAGES + +#define DEFAULT_HTTP_PORT 80 + +typedef std::vector vectorOBSERVER_RESULT; + +class argusModuleOnvifObserver; + +typedef struct S_PROBE_CTX{ + int AddressID; + char IpAddress[16]; + int Port; + int socketFD; + char buff[MAX_BUFF_SIZE + 1]; + CSTR send_buff; + CSTR recv_buff; + struct sockaddr_in r_address; + bool bOptVal; + int bOptLen; + int iOptLen; + int RetVal; + int index; + bool isFinished; + argusModuleOnvifObserver * observer; +}PROBE_CTX; + +typedef struct S_OBSERVER_CTX{ + DWORD m_dwThreadID; +#ifdef __linux__ + pthread_t m_hThreadHandle; +#else + HANDLE m_hThreadHandle; +#endif + PROBE_CTX * context; +}OBSERVER_CTX; + +typedef std::vector vectorOBSERVER_CTX; + + +class argusModuleOnvifObserver: public argusKernelModule, public basicThread { + private: + basicEventHeap * m_pEventHeap; + //enumeratorInfo m_vLocalDevices; + //localIpAddresses m_vIpAddresses; + + vectorOBSERVER_RESULT m_vResultPool; + basicMutex m_mResultProtector; + basicMutex m_mNIFMUTEX; + vectorCSTR m_vNIFIPS; + bool m_bProbeIsActive; + bool m_bWSAOK; + uint8_t m_bCurrentNIF; + + //PROBE_CTX * init_PROBE_CTX( CSTR ADR, int ID ); + //bool loadAssignedSources(void); + //bool startProbe( CSTR IP, int ID ); + //static void * probeThreadProc(void *); + OBSERVER_RESULT * parseXML( CSTR data ); + protected: + virtual void m_fThreadProc( void ); + + public: + explicit argusModuleOnvifObserver( uint32_t moduleID ); + ~argusModuleOnvifObserver(); + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); +}; + +#endif diff --git a/lib/App/mojo/rgooseModuleSSDP.cpp b/lib/App/mojo/rgooseModuleSSDP.cpp new file mode 100644 index 00000000..3d114984 --- /dev/null +++ b/lib/App/mojo/rgooseModuleSSDP.cpp @@ -0,0 +1,46 @@ +#include "rgooseModuleSSDP.h" + +#define LOG( X ) m_pLog->Log( "MOD_SSDP", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "MOD_SSDP", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "MOD_SSDP", this, _LOG_ERROR, X ); +#endif + + +argusModuleSSDPAnnouncer::argusModuleSSDPAnnouncer( uint32_t ModuleID ) : argusKernelModule( ModuleID, ARGUS_MODULE_SSDP_ANONCE ){ + m_pEventHeap = basicEventHeap::getInstance(); +}; + +argusModuleSSDPAnnouncer::~argusModuleSSDPAnnouncer(){ +}; + +void argusModuleSSDPAnnouncer::dispatchEvent( EVENT_CONTAINER *Evt ){ + +}; + +void argusModuleSSDPAnnouncer::m_fThreadProc( void ){ + +}; + +bool argusModuleSSDPAnnouncer::reloadSettings(){ + return false; +}; +bool argusModuleSSDPAnnouncer::startService(){ + return false; +}; +bool argusModuleSSDPAnnouncer::stopService( bool force ){ + return true; +}; +bool argusModuleSSDPAnnouncer::validate(){ + return true; +}; + + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/mojo/rgooseModuleSSDP.h b/lib/App/mojo/rgooseModuleSSDP.h new file mode 100644 index 00000000..ef1aaadf --- /dev/null +++ b/lib/App/mojo/rgooseModuleSSDP.h @@ -0,0 +1,23 @@ +#ifndef __ARGUS_MODULE_SSDP_ANNOUNCER_HEADER__ +#define __ARGUS_MODULE_SSDP_ANNOUNCER_HEADER__ +#include "rgooseModule.h" +#include "../components/base/basicThread.h" +#include "../components/base/basicEventHeap.h" + + + +class argusModuleSSDPAnnouncer: public argusKernelModule, public basicThread { + private: + basicEventHeap * m_pEventHeap; + protected: + virtual void m_fThreadProc( void ); + public: + explicit argusModuleSSDPAnnouncer( uint32_t moduleID ); + ~argusModuleSSDPAnnouncer(); + virtual bool reloadSettings(); + virtual bool startService(); + virtual bool stopService( bool force = false ); + virtual void dispatchEvent(EVENT_CONTAINER *Evt); + virtual bool validate(); +}; +#endif diff --git a/lib/App/mojo/rgooseModuleUSBRelay.cpp b/lib/App/mojo/rgooseModuleUSBRelay.cpp new file mode 100644 index 00000000..12881f7b --- /dev/null +++ b/lib/App/mojo/rgooseModuleUSBRelay.cpp @@ -0,0 +1,317 @@ +#include +#include +#include +#include +#include +#include +#include +#include "rgooseModuleUSBRelay.h" + +#define LOG( X ) m_pLog->Log( "MOD_USBDC", this, X ) + +#ifdef DEBUG + #define LOG_ERROR( X ) {\ + char _tBfrErrMSG2w34[256];\ + sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ + m_pLog->Log( "MOD_USBDC", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ + } +#else + #define LOG_ERROR( X ) m_pLog->Log( "MOD_USBDC", this, _LOG_ERROR, X ); +#endif + + +//Global variables +unsigned short vendor_id = 0x16c0; +unsigned short product_id = 0x05df; +relay_board *relay_boards = 0; +int relay_board_count = 0; +int i, k; + +//Private function prototypes +static int get_board_features(relay_board *board, hid_device *handle); + +/** + * Enumerate all possible relay devices in the system + */ +int enumerate_relay_boards(const char *product, int verbose, int debug){ + char *vendor; + int result = 0; + struct hid_device_info *devs, *cur_dev; + + //If we were given a product code, use it + if (product != NULL) + { + vendor = strsep((char **)&product, ":"); + if (vendor && *vendor) + { + vendor_id = strtol(vendor, NULL, 16); + } + if (product && *product) + { + product_id = strtol(product, NULL, 16); + } + } + + //Enumerate USB devices with the given IDs + devs = hid_enumerate(vendor_id, product_id); + + //Count the number of returned devices + cur_dev = devs; + + for (relay_board_count = 0; cur_dev != NULL; relay_board_count++) + { + cur_dev = cur_dev->next; + } + + //Allocate a buffer for the relays + if (relay_board_count > 0) + { + relay_boards = (relay_board *) malloc((relay_board_count) * sizeof(relay_board)); + + //Fill the relay structs + cur_dev = devs; + for (i = 0; i < relay_board_count; i++) + { + //Save the path to this device + relay_boards[i].path = (char *) malloc(strlen(cur_dev->path)+1); + memcpy(relay_boards[i].path, cur_dev->path, strlen(cur_dev->path) + 1); + + // The product string is USBRelayx where x is number of relays read to the \0 in case there are more than 9 + relay_boards[i].relay_count = atoi((const char *)&cur_dev->product_string[8]); + + //Open it to get more details + hid_device *handle; + handle = hid_open_path(cur_dev->path); + if (handle) + { + result = get_board_features(&relay_boards[i], handle); + hid_close(handle); + } + else + { + perror("unable to open device\n"); + result = -1; + } + + //Output the device enumeration details if verbose is on + if (verbose) + { + fprintf(stderr, "Device Found\n type: %04hx %04hx\n path: %s\n serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number); + fprintf(stderr, "\n"); + fprintf(stderr, " Manufacturer: %ls\n", cur_dev->manufacturer_string); + fprintf(stderr, " Product: %ls\n", cur_dev->product_string); + fprintf(stderr, " Release: %hx\n", cur_dev->release_number); + fprintf(stderr, " Interface: %d\n", cur_dev->interface_number); + + fprintf(stderr, " Number of Relays = %d\n", relay_boards[i].relay_count); + + //If verbose and debug are on, output individual relay details + if (debug) + { + for (k = 0; k < relay_boards[i].relay_count; k++) + { + if (relay_boards[i].state & 1 << k) + { + printf("%s_%d=1\n", relay_boards[i].serial, k + 1); + } + else + { + printf("%s_%d=0\n", relay_boards[i].serial, k + 1); + } + } + } + } + cur_dev = cur_dev->next; + } + } + hid_free_enumeration(devs); + return result; +} + +/** + * Command a relay at a particular /dev path to switch to a given state + */ +int operate_relay(const char *serial, unsigned char relay, unsigned char target_state) +{ + unsigned char buf[9]; // 1 extra byte for the report ID + int res = -1; + hid_device *handle; + + relay_board *board = find_board(serial); + if (board != NULL && relay >0 && relay <= board->relay_count) + { + handle = hid_open_path(board->path); + + if (handle) + { + buf[0] = 0x0; //report number + buf[1] = target_state; + buf[2] = relay; + buf[3] = 0x00; + buf[4] = 0x00; + buf[5] = 0x00; + buf[6] = 0x00; + buf[7] = 0x00; + buf[8] = 0x00; + res = hid_write(handle, buf, sizeof(buf)); + } + else + { + res = -1; + } + + if (res > 0) + { + //Update our relay status + res = get_board_features(board, handle); + } + else + { + fprintf(stderr, "Unable to write()\n"); + fprintf(stderr, "Error: %ls\n", hid_error(handle)); + } + + hid_close(handle); + } + + return (res); +} + +int set_serial(const char *serial, char *newserial) +{ + unsigned char buf[9]; // 1 extra byte for the report ID + int res = -1; + hid_device *handle; + + relay_board *board = find_board(serial); + if (board != NULL) + { + handle = hid_open_path(board->path); + + if (handle) + { + buf[0] = 0x0; //report number + buf[1] = CMD_SET_SERIAL; + buf[2] = newserial[0]; + buf[3] = newserial[1]; + buf[4] = newserial[2]; + buf[5] = newserial[3]; + buf[6] = newserial[4]; + buf[7] = 0x00; + buf[8] = 0x00; + res = hid_write(handle, buf, sizeof(buf)); + } + else + { + res = -1; + } + + if (res > 0) + { + //Update our copy of the serial number + res = get_board_features(board, handle); + } + else + { + fprintf(stderr, "Unable to write()\n"); + fprintf(stderr, "Error: %ls\n", hid_error(handle)); + } + hid_close(handle); + } + + return (res); +} + +/** + * Find a board path given a relay board serial + */ +relay_board *find_board(const char *serial) +{ + for (i = 0; i < relay_board_count; i++) + { + if (strcmp(relay_boards[i].serial, serial) == 0) + { + return &relay_boards[i]; + } + } + return NULL; +} + +/** + * Return the count of relay boards + */ +int get_relay_board_count() +{ + return relay_board_count; +} + +/** + * Return the actual relay_board structs + */ +relay_board *get_relay_boards() +{ + return relay_boards; +} + +/** + * Return all allocated resources and perform any other cleanup + */ +void shutdown() +{ + + /* Free static HIDAPI objects. */ + hid_exit(); + + for (i = 0; i < relay_board_count; i++) + { + free(relay_boards[i].path); + } + if (relay_board_count > 0) + { + free(relay_boards); + } +} + +//Private functions + +/** + * Load the board serial and relay status + * This intentionally reuses a handle as it's meant to be called by the + * other functions while they have one already open + */ +static int get_board_features(relay_board *board, hid_device *handle) +{ + unsigned char buf[9]; + //Get the features of the device + buf[0] = 0x01; + int ret = hid_get_feature_report(handle, buf, sizeof(buf)); + if (ret == -1) + { + perror("hid_get_feature_report\n"); + } + + //Set the serial number (0x0 for termination) + memset(board->serial, 0x0, sizeof(board->serial)); + memcpy(board->serial, buf, Serial_Length); + + //Byte 7 in the response contains the target_state of the relays + board->state = buf[7]; + + return ret; +} + + +argusModuleUSBRelay::argusModuleUSBRelay( uint32_t ModuleID ) : argusKernelModule( ModuleID, ARGUS_MODULE_DCBUSB ){ + +}; + +argusModuleUSBRelay::~argusModuleUSBRelay(){ +}; + +void argusModuleUSBRelay::dispatchEvent( EVENT_CONTAINER *Evt ){ + +}; + + +#undef LOG +#undef LOG_ERROR diff --git a/lib/App/mojo/rgooseModuleUSBRelay.h b/lib/App/mojo/rgooseModuleUSBRelay.h new file mode 100644 index 00000000..cd0c3179 --- /dev/null +++ b/lib/App/mojo/rgooseModuleUSBRelay.h @@ -0,0 +1,40 @@ +#ifndef __ARGUS_USB_RELAY_MODULE_HEADER__ +#define __ARGUS_USB_RELAY_MODULE_HEADER__ + +#include "rgooseModule.h" + +//Configuration +#define CMD_ON 0xff +#define CMD_OFF 0xfd +#define CMD_SET_SERIAL 0xfa + +#define Serial_Length 6 // 5+1 for the \0 string terminator + +//Struct for relay boards +typedef struct S_relay_board { + char serial[Serial_Length]; + unsigned char relay_count; + unsigned char state; + char *path; +} relay_board; + +int enumerate_relay_boards( const char *product, int verbose, int debug); +int operate_relay( const char *path,unsigned char relay, unsigned char state); +int set_serial( const char *path,char *newserial); +relay_board *find_board( const char *serial); +int get_relay_board_count( void); +relay_board* get_relay_boards(void); +void shutdown(void); + +class argusModuleUSBRelay: public argusKernelModule { + private: + relay_board m_sBoardDef; + uint32_t m_nNO_CONFIG; + uint32_t m_nCURRENT_STATE; + uint32_t m_aCHANNEL_CONFIGS[32]; + public: + explicit argusModuleUSBRelay( uint32_t ModuleID ); + virtual ~argusModuleUSBRelay(); + virtual void dispatchEvent( EVENT_CONTAINER *Evt ); +}; +#endif \ No newline at end of file diff --git a/lib/alg/generic/heapDebug.cpp b/lib/alg/generic/heapDebug.cpp index 85199bb6..79641ca4 100644 --- a/lib/alg/generic/heapDebug.cpp +++ b/lib/alg/generic/heapDebug.cpp @@ -1,95 +1,95 @@ -#include "heapDebug.h" - -#if !defined( DEBUG ) && !defined( MEM_DEBUG_LOG ) - size_t getPeakRSS( ){ return 0; }; - size_t getCurrentRSS( ){ return 0; }; -#else - /** - * Returns the peak (maximum so far) resident set size (physical - * memory use) measured in bytes, or zero if the value cannot be - * determined on this OS. - */ - size_t getPeakRSS( ) - { - #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.PeakWorkingSetSize; - - #elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) - /* AIX and Solaris ------------------------------------------ */ - struct psinfo psinfo; - int fd = -1; - if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 ) - return (size_t)0L; /* Can't open? */ - if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) ) - { - close( fd ); - return (size_t)0L; /* Can't read? */ - } - close( fd ); - return (size_t)(psinfo.pr_rssize * 1024L); - - #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) - /* BSD, Linux, and OSX -------------------------------------- */ - struct rusage rusage; - getrusage( RUSAGE_SELF, &rusage ); - #if defined(__APPLE__) && defined(__MACH__) - return (size_t)rusage.ru_maxrss; - #else - return (size_t)(rusage.ru_maxrss * 1024L); - #endif - - #else - /* Unknown OS ----------------------------------------------- */ - return (size_t)0L; /* Unsupported. */ - #endif - } - - - - - - /** - * Returns the current resident set size (physical memory use) measured - * in bytes, or zero if the value cannot be determined on this OS. - */ - size_t getCurrentRSS( ) - { - #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.WorkingSetSize; - - #elif defined(__APPLE__) && defined(__MACH__) - /* OSX ------------------------------------------------------ */ - struct mach_task_basic_info info; - mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; - if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, - (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) - return (size_t)0L; /* Can't access? */ - return (size_t)info.resident_size; - - #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) - /* Linux ---------------------------------------------------- */ - long rss = 0L; - FILE* fp = NULL; - if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL ) - return (size_t)0L; /* Can't open? */ - if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) - { - fclose( fp ); - return (size_t)0L; /* Can't read? */ - } - fclose( fp ); - return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE); - - #else - /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ - return (size_t)0L; /* Unsupported. */ - #endif - } - +#include "heapDebug.h" + +#if !defined( DEBUG ) && defined( SKIP_MEM_CHECK ) + size_t getPeakRSS( ){ return 0; }; + size_t getCurrentRSS( ){ return 0; }; +#else + /** + * Returns the peak (maximum so far) resident set size (physical + * memory use) measured in bytes, or zero if the value cannot be + * determined on this OS. + */ + size_t getPeakRSS( ) + { + #if defined(_WIN32) + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); + return (size_t)info.PeakWorkingSetSize; + + #elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) + /* AIX and Solaris ------------------------------------------ */ + struct psinfo psinfo; + int fd = -1; + if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 ) + return (size_t)0L; /* Can't open? */ + if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) ) + { + close( fd ); + return (size_t)0L; /* Can't read? */ + } + close( fd ); + return (size_t)(psinfo.pr_rssize * 1024L); + + #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) + /* BSD, Linux, and OSX -------------------------------------- */ + struct rusage rusage; + getrusage( RUSAGE_SELF, &rusage ); + #if defined(__APPLE__) && defined(__MACH__) + return (size_t)rusage.ru_maxrss; + #else + return (size_t)(rusage.ru_maxrss * 1024L); + #endif + + #else + /* Unknown OS ----------------------------------------------- */ + return (size_t)0L; /* Unsupported. */ + #endif + } + + + + + + /** + * Returns the current resident set size (physical memory use) measured + * in bytes, or zero if the value cannot be determined on this OS. + */ + size_t getCurrentRSS( ) + { + #if defined(_WIN32) + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); + return (size_t)info.WorkingSetSize; + + #elif defined(__APPLE__) && defined(__MACH__) + /* OSX ------------------------------------------------------ */ + struct mach_task_basic_info info; + mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; + if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, + (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) + return (size_t)0L; /* Can't access? */ + return (size_t)info.resident_size; + + #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) + /* Linux ---------------------------------------------------- */ + long rss = 0L; + FILE* fp = NULL; + if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL ) + return (size_t)0L; /* Can't open? */ + if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) + { + fclose( fp ); + return (size_t)0L; /* Can't read? */ + } + fclose( fp ); + return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE); + + #else + /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ + return (size_t)0L; /* Unsupported. */ + #endif + } + #endif // DEBUG \ No newline at end of file diff --git a/lib/alg/generic/heapDebug.h b/lib/alg/generic/heapDebug.h index 74f88ead..cd5f3dc6 100644 --- a/lib/alg/generic/heapDebug.h +++ b/lib/alg/generic/heapDebug.h @@ -4,7 +4,7 @@ * License: Creative Commons Attribution 3.0 Unported License * http://creativecommons.org/licenses/by/3.0/deed.en_US */ -#if !defined( DEBUG ) && !defined( MEM_DEBUG_LOG ) +#if !defined( DEBUG ) && defined( SKIP_MEM_CHECK ) #include size_t getPeakRSS( ); size_t getCurrentRSS( ); diff --git a/lib/components/base/basicDataProvider.h b/lib/components/base/basicDataProvider.h new file mode 100644 index 00000000..e2f3665e --- /dev/null +++ b/lib/components/base/basicDataProvider.h @@ -0,0 +1,17 @@ +#ifndef __BASIC_DATA_PROVIDER__ +#define __BASIC_DATA_PROVIDER__ + + + + + + +class basicDataProvider{ + public: + basicDataProvider(); + virtual ~basicDataProvider(); +}; + + + +#endif \ No newline at end of file diff --git a/lib/components/base/basicEngine.cpp b/lib/components/base/basicEngine.cpp index c1b5f531..39aa413d 100644 --- a/lib/components/base/basicEngine.cpp +++ b/lib/components/base/basicEngine.cpp @@ -1,4 +1,49 @@ #include "basicEngine.h" -// TODO: your implementation here +// Constructor implementation +basicEngine::basicEngine():basicObject(){ + m_bOWM = 0; + m_bWM = 0; +}; +// Destructor implementation +basicEngine::~basicEngine(){ + m_mWMProtector.lock(); + m_mWMProtector.unlock(); +}; + +bool basicEngine::setWM( uint8_t s, bool hard ){ + if( hard ){ + m_mWMProtector.lock(); + m_bOWM = m_bWM; + m_bWM = s; + m_mWMProtector.unlock(); + } else { + if( m_mWMProtector.try_lock() ){ + m_bOWM = m_bWM; + m_bWM = s; + m_mWMProtector.unlock(); + } else return false; + }; + return true; +}; + +uint8_t basicEngine::getWM( void ){ + uint8_t s; + m_mWMProtector.lock(); + s = m_bWM; + m_mWMProtector.unlock(); + return s; +}; +uint8_t basicEngine::getOWM( void ){ + uint8_t s; + m_mWMProtector.lock(); + s = m_bOWM; + m_mWMProtector.unlock(); + return s; +}; +void basicEngine::setBackOWM( void ){ + m_mWMProtector.lock(); + m_bWM = m_bOWM; + m_mWMProtector.unlock(); +}; \ No newline at end of file diff --git a/lib/components/base/basicEngine.h b/lib/components/base/basicEngine.h index 8959350c..a9d0222c 100644 --- a/lib/components/base/basicEngine.h +++ b/lib/components/base/basicEngine.h @@ -13,6 +13,7 @@ class basicEngine: public basicObject { private: basicMutex m_mWMProtector; uint8_t m_bWM; + uint8_t m_bOWM; public: // Constructor basicEngine(); @@ -21,25 +22,12 @@ class basicEngine: public basicObject { virtual ~basicEngine(); virtual bool startService(){ return false; }; virtual bool stopService(){ return true; }; - void setWM( uint8_t s ){ - m_mWMProtector.lock(); - m_bWM = s; - m_mWMProtector.unlock(); - }; - uint8_t getWM( void ){ - uint8_t s; - m_mWMProtector.lock(); - s = m_bWM; - m_mWMProtector.unlock(); - return s; - }; + bool setWM( uint8_t s, bool hard = true ); + uint8_t getWM( void ); + uint8_t getOWM( void ); + void setBackOWM( void ); }; -// Constructor implementation -inline basicEngine::basicEngine():basicObject(){}; - -// Destructor implementation -inline basicEngine::~basicEngine(){}; // TODO: Uncomment the copy constructor when you need it. //inline basicEngine::basicEngine(const basicEngine& src) diff --git a/lib/components/object/objectSystemAnchor.cpp b/lib/components/object/objectSystemAnchor.cpp index b1f17337..7c2a630d 100644 --- a/lib/components/object/objectSystemAnchor.cpp +++ b/lib/components/object/objectSystemAnchor.cpp @@ -232,7 +232,7 @@ bool systemAnchor::convertToLocal( basicPosition *SP, C3D_DECART POS, C3D_SPH_DE transform_3* pTF = SP->getTransform(); C3D_DECART tDec; vector_3 A, B; -#ifdef DEBUG_EXTRA +#ifdef DEBUG char tB[256]; LOG("C2L Dec. -> Sph.(deg)"); sprintf(tB, "System Decart: %.3f %.3f %.3f", POS.x, POS.y, POS.z ); @@ -240,15 +240,17 @@ bool systemAnchor::convertToLocal( basicPosition *SP, C3D_DECART POS, C3D_SPH_DE #endif // POS - is Relative to System Anchore!! if( m_bUseJustLocalDiffCoords ) { + LOG("JLO"); A[0] = POS.x + getX();// - getX(); // in general getX() = 0 as other coords of anchore A[1] = POS.y + getY();// - getY(); A[2] = POS.z + getZ();// - getZ(); } else { - A[0] = POS.x; - A[1] = POS.y; - A[2] = POS.z; + LOG("NLO"); + A[0] = POS.x + getX(); + A[1] = POS.y + getY(); + A[2] = POS.z + getZ(); }; -#ifdef DEBUG_EXTRA +#ifdef DEBUG sprintf(tB, "Prepared Global Decart: %.3f %.3f %.3f", A[0], A[1], A[2] ); LOG( tB ); #endif @@ -262,7 +264,7 @@ bool systemAnchor::convertToLocal( basicPosition *SP, C3D_DECART POS, C3D_SPH_DE tDec.x = B[0];// + getX() - SP->getX(); tDec.y = B[1]; //+ getY() - SP->getY(); tDec.z = B[2]; //+ getZ() - SP->getZ(); -#ifdef DEBUG_EXTRA +#ifdef DEBUG sprintf(tB, "Local Decart: %.3f %.3f %.3f", B[0], B[1], B[2] ); LOG( tB ); //sprintf(tB, "Local Decart: %.3f %.3f %.3f", tDec.x, tDec.y, tDec.z ); diff --git a/lib/data/blog/binaryLogging.cpp b/lib/data/blog/binaryLogging.cpp new file mode 100644 index 00000000..eb25d221 --- /dev/null +++ b/lib/data/blog/binaryLogging.cpp @@ -0,0 +1,8 @@ +#include "binaryLogging.h" + +binaryStorage::binaryStorage( CSTR StorageName, uint32_t partitionSize ): m_nPartSize( partitionSize ) { + +}; + +binaryStorage::~binaryStorage(){ +}; \ No newline at end of file diff --git a/lib/data/blog/binaryLogging.h b/lib/data/blog/binaryLogging.h new file mode 100644 index 00000000..2694a1c9 --- /dev/null +++ b/lib/data/blog/binaryLogging.h @@ -0,0 +1,41 @@ +#ifndef __DATA_BINARY_LOGGING_HEADERS__ +#define __DATA_BINARY_LOGGING_HEADERS__ + +typedef enum E_BLOG_STATUS{ + BLOG_RECORD_EMPTY = 0, + BLOG_RECORD_OK = 1, + BLOG_RECORD_BUSY = 2, + BLOG_RECORD_DELETED = 255 +}BLOG_STATUS; + +typedef struct S_BLOG_RECORD{ + uint8_t crc; + uint8_t * data; + uint32_t size; + uint32_t uts; + uint8_t status; +}BLOG_RECORD; + + +typedef enum E_BLOG_STATUS{ +}BLOG_STATUS; + +class binaryStorage{ + private: + uint64_t m_nCurrentSize; + uint32_t m_nPartSize; + uint32_t m_nRecordsCount; + basicMutex m_mOpProtector; + char m_cFileName[MAX_PATH]; + public: + explicit binaryStorage( CSTR StorageName, uint32_t partitionSize = 0 ); + virtual ~binaryStorage(); + getCounts(); + uint32_t fetch_first( uint32_t ts ); + uint32_t fetch_last( uint32_t ts ); + BLOG_RECORD * getRecord( uint32_t id ); + bool validate(); + bool updateRecord( uint32_t id, uint8_t *data, uint32_t size ); +}; + +#endif \ No newline at end of file diff --git a/lib/data/mysql/database_class.cpp b/lib/data/mysql/mysql_class.cpp similarity index 98% rename from lib/data/mysql/database_class.cpp rename to lib/data/mysql/mysql_class.cpp index c1f7da91..50cc7d83 100644 --- a/lib/data/mysql/database_class.cpp +++ b/lib/data/mysql/mysql_class.cpp @@ -1,4 +1,4 @@ -#include "database_class.h" +#include "mysql_class.h" #define LOG( X ) m_pLog->Log( "MYDB", this, X ) #define LOG_ERROR( X ) m_pLog->Log( "MYDB", this, _LOG_ERROR, X ) @@ -167,11 +167,11 @@ AAssoc *MySQL_Connector::Query( CSTR QS, bool useCache ){ unsigned int num_Fields; MYSQL_RES * Result = NULL; char temp[256]; - - m_mAccessMutex.lock(); + #ifdef DEBUG_MYSQL_QUERIES LOG( QS ); #endif + m_mAccessMutex.lock(); /* if( mysql_query( m_pDBLink, QS ) ){ LOG_ERROR( mysql_error( m_pDBLink )); @@ -271,10 +271,11 @@ AAssoc *MySQL_Connector::Query( CSTR QS, bool useCache ){ }; CSTR MySQL_Connector::escapeString( CSTR str ){ - CSTR temp = ( CSTR ) malloc( strlen( str ) * 2 + 1 ); + int len = strlen( str ); + CSTR temp = ( CSTR ) malloc( len * 2 + 1 ); if ( temp ) { m_mAccessMutex.lock(); - mysql_real_escape_string( m_pDBLink, temp, str, strlen(str) ); + mysql_real_escape_string( m_pDBLink, temp, str, len ); m_mAccessMutex.unlock(); }; return temp; diff --git a/lib/data/mysql/database_class.h b/lib/data/mysql/mysql_class.h similarity index 100% rename from lib/data/mysql/database_class.h rename to lib/data/mysql/mysql_class.h diff --git a/lib/data/protocol/protocolLGS2D.h b/lib/data/protocol/protocolLGS2D.h index cf322502..926ce460 100644 --- a/lib/data/protocol/protocolLGS2D.h +++ b/lib/data/protocol/protocolLGS2D.h @@ -5,10 +5,14 @@ #include "protocolLGS_data.h" #include "../../alg/lgs/detectorStructures.h" #include "../../alg/lgs/mask.h" -#include "../../rgoose/rgooseTypes.h" +//#include "../../rgoose/rgooseTypes.h" #define LEGACY_2ZEROS_BEFORE_PACKAGE +//#include "../../App/common/dataBinder_structures.h" + + + class protocolLGS_2D: public protocolParser{ private: basicLogCollection * m_pLog; diff --git a/lib/data/protocol/protocolLGS_data.h b/lib/data/protocol/protocolLGS_data.h index ed2d832a..7117d0fa 100644 --- a/lib/data/protocol/protocolLGS_data.h +++ b/lib/data/protocol/protocolLGS_data.h @@ -1054,4 +1054,29 @@ typedef struct S_DEVICE_STATUS{ bool ProgressIsActive; } DEVICE_STATUS, *PDEVICE_STATUS; +typedef struct S_SHADOW_RAY{ + uint8_t bType; + uint16_t nMin; + uint16_t nMax; +} SHADOW_RAY; + +typedef struct S_SHADOW_RAY_LINE{ + uint16_t nCount; + SHADOW_RAY * rays; +}SHADOW_RAY_LINE; + +typedef struct S_SHADOW_POLY{ + uint8_t bType; + uint16_t wCount; + HZ_POINT * pPoint; + uint32_t m_nDBID; +}SHADOW_POLY; + +typedef struct S_SHADOW{ + uint16_t m_nPolygonCount; + SHADOW_POLY * pPolygones; + SHADOW_RAY_LINE ray_lines[MAX_2D_SHADOW_RAY_LINES]; + uint32_t m_nEnabled; +}SHADOW; + #endif diff --git a/lib/data/sqlite/sqlite_class.cpp b/lib/data/sqlite/sqlite_class.cpp new file mode 100644 index 00000000..ee702715 --- /dev/null +++ b/lib/data/sqlite/sqlite_class.cpp @@ -0,0 +1,310 @@ +#include "sqlite_class.h" + +#define LOG( X ) m_pLog->Log( "SQDB", this, X ) +#define LOG_ERROR( X ) m_pLog->Log( "SQDB", this, _LOG_ERROR, X ) + +static bool sqlite_global_config_is_set = false; +static uint8_t sqlite_global_inctances_count = 0; + + +static void errorLogCallback( void *pArg, int iErrCode, const char *zMsg ){ + char tB[1024]; + sprintf( tB, "(%d) %s", iErrCode, zMsg ); + basicLogCollection::getInstance()->Log( "SQDB_G", pArg, tB ); +}; + +SQLite_Connector::SQLite_Connector(){ + m_pLog = basicLogCollection::getInstance(); + m_bIsConnected = false; + m_bPersistentConnection = false; + m_pDBLink = NULL; + if( !sqlite_global_config_is_set ){ + //if( SQLITE_OK != sqlite3_config(int, ...) ){ SQLITE_MISUSE + sqlite3_config( SQLITE_CONFIG_LOG, errorLogCallback, this ); + + sqlite3_initialize(); + sqlite_global_config_is_set = true; + }; + sqlite_global_inctances_count++; +}; + +SQLite_Connector::~SQLite_Connector(){ + m_bIsConnected = !Disconnect(); + if( sqlite_global_inctances_count == 1 ){ + sqlite3_shutdown(); + }; + sqlite_global_inctances_count--; +}; + +bool SQLite_Connector::Connect( CSTR FileName, int AUX_FLAGS, bool Persistent ){ + m_mAccessMutex.lock(); + m_bPersistentConnection = Persistent; + if( m_bIsConnected ){ + LOG("Connected -> Disconnect!"); + m_bIsConnected = false; + if( m_pDBLink != NULL ){ + if( SQLITE_OK != sqlite3_close( m_pDBLink ) ) { + m_mAccessMutex.unlock(); + return false; + }; + }; + }; + sprintf( m_pDBName, "%s", FileName ); + m_nFLAGS = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | AUX_FLAGS; + if( m_bPersistentConnection ){ + LOG("Making Connection...."); + if( SQLITE_OK == sqlite3_open_v2( m_pDBName, &m_pDBLink, m_nFLAGS, NULL ) ) m_bIsConnected = true; + LOG("Done!"); + } else { + m_bIsConnected = true; + }; + m_mAccessMutex.unlock(); + return m_bIsConnected; +}; + +bool SQLite_Connector::ReConnect( void ){ + if( m_pDBLink != NULL ) if( SQLITE_OK != sqlite3_close( m_pDBLink ) ) return false; + if( SQLITE_OK == sqlite3_open_v2( m_pDBName, &m_pDBLink, m_nFLAGS, NULL ) ) return true; + return false; +}; + +bool SQLite_Connector::Disconnect( void ){ + if( m_pDBLink != NULL ) if( SQLITE_OK != sqlite3_close( m_pDBLink ) ) return false; + m_pDBLink = NULL; + return true; +}; + +bool SQLite_Connector::SilentQuery( CSTR QS ){ + if ( m_bIsConnected ) { + int QSlen = strlen( QS ); + m_mAccessMutex.lock(); + if( !m_bPersistentConnection ){ + if( !ReConnect() ){ + m_mAccessMutex.unlock(); + return false; + }; + }; + sqlite3_stmt * query = NULL; + //if( SQLITE_OK != sqlite3_prepare_v2( m_pDBLink, QS, QSlen, NULL, NULL ) ){ + if( SQLITE_OK != sqlite3_prepare_v2( m_pDBLink, QS, QSlen, &query, NULL ) ){ + m_mAccessMutex.unlock(); + return false; + }; + +#ifdef DEBUG_EXTRA + LOG( sqlite3_expanded_sql( query ) ); +#endif + + if( SQLITE_DONE != sqlite3_step( query )){ + sqlite3_finalize( query ); + m_mAccessMutex.unlock(); + return false; + }; + + sqlite3_finalize( query ); + + if( !m_bPersistentConnection ){ + if( !Disconnect() ){ + m_mAccessMutex.unlock(); + return false; + }; + }; + m_mAccessMutex.unlock(); + return true; + }; + return false; +}; + +AAssoc *SQLite_Connector::Query( CSTR QS, bool useCache ){ + AAssoc * RetVal = NULL; + Assoc * tElement; + unsigned int num_Fields; + sqlite3_stmt * query = NULL; + char temp[256]; + + int QSlen = strlen( QS ); + m_mAccessMutex.lock(); + if( !m_bPersistentConnection ){ + if( !ReConnect() ){ + m_mAccessMutex.unlock(); + return RetVal; + }; + }; + if( SQLITE_OK != sqlite3_prepare_v2( m_pDBLink, QS, QSlen, &query, NULL ) ){ + m_mAccessMutex.unlock(); + return RetVal; + }; +#ifdef DEBUG_EXTRA + LOG( sqlite3_expanded_sql( query ) ); +#endif + RetVal = new AAssoc(); + while( sqlite3_step( query ) != SQLITE_DONE ){ + string *Key; + string *Val; + uint32_t num_cols = sqlite3_column_count( query ); + if( num_cols ){ + tElement = new Assoc(); + if( tElement ){ + for( uint32_t i = 0; i < num_cols; i++ ){ + Key = NULL; + Val = NULL; + Key = new string( sqlite3_column_name( query, i ) ); + if( Key!= NULL ) { + switch( sqlite3_column_type( query, i ) ){ + case SQLITE_INTEGER: + Val = new std::string( (char*) sqlite3_column_text( query, i ) ); + break; + case SQLITE_FLOAT: + Val = new std::string( (char*) sqlite3_column_text( query, i ) ); + break; + case SQLITE3_TEXT: + Val = new std::string( (char*) sqlite3_column_text( query, i ) ); + break; + case SQLITE_BLOB: + case SQLITE_NULL: + Val = new std::string( "" ); + break; + default: + Val = new std::string( "" ); + break; + }; + if( Val != NULL ){ + //(*tElement).insert( pair< string, string > ( *Key, *Val ) ); + (*tElement)[*Key]=*Val; + } else { + LOG_ERROR( "Val Alloc Error" ); + }; + } else { + LOG_ERROR( "Key Alloc Error" ); + }; + }; + RetVal->push_back( tElement ); + }; + }; + }; + + sqlite3_finalize( query ); + + if( !m_bPersistentConnection ){ + if( !Disconnect() ){ + m_mAccessMutex.unlock(); + return RetVal; + }; + }; + m_mAccessMutex.unlock(); + return RetVal; +}; + +CSTR SQLite_Connector::escapeString( CSTR value ){ + CSTR buffer = NULL; + int v_len = strlen(value); + CSTR result = (CSTR) malloc( 3 * v_len ); + if( result ){ + int idx = 0; + for( int i = 0; i < v_len; i++ ){ + //If character is printable + if(isprint( value[i] ) != 0){ + strncat( result+idx, value+i, 1 ); + idx++; + }else{ + char tB[4]; + snprintf( tB, 4, "#%02X", value[i]); + strncat( result+idx, tB, 3 ); + idx+=3; + }; + }; + buffer = ( CSTR ) malloc( idx+1 ); + if( buffer ) { + strncat( buffer, result, idx ); + buffer[idx] = (char)0; + }; + free(result); + }; + return buffer; +}; + +CSTR SQLite_Connector::escapeBinary( uint8_t *value, uint32_t Size ){ + CSTR buffer = NULL; + if ( m_bIsConnected ){ + int v_len = Size; + CSTR result = ( CSTR ) malloc( 3 * v_len ); + if( result ){ + int idx = 0; + for( int i = 0; i < v_len; i++ ){ + //If character is printable + if(isprint( value[i] ) != 0){ + memcpy( result+idx, value+i, 1 ); + idx++; + }else{ + char tB[4]; + snprintf( tB, 4, "#%02X", value[i]); + strncat( result+idx, tB, 3 ); + idx+=3; + }; + }; + buffer = ( CSTR ) malloc( idx+1 ); + if( buffer ) { + strncat( buffer, result, idx ); + buffer[idx] = (char)0; + }; + free(result); + }; + }; + return buffer; +}; + +uint64_t SQLite_Connector::QueryID( CSTR QS ){ + uint64_t RetVal = 0; + uint64_t tVal = 0; + if ( m_bIsConnected ) { + Assoc * tElement; + unsigned int num_Fields; + sqlite3_stmt * query = NULL; + char temp[256]; + int QSlen = strlen( QS ); + m_mAccessMutex.lock(); + if( !m_bPersistentConnection ){ + if( !ReConnect() ){ + m_mAccessMutex.unlock(); + return RetVal; + }; + }; + if( SQLITE_OK != sqlite3_prepare_v2( m_pDBLink, QS, QSlen, &query, NULL ) ){ + m_mAccessMutex.unlock(); + return RetVal; + }; +#ifdef DEBUG_EXTRA + LOG( sqlite3_expanded_sql( query ) ); +#endif + tVal = sqlite3_last_insert_rowid( m_pDBLink ); + if( SQLITE_DONE != sqlite3_step( query )){ + sqlite3_finalize( query ); + m_mAccessMutex.unlock(); + return false; + }; + RetVal = sqlite3_last_insert_rowid( m_pDBLink ); + sqlite3_finalize( query ); + if( !m_bPersistentConnection ){ + if( !Disconnect() ){ + m_mAccessMutex.unlock(); + return RetVal; + }; + }; + m_mAccessMutex.unlock(); + if( RetVal == tVal ) RetVal = 0; + }; + return RetVal; +}; + +void SQLite_Connector::deleteResult( AAssoc *&R ){ + if( R ){ + while( R->size() ){ + delete( (Assoc *) R->at(0) ); + R->erase( R->begin()); + }; + R->clear(); + delete( R ); + R = NULL; + }; +}; + diff --git a/lib/data/sqlite/sqlite_class.h b/lib/data/sqlite/sqlite_class.h new file mode 100644 index 00000000..6f96eb0c --- /dev/null +++ b/lib/data/sqlite/sqlite_class.h @@ -0,0 +1,47 @@ +#ifndef _SQLITE_base_class_h_ +#define _SQLITE_base_class_h_ + +#include "../../components/base/basicTypes.h" +#include "../../components/base/basicMutex.h" +#include "../../components/base/basicLogCollection.h" +//#include +#include + +#ifdef DEBUG_EXTRA + #define DEBUG_SQLITE_QUERIES +#endif + +class SQLite_Connector{ + private: + basicLogCollection * m_pLog; + bool m_bIsConnected; + basicMutex m_mAccessMutex; + sqlite3 * m_pDBLink; + sqlite3_stmt * m_pResult; + //MYSQL_ROW m_pRow; + char m_pDBName[MAX_PATH]; + int m_nFLAGS; + bool m_bPersistentConnection; + bool ReConnect( void ); + bool Disconnect( void ); + public: + SQLite_Connector(); + SQLite_Connector( CSTR DBHost, CSTR DBUser, CSTR DBPassword, U16 Port = 3306 ); + SQLite_Connector( CSTR DBName, CSTR DBHost, CSTR DBUser, CSTR DBPassword, U16 Port = 3306 ); + //MySQL_Connector( char *LocalUnixSocket, char *DBUser, char* DBPassword ); + virtual ~SQLite_Connector(); + bool Connect( CSTR FileName, int AUX_FLAGS = SQLITE_OPEN_FULLMUTEX, bool Persistent = false ); + + CSTR escapeString( CSTR str ); + CSTR escapeBinary( uint8_t *Data, uint32_t Size ); + bool isConnected( void ){ return m_bIsConnected; }; + uint64_t QueryID( CSTR QS ); + bool SilentQuery( CSTR QS ); + AAssoc * Query( CSTR QS, bool useCache = false ); + void deleteResult( AAssoc *&R ); +}; + +void deleteResult( AAssoc *&ptr ); +//extern MySQL_Connector DBC; + +#endif \ No newline at end of file diff --git a/lib/data/ssdp/ssdpAnnouncer.cpp b/lib/data/ssdp/ssdpAnnouncer.cpp index 153778bc..ebe1a16c 100644 --- a/lib/data/ssdp/ssdpAnnouncer.cpp +++ b/lib/data/ssdp/ssdpAnnouncer.cpp @@ -51,7 +51,7 @@ ssdpAnnouncer::ssdpAnnouncer(config_setting_t *Settings): basicThread(){ supported_types[1] = "upnp:rootdevice"; supported_types[2] = (char *)malloc(64); supported_types[3] = (char *)malloc(64); - supported_types[4] = "urn:schemas-upnp-org:service:Toogler:1"; + supported_types[4] = "urn:schemas-upnp-org:service:DFSL:1"; gethostname(m_sHostName, sizeof(m_sHostName)); m_sIcons.size = 0; diff --git a/lib/include/queue.h b/lib/include/queue.h new file mode 100644 index 00000000..5e81fdd1 --- /dev/null +++ b/lib/include/queue.h @@ -0,0 +1,533 @@ +/* $OpenBSD: queue.h,v 1.43 2015/12/28 19:38:40 millert Exp $ */ +/* $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $ */ + +/* + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)queue.h 8.5 (Berkeley) 8/20/94 + */ + +#ifndef _SYS_QUEUE_H_ +#define _SYS_QUEUE_H_ + +/* + * This file defines five types of data structures: singly-linked lists, + * lists, simple queues, tail queues and XOR simple queues. + * + * + * A singly-linked list is headed by a single forward pointer. The elements + * are singly linked for minimum space and pointer manipulation overhead at + * the expense of O(n) removal for arbitrary elements. New elements can be + * added to the list after an existing element or at the head of the list. + * Elements being removed from the head of the list should use the explicit + * macro for this purpose for optimum efficiency. A singly-linked list may + * only be traversed in the forward direction. Singly-linked lists are ideal + * for applications with large datasets and few or no removals or for + * implementing a LIFO queue. + * + * A list is headed by a single forward pointer (or an array of forward + * pointers for a hash table header). The elements are doubly linked + * so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before + * or after an existing element or at the head of the list. A list + * may only be traversed in the forward direction. + * + * A simple queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. The elements are singly + * linked to save space, so elements can only be removed from the + * head of the list. New elements can be added to the list before or after + * an existing element, at the head of the list, or at the end of the + * list. A simple queue may only be traversed in the forward direction. + * + * A tail queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. The elements are doubly + * linked so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before or + * after an existing element, at the head of the list, or at the end of + * the list. A tail queue may be traversed in either direction. + * + * An XOR simple queue is used in the same way as a regular simple queue. + * The difference is that the head structure also includes a "cookie" that + * is XOR'd with the queue pointer (first, last or next) to generate the + * real pointer value. + * + * For details on the use of these macros, see the queue(3) manual page. + */ + +#if defined(QUEUE_MACRO_DEBUG) || (defined(_KERNEL) && defined(DIAGNOSTIC)) +#define _Q_INVALIDATE(a) (a) = ((void *)-1) +#else +#define _Q_INVALIDATE(a) +#endif + +/* + * Singly-linked List definitions. + */ +#define SLIST_HEAD(name, type) \ +struct name { \ + struct type *slh_first; /* first element */ \ +} + +#define SLIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define SLIST_ENTRY(type) \ +struct { \ + struct type *sle_next; /* next element */ \ +} + +/* + * Singly-linked List access methods. + */ +#define SLIST_FIRST(head) ((head)->slh_first) +#define SLIST_END(head) NULL +#define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head)) +#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) + +#define SLIST_FOREACH(var, head, field) \ + for((var) = SLIST_FIRST(head); \ + (var) != SLIST_END(head); \ + (var) = SLIST_NEXT(var, field)) + +#define SLIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = SLIST_FIRST(head); \ + (var) && ((tvar) = SLIST_NEXT(var, field), 1); \ + (var) = (tvar)) + +/* + * Singly-linked List functions. + */ +#define SLIST_INIT(head) { \ + SLIST_FIRST(head) = SLIST_END(head); \ +} + +#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ + (elm)->field.sle_next = (slistelm)->field.sle_next; \ + (slistelm)->field.sle_next = (elm); \ +} while (0) + +#define SLIST_INSERT_HEAD(head, elm, field) do { \ + (elm)->field.sle_next = (head)->slh_first; \ + (head)->slh_first = (elm); \ +} while (0) + +#define SLIST_REMOVE_AFTER(elm, field) do { \ + (elm)->field.sle_next = (elm)->field.sle_next->field.sle_next; \ +} while (0) + +#define SLIST_REMOVE_HEAD(head, field) do { \ + (head)->slh_first = (head)->slh_first->field.sle_next; \ +} while (0) + +#define SLIST_REMOVE(head, elm, type, field) do { \ + if ((head)->slh_first == (elm)) { \ + SLIST_REMOVE_HEAD((head), field); \ + } else { \ + struct type *curelm = (head)->slh_first; \ + \ + while (curelm->field.sle_next != (elm)) \ + curelm = curelm->field.sle_next; \ + curelm->field.sle_next = \ + curelm->field.sle_next->field.sle_next; \ + } \ + _Q_INVALIDATE((elm)->field.sle_next); \ +} while (0) + +/* + * List definitions. + */ +#define LIST_HEAD(name, type) \ +struct name { \ + struct type *lh_first; /* first element */ \ +} + +#define LIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define LIST_ENTRY(type) \ +struct { \ + struct type *le_next; /* next element */ \ + struct type **le_prev; /* address of previous next element */ \ +} + +/* + * List access methods. + */ +#define LIST_FIRST(head) ((head)->lh_first) +#define LIST_END(head) NULL +#define LIST_EMPTY(head) (LIST_FIRST(head) == LIST_END(head)) +#define LIST_NEXT(elm, field) ((elm)->field.le_next) + +#define LIST_FOREACH(var, head, field) \ + for((var) = LIST_FIRST(head); \ + (var)!= LIST_END(head); \ + (var) = LIST_NEXT(var, field)) + +#define LIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = LIST_FIRST(head); \ + (var) && ((tvar) = LIST_NEXT(var, field), 1); \ + (var) = (tvar)) + +/* + * List functions. + */ +#define LIST_INIT(head) do { \ + LIST_FIRST(head) = LIST_END(head); \ +} while (0) + +#define LIST_INSERT_AFTER(listelm, elm, field) do { \ + if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ + (listelm)->field.le_next->field.le_prev = \ + &(elm)->field.le_next; \ + (listelm)->field.le_next = (elm); \ + (elm)->field.le_prev = &(listelm)->field.le_next; \ +} while (0) + +#define LIST_INSERT_BEFORE(listelm, elm, field) do { \ + (elm)->field.le_prev = (listelm)->field.le_prev; \ + (elm)->field.le_next = (listelm); \ + *(listelm)->field.le_prev = (elm); \ + (listelm)->field.le_prev = &(elm)->field.le_next; \ +} while (0) + +#define LIST_INSERT_HEAD(head, elm, field) do { \ + if (((elm)->field.le_next = (head)->lh_first) != NULL) \ + (head)->lh_first->field.le_prev = &(elm)->field.le_next;\ + (head)->lh_first = (elm); \ + (elm)->field.le_prev = &(head)->lh_first; \ +} while (0) + +#define LIST_REMOVE(elm, field) do { \ + if ((elm)->field.le_next != NULL) \ + (elm)->field.le_next->field.le_prev = \ + (elm)->field.le_prev; \ + *(elm)->field.le_prev = (elm)->field.le_next; \ + _Q_INVALIDATE((elm)->field.le_prev); \ + _Q_INVALIDATE((elm)->field.le_next); \ +} while (0) + +#define LIST_REPLACE(elm, elm2, field) do { \ + if (((elm2)->field.le_next = (elm)->field.le_next) != NULL) \ + (elm2)->field.le_next->field.le_prev = \ + &(elm2)->field.le_next; \ + (elm2)->field.le_prev = (elm)->field.le_prev; \ + *(elm2)->field.le_prev = (elm2); \ + _Q_INVALIDATE((elm)->field.le_prev); \ + _Q_INVALIDATE((elm)->field.le_next); \ +} while (0) + +/* + * Simple queue definitions. + */ +#define SIMPLEQ_HEAD(name, type) \ +struct name { \ + struct type *sqh_first; /* first element */ \ + struct type **sqh_last; /* addr of last next element */ \ +} + +#define SIMPLEQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).sqh_first } + +#define SIMPLEQ_ENTRY(type) \ +struct { \ + struct type *sqe_next; /* next element */ \ +} + +/* + * Simple queue access methods. + */ +#define SIMPLEQ_FIRST(head) ((head)->sqh_first) +#define SIMPLEQ_END(head) NULL +#define SIMPLEQ_EMPTY(head) (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head)) +#define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) + +#define SIMPLEQ_FOREACH(var, head, field) \ + for((var) = SIMPLEQ_FIRST(head); \ + (var) != SIMPLEQ_END(head); \ + (var) = SIMPLEQ_NEXT(var, field)) + +#define SIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = SIMPLEQ_FIRST(head); \ + (var) && ((tvar) = SIMPLEQ_NEXT(var, field), 1); \ + (var) = (tvar)) + +/* + * Simple queue functions. + */ +#define SIMPLEQ_INIT(head) do { \ + (head)->sqh_first = NULL; \ + (head)->sqh_last = &(head)->sqh_first; \ +} while (0) + +#define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \ + if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ + (head)->sqh_last = &(elm)->field.sqe_next; \ + (head)->sqh_first = (elm); \ +} while (0) + +#define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \ + (elm)->field.sqe_next = NULL; \ + *(head)->sqh_last = (elm); \ + (head)->sqh_last = &(elm)->field.sqe_next; \ +} while (0) + +#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ + if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ + (head)->sqh_last = &(elm)->field.sqe_next; \ + (listelm)->field.sqe_next = (elm); \ +} while (0) + +#define SIMPLEQ_REMOVE_HEAD(head, field) do { \ + if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ + (head)->sqh_last = &(head)->sqh_first; \ +} while (0) + +#define SIMPLEQ_REMOVE_AFTER(head, elm, field) do { \ + if (((elm)->field.sqe_next = (elm)->field.sqe_next->field.sqe_next) \ + == NULL) \ + (head)->sqh_last = &(elm)->field.sqe_next; \ +} while (0) + +#define SIMPLEQ_CONCAT(head1, head2) do { \ + if (!SIMPLEQ_EMPTY((head2))) { \ + *(head1)->sqh_last = (head2)->sqh_first; \ + (head1)->sqh_last = (head2)->sqh_last; \ + SIMPLEQ_INIT((head2)); \ + } \ +} while (0) + +/* + * XOR Simple queue definitions. + */ +#define XSIMPLEQ_HEAD(name, type) \ +struct name { \ + struct type *sqx_first; /* first element */ \ + struct type **sqx_last; /* addr of last next element */ \ + unsigned long sqx_cookie; \ +} + +#define XSIMPLEQ_ENTRY(type) \ +struct { \ + struct type *sqx_next; /* next element */ \ +} + +/* + * XOR Simple queue access methods. + */ +#define XSIMPLEQ_XOR(head, ptr) ((__typeof(ptr))((head)->sqx_cookie ^ \ + (unsigned long)(ptr))) +#define XSIMPLEQ_FIRST(head) XSIMPLEQ_XOR(head, ((head)->sqx_first)) +#define XSIMPLEQ_END(head) NULL +#define XSIMPLEQ_EMPTY(head) (XSIMPLEQ_FIRST(head) == XSIMPLEQ_END(head)) +#define XSIMPLEQ_NEXT(head, elm, field) XSIMPLEQ_XOR(head, ((elm)->field.sqx_next)) + + +#define XSIMPLEQ_FOREACH(var, head, field) \ + for ((var) = XSIMPLEQ_FIRST(head); \ + (var) != XSIMPLEQ_END(head); \ + (var) = XSIMPLEQ_NEXT(head, var, field)) + +#define XSIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = XSIMPLEQ_FIRST(head); \ + (var) && ((tvar) = XSIMPLEQ_NEXT(head, var, field), 1); \ + (var) = (tvar)) + +/* + * XOR Simple queue functions. + */ +#define XSIMPLEQ_INIT(head) do { \ + arc4random_buf(&(head)->sqx_cookie, sizeof((head)->sqx_cookie)); \ + (head)->sqx_first = XSIMPLEQ_XOR(head, NULL); \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \ +} while (0) + +#define XSIMPLEQ_INSERT_HEAD(head, elm, field) do { \ + if (((elm)->field.sqx_next = (head)->sqx_first) == \ + XSIMPLEQ_XOR(head, NULL)) \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ + (head)->sqx_first = XSIMPLEQ_XOR(head, (elm)); \ +} while (0) + +#define XSIMPLEQ_INSERT_TAIL(head, elm, field) do { \ + (elm)->field.sqx_next = XSIMPLEQ_XOR(head, NULL); \ + *(XSIMPLEQ_XOR(head, (head)->sqx_last)) = XSIMPLEQ_XOR(head, (elm)); \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ +} while (0) + +#define XSIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ + if (((elm)->field.sqx_next = (listelm)->field.sqx_next) == \ + XSIMPLEQ_XOR(head, NULL)) \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ + (listelm)->field.sqx_next = XSIMPLEQ_XOR(head, (elm)); \ +} while (0) + +#define XSIMPLEQ_REMOVE_HEAD(head, field) do { \ + if (((head)->sqx_first = XSIMPLEQ_XOR(head, \ + (head)->sqx_first)->field.sqx_next) == XSIMPLEQ_XOR(head, NULL)) \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \ +} while (0) + +#define XSIMPLEQ_REMOVE_AFTER(head, elm, field) do { \ + if (((elm)->field.sqx_next = XSIMPLEQ_XOR(head, \ + (elm)->field.sqx_next)->field.sqx_next) \ + == XSIMPLEQ_XOR(head, NULL)) \ + (head)->sqx_last = \ + XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ +} while (0) + + +/* + * Tail queue definitions. + */ +#define TAILQ_HEAD(name, type) \ +struct name { \ + struct type *tqh_first; /* first element */ \ + struct type **tqh_last; /* addr of last next element */ \ +} + +#define TAILQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).tqh_first } + +#define TAILQ_ENTRY(type) \ +struct { \ + struct type *tqe_next; /* next element */ \ + struct type **tqe_prev; /* address of previous next element */ \ +} + +/* + * Tail queue access methods. + */ +#define TAILQ_FIRST(head) ((head)->tqh_first) +#define TAILQ_END(head) NULL +#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) +#define TAILQ_LAST(head, headname) \ + (*(((struct headname *)((head)->tqh_last))->tqh_last)) +/* XXX */ +#define TAILQ_PREV(elm, headname, field) \ + (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) +#define TAILQ_EMPTY(head) \ + (TAILQ_FIRST(head) == TAILQ_END(head)) + +#define TAILQ_FOREACH(var, head, field) \ + for((var) = TAILQ_FIRST(head); \ + (var) != TAILQ_END(head); \ + (var) = TAILQ_NEXT(var, field)) + +#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = TAILQ_FIRST(head); \ + (var) != TAILQ_END(head) && \ + ((tvar) = TAILQ_NEXT(var, field), 1); \ + (var) = (tvar)) + + +#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ + for((var) = TAILQ_LAST(head, headname); \ + (var) != TAILQ_END(head); \ + (var) = TAILQ_PREV(var, headname, field)) + +#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ + for ((var) = TAILQ_LAST(head, headname); \ + (var) != TAILQ_END(head) && \ + ((tvar) = TAILQ_PREV(var, headname, field), 1); \ + (var) = (tvar)) + +/* + * Tail queue functions. + */ +#define TAILQ_INIT(head) do { \ + (head)->tqh_first = NULL; \ + (head)->tqh_last = &(head)->tqh_first; \ +} while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field) do { \ + if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ + (head)->tqh_first->field.tqe_prev = \ + &(elm)->field.tqe_next; \ + else \ + (head)->tqh_last = &(elm)->field.tqe_next; \ + (head)->tqh_first = (elm); \ + (elm)->field.tqe_prev = &(head)->tqh_first; \ +} while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field) do { \ + (elm)->field.tqe_next = NULL; \ + (elm)->field.tqe_prev = (head)->tqh_last; \ + *(head)->tqh_last = (elm); \ + (head)->tqh_last = &(elm)->field.tqe_next; \ +} while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ + if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ + (elm)->field.tqe_next->field.tqe_prev = \ + &(elm)->field.tqe_next; \ + else \ + (head)->tqh_last = &(elm)->field.tqe_next; \ + (listelm)->field.tqe_next = (elm); \ + (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ +} while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ + (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ + (elm)->field.tqe_next = (listelm); \ + *(listelm)->field.tqe_prev = (elm); \ + (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ +} while (0) + +#define TAILQ_REMOVE(head, elm, field) do { \ + if (((elm)->field.tqe_next) != NULL) \ + (elm)->field.tqe_next->field.tqe_prev = \ + (elm)->field.tqe_prev; \ + else \ + (head)->tqh_last = (elm)->field.tqe_prev; \ + *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ + _Q_INVALIDATE((elm)->field.tqe_prev); \ + _Q_INVALIDATE((elm)->field.tqe_next); \ +} while (0) + +#define TAILQ_REPLACE(head, elm, elm2, field) do { \ + if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL) \ + (elm2)->field.tqe_next->field.tqe_prev = \ + &(elm2)->field.tqe_next; \ + else \ + (head)->tqh_last = &(elm2)->field.tqe_next; \ + (elm2)->field.tqe_prev = (elm)->field.tqe_prev; \ + *(elm2)->field.tqe_prev = (elm2); \ + _Q_INVALIDATE((elm)->field.tqe_prev); \ + _Q_INVALIDATE((elm)->field.tqe_next); \ +} while (0) + +#define TAILQ_CONCAT(head1, head2, field) do { \ + if (!TAILQ_EMPTY(head2)) { \ + *(head1)->tqh_last = (head2)->tqh_first; \ + (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ + (head1)->tqh_last = (head2)->tqh_last; \ + TAILQ_INIT((head2)); \ + } \ +} while (0) + +#endif /* !_SYS_QUEUE_H_ */ diff --git a/lib/rgoose/rgooseCamera.cpp b/lib/rgoose/rgooseCamera.cpp index 61deba0a..a7b48a82 100644 --- a/lib/rgoose/rgooseCamera.cpp +++ b/lib/rgoose/rgooseCamera.cpp @@ -227,9 +227,7 @@ void ARGUS_Camera::updateOpticalParameters( uint16_t frame_width, uint16_t frame }; bool ARGUS_Camera::create(){ -#ifdef DEBUG - char tB[128]; -#endif + setWM( CAM_WS_INIT ); if( m_sNodeData.aux_id == 0 ) return false; @@ -262,24 +260,28 @@ bool ARGUS_Camera::create(){ - systemAnchor *tSYS = systemAnchor::getInstance(); - if ( tSYS == NULL ) { - LOG_ERROR("Can not get System Anchor!"); - return false; - }; -#ifdef DEBUG - sprintf( tB, "Pos: x:%.3f y:%.3f z:%.3f", m_sCamData.x , m_sCamData.y, m_sCamData.z ); - LOG( tB ); -#endif - if( tSYS->beLocal() ){ - m_oPosition.setPositionXYZ( m_sCamData.x, m_sCamData.y, m_sCamData.z, 0 ); + systemAnchor * SA = systemAnchor::getInstance(); + if( SA ){ + LOG("SysAnchor OK"); + if ( SA->beLocal() ) { + LOG("SysAnchor beLocal!"); + m_oPosition.setPositionXYZ( m_sCamData.x, m_sCamData.y, m_sCamData.z, 0 ); //SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sCamData.x_rot , m_sCamData.y_rot, m_sCamData.z_rot ); + } else { + LOG("SysAnchor is Global Position System!"); + C3D_DECART LD = SA->getXYZ(); + m_oPosition.setPositionXYZ( LD.x + m_sCamData.x, LD.y + m_sCamData.y, LD.z + m_sCamData.z, SA->getUTMZone() ); + m_oPosition.setOrientationDeg( m_sCamData.x_rot , m_sCamData.y_rot, m_sCamData.z_rot ); + }; } else { - C3D_DECART tpp = tSYS->getXYZ(); - m_oPosition.setPositionXYZ( tpp.x + m_sCamData.x, tpp.y + m_sCamData.y, tpp.z + m_sCamData.z, tSYS->getUTMZone() ); + LOG("No SysAnchor!"); + m_oPosition.setPositionXYZ( m_sCamData.x , m_sCamData.y, m_sCamData.z ); + m_oPosition.setOrientationDeg( m_sCamData.x_rot , m_sCamData.y_rot, m_sCamData.z_rot ); }; - m_oPosition.setOrientationDeg( m_sCamData.x_rot , m_sCamData.y_rot, m_sCamData.z_rot ); m_oPosition.updateMatrix(); + #ifdef DEBUG + char tB[128]; sprintf( tB, "Finalized Sensor Location: Lat:%.3f Lon:%.3f Alt:%.3f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); LOG( tB ); sprintf( tB, "Finalized Sensor Location: x:%.3f y:%.3f z:%.3f", m_oPosition.getX(), m_oPosition.getY(), m_oPosition.getZ() ); @@ -812,7 +814,7 @@ void ARGUS_Camera::m_fThreadProc( void ){ LOG("INIT GO -1 -1 -1"); #endif //setBusy( true ); - if( m_pProtocol->goAbsolute( -1, 0, -1 ) ) setWM( CAM_WS_READY ); + if( m_pProtocol->goAbsolute( -1, 0, -1 ) ) setWM( CAM_WS_READY ); //setBusy( false ); break; }; diff --git a/lib/rgoose/rgooseDBConnector.h b/lib/rgoose/rgooseDBConnector.h index ec4e58dd..f408d4c2 100644 --- a/lib/rgoose/rgooseDBConnector.h +++ b/lib/rgoose/rgooseDBConnector.h @@ -2,7 +2,7 @@ #define __ARGUS_DATABASE_CONNECTOR_HEADER__ #include "../components/base/basicSettingsProvider.h" -#include "../data/mysql/database_class.h" +#include "../data/mysql/mysql_class.h" #include "../alg/generic/md5.h" #include "../alg/lgs/mask.h" #include "rgooseTypes.h" diff --git a/lib/rgoose/rgooseHardwareManager.cpp b/lib/rgoose/rgooseHardwareManager.cpp index 25df9ce5..e7a42a55 100644 --- a/lib/rgoose/rgooseHardwareManager.cpp +++ b/lib/rgoose/rgooseHardwareManager.cpp @@ -6,6 +6,10 @@ #include "../hardware/hid/hid_dc.h" #include "../alg/generic/heapDebug.h" #include +#include +#include +#include +#include #define LOG( X ) m_pLog->Log( "HWM", this, X ) @@ -34,8 +38,7 @@ argusHardwareManager* argusHardwareManager::getInstance( bool cold_start ) { return _instance; }; -#include -#include + argusHardwareManager::argusHardwareManager( bool cold_start ){ m_pLog = basicLogCollection::getInstance(); @@ -243,8 +246,6 @@ int xioctl(int fh, int request, void *arg){ #define CLEAR(x) memset(&(x), 0, sizeof(x)) -#include -#include void argusHardwareManager::getMAC( CSTR if_name, CSTR buf ){ char tB[128]; diff --git a/lib/rgoose/rgooseHardwareResourceSerialProvider.cpp b/lib/rgoose/rgooseHardwareResourceSerialProvider.cpp index c482983e..a43dca40 100644 --- a/lib/rgoose/rgooseHardwareResourceSerialProvider.cpp +++ b/lib/rgoose/rgooseHardwareResourceSerialProvider.cpp @@ -766,9 +766,11 @@ void argusHardwareResourceSerialProvider::m_fThreadAProc(void){ if( m_nOutputBufferSize > 0 ){ index = 0; while ((index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED)){ +#ifdef DEBUG_EXTRA char TT[64]; sprintf( TT, "Have %d Bytes to send!", m_nOutputBufferSize ); LOG( TT ); +#endif RetVal = sendBlock( m_pOutputBuffer + index, m_nOutputBufferSize - index ); if( RetVal > 0 ){ index += RetVal; diff --git a/lib/rgoose/rgooseKernel.cpp b/lib/rgoose/rgooseKernel.cpp index 0bef329e..d9514893 100644 --- a/lib/rgoose/rgooseKernel.cpp +++ b/lib/rgoose/rgooseKernel.cpp @@ -376,7 +376,7 @@ CSTR SYS_COMANDS_SCRIPTS[]={ /* Main Kernel Thread Procedure */ void argusKernel::m_fThreadProc( void ){ char Buffer[CTEXT]; - time_t tTimeTSeconds; + time_t tTimeTSeconds = 0; int lastTSS = 0; int lastTMS = 0; DBC_EVT_RECORD * tEvtPtr; diff --git a/lib/rgoose/rgooseKernel.h b/lib/rgoose/rgooseKernel.h index 8c33e443..56ff835a 100644 --- a/lib/rgoose/rgooseKernel.h +++ b/lib/rgoose/rgooseKernel.h @@ -96,31 +96,6 @@ struct serial_struct { #define ARGUS_KERNEL_TAG_SITE_ID "SITE_ID" #define ARGUS_KERNEL_TAG_SERVER_IDENTITY "IDENTITY" -#define ARGUS_CMD_KRNL_RELOAD 128 -#define ARGUS_CMD_KRNL_DELNODE 240 -#define ARGUS_CMD_KRNL_RESET_SITE 245 -#define ARGUS_CMD_KRNL_RESTART 250 -#define ARGUS_CMD_KRNL_PNP 251 -#define ARGUS_CMD_KRNL_SYNC_TIME 252 -#define ARGUS_CMD_KRNL_SHUTDOWN 255 -#define ARGUS_CMD_KRNL_SYSTEM_TASK 120 -#define ARGUS_CMD_MODULES_RELOAD 60 -#define ARGUS_CMD_MODULE_ENABLE 61 -#define ARGUS_CMD_MODULE_DISABLE 62 -#define ARGUS_CMD_NODES_RELOAD 80 -#define ARGUS_CMD_NODE_RELOAD 81 -#define ARGUS_CMD_NODE_UPDATE 82 -#define ARGUS_CMD_ROI_GEO 40 -#define ARGUS_CMD_PTZ_GEO 41 -#define ARGUS_CMD_PTZ_ONVIF 42 -#define ARGUS_CMD_PTZ_MOVE 43 -#define ARGUS_CMD_HARDWARE_DETECT 27 - -#define ARGUS_CMD_STATUS_NEW 0 -#define ARGUS_CMD_STATUS_ACTIVE 1 -#define ARGUS_CMD_STATUS_FINISHED 2 - - class argusKernel: public basicThread, public basicEventHandler { private: #ifdef SIMULATE_KERNEL_TARGETS diff --git a/lib/rgoose/rgooseNode2D.cpp b/lib/rgoose/rgooseNode2D.cpp index 9f3c3066..83b892e8 100644 --- a/lib/rgoose/rgooseNode2D.cpp +++ b/lib/rgoose/rgooseNode2D.cpp @@ -226,17 +226,16 @@ bool ARGUS_2DSensor::startService() { }; m_oPosition.updateMatrix(); - char tB[128]; #ifdef DEBUG - sprintf( tB, "Data Pos: %.4f %.4f %.4f", m_sLRF_DATA.x, m_sLRF_DATA.y, m_sLRF_DATA.z ); - LOG( tB ); - sprintf( tB, "Data Pos: %.4f %.4f %.4f", m_sLRF_DATA.x_rot, m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + char tB[128]; + sprintf( tB, "Finalized Sensor Location: Lat:%.3f Lon:%.3f Alt:%.3f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); LOG( tB ); -#endif - sprintf( tB, "Sensor Position: %.4f %.4f %.4f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); + sprintf( tB, "Finalized Sensor Location: x:%.3f y:%.3f z:%.3f", m_oPosition.getX(), m_oPosition.getY(), m_oPosition.getZ() ); LOG( tB ); - sprintf( tB, "Sensor Orientation: %.4f %.4f %.4f", m_oPosition.getRotX_deg() , m_oPosition.getRotY_deg(), m_oPosition.getRotZ_deg() ); + sprintf( tB, "Orientation: x:%.3f y:%.3f z:%.3f", m_oPosition.getRotX_deg(), m_oPosition.getRotY_deg(), m_oPosition.getRotZ_deg() ); LOG( tB ); +#endif + if( m_sLRF_DATA.filter_id > 0 ) { LOG("DEFINED FILTER"); argusKernel *AK = argusKernel::getInstance(); diff --git a/lib/rgoose/rgooseNode3D.cpp b/lib/rgoose/rgooseNode3D.cpp index 0a584a68..92552832 100644 --- a/lib/rgoose/rgooseNode3D.cpp +++ b/lib/rgoose/rgooseNode3D.cpp @@ -69,17 +69,15 @@ bool argus3DLIDAR::startService(){ }; m_oPosition.updateMatrix(); - char tB[128]; #ifdef DEBUG - sprintf( tB, "Data Pos: %.4f %.4f %.4f", m_sLRF_DATA.x, m_sLRF_DATA.y, m_sLRF_DATA.z ); + char tB[128]; + sprintf( tB, "Finalized Sensor Location: Lat:%.3f Lon:%.3f Alt:%.3f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); LOG( tB ); - sprintf( tB, "Data Pos: %.4f %.4f %.4f", m_sLRF_DATA.x_rot, m_sLRF_DATA.y_rot, m_sLRF_DATA.z_rot ); + sprintf( tB, "Finalized Sensor Location: x:%.3f y:%.3f z:%.3f", m_oPosition.getX(), m_oPosition.getY(), m_oPosition.getZ() ); LOG( tB ); -#endif - sprintf( tB, "Sensor Position: %.4f %.4f %.4f", m_oPosition.getLat(), m_oPosition.getLon(), m_oPosition.getAlt() ); - LOG( tB ); - sprintf( tB, "Sensor Orientation: %.4f %.4f %.4f", m_oPosition.getRotX_deg() , m_oPosition.getRotY_deg(), m_oPosition.getRotZ_deg() ); + sprintf( tB, "Orientation: x:%.3f y:%.3f z:%.3f", m_oPosition.getRotX_deg(), m_oPosition.getRotY_deg(), m_oPosition.getRotZ_deg() ); LOG( tB ); +#endif #ifdef SIMULATE_3D_TARGETS diff --git a/lib/rgoose/rgooseTypes.h b/lib/rgoose/rgooseTypes.h index 540ee7a5..91fc2b2a 100644 --- a/lib/rgoose/rgooseTypes.h +++ b/lib/rgoose/rgooseTypes.h @@ -350,17 +350,44 @@ typedef struct S_DBC_RESOURCE_DATA{ char device[64]; }DBC_RESOURCE_DATA; +#define ARGUS_CMD_KRNL_RELOAD 128 +#define ARGUS_CMD_KRNL_DELNODE 240 +#define ARGUS_CMD_KRNL_RESET_SITE 245 +#define ARGUS_CMD_KRNL_RESTART 250 +#define ARGUS_CMD_KRNL_PNP 251 +#define ARGUS_CMD_KRNL_SYNC_TIME 252 +#define ARGUS_CMD_KRNL_SHUTDOWN 255 +#define ARGUS_CMD_KRNL_SYSTEM_TASK 120 +#define ARGUS_CMD_MODULES_RELOAD 60 +#define ARGUS_CMD_MODULE_ENABLE 61 +#define ARGUS_CMD_MODULE_DISABLE 62 +#define ARGUS_CMD_NODES_RELOAD 80 +#define ARGUS_CMD_NODE_RELOAD 81 +#define ARGUS_CMD_NODE_UPDATE 82 +#define ARGUS_CMD_ROI_GEO 40 +#define ARGUS_CMD_PTZ_GEO 41 +#define ARGUS_CMD_PTZ_ONVIF 42 +#define ARGUS_CMD_PTZ_MOVE 43 +#define ARGUS_CMD_HARDWARE_DETECT 27 + +#define ARGUS_CMD_STATUS_NEW 0 +#define ARGUS_CMD_STATUS_ACTIVE 1 +#define ARGUS_CMD_STATUS_FINISHED 2 #define DBC_CMD_STARTED 1 #define DBC_CMD_FINISHED 100 +#define DBC_CMD_FINISHED_ERROR 128 #define DBC_CMD_READY_TO_CLEAN 250 + typedef struct S_DBC_PUSHED_CMD{ uint32_t id; uint8_t CMD; char PARAM[256]; }DBC_PUSHED_CMD; + + typedef struct S_ROI_CMD_DATA{ uint16_t az_d; uint16_t el_d; @@ -669,6 +696,21 @@ typedef struct S_SHADOW{ uint32_t m_nEnabled; }SHADOW; +typedef struct S_DBC_SYS_LOAD_INFO{ + //Percs + float cpu1; + float cpu5; + float cpu15; + float mem; + float disk; + // Abs + uint64_t T_MEM; + uint64_t T_DISK; + uint64_t C_MEM; + uint64_t C_DISK; + uint32_t CPU_CORES; +}DBC_SYS_LOAD_INFO; + #endif \ No newline at end of file