mbed.org local branch of microbit-dal. The real version lives in git at https://github.com/lancaster-university/microbit-dal

Dependencies:   BLE_API nRF51822 mbed-dev-bin

Dependents:   microbit Microbit IoTChallenge1 microbit ... more

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers MicroBitRadio.cpp Source File

MicroBitRadio.cpp

00001 /*
00002 The MIT License (MIT)
00003 
00004 Copyright (c) 2016 British Broadcasting Corporation.
00005 This software is provided by Lancaster University by arrangement with the BBC.
00006 
00007 Permission is hereby granted, free of charge, to any person obtaining a
00008 copy of this software and associated documentation files (the "Software"),
00009 to deal in the Software without restriction, including without limitation
00010 the rights to use, copy, modify, merge, publish, distribute, sublicense,
00011 and/or sell copies of the Software, and to permit persons to whom the
00012 Software is furnished to do so, subject to the following conditions:
00013 
00014 The above copyright notice and this permission notice shall be included in
00015 all copies or substantial portions of the Software.
00016 
00017 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00018 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00019 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
00020 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00021 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
00022 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
00023 DEALINGS IN THE SOFTWARE.
00024 */
00025 
00026 #include "MicroBitConfig.h"
00027 #include "MicroBitRadio.h"
00028 #include "MicroBitComponent.h"
00029 #include "EventModel.h"
00030 #include "MicroBitDevice.h"
00031 #include "ErrorNo.h"
00032 #include "MicroBitFiber.h"
00033 #include "MicroBitBLEManager.h"
00034 
00035 /**
00036   * Provides a simple broadcast radio abstraction, built upon the raw nrf51822 RADIO module.
00037   *
00038   * The nrf51822 RADIO module supports a number of proprietary modes of operation oher than the typical BLE usage.
00039   * This class uses one of these modes to enable simple, point to multipoint communication directly between micro:bits.
00040   *
00041   * TODO: The protocols implemented here do not currently perform any significant form of energy management,
00042   * which means that they will consume far more energy than their BLE equivalent. Later versions of the protocol
00043   * should look to address this through energy efficient broadcast techbiques / sleep scheduling. In particular, the GLOSSY
00044   * approach to efficient rebroadcast and network synchronisation would likely provide an effective future step.
00045   *
00046   * TODO: Meshing should also be considered - again a GLOSSY approach may be effective here, and highly complementary to
00047   * the master/slave arachitecture of BLE.
00048   *
00049   * TODO: This implementation may only operated whilst the BLE stack is disabled. The nrf51822 provides a timeslot API to allow
00050   * BLE to cohabit with other protocols. Future work to allow this colocation would be benefical, and would also allow for the
00051   * creation of wireless BLE bridges.
00052   *
00053   * NOTE: This API does not contain any form of encryption, authentication or authorisation. Its purpose is solely for use as a
00054   * teaching aid to demonstrate how simple communications operates, and to provide a sandpit through which learning can take place.
00055   * For serious applications, BLE should be considered a substantially more secure alternative.
00056   */
00057 
00058 MicroBitRadio* MicroBitRadio::instance = NULL;
00059 
00060 extern "C" void RADIO_IRQHandler(void)
00061 {
00062     if(NRF_RADIO->EVENTS_READY)
00063     {
00064         NRF_RADIO->EVENTS_READY = 0;
00065 
00066         // Start listening and wait for the END event
00067         NRF_RADIO->TASKS_START = 1;
00068     }
00069 
00070     if(NRF_RADIO->EVENTS_END)
00071     {
00072         NRF_RADIO->EVENTS_END = 0;
00073         if(NRF_RADIO->CRCSTATUS == 1)
00074         {
00075             uint8_t sample = NRF_RADIO->RSSISAMPLE;
00076 
00077             // Associate this packet's rssi value with the data just
00078             // transferred by DMA receive
00079             MicroBitRadio::instance->setRSSI(sample);
00080 
00081             // Now move on to the next buffer, if possible.
00082             // The queued packet will get the rssi value set above.
00083             MicroBitRadio::instance->queueRxBuf();
00084 
00085             // Set the new buffer for DMA
00086             NRF_RADIO->PACKETPTR = (uint32_t) MicroBitRadio::instance->getRxBuf();
00087         }
00088         else
00089         {
00090             MicroBitRadio::instance->setRSSI(0);
00091         }
00092 
00093         // Start listening and wait for the END event
00094         NRF_RADIO->TASKS_START = 1;
00095     }
00096 }
00097 
00098 /**
00099   * Constructor.
00100   *
00101   * Initialise the MicroBitRadio.
00102   *
00103   * @note This class is demand activated, as a result most resources are only
00104   *       committed if send/recv or event registrations calls are made.
00105   */
00106 MicroBitRadio::MicroBitRadio(uint16_t id) : datagram(*this), event (*this)
00107 {
00108     this->id = id;
00109     this->status = 0;
00110     this->group = MICROBIT_RADIO_DEFAULT_GROUP;
00111     this->queueDepth = 0;
00112     this->rssi = 0;
00113     this->rxQueue = NULL;
00114     this->rxBuf = NULL;
00115 
00116     instance = this;
00117 }
00118 
00119 /**
00120   * Change the output power level of the transmitter to the given value.
00121   *
00122   * @param power a value in the range 0..7, where 0 is the lowest power and 7 is the highest.
00123   *
00124   * @return MICROBIT_OK on success, or MICROBIT_INVALID_PARAMETER if the value is out of range.
00125   */
00126 int MicroBitRadio::setTransmitPower(int power)
00127 {
00128     if (power < 0 || power >= MICROBIT_BLE_POWER_LEVELS)
00129         return MICROBIT_INVALID_PARAMETER;
00130 
00131     NRF_RADIO->TXPOWER = (uint32_t)MICROBIT_BLE_POWER_LEVEL[power];
00132 
00133     return MICROBIT_OK;
00134 }
00135 
00136 /**
00137   * Change the transmission and reception band of the radio to the given channel
00138   *
00139   * @param band a frequency band in the range 0 - 100. Each step is 1MHz wide, based at 2400MHz.
00140   *
00141   * @return MICROBIT_OK on success, or MICROBIT_INVALID_PARAMETER if the value is out of range,
00142   *         or MICROBIT_NOT_SUPPORTED if the BLE stack is running.
00143   */
00144 int MicroBitRadio::setFrequencyBand(int band)
00145 {
00146     if (ble_running())
00147         return MICROBIT_NOT_SUPPORTED;
00148 
00149     if (band < 0 || band > 100)
00150         return MICROBIT_INVALID_PARAMETER;
00151 
00152     NRF_RADIO->FREQUENCY = (uint32_t)band;
00153 
00154     return MICROBIT_OK;
00155 }
00156 
00157 /**
00158   * Retrieve a pointer to the currently allocated receive buffer. This is the area of memory
00159   * actively being used by the radio hardware to store incoming data.
00160   *
00161   * @return a pointer to the current receive buffer.
00162   */
00163 FrameBuffer* MicroBitRadio::getRxBuf()
00164 {
00165     return rxBuf;
00166 }
00167 
00168 /**
00169   * Attempt to queue a buffer received by the radio hardware, if sufficient space is available.
00170   *
00171   * @return MICROBIT_OK on success, or MICROBIT_NO_RESOURCES if a replacement receiver buffer
00172   *         could not be allocated (either by policy or memory exhaustion).
00173   */
00174 int MicroBitRadio::queueRxBuf()
00175 {
00176     if (rxBuf == NULL)
00177         return MICROBIT_INVALID_PARAMETER;
00178 
00179     if (queueDepth >= MICROBIT_RADIO_MAXIMUM_RX_BUFFERS)
00180         return MICROBIT_NO_RESOURCES;
00181 
00182     // Store the received RSSI value in the frame
00183     rxBuf->rssi = getRSSI();
00184 
00185     // Ensure that a replacement buffer is available before queuing.
00186     FrameBuffer *newRxBuf = new FrameBuffer();
00187 
00188     if (newRxBuf == NULL)
00189         return MICROBIT_NO_RESOURCES;
00190 
00191     // We add to the tail of the queue to preserve causal ordering.
00192     rxBuf->next = NULL;
00193 
00194     if (rxQueue == NULL)
00195     {
00196         rxQueue = rxBuf;
00197     }
00198     else
00199     {
00200         FrameBuffer *p = rxQueue;
00201         while (p->next != NULL)
00202             p = p->next;
00203 
00204         p->next = rxBuf;
00205     }
00206 
00207     // Increase our received packet count
00208     queueDepth++;
00209 
00210     // Allocate a new buffer for the receiver hardware to use. the old on will be passed on to higher layer protocols/apps.
00211     rxBuf = newRxBuf;
00212 
00213     return MICROBIT_OK;
00214 }
00215 
00216 /**
00217   * Sets the RSSI for the most recent packet.
00218   *
00219   * @param rssi the new rssi value.
00220   *
00221   * @note should only be called from RADIO_IRQHandler...
00222   */
00223 int MicroBitRadio::setRSSI(uint8_t rssi)
00224 {
00225     if (!(status & MICROBIT_RADIO_STATUS_INITIALISED))
00226         return MICROBIT_NOT_SUPPORTED;
00227 
00228     this->rssi = rssi;
00229 
00230     return MICROBIT_OK;
00231 }
00232 
00233 /**
00234   * Retrieves the current RSSI for the most recent packet.
00235   *
00236   * @return the most recent RSSI value or MICROBIT_NOT_SUPPORTED if the BLE stack is running.
00237   */
00238 int MicroBitRadio::getRSSI()
00239 {
00240     if (!(status & MICROBIT_RADIO_STATUS_INITIALISED))
00241         return MICROBIT_NOT_SUPPORTED;
00242 
00243     return this->rssi;
00244 }
00245 
00246 /**
00247   * Initialises the radio for use as a multipoint sender/receiver
00248   *
00249   * @return MICROBIT_OK on success, MICROBIT_NOT_SUPPORTED if the BLE stack is running.
00250   */
00251 int MicroBitRadio::enable()
00252 {
00253     // If the device is already initialised, then there's nothing to do.
00254     if (status & MICROBIT_RADIO_STATUS_INITIALISED)
00255         return MICROBIT_OK;
00256 
00257     // Only attempt to enable this radio mode if BLE is disabled.
00258     if (ble_running())
00259         return MICROBIT_NOT_SUPPORTED;
00260 
00261     // If this is the first time we've been enable, allocate out receive buffers.
00262     if (rxBuf == NULL)
00263         rxBuf = new FrameBuffer();
00264 
00265     if (rxBuf == NULL)
00266         return MICROBIT_NO_RESOURCES;
00267 
00268     // Enable the High Frequency clock on the processor. This is a pre-requisite for
00269     // the RADIO module. Without this clock, no communication is possible.
00270     NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
00271     NRF_CLOCK->TASKS_HFCLKSTART = 1;
00272     while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0);
00273 
00274     // Bring up the nrf51822 RADIO module in Nordic's proprietary 1MBps packet radio mode.
00275     setTransmitPower(MICROBIT_RADIO_DEFAULT_TX_POWER);
00276     setFrequencyBand(MICROBIT_RADIO_DEFAULT_FREQUENCY);
00277 
00278     // Configure for 1Mbps throughput.
00279     // This may sound excessive, but running a high data rates reduces the chances of collisions...
00280     NRF_RADIO->MODE = RADIO_MODE_MODE_Nrf_1Mbit;
00281 
00282     // Configure the addresses we use for this protocol. We run ANONYMOUSLY at the core.
00283     // A 40 bit addresses is used. The first 32 bits match the ASCII character code for "uBit".
00284     // Statistically, this provides assurance to avoid other similar 2.4GHz protocols that may be in the vicinity.
00285     // We also map the assigned 8-bit GROUP id into the PREFIX field. This allows the RADIO hardware to perform
00286     // address matching for us, and only generate an interrupt when a packet matching our group is received.
00287     NRF_RADIO->BASE0 = MICROBIT_RADIO_BASE_ADDRESS;
00288 
00289     // Join the default group. This will configure the remaining byte in the RADIO hardware module.
00290     setGroup(this->group);
00291 
00292     // The RADIO hardware module supports the use of multiple addresses, but as we're running anonymously, we only need one.
00293     // Configure the RADIO module to use the default address (address 0) for both send and receive operations.
00294     NRF_RADIO->TXADDRESS = 0;
00295     NRF_RADIO->RXADDRESSES = 1;
00296 
00297     // Packet layout configuration. The nrf51822 has a highly capable and flexible RADIO module that, in addition to transmission
00298     // and reception of data, also contains a LENGTH field, two optional additional 1 byte fields (S0 and S1) and a CRC calculation.
00299     // Configure the packet format for a simple 8 bit length field and no additional fields.
00300     NRF_RADIO->PCNF0 = 0x00000008;
00301     NRF_RADIO->PCNF1 = 0x02040000 | MICROBIT_RADIO_MAX_PACKET_SIZE;
00302 
00303     // Most communication channels contain some form of checksum - a mathematical calculation taken based on all the data
00304     // in a packet, that is also sent as part of the packet. When received, this calculation can be repeated, and the results
00305     // from the sender and receiver compared. If they are different, then some corruption of the data ahas happened in transit,
00306     // and we know we can't trust it. The nrf51822 RADIO uses a CRC for this - a very effective checksum calculation.
00307     //
00308     // Enable automatic 16bit CRC generation and checking, and configure how the CRC is calculated.
00309     NRF_RADIO->CRCCNF = RADIO_CRCCNF_LEN_Two;
00310     NRF_RADIO->CRCINIT = 0xFFFF;
00311     NRF_RADIO->CRCPOLY = 0x11021;
00312 
00313     // Set the start random value of the data whitening algorithm. This can be any non zero number.
00314     NRF_RADIO->DATAWHITEIV = 0x18;
00315 
00316     // Set up the RADIO module to read and write from our internal buffer.
00317     NRF_RADIO->PACKETPTR = (uint32_t)rxBuf;
00318 
00319     // Configure the hardware to issue an interrupt whenever a task is complete (e.g. send/receive).
00320     NRF_RADIO->INTENSET = 0x00000008;
00321     NVIC_ClearPendingIRQ(RADIO_IRQn);
00322     NVIC_EnableIRQ(RADIO_IRQn);
00323 
00324     NRF_RADIO->SHORTS |= RADIO_SHORTS_ADDRESS_RSSISTART_Msk;
00325 
00326     // Start listening for the next packet
00327     NRF_RADIO->EVENTS_READY = 0;
00328     NRF_RADIO->TASKS_RXEN = 1;
00329     while(NRF_RADIO->EVENTS_READY == 0);
00330 
00331     NRF_RADIO->EVENTS_END = 0;
00332     NRF_RADIO->TASKS_START = 1;
00333 
00334     // register ourselves for a callback event, in order to empty the receive queue.
00335     fiber_add_idle_component(this);
00336 
00337     // Done. Record that our RADIO is configured.
00338     status |= MICROBIT_RADIO_STATUS_INITIALISED;
00339 
00340     return MICROBIT_OK;
00341 }
00342 
00343 /**
00344   * Disables the radio for use as a multipoint sender/receiver.
00345   *
00346   * @return MICROBIT_OK on success, MICROBIT_NOT_SUPPORTED if the BLE stack is running.
00347   */
00348 int MicroBitRadio::disable()
00349 {
00350     // Only attempt to enable.disable the radio if the protocol is alreayd running.
00351     if (ble_running())
00352         return MICROBIT_NOT_SUPPORTED;
00353 
00354     if (!(status & MICROBIT_RADIO_STATUS_INITIALISED))
00355         return MICROBIT_OK;
00356 
00357     // Disable interrupts and STOP any ongoing packet reception.
00358     NVIC_DisableIRQ(RADIO_IRQn);
00359 
00360     NRF_RADIO->EVENTS_DISABLED = 0;
00361     NRF_RADIO->TASKS_DISABLE = 1;
00362     while(NRF_RADIO->EVENTS_DISABLED == 0);
00363 
00364     // deregister ourselves from the callback event used to empty the receive queue.
00365     fiber_remove_idle_component(this);
00366 
00367     // record that the radio is now disabled
00368     status &= ~MICROBIT_RADIO_STATUS_INITIALISED;
00369 
00370     return MICROBIT_OK;
00371 }
00372 
00373 /**
00374   * Sets the radio to listen to packets sent with the given group id.
00375   *
00376   * @param group The group to join. A micro:bit can only listen to one group ID at any time.
00377   *
00378   * @return MICROBIT_OK on success, or MICROBIT_NOT_SUPPORTED if the BLE stack is running.
00379   */
00380 int MicroBitRadio::setGroup(uint8_t group)
00381 {
00382     if (ble_running())
00383         return MICROBIT_NOT_SUPPORTED;
00384 
00385     // Record our group id locally
00386     this->group = group;
00387 
00388     // Also append it to the address of this device, to allow the RADIO module to filter for us.
00389     NRF_RADIO->PREFIX0 = (uint32_t)group;
00390 
00391     return MICROBIT_OK;
00392 }
00393 
00394 /**
00395   * A background, low priority callback that is triggered whenever the processor is idle.
00396   * Here, we empty our queue of received packets, and pass them onto higher level protocol handlers.
00397   */
00398 void MicroBitRadio::idleTick()
00399 {
00400     // Walk the list of packets and process each one.
00401     while(rxQueue)
00402     {
00403         FrameBuffer *p = rxQueue;
00404 
00405         switch (p->protocol)
00406         {
00407             case MICROBIT_RADIO_PROTOCOL_DATAGRAM:
00408                 datagram.packetReceived();
00409                 break;
00410 
00411             case MICROBIT_RADIO_PROTOCOL_EVENTBUS:
00412                 event.packetReceived();
00413                 break;
00414 
00415             default:
00416                 MicroBitEvent(MICROBIT_ID_RADIO_DATA_READY, p->protocol);
00417         }
00418 
00419         // If the packet was processed, it will have been recv'd, and taken from the queue.
00420         // If this was a packet for an unknown protocol, it will still be there, so simply free it.
00421         if (p == rxQueue)
00422         {
00423             recv();
00424             delete p;
00425         }
00426     }
00427 }
00428 
00429 /**
00430   * Determines the number of packets ready to be processed.
00431   *
00432   * @return The number of packets in the receive buffer.
00433   */
00434 int MicroBitRadio::dataReady()
00435 {
00436     return queueDepth;
00437 }
00438 
00439 /**
00440   * Retrieves the next packet from the receive buffer.
00441   * If a data packet is available, then it will be returned immediately to
00442   * the caller. This call will also dequeue the buffer.
00443   *
00444   * @return The buffer containing the the packet. If no data is available, NULL is returned.
00445   *
00446   * @note Once recv() has been called, it is the callers responsibility to
00447   *       delete the buffer when appropriate.
00448   */
00449 FrameBuffer* MicroBitRadio::recv()
00450 {
00451     FrameBuffer *p = rxQueue;
00452 
00453     if (p)
00454     {
00455          // Protect shared resource from ISR activity
00456         NVIC_DisableIRQ(RADIO_IRQn); 
00457 
00458         rxQueue = rxQueue->next;
00459         queueDepth--;
00460 
00461         // Allow ISR access to shared resource
00462         NVIC_EnableIRQ(RADIO_IRQn);
00463     }
00464 
00465     return p;
00466 }
00467 
00468 /**
00469   * Transmits the given buffer onto the broadcast radio.
00470   * The call will wait until the transmission of the packet has completed before returning.
00471   *
00472   * @param data The packet contents to transmit.
00473   *
00474   * @return MICROBIT_OK on success, or MICROBIT_NOT_SUPPORTED if the BLE stack is running.
00475   */
00476 int MicroBitRadio::send(FrameBuffer *buffer)
00477 {
00478     if (ble_running())
00479         return MICROBIT_NOT_SUPPORTED;
00480 
00481     if (buffer == NULL)
00482         return MICROBIT_INVALID_PARAMETER;
00483 
00484     if (buffer->length > MICROBIT_RADIO_MAX_PACKET_SIZE + MICROBIT_RADIO_HEADER_SIZE - 1)
00485         return MICROBIT_INVALID_PARAMETER;
00486 
00487     // Firstly, disable the Radio interrupt. We want to wait until the trasmission completes.
00488     NVIC_DisableIRQ(RADIO_IRQn);
00489 
00490     // Turn off the transceiver.
00491     NRF_RADIO->EVENTS_DISABLED = 0;
00492     NRF_RADIO->TASKS_DISABLE = 1;
00493     while(NRF_RADIO->EVENTS_DISABLED == 0);
00494 
00495     // Configure the radio to send the buffer provided.
00496     NRF_RADIO->PACKETPTR = (uint32_t) buffer;
00497 
00498     // Turn on the transmitter, and wait for it to signal that it's ready to use.
00499     NRF_RADIO->EVENTS_READY = 0;
00500     NRF_RADIO->TASKS_TXEN = 1;
00501     while (NRF_RADIO->EVENTS_READY == 0);
00502 
00503     // Start transmission and wait for end of packet.
00504     NRF_RADIO->TASKS_START = 1;
00505     NRF_RADIO->EVENTS_END = 0;
00506     while(NRF_RADIO->EVENTS_END == 0);
00507 
00508     // Return the radio to using the default receive buffer
00509     NRF_RADIO->PACKETPTR = (uint32_t) rxBuf;
00510 
00511     // Turn off the transmitter.
00512     NRF_RADIO->EVENTS_DISABLED = 0;
00513     NRF_RADIO->TASKS_DISABLE = 1;
00514     while(NRF_RADIO->EVENTS_DISABLED == 0);
00515 
00516     // Start listening for the next packet
00517     NRF_RADIO->EVENTS_READY = 0;
00518     NRF_RADIO->TASKS_RXEN = 1;
00519     while(NRF_RADIO->EVENTS_READY == 0);
00520 
00521     NRF_RADIO->EVENTS_END = 0;
00522     NRF_RADIO->TASKS_START = 1;
00523 
00524     // Re-enable the Radio interrupt.
00525     NVIC_ClearPendingIRQ(RADIO_IRQn);
00526     NVIC_EnableIRQ(RADIO_IRQn);
00527 
00528     return MICROBIT_OK;
00529 }