Skip to content

Commit fb97a39

Browse files
committed
wip #78
1 parent 935ce9f commit fb97a39

File tree

7 files changed

+423
-53
lines changed

7 files changed

+423
-53
lines changed

.camera.py.swp

32 KB
Binary file not shown.

camera.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,15 @@
1818
############################################################################
1919

2020
import time
21-
import copy
2221
import os
23-
import sys
2422
import math
2523
import json
2624
from PIL import Image as PILImage
2725
try:
2826
from BytesIO import BytesIO
2927
except ImportError:
3028
from io import BytesIO
31-
from threading import Thread, Lock
29+
from threading import Thread
3230
import logging
3331

3432
from cv import camera, image, blob
@@ -145,8 +143,8 @@ def get_next_photo_index(self):
145143

146144
def photo_take(self):
147145
photo_index = self.get_next_photo_index()
148-
filename = PHOTO_PREFIX + str(photo_index) + self._camera.PHOTO_FILE_EXT;
149-
filename_thumb = PHOTO_PREFIX + str(photo_index) + PHOTO_THUMB_SUFFIX + self._camera.PHOTO_FILE_EXT;
146+
filename = PHOTO_PREFIX + str(photo_index) + self._camera.PHOTO_FILE_EXT
147+
filename_thumb = PHOTO_PREFIX + str(photo_index) + PHOTO_THUMB_SUFFIX + self._camera.PHOTO_FILE_EXT
150148
of = open(PHOTO_PATH + "/" + filename, "wb+")
151149
oft = open(PHOTO_PATH + "/" + filename_thumb, "wb+")
152150
im_str = self.get_image_jpeg()
@@ -168,10 +166,10 @@ def video_rec(self, video_name=None):
168166
if video_name is None:
169167
video_index = self.get_next_photo_index()
170168
filename = VIDEO_PREFIX + str(video_index) + self._camera.VIDEO_FILE_EXT;
171-
filename_thumb = VIDEO_PREFIX + str(video_index) + PHOTO_THUMB_SUFFIX + self._camera.PHOTO_FILE_EXT;
169+
filename_thumb = VIDEO_PREFIX + str(video_index) + PHOTO_THUMB_SUFFIX + self._camera.PHOTO_FILE_EXT
172170
else:
173-
filename = VIDEO_PREFIX + video_name + self._camera.VIDEO_FILE_EXT;
174-
filename_thumb = VIDEO_PREFIX + video_name + PHOTO_THUMB_SUFFIX + self._camera.PHOTO_FILE_EXT;
171+
filename = VIDEO_PREFIX + video_name + self._camera.VIDEO_FILE_EXT
172+
filename_thumb = VIDEO_PREFIX + video_name + PHOTO_THUMB_SUFFIX + self._camera.PHOTO_FILE_EXT
175173
try:
176174
#remove previous file and reference in album
177175
os.remove(PHOTO_PATH + "/" + filename)
@@ -231,8 +229,8 @@ def find_line(self):
231229
img = img.erode().dilate()
232230
if int(img._data.mean()) > 127:
233231
img = img.invert()
234-
slices = [0,0,0]
235-
blobs = [0,0,0]
232+
slices = [0, 0, 0]
233+
blobs = [0, 0, 0]
236234
slices[0] = img.crop(0, int(self._camera.out_rgb_resolution[1]/1.2), self._camera.out_rgb_resolution[0], self._camera.out_rgb_resolution[1])
237235
slices[1] = img.crop(0, int(self._camera.out_rgb_resolution[1]/1.5), self._camera.out_rgb_resolution[0], int(self._camera.out_rgb_resolution[1]/1.2))
238236
slices[2] = img.crop(0, int(self._camera.out_rgb_resolution[1]/2.0), self._camera.out_rgb_resolution[0], int(self._camera.out_rgb_resolution[1]/1.5))
@@ -245,7 +243,7 @@ def find_line(self):
245243
if len(blobs[idx]):
246244
coords[idx] = (blobs[idx][0].center[0] * 100) / self._camera.out_rgb_resolution[0]
247245
blob = blobs[idx][0]
248-
img.draw_rect(blob.left, y_offset[idx] + blob.top, blob.right, y_offset[idx] + blob.bottom, (0,255,0), 5)
246+
img.draw_rect(blob.left, y_offset[idx] + blob.top, blob.right, y_offset[idx] + blob.bottom, (0, 255, 0), 5)
249247
self.set_image_cv(img)
250248
return coords
251249

@@ -292,7 +290,7 @@ def path_ahead(self):
292290
blobs = img.binarize(threshold).dilate().find_blobs(minsize=self._path_object_size_min, maxsize=self._path_object_size_max)
293291
coordY = 60
294292
if len(blobs):
295-
obstacle = blob.Blob.sort_distance((image_size[0]/2,image_size[1]), blobs)[0]
293+
obstacle = blob.Blob.sort_distance((image_size[0]/2, image_size[1]), blobs)[0]
296294

297295
logging.info("obstacle:" + str(obstacle.bottom))
298296
coords = img.transform([(obstacle.center[0], obstacle.bottom)], img.get_transform(img.size()[1]))
@@ -305,7 +303,7 @@ def path_ahead(self):
305303

306304
def find_color(self, s_color):
307305
image_size = self._camera.out_rgb_resolution
308-
color = (int(s_color[1:3],16), int(s_color[3:5],16), int(s_color[5:7],16))
306+
color = (int(s_color[1:3], 16), int(s_color[3:5], 16), int(s_color[5:7], 16))
309307
code_data = None
310308
ts = time.time()
311309
img = self.get_image()
@@ -321,12 +319,12 @@ def find_color(self, s_color):
321319
if objects and len(objects):
322320
obj = objects[-1]
323321
bottom = obj.bottom
324-
logging.info("bottom: " + str(obj.center[0]) + " " +str(obj.bottom))
322+
logging.info("bottom: " + str(obj.center[0]) + " " + str(obj.bottom))
325323
coords = bw.transform([(obj.center[0], obj.bottom)], bw.get_transform(bw.size()[1]))
326324
logging.info("coordinates: " + str(coords))
327325
x = coords[0][0]
328326
y = coords[0][1]
329-
dist = math.sqrt(math.pow(fov_offset + (fov_total_y * (image_size[1] - y) / (image_size[1]/1.2)),2) + (math.pow((x-(image_size[0]/2)) * fov_total_x / image_size[0],2)))
327+
dist = math.sqrt(math.pow(fov_offset + (fov_total_y * (image_size[1] - y) / (image_size[1]/1.2)), 2) + (math.pow((x-(image_size[0]/2)) * fov_total_x / image_size[0], 2)))
330328
angle = math.atan2(x - (image_size[0]/2), image_size[1] - y) * 180 / math.pi
331329
logging.info("object found, dist: " + str(dist) + " angle: " + str(angle))
332330
#self.save_image(img.to_jpeg())
@@ -335,7 +333,7 @@ def find_color(self, s_color):
335333

336334
def find_text(self, accept, back_color):
337335
text = None
338-
color = (int(back_color[1:3],16), int(back_color[3:5],16), int(back_color[5:7],16))
336+
color = (int(back_color[1:3], 16), int(back_color[3:5], 16), int(back_color[5:7], 16))
339337
img = self.get_image()
340338
image = img.find_rect(color=color)
341339
if image:

config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
CONFIG_FILE = "coderbot.cfg"
2323

24-
class Config:
24+
class Config(object):
2525

2626
_config = {}
2727

event.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
import logging
21
import threading
3-
from pubsub import pub
2+
from pubsub import pub
43

5-
class EventManager:
4+
class EventManager(object):
65
_instance = None
76
@classmethod
87
def get_instance(cls, node_name=None):
@@ -24,7 +23,7 @@ def register_event_generator(self, generator_func):
2423
generator = threading.Thread(target=generator_func)
2524
self._event_generators.append(generator)
2625
generator.start()
27-
26+
2827
def unregister_listeners(self):
2928
pub.unsubAll()
3029

init.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/python
1+
#!/usr/bin/python3
22
############################################################################
33
# CoderBot, a didactical programmable robot.
44
# Copyright (C) 2014, 2015 Roberto Previtera <info@coderbot.org>

main.py

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import os
2424
import json
2525
import logging
26-
import time
2726
import logging.handlers
2827
import subprocess
2928
import picamera
@@ -38,7 +37,7 @@
3837
from event import EventManager
3938
from conversation import Conversation
4039

41-
from flask import Flask, render_template, request, send_file, redirect, Response, jsonify
40+
from flask import Flask, render_template, request, send_file, Response, jsonify
4241
from flask_babel import Babel
4342
from werkzeug.datastructures import Headers
4443
#from flask_sockets import Sockets
@@ -64,7 +63,7 @@
6463
event = None
6564
conv = None
6665

67-
app = Flask(__name__,static_url_path="")
66+
app = Flask(__name__, static_url_path="")
6867
#app.config.from_pyfile('coderbot.cfg')
6968
babel = Babel(app)
7069
app.debug = False
@@ -86,26 +85,33 @@ def get_locale():
8685
@app.route("/")
8786
def handle_home():
8887
stream_port = cam.stream_port if cam else ""
89-
return render_template('main.html', host=request.host[:request.host.find(':')], stream_port=stream_port, locale = get_locale(), config=app.bot_config, program_level=app.bot_config.get("prog_level", "std"), cam=cam!=None, cnn_model_names=json.dumps([[name] for name in cnn.get_models().keys()]))
88+
return render_template('main.html',
89+
host=request.host[:request.host.find(':')],
90+
stream_port=stream_port,
91+
locale=get_locale(),
92+
config=app.bot_config,
93+
program_level=app.bot_config.get("prog_level", "std"),
94+
cam=cam != None,
95+
cnn_model_names=json.dumps([[name] for name in cnn.get_models().keys()]))
9096

9197
@app.route("/config", methods=["POST"])
9298
def handle_config():
9399
Config.write(request.form)
94100
app.bot_config = Config.get()
95-
return "ok";
101+
return "ok"
96102

97103
@app.route("/wifi", methods=["POST"])
98104
def handle_wifi():
99105
mode = request.form.get("wifi_mode")
100106
ssid = request.form.get("wifi_ssid")
101107
psk = request.form.get("wifi_psk")
102-
logging.info( "mode ", mode, " ssid: ", ssid, " psk: ", psk)
108+
logging.info("mode " + mode +" ssid: " + ssid + " psk: " + psk)
103109
client_params = " \"" + ssid + "\" \"" + psk + "\"" if ssid != "" and psk != "" else ""
104110
logging.info(client_params)
105111
os.system("sudo python wifi.py updatecfg " + mode + client_params)
106112
os.system("sudo reboot")
107113
if mode == "ap":
108-
return "http://coder.bot:8080";
114+
return "http://coder.bot:8080"
109115
else:
110116
return "http://coderbot.locali:8080"
111117

@@ -134,28 +140,24 @@ def handle_bot():
134140
motion.stop()
135141
except:
136142
logging.warning("Camera not present")
137-
pass
138143
elif cmd == "take_photo":
139144
try:
140145
cam.photo_take()
141146
audio.say(app.bot_config.get("sound_shutter"))
142147
except:
143148
logging.warning("Camera not present")
144-
pass
145149
elif cmd == "video_rec":
146150
try:
147151
cam.video_rec()
148152
audio.say(app.bot_config.get("sound_shutter"))
149153
except:
150154
logging.warning("Camera not present")
151-
pass
152155
elif cmd == "video_stop":
153156
try:
154157
cam.video_stop()
155158
audio.say(app.bot_config.get("sound_shutter"))
156159
except:
157160
logging.warning("Camera not present")
158-
pass
159161
elif cmd == "say":
160162
logging.info("say: " + str(param1) + " in: " + str(get_locale()))
161163
audio.say(param1, get_locale())
@@ -176,15 +178,14 @@ def handle_bot():
176178
def handle_bot_status():
177179
return json.dumps({'status': 'ok'})
178180

179-
def video_stream(cam):
180-
181+
def video_stream(a_cam):
181182
while not app.shutdown_requested:
182-
frame = cam.get_image_jpeg()
183+
frame = a_cam.get_image_jpeg()
183184
yield ("--BOUNDARYSTRING\r\n" +
184185
"Content-type: image/jpeg\r\n" +
185186
"Content-Length: " + str(len(frame)) + "\r\n\r\n")
186-
yield(frame)
187-
yield("\r\n")
187+
yield frame
188+
yield "\r\n"
188189

189190
@app.route("/video")
190191
def handle_video():
@@ -209,11 +210,12 @@ def handle_video_stream():
209210
h.add('Cache-Control', 'no-cache, private')
210211
h.add('Pragma', 'no-cache')
211212
return Response(video_stream(cam), headers=h, mimetype="multipart/x-mixed-replace; boundary=--BOUNDARYSTRING")
212-
except: pass
213+
except:
214+
pass
213215

214-
def video_stream_cv(cam):
216+
def video_stream_cv(a_cam):
215217
while not app.shutdown_requested:
216-
frame = cam.get_image_cv_jpeg()
218+
frame = a_cam.get_image_cv_jpeg()
217219
yield ("--BOUNDARYSTRING\r\n" +
218220
"Content-type: image/jpeg\r\n" +
219221
"Content-Length: " + str(len(frame)) + "\r\n\r\n" +
@@ -227,9 +229,8 @@ def handle_video_stream_cv():
227229
h.add('Cache-Control', 'no-cache, private')
228230
h.add('Pragma', 'no-cache')
229231
return Response(video_stream_cv(cam), headers=h, mimetype="multipart/x-mixed-replace; boundary=--BOUNDARYSTRING")
230-
except: pass
231-
232-
232+
except:
233+
pass
233234

234235
@app.route("/photos", methods=["GET"])
235236
def handle_photos():
@@ -240,20 +241,18 @@ def handle_photos():
240241
def handle_photo_get(filename):
241242
logging.info("media filename: " + filename)
242243
mimetype = {'jpg': 'image/jpeg', 'mp4': 'video/mp4'}
243-
video = None
244244
try:
245245
media_file = cam.get_photo_file(filename)
246-
except picamera.exc.PiCameraError:
247-
pass
248-
249-
return send_file(media_file, mimetype=mimetype.get(filename[:-3], 'image/jpeg'), cache_timeout=0)
246+
return send_file(media_file, mimetype=mimetype.get(filename[:-3], 'image/jpeg'), cache_timeout=0)
247+
except picamera.exc.PiCameraError as e:
248+
logging.error("Error: " + str(e))
250249

251250
@app.route("/photos/<filename>", methods=["PUT"])
252251
def handle_photo_put(filename):
253252
logging.info("photo update")
254253
data = request.get_data(as_text=True)
255254
data = json.loads(data)
256-
cam.update_photo({"name": filename, "tag":data["tag"]});
255+
cam.update_photo({"name": filename, "tag":data["tag"]})
257256
return jsonify({"res":"ok"})
258257

259258
@app.route("/photos/<filename>", methods=["DELETE"])
@@ -280,7 +279,7 @@ def handle_program_save():
280279
name = request.form.get('name')
281280
dom_code = request.form.get('dom_code')
282281
code = request.form.get('code')
283-
prog = Program(name, dom_code = dom_code, code = code)
282+
prog = Program(name, dom_code=dom_code, code=code)
284283
app.prog_engine.save(prog)
285284
return "ok"
286285

@@ -336,7 +335,7 @@ def handle_cnn_models_new():
336335
@app.route("/cnnmodels/<model_name>", methods=["GET"])
337336
def handle_cnn_models_status(model_name):
338337
logging.info("cnn_models_status")
339-
model_status = cnn.get_model(model_name=model_name)
338+
model_status = cnn.get_models().get(model_name)
340339

341340
return json.dumps(model_status)
342341

@@ -372,10 +371,13 @@ def run_server():
372371
global motion
373372
global audio
374373
global cnn
374+
global conv
375+
global event
375376
try:
376377
try:
377378
app.bot_config = Config.read()
378-
bot = CoderBot.get_instance(servo=(app.bot_config.get("move_motor_mode")=="servo"), motor_trim_factor=float(app.bot_config.get('move_motor_trim', 1.0)))
379+
bot = CoderBot.get_instance(servo=(app.bot_config.get("move_motor_mode") == "servo"),
380+
motor_trim_factor=float(app.bot_config.get('move_motor_trim', 1.0)))
379381
audio = Audio.get_instance()
380382
audio.say(app.bot_config.get("sound_start"))
381383
try:

0 commit comments

Comments
 (0)