Skip to content

Commit ad291ce

Browse files
committed
Merge branch 'program-persistence' into develop
2 parents 1cf7357 + 6ccaf65 commit ad291ce

30 files changed

+250
-311
lines changed

MPU6050.py

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1-
from __future__ import print_function
21
"""This program handles the communication over I2C
32
between a Raspberry Pi and a MPU-6050 Gyroscope / Accelerometer combo.
43
Made by: MrTijn/Tijndagamer
54
Released under the MIT License
65
Copyright 2015
76
"""
87

9-
import smbus2 as smbus
108
import time
9+
import smbus2 as smbus
1110

1211
class MPU6050:
1312

@@ -88,10 +87,9 @@ def read_i2c_word(self, register):
8887

8988
value = (high << 8) + low
9089

91-
if (value >= 0x8000):
90+
if value >= 0x8000:
9291
return -((65535 - value) + 1)
93-
else:
94-
return value
92+
return value
9593

9694
# MPU-6050 Methods
9795

@@ -120,7 +118,7 @@ def set_accel_range(self, accel_range):
120118
# Write the new range to the ACCEL_CONFIG register
121119
self.bus.write_byte_data(self.address, self.ACCEL_CONFIG, accel_range)
122120

123-
def read_accel_range(self, raw = False):
121+
def read_accel_range(self, raw=False):
124122
"""Reads the range the accelerometer is set to.
125123
If raw is True, it will return the raw value from the ACCEL_CONFIG
126124
register
@@ -141,10 +139,9 @@ def read_accel_range(self, raw = False):
141139
return 8
142140
elif raw_data == self.ACCEL_RANGE_16G:
143141
return 16
144-
else:
145-
return -1
142+
return -1
146143

147-
def get_accel_data(self, g = False):
144+
def get_accel_data(self, g=False):
148145
"""Gets and returns the X, Y and Z values from the accelerometer.
149146
If g is True, it will return the data in g
150147
If g is False, it will return the data in m/s^2
@@ -174,13 +171,11 @@ def get_accel_data(self, g = False):
174171
y = y / accel_scale_modifier
175172
z = z / accel_scale_modifier
176173

177-
if g is True:
178-
return {'x': x, 'y': y, 'z': z}
179-
elif g is False:
174+
if g is False:
180175
x = x * self.GRAVITIY_MS2
181176
y = y * self.GRAVITIY_MS2
182177
z = z * self.GRAVITIY_MS2
183-
return {'x': x, 'y': y, 'z': z}
178+
return {'x': x, 'y': y, 'z': z}
184179

185180
def set_gyro_range(self, gyro_range):
186181
"""Sets the range of the gyroscope to range.
@@ -193,7 +188,7 @@ def set_gyro_range(self, gyro_range):
193188
# Write the new range to the ACCEL_CONFIG register
194189
self.bus.write_byte_data(self.address, self.GYRO_CONFIG, gyro_range)
195190

196-
def read_gyro_range(self, raw = False):
191+
def read_gyro_range(self, raw=False):
197192
"""Reads the range the gyroscope is set to.
198193
If raw is True, it will return the raw value from the GYRO_CONFIG
199194
register.
@@ -214,8 +209,7 @@ def read_gyro_range(self, raw = False):
214209
return 1000
215210
elif raw_data == self.GYRO_RANGE_2000DEG:
216211
return 2000
217-
else:
218-
return -1
212+
return -1
219213

220214
def get_gyro_data(self):
221215
"""Gets and returns the X, Y and Z values from the gyroscope.
@@ -249,9 +243,9 @@ def get_gyro_data(self):
249243

250244
def get_all_data(self):
251245
"""Reads and returns all the available data."""
252-
temp = get_temp()
253-
accel = get_accel_data()
254-
gyro = get_gyro_data()
246+
temp = self.get_temp()
247+
accel = self.get_accel_data()
248+
gyro = self.get_gyro_data()
255249

256250
return [accel, gyro, temp]
257251

@@ -267,4 +261,4 @@ def get_all_data(self):
267261
if abs(gyro_data['z']) > mpu.GYRO_THRESHOLD_Z:
268262
dz = gyro_data['z'] * dt
269263
z = z + dz
270-
print( "z: ", z, end="\r")
264+
print("z: ", z, end="\r")

_programs.json

Lines changed: 1 addition & 0 deletions
Large diffs are not rendered by default.

api.py

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from tinydb.operations import delete
1212
from cachetools import cached, TTLCache
1313
from coderbot import CoderBot
14-
from program import ProgramEngine
14+
from program import ProgramEngine, Program
1515
from config import Config
1616

1717
bot_config = Config.get()
@@ -92,24 +92,19 @@ def get_info():
9292
prog_engine = ProgramEngine.get_instance()
9393

9494
# Programs and Activities databases
95-
programs = TinyDB("data/programs.json")
9695
activities = TinyDB("data/activities.json")
9796

98-
query = Query()
99-
10097
## Robot control
10198

10299
def stop():
103100
bot.stop()
104101
return 200
105102

106103
def move(data):
107-
print(data)
108104
bot.move(speed=data["speed"], elapse=data["elapse"])
109105
return 200
110106

111107
def turn(data):
112-
print(data)
113108
bot.turn(speed=data["speed"], elapse=data["elapse"])
114109
return 200
115110

@@ -158,31 +153,24 @@ def updateFromPackage():
158153
## Programs
159154

160155
def saveProgram(data, overwrite):
161-
print(overwrite)
162-
if programs.search(query.name == data["name"]) == []:
163-
programs.insert(data)
164-
return 200
165-
else:
166-
# Disallow overwriting a default program
167-
if programs.search((query.name == data["name"]) & (query.default == "True")):
168-
return "defaultOverwrite"
169-
# Overwrite existing program with the same name
170-
else:
171-
if overwrite == "1":
172-
programs.update(data, query.name == data["name"])
173-
return 200
174-
else:
175-
return "askOverwrite"
156+
existing_program = prog_engine.load(data["name"])
157+
if existing_program and not overwrite:
158+
return "askOverwrite"
159+
elif existing_program and existing_program.is_default() == True:
160+
return "defaultOverwrite"
161+
program = Program(name=data["name"], code=data["code"], dom_code=data["dom_code"])
162+
prog_engine.save(program)
163+
return 200
176164

177165
def loadProgram(name):
178-
return programs.search(query.name == name)[0], 200
166+
existing_program = prog_engine.load(name)
167+
return existing_program.as_dict(), 200
179168

180169
def deleteProgram(data):
181-
programs.remove(query.name == data["name"])
182-
170+
prog_engine.delete(data["name"])
183171

184172
def listPrograms():
185-
return programs.all()
173+
return prog_engine.prog_list()
186174

187175

188176
## Activities

cnn_classifier.py

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,8 @@
2020
This module implements the CNNClassifier class, which is the interface for
2121
using an existing and trained CNN model.
2222
"""
23-
from __future__ import absolute_import
24-
from __future__ import division
25-
from __future__ import print_function
26-
27-
import time
2823
import logging
2924

30-
import operator
3125
import numpy as np
3226
import tensorflow as tf
3327

@@ -41,17 +35,17 @@ def __init__(self, model_file, label_file, input_layer="input", output_layer="fi
4135
self.input_width=input_width
4236
input_name = "import/" + input_layer
4337
output_name = "import/" + output_layer
44-
self._input_operation = self._graph.get_operation_by_name(input_name);
45-
self._output_operation = self._graph.get_operation_by_name(output_name);
38+
self._input_operation = self._graph.get_operation_by_name(input_name)
39+
self._output_operation = self._graph.get_operation_by_name(output_name)
4640
self._session = tf.Session(graph=self._graph)
4741
self._graph_norm = tf.Graph()
4842
with self._graph_norm.as_default():
4943
image_mat = tf.placeholder(tf.float32, None, name="image_rgb_in")
5044
float_caster = tf.cast(image_mat, tf.float32)
51-
dims_expander = tf.expand_dims(float_caster, 0);
45+
dims_expander = tf.expand_dims(float_caster, 0)
5246
resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
5347
normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std], name="image_norm_out")
54-
self._input_operation_norm = self._graph_norm.get_operation_by_name("image_rgb_in")
48+
self._input_operation_norm = self._graph_norm.get_operation_by_name("image_rgb_in")
5549
self._output_operation_norm = self._graph_norm.get_operation_by_name("image_norm_out")
5650
self._sess_norm = tf.Session(graph=self._graph_norm)
5751

@@ -77,16 +71,13 @@ def read_tensor_from_image_file(self, file_name, input_height=299, input_width=2
7771
file_reader = tf.read_file(file_name, input_name)
7872

7973
if file_name.endswith(".png"):
80-
image_reader = tf.image.decode_png(file_reader, channels = 3,
81-
name='png_reader')
74+
image_reader = tf.image.decode_png(file_reader, channels=3, name='png_reader')
8275
elif file_name.endswith(".gif"):
83-
image_reader = tf.squeeze(tf.image.decode_gif(file_reader,
84-
name='gif_reader'))
76+
image_reader = tf.squeeze(tf.image.decode_gif(file_reader, name='gif_reader'))
8577
elif file_name.endswith(".bmp"):
8678
image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader')
8779
else:
88-
image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
89-
name='jpeg_reader')
80+
image_reader = tf.image.decode_jpeg(file_reader, channels=3, name='jpeg_reader')
9081

9182
float_caster = tf.cast(image_reader, tf.float32)
9283
dims_expander = tf.expand_dims(float_caster, 0);
@@ -114,13 +105,13 @@ def classify_image(self,
114105
image_file_or_mat,
115106
top_results=3):
116107
t = None
117-
if type(image_file_or_mat) == str:
108+
if isinstance(image_file_or_mat, str):
118109
t = self.read_tensor_from_image_file(file_name=image_file_or_mat)
119110
else:
120111
t = self.read_tensor_from_image_mat(image_file_or_mat)
121112

122113
results = self._session.run(self._output_operation.outputs[0],
123-
{self._input_operation.outputs[0]: t})
114+
{self._input_operation.outputs[0]: t})
124115

125116
top_results = min(top_results, len(self._labels))
126117
results = np.squeeze(results)

cnn_manager.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ def delete_model(self, model_name):
7373
try:
7474
os.remove(MODEL_PATH + "/" + model_name + ".pb")
7575
os.remove(MODEL_PATH + "/" + model_name + ".txt")
76-
except:
77-
logging.warning("model files not found: " + model_name)
76+
except Exception:
77+
logging.warning("model files not found: %s", model_name)
7878
del self._models[model_name]
7979
self._save_model_meta()
8080

@@ -103,12 +103,12 @@ def wait_train_jobs(self):
103103
def load_model(self, model_name):
104104
model_info = self._models.get(model_name)
105105
if model_info:
106-
return CNNClassifier(model_file = MODEL_PATH + "/" + model_name + ".pb",
107-
label_file = MODEL_PATH + "/" + model_name + ".txt",
106+
return CNNClassifier(model_file=MODEL_PATH + "/" + model_name + ".pb",
107+
label_file=MODEL_PATH + "/" + model_name + ".txt",
108108
output_layer=model_info["output_layer"],
109-
input_height = int(model_info["image_height"]),
110-
input_width = int(model_info["image_width"]))
111-
109+
input_height=int(model_info["image_height"]),
110+
input_width=int(model_info["image_width"]))
111+
return None
112112
class TrainThread(threading.Thread):
113113

114114
def __init__(self, manager, model_name, architecture, image_tags, photos_metadata, training_steps, learning_rate):

0 commit comments

Comments
 (0)