legoEv3/save/home/robot/motor2.py
from ev3dev2.motor import *
from ev3dev2.sensor import INPUT_1
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.led import Leds
from ev3dev.core import Sound
from datetime import datetime, timedelta
import time
import threading
from queue import Queue, Empty
print("start t1.py ... ")
print("sys.version", sys.version, "time=" + str(datetime.now()))
class MotorThr(threading.Thread):
""" thread for this motor - handle all operations in this thread
print the motor state, whenever it changes """
running = True;
def __init__(self, mo):
threading.Thread.__init__(self)
self.mot = mo
self.que = Queue()
def run(self):
self.address = self.mot.address
self.count_per_rot = self.mot.count_per_rot
self.commands = self.mot.commands
nxTi = datetime.now()
print(str(nxTi) + " motor " + self.address + "begin count_per_rot=" +
str(self.count_per_rot) + " commands=" + repr(self.mot.commands))
i = 0
j = 0
oSt = ''
while MotorThr.running:
i = i + 1
try:
# if we can get an element from the queue (before timeout) execute it
tiOu = (nxTi - datetime.now()).total_seconds()
w = self.que.get(True, tiOu) if tiOu > 0 else self.que.get(False)
w(self, self.mot, i)
except Empty:
# Timeout, no input in given time
self.state = self.mot.state
self.position = self.mot.position
# self.speed = self.mot.speed
aSt = " state=" + repr(self.state) + " position="+str(self.position) # + " speed="+str(self.speed)
if aSt != oSt:
j = j+1
print(str(datetime.now()) + " motor " + self.address + aSt + " cnt="+str(i)+'/'+str(j))
nxTi = datetime.now() + timedelta(seconds=0.001)
oSt = aSt
self.mot.stop(stop_action = STOP_ACTION_COAST)
print(str(datetime.now()) + " motor " + self.address + ' end')
leds = Leds()
mA = MotorThr(MediumMotor(OUTPUT_A)) # medium motor on output a
mA.start()
for x in range(0, 3):
Sound.play_song((("A5", 'e'),("C4", 'e'), ('E5', 'h'))) # play postouto
leds.set_color("LEFT", "GREEN") # LED colors
leds.set_color("RIGHT", "RED")
mA.que.put(lambda t, m, i: (print(str(datetime.now()), str(i), "half rotate gripper plus"), m.on_for_rotations(SpeedPercent(75), 1.5, block=False) ) ) # half rotation on gripper
time.sleep(1)
mA.que.put(lambda t, m, i: (print(str(datetime.now()) + " rotate stop"), m.stop()))
Sound.play_song((("A5", 'e'),("C4", 'e'), ('E5', 'h')))
leds.set_color("LEFT", "RED")
leds.set_color("RIGHT", "GREEN")
mA.que.put(lambda t, m, i: (print(str(datetime.now()) + " rotate minus"), m.on_for_rotations(SpeedPercent(-75), 1.5, block=False))) # half rotation backward on gripper
time.sleep(1)
mA.que.put(lambda t, m, i: (print(str(datetime.now()) + " rotate stop"), m.stop()))
Sound.speak('what is going on in motor2.py') # speak a little text
leds.set_color("LEFT", "YELLOW")
leds.set_color("RIGHT", "RED")
MotorThr.running = False
leds.set_color("LEFT", "BLACK")
leds.set_color("RIGHT", "BLACK")