Browse Source

First attempt at a service with python

master
John Shaver 1 year ago
parent
commit
8bfc406e85
3 changed files with 217 additions and 0 deletions
  1. 67
    0
      main.js
  2. 65
    0
      miccontrol.c
  3. 85
    0
      service.py

+ 67
- 0
main.js View File

@@ -0,0 +1,67 @@
1
+const GPIO = require("onoff").Gpio;
2
+const WS = require("ws");
3
+
4
+const HEARTBEAT_INT = 400;
5
+
6
+const button = new GPIO(4, "in", "both", {debounceTimeout: 30, activeLow: true});
7
+const ledOnAir = new GPIO(24, "low");
8
+const ledReady = new GPIO(23, "low");
9
+
10
+const ws = new WS('ws://10.0.0.4:2000');
11
+
12
+let currentID = 0;
13
+
14
+let heartBeat;
15
+
16
+ws.on('open', () => {
17
+
18
+  button.watch((e, value) => {
19
+    if(e) {
20
+      console.error("Error on button watch:", e);
21
+      return;
22
+    }
23
+    if(value) {
24
+      ws.send(JSON.stringify({type: 'button-press'}));
25
+    } else {
26
+        ws.send(JSON.stringify({type: 'button-release'}));
27
+    }
28
+
29
+    ledOnAir.write(value, (e) => e && console.error("Error writing to led: ", e));
30
+  });
31
+  heartBeat = setInterval(() => {
32
+    button.read((e, buttonState) => {
33
+      console.log("Button state!", buttonState);
34
+      if(e) {
35
+        return console.error("Error reading button state!", e);
36
+      }
37
+      ws.send(JSON.stringify({
38
+        type: 'button-update', 
39
+        body: {buttonState}
40
+      }));
41
+    });
42
+  }, 400);
43
+  ledReady.write(1, console.error);
44
+});
45
+
46
+ws.on('error', (e) => {
47
+  console.error(e);
48
+  cleanup();
49
+  process.exit();
50
+});
51
+
52
+function cleanup() {
53
+  ledOnAir.unexport();
54
+  ledReady.unexport();
55
+  button.unexport();
56
+  ws.close();
57
+  if(heartBeat) {
58
+    cancelInterval(heartBeat);
59
+    heartBeat = null;
60
+  }
61
+}
62
+
63
+process.on('SIGINT', () => {
64
+  cleanup();
65
+});
66
+
67
+

+ 65
- 0
miccontrol.c View File

@@ -0,0 +1,65 @@
1
+/*
2
+ * miccontrol.c
3
+ * Copyright (C) 2018 jshaver <jshaver@je-laptop>
4
+ *
5
+ * Distributed under terms of the MIT license.
6
+ */
7
+
8
+#include "stdio.h"
9
+#include "pulse/pulseaudio.h"
10
+
11
+const char *NAME = "miccontrol";
12
+
13
+static pa_context *context = NULL;
14
+static pa_mainloop_api *mainloop_api = NULL;
15
+static pa_mainloop *mainloop = NULL;
16
+
17
+void querySources(pa_context *c, void *userdata);
18
+void handleSourceList(struct pa_context *c, const pa_source_info *i, int eol, void *userdata);
19
+
20
+int main() {
21
+  int ret = 1;
22
+  mainloop = pa_mainloop_new();
23
+  mainloop_api = pa_mainloop_get_api(mainloop);
24
+  context = pa_context_new(mainloop_api, NULL);
25
+  pa_context_set_state_callback(context, querySources, NULL);
26
+  pa_context_connect(context, NULL, 0, NULL);
27
+  //pa_operation_unref(getSourceOp);
28
+  
29
+  pa_mainloop_run(mainloop, &ret);
30
+
31
+  pa_context_unref(context);
32
+  pa_mainloop_free(mainloop);
33
+
34
+  return ret;
35
+}
36
+
37
+void querySources(pa_context *c, void *userdata) {
38
+  if(pa_context_get_state(context) != PA_CONTEXT_READY) {
39
+    return;
40
+  }
41
+  pa_operation *getSourceOp = NULL;
42
+  getSourceOp = pa_context_get_source_info_list(context, handleSourceList, NULL);
43
+  if(!getSourceOp) {
44
+  } else {
45
+    pa_operation_state_t state = pa_operation_get_state(getSourceOp);
46
+    switch(state) {
47
+      case PA_OPERATION_RUNNING:
48
+        break;
49
+      case PA_OPERATION_DONE:
50
+        break;
51
+      case PA_OPERATION_CANCELLED:
52
+    }
53
+  }
54
+
55
+}
56
+
57
+void handleSourceList(pa_context *c, const pa_source_info *i, int eol, void *userdata) {
58
+  printf("Callback called...\n");
59
+  printf("eol is %d\n", eol);
60
+  printf(i->description);
61
+  printf("\n");
62
+  
63
+  return;
64
+}
65
+

+ 85
- 0
service.py View File

@@ -0,0 +1,85 @@
1
+#! /usr/bin/env python
2
+# -*- coding: utf-8 -*-
3
+
4
+from pulsectl import Pulse
5
+import SocketServer
6
+from threading import Thread
7
+
8
+LISTEN_ON = ("10.0.0.4", 2000)
9
+
10
+def main():
11
+    pulse = Pulse('mic-control')
12
+
13
+    sources = pulse.source_list()
14
+
15
+    sourceNumber = getSourceSelection(sources)
16
+    
17
+
18
+    try:
19
+        server = SocketServer.TCPServer(LISTEN_ON, RequestHandler)
20
+        server.serve_forever()
21
+    except KeyboardInterrupt:
22
+        server.shutdown()
23
+        server.server_close()
24
+    except:
25
+        server.shutdown()
26
+        server.server_close()
27
+
28
+
29
+def getSourceSelection(sources):
30
+    sourceCount = len(sources) - 1
31
+    error = False
32
+    while True:
33
+        message = error if error else "Please select a source: "
34
+        print(message)
35
+        for i, source in enumerate(sources):
36
+            print "%i: %s" % (i, source.description)  
37
+        selection = raw_input("Enter a number[0-%i]:" % sourceCount)
38
+        print("")
39
+        try :
40
+            return getInt(selection, sourceCount)
41
+        except InputError as e:
42
+            error = e.message
43
+
44
+def getInt(value, sourceCount):
45
+
46
+    number = 0
47
+    try:
48
+        number = int(value)
49
+    except ValueError as e:
50
+        raise InputError("Enter only a number...")
51
+
52
+    if number not in range(0, sourceCount):
53
+        raise InputError("Not a valid option...")
54
+
55
+    return number
56
+
57
+class RequestHandler(SocketServer.StreamRequestHandler):
58
+    def handle(self):
59
+
60
+        for line in self.rfile:
61
+            message = line.strip()
62
+            if message in messageTypes:
63
+                messageTypes[message]()
64
+            print("message: ".message)
65
+        print("Closed!")
66
+        self.request.close()
67
+
68
+
69
+def buttonPressed():
70
+    print("down!")
71
+
72
+def buttonReleased():
73
+    print("up!")
74
+
75
+messageTypes = {
76
+    'button_press': buttonPressed,
77
+    'button_release': buttonReleased,
78
+}
79
+
80
+class InputError(Exception):
81
+    def __init__(self, message):
82
+        self.message = message
83
+
84
+    
85
+main()

Loading…
Cancel
Save