forked from vlachoudis/bCNC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CNCPendant.py
161 lines (137 loc) · 3.95 KB
/
CNCPendant.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# -*- coding: latin1 -*-
# $Id: CNCPendant.py,v 1.3 2014/10/15 15:04:48 bnv Exp bnv $
#
# Author: [email protected]
# Date: 06-Oct-2014
__author__ = "Vasilis Vlachoudis"
__email__ = "[email protected]"
import os
import sys
#import cgi
import json
import threading
import urllib
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
try:
import BaseHTTPServer as HTTPServer
except ImportError:
import http.server as HTTPServer
HOSTNAME = "localhost"
port = 8080
httpd = None
prgpath = os.path.abspath(os.path.dirname(sys.argv[0]))
#==============================================================================
# Simple Pendant controller for CNC
#==============================================================================
class Pendant(HTTPServer.BaseHTTPRequestHandler):
#----------------------------------------------------------------------
def log_message(self, fmt, *args):
# Only requests to the main page log them, all other ignore
if args[0].startswith("GET / "):
HTTPServer.BaseHTTPRequestHandler.log_message(self, fmt, *args)
#----------------------------------------------------------------------
def do_HEAD(self, rc=200, content="text/html"):
self.send_response(rc)
self.send_header("Content-type", content)
self.end_headers()
#----------------------------------------------------------------------
def do_GET(self):
"""Respond to a GET request."""
if "?" in self.path:
page,arg = self.path.split("?",1)
arg = dict(urlparse.parse_qsl(arg))
else:
page = self.path
arg = None
#print self.path,type(self.path)
#print page
#print arg
if page == "/send":
if arg is None: return
for key,value in arg.items():
if key=="gcode":
for line in value.split('\n'):
httpd.app.queue.put(line+"\n")
elif key=="cmd":
httpd.app.pendant.put(urllib.unquote(value))
#send empty response so browser does not generate errors
self.do_HEAD(200, "text/text")
self.wfile.write("")
elif page == "/state":
self.do_HEAD(200, "text/text")
self.wfile.write(json.dumps(httpd.app._pos))
elif page == "/config":
self.do_HEAD(200, "text/text")
snd = {}
snd["rpmmax"] = httpd.app.get("CNC","spindlemax")
self.wfile.write(json.dumps(snd))
elif page == "/icon":
if arg is None: return
self.do_HEAD(200, "image/gif")
filename = os.path.join(
os.path.abspath(
os.path.dirname(sys.argv[0])),
"icons",
arg["name"]+".gif")
try:
f = open(filename,"rb")
self.wfile.write(f.read())
f.close()
except:
pass
else:
self.mainPage(page[1:])
# ---------------------------------------------------------------------
def mainPage(self, page):
global prgpath
#handle certain filetypes
filetype = page.rpartition('.')[2]
if filetype == "css": self.do_HEAD(content="text/css")
elif filetype == "js": self.do_HEAD(content="text/javascript")
else: self.do_HEAD()
if page == "": page = "index.html"
try:
f = open(os.path.join(prgpath,page),"r")
self.wfile.write(f.read())
f.close()
except IOError:
self.wfile.write("""<!DOCTYPE html>
<html>
<head>
<title>Errortitle</title>
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=yes" />
</head>
<body>
Page not found.
</body>
</html>
""")
# -----------------------------------------------------------------------------
def _server(app):
global httpd
server_class = HTTPServer.HTTPServer
try:
httpd = server_class(('', port), Pendant)
httpd.app = app
httpd.serve_forever()
except:
httpd = None
# -----------------------------------------------------------------------------
def start(app):
global httpd
if httpd is not None: return False
thread = threading.Thread(target=_server, args=(app,))
thread.start()
return True
# -----------------------------------------------------------------------------
def stop():
global httpd
if httpd is None: return False
httpd.shutdown()
httpd = None
return True
if __name__ == '__main__':
start()