Code Monkey home page Code Monkey logo

pslab-python's Introduction

PSLab Python Library

The Python library for the Pocket Science Lab from FOSSASIA.

Build Status Gitter Codacy Badge Mailing List Twitter Follow

This repository hosts the Python library for communicating with the Pocket Science Lab open hardware platform (PSLab). Using this library you can communicate with the PSLab using simple Python code. The Python library is also used by the PSLab GUI as a backend component.

The goal of PSLab is to create an Open Source hardware device (open on all layers) and software applications that can be used for experiments by teachers, students and scientists. Our tiny pocket lab provides an array of instruments for doing science and engineering experiments. It provides functions of numerous measurement tools including an oscilloscope, a waveform generator, a logic analyzer, a programmable voltage and current source, and even a component to control robots with up to four servos.

For more information see https://pslab.io.

Buy

Installation

pslab-python can be installed from PyPI:

$ pip install pslab

Note: Linux users must either install a udev rule by running 'pslab install' as root, or be part of the 'dialout' group in order for pslab-python to be able to communicate with the PSLab device.

Note: If you are only interested in using PSLab as an acquisition device without a display/GUI, only pslab-python needs to be installed. If you would like a GUI, install the pslab-desktop app and follow the instructions of the Readme in that repo.

Validate installation

  1. Plug in the PSLab device and check that both the LEDs light up.
  2. The following piece of code should run without errors:
from pslab import ScienceLab
psl = ScienceLab()
capacitance = psl.multimeter.measure_capacitance()
print(capacitance)

Communication

Wherever we interact, we strive to follow the FOSSASIA Code of Conduct.

Contributing

See CONTRIBUTING.md to get started.

License

Copyright (C) 2014-2021 FOSSASIA

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

pslab-python's People

Contributors

akarshan96 avatar bessman avatar bhadreshpsavani avatar cclauss avatar cloudypadmal avatar cweitat avatar cynddl avatar ericliclair avatar fragm3 avatar hpdang avatar igorwilbert avatar jithinbp avatar mariobehling avatar neel1998 avatar nkpro2000sr avatar orangecms avatar pipe-runner avatar rafaelleeimg avatar shivam7-1 avatar viveksb007 avatar wavicles 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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pslab-python's Issues

Implementing a new feature of trigger modes

Description
We can add the various types of trigger modes found in the oscilloscopes used in Labs. They are as follows:-
A. Auto - This trigger mode allows the oscilloscope to acquire a waveform even when it does not detect a trigger condition. If no trigger condition occurs while the oscilloscope waits for a specific period (as determined by the time-base setting), it will force itself to trigger.
B. Normal - The Normal mode allows the oscilloscope to acquire a waveform only when it is triggered. If no trigger occurs, the oscilloscope will not acquire a new waveform, and the previous waveform, if any, will remain on the display.
C. Single - The Single mode allows the oscilloscope to acquire one waveform each time you press the RUN button, and the trigger condition is detected.
D. Scan โ€“ The Scan mode continuously sweeps waveform from left to right.
I can implement these in the oscilloscope UI and these would help to make it more elaborate.

x.setOffset() is missing

In the file : achan.py on line 128 it says

x.setOffset(1.65)

but in the class analogInputSource there is no such function. Is it missing by mistake or by purpose?
Can someone clarify? If it is needed to set values of self.defaultOffsetcode then I can do the same.
ping @jithinbp @CloudyPadmal

Automatic generation of Menus in Sensor Data logger

In the present scenario most sensors have several configuration options, and these are defined in a dict element called 'Params' in each sensor's class. The Sensor data Logger application uses this dictionary to autogenerate menus with the 'key' as the name , and corresponding 'values' as a submenu . When the user opens a menu and clicks on a 'value' , the 'value' is passed to a function whose name is the corresponsing key , and which must be defined in the sensor's class.
An Example to illustrate
The following Params dictionary defined in the class of MPU6050 creates a menu as shown in the second image

self.params = { 'powerUp':['Go'],
  'setGyroRange':[250,500,1000,2000],
  'setAccelRange':[2,4,8,16],
  'KalmanFilter':[.01,.1,1,10,100,1000,10000,'OFF']
}

|mpu6050|

As shown in the image , when the user clicks on '8' , MPU6050.setAccelRange(8) is executed.

There are obvious limitations to this approach:

  • For functions with no arguments, a dummy variable is defined just so the user has something to click on.
  • This does not work for functions which require an arbitrary user defined input. e.g. , the Kalman filter menu shows a range of pre-defined values, wherein it should actually be a QDoubleSpinBox input.

I propose the following changes:

  • For functions with no arguments, the value field should be None , and the GUI should generate a QMenuAction instead of a QSubMenu.
  • For functions with variable input arguments, the menu should display a QSlider/QSpinBox/QTextArea/QColorDialog etc . For such functions, instead of providing a list of values, a string mentioning the type of input must be declared. Possible types : integer,double,string etc.

Split up sciencelab.py into smaller modules

The Sciencelab class is currently almost 4000 lines long. It is actually so long that Codacy ignores it when checking code quality.

As a rule of thumb, I like to keep classes under 500 lines or so. I intend to split the Sciencelab class into smaller classes based on individual instruments, like Multimeter, Oscilloscope, Waveform, LogicAnalyzer, etc. Possibly with some parent base class to avoid duplication of shared functionality.

remove existing bugs and format code according to pep8 styling guidelines

There are many instances of assignment of variables with a trailing semi-colon ';' , it doesn't raise any error but is avoided in python.

There are other bugs like

  • functions used without importing the necessary module
  • error in variable referencing

I would like to send a PR after fixing above bugs and code formatting according to pep8 python styling guidelines

Implementation with browser web UI options

What are the options to implement this project and make it accessible through the browser? This would have huge advantages in regards to the devices that can be used.

ubuntu/budgie: ModuleNotFoundError: No module named 'sip'

Installed pslab and pslab-apps succesfully with no errors, but starting Experiments ends up in a stack-trace reg. not found modules (at least sip and apt-pkg was mentioned).
Before posting endless traces: Does anybody made the same experience?
I have several versions of python installed (2.7, 3.6 and 3.7 at least) and tried this within the 2.7-Environment as well as in 3.7, with the same result. Well, at least the 2.7 should work, as I use it also for PlatformIO, which works perfectly.
What is so special on this pslab? I don't want to create a completely isolated environment just for that.

Convert capture method for sensor oscilloscope into a non-blocking call

The capture method for acquiring time critical datasets from sensors is currently a blocking call. This freezes up GUIs that may become unresponsive if acquisition length is of the order of seconds.

I propose to modify the same into three separate functions

  • Function to initialize the acquisition process. Arguments will include Address of the I2C sensor, Address of the sensor's register to start reading from, number of bytes to read per sample, total number of samples, and timegap.
  • Function to fetch the buffer after it is filled
  • Function to interpret the fetched buffer. This will handle data conversion into int/float, and return time, data arrays

Custom exception handling makes troubleshooting difficult

Throughout PSL, this is a common pattern:

try:
    <do something>
except Exception as ex:
    self.raiseException(ex, "Communication Error , Function : " + inspect.currentframe().f_code.co_name)

This makes troubleshooting difficult for several reasons:

  1. First and foremost, self.raiseException is not python3-compatible, so anytime it is called the original error is lost and an unrelated AttributeError is raised instead.
  2. self.raiseException is called from within classes which do not implement it (for example), which again loses the original exception and raises an unrelated one.

Even if the two above bugs are addressed, this type of custom exception handling reduces the amount of information normally available.

  1. Information on what happened is lost, since the exception type degenerates to a generic RuntimeError.
  2. Information on where it happened is lost, since every error is raised on line 4107 of sciencelab.py, instead of whereever the original exception was raised.
  3. It can inject false information about what happened. In the above try-except block, every exception is reported as "Communication Error", even though the except catches all exceptions, not just communication related ones.
  4. It increases cyclomatic complexity, making the code harder to understand and harder to unit test.

Python has excellent built-in exception handling, and as far as I can see PSL's custom implementation offers no advantages over it. What is its purpose?

Issues related to TSL2561.py

GAIN_0X is used here but it's value is never declared.

Also, refer this. I think the sleeping time should be 14ms but mentioned 140ms.
It should be time.sleep(0.014)

Add Open Firmware and Hardware Schematics

#fossasia/labs.fossasia.org#205

For the PSLab project we need a completely Open firmware and hardware schematics. There are already schematics in pdf format. In order to progress to the next level of development these files need to be implemented in code and added to the repository.

Please create a list of features for the firmware and sample implementations for tests. Add your schematics to the PSLab repo and create a fully functional hardware, that can be freely used by others.

PSLab is a new addition to FOSSASIA Science Lab. This tiny pocket lab provides an array of necessary equipments for doing science and engineering experiments. It can function like an oscilloscope, waveform generator, frequency counter, programmable voltage and current source and also as a data logger. The control and measurement functions are written in Python programming language. Pyqtgraph is used for plotting library. A variety of experiments can be performed using GUI applications written in python. PSLab is interfaced and powered by USB port of the computer.

Repository: https://github.com/fossasia/pslab

Website: http://pslab.fossasia.org

Problem while using fft funtion in the analyticClass

The fft funtion from the analyticClass of PSL has a fundamental issue that leads to type error

def fft(self, ya, si):
        ns = len(ya)
        if ns % 2 == 1:  # odd values of np give exceptions
            ns -= 1  # make it even
            ya = ya[:-1]
        v = np.array(ya)
        tr = abs(np.fft.fft(v)) / ns
        frq = np.fft.fftfreq(ns, si)
        x = frq.reshape(2, ns / 2)
        y = tr.reshape(2, ns / 2)
return x[0], y[0]

The 3rd last and 2nd last line of the code should be

        x = frq.reshape(2, ns // 2)
        y = tr.reshape(2, ns // 2)

Resource manager

Certain functions share the same hardware resource. For example, the oscilloscope and the logic analyzer both use the ADC buffer, which means they cannot be used at the same time. Another example is the pulse counter, which shares a timer with the logic analyzer.

We should create a resource manager to keep track of this, to prevent users from accidentally using multiple functions which use the same hardware simultaneously. Doing so can yield extremely strange results.

Develop an Android App for PSLab Experiments

There are a number of experiments currently running with PSLab. These are written as desktop experiments in Python. The next phase of the project enables users to make use of their mobile phone. Please propose an architecture, that does not necessarily require a server and offers teachers and students a way to make full use of the PSLab architecture.

PSLab is a new addition to FOSSASIA Science Lab. This tiny pocket lab provides an array of necessary equipments for doing science and engineering experiments. It can function like an oscilloscope, waveform generator, frequency counter, programmable voltage and current source and also as a data logger. The control and measurement functions are written in Python programming language. Pyqtgraph is used for plotting library. A variety of experiments can be performed using GUI applications written in python. PSLab is interfaced and powered by USB port of the computer.

Repository: https://github.com/fossasia/pslab

Chat: https://fossasia.slack.com/messages/pocketscience/details/ | [Get an invite]

Website: http://pslab.fossasia.org

fossasia/labs.fossasia.org#206

Communication library for MPU925x 10-DOF Inertial Measurement Unit

Add support for MPU-925x MotionTracking device series by InvenSense.
This sensor has 9 degrees of freedom measurement

  • 3-Axis Accelerometer
  • 3-Axis Gyroscope
  • 3-Axis Magnetometer
    It also has a built in temperature sensor

The magnetometer resides on the same chip, but has a separate I2C address.

Add unit tests

PSL lacks unit tests. I'm interested in writing them, if you think they would be useful to the project.

  • Add unit tests for Peripherals
  • Add unit tests for achan
  • Add units tests for analyticsClass
  • Add unit tests for commands_proto
  • Add unit tests for digital_channel
  • Add unit tests for packet_handler
  • Add unit tests for sciencelab
  • Add unit tests for sensorlist

Add unit tests for SENSORS

  • AD7718_class
  • AD9833
  • ADS1115
  • BH1750
  • BMP180
  • ComplementaryFilter
  • HMC5883L
  • Kalman
  • MF522
  • MLX90614
  • MPU6050
  • MPU925x
  • SHT21
  • SSD1306
  • Sx1276
  • TSL2561
  • supported

Undefined names:

flake8 testing of https://github.com/fossasia/pslab-python on Python 3.7.1

$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics

./PSL/analyticsClass.py:170:28: F821 undefined name 't'
        vf = self.sineFunc(t, par[0], par[1], par[2], par[3])
                           ^
./PSL/analyticsClass.py:171:21: F821 undefined name 'v'
        diff = sum((v - vf) ** 2) / max(v)
                    ^
./PSL/analyticsClass.py:171:41: F821 undefined name 'v'
        diff = sum((v - vf) ** 2) / max(v)
                                        ^
./PSL/analyticsClass.py:179:32: F821 undefined name 't'
            vf = self.sineFunc(t, par[0], par[1], par[2], par[3])
                               ^
./PSL/analyticsClass.py:180:25: F821 undefined name 'v'
            diff = sum((v - vf) ** 2) / max(v)
                        ^
./PSL/analyticsClass.py:180:45: F821 undefined name 'v'
            diff = sum((v - vf) ** 2) / max(v)
                                            ^
6     F821 undefined name 't'
1

Document the Python Library

The python library containing all the back-end functions used in PSLab has no documentation. sciencelab.py script has most of the functions and these functions need to be documented so that users can refer to them easily.

Expectation:
Prepare documentation for each function in a markdown file inside PSL directory

Add Calibration Utility

The PSLab unit's analog and digital features must be calibrated in order to make it accurate.
The ADS1115 16-bit ADC is a 4-channel, 0-3.3V ADC that can be interfaced via I2C . Typical initial accuracy of the internal voltage reference 0.01% and data rates higher than 500SPS are possible. It is cost effective, and convenient breakout boards that can directly plug into the PSLab's I2C port are available. Buy links: A , B , C
Therefore, it appears to be most suited to calibrate individual PSLab devices.

Tasks

  • Add I2C communication library for ADS1115
    • Include methods for reading single ended , and differential channels
    • Include selection of voltage range and voltage reference
  • Add Qt based UI . Features : These changes will be made in pslab-desktop-apps: issue #100
    • Calibrate CH1, CH2, CH3 & PV1, PV2, PV3 using ADS1115. Generate Cubic interpolation functions for each
    • Calibrate PCS using a measured Load resistor, and calibrated analog channel. Generate interpolation function
    • Calibrate CAP using precision capacitors
    • Write all calibration constants into flash memory after assigning a timestamp
    • Store raw calibration data in a client-side folder

sciencelab.capture_multiple does not return correct data

https://github.com/fossasia/pslab-python/blob/development/PSL/sciencelab.py#L593

This function is meant to be used as an oscilloscope where > 4 channels need to be recorded. Up to 4 channels can be simultaneously sampled using capture_traces instead.

The function accepts channel names as extra arguments, and the firmware scans through a sorted list of specified channels . The retrieved buffer must then be parsed into separate Y axes data , and the time axes for each channel must also be returned separately since this is sequential not simultaneous sampling.

LinuxMint: Sciencelab refuses to connect due to insufficient rights

The hardware registers itself as serial device. Unfortunately serial devices are part of the group dialout and the default user on my system (and probably other) doesn't have access rights to it.

So, you need root rights or you need to add your user to the dialout group:
sudo usermod -a -G dialout MY_USER_NAME

I don't know if Mint is special in this case, but I would recommend to add something in the installation documentation.

Reformat and upgrade source code

Python 2.7 is being depreciated and so does the supporting libraries. We need to upgrade the app with new libraries and python 3.7

Should repository be renamed to pslab-python

There are several components to PSLab. Currently this repository is holding the code for the python project. Therefore it would probably be better to rename this repository to pslab-python.

add transaction method for PSL.SPI

Implement a single function call to exchange small chunks of data via the SPI bus
e.g.

>>> print (sciencelab.SPI.xfer('CS1',[0x80,0xAA,0x55]) #Transmit this array, and return an array of bytes that were received against each element.
[0x00,0xFF,0xFF]

Add support for Long range wireless communication in SENSORS

The NRF wireless transceiver modules currently supported in the firmware have reliable working ranges up to 100 metres, but are generally suited for short range acquisition tasks.
The SX1276 chipset from Semtech allows long range transmissions up to 15kms line of sight while being extremely power efficient at the same time.
Its frequency is configurable over a wide range, and several modules tuned to various open frequency bands such as 434MHz, 868MHz etc are available.
Since it is an SPI device, and high data rates is not one of the features, the library can be added to the python module's SENSORS submodule

Implement standard project workflow and testing

In order to welcome more devs, we need to implement a standard workflow. Please:

  • Set up a development branch and merge the dev branch once a week to master
  • Add test frameworks (Which ones are suitable? travis, codecov, gemnasium, codeclimate..)

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.