Update Iot.js
[platform/upstream/iotjs.git] / tools / test / run_pass / test_spi.js
1 /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 var assert = require('assert');
17 var Spi = require('spi');
18
19 var spi = new Spi();
20
21 //  mcp3008 test
22 var channel = 0;
23 var spi0 = spi.open({
24   device: '/dev/spidev0.0'
25 }, function() {
26   var mode = (8 + channel) << 4;
27   var tx = [1, mode, 0];
28   var rx = [0, 0, 0];
29
30   spi0.transferSync(tx, rx);
31   console.log(((rx[1] & 0x03) << 8) + rx[2]);
32
33   setTimeout(function() {
34     spi0.transfer(tx, rx, function(err) {
35       assert.equal(err, null);
36       assert.equal(rx.length, 3);
37
38       var value = ((rx[1] & 0x03) << 8) + rx[2];
39       console.log(value);
40
41       spi0.close();
42     });
43   }, 500);
44 });
45
46 // Buffer test
47 var spi1 = spi.open({device: '/dev/spidev0.0'}, function() {
48   var data = 'Hello IoTjs';
49   var tx = new Buffer(data);
50   var rx = new Buffer(11);
51
52   this.transferSync(tx, rx);
53   var value = '';
54   for (var i = 0; i < 11; i++) {
55     value += String.fromCharCode(rx[i]);
56   }
57   console.log(value);
58   assert.equal(value, data);
59
60   setTimeout(function() {
61     spi1.transfer(tx, rx, function(err) {
62       assert.equal(err, null);
63       assert.equal(rx.length, 11);
64
65       var value = '';
66       for (var i = 0; i < 11; i++) {
67         value += String.fromCharCode(rx[i]);
68       }
69       console.log(value);
70       assert.equal(value, data);
71
72       spi1.close();
73     });
74   }, 500);
75 });