Set output pin high/low or send pulse
()
| 296 | |
| 297 | @app.route('/api/write', methods=['POST']) |
| 298 | def write_pin(): |
| 299 | """Set output pin high/low or send pulse""" |
| 300 | try: |
| 301 | data = request.get_json() |
| 302 | pin = int(data['pin']) |
| 303 | action = data['action'].lower() |
| 304 | |
| 305 | if pin not in pin_states or pin_states[pin]['mode'] != 'output': |
| 306 | return jsonify({'error': f'Pin {pin} is not configured as output'}), 400 |
| 307 | |
| 308 | if action in ['high', 'low']: |
| 309 | value = 1 if action == 'high' else 0 |
| 310 | |
| 311 | if GPIO_BACKEND == 'gpiozero': |
| 312 | device = pin_states[pin]['device'] |
| 313 | if value: |
| 314 | device.on() |
| 315 | else: |
| 316 | device.off() |
| 317 | elif GPIO_BACKEND == 'RPi.GPIO': |
| 318 | GPIO.output(pin, GPIO.HIGH if value else GPIO.LOW) |
| 319 | else: # mock |
| 320 | GPIO.output(pin, value) |
| 321 | |
| 322 | pin_states[pin]['value'] = value |
| 323 | log_event(f"Pin {pin} set to {action.upper()}") |
| 324 | |
| 325 | elif action == 'pulse': |
| 326 | duration = float(data.get('duration', 100)) / 1000.0 # ON time in seconds |
| 327 | loops = int(data.get('loops', 5)) |
| 328 | off_time = duration |
| 329 | if GPIO_BACKEND == 'gpiozero': |
| 330 | device = pin_states[pin]['device'] |
| 331 | for _ in range(loops): |
| 332 | device.on() |
| 333 | time.sleep(duration) |
| 334 | device.off() |
| 335 | time.sleep(off_time) |
| 336 | elif GPIO_BACKEND == 'RPi.GPIO': |
| 337 | for _ in range(loops): |
| 338 | GPIO.output(pin, GPIO.HIGH) |
| 339 | time.sleep(duration) |
| 340 | GPIO.output(pin, GPIO.LOW) |
| 341 | time.sleep(off_time) |
| 342 | else: # mock |
| 343 | for _ in range(loops): |
| 344 | GPIO.output(pin, 1) |
| 345 | time.sleep(duration) |
| 346 | GPIO.output(pin, 0) |
| 347 | time.sleep(off_time) |
| 348 | |
| 349 | pin_states[pin]['value'] = 0 # Pulse ends in LOW state |
| 350 | log_event(f"Pin {pin} pulsed for {duration*1000:.1f}ms") |
| 351 | |
| 352 | else: |
| 353 | return jsonify({'error': f'Invalid action {action}'}), 400 |
| 354 | |
| 355 | return jsonify({'success': True}) |