forked from EwoudvanUijthoven/BEESM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharduino_web_server.py
347 lines (331 loc) · 12.3 KB
/
arduino_web_server.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#Download/install the latest version of Python 2 from https://www.python.org/ftp/python/2.7.8/python-2.7.8.msi
#32-bit installs is fine as we have encountered other libraries/modules that only offered 32-bit versions.
#####################################
#####################################
#####################################
import cherrypy
import logging
import platform
import os
import re
import subprocess
import tempfile
import urllib
from optparse import OptionParser
import sys
import glob
import json
import serial
# import syslog
import itertools
import time
import threading
import urllib3
###################################################
logging.basicConfig(level=logging.DEBUG)
# arduino_cmd = '"C:/Program Files/Arduino IDE/Arduino IDE"'
arduino_cmd = '"C:/Program Files (x86)/Arduino/arduino"'
###################################################
###################################################
#shoutdown the server
def shutdown():
cherrypy.engine.exit()
###################################################
#detect the port automatically
def serial_ports():
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
###################################################
portList = serial_ports()
if not portList:
print("List is empty-main! Please connect micro-controller!")
os.system("pkill -f arduino_web_server.py")
for i in portList:
print("Port Name:"+i)
port = i
arduData = None
###################################################
###################################################
def get_arduino_command():
global arduino_cmd
if not arduino_cmd:
if platform.system() == "Darwin":
arduino_cmd_guesses = ["/Applications/Arduino.app/Contents/MacOS/Arduino"]
elif platform.system() == "Windows":
arduino_cmd_guesses = [
"c:\Program Files\Arduino\Arduino_debug.exe",
"c:\Program Files\Arduino\Arduino.exe",
'"c:\Program Files (x86)\Arduino\Arduino_debug.exe"',
'"c:\Program Files (x86)\Arduino\Arduino.exe"'
]
else:
arduino_cmd_guesses = []
for guess in arduino_cmd_guesses:
if os.path.exists(guess):
logging.info("Found Arduino command at %s", guess)
arduino_cmd = guess
break
else:
logging.info("Couldn't find Arduino command; hoping it's on the path!")
arduino_cmd = "arduino"
return arduino_cmd
###################################################
def guess_port_name():
portname = None
if platform.system() == "Windows":
# If python version is 2.7 (or any other 2.x version)
if sys.version_info.major == 2:
import _winreg as winreg
# If python version is 3.10 (or any other 3.x version)
elif sys.version_info.major == 3:
import winreg
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM")
for i in itertools.count():
try:
portname = winreg.EnumValue(key, i)[1]
except WindowsError:
break
else:
ttys = [filename for filename in os.listdir("/dev")
if (filename.startswith("tty") or filename.startswith("cu."))
and not "luetooth" in filename]
ttys.sort(key=lambda k:(k.startswith("cu."), k))
if ttys:
portList = serial_ports()
for i in portList:
print("Port Name:"+i)
portname = i
logging.info("Guessing port name as %s", portname)
return portname
parser = OptionParser()
parser.add_option("--port", dest="port", help="Upload to serial port named "
"PORT", metavar="PORT")
parser.add_option("--board", dest="board", help="Board definition to use", metavar="BOARD")
parser.add_option("--command", dest="cmd", help="Arduino command name", metavar="CMD")
###################################################
###########serial monitor + web socket#############
###################################################
def arduCherry():
global arduData
time.sleep(2)
while True:
if (arduData != None and arduData.is_open):
try:
msgArdu = arduData.readline()
print("###")
print("CherryPy recieved: ")
print(msgArdu)
###parser
#for set and get with wifi shield
'''msg = msgArdu.split()
if msg[0] == "Waiting":
funcSet_port1()
else:
funcSet_port2()'''
#for set and get without wifi shield
'''str = msgArdu.split()
#print str[0]
if str[0] == "set":
funcSet(str[1], str[2])
break
elif str[0] == "setRGB":
funcSetRgb(str[1], str[2], str[3], str[4])
break
elif str[0] == "setTV":
funcSetTv(str[1], str[2])
break
elif str[0] == "get":
funcGet(str[1])
break'''
#
'''for temp in str:
print str[0]'''
###parser END
sendWebSocketMsg(json.dumps({"type":"outputMsg", "value": msgArdu}))
except TypeError:
time.sleep(1)
except UnicodeDecodeError:
pass
except:
closePort()
time.sleep(1)
openPort()
else:
time.sleep(1)
###################################################
def funcSet(str1, str2):
name = str1
value = str2
http = urllib3.PoolManager()
http.request("POST", "http://baall-server-2.informatik.uni-bremen.de/api/set?id="+name+"&value="+value)
#####################
def funcSetRgb(str1, str2, str3, str4):
name = str1
valueR = str2
valueG = str3
valueB = str4
http = urllib3.PoolManager()
http.request("POST", "http://baall-server-2.informatik.uni-bremen.de/api/setRGB?id="+name+"&r="+valueR+"&g="+valueG+"&b="+valueB)
#####################
def funcSetTv(str1, str2):
namePro = "tvProgram"
value = str1
httpPro = urllib3.PoolManager()
httpPro.request("POST", "http://baall-server-2.informatik.uni-bremen.de/api/set?id="+namePro+"&value="+value)
nameVol = "tvVolume"
volume = str2
httpVol = urllib3.PoolManager()
httpVol.request("POST", "http://baall-server-2.informatik.uni-bremen.de/api/set?id="+nameVol+"&value="+volume)
#####################
def funcGet(str1):
name = str1
http = urllib3.PoolManager()
response = http.request("GET", "http://baall-server-2.informatik.uni-bremen.de/api/item/"+name)
#response = http.request("GET", "http://baall-server-2.informatik.uni-bremen.de/api/status")
response_json = json.loads(response.data.decode('utf-8'))
print(response.response_json.status)
return response.response_json.status
###################################################
###################################################
################### parser ########################
###################################################
###################################################
def funcSet_port1(): #for set and get
global arduData
arduData = serial.Serial(port,115200)
return arduData
def funcSet_port2(): #without set and get
global arduData
arduData = serial.Serial(port,9600)
return arduData
###########open and closing the port###############
def openPort():
global arduData
arduData = serial.Serial(port,115200)
###################################################
def closePort():
global arduData
if (arduData != None):
try:
arduData.close()
except:
pass
arduData = None
time.sleep(1)
###################################################
def uploadAndCompile(self, text):
closePort()
print("sketch to upload: " + text.decode('utf-8'))
options, args = parser.parse_args()
dirname = tempfile.mkdtemp()
sketchname = os.path.join(dirname, os.path.basename(dirname)) + ".ino"
f = open(sketchname, "wb")
f.write(text)
f.close()
print("created sketch at %s" % (sketchname,))
compile_args = [
options.cmd or get_arduino_command(),
"--upload",
"--port",
options.port or guess_port_name(),
]
if options.board:
compile_args.extend([
"--board",
options.board
])
compile_args.append(sketchname)
print("Uploading with %s" % (" ".join(compile_args)))
print("***")
# Arduino output will be shown in the BEESM output
rc = subprocess.Popen(" ".join(compile_args), stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
#####################
#to show compiling and verifying as well as uploading in the BEESM output
sendWebSocketMsg(json.dumps({"type":"compiling", "value": "Compiling..."}))
while True:
line = rc.stdout.readline()
sendWebSocketMsg(json.dumps({"type":"outputCon", "value": line.decode('utf-8')}))
if (line.decode('utf-8').startswith("Global variables use")):
sendWebSocketMsg(json.dumps({"type":"uploading", "value": "Uploading..."}))
if not line:
break
#####################
(output, err) = rc.communicate()
rc_status = rc.wait()
print("Command output : ", output)
print("Error output : ", err)
print("Command exit status/return code: ", rc_status)
print("***")
print("***")
msg = json.dumps({"output":output.decode('utf-8'), "error":err.decode('utf-8'),"status":rc_status})
openPort()
return msg
###################################################
###################################################
############# Web Socket Connection ###############
###################################################
###################################################
def sendWebSocketMsg(msg):
for conn in SUBSCRIBERS:
try:
conn.send(msg)
except:
pass
###################################################
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import WebSocket, EchoWebSocket
WebSocketPlugin(cherrypy.engine).subscribe()
cherrypy.tools.websocket = WebSocketTool()
SUBSCRIBERS = set()
class Publisher(WebSocket):
def __init__(self, *args, **kw):
WebSocket.__init__(self, *args, **kw)
SUBSCRIBERS.add(self)
###################################################
class ArduHandler(object): #SimpleHTTPServer.SimpleHTTPRequestHandler
#just to check the websocket connection
@cherrypy.expose
def ws(self):
pass
@cherrypy.expose
def socket(self, msg):
pass
#####################
@cherrypy.expose
def index(self):
return "Hello ALL!"
@cherrypy.expose
def upload(self):
length = cherrypy.request.headers['Content-Length']
text = cherrypy.request.body.read(int(length))
output = uploadAndCompile(self, text)
cherrypy.response.headers['Access-Control-Allow-Origin'] = "*"
return output
if __name__ == '__main__':
serial_ports()
if not portList:
print("List is empty-cherry! Please connect micro-controller!")
os.system("pkill -f arduino_web_server.py")
print("Blockly-Arduino can now be accessed at http://127.0.0.1:8090/")
thread = threading.Thread(target=arduCherry)
thread.daemon = True
thread.start()
cherrypy.config.update({'server.socket_host':"127.0.0.1", 'server.socket_port': 8090})
cherrypy.quickstart(ArduHandler(), '/',
config={'/ws': {'tools.websocket.on': True,
'tools.websocket.handler_cls': Publisher}})