forked from stetsmando/pi-camera
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (71 loc) · 2.17 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const Execute = require('./lib/Execute');
const FLAGS = require('./flags');
const OPTS = require('./options');
class PiCamera {
constructor(config) {
// Ensure config is an object
config = config || {};
if (!config.mode) {
throw new Error('PiCamera requires a mode to be created');
}
// Set the mode prop
this.mode = config.mode;
// Remove mode and set config
delete config.mode;
this.config = config;
}
/*
* Getter
*/
get(prop) {
if (!this.config[prop]) {
throw new Error(`${ prop } isn't set on current object!`);
}
return this.config[prop];
}
/*
* Setter
*/
set(prop, value) {
this.config[prop] = value;
return this.config[prop];
}
// Take a picture
snap() {
if (this.mode !== 'photo') {
throw new Error(`snap() can only be called when Pi-Camera is in 'photo' mode`);
}
return Execute.run(Execute.cmd('raspistill', this.configToArray()));
}
// Take a picture and return it in Data URL format (data:image/jpg;base64,...)
async snapDataUrl(maxBuffer = 1024*1024*10) {
if (this.mode !== 'photo') {
throw new Error(`snapDataUrl() can only be called when Pi-Camera is in 'photo' mode`);
}
this.config.output = '-';
const image = await Execute.run(Execute.cmd('raspistill', this.configToArray()), {encoding: 'binary', maxBuffer: maxBuffer});
let data = Buffer.from(image, 'binary').toString('base64');
return 'data:image/jpg;base64,' + data;
}
// Record a video
record() {
if (this.mode !== 'video') {
throw new Error(`record() can only be called when Pi-Camera is in 'video' mode`);
}
return Execute.run(Execute.cmd('raspivid', this.configToArray()));
}
}
// Takes internal config object and return array version
PiCamera.prototype.configToArray = function() {
let configArray = []
Object.keys(this.config).forEach((key, i) => {
// Only include flags if they're set to true
if (FLAGS.includes(key) && this.config[key]) {
configArray.push(`--${key}`)
} else if (OPTS.includes(key)) {
configArray.push(`--${key}`, this.config[key])
}
})
return configArray;
}
module.exports = PiCamera;