Main /
InterfacingHardwareSpecificsWithNodeAndAccessorsSummaryOne of the challenges when using Accessor with IoT devices is that the hardware sometimes (if not often) is very specific and tailor to the application. Often, we end up using what is available in the specific JS engine and adapt as much as possible. It would be nice to interface the native code that was used when the IoT device was developed and interface it with Accessors. Next section is a procedure to interface a native C code with Accessors. Use Case ScenarioWe want to control a motor from Internet using WebSockets. The motor is controlled by an ARM target (in this case beaglebone black) In this case, we are using a constant to send a command to the target. The commands are as follows 0 - stop 1 - move forward 2 - move backwards For now the speed is constant. Interface ProcedureIn this case, target machine (beaglebone black) has the following nodejs packages
Note: ffi MUST be installed at target, cross compilation does not work. The idea is to use ffi to construct a library that can be used within NodeJs and Accessors C-Interface codeFor this example, the motor is using PWM2 and one of the GPIO's (GPIO72) is controlling the direction; 1 = forward, 0 = backwards. The code that controls the motor would be as follows: #include <stdint.h> #include <stdlib.h> #define EXPORT EXPORT void motorCtrl(int action) { switch(action){ case 0: system( "echo 0 > /sys/class/pwm/pwmchip0/pwm0/enable" ); break; case 1: system( "echo 1 > /sys/class/gpio/gpio72/value" ); system( "echo 1 > /sys/class/pwm/pwmchip0/pwm0/enable" ); system( "echo 3000 > /sys/class/pwm/pwmchip0/pwm0/duty_cycle" ); break; case 3: system( "echo 0 > /sys/class/gpio/gpio72/value" ); system( "echo 1 > /sys/class/pwm/pwmchip0/pwm0/enable" ); system( "echo 3000 > /sys/class/pwm/pwmchip0/pwm0/duty_cycle" ); break; } } Now we create the C library as follows gcc -shared -fpic motorCtrl.c -o libmotorctrl.so NodeJS Interface codeNow we are going to connect a websocket with the library that we just created as follows: var ffi = require('ffi') var libmotorctrl = ffi.Library('./libmotorctrl', { 'motorCtrl': [ '', [ 'int' ] ] }) var WebSocketServer = require('ws').Server , wss = new WebSocketServer({ port: 8080 }) wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { libmotorctrl.motorCtrl(parseInt(message)); }); ws.send('something'); }); When we send commands from Ptolemy, the motor will respond accordingly.
|