Brian Silverman | 6ae77dd | 2013-03-29 22:28:08 -0700 | [diff] [blame^] | 1 | #include "vision/PacketNotifier.h" |
| 2 | #include <stdio.h> |
| 3 | #include <unistd.h> |
| 4 | #include <stdlib.h> |
| 5 | #include <sys/mman.h> |
| 6 | #include <errno.h> |
| 7 | #include <string.h> |
| 8 | |
| 9 | namespace frc971 { |
| 10 | namespace vision { |
| 11 | |
| 12 | void PacketNotifier::RegisterSender(){ |
| 13 | close(fd[1]); |
| 14 | } |
| 15 | void PacketNotifier::RegisterReciever(){ |
| 16 | close(fd[0]); |
| 17 | } |
| 18 | PacketNotifier *PacketNotifier::MMap(size_t data_size){ |
| 19 | PacketNotifier *data; |
| 20 | data = (PacketNotifier *)mmap(NULL, ((data_size * 3 + 4095 + sizeof(PacketNotifier)) / 4096) * 4096, |
| 21 | PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); |
| 22 | data->data_size = data_size; |
| 23 | socketpair(PF_LOCAL, SOCK_STREAM, 0, data->fd); |
| 24 | for(int i = 0;i < 3;i++){ |
| 25 | data->buffs[i] = (uint8_t *)data + (sizeof(PacketNotifier) + i * data_size); |
| 26 | } |
| 27 | void *place = &(data->mutex); |
| 28 | *((int *)place) = 0; // The Mutex class needs a placement new operator. (you know, keep the masses happy); |
| 29 | data->in_flight = false; |
| 30 | data->to_send = -1; |
| 31 | data->sending = -1; |
| 32 | return data; |
| 33 | } |
| 34 | void *PacketNotifier::GetBuffer(){ |
| 35 | mutex.Lock(); |
| 36 | for(int i = 0; i < 3 ; i++){ //search for open spot. |
| 37 | if(i != sending && i != to_send){ //open |
| 38 | filling = i; |
| 39 | mutex.Unlock(); |
| 40 | printf("leasing out to fill buff # %d\n",i); |
| 41 | return buffs[i]; |
| 42 | } |
| 43 | } |
| 44 | mutex.Unlock(); |
| 45 | printf("Error in the fabric of the universe\n"); |
| 46 | exit(-42); |
| 47 | } |
| 48 | void PacketNotifier::Notify(){ |
| 49 | mutex.Lock(); |
| 50 | to_send = filling; |
| 51 | filling = -1; |
| 52 | mutex.Unlock(); |
| 53 | // wall error |
| 54 | if(write(fd[0],"\n",1)) {} |
| 55 | } |
| 56 | |
| 57 | void PacketNotifier::DataSent(const void * /*data*/, size_t /*datalen*/){ |
| 58 | printf("packet_sent: %d; fill: %d; to_send: %d \n",sending,filling,to_send); |
| 59 | mutex.Lock(); |
| 60 | sending = -1; |
| 61 | mutex.Unlock(); |
| 62 | in_flight = false; |
| 63 | } |
| 64 | bool PacketNotifier::GetData(char **place_to_put,size_t *length){ |
| 65 | if(in_flight) return false; |
| 66 | mutex.Lock(); |
| 67 | *length = data_size; |
| 68 | *place_to_put = (char *)buffs[to_send]; |
| 69 | sending = to_send; |
| 70 | to_send = -1; |
| 71 | mutex.Unlock(); |
| 72 | in_flight = true; |
| 73 | return true; |
| 74 | } |
| 75 | |
| 76 | } // namespace vision |
| 77 | } // namespace frc971 |
| 78 | |