Line data Source code
1 : /* 2 : This program is free software: you can redistribute it and/or modify 3 : it under the terms of the GNU General Public License as published by 4 : the Free Software Foundation, either version 3 of the License, or 5 : (at your option) any later version. 6 : 7 : This program is distributed in the hope that it will be useful, 8 : but WITHOUT ANY WARRANTY; without even the implied warranty of 9 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 : GNU General Public License for more details. 11 : 12 : You should have received a copy of the GNU General Public License 13 : along with this program. If not, see <http://www.gnu.org/licenses/>. 14 : */ 15 : 16 : /* 17 : * AP_IRLock_SITL.cpp 18 : * 19 : * Created on: June 09, 2016 20 : * Author: Ian Chen 21 : */ 22 : #include "AP_IRLock_config.h" 23 : 24 : #if AP_IRLOCK_SITL_GAZEBO_ENABLED 25 : 26 : #include "AP_IRLock_SITL_Gazebo.h" 27 : #include <SITL/SITL.h> 28 : #include <fcntl.h> 29 : #include <unistd.h> 30 : 31 : #include <iostream> 32 : 33 : extern const AP_HAL::HAL& hal; 34 : 35 0 : AP_IRLock_SITL_Gazebo::AP_IRLock_SITL_Gazebo() : 36 0 : _last_timestamp(0), 37 0 : sock(true) 38 0 : {} 39 : 40 0 : void AP_IRLock_SITL_Gazebo::init(int8_t bus) 41 : { 42 0 : SITL::SIM *sitl = AP::sitl(); 43 : // try to bind to a specific port so that if we restart ArduPilot 44 : // Gazebo keeps sending us packets. Not strictly necessary but 45 : // useful for debugging 46 0 : sock.bind("127.0.0.1", sitl->irlock_port); 47 : 48 0 : sock.reuseaddress(); 49 0 : sock.set_blocking(false); 50 : 51 0 : hal.console->printf("AP_IRLock_SITL::init()\n"); 52 : 53 0 : _flags.healthy = true; 54 0 : } 55 : 56 : // retrieve latest sensor data - returns true if new data is available 57 0 : bool AP_IRLock_SITL_Gazebo::update() 58 : { 59 : // return immediately if not healthy 60 0 : if (!_flags.healthy) { 61 0 : return false; 62 : } 63 : 64 : // receive packet from Gazebo IRLock plugin 65 : 66 : /* 67 : reply packet sent from simulator to ArduPilot 68 : */ 69 : struct irlock_packet { 70 : uint64_t timestamp; // in milliseconds 71 : uint16_t num_targets; 72 : float pos_x; 73 : float pos_y; 74 : float size_x; 75 : float size_y; 76 : } pkt; 77 0 : const int wait_ms = 0; 78 0 : ssize_t s = sock.recv(&pkt, sizeof(irlock_packet), wait_ms); 79 : 80 0 : bool new_data = false; 81 : 82 0 : if (s == sizeof(irlock_packet) && pkt.timestamp > _last_timestamp) { 83 : // fprintf(stderr, " posx %f posy %f sizex %f sizey %f\n", pkt.pos_x, pkt.pos_y, pkt.size_x, pkt.size_y); 84 0 : _target_info.timestamp = pkt.timestamp; 85 0 : _target_info.pos_x = pkt.pos_x; 86 0 : _target_info.pos_y = pkt.pos_y; 87 0 : _last_timestamp = pkt.timestamp; 88 0 : _last_update_ms = _last_timestamp; 89 0 : new_data = true; 90 : } 91 : 92 : // return true if new data found 93 0 : return new_data; 94 : } 95 : 96 : #endif // AP_IRLOCK_SITL_GAZEBO_ENABLED