def run(self: Detector) -> None: self.camera.start() try: framecount = 0 motion = Motion() for image in self.camera.yield_image(): framecount += 1 if framecount >= self.fastforward: start_time = time.perf_counter() bboxes = motion.detect(image) objects = self.predictor.predict(image, bboxes) end_time = time.perf_counter() elapsed_ms = (end_time - start_time) * 1000 self.camera.clear() self.camera.draw_objects(objects) self.camera.draw_time(elapsed_ms) self.camera.draw_count(len(objects)) self.camera.update() framecount = 0 self.before = image except KeyboardInterrupt: pass finally: self.camera.stop() return
def __init__(self, infile=0): self.cam = cv2.VideoCapture(infile) self.mot = Motion() self.stopped = False Thread(target=self.run, args=()).start()
def __init__(self): super().__init__() #ノード名を宣言 rospy.init_node('OP3Env', anonymous=True) self.rate = rospy.Rate(RATE) action = np.array([ -1.5, 1.5, -1.7, 0.00, 1.7, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ]) # OP3Env.state = np.array([0, 0, 1.8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) OP3Env.state = np.zeros(NUM_STATE) # state更新 sub1 = rospy.Subscriber('gazebo/model_states', ModelStates, callback_get_state) sub2 = rospy.Subscriber('robotis_op3/joint_states', JointState, callback_get_joint_state) reward = 0 self.action_space = gym.spaces.Discrete(NUM_ACTION) self.observation_space = gym.spaces.Box(low=-np.pi, high=np.pi, shape=(NUM_STATE, )) self.Com = Motion(action) self.reset()
def __init__(self): self.kb = KnowledgeBase() self.location = BarcodeServer(self.location_callback) self.flight_path = FlightPath() self.motion = Motion(self.kb) self.node_a = NodeAServer()
def load_modules(self): self._speech = Speech(self.session) self._motion = Motion(self.session) self._tablet = Tablet(self.session) self._face_detection = FaceDetection(self.session, self) self._wave_detection = WavingDetection(self.session) self._audio_player = AudioPlayer(self.session) self._speech_recognition = SpeechRecognition(self.session) self._system = System(self.session)
def motion_window(self): from motion import Motion self.motion_window = tk.Toplevel(self.master) main_window.withdraw() new_window = Window() new_window.center_window(self.motion_window, 675, 590) self.app = Motion(self.motion_window) self.motion_window.protocol( "WM_DELETE_WINDOW", lambda: self.iconify_main_panel(self.motion_window))
def __init__(self, pheromone_map, pos=(0, 0), size=200): self.pos = pos self.pheromone_map = pheromone_map self.ants = [] for i in range(size): ant = Ant(colony_pos=pos, direction=random.choice(Direction.to_list())) ant.motion = Motion(pheromone_map=pheromone_map, ant=ant, direction_distr=[0.7, 0.2, 0.1], pheromone_importance=0.9) self.ants.append(ant)
def __init__(self): self.motionDetected = False; self.relay = Relays(7); self.relay.setAllOff(); self.motion = Motion(0, 3, self); self.light = Light(3, 1000, self); self.temp = Temp(1, 85, self); self.start = time.time(); while True: print('********** Switch Module Starting **********'); time.sleep(5);
def run(self): motion = Motion() try: self._sift = MatchWithSIFT() self._sift.load_refs() except (AttributeError, cv2.error): print("SIFT not available! Won't parse dice!") _run = False _stop = False _sample = False with self.conlock: _run = self._apprun _stop = self._appstop _sample = self._sample while _run: self._cam.start() while self._cam.ready(): with self.conlock: self.conlock.wait_for(lambda: (self._appstop or self._sample)) _sample = self._sample _stop = self._appstop if _stop: break if not _sample: continue motion.roll() frame = None while frame is None: frame = self._cam.get_frame() dice, frame = self._process_image(frame) with self.conlock: self._sample = False with self.reslock: self.dice = dice self.frame = frame self.fresh = True self.reslock.notify() self._cam.stop() with self.conlock: _run = self._apprun
def mappingMode(): try: motionVals = Motion() map_all_inputs(possibleInputs) # mapping all the inputs while True: movementVals = motionVals.get_motion() printInput = check_input( movementVals, possibleInputs ) # every second, check for the current input among all the possible inputs print(printInput) movementVals = [] # reset current motion val time.sleep(1.0) # sleep for 1 second except KeyboardInterrupt: sys.exit()
def ManageMotion(): motion = Motion() while motion.IsActive(): ManageCommands(motion) # Manage motion and gestures motion.GetInformationOnNextFrame() if motion.TimeElapsedSinceLastMotion( ) > config['timeToWaitWhenNoMovementBeforeSleep']: time.sleep(config['timeToSleepWhenNoMovement']) gesture = motion.GetGesture() threading.Thread(target=SendGesture, args=(gesture, )).start() motion.Dispose()
def __init__(self): # Initialize ROS node rospy.init_node("Controller") self.name = "Controller object" self.rate = rospy.Rate(10) # allow node to 'spin' at 10hz rospy.on_shutdown(self.shutdown) # calls this function when Ctrl+C self.motion = Motion() self.sensor = Sensor() self.localizer = Localizer() self.visited_highlights = [] # Boolean for reached goal self.goalReached = False
def __init__(self, dir, color_dir, semantic_dir, audio_dir, motion_dir): color = Color(dir, color_dir, 352, 288, color_space="RGB", mode="average", bins=32) color.load() resnet = ResNet(dir, semantic_dir, 352, 288) resnet.load() audio = Audio(dir, audio_dir, mode="max") audio.load() motion = Motion(dir, motion_dir) motion.load() self.audio = audio self.resnet = resnet self.color = color self.motion = motion
def run(delay, sensor_type, pin, webhook, source, metric_prefix, output, format): sensor = None is_polling = False if sensor_type.startswith('DHT'): pin = int(pin) sensor = Temp(source, metric_prefix, output, sensor_type, pin, format) is_polling = True elif sensor_type == 'HC-SRO': pins = pin.split(',') sensor = Distance(source, metric_prefix, output, sensor_type, int(pins[0]), int(pins[1]), format) is_polling = True elif sensor_type == 'SSM-1': pin = int(pin) sensor = Generic(source, metric_prefix, output, sensor_type, pin, 'Sound') elif sensor_type == 'HC-SR501': pin = int(pin) sensor = Motion(source, metric_prefix, output, sensor_type, pin) elif sensor_type == 'SEO53': pin = int(pin) sensor = Generic(source, metric_prefix, output, sensor_type, pin, 'Vibration') elif sensor_type == 'SEO23': pin = int(pin) sensor = Generic(source, metric_prefix, output, sensor_type, pin, 'Tilt') elif sensor_type == 'YL-69': pin = int(pin) sensor = Moisture(source, metric_prefix, output, sensor_type, pin, 'Moisture', delay) else: sensor = Host(source, metric_prefix, output) is_polling = True while True: sensor.get_info() metrics = sensor.format_metrics() if webhook is not None: send_metrics(metrics, output, webhook, source) else: print(metrics) # check if the senor is something that needs to poll for results based on a delay. if is_polling: time.sleep(delay)
def __init__(self, jerky=False, walking_speed=1): # listen for frame transformations TfTransformer.__init__(self) # initialize motion component of navigation self._motion = Motion() self._sensors = Sensors() self._jerky = jerky self._walking_speed = min(abs(walking_speed), 1) self._logger = Logger("Navigation") # set up obstacle avoidance self._avoiding = False self._obstacle = False self._bumped = False self._bumper = 0 # we're going to send the turtlebot to a point a quarter meter ahead of itself self._avoid_goto = PointStamped() self._avoid_goto.header.frame_id = "/base_footprint" self._avoid_goto.point.x = self._AVOID_DIST self._avoid_target = None self._avoid_turn = None # subscibe to the robot_pose_ekf odometry information self.p = None self.q = None self.angle = 0 self._target_turn_delta = 0 rospy.Subscriber('/robot_pose_ekf/odom_combined', PoseWithCovarianceStamped, self._ekfCallback) # set up navigation to destination data self._reached_goal = True # set up the odometry reset publisher (publishing Empty messages here will reset odom) reset_odom = rospy.Publisher('/mobile_base/commands/reset_odometry', Empty, queue_size=1) # reset odometry (these messages take about a second to get through) timer = time() while time() - timer < 1 or self.p is None: reset_odom.publish(Empty())
def transformMotion(self, signals): self.signals = signals interpolator = Interpolator() n = 64 startTime = None endTime = None for event in self.signals: if startTime == None: startTime = event.getTime() elif startTime > event.getTime(): startTime = event.getTime() if endTime == None: endTime = event.getTime() elif endTime < event.getTime(): endTime = event.getTime() if isinstance(event, RotationEvent): self.recordedRotations.append(event) elif isinstance(event, ButtonEvent): self.recordedButtons.append(event) elif isinstance(event, TouchEvent): self.recordedTouches.append(event) else: pass if startTime is None or endTime is None: raise NotEnoughSignals() #Construct Motion transformedMotion = Motion() transformedMotion.setStartTime(startTime) transformedMotion.setEndTime(endTime) self.addNeutralValues(startTime, endTime) #Rotation Part of Motion result = interpolator.linearInterpolation(self.recordedRotations, n) transformedTime = result[0] transformedSum = result[1] for i in range(len(transformedTime)): event = RotationEvent(transformedTime[i], None, transformedSum[i]) transformedMotion.addEvent(event) #Button Part of Motion result = interpolator.linearInterpolation(self.recordedButtons, n) transformedTime = result[0] transformedValue = result[1] for i in range(len(transformedTime)): event = ButtonEvent(transformedTime[i], transformedValue[i]) transformedMotion.addEvent(event) #Touch Part of Motion touchEventDictionary = self.sortTouches() for touchLocation in touchEventDictionary: result = interpolator.linearInterpolation(touchLocation[1], n) transformedTime = result[0] transformedValue = result[1] for i in range(len(transformedTime)): event = TouchEvent(transformedTime[i], touchLocation[0], transformedValue[i]) transformedMotion.addEvent(event) #Scaling and adjustment self.scaleMotion(transformedMotion) self.adjustValues(transformedMotion) return transformedMotion
# Change on method to receive user's input (laser to finger) # Implemented new logic for processing. # # @version 1.0 # @since 2015-10-08 # First implementation from finger_tracker import FingerTracker from camera import Camera from ocr import demo_word_ocr_cv # need to modify from motion import Motion import time camera = Camera(0) finger_tracker = FingerTracker() motion = Motion() ocr = OCR() ''' get finger point (by FingerTracker object) -> accumulate information about point -> check some motion (by Motion object) -> if line type -> waits for finger disappeared -> get area for letters (by ?? object) -> get word (by OCR object) ''' def loop(): image = camera.getImage() new_point = finger_tracker.getFingerPoint(image) if new_point:
def __init__(self, IO): print('I am a toddler playing in a sandbox') self.IO = IO self.sensors = Sensors(self.IO) self.motion = Motion(self.IO) self.motors = Motors(self.IO)
def ManageMotion(): motion = Motion() # Params to change on the fly cv2.namedWindow('paramMinMaxPalm') cv2.createTrackbar('MAX H', 'paramMinMaxPalm', 1, 255, nothing) cv2.createTrackbar('MAX S', 'paramMinMaxPalm', 1, 255, nothing) cv2.createTrackbar('MAX V', 'paramMinMaxPalm', 1, 255, nothing) cv2.createTrackbar('MIN H', 'paramMinMaxPalm', 1, 255, nothing) cv2.createTrackbar('MIN S', 'paramMinMaxPalm', 1, 255, nothing) cv2.createTrackbar('MIN V', 'paramMinMaxPalm', 1, 255, nothing) cv2.setTrackbarPos('MAX H', 'paramMinMaxPalm', config['hand']['hsv_palm_max'][0]) cv2.setTrackbarPos('MAX S', 'paramMinMaxPalm', config['hand']['hsv_palm_max'][1]) cv2.setTrackbarPos('MAX V', 'paramMinMaxPalm', config['hand']['hsv_palm_max'][2]) cv2.setTrackbarPos('MIN H', 'paramMinMaxPalm', config['hand']['hsv_palm_min'][0]) cv2.setTrackbarPos('MIN S', 'paramMinMaxPalm', config['hand']['hsv_palm_min'][1]) cv2.setTrackbarPos('MIN V', 'paramMinMaxPalm', config['hand']['hsv_palm_min'][2]) cv2.namedWindow('paramSearchRangeHand') cv2.createTrackbar('INC H', 'paramSearchRangeHand', 1, 255, nothing) cv2.createTrackbar('INC S', 'paramSearchRangeHand', 1, 255, nothing) cv2.createTrackbar('INC V', 'paramSearchRangeHand', 1, 255, nothing) cv2.createTrackbar('DEC H', 'paramSearchRangeHand', 1, 255, nothing) cv2.createTrackbar('DEC S', 'paramSearchRangeHand', 1, 255, nothing) cv2.createTrackbar('DEC V', 'paramSearchRangeHand', 1, 255, nothing) cv2.setTrackbarPos('INC H', 'paramSearchRangeHand', config['hand']['hsv_hand_inc'][0]) cv2.setTrackbarPos('INC S', 'paramSearchRangeHand', config['hand']['hsv_hand_inc'][1]) cv2.setTrackbarPos('INC V', 'paramSearchRangeHand', config['hand']['hsv_hand_inc'][2]) cv2.setTrackbarPos('DEC H', 'paramSearchRangeHand', config['hand']['hsv_hand_dec'][0]) cv2.setTrackbarPos('DEC S', 'paramSearchRangeHand', config['hand']['hsv_hand_dec'][1]) cv2.setTrackbarPos('DEC V', 'paramSearchRangeHand', config['hand']['hsv_hand_dec'][2]) frameIdx = 0 currentSliding = "None" timeElapsedSinceLastSlide = time.time() if not motion.IsActive(): print("No camera found") # Debug Palm Tracking (See palm color detection in real time - consuming) motion.debugPalm = False while motion.IsActive(): # Refresh OpenCV Windows cv2.waitKey(1) main.ManageCommands(motion) # Refresh config from param config['hand']['hsv_palm_max'] = [ cv2.getTrackbarPos('MAX H', 'paramMinMaxPalm'), cv2.getTrackbarPos('MAX S', 'paramMinMaxPalm'), cv2.getTrackbarPos('MAX V', 'paramMinMaxPalm') ] config['hand']['hsv_palm_min'] = [ cv2.getTrackbarPos('MIN H', 'paramMinMaxPalm'), cv2.getTrackbarPos('MIN S', 'paramMinMaxPalm'), cv2.getTrackbarPos('MIN V', 'paramMinMaxPalm') ] config['hand']['hsv_hand_inc'] = [ cv2.getTrackbarPos('INC H', 'paramSearchRangeHand'), cv2.getTrackbarPos('INC S', 'paramSearchRangeHand'), cv2.getTrackbarPos('INC V', 'paramSearchRangeHand') ] config['hand']['hsv_hand_dec'] = [ cv2.getTrackbarPos('DEC H', 'paramSearchRangeHand'), cv2.getTrackbarPos('DEC S', 'paramSearchRangeHand'), cv2.getTrackbarPos('DEC V', 'paramSearchRangeHand') ] # Manage motion and gestures motion.GetInformationOnNextFrame() # Infos movement try: cv2.putText( motion.frameDifference, "Elapsed: " + str(motion.TimeElapsedSinceLastMotion()) + "/" + str(config['timeToWaitWhenNoMovementBeforeSleep']), (5, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) cv2.putText( motion.frameDifference, "Movement: " + str(motion.movementRatio) + "/" + str(config['frameDifferenceRatioForMovement']), (5, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) cv2.imshow('Movement detected', motion.frameDifference) except: pass if motion.TimeElapsedSinceLastMotion( ) > config['timeToWaitWhenNoMovementBeforeSleep']: cv2.putText(motion.currentFrame, "SLEEP MODE NO MOVEMENT", (5, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) cv2.imshow('Current Frame', motion.currentFrame) time.sleep(config['timeToSleepWhenNoMovement']) gesture = motion.GetGesture() if gesture.properties['palm']: print("PALM") threading.Thread(target=main.SendGesture, args=(gesture, )).start() # Gesture infos try: #print("Frame: " + str(frameIdx)) frameIdx += 1 #print(gesture.properties) if motion.handTracked is None: cv2.putText(motion.currentFrame, "Seach Palm", (5, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, 200, 1) cv2.imshow('Current Frame', motion.currentFrame) cv2.imshow('Mask from HSV Range', motion.mask_rafined) cv2.putText(motion.currentFrame, "Width: " + str(gesture.recW), (5, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, 200, 1) cv2.putText(motion.currentFrame, "Height: " + str(gesture.recH), (5, 250), cv2.FONT_HERSHEY_SIMPLEX, 1, 200, 1) cv2.putText(motion.currentFrame, "SRatio: " + str(gesture.recH / gesture.recW), (5, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, 200, 1) cv2.rectangle( motion.currentFrame, (gesture.recX, gesture.recY), (gesture.recX + gesture.recW, gesture.recY + gesture.recH), (0, 255, 0), 2) cv2.putText(motion.currentFrame, "MSize: " + str(gesture.moments['m00']), (5, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, 200, 1) cv2.drawContours(motion.currentFrame, [gesture.handContour], 0, (0, 255, 0), 3) cv2.circle(motion.currentFrame, (int(gesture.centerX), int(gesture.centerY)), int(gesture.radius / 1.5), [255, 0, 255], 1) cv2.circle(motion.currentFrame, (int(gesture.centerX), int(gesture.centerY)), int(gesture.radius / 3.2), [255, 0, 255], 1) cv2.putText(motion.currentFrame, "A: " + str(gesture.properties['angle']), (5, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, 200) if gesture.properties['palm']: cv2.putText(motion.currentFrame, "PALM", (5, 400), cv2.FONT_HERSHEY_SIMPLEX, 2, 150, 3) elif gesture.properties['thumbsUp']: cv2.putText(motion.currentFrame, "THUMBS UP", (5, 400), cv2.FONT_HERSHEY_SIMPLEX, 2, 150, 3) elif gesture.properties['thumbsDown']: cv2.putText(motion.currentFrame, "THUMBS DOWN", (5, 400), cv2.FONT_HERSHEY_SIMPLEX, 2, 150, 3) if gesture.properties['slideUp'] or gesture.properties[ 'slideDown'] or gesture.properties[ 'slideRight'] or gesture.properties['slideLeft']: timeElapsedSinceLastSlide = time.time() currentSliding = "UP" if gesture.properties[ 'slideUp'] else "DOWN" if gesture.properties[ 'slideDown'] else "RIGHT" if gesture.properties[ 'slideRight'] else "LEFT" if time.time() - timeElapsedSinceLastSlide < 1: cv2.putText(motion.currentFrame, "Sliding " + currentSliding, (5, 450), cv2.FONT_HERSHEY_SIMPLEX, 2, 150, 3) for defect in gesture.palmDefects: cv2.line(motion.currentFrame, defect[0], defect[1], [255, 0, 0], 2) cv2.circle(motion.currentFrame, defect[2], 6, [0, 0, 255], -1) cv2.imshow('Current Frame', motion.currentFrame) except: pass pressedKey = cv2.waitKey(33) if pressedKey == 27: # Esc key to stop break motion.Dispose() os._exit(1)
def map_all_inputs(inputArray): motion_instance = Motion() for x in inputArray: x.movementVal = motion_instance.map_input(x) return
def set_motion_tracker(self): """ :return: Motion object """ width, height = self.get_frame_size() return Motion(height, width, self.current_frame)
self.update_state_ui() if self.state == MotionState.PREDICT: measurements = self.motion.get_measurements() if measurements is not None: self.mes_graph.update(measurements[:,:3]) predictions, time = self.motion.get_predictions() if predictions is not None: self.pred_graph.update(predictions) clss = np.argmax(predictions) self.prediction_label.configure(text=(self.motion.motions + ["other"])[clss]) self.classification_time.configure(text=f"{int(time*1000)}ms") self.root.after(1, self.loop) def run(self): motion_thread = self.motion.create_thread() motion_thread.start() self.root.after(100, self.loop) self.root.mainloop() self.motion.stop() if __name__ == "__main__": if len(sys.argv) == 2: ip = sys.argv[1] motions = ["Forward", "Left", "Right"] model = TsNN(30, threshold=3.4, augmentation=None) RealtimeViewer(Motion(motions, ip, model, training_duration=5.0)).run() else: print("No ip-address specified.")
def __init__(self, *, port: str, baudrate: int, number: str, url: str, dump: bool, cs: str): self.logger = getLogger('Log') self.dump = dump self.port = port self.baudrate = baudrate self.url = url self.number = number self.cs = cs self.ready: bool = True self.loopCounter: int = 0 self.sends: int = 0 self.report: Dict[str, any] = { 'number': number, 'bootup': dt.now().strftime(Constants.SYSdatetimeformat), 'location': '', } self.qp = Queue() self.sq = Queue() self.sleepTable: List[dict] = [ # {'max': 5, 'val': 60 * 1}, # {'max': 10, 'val': 30 * 1}, # {'max': 20, 'val': 4}, # {'max': 40, 'val': 3}, # {'max': 80, 'val': 2}, { 'max': 5, 'val': 15 }, { 'max': 10, 'val': 30 }, { 'max': 20, 'val': 4 }, { 'max': 40, 'val': 3 }, { 'max': 80, 'val': 2 }, ] try: sp = Serial(port=port, baudrate=baudrate) except (SerialException, ) as e: self.ready = False self.logger.error(msg=e) else: self.receiver = Receiver(sp=sp, qp=self.qp) self.driver = Driver(sp=sp, qp=self.qp, dump=self.dump, cs=self.cs) self.sender = Sender(url=url, sq=self.sq) self.motion = Motion(address=Constants.adxl345.address, threshold=Constants.adxl345.threshold) self.led = LEDController(pin=26) self.intervalSecs: int = 1
def __init__(self): self.vision = Vision(self._on_new_capture) self.motion = Motion()
import logging from motion import Motion log = logging.getLogger(__name__) tasks = Motion(stream_name='borgstrom-test') @tasks.respond_to('simple') def simple(payload): log.info("Simple task: %s", payload)
#print(myLinearInterpolation( # [(0, 1), (6, 3), (13, 8), (20, 12)], n)) r1 = RotationEvent(1, 1, 1) r2 = RotationEvent(2, 2, 3) r3 = RotationEvent(3, 1, 4) r4 = RotationEvent(4, 1, 5) r5 = RotationEvent(5, -2, 3) r6 = RotationEvent(1, 1, 1) r7 = RotationEvent(2, -1, 0) r8 = RotationEvent(3, 2, 2) r9 = RotationEvent(4, 4, 6) r10 = RotationEvent(5, -2, 3) m1 = Motion() m2 = Motion() m1.addEvent(r1) m1.addEvent(r2) m1.addEvent(r3) m1.addEvent(r4) m1.addEvent(r5) m2.addEvent(r6) m2.addEvent(r7) m2.addEvent(r8) m2.addEvent(r9) m2.addEvent(r10) c = Calculator()
def transformMotion(self, signals): self.signals = signals interpolator = Interpolator() n = 64 startTime = None endTime = None for event in self.signals: if startTime == None: startTime = event.getTime() elif startTime > event.getTime(): startTime = event.getTime() if endTime == None: endTime = event.getTime() elif endTime < event.getTime(): endTime = event.getTime() if isinstance(event, RotationEvent): self.recordedRotations.append(event) elif isinstance(event, ButtonEvent): self.recordedButtons.append(event) elif isinstance(event, TouchEvent): #self.recordedTouches.append(event) if event.getLocation is None: raise NameError('Hier ist ein Fehler aufgetreten') #Sort Touches by Locations if event.getLocation() not in self.touches: self.touches[event.getLocation()] = [] self.touches[event.getLocation()].append(event) else: pass if startTime is None or endTime is None: raise NotEnoughSignals() #Construct Motion transformedMotion = Motion() transformedMotion.setStartTime(startTime) transformedMotion.setEndTime(endTime) self.addNeutralValues(startTime, endTime) #print('ROTATIONS') #print(self.recordedRotations) #print('BUTTONS') #print(self.recordedButtons) #print('TOUCHES ARRAY') #print(self.recordedTouches) #print('TOUCHES DIC') #print(self.touches) #return #Rotation Part of Motion if len(self.recordedRotations) > 0: result = interpolator.linearInterpolation(self.recordedRotations, n) transformedTime = result[0] transformedSum = result[1] for i in range(len(transformedTime)): event = RotationEvent(transformedTime[i], None, transformedSum[i]) transformedMotion.addEvent(event) else: print('Es wurde keine Rotation hinzugefügt') #Button Part of Motion if len(self.recordedButtons) > 0: result = interpolator.linearInterpolation(self.recordedButtons, n) transformedTime = result[0] transformedValue = result[1] for i in range(len(transformedTime)): event = ButtonEvent(transformedTime[i], transformedValue[i]) transformedMotion.addEvent(event) else: print('Es wurde kein Button hinzugefügt') #Touch Part of Motion for location in self.touches: touchEvents = self.touches[location] result = interpolator.linearInterpolation(touchEvents, n) transformedTime = result[0] transformedValue = result[1] for i in range(len(transformedTime)): event = TouchEvent(transformedTime[i], location, transformedValue[i]) transformedMotion.addEvent(event) #Scaling and adjustment self.scaleMotion(transformedMotion) self.adjustValues(transformedMotion) return transformedMotion
def print_instructions(): print('\n\n' + '='*40 + '\n' + 'Press \'1\' to select thumb') print('Press \'2\' to select index') print('Press \'3\' to select middle') print('Press \'4\' to select ring') print('Press \'5\' to select pinky') print('Press \'6\' to select wrist') print('Press \'t\' to toggle back and fourth movement') print('Press \'Enter\' to increment server position') print('Press \'r\' to reprint these instructions') print('Press \'Ctrl + C\' to exit') print('='*40 + '\n\n') if __name__ == '__main__': m = Motion() selection = 0 finger = m.thumb pos = m.positions[selection] path = -1 pathname = {1: 'forward', -1:'backward'} #press = keyboard.is_pressed print_instructions() while True: press = input() #press = keyboard.read_key() try: if press == '1': finger = m.thumb
from flask import Flask from temperature import TemperatureSensor from motion import Motion import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) temperature = TemperatureSensor(14) motion = Motion(17) motion.run() app = Flask(__name__) @app.route("/metrics") def metrics(): temperature_data = "" result = temperature.read() if result.is_valid(): temperature_data = f"""pihome_temperature {result.temperature} pihome_humidity {result.humidity}""" return f"""{temperature_data} pihome_movement {motion.read()}""", 200, { 'Content-Type': 'text/plain; charset=utf-8' } if __name__ == "__main__":
import sys sys.path.append(r'/home/pi/pysrc') sys.path.append(r'/home/pi/coderbot') sys.path.append(r'/home/pi/coderbot/viz') import pydevd from coderbot import CoderBot, PIN_PUSHBUTTON from camera import Camera from motion import Motion from viz import camera, streamer, image, blob pydevd.settrace('10.0.0.9') mybot = Motion()