Giter Site home page Giter Site logo

seeed-studio / seeed_python_reterminal Goto Github PK

View Code? Open in Web Editor NEW
25.0 13.0 6.0 16.84 MB

This is a Python library which enables you to use the onboard hardware on the reTerminal.

License: MIT License

Python 100.00%
python reterminal seeedstudio raspberrypi

seeed_python_reterminal's Introduction

Python Library for reTerminal

This is a Python library which enables you to use the onboard hardware on the reTerminal and reTerminal Bridge. Currently the accelerometer, user LEDs, user buttons and buzzer can be accessed using this Python library on reTerminal, and the fan, RS232, RS485, CAN can be accessed by using this Python library on reTerminal Bridge.

Installation

From PyPI

  • To install the latest release from PyPI
sudo pip3 install seeed-python-reterminal

From Source

  • To install from source, clone this repository
git clone https://github.com/Seeed-Studio/Seeed_Python_ReTerminal
  • Install the library
cd Seeed_Python_ReTerminal
sudo pip3 install .

Usage

User LEDs Test

import seeed_python_reterminal.core as rt
import time

print("STA ON, USR OFF")
rt.sta_led = True
rt.usr_led = False
time.sleep(1)

print("STA OFF, USR ON")
rt.sta_led = False
rt.usr_led = True
time.sleep(1)

print("STA RED, USR OFF")
rt.sta_led_green = False
rt.sta_led_red = True
rt.usr_led = False
time.sleep(1)

print("STA OFF, USR OFF")
rt.sta_led = False
rt.usr_led = False

Buzzer Test

import seeed_python_reterminal.core as rt
import time

print("BUZZER ON")
rt.buzzer = True
time.sleep(1)

print("BUZZER OFF")
rt.buzzer = False

User Buttons Test

import seeed_python_reterminal.core as rt
import seeed_python_reterminal.button as rt_btn


device = rt.get_button_device()
while True:
    for event in device.read_loop():
        buttonEvent = rt_btn.ButtonEvent(event)
        if buttonEvent.name != None:
            print(f"name={str(buttonEvent.name)} value={buttonEvent.value}")

Accelerometer Test

import seeed_python_reterminal.core as rt
import seeed_python_reterminal.acceleration as rt_accel


device = rt.get_acceleration_device()
while True:
    for event in device.read_loop():
        accelEvent = rt_accel.AccelerationEvent(event)
        if accelEvent.name != None:
            print(f"name={str(accelEvent.name)} value={accelEvent.value}")

Accelerometer and Buttons Test

import asyncio
import seeed_python_reterminal.core as rt
import seeed_python_reterminal.acceleration as rt_accel
import seeed_python_reterminal.button as rt_btn


async def accel_coroutine(device):
    async for event in device.async_read_loop():
        accelEvent = rt_accel.AccelerationEvent(event)
        if accelEvent.name != None:
            print(f"accel name={str(accelEvent.name)} value={accelEvent.value}")


async def btn_coroutine(device):
    async for event in device.async_read_loop():
        buttonEvent = rt_btn.ButtonEvent(event)
        if buttonEvent.name != None:
            print(f"name={str(buttonEvent.name)} value={buttonEvent.value}")


accel_device = rt.get_acceleration_device()
btn_device = rt.get_button_device()

asyncio.ensure_future(accel_coroutine(accel_device))
asyncio.ensure_future(btn_coroutine(btn_device))

loop = asyncio.get_event_loop()
loop.run_forever()

Illuminance Sensor Test

import time
import seeed_python_reterminal.core as rt

while True:
    print(rt.illuminance)
    time.sleep(0.2)

The Following Test Should Work With Reterminal Bridge

fan Test

import seeed_python_reterminal.core as rt
import time

print("FAN ON")
rt.fan = True
time.sleep(1)

print("FAN OFF")
rt.fan = False

RS232 Test

import sys
import serial
import time
import seeed_python_reterminal.core as rt

param1 = sys.argv[1]

# enable the rs232 for test
rt.rs232_or_rs485 = "RS232"

# init the serial
ser = serial.Serial(
    port='/dev/ttyS0',
    baudrate = 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
)

if param1 == "send":
    counter=0
    try:
        print("rs232 starts now!\n")
        ser.write("rs232 starts now!\n".encode())
        while 1:
                ser.write(("Write counter:{}\n".format(counter)).encode())
                time.sleep(1)
                counter += 1
    except KeyboardInterrupt:
        exit()
elif param1 == "receive":
    try:
        print("Start receiving data now!\n")
        while 1:
            x=ser.readline()
            if x != b'':
                print(x)
    except KeyboardInterrupt:
        exit()
else:
    print('param input error,try again with send or receive')

Note::When we use the test script of RS232/RS485/CAN.We need to pass a parameter to them.

Take the RS232 for example:

python3 test_rs232.py send # test the send(TX) function of RS232
python3 test_rs232.py receive # test the receive(RX) function of RS232

RS485 Test

import sys
import serial
import time
import seeed_python_reterminal.core as rt

param1 = sys.argv[1]

# enable the rs485 for test
rt.rs232_or_rs485 = "RS485"

# init the serial
ser = serial.Serial(
    port='/dev/ttyS0',
    baudrate = 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
)

if param1 == "send":
    counter=0
    # enable the rs485 for tx
    rt.rs485_tx_rx_stat = "TX"
    try:
        print("rs485 starts now!\n")
        ser.write("rs485 starts now!\n".encode())
        while 1:
                ser.write(("Write counter:{}\n".format(counter)).encode())
                time.sleep(1)
                counter += 1
    except KeyboardInterrupt:
        exit()
elif param1 == "receive":
    # enable the rs485 for rx
    rt.rs485_tx_rx_stat = "RX"
    try:
        print("Start receiving data now!\n")
        while 1:
            x=ser.readline()
            if x != b'':
                print(x)
    except KeyboardInterrupt:
        exit()
else:
    print('param input error,try again with send or receive')

CAN Test

# NOTICE: please make sure you have pip3 install python-can
#         before you use this test script
# import the library
import can
import sys
import time

param1 = sys.argv[1]

# create a bus instance
# many other interfaces are supported as well (see documentation)
bus = can.Bus(interface='socketcan',
              channel='can0',
              receive_own_messages=True)

if param1 == "send":
    # send a message
    counter=0
    print("can send starts now!\n")
    try:
        while True:
            message = can.Message(arbitration_id=123, is_extended_id=True,
                      data=[0x11, 0x22, counter])
            bus.send(message, timeout=0.2)
            time.sleep(1)
            counter += 1
    except KeyboardInterrupt:
        exit()

elif param1 == "receive":
    # iterate over received messages
    try:
        for msg in bus:
            print(f"{msg.arbitration_id:X}: {msg.data}")
    except KeyboardInterrupt:
        exit()
else:
    print('param input error,try again with send or receive')

Note: Please make sure your CAN interface is working before run this script. If not. You will get the error log with "Network is down". And you can enable the can with "sudo ip link set can0 up type can bitrate 500000".

API Reference

  • usr_led: Turn on/off green USR LED
rt.usr_led = True #Turn on green USR LED
rt.usr_led = False #Turn off green USR LED
  • sta_led_red: Turn on/off red STA LED
rt.sta_led_red = True #Turn on red STA LED
rt.sta_led_red = False #Turn off red STA LED
  • sta_led_green: Turn on/off green STA LED
rt.sta_led_green = True #Turn on green STA LED
rt.sta_led_green = False #Turn off green STA LED

Note: If red STA LED is on during this time, the green STA LED will turn on over the red STA LED

  • sta_led: Turn on/off green STA LED
rt.sta_led = True #Turn on green STA LED
rt.sta_led = False #Turn off green STA LED

Note: If red STA LED is on during this time, the green STA LED will turn on and the red STA LED will turn off

  • buzzer : Turn on/off buzzer
rt.buzzer = True #Turn on buzzer
rt.buzzer = False #Turn off buzzer
  • get_button_device(): Obtain information about the buttons including all the events supported by them
device = rt.get_button_device()
  • ButtonEvent(): Calls the ButtonEvent() and returns the EVENT
buttonEvent = rt_btn.ButtonEvent(event)
  • get_acceleration_device(): Obtain information about the accelerometer including all the events supported by it
device = rt.get_acceleration_device()
  • AccelerationEvent(): Calls the AccelerationEvent() and returns the EVENT
accelEvent = rt_accel.AccelerationEvent(event)
  • Illuminance :Obtain the current value from the illuminance sensor
illuminance = rt.illuminance
  • fan: Turn on/off fan
rt.fan = True # Turn on fan
rt.fan = False # Turn off fan
  • rs232_or_rs485: Open the RS232 or RS485
rt.rs232_or_rs485 = "RS232" # open the RS232
rt.rs232_or_rs485 = "RS485" # open the RS485
  • rs485_tx_rx_stat: Switch the function between send(TX) and receive(Rx) of RS485
rt.rs485_tx_rx_stat = "TX" # enable the send(TX) of RS485
rt.rs485_tx_rx_stat = "RX" # enable the receive(RX) of RS485

seeed_python_reterminal's People

Contributors

bigbearishappy avatar kasunthushara avatar kbowen-hendrickson avatar lakshanthad avatar matsujirushi avatar pillar1989 avatar reaxt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

seeed_python_reterminal's Issues

Property `illuminance` not available in pypi library

Problem

The version of this library installed with pip does not includes the property illuminance from core.py.

Tested in multiple reTerminals.

Steps to reproduce it

  1. Install the library as per official instructions: sudo pip3 install seeed-python-reterminal

  2. Start a python shell, import the module and try to read illuminance data:

import seeed_python_reterminal.core as rt
print(rt.illuminance)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_Core' object has no attribute 'illuminance'

Potential solution

The library version in pypi is 0.2, published on May 20. 2021, and matches the version 0.2 in setup.py of this repo.

The illuminance property and example were added on June 15, 2021. Uploading a new version 0.3 to pypi might be necessary.

Workaround

  1. Find library installation path with pip3 show seeed-python-reterminal. Look for Location: path.
  2. Go to library installation folder and open core.py with CLI editor of choice (eg. nano, vim, etc).
  3. Manually add the two missing lines to core.py, match code in the main branch.
   __LIGHT_ILLUMINANCE = "/sys/bus/iio/devices/iio:device0/in_illuminance_input"

  @property
    def illuminance(self):
        return int(self.__read_1st_line_from_file(_Core.__LIGHT_ILLUMINANCE))

I cannot run ‘test_led.py'

Execution result.

I tried to run test_led.py, it produced an error.

python test_led.py

STA ON, USR OFF
Traceback (most recent call last):
File "/home/pi/Downloads/Seeed_Python_ReTerminal/samples/test_led.py", line 7, in
rt.sta_led = True
File "/usr/local/lib/python3.9/dist-packages/seeed_python_reterminal/core.py", line 41, in sta_led
self.sta_led_green = value
File "/usr/local/lib/python3.9/dist-packages/seeed_python_reterminal/core.py", line 50, in sta_led_green
self.__write_to_file(_Core.__STA_LED_GREEN_BRIGHTNESS, "1" if value else "0")
File "/usr/local/lib/python3.9/dist-packages/seeed_python_reterminal/core.py", line 147, in __write_to_file
with open(file_name, "w") as f:
FileNotFoundError: [Errno 2] No such file or directory: '/sys/class/leds/usr_led2/brightness'

My environment.

image

Bluetooth is not working

Hello, I have a problem with my reTerminal and I can’t find solutions online.
I had the problem with the reTerminal powering up a blank screen after the first boot.
So I flashed the 32 bit Raspbian-reTerminal image by following the instructions from : https://wiki.seeedstudio.com/reTerminal-FAQ/#q2-how-can-i-flash-raspberry-pi-os-which-is-originally-shipped-with-reterminal
The reTerminal is now working great except for bluetooth.
Indeed, after the first boot I type sudo systemctl status bluetooth and I get this result :

bluetooth.service - Bluetooth service
     Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled)
     Active: inactive (dead)
       Docs: man:bluetoothd(8)

Sep 20 16:35:27 tgf systemd[1]: Condition check resulted in Bluetooth service being skipped.
Sep 20 16:36:56 tgf systemd[1]: Condition check resulted in Bluetooth service being skipped.

So I typed sudo modprobe btusb and then started bluetooth manually, when I type sudo systemctl status bluetooth I now get this result :

bluetooth.service - Bluetooth service
     Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2023-09-20 16:37:18 BST; 1s ago
       Docs: man:bluetoothd(8)
   Main PID: 1569 (bluetoothd)
     Status: "Running"
      Tasks: 1 (limit: 4164)
        CPU: 49ms
     CGroup: /system.slice/bluetooth.service
             └─1569 /usr/libexec/bluetooth/bluetoothd

Sep 20 16:37:18 tgf systemd[1]: Starting Bluetooth service...
Sep 20 16:37:18 tgf bluetoothd[1569]: Bluetooth daemon 5.55
Sep 20 16:37:18 tgf systemd[1]: Started Bluetooth service.
Sep 20 16:37:18 tgf bluetoothd[1569]: Starting SDP server
Sep 20 16:37:18 tgf bluetoothd[1569]: Bluetooth management interface 1.21 initialized

Now my problem is that when I type “hcitool dev” there is no device.
Also, I saw online that it could be a problem with the UART and when I type “sudo systemctl status hciuart.service” I get this result :

     hciuart.service - Configure Bluetooth Modems connected by UART
     Loaded: loaded (/lib/systemd/system/hciuart.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Wed 2023-09-20 16:35:49 BST; 4min 12s ago
    Process: 557 ExecStart=/usr/bin/btuart (code=exited, status=1/FAILURE)
        CPU: 68ms

Sep 20 16:35:19 tgf systemd[1]: Starting Configure Bluetooth Modems connected by UART...
Sep 20 16:35:49 tgf btuart[625]: Initialization timed out.
Sep 20 16:35:49 tgf btuart[625]: bcm43xx_init
Sep 20 16:35:49 tgf systemd[1]: hciuart.service: Control process exited, code=exited, status=1/FAILURE
Sep 20 16:35:49 tgf systemd[1]: hciuart.service: Failed with result 'exit-code'.
Sep 20 16:35:49 tgf systemd[1]: Failed to start Configure Bluetooth Modems connected by UART.

Does anyone have a solution for this? My goal is to be able to scan bluetooth devices around the reTerminal.

I bought a Bluetooth adapter : Asus USB-BT500 and plugged it to the reTerminal, it is recognized and I can scan bluetooth devices.
Does that mean that I have problem with the hardware in reTerminal or maybe I need to change some configurations in order to use bluetooth with the ReTerminal's hardware ?
Thanks

Installation prevented on PEP 668 Compliant Systems (e.g. Debian 12 Bookworm)

My system info

Raspberry Pi CM4 inside ReSeed terminal running Debian Bookworm 64bit. OS/Python info:

sudoer@hostname:~/ $ lsb_release -d | tail -n 1
Description:	Debian GNU/Linux 12 (bookworm)
sudoer@hostname:~/ $ pip3 --version
pip 23.0.1 from /usr/lib/python3/dist-packages/pip (python 3.11)
sudoer@hostname:~/ $ python --version
Python 3.11.2

Problem

On Raspberry Pi systems running the latest stable Debian (Bookworm 12), the sudo pip3 install seeed-python-reterminal installation procedure does not work:

sudoer@hostname:~/ $ sudo pip3 install seeed-python-reterminal
error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.
    
    If you wish to install a non-Debian-packaged Python package,
    create a virtual environment using python3 -m venv path/to/venv.
    Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
    sure you have python3-full installed.
    
    For more information visit http://rptl.io/venv

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.

The reason why can be found in the raspberry pi docs, see Python on Raspberry Pi

From Bookworm onwards, packages installed via pip must be installed into a Python Virtual Environment using venv. This has been introduced by the Python community, not by Raspberry Pi; see PEP 668 for more details.

PEP 668 essentially recommends that system python packages should be installed using the system package manager, while user python packages should be installed inside a venv.

Since seeed-python-reterminal requires access to system-level files, and since there is no debian release of the package, the correct installation workflow is unclear.

Proposals

Here are a couple ideas for changes to the installation instructions/workflow that should fix this problem.

I've included output from the README User LEDS Test script to show that these solutions should work.

Add instruction to use --breaks-system-packages flag

This is the fastest but least robust solution. Should look like this:

sudoer@hostname: $ sudo pip3 install seeed-python-reterminal --break-system-packages
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting seeed-python-reterminal
  Downloading https://www.piwheels.org/simple/seeed-python-reterminal/seeed_python_reterminal-0.5-py3-none-any.whl (7.2 kB)
Requirement already satisfied: evdev in /usr/lib/python3/dist-packages (from seeed-python-reterminal) (1.6.1)
Installing collected packages: seeed-python-reterminal
Successfully installed seeed-python-reterminal-0.5
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

Then:

sudoer@hostname:~/ $ sudo python ./user-leds-test.py 
STA ON, USR OFF
STA OFF, USR ON
STA RED, USR OFF
STA OFF, USR OFF

Create and install local .deb of Seeed_Python_Reterminal

This would replace the "Install from Source" instructions, and remove the warning statements of using --breaks-system-packages.

There are many ways to do this, here's one using stdeb:

# Install debian dependencies
sudoer@hostname:~/ $ sudo apt install stdeb dh-python

# Download source
sudoer@hostname:~/ $ git clone https://github.com/Seeed-Studio/Seeed_Python_ReTerminal && cd ./Seeed_Python_ReTerminal

# Create .deb
sudoer@hostname:~/Seeed_Python_ReTerminal $ python3 setup.py --command-packages=stdeb.command debianize
sudoer@hostname:~/Seeed_Python_ReTerminal dpkg-buildpackage -b -us -uc

# Install .deb
sudoer@hostname:~/Seeed_Python_ReTerminal sudo apt install ../python3-seeed-python-reterminal

Then:

sudoer@hostname:~/ $ sudo python ./user-leds-test.py 
STA ON, USR OFF
STA OFF, USR ON
STA RED, USR OFF
STA OFF, USR OFF

Distribute debian package

If there are any Debian Maintainers interested in maintaining this package, I think distributing a Debian package would be the most robust solution in the long run. I am not a Debian Maintainer.

The workflow would be:

sudo apt install python3-seeed-python-reterminal

Update documentation to recommend venv like PEP668 does

The only issue with using venv is the need for root access to /sys/ folders, but that can be resolved, and users should be directed to this workflow anyway.

The following workflow works:

$ python -m venv --system-site-packages env 
$ source env/bin/activate
(env) $ pip install seeed-python-reterminal
(env) $ sudo $(which python) ./user-leds-test.py 
STA ON, USR OFF
STA OFF, USR ON
STA RED, USR OFF
STA OFF, USR OFF

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.