-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·761 lines (579 loc) · 20 KB
/
main.py
File metadata and controls
executable file
·761 lines (579 loc) · 20 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
#!/usr/bin/python3
import json
import os
os.environ["DISPLAY"] = ":0.0"
import time
from threading import Thread
from kivy.properties import AliasProperty, ObjectProperty, NumericProperty
from kivy.animation import Animation
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.vector import Vector
import sys
sys.path.insert(0, 'Kivy/')
sys.path.insert(0, 'Kivy/Scenes/')
sys.path.insert(0, 'Libraries')
from Kivy.Scenes import AdminScreen
from apscheduler.schedulers.background import BackgroundScheduler
from dpea.utilities import MixPanel
import TemperatureSensor
import Stepper
from kivy.logger import Logger
Logger.setLevel("DEBUG")
import logging
logging.getLogger().setLevel(logging.DEBUG)
"""
Globals
"""
MIXPANEL_TOKEN = "02f0373e5a3d6354fbc9d41d6b3a002a"
#SCALE = 7.77
SCALE = 1
STEPS_PER_INCH = 25.4 * SCALE
BALL_DIAMETER = 2.25 * STEPS_PER_INCH
offset_right = 0
offset_left = 0
offset_v_right = 0
offset_v_left = 0
STOP_DISTANCE = 2.41 * STEPS_PER_INCH
START_INSET = 10 * SCALE
BACKUP_DISTANCE = -4.5 * STEPS_PER_INCH
LIFT_DISTANCE = 3 * STEPS_PER_INCH
VERTICAL_SPEED = 800
LIFT_SPEED = 40
STOPPING_SPEED = 7.5
HORIZONTAL_SPEED = 36
MICRO_STEPS_HORIZONTAL = 16
MICRO_STEPS_VERTICAL = 16
STEPS_PER_UNIT = 25
ACCELERATION = 40
RIGHT_HORIZONTAL_STEPPER = Stepper.Stepper(port=0, microSteps=MICRO_STEPS_HORIZONTAL, stepsPerUnit=STEPS_PER_UNIT,
speed=HORIZONTAL_SPEED, accel=ACCELERATION)
RIGHT_VERTICAL_STEPPER = Stepper.Stepper(port=1, microSteps=MICRO_STEPS_VERTICAL, speed=VERTICAL_SPEED,
accel=ACCELERATION)
LEFT_HORIZONTAL_STEPPER = Stepper.Stepper(port=2, microSteps=MICRO_STEPS_HORIZONTAL, stepsPerUnit=STEPS_PER_UNIT,
speed=HORIZONTAL_SPEED, accel=ACCELERATION)
LEFT_VERTICAL_STEPPER = Stepper.Stepper(port=3, microSteps=MICRO_STEPS_VERTICAL, speed=VERTICAL_SPEED,
accel=ACCELERATION)
GESTURE_MIN_DELTA = 25
GESTURE_MAX_DELTA = 75
"""
Main functions
"""
def quit_all():
"""Called upon exiting UI, frees all steppers"""
RIGHT_HORIZONTAL_STEPPER.free()
RIGHT_VERTICAL_STEPPER.free()
LEFT_VERTICAL_STEPPER.free()
LEFT_HORIZONTAL_STEPPER.free()
quit()
def are_horizontal_busy():
"""Check to see if the horizontal steppers are currently busy (moving)"""
return RIGHT_HORIZONTAL_STEPPER.isBusy() or LEFT_HORIZONTAL_STEPPER.isBusy()
def are_vertical_busy():
"""
Check to see if the vertical steppers are busy
:return: True if busy, False if not
"""
return RIGHT_VERTICAL_STEPPER.isBusy() or LEFT_VERTICAL_STEPPER.isBusy()
def set_vertical_speed(speed):
"""
Set the speed of the vertical steppers
:param speed: Speed to set the vertical steppers at
:return: None
"""
LEFT_VERTICAL_STEPPER.setSpeed(speed)
RIGHT_VERTICAL_STEPPER.setSpeed(speed)
def set_horizontal_speed(speed):
"""
Set the speed of the horizontal steppers
:param speed: Speed to set the horizontal steppers at
:return: None
"""
LEFT_HORIZONTAL_STEPPER.setSpeed(speed)
RIGHT_HORIZONTAL_STEPPER.setSpeed(speed)
def set_vertical_pos(pos):
"""
Set the vertical position of the vertical steppers
:param pos: The position to both of the vertical stepper to
:return: None
"""
RIGHT_VERTICAL_STEPPER.startGoToPosition(pos + offset_v_right * SCALE)
LEFT_VERTICAL_STEPPER.startGoToPosition(pos + offset_v_left * SCALE)
while are_vertical_busy():
continue
def set_vertical_poss(pos_l, pos_r):
"""
Set the vertical position (relative) of the vertical steppers
:param pos_l: Relative move amount for left vertical stepper
:param pos_r: Relative move amount for right vertical stepper
:return: None
"""
LEFT_VERTICAL_STEPPER.startGoToPosition(pos_l + offset_v_left * SCALE)
RIGHT_VERTICAL_STEPPER.startGoToPosition(pos_r + offset_v_right * SCALE)
while are_vertical_busy():
continue
def set_vertical_pos_rel(r):
RIGHT_VERTICAL_STEPPER.startRelativeMove(r)
LEFT_VERTICAL_STEPPER.startRelativeMove(r)
while are_vertical_busy():
continue
def set_horizontal_pos(pos):
"""
Set the horizontal position of the horizontal steppers
:param pos: Position for each horizontal stepper to start a relative move to
:return: None
"""
LEFT_HORIZONTAL_STEPPER.startGoToPosition(pos)
RIGHT_HORIZONTAL_STEPPER.startGoToPosition(pos)
while are_horizontal_busy():
continue
def set_horizontal_poss(pos_l, pos_r):
"""
Set the horizontal positions of the steppers
:param pos_l: Position of the left horizontal stepper
:param pos_r: Position of the right horizontal stepper
:return: None
"""
LEFT_HORIZONTAL_STEPPER.startGoToPosition(pos_l)
RIGHT_HORIZONTAL_STEPPER.startGoToPosition(pos_r)
while are_horizontal_busy():
continue
def set_horizontal_pos_rel(r):
"""
Start a relative horizontal move
:param r: Amount to perform a horizontal move
:return: None
"""
LEFT_HORIZONTAL_STEPPER.startRelativeMove(r)
RIGHT_HORIZONTAL_STEPPER.startRelativeMove(r)
while are_horizontal_busy():
continue
def home():
"""
Home all of the steppers
:return:
"""
LEFT_VERTICAL_STEPPER.home(0)
RIGHT_VERTICAL_STEPPER.home(0)
LEFT_HORIZONTAL_STEPPER.home(0)
RIGHT_HORIZONTAL_STEPPER.home(0)
def send_start_event(num_left, num_right):
"""
Send the number of balls selected on both sides to MixPanel
:param num_left: Number of balls selected on the left side
:param num_right: Number of balls selected on the right side
:return: None
"""
global mixpanel
mixpanel.setEventName("Start")
mixpanel.addProperty("Left ball count", num_left)
mixpanel.addProperty("Right ball count", num_right)
mixpanel.sendEvent()
def check_temperature():
"""
Check the temperature from the slush engine temperature sensor and send the data to MixPanel
:return:
"""
global mixpanel
temp_sensor = TemperatureSensor.TemperatureSensor()
temp = temp_sensor.getTemperatureInFahrenheit()
mixpanel.setEventName("Temperature")
mixpanel.addProperty("Temperature", temp)
mixpanel.sendEvent()
def new_scoop():
"""
New scooped initiated, gets the number of balls on each side and calls the perspective function to control pickups
:return: None
"""
num_left = sm.get_screen('main').cradle.num_left()
num_right = sm.get_screen('main').cradle.num_right()
if num_left + num_right == 0:
return
stop_balls()
set_vertical_speed(LIFT_SPEED)
if num_left + num_right == 5:
scoop_left(num_left)
scoop_right(num_right)
while are_horizontal_busy():
continue
else:
scoop_both(num_left, num_right)
set_vertical_speed(VERTICAL_SPEED)
release_both()
home()
time.sleep(5)
sm.get_screen('main').unpause()
def scoop_left(num):
"""
Scoop the balls on the left, doesn't wait for the last move to complete
:param num: Number of balls to scoop on the left
:return: None
"""
if num == 0:
return
p = STOP_DISTANCE - START_INSET + offset_left * SCALE + BALL_DIAMETER * num
set_horizontal_speed(HORIZONTAL_SPEED)
LEFT_HORIZONTAL_STEPPER.startGoToPosition(p)
while are_horizontal_busy():
continue
LEFT_VERTICAL_STEPPER.startGoToPosition(LIFT_DISTANCE)
while are_vertical_busy():
continue
LEFT_HORIZONTAL_STEPPER.startRelativeMove(BACKUP_DISTANCE)
def scoop_right(num):
"""
Scoop the balls on the right, doesn't wait for the last move to complete
:param num: Number of balls to scoop on the right
:return: None
"""
if num == 0:
return
p = STOP_DISTANCE - START_INSET + offset_right * SCALE + BALL_DIAMETER * num
set_horizontal_speed(HORIZONTAL_SPEED)
RIGHT_HORIZONTAL_STEPPER.startGoToPosition(p)
while are_horizontal_busy():
continue
RIGHT_VERTICAL_STEPPER.startGoToPosition(LIFT_DISTANCE)
while are_vertical_busy():
continue
RIGHT_HORIZONTAL_STEPPER.startRelativeMove(BACKUP_DISTANCE)
def scoop_both(num_left, num_right):
"""
Scoop both sides
:param num_left: Number of balls on the left side to be scooped
:param num_right: Number of balls on the right side to be scooped
:return: None
"""
p_r = STOP_DISTANCE - START_INSET + offset_right * SCALE + BALL_DIAMETER * num_right
p_l = STOP_DISTANCE - START_INSET + offset_left * SCALE + BALL_DIAMETER * num_left
set_horizontal_speed(HORIZONTAL_SPEED)
if num_right > 0:
RIGHT_HORIZONTAL_STEPPER.startGoToPosition(p_r)
if num_left > 0:
LEFT_HORIZONTAL_STEPPER.startGoToPosition(p_l)
while are_horizontal_busy():
continue
if num_right > 0:
RIGHT_VERTICAL_STEPPER.startGoToPosition(LIFT_DISTANCE)
if num_left > 0:
LEFT_VERTICAL_STEPPER.startGoToPosition(LIFT_DISTANCE)
while are_vertical_busy():
continue
if num_right > 0:
RIGHT_HORIZONTAL_STEPPER.startRelativeMove(BACKUP_DISTANCE)
if num_left > 0:
LEFT_HORIZONTAL_STEPPER.startRelativeMove(BACKUP_DISTANCE)
while are_horizontal_busy():
continue
def release_both():
"""
Release both of the vertical steppers
:return: None
"""
set_vertical_pos(0)
def stop_balls():
"""
Stop the balls movement, by bringing horiz. steppers out the uo to stop all balls
:return: None
"""
# move vertical steppers up
set_vertical_pos(LIFT_DISTANCE)
# slowly move the horizontal steppers into the middle/stopping positions
set_horizontal_speed(STOPPING_SPEED)
set_horizontal_poss(STOP_DISTANCE + offset_left * SCALE, STOP_DISTANCE + offset_right * SCALE)
time.sleep(1)
# back away slowly
set_horizontal_speed(STOPPING_SPEED / 10)
set_horizontal_pos_rel(-1 * SCALE)
set_horizontal_speed(STOPPING_SPEED / 5)
set_horizontal_pos_rel(-4 * SCALE)
# bring the vertical steppers down
set_vertical_pos(0)
"""
PauseScene functions
"""
def pause(text, sec):
"""
Pause the screen for a set amount of time
:param text: Text to display while the pause screen is visible
:param sec: Number of seconds to pause the screen for
:return: None
"""
sm.transition.direction = 'left'
sm.current = 'pauseScene'
sm.current_screen.ids.pauseText.text = text
load = Animation(size=(10, 10), duration=0) + \
Animation(size=(150, 10), duration=sec)
load.start(sm.current_screen.ids.progressBar)
def transition_back(original_scene):
"""
Transition back to the previous scene
:param original_scene: The previous scene to transition back to
:return: None
"""
sm.transition.direction = 'right'
sm.current = original_scene
def scoop_balls_thread(*largs):
main = sm.get_screen('main')
num_left = main.cradle.num_left()
num_right = main.cradle.num_right()
if num_right == 0 and num_left == 0:
return
pause_time = 5 + 26 + 2 * max(num_left, num_right)
if main.is_paused:
return
main.pause(pause_time)
send_start_event(num_left, num_right)
Thread(target=new_scoop).start()
sm = ScreenManager()
class Ball(Widget):
interactive = True
down_exists = False
down = ObjectProperty((0, 0))
def transform_point(self, v):
v -= Vector(self.parent.pos)
v = v.rotate(-self.parent.rotation)
v += Vector(self.parent.pos)
return v
def clear(self):
self.down = (0, 0)
Ball.down_exists = False
def pushed(self, touch):
pos = touch.pos
v = self.transform_point(Vector(pos))
if self.collide_point(v.x, v.y) and (not Ball.down_exists) and Ball.interactive:
self.down = v
Ball.down_exists = True
def moved(self, touch):
p = self.parent
pos = touch.pos
v = self.transform_point(Vector(pos))
if self.down != (0, 0):
d = v - Vector(self.down)
if d.length() >= GESTURE_MAX_DELTA:
if d.x >= GESTURE_MIN_DELTA:
self.parent.parent.ball_right(p)
self.clear()
elif d.x <= -GESTURE_MIN_DELTA:
self.parent.parent.ball_left(p)
self.clear()
def released(self, touch):
p = self.parent
pos = touch.pos
v = self.transform_point(Vector(pos))
if self.down != (0, 0):
d = v - Vector(self.down)
if d.x >= GESTURE_MIN_DELTA:
self.parent.parent.ball_right(p)
self.clear()
return
elif d.x <= -GESTURE_MIN_DELTA:
self.parent.parent.ball_left(p)
self.clear()
self.parent.parent.ball_touched(p)
self.clear()
class BallString(Widget):
rotation = ObjectProperty(0)
ball = ObjectProperty(None)
name = ObjectProperty("middle")
ROT_LEFT = -35
ROT_RIGHT = 35
ROT_DOWN = 0
a_down = Animation(rotation=ROT_DOWN, t="out_quad")
a_left = Animation(rotation=ROT_LEFT, t="out_quad")
a_right = Animation(rotation=ROT_RIGHT, t="out_quad")
r = ObjectProperty(ROT_DOWN)
def down(self):
Animation.cancel_all(self)
BallString.a_down.start(self)
self.r = BallString.ROT_DOWN
def left(self):
Animation.cancel_all(self)
BallString.a_left.start(self)
self.r = BallString.ROT_LEFT
def right(self):
Animation.cancel_all(self)
BallString.a_right.start(self)
self.r = BallString.ROT_RIGHT
class Cradle(Widget):
def num_left(self):
return sum(ball.r == BallString.ROT_LEFT for ball in self.get_balls())
def num_right(self):
return sum(ball.r == BallString.ROT_RIGHT for ball in self.get_balls())
def reset_balls(self):
balls = self.get_balls()
self.ball_down(balls[0])
self.ball_down(balls[-1])
def get_balls(self):
return self.children
def ball_right(self, ball_string):
if ball_string.r == BallString.ROT_LEFT:
self.ball_down(ball_string)
return
balls = self.get_balls()[::-1]
i = balls.index(ball_string)
for ball in balls[i:]:
if ball.name == "left":
ball.down()
else:
ball.right()
sm.get_screen("main").update_button()
def ball_left(self, ball_string):
if ball_string.r == BallString.ROT_RIGHT:
self.ball_down(ball_string)
return
balls = self.get_balls()
i = balls.index(ball_string)
for ball in balls[i:]:
if ball.name == "right":
ball.down()
else:
ball.left()
sm.get_screen("main").update_button()
def ball_down(self, ball_string):
if ball_string.r == BallString.ROT_LEFT:
balls = self.get_balls()[::-1]
i = balls.index(ball_string)
for ball in balls[i:]:
if ball.r != BallString.ROT_LEFT:
break
ball.down()
elif ball_string.r == BallString.ROT_RIGHT:
balls = self.get_balls()
i = balls.index(ball_string)
for ball in balls[i:]:
if ball.r != BallString.ROT_RIGHT:
break
ball.down()
sm.get_screen("main").update_button()
def ball_touched(self, ball_string):
if ball_string.r == BallString.ROT_DOWN:
if ball_string.name == "left":
self.ball_left(ball_string)
elif ball_string.name == "middle-left":
self.ball_left(ball_string)
elif ball_string.name == "middle":
self.ball_right(ball_string)
elif ball_string.name == "middle-right":
self.ball_right(ball_string)
elif ball_string.name == "right":
self.ball_right(ball_string)
else:
self.ball_down(ball_string)
sm.get_screen("main").update_button()
class MyApp(App):
def build(self):
"""
Called upon launching application
:return: Screen Manager
"""
return sm
Builder.load_file('Kivy/Scenes/main.kv')
Builder.load_file('Kivy/Libraries/DPEAButton.kv')
Builder.load_file('Kivy/Scenes/PauseScene.kv')
Builder.load_file('Kivy/Scenes/AdminScreen.kv')
Window.clearcolor = (1, 1, 1, 1) # (WHITE)
"""
MainScreen Class
"""
class MainScreen(Screen):
cradle = ObjectProperty(None)
execute = ObjectProperty(None)
hint = ObjectProperty(None)
progress = ObjectProperty(None)
wait = ObjectProperty(None)
is_paused = False
fade_out = Animation(opacity=0, t="out_quad")
fade_in = Animation(opacity=1, t="out_quad")
@staticmethod
def admin_action():
sm.current = 'admin'
def scoop_call_back(self):
Clock.schedule_once(scoop_balls_thread, 0)
def set_visible(self, widget):
if self.is_paused:
return
Animation.cancel_all(self.hint)
Animation.cancel_all(self.execute)
#Animation.cancel_all(self.progress)
Animation.cancel_all(self.wait)
MainScreen.fade_out.start(self.hint)
MainScreen.fade_out.start(self.execute)
#MainScreen.fade_out.start(self.progress)
MainScreen.fade_out.start(self.wait)
Animation.cancel_all(widget)
MainScreen.fade_in.start(widget)
def pause(self, delay):
Ball.interactive = False
self.set_visible(self.wait)
self.is_paused = True
#self.progress.value = 0
#a = Animation(value=100, duration=delay)
#a.start(self.progress)
def unpause(self):
Ball.interactive = True
self.cradle.reset_balls()
self.is_paused = False
self.set_visible(self.hint)
def update_button(self):
l = self.cradle.num_left()
r = self.cradle.num_right()
if l == 0 and r == 0:
self.set_visible(self.hint)
else:
self.set_visible(self.execute)
class MyProgressBar(Widget):
value = NumericProperty(0)
variables_dict = {}
if os.path.exists("variables.json"):
with open("variables.json") as o:
variables_dict = json.loads(o.read())
for v in variables_dict.keys():
globals()[v] = variables_dict[v]
class VariableChanger(Widget):
name = ObjectProperty(None)
label = ObjectProperty(None)
def get_value(self):
return globals().get(self.name, None)
def inc_value(self):
self.set_value(self.get_value() + 1)
def dec_value(self):
self.set_value(self.get_value() - 1)
def set_value(self, value):
globals()[self.name] = value
variables_dict[self.name] = value
self.label.text = self.name + ": " + str(self.get_value())
self.save_value()
def save_value(self):
with open("variables.json", "w+") as o:
o.write(json.dumps(variables_dict))
# ////////////////////////////////////////////////////////////////
# // PauseScene and Admin Scene Class //
# ////////////////////////////////////////////////////////////////
class adminFunctionsScreen(Screen):
@staticmethod
def quit_action():
quit_all()
@staticmethod
def back_action():
home()
sm.current = 'main'
sm.add_widget(MainScreen(name='main'))
sm.add_widget(AdminScreen.AdminScreen(name='admin'))
sm.add_widget(adminFunctionsScreen(name='adminFunctionsScreen'))
mixpanel = MixPanel("Newtons Cradle", MIXPANEL_TOKEN)
temperature_refresh = BackgroundScheduler()
temperature_refresh.add_job(check_temperature, 'interval', minutes=5)
if __name__ == "__main__":
try:
home()
mixpanel.setEventName("Project Initialized")
mixpanel.sendEvent()
temperature_refresh.start()
MyApp().run()
except KeyboardInterrupt:
quit_all()