UNPKG

1.96 kBJavaScriptView Raw
1var Servo = require("./servo"),
2 __ = require("./fn");
3
4/**
5 * Gripper
6 *
7 * Supports:
8 * [Parallax Boe-Bot gripper](http://www.parallax.com/Portals/0/Downloads/docs/prod/acc/GripperManual-v3.0.pdf)
9 *
10 * [DFRobot LG-NS](http://www.dfrobot.com/index.php?route=product/product&filter_name=gripper&product_id=628#.UCvGymNST_k)
11 *
12 *
13 * @param {[type]} servo [description]
14 */
15
16function Gripper(opts) {
17
18 if (!(this instanceof Gripper)) {
19 return new Gripper(opts);
20 }
21
22 // Default options mode, assume only when opts is a pin number
23 if (typeof opts === "number") {
24 opts = {
25 servo: {
26 pin: opts,
27 range: [0, 180]
28 },
29 scale: [0, 10]
30 };
31 }
32
33 // Default set() args to 0-10
34 this.scale = opts.scale || [0, 10];
35
36 // Setup servo
37 // Allows pre-constructed servo or creating new servo.
38 // Defaults for new Servo creation fall back to Servo defaults
39 this.servo = opts.servo instanceof Servo ?
40 opts.servo : new Servo(opts.servo);
41}
42
43[
44 /**
45 * open Open the gripper
46 *
47 * @return {Object} this
48 */
49 {
50 name: "open",
51 args: function() {
52 return this.servo.range[0];
53 }
54 },
55 /**
56 * close Close the gripper
57 *
58 * @return {Object} this
59 */
60 {
61 name: "close",
62 args: function() {
63 return this.servo.range[1];
64 }
65 },
66 /**
67 * set Set the gripper's open width
68 *
69 * @param {Number} 0-10, 0 is closed, 10 is open
70 *
71 * @return {Object} this
72 */
73 {
74 name: "set",
75 args: function(position) {
76 // Map/Scale position value to a value within
77 // the servo's lo/hi range
78 return Math.floor(
79 __.map(
80 position,
81 this.scale[0], this.scale[1],
82 this.servo.range[1], this.servo.range[0]
83 )
84 );
85 }
86 }
87].forEach(function(api) {
88 Gripper.prototype[api.name] = function() {
89 return this.servo.to(
90 api.args.apply(this, [].slice.call(arguments))
91 );
92 };
93});
94
95module.exports = Gripper;