scieee AI-readable full text Open interactive document viewer

Comunicació de dades a través de línies de potència mitjançant un sistema basat en BeagleBone

Ortega César, Josep Maria

Abstract

L’objectiu d’aquest projecte és dissenyar un sistema assequible però alhora altament personalitzable per poder ser utilitzat com a eina de laboratori per experimentar amb la comunicació entre dispositius a través d’una línia de potència i, en particular, a través de la xarxa elèctrica de 240VAC, fent ús de la banda de baixes freqüències autoritzada (al voltant dels 100kHz). L’eina hauria de servir per a poder avaluar el desplegament de la tecnologia PLC en escenaris diferents i així determinar la seva viabilitat. Per tant, ha de proporcionar una gran varietat d’opcions de configuració per a una màxima versatilitat, com per exemple, diferents esquemes de modulació, velocitats de transmissió configurables, nivells de tensió ajustables, etc. La transmissió de dades a través de la xarxa elèctrica es pot resumir en aquests punts claus: • En la part transmissora les dades s’han de modular per a no interferir amb altres senyalitzacions existents, com pot ser la telemetria intel·ligent emprada per les companyies elèctriques. L’ús de la banda disponible està regulat per organitzacions globals i és diferent segons la regió. • En la part receptora el senyal s’ha de capturar amb una freqüència de mostreig suficient per poder desmodular-lo correctament i recuperar les dades enviades. • En ambdós costats de la comunicació l’electrònica ha de gestionar l’acoblament entre el senyal modulat que porta les dades i el subministrament d’energia. Aquest projecte consisteix en el desenvolupament d’un paquet complet de software encarregat de governar un sistema existent basat en la popular plataforma BeagleBone Black amb una placa annexa (cape) que ha estat desenvolupada explícitament per aquest projecte (denominada PlcCape). El cor d’aquesta placa és un bloc analògic que integra un DAC d’alta velocitat que es controla mitjançant un bus SPI. El DAC, juntament amb una etapa de potència integrada, generarà el senyal modulat que es transmetrà per la línia de potència. Aquest projecte abasta les àrees següents: • Modificacions del codi font dels drivers SPI i ADC que vénen de sèrie amb la versió del Linux de la BBB, amb l’objectiu d’assolir el rendiment en temps-real que es necessita. • Creació de llibreries estàtiques reutilitzables que encapsulin l’accés de baix nivell al hardware. • Disseny d’un sistema basat en extensions (plugins) per permetre una fàcil personalització i expansió del software mitjançant la incorporació d’algoritmes de modulació de tercers. • Desenvolupament d’una aplicació dedicada per a ser utilitzada com una eina de laboratori que permeti provar amb diferents formes d’ona, freqüències, modulacions, filtres, guanys, etc. • Execució de proves de tot el sistema en escenaris diferents per confirmar la viabilitat de la solució proposada.

Full text

PROJECTE FINAL DE CARRERA Comunicació de dades a través de línies de potència mitjançant un sistema basat en BeagleBone (Data communication through power lines using a system based on BeagleBone) Estudis: Enginyeria de Telecomunicació Autor: Josep Maria Ortega César Director/a: Manuel Domínguez Pumar Any: 2016 2/180 Data communication through power lines using a system based on BeagleBone Data communication through power lines using a system based on BeagleBone 3/180 Table of Contents Agraïments........................................................................................................................................11 Resum del Projecte..........................................................................................................................12 Resumen del Proyecto.....................................................................................................................13 Abstract............................................................................................................................................14 1 Introduction...................................................................................................................................15 1.1 Context.................................................................................................................................15 1.2 Scenarios of use....................................................................................................................16 1.2.1 Industrial scope: data reporting to a central unit......................................................16 1.2.2 Domestic scope: sensors with medium-power consumption...................................16 1.3 Objectives.............................................................................................................................17 1.4 Challenges............................................................................................................................18 1.5 Document structure..............................................................................................................18 1.6 Document styles...................................................................................................................19 2 Background....................................................................................................................................20 2.1 PLC.......................................................................................................................................20 2.1.1 Basic notions............................................................................................................20 2.1.2 Standard protocols....................................................................................................21 2.1.3 CENELEC Bands.....................................................................................................23 2.1.4 Free open software solutions....................................................................................23 2.1.5 Commercial development kits.................................................................................24 2.2 BeagleBone black.................................................................................................................26 2.3 Linux....................................................................................................................................27 2.4 PlcCape board.......................................................................................................................29 2.4.1 Overview..................................................................................................................29 2.4.2 PlcCape-v1...............................................................................................................30 2.4.3 PlcCape-v2...............................................................................................................31 2.4.4 Software management..............................................................................................32 2.5 AFE031................................................................................................................................33 3 Implementation..............................................................................................................................36 3.1 Overview..............................................................................................................................36 3.2 Software development strategy............................................................................................36 3.3 Components developed........................................................................................................38 3.4 Drivers..................................................................................................................................39 3.4.1 Main target...............................................................................................................39 3.4.2 Basic notions............................................................................................................39 3.4.3 Loadable vs built-in.................................................................................................39 3.4.4 Device Tree Overlays...............................................................................................40 3.4.4.1 Basic notions..............................................................................................40 3.4.4.2 SPI data pins direction...............................................................................41 3.4.4.3 Driver entry-point hooking........................................................................42 3.4.4.4 DTO loading..............................................................................................42 3.4.5 Drivers loading notes...............................................................................................43 3.4.6 Drivers developed....................................................................................................43 3.4.6.1 spi-driver....................................................................................................44 4/180 Data communication through power lines using a system based on BeagleBone 3.4.6.1.1 Summary....................................................................................44 3.4.6.1.2 Requirements.............................................................................44 3.4.6.1.3 Testing means.............................................................................44 3.4.6.1.4 Auto Chip Select toggling..........................................................45 3.4.6.1.5 Ping Pong buffer with EDMA...................................................49 3.4.6.1.6 Analysis.....................................................................................53 3.4.6.1.7 Effective DAC frequency..........................................................54 3.4.6.2 adc-driver...................................................................................................58 3.4.6.2.1 Summary....................................................................................58 3.4.6.2.2 Requirements.............................................................................58 3.4.6.2.3 Patch...........................................................................................58 3.4.6.2.4 Analysis.....................................................................................61 3.5 Static libraries.......................................................................................................................68 3.5.1 Overview..................................................................................................................68 3.5.2 Libraries developed..................................................................................................68 3.5.2.1 libplc-tools.................................................................................................69 3.5.2.2 libplc-gpio..................................................................................................70 3.5.2.3 libplc-adc....................................................................................................71 3.5.2.4 libplc-cape..................................................................................................72 3.6 Plugins..................................................................................................................................73 3.6.1 Overview..................................................................................................................73 3.6.2 Categories.................................................................................................................73 3.6.2.1 Encoders.....................................................................................................74 3.6.2.2 Decoders....................................................................................................76 3.6.2.3 User Interface.............................................................................................77 3.6.3 Plugins developed....................................................................................................80 3.6.3.1 encoder-wave.............................................................................................81 3.6.3.2 encoder-pwm..............................................................................................83 3.6.3.3 decoder-pwm..............................................................................................85 3.6.3.4 encoder-ook................................................................................................86 3.6.3.5 decoder-ook................................................................................................87 3.6.3.6 ui-ncurses...................................................................................................90 3.6.3.7 ui-console...................................................................................................91 3.7 Applications..........................................................................................................................92 3.7.1 Overview..................................................................................................................92 3.7.2 Applications execution.............................................................................................92 3.7.3 Applications developed............................................................................................93 3.7.3.1 plc-cape-demo-lib-usage............................................................................94 3.7.3.2 plc-cape-autotest........................................................................................95 3.7.3.3 plc-cape-lab................................................................................................96 3.7.3.3.1 Main concepts............................................................................96 3.7.3.3.2 Features......................................................................................97 3.7.3.3.3 Basic operation..........................................................................97 3.7.3.3.4 Command line parameters.......................................................102 3.8 Pending tasks......................................................................................................................102 3.9 Development with Octave..................................................................................................104 3.9.1 Post-analysis...........................................................................................................104 3.9.2 IIR coefficients.......................................................................................................104 Data communication through power lines using a system based on BeagleBone 5/180 4 Analysis & results........................................................................................................................105 4.1 Overview............................................................................................................................105 4.2 Test equipment...................................................................................................................105 4.3 Data transmission in loop-mode.........................................................................................107 4.3.1 Purpose...................................................................................................................107 4.3.2 Testing environment...............................................................................................108 4.3.3 Results....................................................................................................................110 4.3.3.1 Test with PlcCape-v2...............................................................................110 4.3.3.2 Test with PlcCape-v1...............................................................................114 4.3.4 Conclusions............................................................................................................116 4.4 Data output at the Power Amplifier....................................................................................117 4.4.1 Purpose...................................................................................................................117 4.4.2 Testing environment...............................................................................................117 4.4.3 Results....................................................................................................................118 4.4.4 Conclusions............................................................................................................120 4.5 Data transmission over an unpowered line.........................................................................121 4.5.1 Purpose...................................................................................................................121 4.5.2 Testing environment...............................................................................................121 4.5.3 Results....................................................................................................................123 4.5.4 Conclusions............................................................................................................128 4.6 Data transmission over a low-voltage AC line...................................................................129 4.6.1 Purpose...................................................................................................................129 4.6.2 Testing environment...............................................................................................129 4.6.3 Results....................................................................................................................131 4.6.4 Conclusions............................................................................................................135 4.7 Data transmission over a high-voltage AC line..................................................................136 4.7.1 Purpose...................................................................................................................136 4.7.2 Testing environment...............................................................................................136 4.7.3 Results....................................................................................................................137 4.7.4 Conclusions............................................................................................................137 5 Conclusions..................................................................................................................................138 5.1 Feasibility...........................................................................................................................138 5.2 Reusability..........................................................................................................................139 5.3 Future development............................................................................................................140 5.4 Final assessment.................................................................................................................140 6 Annex I. Development tools........................................................................................................141 6.1 Hardware............................................................................................................................141 6.2 Software development tools...............................................................................................141 6.3 Other tools..........................................................................................................................141 7 Annex II. Connection between a Desktop PC and the BBB....................................................142 7.1 Configuration key points....................................................................................................142 7.2 Connection from a desktop PC to the BBB........................................................................142 7.3 Initial interaction with the BBB.........................................................................................145 7.4 Internet access....................................................................................................................147 7.4.1 Steps in the Desktop PC.........................................................................................147 7.4.2 Steps in the BBB....................................................................................................148 7.4.3 Date time management...........................................................................................149 6/180 Data communication through power lines using a system based on BeagleBone 7.5 Source code edition............................................................................................................150 7.6 Sending files to the BBB....................................................................................................150 7.7 Sharing files........................................................................................................................151 7.7.1 Sharing files through SAMBA...............................................................................151 7.7.2 Sharing files through NFS......................................................................................152 8 Annex III. Getting started with the development environment..............................................153 8.1 Tree structure......................................................................................................................153 8.1.1 Source code............................................................................................................153 8.1.2 Output warehouse..................................................................................................154 8.2 Basic equipment.................................................................................................................154 8.3 Checking the building environment...................................................................................155 8.4 Basic setup: compiling the ‘plc-cape’ framework..............................................................156 8.5 Advanced setup: out-of-tree building.................................................................................156 8.6 Benefits of the out-of-tree building....................................................................................158 8.7 Required packages: ncurses...............................................................................................159 8.8 Building hierarchy..............................................................................................................160 8.9 Building options.................................................................................................................161 8.10 makefile strategy on user-space components......................................................................161 8.11 makefile strategy on kernel-modules..................................................................................162 8.12 Doxygen.............................................................................................................................166 9 Annex IV. Software design principles........................................................................................169 9.1 Object Oriented Programming...........................................................................................169 9.2 Other source code guidelines.............................................................................................170 10 Annex V. Source code files.........................................................................................................173 10.1 Main C source code............................................................................................................173 10.2 Device Tree Overlays.........................................................................................................173 10.2.1 SPI..........................................................................................................................173 10.2.2 ADC.......................................................................................................................174 10.3 Octave.................................................................................................................................175 11 Bibliography...............................................................................................................................178 11.1 BeagleBoneBlack...............................................................................................................178 11.2 Linux..................................................................................................................................178 11.3 GNU packages....................................................................................................................179 11.4 C Language.........................................................................................................................179 11.5 PLC.....................................................................................................................................179 11.6 SDR....................................................................................................................................180 11.7 AFE031..............................................................................................................................180 11.8 Tools...................................................................................................................................180 Data communication through power lines using a system based on BeagleBone 7/180 Figures Figure 1. BeagleBone Black components..........................................................................................15 Figure 2. BBB main specifications.....................................................................................................26 Figure 3. PlcCape board attached to a BeagleBone Black.................................................................29 Figure 4. Blocks diagram of the assembly BBB (blue) + PlcCape (green)........................................29 Figure 5. PlcCape-v1 mounted board.................................................................................................30 Figure 6. PlcCape-v1 probing points..................................................................................................30 Figure 7. PlcCape-v2 mounted board.................................................................................................31 Figure 8. PlcCape-v2 probing points..................................................................................................31 Figure 9. AFE031 blocks and pins.....................................................................................................33 Figure 10. Drivers tree........................................................................................................................43 Figure 11. Writing to the DAC register..............................................................................................45 Figure 12. Absence of CSN pulse with the standard SPI driver.........................................................45 Figure 13. SPI Single-Channel Mode behavior..................................................................................46 Figure 14. Automatic CSN pulse with the patched SPI driver...........................................................47 Figure 15. Real-time test of DAC samples transmission using a sawtooth wave..............................47 Figure 16. Test of sinusoid generation at 50kHz................................................................................48 Figure 17. Typical effect in the DAC generation of a background operation....................................48 Figure 18. Chip-Select timing control................................................................................................54 Figure 19. SCLK (blue) and CSN (red) at SPI bitrate = 375kbps......................................................54 Figure 20. SCLK (blue) and CSN (red) at SPI bitrate = 1500kbps....................................................55 Figure 21. SCLK (blue) and CSN (red) at SPI bitrate = 3000kbps....................................................55 Figure 22. SCLK (blue) and CSN (red) at SPI bitrate = 6000kbps....................................................56 Figure 23. Width of the CSN pulse measured at 3000 kbps...............................................................56 Figure 24. ADC main specifications..................................................................................................58 Figure 25. Sinusoid of 10kHz captured by the ADC and plotted with Octave..................................62 Figure 26. Zoom of the ADC captured data to the sample level........................................................63 Figure 27. ADC capture of a sawtooth wave......................................................................................63 Figure 28. ADC capture of a triangular wave.....................................................................................64 Figure 29. ADC capture of a sinusoid of 80kHz................................................................................65 Figure 30. ADC capture of a sinusoid of 90kHz................................................................................65 Figure 31. ADC capture of a sinusoid of 100kHz..............................................................................66 Figure 32. ADC capture of a sinusoid of 110kHz..............................................................................66 Figure 33. ADC capture of a sinusoid of 120kHz..............................................................................67 Figure 34. Libraries tree.....................................................................................................................68 Figure 35. Plugins tree........................................................................................................................73 Figure 36. Example of PWM-encoded message................................................................................83 Figure 37. Test of the OOK modulation in calibration mode (auto-loop)..........................................88 Figure 38. OOK captured data + IIR filtering result + Data decoded................................................89 Figure 39. OOK encoding for the 'H' character = 72 = 0b01001000.................................................89 Figure 40. OOK encoding for the 'i' character = 105 = 0b01101001.................................................89 Figure 41. OOK 10kHz carrier detail.................................................................................................89 Figure 42. Main screen of the ‘plc-cape-lab’ when running with ui-console.....................................91 Figure 43. Applications tree...............................................................................................................92 Figure 44. Main screen of the 'plc-cape-autotest' application............................................................95 Figure 45. Main screen of the 'plc-cape-lab' application (running with 'ui-ncurses').........................96 Figure 46. Settings corresponding to the profile 'TX+RX CAL 2kHz'............................................100 Figure 47. Test kit.............................................................................................................................105 Figure 48. Calibration mode diagram...............................................................................................107 8/180 Data communication through power lines using a system based on BeagleBone Figure 49. Testing environment on calibration mode.......................................................................108 Figure 50. PlcCape-v2 patched with a wire......................................................................................108 Figure 51. Testing tools in the desktop PC.......................................................................................109 Figure 52. Communication test with plc-cape-lab in calibration mode............................................110 Figure 53. TX_F_OUT corresponding to 3 repetitions of the message transmitted.........................111 Figure 54. Detail of the 110kHz carrier............................................................................................112 Figure 55. Data captured by the ADC of the BBB...........................................................................112 Figure 56. Data captured by the ADC: zoom to 2000 first samples.................................................113 Figure 57. Data captured by the ADC: zoom to 100 first samples...................................................113 Figure 58. Testing environment with PlcCape-v1............................................................................114 Figure 59. Communication test with PlcCape-v1 in calibration mode.............................................114 Figure 60. TX_F_OUT of 3 messages iterations with PlcCape-v1..................................................115 Figure 61. Identification of the characters composing the message.................................................115 Figure 62 Detail of the 110kHz carrier generated by the PlcCape-v1..............................................116 Figure 63. Testing environment to check the Power Amplifier of the PlcCape-v1..........................117 Figure 64. Line-coupling auxiliary circuit........................................................................................117 Figure 65. Configuration settings to generate output through the Power Amplifier........................118 Figure 66. Signals at TX_F_OUT (CH1) and TXRX (CH2), 100ms/div.........................................118 Figure 67. Signals at TX_F_OUT (CH1) and TXRX (CH2), 10us/div............................................119 Figure 68. Configuration to probe the coupled-line.........................................................................119 Figure 69. TX_F_OUT (CH1) and coupled-line (CH2), 100ms/div................................................120 Figure 70. TX_F_OUT (CH1) and coupled-line (CH2), 10us/div...................................................120 Figure 71. Testing environment for communication over an unpowered line..................................121 Figure 72. Testing tools in the desktop PC.......................................................................................122 Figure 73. Screen capture of the plc-cape-lab at transmission.........................................................123 Figure 74. Screen capture of the plc-cape-lab at reception..............................................................123 Figure 75. Detail of the carrier signal in the TXRX pin...................................................................124 Figure 76. Probing point for the ADCIN signal...............................................................................125 Figure 77. TXRX at PlcCape-v1 (CH1) and ADCIN at PlcCape-v2 (CH2)....................................125 Figure 78. TXRX at PlcCape-v1 (CH1) and ADCIN at PlcCape-v2 (CH2), 100ms/div.................126 Figure 79. Correct reception of data when configuring RX_PGA2 to 16V/V (rx2:2).....................127 Figure 80. Detail of the ADCIN magnitude (CH2) when configuring RX_PGA2 to 16V/V..........127 Figure 81. Testing environment in a 12VAC line.............................................................................129 Figure 82. Detail of the wiring in the testing environment..............................................................130 Figure 83. Capture of the 12VAC power rail (CH2) with no transmission (CH1)...........................131 Figure 84. Capture of the 12VAC power rail (CH2) with PWM transmission (CH1).....................131 Figure 85. Detail of the 12VAC with superimposed data and without.............................................132 Figure 86. Detail of the end of a character transmission..................................................................132 Figure 87. Detail of the PWM carrier in the 12VAC........................................................................133 Figure 88. Correct reception of data.................................................................................................133 Figure 89. TXRX at PlcCape-v1 (CH1) and ADCIN at PlcCape-v2 (CH2), 10ms/div...................134 Figure 90. TXRX at PlcCape-v1 (CH1) and ADCIN at PlcCape-v2 (CH2), 10us/div....................134 Figure 91. Data captured by the ADC plotted with Octave..............................................................135 Figure 92. Detail of the data captured by the ADC over 100 samples.............................................135 Figure 93. Testing environment in a 240VAC line (the mains)........................................................136 Figure 94. Typical IP configuration on Windows XP when a BBB is attached to USB..................143 Figure 95. Main screen of the Putty application...............................................................................144 Figure 96. BBB login message (via a remote console on Putty)......................................................145 Figure 97. Version of the Linux Kernel of the BBB.........................................................................145 Figure 98. Resource sharing dialog in Windows XP........................................................................151 Data communication through power lines using a system based on BeagleBone 9/180 Figure 99. Source code tree..............................................................................................................153 Figure 100. Output tree.....................................................................................................................154 Figure 101. Basic development environment...................................................................................155 Figure 102. Main screen of the Doxywizard application.................................................................166 Figure 103. Home page of the Doxygen documentation..................................................................167 Figure 104. Doxygen documentation generated from the comments in the source code.................168 16/180 Data communication through power lines using a system based on BeagleBone 1.2 Scenarios of use This project is focused on the transmission of short packets of sporadic data, which can cover several scenarios. 1.2.1 Industrial scope: data reporting to a central unit An example of an interesting application of this technology is on industrial machines that need to report periodic status information to central servers: •When compared with other wired technologies, an advantage of PLC is its low implementation cost because it can reuse the existing infrastructure instead of having to deploy new rewiring (e.g. for a dedicated Ehternet connection). When compared with wireless systems, PLC is not attenuated by thick walls, it doesn’t require repeaters, it is less affected by RF interferences. •On the negative side, PLC in the industrial scope can be impacted by the high levels of noise generated by the high power machines operating in the factories. Moreover, the PLC devices could be forced to source high levels of current during the transmission of the data to avoid the attenuation due to the low-impedance of the high power machines. So, the viability of a PLC system on the industrial domain will probably depend on each specific situation: type and amount of machinery connected, distance to be covered, noise, quality and layout of the power supply network, reporting schedule (if it is acceptable or not to send data on idle periods), etc. A typical use case could be a package machine (or similar) in a production line reporting sporadic data. For example, it could send a data packet, after a predetermined number of products or at a predefined time interval, to notify a server (in a different place in the warehouse) about the status of the production, the products discarded, the incidences occurred, etc. 1.2.2 Domestic scope: sensors with medium-power consumption There are lots of sensors that are more suitable to be powered over the mains than to be battery-based. For example, the presence-detectors, which may send a packet of data to a server when people come into a room. Being usually located in places which are hard to reach, they would pose a maintenance problem if powered by batteries. In such a case, a PLC-based technology could be cheap enough to compete with Wifi or Bluetooth and may avoid the concerns around the deployment of “Access points” (repeaters, IP addresses, RF interferences, etc.). Concerning costs, a wireless solution is unbeatable when a low power device is involved (a temperature sensor for example) because some cheap battery-based implementation can be used. But if a medium-power device is required (a light bulb or some rolling shutters, for example), the wireless solution needs to interact with the AC mains (through a relay, TRIAC or similar), and therefore it will have a similar cost to the PLC implementation when considering the overall system. In particular, the cost of the communication block for each technology would come from: •wireless: IC to manage wireless protocol + antenna •PLC: IC to manage PLC protocol + Analog Front End (AFE) to produce the modulated signal + linecoupling transformer Other typical scenarios where the PLC technology can compete with Wi-Fi are those that require covering medium or long distances. For instance, to monitor information coming from presence-detectors or weatherstations in a community of neighbors (or in a large garden area): it could be more practical and convenient to Data communication through power lines using a system based on BeagleBone 17/180 install PLC-based devices than a wireless based solution that will likely require additional repeaters (the transmission power that a wireless device can deliver is limited by law to properly manage the sharing of the publicly available band). 1.3 Objectives This project has these main goals in mind: •create a highly customizable system able to fit into different scenarios: ◦low-power AC lines (e.g. 12 VAC), high-power AC lines (e.g. 240 VAC), DC power (e.g. 5VDC), unpowered direct wire ◦short and long transmission distances ◦noise, interferences, data coming from other devices in the power supply network ◦negotiable transmission rates for increased robustness and reliability when required •propose an inexpensive system to allow anyone to be introduced in the PLC domain •design a comfortable open free source framework to simplify evolutions, maintenance and experimentation with (the unstoppable DIY trend) •open the functionality offered by the device not only to PLC but to other areas relying on a DAC (Digital-to-Analog Converter) and/or an ADC (Analog-to-Digital Converter) •design a reusable and portable framework to allow adapting the project to other similar platforms (e.g. Raspberry Pi) with no excessive effort •learn about the programming model of a Linux-based device •make a clear and detailed documentation of the whole development process just in case other developers can benefit someway of the work done for this project The system will be focused on the transmission of short packets of sporadic data (control commands, presence detection, temperature...). Therefore, the data transmission rate is not a determining factor. Robustness is one of the priorities. Note that there are several standard protocols referring PLC. The target of this project is not to fit within one of those standards nor to compete with them but to give the user the possibility to define his own, which will probably be much simpler (and affordable) but featured enough for specific scenarios. Anyway, the proposed framework shall allow the development of pieces of custom software (plugins) for higher levels of agreement with existing standards. The hardware should be ready to meet them; the limiting factor could be the computational effort involved. There are also many commercial products concerning PLC. The target of this project is not to vie with them but to provide a versatile tool for students or hobbyists willing to be introduced to this world in an open, and affordable way. 18/180 Data communication through power lines using a system based on BeagleBone 1.4 Challenges Due to the chosen implementation, this project involves these main challenges: •Understand how the BeagleBone Black works and the features offered by the core microcontroller, the SITARA AM3358 SoC •Learn how to develop device drivers in Linux and tune/patch the ones for SPI and ADC to optimize performance for the PlcCape specific design •Learn how to develop different types of components (libraries, plugins and applications) in Linux •Learn how to use third party libraries, as ncurses for richer User Interfaces •Use, as much as possible, free software tools for the development (gcc, make, Octave, Eclipse…) and for the documentation (LibreOffice, Doxygen) •Make the application generic enough to be used for other purposes 1.5 Document structure This document covers the following areas in five main chapters: Chapter Topics covered Introduction Page 15 Basic notions, targets, challenges and a summary of the main topics covered by this project Background Page 20 Basic notions on Power Line Communications (PLC) A quick overview of some existing solutions Some notions about the BeagleBone Black platform Some notes about the Linux Operating System Main features of the Analog Front End chip used, the AFE031 A brief explanation about the PlcCape boards used Implementation Page 36 Software development principles and strategy Description of the patches done on the SPI and ADC drivers Summary of the components provided: libraries, plugins and applications A detailed description of the plc-cape-lab application which is the main tool developed to interact with the final assembly (BBB + PlcCape) Some notes about Octave use Analysis & results Page 105 Detailed description of a series of communication experiments, indicating the purpose, the testing environment, the results and the conclusions obtained for each one Conclusions Page 138 Final conclusions about the whole system feasibility after the tests Table 1. Summary of topics covered per chapter Data communication through power lines using a system based on BeagleBone 19/180 To simplify the reading of this documentation I’ve focused on the specific details of the project. I’ve also mentioned some basic background notions but tried to avoid reproducing much information easily available elsewhere (I’ve indicated the URL links instead). 1.6 Document styles For a simpler reading, the following styles have been used depending on the category of the documented entity: Category Style Source code main.c #include <stdio.h> int main(int argc, char *argv[]) { // Just a comment printf("Hello world\n"); return 0; } Other file content test.sh #!/bin/bash @echo Hello World Linux console commands # echo Hello world Note: Linux command lines starting with ‘#’ indicate execution from the root user, the default way in the BBB; ‘$’ means execution from a normal user, the default and recommended way for commands executed in a desktop PC with Linux (whenever possible) Windows XP console window C:\>echo Hello World Tips Tip: This might be something helpful… Quotes, citations, fragments of existing documentation […] This is a fragment of text from somewhere […] Cross-links to other parts in the document This is a link to this Style table References to Bibliography This is a reference to the first bibliographic reference[1] Table 2. Document styles 20/180 Data communication through power lines using a system based on BeagleBone 2 Background 2.1 PLC 2.1.1 Basic notions Power Line communications[34] is an old well-known technology used to transfer data reusing the same lines that are used to power the devices. Contrary to the wireless technologies, which usually fit to well-known standards (WiFi, BT, ZigBee…), PLC is not so standardized. That’s because it’s difficult to have a standard that efficiently covers all the needs of all the different possible PLC scenarios, like: •telemetry (smart-metering) for energy providers •telemetry on industrial specific areas (e.g. in solar plants) •monitoring of equipment in factories •home automation where devices are controlled/supervised from a central unit (lights, shutters, alarms, weather sensors…) •LAN over the power supply network at home •Internet brought to clients by energy providers Each application has its own particularities and challenges. Defining a protocol or a hardware that works well in all the situations could unnecessarily increase the cost of some basic solutions that may satisfy specific scenarios. These are examples of different requirements according to the target field: •in the industrial scope we can have hard and noisy environments because the action of the high power machines (motors, brute switching of high-loads, etc.) •in the home automation area we can sporadically have some noise and interferences coming from some high-power appliances (hairdryers, microwaves, etc) Depending on the environment and the requirements, the way to fight against the typical troubles. For example: •A custom transmission protocol could wait the source of the trouble (e.g. the hairdryer) to be switched off (monitoring the line). A basic error detection system may be enough to reject the invalid data received and wait for the next packet •Other applications may require FEC (Forward Error Correction) by the addition of an ECC (Error Correcting Code) prior to the transmission in order the receiver to be able to correct most of the wrong data captured •And other applications can require requesting the transmitter to resend the packet if an error is detected. This would involve more complexity in both devices, the transmitter and the receiver, because they would have to implement both communication directions (TX and RX) Data communication through power lines using a system based on BeagleBone 21/180 Depending on the power supply network we can also receive data from neighbors. If confidential information has to be managed, some kind of encryption should be considered. Note that in most cases we will need to deal with low impedance loads which impose the transmitters to source relatively high currents to avoid signal attenuation. 2.1.2 Standard protocols As already commented in 1.3 Objectives, the target of this project is not to develop good modulations algorithms nor complex protocol layers. Anyway some basic information about the existing standards is provided. For that and just for quick reference, I’ve reproduced the main points of the summarized information given in the always helpful Wikipedia: HomePlug http://en.wikipedia.org/wiki/HomePlug […] HomePlug is the family name for various power line communications specifications under the HomePlug designation, with each offering unique performance capabilities and coexistence or compatibility with other HomePlug specifications. Some HomePlug specifications target broadband applications such as in-home distribution of low data rate IPTV, gaming, and Internet content, while others focus on low-power, low throughput, and extended operating temperatures for applications such as smart power meters and in-home communications between electric systems and appliances […] PRIME https://en.wikipedia.org/wiki/PRIME_(PLC) […] PRIME is a specification for narrow band powerline communication. Power-line communication uses power lines as transmission media. PRIME is an acronym for "PoweRline Intelligent Metering Evolution". PRIME was conceived in 2007. […] The PRIME physical layer is based on OFDM (Orthogonal Frequency Division Multiplexing) and Differential Phase Shift Keying (BPSK, DQPSK and D8PSK) as carrier modulation. To address averse power line channel properties, robustness mechanism convolutional encoding (optional), scrambling and interleaving are used. PRIME Specification v1.4 also introduces repetition coding[5] as additional robustness mechanism. Originally, PRIME uses carrier frequencies (42 – 89 kHz) within the CENELEC A band and offers raw data rates between 5.4 kbit/s (Robust mode: DBPSK with convolutional encoding and repetition code) and 128.6 kbit/s (D8PSK). Since specification version 1.4, more frequency bands were introduced to utilize the higher frequencies (up to 471 kHz) in ARIB and FCC bands. Using the full FCC band, raw data rates are eight times as high as in CENELEC A band. […] G3-PLC https://en.wikipedia.org/wiki/Power-line_communication […] G3-PLC is the low layer protocol to enable large scale infrastructure on the electrical grid. G3-PLC may operate on CENELEC A band (35 kHz to 91 kHz) or CENELEC B band (98 kHz to 122 kHz) in Europe, on ARIB band (155 kHz to 403 kHz) in Japan and on FCC (155 kHz to 487 kHz) for the US and the rest of the world.[25] The technology used is OFDM sampled at 400 kHz with adaptative modulation and tone mapping. Error detection and correction is made by both a convolutional code and Reed-Solomon error correction. The required media access control is taken from IEEE 802.15.4, a radio standard 22/180 Data communication through power lines using a system based on BeagleBone […] In December 2011, G3 PLC technology was recognised as an international standard at ITU in Geneva where it is referenced as G.9903.[26][27] Narrowband orthogonal frequency division multiplexing power line communicationtransceivers for G3-PLC networks. With the use of IPv6, both PRIME and G3 enable communication between meters, grid actuators as well as smart objects. […] X10 https://en.wikipedia.org/wiki/X10_(industry_standard) […] X10 is a protocol for communication among electronic devices used for home automation (domotics). It primarily uses power line wiring for signaling and control, where the signals involve brief radio frequency bursts representing digital information. A wireless radio based protocol transport is also defined. […] UPB https://en.wikipedia.org/wiki/Universal_powerline_bus [...] Universal powerline bus (UPB) is a proprietary software protocol for power line communication between devices used for home automation. Household electrical wiring is used to send digital data between UPB devices via pulse-position modulation.[1] Communication can be peer to peer, with no central controller necessary.[2] UPB addressing allows 250 devices per house and 250 houses per transformer, and switches can coexist with other powerline carrier systems within the same house.[3] While UPB may be more efficient than X10, it has far fewer products available on the market.[4] [...] LonTalk https://en.wikipedia.org/wiki/LonTalk […] LonTalk is a protocol optimized for control. Originally developed by Echelon Corporation for networking devices over media such as twisted pair, powerlines, fiber optics, and RF. It is popular for the automation of various functions in industrial control, home automation, transportation, and buildings systems such as lighting and HVAC; see Intelligent building, the protocol has now been adopted as an open international control networking standard in the ISO/IEC 14908[1] family of standards. Published through ISO/IEC JTC 1/SC 6, this standard specifies a multi-purpose control network protocol stack optimized for smart grid, smart building, and smart city applications.. […] Table 3. PLC standards Data communication through power lines using a system based on BeagleBone 23/180 2.1.3 CENELEC Bands CENELEC is the European Committee for Electrotechnical Standardization[38][39]. This organization has regulated the way the low-frequency band can be used in power supply networks in the European Region: CENELEC Frequency Band Frequency Range Description Band A 9 kHz to 95 kHz Reserved for energy providers, mainly for telemetry Band B 95 kHz to 125 kHz Available for customers use. No protocol defined Band C 125 kHz to 140 kHz Available for customers use. Protocols must implement CSMA Band D 140 kHz to 148.5 kHz Available for customers use. No protocol defined Table 4. CENELEC bands For this project the CENELEC B band has been used. 2.1.4 Free open software solutions One of the principles of this project is to do as much as possible by software in order any modulation algorithm can be added just by updating the source code, without requiring changes on the electronics. This approach has also some drawbacks: Benefits Scalability New modulation schemes can be added just by updating the software Adaptability We have a mini laboratory tool that may help us to evaluate the feasibility of the PLC approach in different scenarios (if transmission speed is not important we can use slow encoding algorithms but with improved robustness and with reinforces tolerance to specific error conditions) Reusability By having full control of the DAC, we can afford applications other than just PLC, as we’ll see Cost effectiveness We can implement simple modulation schemes that can help cheap devices to report data with low-cost electronics Drawbacks CPU load The software for some modulation schemes may require heavy calculations in realtime. This may impose an intensive CPU load affecting the performance of other running applications or even a not attainable scenario Table 5. Benefits and Drawbacks of handling modulations by software That’s not a new idea. In fact the same concept is already put in place in some radio frequency systems. It is called Software Defined Radio[40] (SDR). The main difference here is that, in our case, we are focused on the more affordable low-frequency band of the PLC technology. Note that experimenting with SDR usually requires expensive hardware due to the high frequencies involved. 24/180 Data communication through power lines using a system based on BeagleBone An example of a free open software radio ecosystem is the GNU Radio[41]. It is very powerful with lots of modulators, demodulators, filters, generators, already implemented. It is possible that some algorithms implemented for the GNU Radio (in C++) can be adapted to our project in C (it’s something to evaluate in future). In any case, other open free software packages being specialized in signal processing, are also available, as the IT++[32]. As an example of the source code availability, find following some links to some information about the OFDM implementation in both ecosystems: •http://gnuradio.org/doc/doxygen/page_ofdm.html •http://itpp.sourceforge.net/devel/ofdm_8h.html Finally, many contributions from the Community can also be found in GitHub or similar hosting services. For example this project implements a QPSK modulator/demodulator in two versions, fixed point and floating-point: •https://github.com/gvaf/QPSK-Modem 2.1.5 Commercial development kits There are many proprietary products concerning PLC. For example, find below some developer kits for PLC from Texas Instruments (the manufacturer of the AFE031 chip used in this project): C2000 Power Line Modem Developer's Kit - TMDSPLCKIT-V3 http://www.ti.com/tool/tmdsplckit-v3 The C2000 Power Line Modem Developer's Kit enables easy development of software based Power Line Communication (PLC) modems. The kit includes two PLC modems based on the C2000 TMS320F28069 controlCARD and TI's advanced PLC analog front end AFE031. The included PLC SUITE software supports several communication techniques, including OFDM (PRIME/G3-PLC and 1901.2) and is SFSK-capable. The kit includes onboard USB JTAG emulation and Code Composer Studio. PRICE = $599.00(USD) Power Line Communications (PLC) Lite™ Reference Design for Industrial Applications - TIDM-INDUSTRIAL-PLC http://www.ti.com/tool/tidm-industrial-plc This TI implementation of Power Line Communications (PLC) is a new option for adding communications to industrial equipment such as solar arrays. PLC Lite™ offers higher data throughput than earlier forms of PLC and greater robustness for transmission across noisy electric lines by using OFDM PHY technology. This design is based upon a C2000 controlCARD and an analog front end for PLC. The C2000 MCU executes the entire PLC Lite software stack. TIDM-INDUSTRIAL-PLC achieves up to 21 kbps data rates across AC or DC power lines compared to traditional SFSK PLC solutions (2-5 kbps) all while decreasing the overall BOM cost of a typical PLC modem. PRICE = TMDSPLCKIT-V3 ($599) + TMDSCNCD28035 ($59) Data communication through power lines using a system based on BeagleBone 25/180 Power Line Communications Kit for CENELEC Frequency Band - TMDSPLCKITV4-CEN http://www.ti.com/tool/tmdsplckitv4-cen#0 This PLC kit is designed for the development of narrowband PLC systems across the CENELEC frequency bands (35 kHz-121kHz). The kit includes a pair of PLC modems each using Texas Instruments’ PLC docking station and SOMPLC-F28PLC83 System on Module (SOM). The SOMPLC-F28PLC83 SOM is a singleboard design for PLC in the CENELEC A frequency band. This single hardware design supports several popular PLC industry standards including G3 and PRIME. TI develops and provides the complete PLC software stacks along with the SoM. The PLC docking station includes the AC mains line coupling circuitry and system power management. PRICE = $499.00(USD) These kits are usually sold along with proprietary software in the form of libraries or firmware (binaries), as it is mentioned in this page: http://processors.wiki.ti.com/index.php/Smart_Grid_PLC_FAQ […] Is the PLC software open source? The software is an "open API" with libraries. We provide libraries and documentation on the contents of the libraries and how to use them. […] 32/180 Data communication through power lines using a system based on BeagleBone 2.4.4 Software management The PlcCape has the following connection points with the BBB that can be controlled by the software: •SPI bus to send both, either commands or DAC samples •Several GPIOs to flash three programmable LEDs in the PlcCape •Several GPIOs to detect fault conditions from the PlcCape board •Input data to be captured by the ADC at maximum speed (200 ksps by specifications) Through SPI commands we can manage: •the AFE031 blocks to enable (DAC, TX chain, RX chain, filters, PA, etc.) •the gains of the involved programmable amplifiers •the frequency band to be used (CENELEC A vs B/C/D) •the calibration modes, a function of the AFE031 that allows some internal routing among blocks •the source of a problem that caused a faulty condition The DAC of the AFE031 doesn’t produce predefined waves (as other chips do). This is one of the main missions of the software developed in this project. Data communication through power lines using a system based on BeagleBone 33/180 2.5 AFE031 The core of the PlcCape is the AFE031 integrated circuit which is composed of the following blocks: Figure 9. AFE031 blocks and pins A brief description of the main blocks and involved signals follows in the next pages. For more detailed information consult the AFE031 datasheet. The following two tables describe the blocks that compose the AFE031 and the related pins and signals. 34/180 Data communication through power lines using a system based on BeagleBone Block Description SPI Receives and routes two type of data: •8-bit based commands: to enable/disable the different blocks and configure them •10-bits based samples: real-time data to be sent to the DAC DAC Generates the analog voltages (from 0 to 3.3V) corresponding to the digital samples coming from the SPI block TxPGA Transmission (Tx) Programmable Gain Amplifier (PGA) for better output control. It allows four programmable gains: 0.250, 0.500, 0.707, 1.000 (in V/V units) Tx Filter Transmission Low Pass Filter (LPF). It filters the input signal at Tx_F_IN1 (usually the output from the TxPGA) with a configurable cut-off frequency: 95kHz for CENELEC A, 145kHz for CENELC B/C/D. The output goes from 0 to VDD. The maximum continuous DC current for both sourcing and sinking is about 25mA. Power Amplifier Amplifies the voltage of the input signal (limited to the voltage supply VDD <= 5.5V) to the higher levels of another external power supply (PA_VS from +7V to +24V). The PA offers a nominal gain of 6.5 V/V. The PA is able to deliver 1.5A. This project is designed for a +15V power supply RxPGA_1 First Programmable Gain Amplifier in the reception chain, before the integrated low-pass filter. If provides four programmable gains: 0.25, 0.5, 1, 2 (in V/V units) Rx Filter It’s a filter in the reception chain intended to remove the unwanted signals out of the CENELEC band. The cut-off frequency is affected by the parametrization of the CENELEC mode (A vs B/C/D) RxPGA_2 Second Programmable Gain Amplifier in the reception chain, after the low-pass filter. It provides four programmable gains: 1, 4, 16, 64 (in V/V units) Two-Wire Rx/Tx This block can be used for simple implementations of communications that use amplitude shift keying (ASK) with on-off keying (OOK) modulation. It is not used in this project because this functionality is already covered by the DAC-based implementation. Zero Crossing Zero Crossing module to easily detect the AC phase edges and thus allow a better use of the channel: •some protocols can relay on it for synchronization purposes •the data can be transmitted near the zero-pass-region where the consumption of connected machines or appliances may be lower Table 8. AFE031 main blocks Data communication through power lines using a system based on BeagleBone 35/180 Block Pin name Description SPI SCLK Serial clock indicating when DI and DO are valid DI Serial data sent from the BBB to the AFE031 (commands or DAC samples) DO Serial data sent back from the AFE031 to the BBB in response to BBB commands CSN Chip Select (Negated) used by the AFE031 as a strobe signal indicating the end of a 10-bits DAC sample TX TX_PGA_OUT Analog samples after the SPI to DAC conversion + TxPGA attenuation. This signal has a “step-shape” because the constant level between DAC samples Tx_F_OUT In this project the TX_PGA_OUT is directly routed to Tx_F_IN1. This leads TX_F_OUT to be the result of applying the low-pass TxFilter to the TX_PGA_OUT signal. The effect of this is a smother signal removing part of the DAC-quantification shape PA PA_IN It is the input to the Power Amplifier. The PA requires the signal to don’t have a DC component. To achieve this the TX_F_OUT traverses a decoupling capacitor PA_OUT This is the output of the Power Amplifier which magnifies the input signal using the PA_VS power supply RX Rx_PGA1_IN Input signal coming from the AC decoupling stage + the external pass-band filter. A decoupling capacitor is also required to allow the AFE031 biasing the level of the received AC signal Rx_PGA1_OUT = Rx_F_IN Output signal of the RxPGA_1 block. It’s the RX_PGA1_IN after some programmable amplification factor. This signal is directly connected to the input of the RxFilter (RX_F_IN) Rx_F_OUT Rx_F_IN filtered signal in either CENELEC A or B/C/D band Rx_PGA2_IN Input to the RxPGA_2 block. It’s the RX_F_OUT after a decoupling capacitor to allow the AFE031 for proper internal biasing of the AC signal Rx_PGA2_OUT Output of the RxPGA_2 block after the last programmable amplification ADCIN (not in the AFE but in the BBB) Signal sent to the ADC of the BBB. It comes from Rx_PGA2_OUT after a voltage resistor divider to adjust the levels (from 0 to 3.3V) to the range of the ADC in the BBB (absolute max value 1.8V) ZC ZC_IN1 Low-level “clone” of the 240 VAC line for Zero Cross detection. The 240 VAC can be converted to a low-level clone through high-impedance resistors or through an optocoupler ZC_OUT1 Digital signal indicating the zero-crossing points Table 9. AFE031 pins and signals 36/180 Data communication through power lines using a system based on BeagleBone 3 Implementation 3.1 Overview The main target of this project is to develop a versatile system to send data over Power Lines based on an existing assembly composed of a BBB + a PlcCape board, and evaluate the feasibility of the solution in different scenarios. For that purpose, one of the main missions of the software is to convert data to a modulated signal within the allowed CENELEC band. The main requirements for this project are quite common: •high speed SPI communication to send real time data to a DAC •high-speed ADC capturing This leads to consider developing reusable code that may be adapted to other similar projects. Note that this project is not focused on providing good modulation/demodulation algorithms. There already are existing packages doing so in efficient ways (as already discussed in 2.1.4 Free open software solutions). So, very basic modulators are going to be developed here, just to cover the feasibility analysis. As the software is the key-point of this project, next chapters will focus on a detailed explanation about. 3.2 Software development strategy To manage the BBB + PlcCape assembly, a dedicated software has been developed consisting on: •Modifications of the existing drivers: ◦in the SPI driver: ▪to adapt it to the custom behavior of the AFE031 DAC which uses the Chip Select line as a clock synchronization mechanism ▪to use a DMA ping-pong buffer for real-time continuous data transmission to the DAC of the AFE031, leaving the CPU free for other tasks in the background ◦in the ADC driver, for faster data capturing •Development of static libraries (*.a) for a convenient encapsulation of the reusable functionality •Development of dynamic libraries (*.so) as a convenient way of developing extensions (plugins) with a short-learning curve •Creation of dedicated applications to explore all the possibilities of the AFE031 chip The whole ensemble has been called the “plc-cape framework”. The plc-cape framework is customized for the PlcCape board but the idea (the tree architecture, the makefile strategy, etc) can be reused as a template or skeleton to build other similar projects. Data communication through power lines using a system based on BeagleBone 37/180 For portability and maintenance reasons, these principles have been followed: •The framework has been developed in ANSI-C (and not C++) for maximum portability: even though C++ compilers are frequent, C compilers are present in almost any platform (even for low-cost microcontrollers or DSPs). Moreover, note that being C++ a superset of C (C++ compilers can compile C code), the chances of having a C compiler for a specific platform is always higher •The dependencies with third party packages have been minimized for portability reasons too. When a third party library is used (e.g. the ncurses package), it has been encapsulated (within a plugin for example) to simplify the task of migrating the framework to other platforms. Thus, if a dependency doesn’t exist on a particular system (a common scenario when third-party components are only offered in binary format), only the affected plugin need to be adapted; the remaining parts of the framework can still work Logically, the use of existing libraries for complex tasks (e.g. complex modulators plugins) is encouraged to avoid spending time reinventing the wheel For this project only one third-party library (not included in the standard Debian Wheezy distribution coming with the BBB) has been used, the ncurses package, to provide a rich-enough user interface for comfortable testing of the PlcCape board. Information about how to install this package can be found in Annex III. Getting started with the development environment. The framework is based on the principles of modularity and encapsulation, implicitly imposed by the usage of libraries and plugins. This approach has the following benefits: Pros Customization Easily customizable by creating: •new standalone applications relying on the functionality offered by the libraries of the framework •new plugins for improved modulators and demodulators Maintenance The source code is more readable because isolated per functional/logical area The origin of the bugs can be quickly located The decomposition of the framework in isolated building units allows for faster compilation times because only the affected component needs to be rebuilt (interesting when compiling on the BBB which has a medium speed processor) Table 10. Main benefits of a modular approach The source code has been documented following Doxygen[48] patterns. This provides: •a good way to quickly produce an always updated and synchronized documentation of the source code •a rich and practical documentation with very helpful and comfortable cross-referenced links between the source-code and other organized documentation More information about Doxygen is available in the section 8.12 Doxygen. 38/180 Data communication through power lines using a system based on BeagleBone Despite the considerable programming work done, the software is still in an early development stage: on one hand the current foundations of the framework are quite consolidated but on the other hand the specific implementation of the components needs to be optimized (for better performance) and refactored (for better modularity and maintenance). A brief explanation of the developed components and the key points of the software are exposed in the next sections with the aim of providing enough information to allow anyone that can be interested in, to be introduced to the framework with the minimum effort and with a short learning-curve. Anyone who wants to play with the source-code should read first these annexes: •Annex III. Getting started with the development environment: to quickly setup the development environment and be able to compile the plc-cape framework in a BBB platform •Annex IV. Software design principles: to know some details about the source code implementation •Annex V. Source code files: to get the sources 3.3 Components developed Next sections will focus on the components developed within each category: Category Components developed drivers spi, adc static libraries libplc-tools, libplc-gpio, libplc-adc, libplc-cape plug-ins encoders: encoder-wave, encoder-pwm, encoder-ook decoders: decoder-pwm, decoder-ook user interfaces: ui-ncurses, ui-console applications plc-cape-demo-lib-usage, plc-ape-autotest, plc-cape-lab Table 11. Components developed per category For each category some brief notes will be exposed first. Then a brief description of each developed component will be given (in tabular format) as a quick way to easily find the purpose and features covered by each element. Links to the Doxygen’s documentation are included, though unfortunately they point to a hard-coded location, Y:\doc\doxygen\html. If you can map Doxygen’s documentation to that path, you’ll have additional information when clicking on those links. If not, this information can also be accessed just by browsing the Doxygen’s Wiki pages: double click on the Doxygen’s main page, doc/doxygen/html/index.html, and use the tree panel or the search box. More information about Doxygen is included in the section 8.12 Doxygen. Shortcut: plc-cape-lab is the main application used in the chapter 4 Analysis & results. It’s a kind of laboratory tool with multiple options. A detailed description can be found in the chapter 3.7.3.3 plc-cape-lab. Data communication through power lines using a system based on BeagleBone 39/180 3.4 Drivers 3.4.1 Main target The standard SPI and ADC drivers in the off-the-shelf Debian Linux distribution which comes with the BBB are not able to process the data with the particularities required by this project, which can be summarized in: •ChipSelect auto-toggling per DAC sample •continuous transmission of DAC samples in real-time (without jitter and with low CPU impact) •high-speed ADC capturing The underlying hardware provides functionality enough to cover these requirements. SPI and ADC drivers need to be adapted to maximize performance taking advantage of the BBB processor. 3.4.2 Basic notions Drivers are made up of low-level code designed to manage devices. They have the following characteristics: •run in kernel space in privileged mode. In contrast to user-space applications drivers have full access to the hardware. Thus, they must be developed with care as they can easily hang the whole system •provide a high-level interface for communication with devices, aimed to applications running in user-space •drivers cannot use the functionality provided by well-known standard C libraries as glibc, pthread, etc. They have their own syntax (e.g. printk is the dual to printf) The separation between user-space and kernel-space is very convenient as a way to protect the system. For instance, it allows the system to nicely kill a user-space process that is hanging the system: •a "while(1);" loop from a user space application can be killed •a "while(1);" loop from a kernel space driver can hang the system Most development is done in user-space. The implementation of the different running modes (kernel-space vs user-space) requires the CPU to support privileged modes. Old processors, as the 8086 didn’t have that support. Subsequent evolutions of the x86 architecture (286, 386, 486, 586 = Pentium, etc) added support to privileged modes and memory mapping that increased robustness. The main drawback of protected modes is only the addition of some development complexity, as we’ll see when patching the drivers. The BeagleBone Back is based on the ARM Cortex-A8 (based on the ARM7 architecture) which also integrates privileged modes and memory mapping. 3.4.3 Loadable vs built-in In the Linux Kernel we roughly have two types of drivers: •built-in: they are integrated within the kernel image and loaded at operating system initialization 40/180 Data communication through power lines using a system based on BeagleBone •loadable: they come in separate binary files with the extension .ko (standing for Kernel Object). They can be loaded and unloaded on-demand. They are called kernel modules These are some interesting commands related with the management of modules: Command Summary insmod Installs/loads a loadable kernel module rmmod Removes a loadable kernel module modprobe Checks if a kernel module is currently loaded. If it is not then modprobe tries to install it (as insmod) modinfo Gets information from a kernel module Table 12. Basic commands for modules management In the Linux Kernel that comes with the off-the-shelf BBB, the SPI and ADC drivers are built-in, a fact that make things a bit more complex. We have (at least) three methods to modify these drivers: •patch the source code of the original drivers and then rebuild the whole Linux Kernel. This is an unaffordable procedure in initial development phases because even simple tests would take too long to be practical. This is only a possible solution when the source code of the drivers is stable enough •rebuild the kernel configuring the SPI and ADC drivers as loadable modules instead of built-in. This is the typical way but still requires the whole kernel to be rebuilt once, which is an intimidating task (at least for newbies as I am) •modify the source-code of the SPI and ADC drivers but load them as auxiliary modules, complementing the functionality of the standard ones. The complexity of this solution resides on redirecting standard SPI and ADC calls to our customized drivers. It’s a kind of hooking or hacking In this project, the option chosen has been the last one: “driver redirection”. To do that, the standard Device Tree Overlays of SPI and ADC have been modified. 3.4.4 Device Tree Overlays 3.4.4.1 Basic notions Device Tree Overlays (DTO) is a Linux concept intended to simplify the configuration of devices among different platforms. They describe the resources required by a specific device and provide a comfortable way of configuring it “on-the-fly”. In old versions of Linux that information was set when building the kernel. So, even for basic modifications of the hardware, a kernel rebuilding process was required, which is a task that usually takes several hours. In this project some parts of the standard DTOs for the SPI and ADC drivers have been customized with two goals in mind: •define a hook to redirect the standard driver calls to the customized ones •provide some specific configuration (e.g. the direction of the DIN and DOUT pins in the SPI bus) Data communication through power lines using a system based on BeagleBone 41/180 DTOs are described in a human readable form (in a *.dts file) which needs to be compiled with the dtc tool to the binary format the Linux Kernel understands[27] (a *.dtbo file, standing for Device Tree Blob). For that purpose a script has been provided together with the DTS. For instance, this is the one for the ADC driver: drivers/adc/dtb/compile-overlay.sh dtc -O dtb -o PLC_CAPE-ADC-00A0.dtbo -b 0 -@ PLC_CAPE-ADC-00A0.dts mv PLC_CAPE-ADC-00A0.dtbo /lib/firmware The script compiles the PLC_CAPE-ADC-00A0.dts to PLC_CAPE-ADC-00A0.dtbo and moves it to the /lib/firmware folder where all the DTBOs reside. The DTS files used are enclosed in 10.2 Device Tree Overlays. We can do the reverse process of getting the human readable format from a DTBO with the fdtdump tool: # fdtdump /lib/firmware/BB-SPIDEV0-00A0.dtbo 3.4.4.2 SPI data pins direction The standard SPI driver allows configuring the direction of the DIN and DOUT pins in the SPI bus through its DTO. PlcCape-v1 was designed with DIN and DOUT following the opposite configuration of the default convention. PlcCape-v2 was designed to be conforming to. So, the PlcCape-v1 requires the default DTO to be adapted. For that, PLC_CAPE_V1-SPI0-00A0.dts needs the DIN and DOUT pins to be configured in two places: •a first modification in the am33xx_pinmux target to specify the hardware configuration (OUTPUT ↔ INPUT) •a second modification in the spi0 target to indicate the logical behavior of the pins. For PlcCape-v1 we are requesting the SPI driver to work in the pindir-d0-out-d1-in configuration, the opposite of the standard mode PLC_CAPE_V2-SPI0-00A0.dts ... fragment@0 { target = <&am33xx_pinmux>; __overlay__ { spi0_pins_s0: spi0_pins_s0 { pinctrl-single,pins = < 0x150 0x30 /* spi0_sclk, INPUT_PULLUP | MODE0 */ /* D0 & D1 with std configuration */ 0x154 0x30 /* spi0_d0, INPUT_PULLUP | MODE0 */ 0x158 0x10 /* spi0_d1, OUTPUT_PULLUP | MODE0 */ 0x15c 0x10 /* spi0_cs0, OUTPUT_PULLUP | MODE0 */ >; }; }; }; PLC_CAPE_V1-SPI0-00A0.dts ... fragment@0 { target = <&am33xx_pinmux>; __overlay__ { spi0_pins_s0: spi0_pins_s0 { pinctrl-single,pins = < 0x150 0x30 /* spi0_sclk, INPUT_PULLUP | MODE0 */ 48/180 Data communication through power lines using a system based on BeagleBone This leads to a sampling rate greater than 50k*2*11 = 1100 kbps. By default, the SPI driver is configured to allow bit rates in multiples of 2, with 750 kbps a typical value. For our case we need at least the next step which is 1500 kbps (1.5 Mbps). Find following a capture of a 50kHz sinusoid at 1.5Mbps: Figure 16. Test of sinusoid generation at 50kHz It seems good but, unfortunately, after several tests we realize that sometimes a wrong generation happens: Figure 17. Typical effect in the DAC generation of a background operation The graph above seems to indicate that there is a small gap during which the DAC generation is paused and kept constant (here for about 30 microseconds). To correct this effect we can: •boost the priority of our dedicated thread and our main process: this will reduce the chance of another process to acquire the CPU for too much time, but the possibility still exists. Moreover, this Data communication through power lines using a system based on BeagleBone 49/180 system will fail if other threads are also boosting their priority for other real-time tasks (as the highspeed ADC capturing process) •implement a DAC feeding system through Direct Memory Access (DMA): the benefits of this approach are huge: ◦transmission will be stable and regular because the bus will be acquired quickly for each DAC sample ◦it won’t impact the CPU because the processor doesn’t participate in the automatic exchanges. Note, however, that it will still have some little impact on the overall performance because it relies on using the common shared bus: if a CPU instruction requires accessing the memory (which is the most frequent operation) it may be delayed for a short time 3.4.6.1.5 Ping Pong buffer with EDMA The main target here is to implement the transmission of SPI data through a ping-pong DMA buffer providing a notification of when toggling occurs in order the client application to update the free buffer with the subsequent data. The implementation of this functionality has been quite complex (maybe the most complex part of the whole project). Due to my lack of knowledge on kernel drivers development I’ve used techniques which are not elegant and which result in a quite awkward patched code. But in any case the solution provided is functional and valid enough for the target of this project. These are some examples of things to improve in future releases: •I’ve used a real time SIGNAL (#define PLC_SIGNUM_APP_WARNING 44) to notify the client applications when a buffer underrun (aka underflow) occurs. The overhead entailed by signal exchanges between kernel-space-drivers and user-space-applications discourages its usage here. In fact, I changed the initial implementation that was sending a signal per buffer underrun because it frequently hung the whole system. I put a contention mechanism to send the signal once per second at the most, just to notify the client application that a problem occurred. Notice also the hard-coded #define to 44 that I’ve randomly chosen within the available range for real-time signals (from 33 to 64). This is a not recommended practice3 but is acceptable enough for the evaluation purposes of this project •For simplicity, I’ve used the debugging file system (debugfs) to carry out some normal exchanges between the client application and the kernel driver. Obviously another better system must be put in place because, as mentioned in the official documentation[24]: […] Debugfs is a simple to use RAM based file system especially designed for debugging purposes. Developers are encouraged to use debugfs instead of procfs in order to obtain some debugging information from their kernel code. Debugfs is quite flexible: it provides the possibility to set or get a single value with the help of just one line of code but the developer is also allowed to write its own read/write functions, and he can use the seq_file interface described in the procfs section. […] An intense refactoring of the source code for the SPI driver is therefore required. You can take a look at the enclosed source code for the whole patch. 3 To use a real-time SIGNAL for custom purposes it should be based on SIGRTMIN. More information can be obtained in the manual page for signals (man 7 signal) 50/180 Data communication through power lines using a system based on BeagleBone Just to have an idea, find following some key-points of the current implementation, mainly done in the spiomap2-mcspi.c file (identified as OMAP2 McSPI controller driver): DMA PING-PONG CONFIGURATION spi-omap2-mcspi.c [Original code] static void omap2_mcspi_tx_dma(struct spi_device *spi, struct spi_transfer *xfer, struct dma_slave_config cfg) { struct omap2_mcspi *mcspi; struct omap2_mcspi_dma *mcspi_dma; unsigned int count; mcspi = spi_master_get_devdata(spi->master); mcspi_dma = &mcspi->dma_channels[spi->chip_select]; count = xfer->len; if (mcspi_dma->dma_tx) { struct dma_async_tx_descriptor *tx; struct scatterlist sg; dmaengine_slave_config(mcspi_dma->dma_tx, &cfg); sg_init_table(&sg, 1); sg_dma_address(&sg) = xfer->tx_dma; sg_dma_len(&sg) = xfer->len; tx = dmaengine_prep_slave_sg(mcspi_dma->dma_tx, &sg, 1, DMA_MEM_TO_DEV, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (tx) { tx->callback = omap2_mcspi_tx_callback; tx->callback_param = spi; dmaengine_submit(tx); } else { /* FIXME: fall back to PIO? */ } } dma_async_issue_pending(mcspi_dma->dma_tx); omap2_mcspi_set_dma_req(spi, 0, 1); } spi-omap2-mcspi_plc.c [Patched code] static void omap2_mcspi_tx_configure_dma_ping_pong(struct spi_device *spi, struct dma_slave_config cfg) { struct omap2_mcspi *mcspi; struct omap2_mcspi_dma *mcspi_dma; mcspi = spi_master_get_devdata(spi->master); mcspi_dma = &mcspi->dma_channels[spi->chip_select]; dev_dbg(mcspi->dev, "omap2_mcspi_tx_configure_dma_ping_pong:init"); if (!mcspi_dma->ping_pong_enabled || !mcspi_dma->dma_tx) dev_err(mcspi->dev, "Ping pong not enabled!\n"); // [PLC] List of three items for an easy dual buffer implementation // An intem is required for the active PaRAM, the other two maintain the ping-pong link { struct dma_async_tx_descriptor *tx; struct scatterlist sg[3]; dmaengine_slave_config(mcspi_dma->dma_tx, &cfg); sg_init_table(sg, 3); sg_dma_address(&sg[0]) = mcspi_dma->ping_pong.buf1_dma; sg_dma_len(&sg[0]) = mcspi_dma->ping_pong.buf1_count*2; sg_dma_address(&sg[1]) = mcspi_dma->ping_pong.buf2_dma; sg_dma_len(&sg[1]) = mcspi_dma->ping_pong.buf2_count*2; sg_dma_address(&sg[2]) = mcspi_dma->ping_pong.buf1_dma; sg_dma_len(&sg[2]) = mcspi_dma->ping_pong.buf1_count*2; tx = dmaengine_prep_slave_sg(mcspi_dma->dma_tx, sg, 3, Data communication through power lines using a system based on BeagleBone 51/180 DMA_MEM_TO_DEV, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (tx) { mcspi_dma->ping_pong.cur_buffer_in_dma_index = 0; tx->callback = omap2_mcspi_tx_callback; tx->callback_param = spi; dmaengine_submit(tx); } else { /* FIXME: fall back to PIO? */ } } dma_async_issue_pending(mcspi_dma->dma_tx); omap2_mcspi_set_dma_req(spi, 0, 1); dev_dbg(mcspi->dev, "omap2_mcspi_tx_configure_dma_ping_pong:end"); } In the above code we can see how I have chained DMA addresses using the PaRAM for a ping-pong buffer: DMA uses first ping_pong.buf1_dma, then automatically switches to ping_pong.buf2_dma and finally it switches to ping_pong.buf1_dma again. The edma.c file (identified as TI EDMA DMA engine driver) has also been required to be modified. For example you can take a look at the edma_execute function (among other changes): edma.c [Original code] static void edma_execute(struct edma_chan *echan) { struct virt_dma_desc *vdesc = vchan_next_desc(&echan->vchan); struct edma_desc *edesc; ... /* Write descriptor PaRAM set(s) */ for (i = 0; i < edesc->pset_nr; i++) { ... /* Link to the previous slot if not the last set */ if (i != (edesc->pset_nr - 1)) edma_link(echan->slot[i], echan->slot[i+1]); /* Final pset links to the dummy pset */ else edma_link(echan->slot[i], echan->ecc->dummy_slot); } edma_start(echan->ch_num); } edma_plc.c [Patched code] static void edma_execute(struct edma_chan *echan) { struct virt_dma_desc *vdesc = vchan_next_desc(&echan->vchan); struct edma_desc *edesc; ... /* Write descriptor PaRAM set(s) */ for (i = 0; i < edesc->pset_nr; i++) { ... // [PLC] DMA linking on channel CHANNEL_SPITX if (echan->ch_num == CHANNEL_SPITX) { // Single buffer mode if (edesc->pset_nr == 1) { edma_link(echan->slot[i], echan->ecc->dummy_slot); // Continuous mode } else if (edesc->pset_nr == 2) { if (i == 0) edma_link(echan->slot[0], echan->slot[1]); else edma_link(echan->slot[1], echan->slot[1]); // Circular buffers with PaRAM[0] being the active one } else if (edesc->pset_nr == 3) { if (i == 2) edma_link(echan->slot[i], echan->slot[1]); else 52/180 Data communication through power lines using a system based on BeagleBone edma_link(echan->slot[i], echan->slot[i+1]); } else { dev_err(echan->vchan.chan.device->dev, "Unexpected DMA data"); } } else { /* Link to the previous slot if not the last set */ if (i != (edesc->pset_nr - 1)) edma_link(echan->slot[i], echan->slot[i+1]); /* Final pset links to the dummy pset */ else edma_link(echan->slot[i], echan->ecc->dummy_slot); } } edma_start(echan->ch_num); } For more information about EDMA and PaRAM management consult the pages 1538 and 1542 of the AM335x Technical Guide[10], within the chapter 11.3.3.2 EDMA3 Channel PaRAM Set Entry Fields. BUFFER UNDERRUN NOTIFICATION WITH FREQUENCY CONTENTION spi-omap2-mcspi_plc.c static void omap2_mcspi_plc_send_warning_signal(struct device *dev, struct task_struct *app_task) { struct siginfo info; int ret; memset(&info, 0, sizeof(struct siginfo)); info.si_signo = PLC_SIGNUM_APP_WARNING; info.si_code = SI_QUEUE; info.si_int = 1234; ret = send_sig_info(PLC_SIGNUM_APP_WARNING, &info, app_task); if (ret < 0) { dev_err(dev, "error sending signal\n"); return; } } static void omap2_mcspi_tx_callback(void *data) { struct spi_device *spi = data; struct omap2_mcspi *mcspi = spi_master_get_devdata(spi->master); struct omap2_mcspi_dma *mcspi_dma = &mcspi->dma_channels[spi->chip_select]; // [PLC] Send signals if (mcspi_dma->ping_pong_enabled) { // TODO: Improve access to 'dma_buffer_waiting'. Locking required? if (mcspi_dma->ping_pong.check_missed_dma_buffer && (mcspi_dma->ping_pong.dma_buffer_waiting == 0)) { u64 stamp = jiffies; if (stamp > next_warning_stamp) { next_warning_stamp = stamp+usecs_to_jiffies(WARNING_CONTENTION_US); omap2_mcspi_plc_send_warning_signal(&spi->dev, mcspi_dma->app_task); } } mcspi_dma->ping_pong.cur_buffer_in_dma_index = (mcspi_dma->ping_pong.cur_buffer_in_dma_index+1) & 0x1; complete(&mcspi_dma->dma_tx_completion); } else if (mcspi_dma->stop_dma_after_tx && !mcspi_dma->dma_completion_notified) { mcspi_dma->dma_tx_in_progress = 0; complete(&mcspi_dma->dma_tx_completion); /* We must disable the DMA TX request */ omap2_mcspi_set_dma_req(spi, 0, 0); } } In the code of the omap2_mcspi_tx_callback we can see how the signal PLC_SIGNUM_APP_WARNING is triggered when the mcspi_dma->ping_pong.dma_buffer_waiting is equal to 0 indicating that the client application is not waiting for the DMA buffer yet, probably because it is still busy processing the previous Data communication through power lines using a system based on BeagleBone 53/180 buffer. If so, this would mean a buffer underrun condition (i.e. DMA dispatches data faster than the client application is able to fill) and hence, the SIGNAL notification. EXCHANGES THROUGH ‘DEBUGFS’ TO NOTIFY PING-PONG TOGGLING spi-omap2-mcspi_plc.c #define DEBUGFS_IOC_MAGIC 'd' #define DEBUGFS_IOC_RD_WAIT_DMA_BUFFER _IOR(DEBUGFS_IOC_MAGIC, 1, __u8) static long debugfs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { int err = 0; int retval = 0; struct omap2_mcspi *mcspi = spi_master_get_devdata(spi_master_global); struct omap2_mcspi_dma *mcspi_dma = &mcspi->dma_channels[chip_select_global]; /* Check type and command number */ if (_IOC_TYPE(cmd) != DEBUGFS_IOC_MAGIC) return -ENOTTY; /* Check access direction once here; don't repeat below. * IOC_DIR is from the user perspective, while access_ok is * from the kernel perspective; so they look reversed. */ if (_IOC_DIR(cmd) & _IOC_READ) err = !access_ok(VERIFY_WRITE, (void __user *)arg, _IOC_SIZE(cmd)); if (err == 0 && _IOC_DIR(cmd) & _IOC_WRITE) err = !access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd)); if (err) return -EFAULT; switch (cmd) { /* read requests */ case DEBUGFS_IOC_RD_WAIT_DMA_BUFFER: // TODO: Improve to notify an idle or aborted DMA transfer instead of // just sending a hard-coded zero or a partially transmitted buffer if (!mcspi_dma->dma_tx_in_progress) { retval = __put_user(0, (__u8 __user *)arg); break; } mcspi_dma->ping_pong.dma_buffer_waiting = 1; init_completion(&mcspi_dma->dma_tx_completion); wait_for_completion(&mcspi_dma->dma_tx_completion); mcspi_dma->ping_pong.dma_buffer_waiting = 0; retval = __put_user(mcspi_dma->ping_pong.cur_buffer_in_dma_index, (__u8 __user *)arg); break; } return retval; } In the debugfs_ioctl there is an example of how I’ve used the debugfs to implement the synchronization with the Ping Pong buffer. 3.4.6.1.6 Analysis The results of the data transmission using the Ping-Pong DMA buffer demonstrates the importance of this implementation. When using it, the output waves are stable even if the CPU is switching among other tasks in the background (we’ll see some graphs about in the chapter 3.4.6.2 adc-driver). In fact, the wave generation continues to run even if the BBB freezes (due to the standalone working mode of the DMA). But the source code must still be optimized: the signal PLC_SIGNUM_APP_WARNING, notifying about buffer underrun conditions, is sometimes fired, specially when using high SPI bit rates. An easy way to improve it may be through the use of larger DMA buffers for example (now limited by the page size = 4096 bytes, for implementation simplicity). 54/180 Data communication through power lines using a system based on BeagleBone 3.4.6.1.7 Effective DAC frequency The tests done to validate the SPI functionality show that there is an extra gap between samples of about half a clock cycle. In fact, this gap is configurable through the TCS field of the CF0CONF register, being 0.5 clock cycles the minimum value, as described in this capture from the AM335x Technical Manual[10] at page 4838: Figure 18. Chip-Select timing control For this project we need to accurately know the DAC sampling rate because the application requires it to produce an output signal of a given frequency. For medium bit rates we have confirmed with the oscilloscope that the DAC sampling frequency is equal to “SPI_Bit_Rate/10.5”. But for higher frequencies we observe an unexpected slippage which increases with the bitrate. By analyzing the involved signals, we can observe that the cause of this deviation is the fixed width of the Chip Select toggling pulse, negligible at low bit rates, but significant at high ones. The following captures show the signals SCLK (in blue) and CSN (in red) at different capturing rates: Figure 19. SCLK (blue) and CSN (red) at SPI bitrate = 375kbps At low SPI rates the width of the CSN pulse is negligible. Data communication through power lines using a system based on BeagleBone 55/180 Figure 20. SCLK (blue) and CSN (red) at SPI bitrate = 1500kbps At 1.5Mbps: •SCLK cycle = 1/1.5E6 = 667ns •Expected gap between words (from falling to rising SCLK) = ½ cycle due to usual clock toggling rate + ½ extra cycle due to TCS = 1 full SCLK cycle = 667ns •Measured gap from falling to rising SCLK edges = 834ns •Difference = 834ns-667ns = 167ns So, there is a noticeable extra gap due to the CSN pulse Figure 21. SCLK (blue) and CSN (red) at SPI bitrate = 3000kbps At 3Mbps: •SCLK cycle = 1/3.0E6 = 333 ns •Expected falling-to-rising-edges = 1 SCLK cycle = 333ns •Measured gap = 480ns •Difference = 480-333 = 147ns At 3Mbps the difference has a similar value in absolute terms which means a higher deviation in relative terms. 56/180 Data communication through power lines using a system based on BeagleBone Figure 22. SCLK (blue) and CSN (red) at SPI bitrate = 6000kbps At 6Mbps: •SCLK cycle = 1/6.0E6 = 167 ns •Expected falling-to-rising-edges = 1 SCLK cycle = 167ns •Measured gap = 335ns •Difference = 335-167 = 168ns At 6Mbps the measured gap doubles the expected one. The captures of the CSN seem to indicate a pulse width close to 160ns: Figure 23. Width of the CSN pulse measured at 3000 kbps In the above capture, the CSN pulse exposes an oscillating smooth shape rather than the expected squared form. This is due to the bandwidth limitation of the USB oscilloscope and the interpolation algorithm applied. For maximum accuracy the following process has been used to find the exact formula that converts bit rates (bits per second) to sampling rates (samples per second): 1. With the plc-cape-lab application a sinusoid of 2kHz has been generated and captured with the oscilloscope 2. Initially, low bit rates have been tested confirming the 0.5-clock-cycle-extra-gap and the corresponding basic formula, f[sps] = bps/10.5 Data communication through power lines using a system based on BeagleBone 57/180 3. Then, higher bit rates have been tested. As expected, the resulting frequency, measured with the oscilloscope, is then smaller than the 2kHz because the effect of the CSN width. Octave has also been used to measure the effective frequency by locating the peak of [Abs(FFT)] 4. The 160ns-CSN-pulse factor has been included into the formula and checked again with much better results but with still some little deviation 5. The CSN-pulse-width factor has then been tuned until found the one giving the best results at high bit rates. The best matching occurred for a CSN width of 165ns So the formula to convert from bit-rate to sample-rate has finally resulted in: freq_DAC [samples per second]=1 10.5 SPI rate in bits per second +165∗10−9 Or in source-code terms: freq_dac_sps = 1.0/(10.5/(float)settings->tx.freq_bps+165e-9); 64/180 Data communication through power lines using a system based on BeagleBone 0.4mV per ADC unit (1.65/4096). The captured graph covers 600 ADC units (between 800 and 1400) which are equivalent to 600*0.4mV = 240mVpp. Note that the ramp-wave expands over a lot of frequencies (many FFT peaks) because the asymmetry of the signal. It we use a symmetric triangular-wave instead, that’s what we get: Figure 28. ADC capture of a triangular wave With all these tests we have confirmed that the patched ADC driver is properly working at 200ksps. Next series of tests will explore the behavior of the ADC at the frequencies we need to use in this project, which are over the maximum supported. Data communication through power lines using a system based on BeagleBone 65/180 Test with a sinusoid of 80kHz: Figure 29. ADC capture of a sinusoid of 80kHz Note that in the captured image in the top it’s difficult to identify the sinusoid shape. That’s because we are using only 2.5 samples per cycle (200k/80k). The FFT, however, clearly exposes the sinusoidal behavior at the 80kHz (peak at index 80). Repeating the test over 90kHz results in this: Figure 30. ADC capture of a sinusoid of 90kHz We have now 2,22 samples per cycle (200k/90k). 66/180 Data communication through power lines using a system based on BeagleBone Finally, find following the result of increasing the frequency to 100kHz, 110kHz and 120kHz: Frequency = 100 kHz Figure 31. ADC capture of a sinusoid of 100kHz Frequency = 110 kHz Figure 32. ADC capture of a sinusoid of 110kHz Data communication through power lines using a system based on BeagleBone 67/180 Frequency = 120 kHz Figure 33. ADC capture of a sinusoid of 120kHz The point to mention here is that when increasing the generated frequency over the capturing rate (Nyquist frequency5 = half of the sampling rate = 100kHz), the ADC captures decreasing frequencies. For a generated wave of 110k we have the same results as for 90kHz. And in 120kHz the same as in the 80kHz case. That’s due to the undersampling theory6. For the feasibility tests done in this project it doesn’t pose a big problem (as we’ll seen in 4 Analysis & results) because the AFE031 filters out the frequency content out of the band of interest (CENELEC A or B/C/D) and because our tests are based on just one carrier. But we should have this limitation in mind. Note that the CENELEC B/C/D band (95kHz to 125kHz as mentioned in Table 4. CENELEC bands) falls in the middle of the capturing frequency (=100kHz). When using modulation schemes that extend over all the band, the captured signal would be a mix that couldn’t be decoded. A possible solution to that could be selecting another capturing ADC rate allowing to have the correct replica over all the band. This ends the chapter dedicated to drivers and kernel-space. From now on we’ll lie in user-space. 5 Some notes about in https://en.wikipedia.org/wiki/Nyquist_frequency 6 Basic information on Undersampling theory in https://en.wikipedia.org/wiki/Undersampling 68/180 Data communication through power lines using a system based on BeagleBone 3.5 Static libraries 3.5.1 Overview Static libraries are a convenient and comfortable way of reusing source code. The result of a static library is a *.a file with the executable code. Developers that want to use a library must know the publicly exported symbols (functions or variables). The encapsulation of reusable code in libraries (versus cloning source code everywhere) has the following benefits: •Having the shared code located in one single place simplifies the maintenance: bug fixing or improvements need to be done just in one single place •When the source code of a static library is updated, the dependent projects need to be just re-linked which is a faster process than recompiling To simplify maintenance, all the public symbols offered by a library are declared in headers (*.h) in a subfolder called api (from Application Programming Interface). The api sub-directory strategy has these goals: •for the consumers of libraries, it simplifies the task of discovering the functionality offered by a library because all the public declarations are located in one well-known easily accessible point •for the developers of libraries, it points out that a function has been declared as public and, therefore, shouldn’t be modified in a backwards incompatibility way 3.5.2 Libraries developed For this project these libraries have been defined: Name Source code Brief description libplc-tools ./libraries/libplc-tools Generic functionality to be reused by any plc-cape-based component. libplc-gpio ./libraries/libplc-gpio GPIO helpful extra functionality. libplc-adc ./libraries/libplc-adc ADC functionality provided by the plc-cape modified ADC driver. libplc-cape ./libraries/libplc-cape Encapsulation of the PlcCape board functionality. Table 13. Static libraries developed Next sections will provide a brief description of each library and an extract of the public API offered (from the headers in the api folder). This is a good means of having an idea about the main available functionality. I’ve removed the Doxygen’s comments to present this information in a more compact format. Figure 34. Libraries tree Data communication through power lines using a system based on BeagleBone 69/180 3.5.2.1 libplc-tools Target libplc-tools.a Purpose This library offers generic functionality to be used by any project belonging to the plc-cape framework Details This library relies only on functionality provided by the Linux Operating system. Therefore, it could be used in other Linux-based platforms besides the BeagleBone Black platform This version of the library covers these areas: •application: Helper functions related to the management of applications. •file: Generic file functionality as writing data in Octave-compatible format. •plugin: Helper functions related to the plugin management. •terminal_io: Extended input/output functionality in terminal consoles, as checking for key pressing in non-blocking mode. •time: Time measurement facilities. •trace: Tracing helper functions. Dependencies librt: for some time-measurement functions API help ./libraries/libplc-tools/api Source code ./libraries/libplc-tools Extract of the provided API: application.h char *plc_application_get_abs_path(void); char *plc_application_get_abs_dir(void); char *plc_application_get_output_abs_dir(void); file.h void plc_file_write_string(const char *base_path, const char *rel_path, const char *value); int plc_file_write_csv(const char *filename, enum csv_type_enum csv_type_enum, void *buffer, ... plugin.h char *plc_plugin_get_abs_path(enum plc_plugin_category category, const char *plugin_name); struct plc_plugin_list *plc_plugin_list_create(enum plc_plugin_category category); void plc_plugin_list_release(struct plc_plugin_list *plc_plugin_list); int plc_plugin_list_find_name(struct plc_plugin_list *plc_plugin_list, const char *plugin_name); terminal_io.h struct plc_terminal_io *plc_terminal_io_create(void); void plc_terminal_io_release(struct plc_terminal_io *plc_terminal_io); int plc_terminal_io_kbhit(struct plc_terminal_io *plc_terminal_io); int plc_terminal_io_getchar(struct plc_terminal_io *plc_terminal_io); time.h uint32_t plc_time_get_tick_ms(void); struct timespec plc_time_get_hires_stamp(void); uint32_t plc_time_hires_interval_to_usec(struct timespec t1, struct timespec t2); 70/180 Data communication through power lines using a system based on BeagleBone 3.5.2.2 libplc-gpio Target libplc-gpio.a Purpose It encapsulates some useful GPIO extended functionality like callbacks-on- toggling. Details This library doesn't rely on the PlcCape board but only on the BBB It implements two sets of functions to access the GPIO: •using the standard file system '/sys/class/gpio/...' ◦pros: encapsulates the access to 'gpio' through a driver. This allows a better use of shared resources. For example if a GPIO pin is already used, a cape could automatically (or manually through jumper) use a different one •using direct access to memory ◦pros: optimum performance because not intermediate wrappers ◦cons: requires 'root' access Dependencies pthread: some gpio functions spawn new threads libplc-tools: used to get some information from device-based files API help ./libraries/libplc-gpio/api Source code ./libraries/libplc-gpio Extract of the provided API: gpio.h void plc_gpio_set_soft_emulation(int soft_emulation); struct plc_gpio; struct plc_gpio *plc_gpio_create(void); void plc_gpio_release(struct plc_gpio *plc_gpio); struct plc_gpio_pin_out; struct plc_gpio_pin_out *plc_gpio_pin_out_create(struct plc_gpio *plc_gpio, uint32_t pin_bank, uint32_t pin_mask); void plc_gpio_pin_out_release(struct plc_gpio_pin_out *plc_gpio_pin_out); void plc_gpio_pin_out_set(struct plc_gpio_pin_out *plc_gpio_pin_out, int on); void plc_gpio_pin_out_toggle(struct plc_gpio_pin_out *plc_gpio_pin_out); struct plc_gpio_pin_in; struct plc_gpio_pin_in *plc_gpio_pin_in_create(struct plc_gpio *plc_gpio, uint32_t pin_bank, uint32_t pin_mask); void plc_gpio_pin_in_release(struct plc_gpio_pin_in *plc_gpio_pin_in); int plc_gpio_pin_in_get(struct plc_gpio_pin_in *plc_gpio_pin_in); struct plc_gpio_sysfs_pin; struct plc_gpio_sysfs_pin *plc_gpio_sysfs_pin_create(uint32_t gpio_number, int output); void plc_gpio_sysfs_pin_release(struct plc_gpio_sysfs_pin *plc_gpio_sysfs_pin); int plc_gpio_sysfs_pin_get(struct plc_gpio_sysfs_pin *plc_gpio_sysfs_pin); void plc_gpio_sysfs_pin_set(struct plc_gpio_sysfs_pin *plc_gpio_sysfs_pin, int on); void plc_gpio_sysfs_pin_callback(struct plc_gpio_sysfs_pin *plc_gpio_sysfs_pin, void (*callback)(void *data, int flag_status), void *data); Data communication through power lines using a system based on BeagleBone 71/180 3.5.2.3 libplc-adc Target libplc-adc.a Purpose Provides comfortable access to the high speed capturing system based on the modified ADC driver Details The functionality offered doesn't depend on the PlcCape but only on the BBB. Thus, it can be used directly on an isolated BBB or with others capes Dependencies libplc-tools: time functions used API help ./libraries/libplc-adc/api Source code ./libraries/libplc-adc Extract of the provided API: adc.h typedef void (*rx_buffer_completed_callback_t)( void *data, sample_rx_t *samples_buffer, uint32_t samples_buffer_count); float plc_adc_get_sampling_frequency(void); struct plc_adc *plc_adc_create(int plc_driver); void plc_adc_release(struct plc_adc *plc_adc); void plc_adc_set_rx_buffer_completed_callback(struct plc_adc *plc_adc, rx_buffer_completed_callback_t rx_buffer_completed_callback, void *rx_buffer_completed_callback_data); sample_rx_t plc_adc_read_sample(struct plc_adc *plc_adc); void plc_adc_start_capture(struct plc_adc *plc_adc, uint32_t buffer_samples, int kernel_buffering); void plc_adc_stop_capture(struct plc_adc *plc_adc); analysis.h struct rx_statistics { uint32_t buffers_handled; uint32_t buffer_preparation_us; uint32_t buffer_preparation_min_us; uint32_t buffer_preparation_max_us; uint32_t buffer_cycle_us; uint32_t buffer_cycle_min_us; uint32_t buffer_cycle_max_us; sample_rx_t buffer_min; sample_rx_t buffer_max; float buffer_dc_mean; float buffer_ac_mean; }; struct plc_rx_analysis *plc_rx_analysis_create(void); void plc_rx_analysis_release(struct plc_rx_analysis *plc_rx_analysis); void plc_rx_analysis_configure(struct plc_rx_analysis *plc_rx_analysis, float freq_adc_sps, uint32_t data_bit_us, sample_rx_t data_offset, sample_rx_t data_hi_threshold_detection); void plc_rx_analysis_reset(struct plc_rx_analysis *plc_rx_analysis); void plc_rx_analysis_set_statistics_mode(struct plc_rx_analysis *plc_rx_analysis, enum plc_rx_statistics_mode mode); ATTR_EXTERN int plc_rx_analysis_analyze_buffer(struct plc_rx_analysis *plc_rx_analysis, sample_rx_t *buffer, uint32_t buffer_samples); 84 const struct rx_statistics *plc_rx_analysis_get_statistics(struct plc_rx_analysis *plc_rx_analysis); 72/180 Data communication through power lines using a system based on BeagleBone 3.5.2.4 libplc-cape Target libplc-cape.a Purpose It encapsulates the low-level access to the PlcCape board providing a high-level API for interacting with Details Dependencies API help ./libraries/libplc-cape/api Source code ./libraries/libplc-cape Extract of the provided API: cape.h struct plc_cape *plc_cape_create(int plc_driver); void plc_cape_release(struct plc_cape *plc_cape); struct plc_afe *plc_cape_get_afe(struct plc_cape *plc_cape); struct plc_leds *plc_cape_get_leds(struct plc_cape *plc_cape); afe.h void plc_afe_configure(struct plc_afe *plc_afe, const struct afe_settings *settings); char *plc_afe_get_info(struct plc_afe *plc_afe); void plc_afe_set_flags_callback(struct plc_afe *plc_afe, void (*callback)(void *data, int tx_flag, int rx_flag, int ok_flag), void *data); void plc_afe_set_standy(struct plc_afe *plc_afe, int standby); void plc_afe_activate_blocks(struct plc_afe *plc_afe, enum afe_block_enum blocks); void plc_afe_set_calibration_mode(struct plc_afe *plc_afe, enum afe_calibration_enum calibration_mode); void plc_afe_set_gain_tx(struct plc_afe *plc_afe, enum afe_gain_tx_pga_enum gain); void plc_afe_set_gains_rx(struct plc_afe *plc_afe, enum afe_gain_rx_pga1_enum gain1, enum afe_gain_rx_pga2_enum gain2); void plc_afe_disable_all(struct plc_afe *plc_afe); void plc_afe_clear_overloads(struct plc_afe *plc_afe); uint8_t plc_afe_get_overloads(struct plc_afe *plc_afe); void plc_afe_configure_spi(struct plc_afe *plc_afe, uint32_t spi_dac_freq, uint16_t spi_dac_delay); void plc_afe_set_dac_mode(struct plc_afe *plc_afe, int enable); void plc_afe_transfer_dac_sample(struct plc_afe *plc_afe, uint16_t sample); leds.h void plc_leds_toggle_app_activity(struct plc_leds *plc_leds); void plc_leds_set_app_activity(struct plc_leds *plc_leds, int on); void plc_leds_set_tx_activity(struct plc_leds *plc_leds, int on); void plc_leds_set_rx_activity(struct plc_leds *plc_leds, int on); tx.h struct plc_tx *plc_tx_create(tx_fill_cycle_callback_t tx_fill_cycle_callback, tx_fill_cycle_callback_h tx_fill_cycle_callback_handle, tx_on_buffer_sent_callback_t tx_on_buffer_sent_callback, tx_on_buffer_sent_callback_h tx_on_buffer_sent_callback_handle, enum spi_tx_mode_enum tx_mode, uint32_t tx_buffers_len, struct plc_afe *plc_afe); const struct tx_statistics *tx_get_tx_statistics(struct plc_tx *plc_tx); void plc_tx_release(struct plc_tx *plc_tx); void plc_tx_fill_buffer_iteration(struct plc_tx *plc_tx, uint16_t *buffer, uint32_t buffer_samples); void plc_tx_start_transmission(struct plc_tx *plc_tx); void plc_tx_stop_transmission(struct plc_tx *plc_tx); Data communication through power lines using a system based on BeagleBone 73/180 3.6 Plugins 3.6.1 Overview Plugins are a kind of dynamic libraries that can be loaded on-demand. Like static libraries, plugins are a convenient way of reusing code. The file with the executable code has the extension *.so. The main differences with static libraries are: •instead of being embedded at the linking stage (case of static libraries) the plugins are loaded at run-time •the address of the plugin-exported functions must be found via the standard libdl library. Functions are retrieved by their name. The suitability of the parameters is not checked. Thus, special care must be taken to avoid compatibility problems. Moreover, incompatible evolutions of public functions may result in old-applications to crash (until adapted to the new interfaces). Note that, by contrast, compatibility problems are easily detected at compile-time when using static libraries •a positive side effect of dynamic libraries (in contrast to static libraries) is that if a bug is fixed in the *.so, all the applications relying on it will automatically use the fix, with no rebuilding involved For maintenance purposes and to guarantee compatibility these rules need to be followed: •plugins are grouped into categories. Each category defines the exact API that plugins belonging to must satisfy •when an API is officially released, exported methods become immutable: they cannot be removed nor modified (either in name, arguments or behavior). The only safe operation in future releases is to add new methods 3.6.2 Categories Plugins are divided in categories depending on the target function: Category Public API Source code Brief description Encoders encoder_api ./plugins/encoder Generate RAW samples to feed a DAC from input data or given settings. Decoders decoder_api ./plugins/decoder Generate output data from RAW samples coming from an ADC. User Interfaces ui_api ./plugins/ui Implement a specific user interface mechanism. Table 14. Plugin categories Figure 35. Plugins tree 80/180 Data communication through power lines using a system based on BeagleBone 3.6.3 Plugins developed For this project these plugins have been developed: ENCODERS Name Source code Brief description encoder-wave ./plugins/encoder/encoder-wave Typical waves generator. encoder-pwm ./plugins/encoder/encoder-pwm Basic PWM modulator. encoder-ook ./plugins/encoder/encoder-ook Basic modulator of data in OOK codifications. Table 15. Plugins developed within the 'encoder' category DECODERS Name Source code Brief description decoder-pwm ./plugins/decoder/decoder-pwm Basic demodulator of data in PWM codifications. decoder-ook ./plugins/decoder/decoder-ook Basic demodulator of data in OOK codifications. Table 16. Plugins developed within the 'decoder' category USER INTERFACES Plugin Source code Brief description ui-ncurses ./plugins/ui/ui-ncurses Basic UI plugin based on the ncurses package. ui-console ./plugins/ui/ui-console Basic UI plugin with the classical console look and feel. Table 17. Plugins developed within the 'user interface' category All these plugins are in an early development stage. They aren’t optimized but are good-enough to test the feasibility of the whole system. In particular encoders and decoders should be optimized for computational efficiency and use better modulation/demodulation algorithms for reinforced robustness and protection against interferences, noise, attenuation, etc. In the following sections a brief description of all the plugins implemented for this project will be given. Fragments of the source code in the core functions will also be included because it can give a quick idea of what’s implemented and the complexity around. For encoders the core function is: prepare_next_samples For decoder the core function is: parse_next_samples In User Interfaces there is not a single core function, so, just basic concepts will be introduced. For additional info refer to the source code. Data communication through power lines using a system based on BeagleBone 81/180 3.6.3.1 encoder-wave Target encoder-wave.so Purpose Generator of typical waves: sinusoids, ramps, constant values, ... Details Encodings supported: •Sinuosoid •Ramps •Triangular waves •... Source code ./plugins/encoder/encoder-wave This plugin generates the raw samples of the typical waves depending on the settings provided. Stream type Output constant Fills the output buffer with just a constant value freq_max Fills the output buffer with alternating values between min and max. It produces a signal with the maximum frequency the DAC can generate, which is freq_dac_sps/2 (Nyquist frequency) freq_max_div2 Fills the output buffer with the repetitive pattern [0, max_value, 0, min_value, 0, max_value…]. This is a computational efficient way of generating an output frequency equivalent to freq_dac_sps/4. sinus Fills the output buffer with a configurable sinusoid ramp Fills the output buffer with a ramp triangular Fills the output buffer with a triangular wave stream_file Fills the output buffer with the samples read from a file. The file is restarted to repetitively fill the output buffer bit_padding_per_ cycle Fills the output buffer by introducing 1-bit after each DAC sample. In other words, this repetitive pattern is followed: [0x1, 0x3, 0x7, 0x15… 0x3FF, 0x1…]. It can be helpful for testing purposis freq_sweep Generates a sinusoid with a frequency which varies in time am_modulation Generates a sinusoid with an amplitude which varies in time Table 18. Type of waves generated by the 'encoder-wave' plugin 82/180 Data communication through power lines using a system based on BeagleBone This is a fragment of the main function in the plugin in charge of generating the raw data: plugins/encoder/encoder-wave/encoder-wave.c void encoder_prepare_next_samples(struct encoder *encoder, sample_tx_t *buffer, uint32_t buffer_count) { switch (encoder->settings.stream_type) { case stream_ramp: for (i = 0; i < buffer_count; i++, encoder->stream_ramp.value_last += encoder->stream_ramp.value_delta) { if (encoder->stream_ramp.value_last >= encoder->stream_ramp.value_max) encoder->stream_ramp.value_last -= encoder->settings.range; buffer[i] = (sample_tx_t) round(encoder->stream_ramp.value_last); } break; ... case stream_constant: for (i = 0; i < buffer_count; i++) buffer[i] = encoder->settings.offset; break; case stream_freq_max: { int nMin = encoder->settings.offset - encoder->settings.range / 2 + 1; int nMax = encoder->settings.offset + encoder->settings.range / 2 - 1; for (i = 0; i < buffer_count; i++) buffer[i] = (i % 2) ? nMin : nMax; break; } case stream_freq_sinus: { float amp = (encoder->settings.range - 1) / 2; float freq = 2.0 * M_PI * (float) encoder->settings.freq / encoder->freq_dac_sps; for (i = 0; i < buffer_count; i++, encoder->counter++) buffer[i] = (sample_tx_t) round( (float) encoder->settings.offset + amp * sin(freq * encoder->counter)); break; } ... } Data communication through power lines using a system based on BeagleBone 83/180 3.6.3.2 encoder-pwm Target encoder-pwm.so Purpose Encodes data in a simple Pulse Width Modulation codification Details Configurable settings •us_per_bit •guard_time Source code ./plugins/encoder/encoder-pwm The encoder-pwm plugin generates a sinusoidal carrier of configurable frequency with duration proportional to the value of the incoming data. To check it, we can use the plc-cape-lab tool with the following parameters: •AFE mode = calib_dac_txpga •SPI bitrate = 1.5Mbps •Carrier freq = 1kHz, DC Offset=800, AC Range=400 •Store to file = 20000 samples •Msg to encode = ~Hi! This message incorporates 4 characters distributed among the ASCII code in a way we can appreciate the PWM encoding implementation. Figure 36. Example of PWM-encoded message We can see in the top, in dark green, the ASCII codes of the characters sent, and in the bottom, in dark red, the corresponding characters. 84/180 Data communication through power lines using a system based on BeagleBone This is the main routine in charge of composing the encoded data: plugins/encoder/encoder-pwm/encoder-pwm.c void encoder_prepare_next_samples(struct encoder *encoder, sample_tx_t *buffer, uint32_t buffer_count) { int i; for (i = 0; i < buffer_count; i++) { if (encoder->guard_samples == 0) { buffer[i] = (sample_tx_t) round( encoder->settings.offset + encoder->amp * sin(encoder->freq * (encoder->pwm_counter++))); if (encoder->pwm_counter == encoder->pwm_next) encoder->guard_samples = GUARD_SAMPLES; } else { buffer[i] = (sample_tx_t) round(encoder->settings.offset); if (!encoder->message_end_reached) { encoder->guard_samples--; if (encoder->guard_samples == 0) { encoder->pwm_counter = 0; if (encoder->message_index == encoder->message_length) { encoder->message_index = 0; if (!encoder->settings.loop_message) { encoder->message_end_reached = 1; encoder->guard_samples = (uint16_t) -1; } } encoder->pwm_next = round( encoder->samples_per_bit * encoder->settings.message[encoder->message_index++]); } } } } } Data communication through power lines using a system based on BeagleBone 85/180 3.6.3.3 decoder-pwm Target decoder-pwm.so Purpose Decodes data from a simple Pulse Width Modulation codification Details Configurable settings •us_per_bit •guard_time Source code ./plugins/decoder/decoder-pwm This plugin decodes PWM-encoded data. It’s the dual of the encoder-pwm plugin. This is the main function in charge of the decoding: plugins/decoder/decoder-pwm/decoder-pwm.c uint32_t decoder_parse_next_samples(struct decoder *decoder, const sample_rx_t *buffer_in, uint8_t *buffer_data_out, uint32_t buffer_data_out_count) { uint8_t *buffer_data_out_ini = buffer_data_out; const sample_rx_t *buffer_in_end = buffer_in + decoder->chunk_samples; for (; buffer_in < buffer_in_end; buffer_in++) { int hi_level_detected = (abs((int16_t) *buffer_in - (int16_t) decoder->offset) >= decoder->carrier_threshold); if (decoder->samples_with_carrier == 0) { if (hi_level_detected) decoder->samples_with_carrier++; } else { decoder->samples_with_carrier++; if (hi_level_detected) { // Whenever carrier detected reset the 'samples_without_carrier' counter decoder->samples_without_carrier = 0; } else { if (++decoder->samples_without_carrier >= decoder->stop_samples) { // Reject the spurius if (decoder->samples_with_carrier < round(decoder->samples_per_bit / 2.0)) { decoder->samples_with_carrier = 0; decoder->samples_without_carrier = 0; } else { // Adjust removing the stop-samples extra-counting decoder->samples_with_carrier -= decoder->stop_samples; *buffer_data_out++ = (uint8_t) round( decoder->samples_with_carrier / decoder->samples_per_bit); decoder->samples_with_carrier = 0; decoder->samples_without_carrier = 0; } } } } } return buffer_data_out - buffer_data_out_ini; } 86/180 Data communication through power lines using a system based on BeagleBone 3.6.3.4 encoder-ook Target encoder-ook.so Purpose Encodes data in a simple On-Off-Keying codification Encodes data in a simple On-Off-Keying codification Details Source code ./plugins/encoder/encoder-ook For the analysis in this project I’ve basically used the PWM encoding (encoder-pwm and decoder-pwm plugins) because it’s very simple to identify in the oscilloscope captures. However, a basic OOK modulation has also been provided to prove the adaptability of the framework to other codifications. The core implementation is quite simple: a carrier is generated or not depending on each bit to be sent. A start bit is also required to delimit each character (like typical UARTs7). plugins/encoder/encoder-ook/encoder-ook.c void encoder_prepare_next_samples(struct encoder *encoder, sample_tx_t *buffer, uint32_t buffer_count) { int i; for (i = 0; i < buffer_count; i++) { if ((encoder->guard_bits == 0) && ((encoder->bit_index == 0xFF) || ((encoder->settings.message[encoder->message_index] << encoder->bit_index) & 0x80))) { buffer[i] = (sample_tx_t) round( encoder->settings.offset + encoder->amp * sin( encoder->freq * (encoder->counter - encoder->counter_bit))); } else { buffer[i] = (sample_tx_t) round(encoder->settings.offset); } encoder->counter++; if ((encoder->counter % encoder->samples_per_bit) == 0) { if (encoder->guard_bits > 0) { encoder->guard_bits--; } else { if (++encoder->bit_index == 8) { encoder->guard_bits = GUARD_BITS; encoder->bit_index = 0xFF; // -1 because the '\0' ending if (++encoder->message_index == encoder->message_length) encoder->message_index = 0; } // 'encoder->counter' to 0 to reset frequency phase per symbol. encoder->counter_bit = encoder->counter; } } } } 7 https://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter Data communication through power lines using a system based on BeagleBone 87/180 3.6.3.5 decoder-ook Target decoder-ook.so Purpose Decodes data from a simple On-Off-Keying codification Details Source code ./plugins/decoder/decoder-ook This plugin includes some code that applies a low pass filter to the input (either through FIR or IIR8). It’s not optimized but it gives an overview of how digital filters can be implemented in C. plugins/encoder/decoder-ook/decoder-ook.c uint32_t decoder_parse_next_samples_buffer(struct decoder *decoder, const sample_rx_t *buffer_in, uint8_t *buffer_data_out, uint32_t buffer_data_out_count) { // // CHUNK_PUSH: Filtering // int n; float *in_f = decoder->buffer_in_f + decoder->iir_b_count; float *out_f = decoder->buffer_out_f + decoder->iir_a_count; // Chain previous in/out values for (n = 0; n < decoder->iir_b_count; n++) decoder->buffer_in_f[n] = decoder->buffer_in_f[decoder->chunk_samples + n]; for (n = 0; n < decoder->iir_a_count; n++) decoder->buffer_out_f[n] = decoder->buffer_out_f[decoder->chunk_samples + n]; // Push new values // Demodulation for (n = 0; n < decoder->chunk_samples; n++) { in_f[n] = abs(buffer_in[n] - decoder->data_offset); out_f[n] = 0.0; } // Aplpy filter // Filtering algorithm (1-based): // y[n]*iir_a[1] = Sum(k=0..M) [ iir_b[k+1]*x[n-k] ] - Sum(k=1..N) [ iir_a[k+1]*y[n-k] ] // N=len(iir_a)-1; M=len(iir_b)-1 // More info about filtering can be found in 'Octave' in 'doc filter' for (n = 0; n < decoder->chunk_samples; n++) { int k; for (k = 0; k < decoder->iir_b_count; k++) out_f[n] += decoder->iir_b[k] * in_f[n - k]; for (k = 1; k < decoder->iir_a_count; k++) out_f[n] -= decoder->iir_a[k] * out_f[n - k]; out_f[n] /= decoder->iir_a[0]; // Quantification decoder->buffer_out_filter[n] = (sample_rx_t) round(out_f[n]); } // // CHUNK_SIGNAL_TO_DATA: Interpretation // if (buffer_data_out_count == 0) return 0; uint8_t *buffer_data_out_end = buffer_data_out + buffer_data_out_count; uint8_t *buffer_data_out_cur = buffer_data_out; while (1) ... 8 FIR and IIR are computationally efficient ways of implementing filters in source code: •FIR = Finite Impulse Respone. See https://en.wikipedia.org/wiki/Finite_impulse_response •IIR = Infinite Impulse Response. See https://en.wikipedia.org/wiki/Infinite_impulse_response 88/180 Data communication through power lines using a system based on BeagleBone The proper behavior of the pair encoder-ook and decoder-ook has been checked with the plc-cape-lab application with the following configuration: •calibration mode (i.e. internal bridge between TX and RX) •low frequency carrier of 10kHz to simplify the analysis with Octave •SPI clock = 750k bps •Message to be send and received continuously: Hi •ADC recording = 50k samples This is a screenshot of the plc-cape-lab with the results of the test: Figure 37. Test of the OOK modulation in calibration mode (auto-loop) We can see that the message has been properly decoded: h.HiHiHiHiHiHiH. We see an error at beginning of the stream (h.). That’s due to the required ADC setup time. With Octave we can take a look at the first 50k ADC stored samples and identify there the symbols transmitted with the OOK modulation. In the following figure we have three graphs: •the 50k samples received •the 50k samples after having applied the IIR low-pass filter •the decoded data Data communication through power lines using a system based on BeagleBone 89/180 Figure 38. OOK captured data + IIR filtering result + Data decoded When zooming, we can see the composition of the H and i symbols in detail (1 start-bit + 8 data bits): Figure 39. OOK encoding for the 'H' character = 72 = 0b01001000 Figure 40. OOK encoding for the 'i' character = 105 = 0b01101001 If we zoom to one bit of data, we can see the carrier and check that has the expected frequency (10kHz): Figure 41. OOK 10kHz carrier detail 96/180 Data communication through power lines using a system based on BeagleBone 3.7.3.3 plc-cape-lab Target plc-cape-lab Purpose Laboratory tool to explore the main features offered by the PlcCape board Details It is the main application for "laboratory work". It offers access to the different configurable options of the AFE031. Features: •Multi wave generation •Real-time and deferred DAC transmission •Real-time and deferred ADC reception •Capturing to file in Octave-compatible format for post-analysis •Time measurements •Gains... Source code ./applications/plc-cape-lab 3.7.3.3.1 Main concepts The plc-cape-lab is the core application of this project. It implements different tests and tools to analyze the behavior of the BBB + PlcCape assemblies. It offers a text-based user interface (TUI) relying on the ncurses package for a user-friendly menu-based interface. The main screen looks like this: Figure 45. Main screen of the 'plc-cape-lab' application (running with 'ui-ncurses') A graphical-based plugin (GUI) could be developed in a future version to provide some extra functionality, like showing the ADC captured data without requiring external tools. Data communication through power lines using a system based on BeagleBone 97/180 Note that a TUI has also some advantages over a GUI. For example, it can be executed remotely from a desktop PC through a simple SSH session. plc-cape-lab depends only on standard built-in libraries. It logically depends on the ncurses package when using the ui-ncurses plugin (the usual operating mode). When completed, the ui-console plugin could be used as an alternative on systems that doesn’t provide ncurses. 3.7.3.3.2 Features The plc-cape-lab application implements the following features: •AFE031 functionality ◦TX and RX programmable gains ◦CENELEC band configuration (A or B/C/D) ◦Calibration modes ◦Asynchronous error notification: thermal & current protection flag ◦Per block enabling/disabling control to optimize consumption •Signal generation (TX) in real-time or deferred mode •Signal capture (RX) in real-time or deferred mode •Periodic transmission (to send short packets of data at intervals) •Modulation/demodulation (encoding/decoding) •Plugins management ◦Dynamic loading and unloading of encoders and decoders ◦Automatically generated lists of available plugins for user selection •LED control •Monitoring ◦Errors: buffer underflow conditions ◦Processing Time: reporting of the time required to prepare a buffer of samples when using the current encoder/decoder ◦Input signal statistics: reporting of some real-time measurements, as the AC mean and DC mean of each buffer received. It is specially useful to simplify the PlcCape tuning. It can also be disabled to reduce the involved CPU load •Profiles concept, to predefine sets of settings 3.7.3.3.3 Basic operation The recommended way to start the application is by using the run.sh script (specifying the version of the BBB and PlcCape as indicated in 3.7.2 Applications execution): # cd $DEV_SRC_DIR/applications/plc-cape-lab # ./run.sh 2 2 Then the main screen shown above is displayed. 98/180 Data communication through power lines using a system based on BeagleBone MAIN SCREEN In the main screen of the application we have four areas: Main menu (in the left side) With Up and Down arrows we can move among the different menu items With RETURN we open pop-up sub-menus or execute operations The characters in square brackets (or numbers, when indicated) are shortcuts for the menu items Settings (in the right) This panel displays all the current configured settings grouped by scope area: settings affecting the transmission (TX), the reception (RX), the AFE031 generic behavior, etc. Log window (in the center) This is a generic-purpose output console (a “stdout”). All the messages reported by the application are shown here. The real-time received data is also reported here if the applications is configured to do so. Status bar (at bottom) The bottom line of the screen is used to report some brief real-time data, like statistics about the received data, DMA buffers processed on transmission, some AFE031 flags, etc. Table 21. Main screen panels MAIN MENU The Main menu at the left offers these options: ON Starts the communication (transmission and/or reception of data) OFF Stops the communication Profiles Configures the application by selecting one of the predefined profiles Settings Global Configuration of some generic-purpose settings Settings TX Configuration of transmission-related settings Settings RX Configuration of reception-related settings Monitoring profiles Offers the possibility to select the type of information to show in the status bar (processing time, data received statistics, etc.) Tools Several one-shot operations Quit Terminates the application Table 22. Main menu options Most options in the main menu open pop-up sub-menus. Following, there are some captures enclosed with a brief explanation about. Data communication through power lines using a system based on BeagleBone 99/180 PROFILES SUB-MENU This sub-menu shows first a categorization of the different available profiles, as: TX+RX CAL: Profiles based on the AFE031 calibration modes that internally route the transmitter to the receiver. These profiles allow us to easily check the whole communication path: data modulation + TX + RX + data demodulation TX: Profiles that only enable the low-power transmitter blocks (DAC + TxPGA + TxFilter). The generated signal can be measured with an oscilloscope on the TX_F_OUT pin (see 2.5 AFE031) TX+PA: Like in the TX profile but also enabling the Power Amplifier stage. So, this will generate amplified output in the PA_OUT pin TX+PA+RX: Like in TX+PA but also enabling the reception blocks. This configuration can be useful to do a TX-RX loop (like in the TX+RX CAL profile) but using external circuitry. RX: Profiles that only enable the reception-related blocks TX+RX CAL PROFILES This is an example of the list of profiles we get in the TX+RX CAL category. For example we have TX+RX CAL 2kHz, a typical profile for quick testing and check that all the system works OK. It is pre-configured with these settings: •The AFE is configured to operate in the calibration mode that enables the DAC and the TxPGA blocks (shown in the UI as calib_dac_txpga) •At TX it generates a sinusoid of 2 kHz with a DC Offset value of 800 (in DAC units) and an AC Range of 400 (in DAC units too). The SPI rate is configured at 1.5Mbps, which allows for a maximum wave frequency of 69 kHz (because the 10-bits per sample and the Nyquist frequency). •At RX it is configured to store in a file (adc.csv) 10000 samples in Octave-compatible format, for post-analysis 100/180 Data communication through power lines using a system based on BeagleBone The settings panel is automatically updated with these values when selecting the profile, as can be observed in the below figure: Figure 46. Settings corresponding to the profile 'TX+RX CAL 2kHz' A profile configures a group of settings in one go (for convenience). But anyway, these settings can also be configured individually through the corresponding sub-menus (Global, TX, RX): Data communication through power lines using a system based on BeagleBone 101/180 Some settings are self-explanatory, some others will be commented when they will be used in the 4 Analysis & results. MONITORING OPTIONS This sub-menu selects the information to be displayed in the status-bar: None: No information is provided. This saves CPU for other tasks. Buffers processed: Just information about the amount of buffers transmitted and received is displayed. The impact on the CPU is very low. TX values: Statistics about the missed versus successful buffers transmitted TX time: Real-time statistics (max, min, average) of the time consumed to generate a buffer for transmission. It will give an idea about the computational effort required for a given modulation/encoding algorithm. RX values: Real-time statistics over each received buffer. The values monitored here are specially important to tune the system at reception. The most important data provided is: •DC Mean (or DC Offset): is the average of all the samples captured by the ADC •AC Mean: is the average of the absolute values once removed the DC Mean. It is a method computationally efficient that gives a good measure of the amplitude of the signal received. We can increase the gains of the RxPGA1 and/or RxPGA2 to increase this value •Range: gives the difference between the maximum value and the minimum one. It’s like a peak-to- peak voltage. However, it is not very reliable because affected by spurious or glitches TOOLS Different one-shot tools are provided here: 102/180 Data communication through power lines using a system based on BeagleBone Log overloads: Just reports the status of the AFE031 register in charge of notifying the source cause of an error condition, either Thermal overload or Current overload. Clear overloads: This explicitly clears the Overloads register. View current settings: Just prints the list of currently configured settings in the Log panel. Measure processing time on modulation: Does a modulation test with the current settings and displays the time required to complete it. It gives an idea of the maximum transmission rate we can achieve to have on-the-fly encoding (i.e. continuous modulation and transmission of incoming data). 3.7.3.3.4 Command line parameters For simpler usage the plc-cape-lab application gives the possibility to pre-configure some of its parameters through the command line: # ./plc-cape-lab --help Usage: plc-cape-lab [OPTION]... "Laboratory" to experiment with the PlcCape board -A:MODE Select ADC receiving mode -d Forces the application to use the standard drivers -D:INTERVAL Max duration for the test [ms] -F:BPS SPI bit rate [bps] -H:FREQ Signal frequency [Hz] -I:INTERVAL Repetitive test interval [ms] -L:DELAY Samples delay [us] -N:SIZE Buffer size [samples] -O:OFFSET Signal offset [DAC value] -P:PROFILE Select a predefined profile -R:RANGE Signal range [DAC value] -S:MODE SPI transmitting mode -T:MODE Operating mode -U:NAME UI plugin name (without extension) -W:SAMPLES Received samples to be stored in a file -x Auto start -Y:TYPE Stream type --help display this help and exit For the arguments requiring an index from a list of options you can get more information specifiying the parameter followed by just a colon For more information refer to the source-code. 3.8 Pending tasks This is the first version of the framework (0.1), an early draft. Many things must be improved, bugs fixed and new features implemented. For example, these are possible improvements or new features to be covered in future versions of the framework: •Zero-crossing detection of the AC voltage to be used as a synchronization mechanism •Better management of the AFE031 asynchronous error notifications •Implement simple protocols (proprietary or based on some standard) •FEC (Forward Error Correction), 16bit CRC (Cyclic Redundancy Check), encryption algorithms Data communication through power lines using a system based on BeagleBone 103/180 •Define a whole Device Tree Overlay for the PlcCape to indicate which GPIOs are used by the board and thus allow other Capes to be stacked without conflicts There are also some optimizations that can be explored for better computational efficiency: •take advantage of the Floating Point Unit (FPU) of the BBB CPU9 (VFPLite) •replace floating point calculations by 32-bit integer whenever possible. In fact, the BBB is specially powerful when managing integers but it’s behind other platforms on floating-point support. Here attached, an extract10 of an interesting conclusion obtained from a benchmark with the nbench tool over some popular embedded platforms: […] Looking at the results, the Beaglebone Black has the strongest memory and integer performance. However the Beaglebone Black's floating point performance is slightly behind the Raspberry Pi. This can be explained because the ARM Cortex-A8 processor on the Beaglebone Black has a 'VFPLite' floating point unit which isn't as fast as other ARM FPUs. If you only care about performance and don't have a floating point heavy workload, the Beaglebone Black is a good board to consider. […] •use preloaded tables + interpolation for the sin(x) values •take advantage of one of the specific features of the BBB microcontroller: the PRUs[13], which are parallel processors able to do some job in real-time Optimization note: in the present version of the software we have used single precision floating-points (float type) to have a small gain in performance. Usually floats give accuracy enough but it’s likely that double precession will be required when dealing with more sophisticated modulations. Concerning bugs: •the software still freezes in some scenarios that have not been protected. For example the application hangs when the ADC is not able to reach the capturing speed due to other threads running in the background and performing CPU-intensive tasks •the framework is mulithreaded (MT), though only some preliminary resource-sharing control has been implemented. Full MT-safe code must be implemented as soon as possible 9 Some notes about how to use full hardware floating point in https://wiki.debian.org/ArmHardFloatPort 10 Full article available at https://learn.adafruit.com/embedded-linux-board-comparison/performance 104/180 Data communication through power lines using a system based on BeagleBone 3.9 Development with Octave Octave is the Open Source alternative to Matlab. It’s a very powerful tool for mathematical analysis. In this project it has been used to analyze the captured data by the ADC of the BBB. It has also been used to get the coefficients of the low-pass IIR filter used in the decoder-ook plugin. A single Octave file (*.m) has been created to store all the tests done during the development of this project. It is not the best way to do things but it’s quick and functional enough. Each test has been identified with a name which is specified on the calling function (execute_test). A big switch selects the test to run. The whole source-code of the Octave file used is enclosed in Annex V. Source code files, in the section 10.3 Octave. 3.9.1 Post-analysis The typical steps to analyze ADC captured data are: 1. Run the plc-cape-lab application configured to store the ADC captures to a file with name adc.csv 2. Start Octave 3. Launch the execute_test function specifying one of the available test types. For example, to see the captures of the ADC execute this sentence: >> run "X:/tools/octave/plot_adc_fft.m"; execute_test("adc", "Y:/applications/plc-cape-lab") where X: is the mapped unit where the source code resides, and Y: is the mapped unit where the output data is stored. 4. For the “adc” test type, Octave will plot the samples received and the corresponding FFT. There are some examples about in 3.4.6.2.4 Analysis within the adc-driver chapter. 3.9.2 IIR coefficients Octave can be used to easily get the necessary coefficients to implement a basic FIR/IIR filter. For example we can use the butter function within the signal package to get the coefficients of a 1st order filter with a cut-off frequency = 0.1: >> pkg load signal >> [iir_b,iir_a] = butter(1, 0.1) iir_b = 0.13673 0.13673 iir_a = 1.00000 -0.72654 Then we can update the source code with these coefficients to apply the corresponding IIR filter to a signal: static const float iir_a_default[] = { 1.00000, -0.72654}; static const float iir_b_default[] = { 0.13673, 0.13673}; An example of this can be found in the decoder-ook plugin. Note that the more coefficients the more the accuracy in the cutoff frequency but the more the computational effort required, which is the limiting factor in real-time communications. Data communication through power lines using a system based on BeagleBone 105/180 4 Analysis & results 4.1 Overview In the previous chapters, I’ve described the software that has been developed for this project. Now it’s time to use it to evaluate the feasibility of the assembly composed of a BeagleBone Black and a PlcCape board as an alternative for data transmission over Power Lines. For the tests, the PWM encoding has been used because: •it’s easy to manage and to identify characters in the resulting captures •it’s protected against attenuation: PWM characters will be properly decoded while the carrier is over a predefined configurable threshold 4.2 Test equipment The preliminary tests are focused on checking that the electronics and the software are working as expected. For that purpose, we just need one BeagleBone Black equipped with a PlcCape and a USB connection with a desktop PC. For the tests involving data communication between boards, we’ll need another BBB and extra power supplies. In particular these are the electronic devices that have been used for the analysis: Figure 47. Test kit 112/180 Data communication through power lines using a system based on BeagleBone By zooming in, we can get a detailed view of the carrier: Figure 54. Detail of the 110kHz carrier Notice that despite the few samples per cycle used in the DAC generation we can see a quite good sinusoid of about 350mVpp and 110kHz (the 10.93kHz measured by the cursor is because I’ve considered 10 cycles for better accuracy). With Octave, we can also take a look at the 10000 first samples captured by the ADC: Figure 55. Data captured by the ADC of the BBB Data communication through power lines using a system based on BeagleBone 113/180 From the Octave’s graph, we can deduce some interesting conclusions: •In the top plot, which shows the value of the samples captured by the ADC, we can see that, in our test, a small subset (from 1550 to 1800) of the whole ADC available range (from 0 to 4095) is used. Even in that low-level reception conditions, the system is properly demodulating the PWM signal. Note that 10000 samples at 200 ksps correspond to a capturing interval of 10k/200k = 50ms. In a previous oscilloscope capture we have seen that our full message is repeated each 385ms. So, in this Octave’s capture, we are not seeing whole messages but just some characters of the composing message, encoded in PWM. •In the bottom plot, we have the absolute value of the Fast Fourier Transform which give us the composition of the received signal in the frequency domain. More details about the FFT graphs where explained in the section 3.4.6.2.4 Analysis when describing the adc-driver. To get more details about the ADC capture, I have zoomed in the graph to 2000 and 100 samples: Figure 56. Data captured by the ADC: zoom to 2000 first samples Figure 57. Data captured by the ADC: zoom to 100 first samples We can see that at the current frequency of the carrier (110kHz) there is only a couple of samples per cycle. We almost get an alternating signal between the minimum (1550) and the maximum values (1800). 114/180 Data communication through power lines using a system based on BeagleBone 4.3.3.2 Test with PlcCape-v1 To test the real communication between two devices we will need the PlcCape-v1 to be used as the transmitter (the PlcCape-v2 has the Power Amplifier stage damaged). So, I’ve repeated the previous test, but now with the PlcCape-v1 and with this probing configuration (measuring TX_F_OUT too): Figure 58. Testing environment with PlcCape-v1 First, the proper operation of the TX-RX loop is checked by repeating the steps described in 4.3.3.1: Figure 59. Communication test with PlcCape-v1 in calibration mode Data communication through power lines using a system based on BeagleBone 115/180 I’ve taken some captures with the oscilloscope to compare the output with the one in PlcCape-v2. Figure 60. TX_F_OUT of 3 messages iterations with PlcCape-v1 The output obtained at 100ms/div is more or less the same one as in the PlcCape-v2 case. If we zoom to 20ms/div, we can see the PWM modulation of each character composing the message sent. I’ve superimposed in red the characters of the message with the corresponding ASCII code in green: Figure 61. Identification of the characters composing the message 116/180 Data communication through power lines using a system based on BeagleBone By zooming in, we get a detailed view of the carrier: Figure 62 Detail of the 110kHz carrier generated by the PlcCape-v1 The shape is similar to the one in PlcCape-v2 but the output voltage is slightly higher, 447mVpp (+27%). This could be due to the different components and layout of both PlcCapes. In any case, the qualitative behavior of both PlcCape boards is the expected one. 4.3.4 Conclusions From the experiments done in this section, we can draw these conclusions: •The transmission and reception chains (including the PWM encoder and PWM decoder plugins) are working properly •The configuration and parameters of this test are suitable for further tests (not only for Calibration Modes) Data communication through power lines using a system based on BeagleBone 117/180 4.4 Data output at the Power Amplifier 4.4.1 Purpose In this section we’ll check that the transmission stages and, in particular, the Power Amplifier of the PlcCape-v1, work as expected. 4.4.2 Testing environment The testing environment is composed of BBB + PlcCape-v1 + 15VDC power supply + OSC probing: Figure 63. Testing environment to check the Power Amplifier of the PlcCape-v1 Note that for this test we need the AC-coupling auxiliary board that attaches to the PlcCape-v1 and which provides easy connection points through practical screw-based connectors. From top to bottom, this is the purpose of the pins in the column of connectors: 1PA_GND (in) Ground of power supply used to provide energy to the Power Amplifier stage of the AFE031 2PA_VS (in) Positive power supply pin for the PA stage. In this test we use 15VDC 3VCC_5V (out) Comfortable access to the 5VDC provided by the power supply that feeds the BBB 4VCC_GND (out) Ground of the 5VDC 5 6 AC-coupling (in/out) Connection points with the coupled line used for data communication Table 26. Pinout of the AC-coupling auxiliary board In this test we’ll measure: •the TX_F_OUT signal (green-wire probe), which corresponds to the output of the TxPGA + TxFilter •the TXRX signal (orange-wire probe) which corresponds to the output of the Power Amplifier stage (PA_OUT) after a decoupling capacitor of 10uF (which removes any DC component) Figure 64. Line-coupling auxiliary circuit 118/180 Data communication through power lines using a system based on BeagleBone 4.4.3 Results To check the Power Amplifier of the PlcCape, the plc-cape-lab application has been configured this way: Figure 65. Configuration settings to generate output through the Power Amplifier This is the oscilloscope capture obtained (CH1 in blue = TX_F_OUT, CH2 in red = TXRX): Figure 66. Signals at TX_F_OUT (CH1) and TXRX (CH2), 100ms/div We can see observe here the gain of the in TXRX (Power Amplifier output) over the TX_F_OUT. Data communication through power lines using a system based on BeagleBone 119/180 A zoom to 10us/div allows us to better measure the amplitude of the TXRX signal: Figure 67. Signals at TX_F_OUT (CH1) and TXRX (CH2), 10us/div The AFE031 data sheet mentions that the typical gain of the Power Amplifier in relation to the input is about 6.5V/V which corresponds to the results got. The next step is to check the output after the AC coupling circuit. The same testing configuration has been used; only the probing point associated to CH2 has been changed from TXRX to the line-coupling connector (white and green wires): Figure 68. Configuration to probe the coupled-line 120/180 Data communication through power lines using a system based on BeagleBone These are the corresponding oscilloscope captures: Figure 69. TX_F_OUT (CH1) and coupled-line (CH2), 100ms/div And a zoom in to 10us/div: Figure 70. TX_F_OUT (CH1) and coupled-line (CH2), 10us/div We can notice a small attenuation in the coupled-line output (426mVpp) compared to the previously measured TXRX (655mVpp). 4.4.4 Conclusions •the Power Amplifier stage of the PlcCape-v1 and the line-coupling circuitry provided by the auxiliary board are working as expected •the line-coupling circuitry slightly attenuates the signal coming from the Power Amplifier Data communication through power lines using a system based on BeagleBone 121/180 4.5 Data transmission over an unpowered line 4.5.1 Purpose The target of this section is to check that we can communicate data between two device assemblies (BBB + PlcCape) through an unpowered line. This will confirm the proper behavior of the whole communication path (TX + RX + line-coupling circuitry) for the particular case of 0 VAC. 4.5.2 Testing environment Here, the testing material has been arranged like this: Figure 71. Testing environment for communication over an unpowered line We can see: •On the top (at left), the 15VDC power supply that feeds the Power Amplifier stage of the PlcCape-v1 •Next, we have the transmitter, the assembly composed of a BBB plus a PlcCape-v1 •Finally, we have the receiver, consisting on a BBB and a PlcCape-v2 •The PlcCape-v1 and the PlcCape-v2 are interconnected through a couple of direct wires (green and white) through the line-coupling connectors of both boards The oscilloscope probe is arranged to measure the TXRX line (the output of the Power Amplifier after a decoupling capacitor). 128/180 Data communication through power lines using a system based on BeagleBone 4.5.4 Conclusions •The transmission between boards through the line coupling circuitry works OK •The signal that arrives to the receiver (from the coupled-line) is strongly attenuated by the integrated filters before reaching the ADC •In the conditions of this test, these are the recommended values for a proper demodulation: ◦RX_PGA2 gain of 16V/V ◦DC Offset = 1301 Data communication through power lines using a system based on BeagleBone 129/180 4.6 Data transmission over a low-voltage AC line 4.6.1 Purpose To minimize the risks of damage, the first series of AC tests have been done over a 12V AC line. 4.6.2 Testing environment This is the equipment we have used for this test: Figure 81. Testing environment in a 12VAC line We can identify: •PlcCape-v1 + PlcCape-v2 •15VDC •12VAC •Load simulation with a pair of opposed LEDs with a current limiting series resistor of 10kΩ •Probing TXRX + AC-Line: note that we can use a different ground for each probe because the measurement is done over a floating transformer 130/180 Data communication through power lines using a system based on BeagleBone A zoom: Figure 82. Detail of the wiring in the testing environment We can identify: •Orange and White = 12VAC Power Supply rail •Pair of yellow wires: connection between the power supply rail and the coupling circuit at the transmitter •Pair of green wires: connection between the power supply rail and the coupling circuit at the receiver •Blue: probe over the power supply rail •Red and black: 15VDC power supply for the Power Amplifier stage of the transmitter To simulate a load, two LEDs have been disposed in opposite sense. They are alternatively lighted on each half-cycle. That’s also a basic way of checking that our AC power supply is working as expected: Left-LED lighted Right-LED lighted Although the power supply is marked as 9.5VAC (root-mean-square amplitude) it seems to provide 12VAC because the peak-to-peak voltage measured with the oscilloscope (33.5Vpp) corresponds to it11: VPP=2 √ (2)×VRMS≈2.8×VRMS →VPP (12VAC)=2.8×12=33.6Vpp The deviation between RMS values (expected and real) could be due to the fact we are using the power supply with a high-impedance load (to minimize the power delivered by the AFE) rather than using the nominal conditions of the power supply. In any case this doesn’t mean any trouble for our tests. 11 Further information in https://en.wikipedia.org/wiki/Root_mean_square Data communication through power lines using a system based on BeagleBone 131/180 4.6.3 Results With the transmitter OFF: Figure 83. Capture of the 12VAC power rail (CH2) with no transmission (CH1) With the transmitter ON: Figure 84. Capture of the 12VAC power rail (CH2) with PWM transmission (CH1) We can appreciate now a thicker line for the 12VAC signal. That’s due to the overlapping of the PWM signal over the 12VAC supply. 132/180 Data communication through power lines using a system based on BeagleBone Let’s see that overlapping in more detail with the help of three more captures: Figure 85. Detail of the 12VAC with superimposed data and without In the above capture we can see the difference between both scenarios: the first raising edge corresponds to the 12VAC 50Hz without transmission; the falling edge is thicker because the data is superposed. I’ve also taken a capture at the end of the transmission of a character (at 100us/div): Figure 86. Detail of the end of a character transmission Data communication through power lines using a system based on BeagleBone 133/180 A zoom in to the 50us/div scale allows us to clearly identify the PWM carrier of the transmitted data: Figure 87. Detail of the PWM carrier in the 12VAC In the Putty terminal of the receiver we can observe that the message is properly received over the 12VAC powered line: Figure 88. Correct reception of data There is an error by the middle of the logging. It is due to a glitch when switching OFF the 12VAC power. Since then, we are in the unpowered line scenario analyzed in previous sections. 134/180 Data communication through power lines using a system based on BeagleBone A capture of the TXRX & ADCIN signals (at 10ms/div and 10us/div) shows the expected behavior: Figure 89. TXRX at PlcCape-v1 (CH1) and ADCIN at PlcCape-v2 (CH2), 10ms/div Figure 90. TXRX at PlcCape-v1 (CH1) and ADCIN at PlcCape-v2 (CH2), 10us/div Data communication through power lines using a system based on BeagleBone 135/180 The Octave captures are also the expected ones, without any trace of the 12VAC signal: Figure 91. Data captured by the ADC plotted with Octave And just a final zoom in of the captured data over 100 samples to take a look at the carrier: Figure 92. Detail of the data captured by the ADC over 100 samples 4.6.4 Conclusions Important conclusion: We have been able to reliably communicate data between two BBB + PlcCape assemblies over a 12VAC Power Line. 136/180 Data communication through power lines using a system based on BeagleBone 4.7 Data transmission over a high-voltage AC line 4.7.1 Purpose The final test to be done is to check that the system works also over the mains. Obviously, we have to be very careful here: 240VAC (~680Vpp) is enough voltage to kill people. 4.7.2 Testing environment The main idea is to repeat the previous test, but replacing the 12VAC by the 240VAC mains: Figure 93. Testing environment in a 240VAC line (the mains) Comparing to the 12VAC case: •we have connected directly the mains to the shared coupled-line (power and data) •the 10 kΩ serial resistor used to limit the current in the low-power LEDs has been replaced here by two low-power resistors (250mW) of 3.3 MΩ each. With this configuration, the LEDs get very little current (< 1mA) but enough to be slightly lighted. In fact, that’s just to have a visual notification that the 240VAC are OK Data communication through power lines using a system based on BeagleBone 137/180 4.7.3 Results Unfortunately, I’ve not been able to do a successful test with the current PlcCape board. In this environment, the AFE031 heats too much and too quickly. In theory, the internal thermal limiter of the AFE should automatically stop any transmission to avoid any further damage, but in this case it seems it has not been fast enough. As with the PlcCape-v2, the Power Amplifier stage of the PlcCape-v1 has been destroyed after this test. Note that the use of the mains (compared to the 12VAC scenario) has two significant differences: •obviously, the PlcCape circuitry must deal with much higher voltages (x20 times) •a lot of domestic appliances are connected to the mains (the TV, the desktop PC, the refrigerator…). All these consume a considerable amount of energy. Or in other words, they represent low impedance sources. That means that our AFE031 in the PlcCape must be able to deliver significant current to attain the required voltage. And, maybe this has been the cause of the excessive heat produced 4.7.4 Conclusions This test has revealed one important point we must be considered when looking at the PLC technology: the management of the power consumption and the design of proper heat dissipation mechanisms. In our specific case, a probable cause of the excessive heat has been the lack of a good thermal design in the PlcCape board. For example, the AFE031 chip has a conductive layer for heat dissipation in the bottom side that MUST be soldered to the board. This was not the case for the boards I’ve used for the tests. After the result of this analysis, we should consider other alternatives to evaluate in the future, like: •provide an option into the plc-cape-lab software to just enable the AFE031 for a very short lapse, to send only one message (or one char). Current software is focused more on repetitive tests •provide an external Power Amplifier stage through a high-power transistor. The benefit is that we should be able to deliver much more power and dissipate heat more easily, but at the expense of higher costs and more board space In any case, this electronic problem is out of the scope of this project 144/180 Data communication through power lines using a system based on BeagleBone Respuesta desde 192.168.7.2: bytes=32 tiempo<1m TTL=64 ... 2. Start Putty and specify the BBB IP Address (192.168.7.2) in the Session panel: Figure 95. Main screen of the Putty application The default BBB SSH connection requires using root as the user name. You can type it in each connection or indicate it in the Connection > Data > Auto-login username field of Putty for quicker access. Tip: for comfort purposes custom sessions can be defined (in previous capture JMO-BBB-Usb, JMO-BBB-Eth...) with the specific required settings (IP address, login name, specific UI colors, etc.). Then double clicking on the saved profile will open the connection Data communication through power lines using a system based on BeagleBone 145/180 3. If the connection is properly established a console window will be opened: Figure 96. BBB login message (via a remote console on Putty) 7.3 Initial interaction with the BBB When working with a remote client (ssh, screen or Putty) all the commands typed on the console will be executed on the BeagleBone. For example to get the version of the OS we can execute uname -a: root@beaglebone:~# uname -a Linux beaglebone 3.8.13-bone70 #1 SMP Fri Jan 23 02:15:42 UTC 2015 armv7l GNU/Linux Figure 97. Version of the Linux Kernel of the BBB Note: for a BeagleBone Black bought on 2015 the original version was a previous one, 3-8-13-bone47: root@beaglebone:~# uname -a Linux beaglebone 3.8.13-bone47 #1 SMP Fri Apr 11 01:36:09 UTC 2014 armv7l GNU/Linux We can get information about the distribution with the command lsb_release -a: # lsb_release -a No LSB modules are available. Distributor ID: Debian Description: Debian GNU/Linux 7.8 (wheezy) Release: 7.8 Codename: wheezy Note: exactly the same distribution was present in the BBB purchased on 2015. 146/180 Data communication through power lines using a system based on BeagleBone Following a list of other possible interesting informative commands: df -h File system information dmesg -head Show initial boot messages (with interesting information) dpkg -l List of all the installed packages in a Human Readable format dpkg-query -W List of all the installed packages in a compact way dpkg-query -W | wc -l Count of installed packages ifconfig Current network interfaces configuration Table 27. Linux commands used on setup And the corresponding execution on the off-the-shelf BBB: # df -h Filesystem Size Used Avail Use% Mounted on rootfs 3.5G 1.8G 1.6G 54% / udev 10M 0 10M 0% /dev tmpfs 100M 580K 99M 1% /run /dev/disk/by-uuid/746f634c-67a5-4e5a-b14d-1ec025ae9095 3.5G 1.8G 1.6G 54% / tmpfs 249M 0 249M 0% /dev/shm tmpfs 249M 0 249M 0% /sys/fs/cgroup tmpfs 100M 0 100M 0% /run/user tmpfs 5.0M 0 5.0M 0% /run/lock /dev/mmcblk0p1 96M 64M 33M 67% /media/BEAGLEBONE # dmesg | head [ 0.000000] Booting Linux on physical CPU 0x0 [ 0.000000] Initializing cgroup subsys cpu [ 0.000000] Linux version 3.8.13-bone70 (root@a5-imx6q-wandboard-2gb) (gcc version 4.6.3 (Debian 4.6.3-14) ) #1 SMP Fri Jan 23 02:15:42 UTC 2015 [ 0.000000] CPU: ARMv7 Processor [413fc082] revision 2 (ARMv7), cr=50c5387d [ 0.000000] CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instruction cache [ 0.000000] Machine: Generic AM33XX (Flattened Device Tree), model: TI AM335x BeagleBone [ 0.000000] Memory policy: ECC disabled, Data cache writeback [ 0.000000] On node 0 totalpages: 130816 [ 0.000000] free_area_init_node: node 0, pgdat c08c09c0, node_mem_map c093e000 [ 0.000000] Normal zone: 1024 pages used for memmap # dpkg-query -W -f='${binary:Package;-20} ${Version;18} ${binary:Summary}\n' acl 2.2.51-8 Access control list utilities acpi-support-base 0.140-5+deb7u3 scripts for handling base ACPI events such as the pow... acpid 1:2.0.16-1+deb7u1 Advanced Configuration and Power Interface event daemon adduser 3.113+nmu3 add and remove users and groups alsa-base 1.0.25+3~deb7u1 ALSA driver configuration files alsa-utils 1.0.25-4 Utilities for configuring and using ALSA am335x-pru-package 0.20141125-1~bpo70 AM335x PRU PACKAGE apache2 2.2.22-13+deb7u4 Apache HTTP Server metapackage ... # dpkg -l | wc -l 957 # ifconfig eth0 Link encap:Ethernet HWaddr ec:12:34:56:78:aa UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) Interrupt:40 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 Data communication through power lines using a system based on BeagleBone 147/180 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) usb0 Link encap:Ethernet HWaddr be:12:34:56:78:bb inet addr:192.168.7.2 Bcast:192.168.7.3 Mask:255.255.255.252 inet6 addr: fe80::1111:2222:3333:4444/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:4722 errors:0 dropped:0 overruns:0 frame:0 TX packets:7598 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:255199 (249.2 KiB) TX bytes:1972885 (1.8 MiB) Tip: At any moment a backup of the current whole flash content (in the eMMC) can be done following the instructions at http://elinux.org/BeagleBone_Black_Extracting_eMMC_contents. 7.4 Internet access For a comfortable development environment it’s very convenient to get access to the Internet. It will allow updating packages on the BBB or download specific ones, to get access to a NTP server to synchronize date/time, etc. A quick way to test if we have an Internet connection is with ping: # ping www.google.com ping: unknown host www.google.com We can also try with one of the IP address associated to www.google.com, 172.217.16.68: # ping 172.217.16.68 connect: Network is unreachable We can check the connection with the PC: # ping 192.168.7.1 PING 192.168.7.1 (192.168.7.1) 56(84) bytes of data. 64 bytes from 192.168.7.1: icmp_req=1 ttl=128 time=0.475 ms 64 bytes from 192.168.7.1: icmp_req=2 ttl=128 time=0.477 ms 64 bytes from 192.168.7.1: icmp_req=3 ttl=128 time=0.610 ms ... A quick simple way to gain Internet access could be connecting a gateway to the Ethernet port. Another way is sharing the Internet connection of the desktop PC: the BBB connects with the PC through the USB and the desktop PC routes the packets to the Internet gateway through the proper adapter (the Wi-Fi interface in my case). 7.4.1 Steps in the Desktop PC If the Desktop PC is equipped with Windows XP we can share the Internet connection following these steps: 1. Open the Control Panel and double-click the Network Connections icon 2. Then select the adapter that is connected to Internet, right click on it and select Properties > Advanced options and enable the option Allow other network users to connect through this computer’s Internet connection 148/180 Data communication through power lines using a system based on BeagleBone If the Desktop PC is equipped with Ubuntu we can share the Internet connection this way: 1. Gain root access $ sudo su 2. With ifconfig find the name of the interface that is connected to Internet. For this example assume it is wlan4 corresponding to a Wi-Fi connection 3. With ifconfig find the name of the interface that is connected to the BBB. For this example assume it is eth5, corresponding to the Ethernet Port 4. Set the bridge between the BBB interface and the Internet one: $ iptables --table nat --append POSTROUTING --out-interface wlan4 -j MASQUERADE $ iptables --append FORWARD --in-interface eth5 -j ACCEPT 5. Enable the forwarding: $ echo 1 > /proc/sys/net/ipv4/ip_forward 7.4.2 Steps in the BBB We need to specify the IP address of the desktop PC sharing the Internet connection: # route add default gw 192.168.7.1 Now we can check the ping with an Internet server IP address or with a domain name: # ping 172.217.16.68 PING 172.217.16.68 (172.217.16.68) 56(84) bytes of data. 64 bytes from 172.217.16.68: icmp_req=1 ttl=53 time=41.9 ms 64 bytes from 172.217.16.68: icmp_req=2 ttl=53 time=51.0 ms 64 bytes from 172.217.16.68: icmp_req=3 ttl=53 time=58.3 ms ... # ping www.google.com PING www.google.com (216.58.208.228) 56(84) bytes of data. 64 bytes from par10s22-in-f228.1e 100.net (216.58.208.228): icmp_req=1 ttl=52 time=48.5 ms 64 bytes from par10s22-in-f4.1e100.net (216.58.208.228): icmp_req=2 ttl=53 time=47.0 ms 64 bytes from par10s22-in-f4.1e100.net (216.58.208.228): icmp_req=3 ttl=53 time=47.6 ms ... Note that the route command applies only to current session. The configuration is lost after reboot. To make permanent the access to the gateway we should update the file /etc/network/interfaces adding the default gateway. However, if we take a look at that file we can see that it’s already defined there: # tail /etc/network/interfaces # wpa-psk "password" # Ethernet/RNDIS gadget (g_ether) # ... or on host side, usbnet and random hwaddr # Note on some boards, usb0 is automaticly setup with an init script iface usb0 inet static address 192.168.7.2 netmask 255.255.255.0 network 192.168.7.0 gateway 192.168.7.1 Data communication through power lines using a system based on BeagleBone 149/180 It doesn’t work because in the BBB there is a custom initial script that enables the USB with a basic configuration without reading the interfaces file. Thus, for our basic configuration we can even replace the previous route command by ifup with similar results: # ping www.google.com ping: unknown host www.google.com # ifup usb0 # ping www.google.com PING www.google.es (172.217.16.67) 56(84) bytes of data. 64 bytes from par03s13-in-f3.1e100.net (172.217.16.67): icmp_req=1 ttl=53 time=46.3 ms 64 bytes from par03s13-in-f3.1e100.net (172.217.16.67): icmp_req=2 ttl=52 time=44.3 ms ... A difference between these two commands is that ifup automatically synchronizes the clock with an NTP server after some seconds (see next sections for more information about NTP). 7.4.3 Date time management The BBB doesn’t have a battery to keep a RTC (Real Time Clock). Thus, it always starts with a predefined date: # date Sun Mar 1 20:46:26 UTC 2015 Having the proper date and time is convenient when using make because it uses the file time stamps to check if there is a change in the source code beyond the date of the compiled binary and then recompile it. We can manually set the clock time with the date command but if an Internet connection is available a more comfortable way to synchronize it is via a NTP server. We can use the ntpdate command and a public NTP server (http://www.pool.ntp.org/en/): # date Sun Mar 1 20:46:26 UTC 2015 # ntpdate europe.pool.ntp.org 10 Jun 17:28:13 ntpdate[1220]: step time server 193.145.15.15 offset 40336754.693955 sec # date Fri Jun 10 17:28:36 UTC 2016 Note: if the Internet access is available at boot-time the ntpdate is executed automatically and the clock synchronized at start-up. By default, ntpdate assumes the UTC+0 time zone. To change it to the local time zone we can use the interactive command tzselect which asks for the local country and then give the steps to configure it permanently. For example this is the response for Spain: # tzselect Please identify a location so that time zone rules can be set correctly. ... You can make this change permanent for yourself by appending the line TZ='Europe/Madrid'; export TZ to the file '.profile' in your home directory; then log out and log in again. ... So next step is to edit the .profile as indicated. One simple way to do so is as follows: # echo "TZ='Europe/Madrid'; export TZ" >> ~/.profile 150/180 Data communication through power lines using a system based on BeagleBone Be careful: the appending operator ‘>>’ MUST be used to don’t overwrite the existing .profile contents. Then close the current session with logout, reopen it again and execute the date command: # date Fri Jun 10 19:33:15 CEST 2016 Now the clock is properly synchronized using the local time zone (CEST instead of UTC). If an Internet connection is not available we can manually set the date ant time we the date command. Note that the default input format is [MMDDhhmm[[CC]YY][.ss]] (see date --help): # date 0713120016 Wed Jul 13 12:00:00 CEST 2016 7.5 Source code edition For source code edition we have many strategies: •Edit and compile the code directly in the BBB •Edit the code in the desktop PC, send it to the BBB and then compile it there •Edit the code in the desktop PC using a shared folder (located in the PC, in the BBB or elsewhere) and compile it in the BBB •Edit the code and compile it in the desktop PC (cross-compilation), then send the binary to the BBB In this project the option of editing the code in the desktop PC through a shared folder and compile it in the BBB was chosen because its simplicity in management and maintenance: it allows to have the source code in the desktop PC where it is easier to manage (edit, backup…) than in the BBB. 7.6 Sending files to the BBB The direct transfer from the PC to the BBB has also been used in some occasion because its simplicity. For instance a simple way is using the pscp tool that comes with Putty. Assume you have a hello.c in your C:\dev\hello folder and the Putty installed on D:\Archivos de programa\Putty. To send the file to the BBB you can use: C:\dev\hello>"D:\Archivos de programa\Putty\pscp" main.c [email protected]:main.c main.c | 0 kB | 0.1 kB/s | ETA: 00:00:00 | 100% Then with Putty you can see the transferred file in the BBB: root@beaglebone:~# ls -l total 4 -rw-r--r-- 1 root root 99 Jun 10 18:12 main.c The pscp tool allows transferring a complete folder too. In the BBB create first a folder to keep the project files (e.g. mkdir projects). Then send all the files from the desktop PC C:\dev\hello folder: C:\dev>"D:\Archivos de programa\Putty\pscp" -r hello [email protected]:projects main.c | 0 kB | 0.1 kB/s | ETA: 00:00:00 | 100% You can see now all the project files in the BBB proper folder: Data communication through power lines using a system based on BeagleBone 151/180 root@beaglebone:~# find . ./.lesshst ./.bashrc ./.profile ./.bash_history ./projects ./projects/hello ./projects/hello/main.c The advantage of this method is that it doesn’t require any specific configuration task. The drawback is that it’s inefficient and slow. 7.7 Sharing files A better strategy for the plc-cape project is to use shared resources: •it avoids redundant and prone-to-error copy/paste processes •we have always the up-to-date version of the code in both the Desktop PC and the BBB •using logical shared resource names instead of hard-paths to physical media makes the maintenance easier. For example the project can be easily relocated 7.7.1 Sharing files through SAMBA SAMBA is a convenient way to share files because supported by both Windows XP and Ubuntu. To share a folder in Windows XP just right click on it, select the option Sharing and Security... and then the option Share this folder on the network, specifying a public name for it12 (e.g. plc-cape-src): Figure 98. Resource sharing dialog in Windows XP 12 More information on How to use the Simple File Sharing feature to share files in Windows XP is available in https://support.microsoft.com/en-us/kb/304040 152/180 Data communication through power lines using a system based on BeagleBone We can also use a batch file to automate the procedure. For example the following batch (init_env.cmd) would create a shared resource plc-cape-src pointing to the source code in a USB Pen drive in F: (“slow” flash media) while the binary generation is done in the HDD C: (fast hard disk drive) and shared as plc-cape- bin: init_env.cmd @echo off echo Sharing resources... net share plc-cape-bin=C:\dev\bin\beaglebone\plc-cape-bin net share plc-cape-src=F:\dev\src\beaglebone\plc-cape-src echo Resources shared pause To share a folder in Ubuntu we have a similar procedure within the Nautilus file explorer. In the BBB we will use the mount command to connect to the shared folder: # mkdir /mnt/dev # mount -t cifs //192.168.7.1/dev /mnt/dev -o user=,password= # find /mnt/dev /mnt/dev /mnt/dev/hello /mnt/dev/hello/main.c 7.7.2 Sharing files through NFS NFS is another protocol to share files commonly used on Linux-based systems. To share a resource in Ubuntu we have to add the shared resources to /etc/exports. For example, this will be the line to share a folder /home/my-user-name/dev: /home/my-user-name/dev 192.168.7.0/255.255.255.0(rw,sync,no_subtree_check) Then we need to request a refreshing of the NFS server exports: $ sudo exportfs -a In the BBB we will use a mount command like this: # mkdir /mnt/dev # mount 192.168.7.1:/home/my-user-name/dev /mnt/dev # find /mnt/dev /mnt/dev /mnt/dev/hello /mnt/dev/hello/main.c Data communication through power lines using a system based on BeagleBone 153/180 8 Annex III. Getting started with the development environment Assuming that a Desktop PC and the BBB are configured as described in the Annex II. Connection between a Desktop PC and the BBB, this chapter describes how to set up the development environment to be able to develop and compile the plc-cape framework. 8.1 Tree structure 8.1.1 Source code The source code is distributed among these folders: •+common: common resources (*.h headers with public declarations, *.mk shared makefiles, etc.) to be used by any application, library or plugin belonging to the plc-cape framework •drivers: source code of the modified drivers. The aim of the code there is to optimize performance of low-level operations and minimize the overall impact to other running processes, taking advantage of the BBB and PlcCape board specific features •libraries: source code for the reusable static libraries (*.a) •plugins: source code of the reusable dynamic libraries (*.so). Plugins are grouped among predefined categories •applications: source code of the standalone executables developed for specific purposes •tools: sources corresponding to other external tools used in the project (e.g. Octave modules) •env: bash scripts, batch files and other resources to simplify the setup of the development environment Figure 99. Source code tree