Rtos API example

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers mbed_poll.cpp Source File

mbed_poll.cpp

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2017 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 #include "mbed_poll.h"
00017 #include "FileHandle.h"
00018 #include "Timer.h"
00019 #ifdef MBED_CONF_RTOS_PRESENT
00020 #include "rtos/Thread.h"
00021 #endif
00022 
00023 namespace mbed {
00024 
00025 // timeout -1 forever, or milliseconds
00026 int poll(pollfh fhs[], unsigned nfhs, int timeout)
00027 {
00028     /**
00029      * TODO Proper wake-up mechanism.
00030      * In order to correctly detect availability of read/write a FileHandle, we needed
00031      * a select or poll mechanisms. We opted for poll as POSIX defines in
00032      * http://pubs.opengroup.org/onlinepubs/009695399/functions/poll.html Currently,
00033      * mbed::poll() just spins and scans filehandles looking for any events we are
00034      * interested in. In future, his spinning behaviour will be replaced with
00035      * condition variables.
00036      */
00037     Timer timer;
00038     if (timeout > 0) {
00039         timer.start();
00040     }
00041 
00042     int count = 0;
00043     for (;;) {
00044         /* Scan the file handles */
00045         for (unsigned n = 0; n < nfhs; n++) {
00046             FileHandle *fh = fhs[n].fh;
00047             short mask = fhs[n].events | POLLERR | POLLHUP | POLLNVAL;
00048             if (fh) {
00049                 fhs[n].revents = fh->poll(mask) & mask;
00050             } else {
00051                 fhs[n].revents = POLLNVAL;
00052             }
00053             if (fhs[n].revents) {
00054                 count++;
00055             }
00056         }
00057 
00058         if (count) {
00059             break;
00060         }
00061 
00062         /* Nothing selected - this is where timeout handling would be needed */
00063         if (timeout == 0 || (timeout > 0 && timer.read_ms() > timeout)) {
00064             break;
00065         }
00066 #ifdef MBED_CONF_RTOS_PRESENT
00067         // TODO - proper blocking
00068         // wait for condition variable, wait queue whatever here
00069         rtos::Thread::wait(1);
00070 #endif
00071     }
00072     return count;
00073 }
00074 
00075 } // namespace mbed