Skip to main content

API for PIC24FV-based Push button Light Control System

Project description

Push Button Light Control API (PB_API)

A high-level Python API for controlling Push Button Light devices with PIC24 microcontrollers using custom UART protocol. This library provides an intuitive interface for LED color and luminosity control in industrial and automation applications.

Features

🎨 Intuitive Color Control - Set LED colors using named presets or custom RGB values

💡 Luminosity Management - Control brightness with presets and smooth fading

🔄 Multiple Control Modes - Support for UART, Switch, Analog, and PWM modes

📡 Multi-Device Support - Control individual devices or broadcast to all

🔒 Thread-Safe - Safe for use in GUI applications and multi-threaded environments

⚡ Event-Driven - Callback system for asynchronous responses

🛡️ Robust Error Handling - Comprehensive error reporting and recovery

Installation

From PyPI (Recommended)

pip install push-button-light-control

From Source

git clone https://github.com/abdulbasit656/PB_API.git

cd PB_API

pip install -e .

🚀 Quick Start

This example provides a complete demonstration of how to connect, control, and test your Push Button Light device using the PushButtonLightControl API. It covers connection setup, control mode configuration, LED color sequencing, brightness adjustment, and built-in luminosity presets.

Basic Usage

from pb_api import PushButtonLightControl

Initialize and connect

pb = PushButtonLightControl('COM3') # Replace with your COM port pb.connect()

Set all LEDs to white at 50% brightness

pb.color.set_all_leds_color(1, 'WHITE') pb.luminosity.set_all_luminosity(1, 50)

Disconnect when done

pb.disconnect()

Complete Example

''' #!/usr/bin/env python3 """ Quick Start Example - Push Button Light Control API Demonstrates connection, control mode, color, and luminosity management. """

import time import sys import os

''' Add parent directory to path for local development ''' sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(file))))

from pb_api import PushButtonLightControl, CTRL_UART, CTRL_SW_LUMIN, LED_UR, LED_UL, LED_LR, LED_LL

def main(): print("Starting Push Button Light Control Demo") print("=" * 40)

# Initialize API (update COM port as needed)
pb = PushButtonLightControl('COM6', timeout=3.0)

try:
    # 1️⃣ Connect to device
    print("1. Connecting to device...")
    if pb.connect():
        print("✓ Connected successfully!")
    else:
        print("✗ Connection failed, continuing anyway...")

    time.sleep(1.0)
    
    # 2️⃣ Set UART control mode
    print("\n2. Setting UART control mode...")
    pb.control_mode.set_control_mode(1, CTRL_UART)
    print("✓ Control mode set successfully")

    # Turn off LEDs and set base brightness
    pb.color.set_all_leds_color(1, 'OFF')
    pb.luminosity.set_all_luminosity(1, 0)
    time.sleep(1.0)
    
    # 3️⃣ Set individual LED colors
    print("\n3. Setting LED colors...")
    pb.luminosity.set_all_luminosity(1, 100)

    pb.color.set_led_color(1, LED_UR, 'GREEN')
    pb.color.set_led_color(1, LED_UL, 'ORANGE')
    pb.color.set_led_color(1, LED_LL, 'RED')
    pb.color.set_led_color(1, LED_LR, 'MAGENTA')
    time.sleep(0.5)

    # Cycle through color patterns
    pb.color.set_all_leds_color(1, 'BLUE')
    pb.color.set_all_leds_color(1, 'RED')
    pb.color.set_all_leds_color(1, 'GREEN')

    # 4️⃣ Set luminosity to maximum
    print("\n4. Setting luminosity to MAX...")
    pb.color.set_all_leds_color(1, 'WHITE')
    pb.luminosity.set_all_luminosity(1, 100)
    print("✓ Luminosity set to 100%")

    # 5️⃣ Test predefined luminosity presets
    print("\n5. Testing presets...")
    for preset in ["DAY", "NIGHT", "OFF"]:
        pb.luminosity.set_luminosity_preset(1, preset)
        print(f"✓ Preset {preset} applied")
        time.sleep(0.5)
    
    print("\nDemo completed successfully!")
    
except Exception as e:
    print(f"\n💥 Demo failed with exception: {e}")
    import traceback
    traceback.print_exc()
finally:
    pb.disconnect()
    print("Disconnected from device")

if name == "main": main() '''

📘 API Overview

The following table describes the key variables, constants, and methods used in the example:

Element Description

PushButtonLightControl Main API class for connecting and communicating with the Push Button Light device.

'COM6' Serial port name. Replace with your actual port (e.g. 'COM3' on Windows or '/dev/ttyUSB0' on Linux).

timeout=3.0 Response timeout for device communication (in seconds).

CTRL_UART Control mode constant for UART (software-controlled) operation.

LED_UR, LED_UL, LED_LR, LED_LL LED position constants: Upper Right, Upper Left, Lower Right, Lower Left.

pb.connect(com_port, baudrate) Opens a serial connection to the device. Returns True on success.

pb.control_mode.set_control_mode(device ID, CTRL_UART) Sets device ID 1 to UART control mode.

pb.color.set_led_color(device ID, led_name, led_color) Sets individual LED color by device ID, LED position, and color name.

pb.color.set_all_leds_color(device ID, led_color) Sets all LEDs on a device (or all devices) to the same color.

pb.luminosity.set_all_luminosity(device ID, lumin_val) Adjusts brightness (0–100%) for all LEDs.

pb.luminosity.set_luminosity_preset(device ID, lumin_preset) Applies a predefined brightness preset: "DAY", "NIGHT", "OFF", or "MAX".

register_callback(event, callback) Register event callback

Predefined color presets

"OFF", "RED", "GREEN", "BLUE", "WHITE", "ORANGE", "MAGENTA", "CYAN"

Predefined luminosity levels

"OFF" # 0% "NIGHT" # 20% (20fL) "DAY" # 50% (150fL) "MAX" # 100%

Detailed Usage Guide

  1. Connecting to Devices

from pb_api import PushButtonLightControl

Basic connection

pb = PushButtonLightControl('COM3')

pb.connect()

With custom baudrate and timeout

pb = PushButtonLightControl('COM3', baudrate=115200, timeout=2.0)

pb.connect()

Check connection status

if pb.is_connected():

print("Device connected")
  1. Setting Control Modes

from pb_api import CTRL_UART, CTRL_SW_LUMIN, CTRL_SW_AN0, CTRL_SW_PWM

Set UART mode (full software control)

pb.control_mode.set_control_mode(1, CTRL_UART)

Set Switch + Luminance mode

pb.control_mode.set_control_mode(1, CTRL_SW_LUMIN)

Set Switch + Analog mode

pb.control_mode.set_control_mode(1, CTRL_SW_AN0)

Set Switch + PWM mode

pb.control_mode.set_control_mode(1, CTRL_SW_PWM)

Using mode names

pb.control_mode.set_control_mode_by_name(1, "UART_MODE")

  1. Color Control

Using Color Presets

Set individual LED colors

pb.color.set_led_color(1, 0, 'RED') # UR LED - Red

pb.color.set_led_color(1, 1, 'GREEN') # UL LED - Green

pb.color.set_led_color(1, 2, 'BLUE') # LR LED - Blue

pb.color.set_led_color(1, 3, 'WHITE') # LL LED - White

Set all LEDs to same color

pb.color.set_all_leds_color(1, 'WHITE')

Broadcast to all devices

pb.color.set_all_leds_color(0, 'BLUE') # 0 = broadcast ID

Custom RGB Colors

Set custom RGB color (values 0-100)

pb.color.set_custom_rgb_color(1, 0, red=100, green=50, blue=25) # UR LED

  1. Luminosity Control

Basic Brightness Control

Set individual LED brightness

pb.luminosity.set_led_luminosity(1, 0, 100) # UR LED - 100%

pb.luminosity.set_led_luminosity(1, 1, 75) # UL LED - 75%

pb.luminosity.set_led_luminosity(1, 2, 50) # LR LED - 50%

pb.luminosity.set_led_luminosity(1, 3, 25) # LL LED - 25%

Set all LEDs to same brightness

pb.luminosity.set_all_luminosity(1, 80) # All LEDs at 80%

Turn off all LEDs (0% brightness)

pb.luminosity.set_all_luminosity(1, 0)

Using Presets

Use predefined luminosity levels

pb.luminosity.set_luminosity_preset(1, "NIGHT") # 20% brightness

pb.luminosity.set_luminosity_preset(1, "DAY") # 50% brightness

pb.luminosity.set_luminosity_preset(1, "MAX") # 100% brightness

pb.luminosity.set_luminosity_preset(1, "OFF") # 0% brightness

Advanced Effects

Smooth fade between brightness levels

pb.luminosity.fade_luminosity(1, 0, 100, steps=20, delay=0.05)

Pulse effect

pb.luminosity.fade_luminosity(1, 30, 80, steps=10, delay=0.1)

pb.luminosity.fade_luminosity(1, 80, 30, steps=10, delay=0.1)

  1. System Configuration

Set luminosity presets for switch control mode

pb.system_config.set_luminosity_percentages(

device_id=1,

max_percent=100,    # Maximum brightness

day_percent=50,     # Daytime brightness  

night_percent=20    # Nighttime brightness

)

Using raw 12-bit values (0-4095)

pb.system_config.set_luminosity_presets(1, 4095, 2047, 819)

  1. Event Handling and Callbacks

def response_handler(data):

"""Handle device responses"""

print(f"Device response: {data}")

def error_handler(data):

"""Handle errors"""

print(f"Error occurred: {data}")

def connection_handler():

"""Handle connection events"""

print("Device connected")

Register callbacks

pb.register_callback('response_received', response_handler)

pb.register_callback('error', error_handler)

pb.register_callback('connected', connection_handler)

  1. Multi-Device Management

Control specific device

pb.color.set_led_color(1, 0, 'RED') # Device 1

pb.color.set_led_color(2, 0, 'GREEN') # Device 2

pb.color.set_led_color(3, 0, 'BLUE') # Device 3

Broadcast to all devices (device ID 0)

pb.color.set_all_leds_color(0, 'WHITE')

pb.luminosity.set_all_luminosity(0, 50)

LED Position Constants

from pb_api import LED_UR, LED_UL, LED_LR, LED_LL

Use these constants for clear position references

pb.color.set_led_color(1, LED_UR, 'RED') # Upper Right

pb.color.set_led_color(1, LED_UL, 'GREEN') # Upper Left

pb.color.set_led_color(1, LED_LR, 'BLUE') # Lower Right

pb.color.set_led_color(1, LED_LL, 'WHITE') # Lower Left

Error Handling

from pb_api import PushButtonError, CommunicationError, TimeoutError, DeviceError

try: pb.connect()

pb.color.set_led_color(1, 0, 'RED')

except CommunicationError as e:

print(f"Connection failed: {e}")

except TimeoutError as e:

print(f"Device timeout: {e}")

except DeviceError as e:

print(f"Device error (Code: 0x{e.error_code:02x}): {e}")

except PushButtonError as e:

print(f"API error: {e}")

▶️ Running the Example

After installation, you can use the included command-line tools:

Run the quick start demo

python examples/quick_start_demo.py

Quick start example

pb-quick-start

Troubleshooting

Common Issues

Device not found

Check COM port name

Verify device is connected and powered

Ensure no other application is using the port

Connection timeout

Check baudrate matches device configuration (usually 115200)

Verify cable connection

Check device power

Command not working

Ensure device is in UART mode

Check device ID is correct

Verify command parameters are within valid ranges

Debug Mode

Enable debug output by setting environment variable:

export PB_API_DEBUG=1

#API Reference

PushButtonLightControl

Documentation: GitHub Wiki

Issues: GitHub Issues

Email: basit.akram@gaenginering.com

License

This project is licensed under the GEA License - see the LICENSE file for details.

Push Button Light Control API - Making LED control simple and intuitive for developers.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

push_button_light_control-1.0.1.tar.gz (29.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

push_button_light_control-1.0.1-py3-none-any.whl (33.3 kB view details)

Uploaded Python 3

File details

Details for the file push_button_light_control-1.0.1.tar.gz.

File metadata

File hashes

Hashes for push_button_light_control-1.0.1.tar.gz
Algorithm Hash digest
SHA256 d41a8dac76b05b99844f6c274918b59292cf1e12b3d03b90a09fe40b84e9f110
MD5 a08bf2da70932f2ceae4c0f5c2867e33
BLAKE2b-256 5d78dab8dfbf6f5ad72aa1aa56522f0521fafba2715c667a24e97b6ad5d56357

See more details on using hashes here.

File details

Details for the file push_button_light_control-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for push_button_light_control-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 130f558aad5a7dcec0e92843e00d71faf74c756820d47f5545c91ae8dc43f5ab
MD5 d6618715d535e0133e41e04c94d5d21a
BLAKE2b-256 c28a8a101992c3c24f9d45c25ce6d0c98089883c1fe3bb20af4e9da518eb7d05

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page