Datasets:

Task Categories: sequence-modeling
Languages: code
Multilinguality: multilingual
Size Categories: unknown
Language Creators: crowdsourced
Annotations Creators: no-annotation
Source Datasets: original
Licenses: gpl-3.0
Dataset Preview Go to dataset viewer
id (int)text (string)repo_name (string)stars (string)repo_language (string)file_name (string)mime_type (string)
0
include LICENSE *.py *.yml *.yaml *.txt *.md include Makefile global-exclude __pycache__ global-exclude *.py[co] # Tests recursive-include tests * # Documentation recursive-include docs * prune docs/_build
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
1
Django>=1.11 django-filter==2.4.0 djangorestframework>=3.8.0 djangorestframework-jwt==1.11.0 drfaddons>=0.1.0 Pillow>=7.2.0
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
2
# How To Contribute<sup>[1](#footnote-1)</sup> First off, thank you for considering contributing to `drf-user`! It's people like _you_ who make it such a great tool for everyone. This document intends to make contribution more accessible by codifying tribal knowledge and expectations. Don't be afraid to open half-finished PRs, and ask questions if something is unclear! ## Workflow - No contribution is too small! Please submit as many fixes for typos and grammar bloopers as you can! - Try to limit each pull request to **_one_** change only. - Since we squash on merge, it's up to you how you handle updates to the master branch. Whether you prefer to rebase on master or merge master into your branch, do whatever is more comfortable for you. - _Always_ add tests and docs for your code. This is a hard rule; patches with missing tests or documentation will not be merged. - Make sure your changes pass our [CI](https://github.com/101loop/drf-user/actions?query=workflow%3ACI). You won't get any feedback until it's green unless you ask for it. - Once you've addressed review feedback, make sure to bump the pull request with a short note, so we know you're done. - Avoid breaking backwards compatibility. ## Code - Obey [PEP 8](https://www.python.org/dev/peps/pep-0008/), [PEP 257](https://www.python.org/dev/peps/pep-0257/), and the [Numpydoc Docstring Guide](https://numpydoc.readthedocs.io/en/latest/format.html). We have a summary line starting the `"""` block: ```python def foo(var1, var2, *args, long_var_name='hi', **kwargs): """Summarize the function in one line. Several sentences providing an extended description. Refer to variables using back-ticks, e.g. `var`. Parameters ---------- var1 : array_like Array_like means all those objects -- lists, nested lists, etc. -- that can be converted to an array. We can also refer to variables like `var1`. var2 : int The type above can either refer to an actual Python type (e.g. ``int``), or describe the type of the variable in more detail, e.g. ``(N,) ndarray`` or ``array_like``. *args : iterable Other arguments. long_var_name : {'hi', 'ho'}, optional Choices in brackets, default first when optional. **kwargs : dict Keyword arguments. Returns ------- type Explanation of anonymous return value of type ``type``. describe : type Explanation of return value named `describe`. out : type Explanation of `out`. type_without_description Raises ------ BadException Because you shouldn't have done that. Notes ----- Notes about the implementation algorithm (if needed). This can have multiple paragraphs. You may include some math: .. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n} And even use a Greek symbol like :math:`\omega` inline. Examples -------- These are written in doctest format, and should illustrate how to use the function. >>> a = [1, 2, 3] >>> print([x + 3 for x in a]) [4, 5, 6] >>> print("a\nb") a b """ # After closing class docstring, there should be one blank line to # separate following codes (according to PEP257). # But for function, method and module, there should be no blank lines # after closing the docstring. ``` - We follow [reorder_python_imports](https://github.com/asottile/reorder_python_imports) for sorting our imports. Similar to [isort](https://github.com/timothycrosley/isort) but uses static analysis more, and we follow the [Black](https://github.com/psf/black) code style with a line length of 88 characters. <!-- As long as you run our full tox suite before committing, or install our [pre-commit](https://pre-commit.com/) hooks (ideally you'll do both -- see [Local Development Environment](#local-development-environment)), you won't have to spend any time on formatting your code at all. If you don't, CI will catch it for you -- but that seems like a waste of your time! --> ## Tests - Write your asserts as `expected == actual` to line them up nicely: ```python x = f() assert 42 == x.some_attribute assert "foo" == x._a_private_attribute ``` <!-- * To run the test suite, all you need is a recent [tox](https://tox.readthedocs.io/). It will ensure the test suite runs with all dependencies against all Python versions just as it will in our CI. If you lack some Python versions, you can can always limit the environments like ``tox -e py35,py36`` (in that case you may want to look into [pyenv](https://github.com/pyenv/pyenv), which makes it very easy to install many different Python versions in parallel). --> - Write [good test docstrings](https://jml.io/pages/test-docstrings.html). ## Documentation Project-related documentation is written in [restructuredtext](https://docutils.sourceforge.io/rst.html) (`.rst`). GitHub-related project documentation (e.g. this file you're reading, `CONTRIBUTING.md`) is written in Markdown, as GitHub doesn't support `.rst` files for some of their features (e.g. automatically picking up the `CODE_OF_CONDUCT.md`) - If you start a new section, add two blank lines before and one blank line after the header, except if two headers follow immediately after each other: ```rst Last line of previous section. Header of New Top Section ------------------------- Header of New Section ^^^^^^^^^^^^^^^^^^^^^ First line of new section. ``` - If you add a new feature, demonstrate its awesomeness under `usage.rst`! ## Local Development Environment <!-- You can (and should) run our test suite using [tox](https://tox.readthedocs.io/). However, you’ll probably want a more traditional environment as well. We highly recommend to develop using the latest Python 3 release because `interrogate` tries to take advantage of modern features whenever possible. --> First create a [virtual environment](https://virtualenv.pypa.io/). It’s out of scope for this document to list all the ways to manage virtual environments in Python, but if you don’t already have a pet way, take some time to look at tools like [pyenv-virtualenv](https://github.com/pyenv/pyenv-virtualenv), [pew](https://github.com/berdario/pew), [virtualfish](https://virtualfish.readthedocs.io/), [virtualenvwrapper](https://virtualenvwrapper.readthedocs.io/), and [pyenv-virtualenvwrapper](https://github.com/pyenv/pyenv-virtualenvwrapper). Next, get an up to date checkout of the `drf-user` repository: ```sh $ git clone git@github.com:101loop/drf-user.git ``` or if you want to use git via `https`: ```sh $ git clone https://github.com/101loop/drf-user.git ``` Change into the newly created directory and **after activating your virtual environment** install an editable version of `drf-user` along with its tests, docs requirements and to avoid committing code that violates our style guide, we use [pre-commit](https://pre-commit.com/) hooks: ```sh (env) $ cd drf-user (env) $ make install ``` At this point, ```sh (env) $ make test ``` should work and pass, as should: ```sh (env) $ cd docs (env) $ make livehtml ``` The built documentation can then be found in [`localhost:8888`](http://localhost:8888). Create a branch for local development: ```sh (env) $ git checkout -b name-of-your-bugfix-or-feature ``` Now you can make your changes locally. When you're done making changes, check that your changes pass tests and code style should be aligned with Flake8 and Black: ```sh (env) $ make check ``` Commit your changes and push your branch to GitHub: ```sh (env) $ git add . (env) $ git commit -m "Your detailed description of your changes." (env) $ git push origin name-of-your-bugfix-or-feature ``` Submit a pull request through the GitHub website. ## Code of Conduct Please note that this project is released with a Contributor [Code of Conduct](https://github.com/101loop/drf-user/blob/master/CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. Please report any harm to `devs [at] 101loop.com` for anything you find appropriate. Thank you for considering contributing to `drf-user`! --- <a name="footnote-1">1</a>: This contribution guide has been taken from [interrogate](https://github.com/econchick/interrogate/).
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
3
# tox (https://tox.readthedocs.io/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = py{36,37,38,39}-django{22}-drf{310,311,312} py{36,37,38,39}-django{30,31}-drf{311,312,master} [testenv] commands = make install-quite pip freeze make check deps = django22: Django>=2.2,<2.3 django30: Django>=3.0,<3.1 django31: Django>=3.1,<3.2 drf310: djangorestframework>=3.10,<3.11 drf311: djangorestframework>=3.11,<3.12 drf312: djangorestframework>=3.12,<3.13 drfmaster: https://github.com/encode/django-rest-framework/archive/master.tar.gz whitelist_externals = make [gh-actions] python = 3.6: py36 3.7: py37 3.8: py38 3.9: py39
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
4
![Build Status](https://github.com/101loop/drf-user/workflows/CI/badge.svg) [![codecov](https://codecov.io/gh/101Loop/drf-user/branch/master/graph/badge.svg)](https://codecov.io/gh/101Loop/drf-user) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/101Loop/drf-user/master.svg)](https://results.pre-commit.ci/latest/github/101Loop/drf-user/master) [![Documentation Status](https://readthedocs.org/projects/drf-user/badge/?version=latest)](https://drf-user.readthedocs.io/en/latest/?badge=latest) [![Documentation Coverage](https://drf-user.readthedocs.io/en/latest/_static/interrogate_badge.svg)](https://github.com/101loop/drf-user) # Django REST Framework - User --- **User APP for Django REST Framework with API Views.**<br> `DRF User` is a Django app that overrides default user app to provide additional attributes and functionalities. The current stable version includes: - [x] Mobile Number - [x] Single field for full name - [x] REST API to register - [x] REST API to login - [x] MultiModelBackend: User can login using either of mobile, email or username - [x] REST API to login with OTP (Same API endpoint as for OTP Verification; Set `is_login: true` while sending JSON request) - [x] OTP Verification for mobile and email - [x] API to register / login with OTP (no pre-registration required) - [x] API to set user's profile image - [x] Mail sending feature upon successful registration - [x] SMS sending feature upon successful registration - [x] Change Password - [x] Update Profile - [x] Generic Configuration based on settings.py - [x] Signal based mails - [x] Mail based activation (optional alternative for OTP based activation) - [ ] Social Auth Endpoints(Login using fb/google) # Documentation --- - For more information on installation and configuration see the documentation at: https://drf-user.readthedocs.io/ # Example --- To get the example project running do: - Clone this repo ```shell $ git clone https://github.com/101Loop/drf-user.git ``` - Go to `example` folder in newly created directory `drf-user` ```shell $ cd drf-user/example ``` - Create and activate virtual environment. - Install requirements ```shell (.venv) $ pip install -r requirements.txt ``` - Run testing server: ```shell (.venv) $ python manage.py runserver ``` Take a look at `http://localhost:8000/swagger`. Swagger will list all the APIs of drf-user. # Contributing --- - Please file bugs and send pull requests to the [GitHub Repository](https://github.com/101loop/drf-user) and [Issue Tracker](https://github.com/101loop/drf-user/issues). See [CONTRIBUTING.md](https://github.com/101Loop/drf-user/blob/master/CONTRIBUTING.md) for details. * For help and support please reach out to us on [Slack](https://101loop.slack.com).
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
5
-r requirements.txt black flake8 model_bakery pre-commit pytest pytest-cov pytest-django sphinx sphinxcontrib_httpdomain tox
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
6
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="drf_user", version=__import__("drf_user").__version__, author=__import__("drf_user").__author__, author_email="me@himanshus.com", maintainer="Sumit Singh", maintainer_email="sumit.singh4613@gmail.com", description="User APP for Django REST Framework with API Views", long_description=long_description, long_description_content_type="text/markdown", license=__import__("drf_user").__license__, url="https://github.com/101loop/drf-user", python_requires=">=3.6", packages=setuptools.find_packages(), install_requires=open("requirements.txt").read().split(), include_package_data=True, classifiers=( "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Django", "Framework :: Django :: 2.2", "Framework :: Django :: 3.0", "Framework :: Django :: 3.1", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Topic :: Software Development :: Libraries :: Django App", "Topic :: Internet :: WWW/HTTP", ), )
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
7
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at `devs [at] 101loop.com`. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.4, available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html).
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
8
.PHONY: clean-pyc clean-build docs clean VIRTUALENV = virtualenv --python=python3 PYTHON = $(VENV)/bin/python VENV := $(shell echo $${VIRTUAL_ENV-.venv}) TEST_FLAGS=--verbosity=2 COVER_FLAGS=--source=drf_user help: @echo "install - install all requirements including for testing" @echo "install-quite - same as install but pipes all output to /dev/null" @echo "clean - remove all artifacts" @echo "clean-build - remove build artifacts" @echo "clean-pyc - remove Python file artifacts" @echo "clean-test - remove test and coverage artifacts" @echo "clean-test-all - remove all test-related artifacts including tox" @echo "lint - check style with flake8" @echo "format - format code with black" @echo "test - run tests quickly with the default Python" @echo "test-coverage - run tests with coverage report" @echo "test-all - run tests on every Python version with tox" @echo "check - run all necessary steps to check validity of project" @echo "release - package and upload a release" @echo "dist - package" install: pip install -r requirements-dev.txt pip install -e . pre-commit install install-quite: pip install -r requirements-dev.txt > /dev/null clean: clean-build clean-pyc clean-test-all clean-build: @rm -rf build/ @rm -rf dist/ @rm -rf *.egg-info clean-pyc: -@find . -name '*.pyc' -follow -print0 | xargs -0 rm -f -@find . -name '*.pyo' -follow -print0 | xargs -0 rm -f -@find . -name '__pycache__' -type d -follow -print0 | xargs -0 rm -rf clean-test: rm -rf .coverage coverage* rm -rf tests/.coverage test/coverage* rm -rf htmlcov/ clean-test-all: clean-test rm -rf .tox/ docs: python setup.py build_sphinx lint: flake8 --exclude=*/migrations/* --max-line-length 88 drf_user format: black --exclude .+/migrations/.+\.py drf_user test: $(PYTHON) -m pytest --disable-pytest-warnings --ds=tests.settings --cov=drf_user tests/ test-coverage: $(PYTHON) -m pytest --disable-pytest-warnings --ds=tests.settings --cov=drf_user tests/ --cov-report=xml test-all: tox check: clean-build clean-pyc clean-test lint format test-coverage release: clean python setup.py sdist upload dist: clean python setup.py sdist ls -l dist
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
9
"""Tests for drf_user/views.py module""" import pytest from django.urls import reverse from model_bakery import baker from rest_framework.test import APITestCase from drf_user.models import AuthTransaction from drf_user.models import User from tests.settings import BASE_DIR class TestLoginView(APITestCase): """LoginView Test""" def setUp(self) -> None: """SetUp test data""" self.url = reverse("Login") self.user = baker.make( "drf_user.User", username="user", email="user@email.com", name="user", mobile=1234569877, is_active=True, ) self.user.set_password("pass123") self.user.save() @pytest.mark.django_db def test_object_created(self): """Check if the User object is created or not""" self.assertEqual(1, User.objects.count()) @pytest.mark.django_db def test_successful_login_view(self): """Check if the credentials are correct""" response = self.client.post( self.url, data={"username": "user", "password": "pass123"} ) self.assertEqual(200, response.status_code) @pytest.mark.django_db def test_unsuccessful_login_view(self): """Check if the credentials are incorrect""" response = self.client.post( self.url, data={"username": "user", "password": "pass1234"} ) self.assertEqual(422, response.status_code) class TestRetrieveUpdateUserAccountView(APITestCase): """RetrieveUpdateUserAccountView Test""" def setUp(self) -> None: """SetUp test data""" self.url = reverse("Retrieve Update Profile") self.user = baker.make( "drf_user.User", username="user", email="user@email.com", mobile=1234569877, password="old_password", ) self.auth_transaction = baker.make( "drf_user.AuthTransaction", created_by=self.user, ) @pytest.mark.django_db def test_object_created(self): """Check if AuthTransaction object created or not""" self.assertEqual(1, User.objects.count()) self.assertEqual(1, AuthTransaction.objects.count()) @pytest.mark.django_db def test_get_user_account_view(self): """Check Retrieve Update Profile View returns user""" self.client.force_authenticate(self.user) response = self.client.get(self.url) self.assertEqual(200, response.status_code) self.assertEqual(self.user.username, response.data["username"]) @pytest.mark.django_db def test_update_username(self): """ Check patch request to Retrieve Update Profile view updates user's username """ self.client.force_authenticate(self.user) response = self.client.patch(self.url, {"username": "updated_username"}) self.assertEqual(200, response.status_code) self.assertEqual("updated_username", self.user.username) @pytest.mark.django_db def test_update_password(self): """ Check patch request to Retrieve Update Profile view updates user's password """ self.client.force_authenticate(self.user) self.assertEqual("old_password", self.user.password) response = self.client.patch(self.url, {"password": "my_unique_password"}) self.assertEqual(200, response.status_code) self.assertEqual("my_unique_password", self.user.password) class TestCheckUniqueView(APITestCase): """CheckUniqueView Test""" def setUp(self) -> None: """SetUp test data""" self.url = reverse("Check Unique") self.user = baker.make( "drf_user.User", username="user", email="user@email.com", mobile=1234569877, ) @pytest.mark.django_db def test_user_object_created(self): """Check if User object created or not""" self.assertEqual(1, User.objects.count()) @pytest.mark.django_db def test_is_unique(self): """Check if the user is unique""" response = self.client.post(self.url, {"prop": "username", "value": "user7"}) self.assertEqual(200, response.status_code) self.assertTrue(response.json()["data"][0]["unique"]) @pytest.mark.django_db def test_is_not_unique(self): """Check if the user is not unique""" response = self.client.post(self.url, {"prop": "username", "value": "user"}) self.assertEqual(200, response.status_code) self.assertFalse(response.json()["data"][0]["unique"]) @pytest.mark.django_db def test_data_invalid(self): """Check CheckUniqueView view raises 422 code when passed data is invalid""" response = self.client.post(self.url, {"prop": "invalid", "value": "user"}) self.assertEqual(422, response.status_code) class TestRegisterView(APITestCase): """RegisterView Test""" def setUp(self) -> None: """SetUp test data""" # pre validate email self.validated_email = baker.make( "drf_user.OTPValidation", destination="random@django.com", is_validated=True ) # pre validate mobile self.validated_mobile = baker.make( "drf_user.OTPValidation", destination="1234567890", is_validated=True ) self.url = reverse("Register") self.validated_data = { "username": "my_username", "password": "test_password", "name": "random_name", "email": "random@django.com", "mobile": 1234567890, } self.not_validated_data = { "username": "random", "password": "test_password", "name": "random_name", "email": "random@example.com", "mobile": 8800880080, } @pytest.mark.django_db def test_register_with_validated_email_and_mobile(self): """Check user creation when validated mobile and email is passed""" response = self.client.post(self.url, self.validated_data) self.assertEqual(201, response.status_code) self.assertEqual("my_username", response.json()["username"]) self.assertEqual("random_name", response.json()["name"]) @pytest.mark.django_db def test_raise_validation_error_when_email_mobile_not_validated(self): """Check view raises Validation Error when mobile and email is not validated""" response = self.client.post(self.url, self.not_validated_data) self.assertEqual(400, response.status_code) self.assertEqual( ["The email must be pre-validated via OTP."], response.json()["email"] ) self.assertEqual( ["The mobile must be pre-validated via OTP."], response.json()["mobile"] ) class TestOTPView(APITestCase): """OTPView Test""" def setUp(self) -> None: """SetUp test data""" self.user = baker.make("drf_user.User", email="user@example.com") self.otp_user = baker.make( "drf_user.OTPValidation", destination="user@example.com", otp=888383 ) self.otp_object = baker.make( "drf_user.OTPValidation", destination="email@django.com", otp=123456 ) self.url = reverse("OTP") @pytest.mark.django_db def test_request_otp_on_email(self): """ Checks when destination and email is passed to OTPView is sends otp on mail """ response = self.client.post( self.url, {"destination": "email@django.com", "email": "email@django.com"} ) self.assertEqual(201, response.status_code) self.assertEqual("Message sent successfully!", response.json()["message"]) @pytest.mark.django_db def test_request_otp_on_email_and_mobile(self): """ Checks when mobile as destination and email is passed to OTPView it sends otp on mail as well as on mobile """ response = self.client.post( self.url, {"destination": 1231242492, "email": "email@django.com"} ) self.assertEqual(201, response.status_code) self.assertEqual("Message sent successfully!", response.json()["message"]) @pytest.mark.django_db def test_raise_api_exception_when_email_invalid(self): """Checks OTPView raises validation error when email/mobile is invalid""" response = self.client.post( self.url, {"destination": "a.b", "email": "abc@d.com"} ) self.assertEqual(500, response.status_code) self.assertEqual( "Server configuration error occured: Invalid recipient.", response.json()["detail"], ) @pytest.mark.django_db def test_raise_validation_error_when_email_not_response_when_user_is_new(self): """ Checks OTPView raises validation error when new user only passes destination and not email """ response = self.client.post(self.url, {"destination": "email@django.com"}) self.assertEqual( ["email field is compulsory while verifying a non-existing user's OTP."], response.json()["non_field_errors"], ) self.assertEqual(400, response.status_code) @pytest.mark.django_db def test_raise_validation_error_when_is_login_response_when_user_is_new(self): """ Checks OTPView raises validation error when new user only passes is_login """ response = self.client.post( self.url, {"destination": "email@django.com", "is_login": True} ) self.assertEqual( "No user exists with provided details", response.json()["detail"] ) self.assertEqual(404, response.status_code) @pytest.mark.django_db def test_verify_otp_in_response(self): """Check otp validation""" response = self.client.post( self.url, { "destination": "email@django.com", "email": "email@django.com", "verify_otp": 123456, }, ) self.assertEqual(202, response.status_code) assert "OTP Validated successfully!" in response.json()["OTP"] @pytest.mark.django_db def test_is_login_in_response(self): """Check user login with OTP""" response = self.client.post( self.url, {"destination": "user@example.com", "verify_otp": 888383, "is_login": True}, ) self.assertEqual(202, response.status_code) class TestOTPLoginView(APITestCase): """OTP Login View""" def setUp(self) -> None: """Setup Test Data""" self.url = reverse("OTP-Register-LogIn") # create user self.user = baker.make( "drf_user.User", username="my_user", email="my_user@django.com", mobile=2848482848, ) # create otp of registered user self.user_otp = baker.make( "drf_user.OTPValidation", destination="my_user@django.com", otp=437474 ) # generate otp for random user self.random_user_otp = baker.make( "drf_user.OTPValidation", destination="random@django.com", otp=888383 ) self.data = { "name": "random_name", "email": "random@django.com", "mobile": 1234567890, } self.data_with_incorrect_email_mobile = { "name": "name", "email": "r@o.com", "mobile": 97, } self.data_with_correct_otp = { "name": "random_name", "email": "random@django.com", "mobile": 1234567890, "verify_otp": 888383, } self.data_with_incorrect_otp = { "name": "random_name", "email": "random@django.com", "mobile": 1234567890, "verify_otp": 999999, } self.data_registered_user = { "name": "my_user", "email": "my_user@django.com", "mobile": 2848482848, "verify_otp": 437474, } self.data_registered_user_with_different_mobile = { "name": "my_user", "email": "my_user@django.com", "mobile": 2846482848, "verify_otp": 437474, } self.data_registered_user_with_different_email = { "name": "my_user", "email": "ser@django.com", "mobile": 2848482848, "verify_otp": 437474, } self.data_random_user = { "name": "test_user1", "email": "test_user1@django.com", "mobile": 2848444448, "verify_otp": 585858, } @pytest.mark.django_db def test_when_only_name_is_passed(self): """Check when only name is passed as data then api raises 400""" response = self.client.post(self.url, data={"name": "test"}, format="json") self.assertEqual(400, response.status_code) self.assertEqual(["This field is required."], response.json()["email"]) self.assertEqual(["This field is required."], response.json()["mobile"]) @pytest.mark.django_db def test_when_name_email_is_passed(self): """Check when name and email is passed as data, then API raises 400""" response = self.client.post( self.url, data={"name": "test", "email": "test@random.com"}, format="json" ) self.assertEqual(400, response.status_code) self.assertEqual(["This field is required."], response.json()["mobile"]) @pytest.mark.django_db def test_when_name_mobile_is_passed(self): """Check when name and mobile is passed as data, then API raises 400""" response = self.client.post( self.url, data={"name": "test", "mobile": 1234838884}, format="json" ) self.assertEqual(400, response.status_code) self.assertEqual(["This field is required."], response.json()["email"]) @pytest.mark.django_db def test_when_email_mobile_is_passed(self): """Check when email and mobile is passed as data, then API raises 400""" response = self.client.post( self.url, data={"email": "test@example.com", "mobile": 1234838884}, format="json", ) self.assertEqual(400, response.status_code) self.assertEqual(["This field is required."], response.json()["name"]) @pytest.mark.django_db def test_sent_otp_when_name_email_mobile_is_passed(self): """ Check when name, email, mobile is passed then OTP is sent on user's email/mobile by API """ response = self.client.post(self.url, data=self.data, format="json") self.assertEqual(201, response.status_code) self.assertEqual( "OTP has been sent successfully.", response.json()["email"]["otp"] ) self.assertEqual( "OTP has been sent successfully.", response.json()["mobile"]["otp"] ) @pytest.mark.django_db def test_login_with_incorrect_otp_for_registered_user(self): """Check when data with correct otp is passed, token is generated or not""" response = self.client.post( self.url, data=self.data_with_incorrect_otp, format="json" ) self.assertEqual(403, response.status_code) self.assertEqual( "OTP Validation failed! 2 attempts left!", response.json()["detail"] ) @pytest.mark.django_db def test_login_with_incorrect_otp_for_new_user_without_validated_otp(self): """Check when data without validated otp is passed, raises 404""" response = self.client.post(self.url, data=self.data_random_user, format="json") self.assertEqual(404, response.status_code) self.assertEqual( "No pending OTP validation request found for provided destination. " "Kindly send an OTP first", response.json()["detail"], ) @pytest.mark.django_db def test_login_with_correct_otp_for_new_user(self): """ Check when data with correct otp is passed, token is generated and user is created """ response = self.client.post( self.url, data=self.data_with_correct_otp, format="json" ) self.assertEqual(202, response.status_code) self.assertContains(text="token", response=response, status_code=202) self.assertTrue(User.objects.get(email="random@django.com")) @pytest.mark.django_db def test_login_with_incorrect_email_mobile(self): """ Checks when wrong data is passed, raises server error """ # this test case verifies that mobile isn't validated by drfaddons, # will update this test case after fixing drfaddons response = self.client.post( self.url, data=self.data_with_incorrect_email_mobile, format="json" ) # TODO: update this test case to assert status_code == 400 # when drf_addons is updated self.assertEqual(500, response.status_code) self.assertEqual( "Server configuration error occured: Invalid recipient.", response.json()["detail"], ) @pytest.mark.django_db def test_login_with_different_email(self): """ Checks when a registered user passed different email, raises validation error or not """ response = self.client.post( self.url, data=self.data_registered_user_with_different_email, format="json" ) self.assertEqual(400, response.status_code) self.assertEqual( [ "Your account is registered with 2848482848 does not has ser@django.com as " # noqa:E501 "registered email. Please login directly via OTP with your mobile." ], response.json()["non_field_errors"], ) @pytest.mark.django_db def test_login_with_different_mobile(self): """ Checks when a registered user passed different mobile, raises validation error or not """ response = self.client.post( self.url, data=self.data_registered_user_with_different_mobile, format="json", ) self.assertEqual(400, response.status_code) self.assertEqual( [ "Your account is registered with my_user@django.com does not has 2846482848" # noqa:E501 " as registered mobile. Please login directly via OTP with your email." ], response.json()["non_field_errors"], ) class TestPasswordResetView(APITestCase): """PasswordResetView Test""" def setUp(self) -> None: """SetUp test data""" self.url = reverse("reset_user_password") self.user = baker.make( "drf_user.User", username="user", email="user@email.com", name="user", mobile=1234569877, is_active=True, ) # create otp of registered user self.user_otp = baker.make( "drf_user.OTPValidation", destination="user@email.com", otp=437474 ) self.data_correct_otp = { "otp": 437474, "email": "user@email.com", "password": "test@123", } self.data_incorrect_otp = { "otp": 767474, "email": "user@email.com", "password": "test@123", } self.data_incorrect_email = { "otp": 437474, "email": "meh@email.com", "password": "test@123", } self.user.set_password("pass123") self.user.save() @pytest.mark.django_db def test_object_created(self): """Check if the User object is created or not""" self.assertEqual(1, User.objects.count()) @pytest.mark.django_db def test_when_nothing_is_passed(self): """Check when nothing is passed as data then api raises 400""" response = self.client.post(self.url, data={}, format="json") self.assertEqual(400, response.status_code) self.assertEqual(["This field is required."], response.json()["otp"]) self.assertEqual(["This field is required."], response.json()["email"]) self.assertEqual(["This field is required."], response.json()["email"]) @pytest.mark.django_db def test_when_incorrect_email_passed(self): """Check when incorrect email is passed as data then api raises 404""" response = self.client.post( self.url, data=self.data_incorrect_email, format="json" ) self.assertEqual(404, response.status_code) @pytest.mark.django_db def test_when_incorrect_otp_passed(self): """Check when incorrect otp is passed as data then api raises 403""" response = self.client.post( self.url, data=self.data_incorrect_otp, format="json" ) self.assertEqual(403, response.status_code) @pytest.mark.django_db def test_when_correct_otp_email_passed(self): """Check when correct otp and email is passed as data then api raises 202""" response = self.client.post(self.url, data=self.data_correct_otp, format="json") self.assertEqual(202, response.status_code) class TestUploadImageView(APITestCase): """UploadImageView Test""" def setUp(self) -> None: """SetUp test data""" self.url = reverse("upload_profile_image") self.user = baker.make( "drf_user.User", username="user", email="user@email.com", name="user", mobile=1234569877, is_active=True, ) @pytest.mark.django_db def test_object_created(self): """Check if the User object is created or not""" self.assertEqual(1, User.objects.count()) @pytest.mark.django_db def test_when_nothing_is_passed(self): """Check when nothing is passed as data then api raises 400""" self.client.force_authenticate(self.user) response = self.client.post(self.url, data={}, format="multipart") self.assertEqual(400, response.status_code) self.assertEqual("No file was submitted.", response.json()["profile_image"][0]) @pytest.mark.django_db def test_when_upload_image_passed(self): """Check when image is passed as data then api raises 201""" self.client.force_authenticate(self.user) with open(f"{BASE_DIR}/tests/fixtures/test.jpg", "rb") as f: response = self.client.post( self.url, data={"profile_image": f}, format="multipart" ) self.assertEqual(201, response.status_code) self.assertEqual("Profile Image Uploaded.", response.json()["detail"])
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
10
"""Tests for drf_user/utils.py module""" import datetime import pytest from django.test import TestCase from django.utils import timezone from model_bakery import baker from rest_framework.exceptions import AuthenticationFailed from drf_user import utils as utils from drf_user.models import OTPValidation from drf_user.models import User class TestCheckUnique(TestCase): """check_unique test""" def setUp(self) -> None: """Create user object using model_bakery""" self.user = baker.make( "drf_user.User", email="user@email.com", ) @pytest.mark.django_db def test_object_created(self): """Check if User object created or not""" self.assertEqual(1, User.objects.count()) @pytest.mark.django_db def test_check_non_unique(self): """Check if the user is non-unique""" self.assertTrue(utils.check_unique("email", "user1@email.com")) @pytest.mark.django_db def test_check_unique(self): """Check if the user is unique""" self.assertFalse(utils.check_unique("email", "user@email.com")) class TestCheckValidation(TestCase): """check_validation test""" def setUp(self) -> None: """Create OTPValidation object using model_bakery""" self.validated_otp_validation = baker.make( "drf_user.OTPValidation", destination="user@email.com", is_validated=True ) @pytest.mark.django_db def test_object_created(self): """Check if OTPValidation object is created or not""" self.assertEqual(1, OTPValidation.objects.count()) @pytest.mark.django_db def test_check_validated_object(self): """Check if the value is validated""" self.assertTrue(utils.check_validation("user@email.com")) @pytest.mark.django_db def test_check_non_validated_object(self): """Check if the value is not validated""" self.assertFalse(utils.check_validation("user1@email.com")) class TestGenerateOTP(TestCase): """generate_otp Test""" @pytest.mark.django_db def test_generate_otp(self): """Check generate_otp successfully generates OTPValidation object or not""" utils.generate_otp("email", "user1@email.com") self.assertEqual(1, OTPValidation.objects.count()) @pytest.mark.django_db def test_generate_otp_reactive_past(self): """ Check generate_otp generates a new otp if the reactive time is yet to be over """ otp_validation1 = utils.generate_otp("email", "user1@email.com") otp_validation2 = utils.generate_otp("email", "user1@email.com") self.assertNotEqual(otp_validation1.otp, otp_validation2.otp) @pytest.mark.django_db def test_generate_otp_reactive_future(self): """ Check generate_otp returns the same otp if the reactive time is already over """ otp_validation1 = utils.generate_otp("email", "user1@email.com") """ Simulating that the reactive time is already been over 5 minutes ago """ otp_validation1.reactive_at = timezone.now() + datetime.timedelta(minutes=5) otp_validation1.save() otp_validation2 = utils.generate_otp("email", "user1@email.com") self.assertEqual(otp_validation2.otp, otp_validation1.otp) class TestValidateOTP(TestCase): """validate_otp test""" def setUp(self) -> None: """Create OTPValidation object using model_bakery""" self.otp_validation = baker.make( "drf_user.OTPValidation", destination="user@email.com", otp=12345 ) @pytest.mark.django_db def test_object_created(self): """Check if OTPValidation object is created or not""" self.assertEqual(1, OTPValidation.objects.count()) @pytest.mark.django_db def test_validate_otp(self): """Check if OTPValidation object is created or not""" self.assertTrue(utils.validate_otp("user@email.com", 12345)) @pytest.mark.django_db def test_validate_otp_raises_attempt_exceeded_exception(self): """Check function raises attempt exceeded exception""" """ Set the validate_attempt to 0. Raises attempt exceeded exception """ self.otp_validation.validate_attempt = 0 self.otp_validation.save() with self.assertRaises(AuthenticationFailed) as context_manager: utils.validate_otp("user@email.com", 56123) self.assertEqual( "Incorrect OTP. Attempt exceeded! OTP has been reset.", str(context_manager.exception.detail), ) @pytest.mark.django_db def test_validate_otp_raises_invalid_otp_exception(self): """Check function raises attempt exceeded exception""" with self.assertRaises(AuthenticationFailed) as context_manager: utils.validate_otp("user@email.com", 5623) self.assertEqual( "OTP Validation failed! 2 attempts left!", str(context_manager.exception.detail), )
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
11
"""Test urls""" from django.urls import include from django.urls import path urlpatterns = [ path("api/user/", include("drf_user.urls")), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
12
"""Tests for drf_user/models.py module""" import pytest from django.test import TestCase from model_bakery import baker from drf_user.models import AuthTransaction from drf_user.models import OTPValidation from drf_user.models import User class TestUserModel(TestCase): """User Model""" def setUp(self) -> None: """Create user object using model_bakery""" self.user = baker.make( "drf_user.User", name="test_user", username="my_unique_username" ) @pytest.mark.django_db def test_object_created(self): """Check if User object created or not""" self.assertEqual(1, User.objects.count()) @pytest.mark.django_db def test_get_full_name(self): """Checks that User.get_full_name() method retuns exact name""" self.assertEqual("test_user", self.user.get_full_name()) @pytest.mark.django_db def test_str_method(self): """Check str method""" self.assertEqual("test_user | my_unique_username", str(self.user)) class TestAuthTransactionModel(TestCase): """AuthTransaction Model""" def setUp(self) -> None: """Create auth_transaction object using model_bakery""" self.auth_transaction = baker.make( "drf_user.AuthTransaction", created_by__name="test_name", created_by__username="test_username", ) @pytest.mark.django_db def test_object_created(self): """Check if AuthTransaction object created or not""" assert AuthTransaction.objects.count() == 1 self.assertEqual(1, AuthTransaction.objects.count()) @pytest.mark.django_db def test_str_method(self): """Check str method""" self.assertEqual("test_name | test_username", str(self.auth_transaction)) class TestOTPValidationModel(TestCase): """OTPValidation""" def setUp(self) -> None: """Create otp_validation object using model_bakery""" self.otp_validation = baker.make("drf_user.OTPValidation", destination="mobile") @pytest.mark.django_db def test_object_created(self): """Check if OTPValidation object created or not""" self.assertEqual(1, OTPValidation.objects.count()) @pytest.mark.django_db def test_str_method(self): """Check str method""" self.assertEqual("mobile", str(self.otp_validation))
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
13
""" With these settings, tests run faster. """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "drf_user", "drfaddons", "rest_framework", "django_filters", ) # pytest --ds=tests.settings_unique tests/tst_unique.py # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = "dummy" # https://docs.djangoproject.com/en/dev/ref/settings/#test-runner TEST_RUNNER = "django.test.runner.DiscoverRunner" TIME_ZONE = "Asia/Kolkata" # CACHES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#caches CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "", } } # PASSWORDS # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] # EMAIL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" EMAIL_FROM = "test" # URL # ------------------------------------------------------------------------------ ROOT_URLCONF = "drf_user.urls" # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media/") # DATABASE # ------------------------------------------------------------------------------ DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } } AUTH_USER_MODEL = "drf_user.User" USER_SETTINGS = { "DEFAULT_ACTIVE_STATE": False, "OTP": { "LENGTH": 7, "ALLOWED_CHARS": "1234567890", "VALIDATION_ATTEMPTS": 3, "SUBJECT": "OTP for Verification", "COOLING_PERIOD": 3, }, "MOBILE_VALIDATION": True, "EMAIL_VALIDATION": True, "REGISTRATION": { "SEND_MAIL": False, "SEND_MESSAGE": False, "MAIL_SUBJECT": "Welcome to DRF-USER", "SMS_BODY": "Your account has been created", "TEXT_MAIL_BODY": "Your account has been created.", "HTML_MAIL_BODY": "Your account has been created.", }, }
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
14
============ Installation ============ Each of the following steps needs to be configured for the `drf-user` to be fully functional. Getting the code ---------------- Install from PyPI (recommended) with ``pip``:: pip install drf_user Or Install via ``easy_install``:: easy_install drf_user Or Install from ``source code``:: pip install -e git+https://github.com/101Loop/drf-user#egg=drf_user Requirements ------------ ``drf-user`` supports Python 3.5 and above. Prerequisites ------------- * Add ``drf_user`` and other dependencies in `INSTALLED_APPS` of your projects ``settings.py`` .. code-block:: python INSTALLED_APPS = [ ... 'drf_user', 'drfaddons', 'rest_framework', 'django_filters', ... ] * Include urls of `drf_user` in your projects ``urls.py`` .. code-block:: python from django.urls import path urlpatterns = [ ... path('api/user/', include('drf_user.urls')), ... ] Or if you have `regex` based urls use `re_path` .. code-block:: python from django.urls import re_path urlpatterns = [ ... re_path(r'^api/user/', include('drf_user.urls')), ... ] * Include `AUTH_USER_MODEL` in ``settings.py`` .. code-block:: python ... AUTH_USER_MODEL = 'drf_user.User' ... * Set `AUTHENTICATION_BACKEND` in ``settings.py`` .. code-block:: python AUTHENTICATION_BACKENDS = [ 'drf_user.auth.MultiFieldModelBackend', ] * Set JWT_AUTH configurations in ``settings.py`` (`these are default values to run drf_user, update as per your requirements`) .. code-block:: python import datetime JWT_AUTH = { "JWT_ENCODE_HANDLER": "rest_framework_jwt.utils.jwt_encode_handler", "JWT_DECODE_HANDLER": "rest_framework_jwt.utils.jwt_decode_handler", "JWT_PAYLOAD_HANDLER": "drf_user.auth.jwt_payload_handler", "JWT_PAYLOAD_GET_USER_ID_HANDLER": "rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler", "JWT_RESPONSE_PAYLOAD_HANDLER": "rest_framework_jwt.utils.jwt_response_payload_handler", "JWT_SECRET_KEY": SECRET_KEY, "JWT_GET_USER_SECRET_KEY": None, "JWT_PUBLIC_KEY": None, "JWT_PRIVATE_KEY": None, "JWT_ALGORITHM": "HS256", "JWT_VERIFY": True, "JWT_VERIFY_EXPIRATION": True, "JWT_LEEWAY": 0, "JWT_EXPIRATION_DELTA": datetime.timedelta(weeks=99999), "JWT_AUDIENCE": None, "JWT_ISSUER": None, "JWT_ALLOW_REFRESH": False, "JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=7), "JWT_AUTH_HEADER_PREFIX": "Bearer", "JWT_AUTH_COOKIE": None, } * Set `DEFAULT_AUTHENTICATION_CLASSES` in `REST_FRAMEWORK` configuration in your ``settings.py`` .. code-block:: python REST_FRAMEWORK = { ... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'drfaddons.auth.JSONWebTokenAuthenticationQS', ... ), ... } * Finally, run ``migrate`` command .. code-block:: shell python manage.py migrate drf_user Manual Settings --------------- User can define manual user config in ``settings.py`` file in `USER_SETTINGS` variable. Default options are provided below, update as per your requirements. .. code-block:: python USER_SETTINGS = { 'DEFAULT_ACTIVE_STATE': False, 'OTP': { 'LENGTH': 7, 'ALLOWED_CHARS': '1234567890', 'VALIDATION_ATTEMPTS': 3, 'SUBJECT': 'OTP for Verification', 'COOLING_PERIOD': 3 }, 'MOBILE_VALIDATION': True, 'EMAIL_VALIDATION': True, 'REGISTRATION': { 'SEND_MAIL': False, 'SEND_MESSAGE': False, 'MAIL_SUBJECT': 'Welcome to DRF-USER', 'SMS_BODY': 'Your account has been created', 'TEXT_MAIL_BODY': 'Your account has been created.', 'HTML_MAIL_BODY': 'Your account has been created.' } }
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
15
================= API Documentation ================= Register -------- API Docs for Register. .. http:post:: /register/ Register a new user to the system. .. code-block:: json { "username": "username", "name": "name", "email": "email@user.com", "mobile": "9999999999", "password": "password" } :jsonparam str username: unique username :jsonparam str name: name of the user :jsonparam str email: unique email of user :jsonparam str mobile: unique mobile number of user :jsonparam str password: password of user :statuscode 201: if supplied params are valid :statuscode 400: if supplied params are invalid Login ----- API Docs for Login. .. http:post:: /login/ Login a user to the system. .. code-block:: json { "username": "username", "password": "my_secret_password", } :jsonparam str username: unique username :jsonparam str password: password of user :statuscode 200: if supplied params are valid :statuscode 422: if supplied params are invalid Account ------- API Docs for Account. .. http:get:: /account/ Get a user. .. code-block:: json { "id": 1, "username": "dummy_username", "name": "dummy_name", "email": "email@dummy.com", "mobile": "9999999999", "is_superuser": true, "is_staff": true } :statuscode 200: if request is authenticated :statuscode 403: if request is not authenticated | .. http:put:: /account/ Update all details of user. .. code-block:: json { "username": "updated_username", "name": "updated_name", "email": "email@updated.com", "mobile": "9999999999", "password": "updated_password" } :jsonparam str username: unique username :jsonparam str name: name of the user :jsonparam str email: unique email of user :jsonparam str mobile: unique mobile number of user :jsonparam str password: password of user :statuscode 200: if request is authenticated :statuscode 400: if any param is not supplied :statuscode 403: if request is not authenticated | .. http:patch:: /account/ Update some details of user. .. code-block:: json { "name": "partial_updated_name", "email": "email@partial_updated.com", } :jsonparam str username: unique username, optional :jsonparam str name: name of the user, optional :jsonparam str email: unique email of user, optional :jsonparam str mobile: unique mobile number of user, optional :jsonparam str password: password of user, optional :statuscode 200: if request is authenticated :statuscode 400: if any param is not supplied :statuscode 403: if request is not authenticated OTP --- API Docs for OTP. .. http:post:: /otp/ Generate, validate and login using OTP. .. code-block:: json { "destination": "1234567890", "email": "email@django.com", "verify_otp": "123456", "is_login": "True", "_comment1": "destination can be email/mobile", "_comment2": "when using mobile as destination, use email", "_comment3": "to verify otp, add verify_otp to request", "_comment4": "for log in, just add is_login to request", } :jsonparam str destination: destination where otp to be sent :jsonparam str email: if mobile is used in destination then use this for email, optional :jsonparam str verify_otp: to verify otp, optional :jsonparam str is_login: to login user, optional :statuscode 201: if supplied params are valid :statuscode 400: if supplied params are invalid :statuscode 403: if supplied otp is invalid OTP Register Login ------------------ API Docs for OTP Register Login. .. http:post:: /otpreglogin/ Register, Login using OTP. .. code-block:: json { "name": "some_awesome_name", "email": "email@django.com", "mobile": "1234567890", "verify_otp": "123456", } :jsonparam str name: name of user :jsonparam str email: email of user :jsonparam str mobile: mobile of user :jsonparam str verify_otp: to verify otp, optional :statuscode 201: if supplied params are valid :statuscode 400: if supplied params are invalid :statuscode 403: if supplied otp is invalid Reset Password -------------- API Docs for Reset Password. .. http:post:: /password/reset/ Reset user's password. * To reset user's password, first you have to call `/otp/` with `is_login` parameter value false. * Then call this API .. code-block:: json { "email": "email@django.com", "otp": "123456", "password": "my_new_secret_password", } :jsonparam str email: email of user :jsonparam str otp: otp received on email :jsonparam str password: new password :statuscode 202: if supplied params are valid :statuscode 400: if supplied params are invalid :statuscode 403: if supplied otp is invalid Is Unique --------- API Docs for Is Unique. .. http:post:: /isunique/ Check uniqueness of username, email, mobile. .. code-block:: json { "prop": "email", "value": "email@django.com" } :jsonparam str prop: property to check for uniqueness, choices are username, email, mobile :jsonparam str value: value to check for uniqueness :statuscode 200: if supplied params are valid :statuscode 400: if supplied params are invalid Upload Image ------------ API Docs for Upload Image. .. http:post:: /uploadimage/ Upload user's profile image. .. code-block:: json { "profile_image": "<file_name>" } :jsonparam file profile_image: image file :statuscode 201: if supplied params are valid :statuscode 400: if image not passed :statuscode 403: if jwt token is not passed or invalid
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
16
.. drf-user documentation master file, created by sphinx-quickstart on Sat Sep 12 17:26:05 2020. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. ==================================== Welcome to drf-user's documentation! ==================================== User APP for Django REST Framework with API Views. ======== Overview ======== ``Django REST Framework - User`` is a Django app that overrides default user app to provide additional attributes and functionalities. .. |check_| raw:: html <input checked="" disabled="" type="checkbox"> .. |uncheck_| raw:: html <input disabled="" type="checkbox"> ============ Feature List ============ |check_| Mobile Number |check_| Single field for full name |check_| REST API to register |check_| REST API to login |check_| MultiModelBackend: User can login using either of mobile, email or username |check_| REST API to login with OTP (Same API endpoint as for OTP Verification; Set is_login: true while sending JSON request) |check_| OTP Verification for mobile and email |check_| API to register / login with OTP (no pre-registration required) |check_| API to set user's profile image |check_| Mail sending feature upon successful registration |check_| SMS sending feature upon successful registration |check_| Change Password |check_| Update Profile |check_| Generic Configuration based on `settings.py` |check_| Signal based mails: Pending in OTP section |check_| Mail based activation (optional alternative for OTP based activation) |uncheck_| Social Auth Endpoints(Login using fb/google) ======== Contents ======== .. toctree:: :maxdepth: 3 installation .. toctree:: :maxdepth: 3 api-doc Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
17
@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=. set BUILDDIR=_build if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% :end popd
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
18
SPHINXOPTS ?= SPHINXPROJ = drf_user SPHINXBUILD ?= sphinx-build SOURCEDIR = . BUILDDIR = _build PORT := 8888 # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif .PHONY: help clean html livehtml linkcheck help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html" livehtml: sphinx-autobuild -p $(PORT) -b html $(SOURCEDIR) $(BUILDDIR)/html $(O) linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt."
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
19
""" Configuration file for the Sphinx documentation builder. """ # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = "drf-user" copyright = "2020, 101 Loop" author = "101 Loop" parent_dir = os.path.dirname(os.path.dirname(__file__)) def get_version(): """Returns current version of the package""" with open(os.path.join(parent_dir, "drf_user", "__init__.py")) as f: for line in f: if line.startswith("__version__ ="): return line.split("=")[1].strip().strip("\"'") # The full version, including alpha/beta/rc tags release = get_version() # The short X.Y version. version = release # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. master_doc = "index" extensions = [ "sphinxcontrib.httpdomain", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] html_theme_options = { "description": "User App for Django REST Framework with API Views.", "github_banner": "true", "github_user": "101loop", "github_repo": "drf-user", "github_button": "true", "github_type": "star", }
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
20
# Hey, I just made a Pull Request! ## Description <!--- Describe your changes --> ## Motivation and Context <!--- Why is this change required? What problem does it solve? --> <!--- If it fixes an open issue, please link to the issue here. --> ## Have you tested this? If so, how? <!--- Valid responses are "I have included unit tests." and --> <!--- "I ran `drf-user` with these changes over some code and it works for me." --> ## Checklist for PR author(s) <!-- If an item doesn't apply to your pull request, **check it anyway** to make it apparent that there's nothing left to do. --> - [ ] Changes are covered by unit tests (no major decrease in code coverage %). - [ ] All tests pass. - [ ] Docstring coverage is **100%** via `interrogate drf_user` (I mean, we _should_ set a good example :smile:). - [ ] Updates to documentation: - [ ] Document any relevant additions/changes in `README.md`. - [ ] Manually update **both** the `README.md` _and_ `docs/index.rst` for any new changes. - [ ] Any changed/added classes/methods/functions have appropriate `versionadded`, `versionchanged`, or `deprecated` [directives](http://www.sphinx-doc.org/en/stable/markup/para.html#directive-versionadded). Find the appropriate next version in the project's [``__init__.py``](https://github.com/101loop/drf-user/blob/master/drf_user/__init__.py) file. ## Release note <!-- If your change is non-trivial (e.g. more than a fixed typo in docs, or updated tests), please write a suggested release note for us to include in `docs/changelog.rst` (we may edit it a bit). 1. Enter your release note in the below block. If the PR requires additional action from users switching to the new release, start the release note with the string "action required: ". Please write it in the imperative. 2. If no release note is required, just write "NONE". --> ```release-note ``` <!--- for more information on how to submit valuable contributions, see https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution -->
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
21
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: CI on: push: branches: [ master ] pull_request: branches: [ master ] # Allow rebuilds via API. repository_dispatch: types: rebuild jobs: tests: name: "Python ${{ matrix.python-version }} on Ubuntu" runs-on: "ubuntu-latest" env: USING_COVERAGE: '3.6,3.7,3.8,3.9' strategy: matrix: python-version: [ "3.6", "3.7", "3.8", "3.9" ] steps: - uses: "actions/checkout@v2" - uses: "actions/setup-python@v2" with: python-version: "${{ matrix.python-version }}" - name: "Install dependencies" run: | set -xe python -VV python -m site python -m pip install --upgrade pip setuptools wheel virtualenv tox tox-gh-actions pytest-xdist if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi - name: "Run tox targets for ${{ matrix.python-version }}" run: "python -m tox" - name: "Upload coverage to Codecov" if: "contains(env.USING_COVERAGE, matrix.python-version)" uses: "codecov/codecov-action@v1" with: token: ${{ secrets.CODECOV_TOKEN }} file: ./coverage.xml files: ./coverage1.xml,./coverage2.xml name: codecov-umbrella fail_ci_if_error: true
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
22
--- name: Feature request about: Suggest an idea for drf-user title: '' labels: enhancement, needs triage assignees: sumit4613 --- ### Describe the feature you'd like <!-- A clear and concise description of what you want to happen. --> <!-- Got some time on your hands and want to contribute a patch? You're freaking awesome! Please include that below. --> ### Is your feature request related to a problem? <!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] --> ### Your Environment <!-- It can help for us to know how you're using interrogate --> - `drf-user` version(s) (`drf-user --version`: - Operating System(s): - Python version(s): ### Additional context <!-- Add any other context or screenshots about the feature request here. -->
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
23
--- name: Bug report about: Create a report to help us improve drf-user <3 title: '' labels: bug, needs triage assignees: sumit4613 --- ### Environment <!-- Please include if you've confirmed one version of something works while another one does not --> - `drf-user` version(s) (`drf-user --version`: - Operating System(s): - Python version(s): ### Description of the bug <!-- A clear and concise description of what the bug is. --> ### What you expected to happen <!-- A clear and concise description of what you expected to happen. --> ### How to reproduce (as minimally and precisely as possible) <!-- If applicable, add screenshots to help explain your problem. --> ### Anything else we need to know? <!-- Add any other context about the problem here. -->
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
24
drf-yasg drf_user
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
25
# About --- This sample project demonstrates all the API endpoints of drf-user. It integrates with swagger so that all the API's can be exported in openapi format. # Running Example Project --- 1. Create and activate your virtual environment 2. Install requirements: ```shell (.venv) $ pip install -r requirements.txt ``` 3. Run testing server: ```shell (.venv) $ python manage.py runserver ``` 4. Take a look at `http://localhost:8000/swagger`. Swagger will list all the APIs of drf-user. 5. Go to `http://localhost:8000/swagger/?format=openapi`. From here you can export all the APIs in openapi format. Exported APIs can be easily imported into tools like [Postman](https://www.postman.com/).
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
26
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo_app.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": main()
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
27
"""demo_app URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include from django.urls import path from django.urls import re_path from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions schema_view = get_schema_view( openapi.Info( title="drf-users api", default_version="v1", description="This Django User Model is customised user model keeping in mind the practical need (esp. in India).", # noqa: E501 terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="devs@101loop.com"), license=openapi.License(name="GPL-3.0 License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path("admin/", admin.site.urls), path("api/user/", include("drf_user.urls")), # swagger urls re_path( r"^swagger(?P<format>\.json|\.yaml)$", schema_view.without_ui(cache_timeout=0), name="schema-json", ), re_path( r"^swagger/$", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui", ), re_path( r"^redoc/$", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc" ), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
28
""" WSGI config for demo_app project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo_app.settings") application = get_wsgi_application()
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
29
"""drf_user example app"""
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
30
""" ASGI config for demo_app project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo_app.settings") application = get_asgi_application()
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
31
""" Django settings for demo_app project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import datetime from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "tlr7z*^%8^l@0)%%e^xyvolo$8l2j1$)!t(gs+7m!7ine8eei-" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "drf_user", "drfaddons", "rest_framework", "django_filters", "drf_yasg", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "demo_app.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "demo_app.wsgi.application" # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", # noqa }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = "/static/" MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media/" STATIC_ROOT = BASE_DIR / "static/" AUTHENTICATION_BACKENDS = [ "drf_user.auth.MultiFieldModelBackend", ] AUTH_USER_MODEL = "drf_user.User" JWT_AUTH = { "JWT_ENCODE_HANDLER": "rest_framework_jwt.utils.jwt_encode_handler", "JWT_DECODE_HANDLER": "rest_framework_jwt.utils.jwt_decode_handler", "JWT_PAYLOAD_HANDLER": "drf_user.auth.jwt_payload_handler", "JWT_PAYLOAD_GET_USER_ID_HANDLER": "rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler", # noqa "JWT_RESPONSE_PAYLOAD_HANDLER": "rest_framework_jwt.utils.jwt_response_payload_handler", # noqa "JWT_SECRET_KEY": SECRET_KEY, "JWT_GET_USER_SECRET_KEY": None, "JWT_PUBLIC_KEY": None, "JWT_PRIVATE_KEY": None, "JWT_ALGORITHM": "HS256", "JWT_VERIFY": True, "JWT_VERIFY_EXPIRATION": True, "JWT_LEEWAY": 0, "JWT_EXPIRATION_DELTA": datetime.timedelta(weeks=99999), "JWT_AUDIENCE": None, "JWT_ISSUER": None, "JWT_ALLOW_REFRESH": False, "JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=7), "JWT_AUTH_HEADER_PREFIX": "Bearer", "JWT_AUTH_COOKIE": None, } REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ("drfaddons.auth.JSONWebTokenAuthenticationQS",), } USER_SETTINGS = { "DEFAULT_ACTIVE_STATE": True, "OTP": { "LENGTH": 7, "ALLOWED_CHARS": "1234567890", "VALIDATION_ATTEMPTS": 3, "SUBJECT": "OTP for Verification", "COOLING_PERIOD": 3, }, "MOBILE_VALIDATION": True, "EMAIL_VALIDATION": True, "REGISTRATION": { "SEND_MAIL": False, "SEND_MESSAGE": False, "MAIL_SUBJECT": "Welcome to DRF-USER", "SMS_BODY": "Your account has been created", "TEXT_MAIL_BODY": "Your account has been created.", "HTML_MAIL_BODY": "Your account has been created.", }, }
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
32
"""Urls module for drf-user""" from django.urls import path from drf_user import views app_name = "drf_user" urlpatterns = [ # ex: api/user/login/ path("login/", views.LoginView.as_view(), name="Login"), # ex: api/user/register/ path("register/", views.RegisterView.as_view(), name="Register"), # ex: api/user/otp/ path("otp/", views.OTPView.as_view(), name="OTP"), # ex: api/user/otpreglogin/ path("otpreglogin/", views.OTPLoginView.as_view(), name="OTP-Register-LogIn"), # ex: api/user/isunique/ path("isunique/", views.CheckUniqueView.as_view(), name="Check Unique"), # ex: api/user/account/ path( "account/", views.RetrieveUpdateUserAccountView.as_view(), name="Retrieve Update Profile", ), # ex: api/user/password/reset/ path( "password/reset/", views.PasswordResetView.as_view(), name="reset_user_password" ), # ex: api/user/uploadImage/ path("uploadimage/", views.UploadImageView.as_view(), name="upload_profile_image"), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
33
""" Custom backends to facilitate authorizations Author: Himanshu Shankar (https://himanshus.com) """ import re import uuid from calendar import timegm from datetime import datetime from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from rest_framework_jwt.compat import get_username from rest_framework_jwt.compat import get_username_field from rest_framework_jwt.settings import api_settings class MultiFieldModelBackend(ModelBackend): """ This is a ModelBacked that allows authentication with either a username or an email address or mobile number. """ user_model = get_user_model() def authenticate(self, request, username=None, password=None, **kwargs) -> None: """ This function is used to authenticate a user. User can send either of email, mobile or username in request to authenticate. The function will check accordingly and login the user. Parameters ---------- request: HttpRequest This is the request that is received by Django view. username: str This is the username sent by user to the API. The default value is None. password: str This is the password sent by user to the API. The default value is None. kwargs Returns ------- user: django.contrib.auth.get_user_model or None """ if username is None: username = kwargs.get(self.user_model.USERNAME_FIELD) if username.isdigit(): kwargs = {"mobile": username} elif not re.match(r"[^@]+@[^@]+\.[^@]+", username): kwargs = {"username": username} else: kwargs = {"email": username} try: user = self.user_model.objects.get(**kwargs) if user.check_password(password): return user except self.user_model.DoesNotExist: return None def get_user(self, username: int) -> None: """Returns user object if exists otherwise None Parameters ---------- username: int ID of the user will be passed here. Returns ------- user: django.contrib.auth.get_user_model or None """ try: return self.user_model.objects.get(pk=username) except self.user_model.DoesNotExist: return None def jwt_payload_handler(user): """ A custom JWT Payload Handler that adds certain extra data in payload such as: email, mobile, name Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- user: get_user_model() Returns ------- payload: dict """ username_field = get_username_field() username = get_username(user) payload = { "user_id": user.pk, "is_admin": user.is_staff, "exp": datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA, } if hasattr(user, "email"): payload["email"] = user.email if hasattr(user, "mobile"): payload["mobile"] = user.mobile if hasattr(user, "name"): payload["name"] = user.name if isinstance(user.pk, uuid.UUID): payload["user_id"] = str(user.pk) payload[username_field] = username # Include original issued at time for a brand new token, # to allow token refresh if api_settings.JWT_ALLOW_REFRESH: payload["orig_iat"] = timegm(datetime.utcnow().utctimetuple()) if api_settings.JWT_AUDIENCE is not None: payload["aud"] = api_settings.JWT_AUDIENCE if api_settings.JWT_ISSUER is not None: payload["iss"] = api_settings.JWT_ISSUER return payload
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
34
"""Serializers related to drf-user""" from django.contrib.auth.password_validation import validate_password from django.core.validators import EmailValidator from django.core.validators import ValidationError from django.utils.text import gettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import NotFound from drf_user import user_settings from drf_user.models import User from drf_user.utils import check_validation from drf_user.variables import EMAIL from drf_user.variables import MOBILE class UserSerializer(serializers.ModelSerializer): """ UserRegisterSerializer is a model serializer which includes the attributes that are required for registering a user. """ def validate_email(self, value: str) -> str: """ If pre-validated email is required, this function checks if the email is pre-validated using OTP. Parameters ---------- value: str Returns ------- value: str """ if user_settings["EMAIL_VALIDATION"]: if check_validation(value=value): return value else: raise serializers.ValidationError( "The email must be " "pre-validated via OTP." ) else: return value def validate_mobile(self, value: str) -> str: """ If pre-validated mobile number is required, this function checks if the mobile is pre-validated using OTP. Parameters ---------- value: str Returns ------- value: str """ if user_settings["MOBILE_VALIDATION"]: if check_validation(value=value): return value else: raise serializers.ValidationError( "The mobile must be " "pre-validated via OTP." ) else: return value def validate_password(self, value: str) -> str: """Validate whether the password meets all django validator requirements.""" validate_password(value) return value class Meta: """Passing model metadata""" model = User fields = ( "id", "username", "name", "email", "mobile", "password", "is_superuser", "is_staff", ) read_only_fields = ("is_superuser", "is_staff") extra_kwargs = {"password": {"write_only": True}} class UserShowSerializer(serializers.ModelSerializer): """ UserShowSerializer is a model serializer which shows the attributes of a user. """ class Meta: """Passing model metadata""" model = User fields = ("id", "username", "name") read_only_fields = ("username", "name") class OTPSerializer(serializers.Serializer): """ This Serializer is for sending OTP & verifying destination via otp. is_login: Set is_login true if trying to login via OTP destination: Required. Place where sending OTP email: Fallback in case of destination is a mobile number verify_otp: OTP in the 2nd step of flow Examples -------- 1. Request an OTP for verifying >>> OTPSerializer(data={"destination": "me@himanshus.com"}) Or for mobile number as destination >>> OTPSerializer(data={"destination": "88xx6xx5xx", >>> "email": "me@himanshus.com"}) 2. Send OTP to verify >>> OTPSerializer(data={"destination": "me@himanshus.com", >>> "verify_otp": 2930432}) Or for mobile number as destination >>> OTPSerializer(data={"destination": "88xx6xx5xx", >>> "email": "me@himanshus.com", >>> "verify_otp": 2930433}) For log in, just add is_login to request >>> OTPSerializer(data={"destination": "me@himanshus.com", >>> "is_login": True}) >>> OTPSerializer(data={"destination": "88xx6xx5xx", >>> "email": "me@himanshus.com", >>> "verify_otp": 2930433, "is_login": True}) Author: Himanshu Shankar (https://himanshus.com) """ email = serializers.EmailField(required=False) is_login = serializers.BooleanField(default=False) verify_otp = serializers.CharField(required=False) destination = serializers.CharField(required=True) def get_user(self, prop: str, destination: str) -> User: """ Provides current user on the basis of property and destination provided. Parameters ---------- prop: str Can be M or E destination: str Provides value of property Returns ------- user: User """ if prop == MOBILE: try: user = User.objects.get(mobile=destination) except User.DoesNotExist: user = None else: try: user = User.objects.get(email=destination) except User.DoesNotExist: user = None return user def validate(self, attrs: dict) -> dict: """ Performs custom validation to check if any user exists with provided details. Parameters ---------- attrs: dict Returns ------- attrs: dict Raises ------ NotFound: If user is not found ValidationError: Email field not provided """ validator = EmailValidator() try: validator(attrs["destination"]) except ValidationError: attrs["prop"] = MOBILE else: attrs["prop"] = EMAIL user = self.get_user(attrs.get("prop"), attrs.get("destination")) if not user: if attrs["is_login"]: raise NotFound(_("No user exists with provided details")) if "email" not in attrs.keys() and "verify_otp" not in attrs.keys(): raise serializers.ValidationError( _( "email field is compulsory while verifying a" " non-existing user's OTP." ) ) else: attrs["email"] = user.email attrs["user"] = user return attrs class CheckUniqueSerializer(serializers.Serializer): """ This serializer is for checking the uniqueness of username/email/mobile of user. """ prop = serializers.ChoiceField(choices=("email", "mobile", "username")) value = serializers.CharField() class OTPLoginRegisterSerializer(serializers.Serializer): """ Registers a new user with auto generated password or login user if already exists This will also set same OTP for mobile & email for easy process. Params name: Name of user email: Email of user mobile: Mobile of user verify_otp: Required in step 2, OTP from user """ name = serializers.CharField(required=True) email = serializers.EmailField(required=True) verify_otp = serializers.CharField(default=None, required=False) mobile = serializers.CharField(required=True) @staticmethod def get_user(email: str, mobile: str): """Fetches user object""" try: user = User.objects.get(email=email) except User.DoesNotExist: try: user = User.objects.get(mobile=mobile) except User.DoesNotExist: user = None if user: if user.email != email: raise serializers.ValidationError( _( "Your account is registered with {mobile} does not has " "{email} as registered email. Please login directly via " "OTP with your mobile.".format(mobile=mobile, email=email) ) ) if user.mobile != mobile: raise serializers.ValidationError( _( "Your account is registered with {email} does not has " "{mobile} as registered mobile. Please login directly via " "OTP with your email.".format(mobile=mobile, email=email) ) ) return user def validate(self, attrs: dict) -> dict: """Validates the response""" attrs["user"] = self.get_user( email=attrs.get("email"), mobile=attrs.get("mobile") ) return attrs class PasswordResetSerializer(serializers.Serializer): """This serializer is for password reset API. Params otp: OTP received on your email/mobile email: Email of the user whose password you're trying to reset password: new password for the user """ otp = serializers.CharField(required=True) email = serializers.EmailField(required=True) password = serializers.CharField(required=True) def get_user(self, destination: str) -> User: """Provides current user on the basis of property and destination provided. Parameters ---------- destination: str Provides value of property Returns ------- user: User """ try: user = User.objects.get(email=destination) except User.DoesNotExist: user = None return user def validate(self, attrs: dict) -> dict: """Performs custom validation to check if any user exists with provided email. Parameters ---------- attrs: dict Returns ------- attrs: dict Raises ------ NotFound: If user is not found ValidationError: Email field not provided """ validator = EmailValidator() validator(attrs.get("email")) user = self.get_user(attrs.get("email")) if not user: raise NotFound(_("User with the provided email does not exist.")) return attrs class ImageSerializer(serializers.ModelSerializer): """This serializer is for Image Upload API. Params profile_image: Profile Image File """ profile_image = serializers.ImageField(required=True) class Meta: """Passing model metadata""" model = User fields = ("profile_image",)
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
35
"""Views for drf-user""" from datetime import datetime from django.utils.text import gettext_lazy as _ from drfaddons.utils import get_client_ip from drfaddons.utils import JsonResponse from rest_framework import status from rest_framework.exceptions import APIException from rest_framework.generics import CreateAPIView from rest_framework.generics import RetrieveUpdateAPIView from rest_framework.parsers import JSONParser from rest_framework.permissions import AllowAny from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_jwt.serializers import JSONWebTokenSerializer from rest_framework_jwt.settings import api_settings from drf_user.models import AuthTransaction from drf_user.models import User from drf_user.serializers import CheckUniqueSerializer from drf_user.serializers import OTPLoginRegisterSerializer from drf_user.serializers import OTPSerializer from drf_user.serializers import PasswordResetSerializer from drf_user.serializers import UserSerializer from drf_user.utils import check_unique from drf_user.utils import generate_otp from drf_user.utils import login_user from drf_user.utils import send_otp from drf_user.utils import validate_otp from drf_user.variables import EMAIL from drf_user.variables import MOBILE class RegisterView(CreateAPIView): """ Register View Register a new user to the system. The data required are username, email, name, password and mobile. Author: Himanshu Shankar (https://himanshus.com) Aditya Gupta (https://github.com/ag93999) """ renderer_classes = (JSONRenderer,) permission_classes = (AllowAny,) serializer_class = UserSerializer def perform_create(self, serializer): """Override perform_create to create user""" user = User.objects.create_user( username=serializer.validated_data["username"], email=serializer.validated_data["email"], name=serializer.validated_data["name"], password=serializer.validated_data["password"], mobile=serializer.validated_data["mobile"], ) serializer = self.get_serializer(user) class LoginView(APIView): """ Login View This is used to Login into system. The data required are 'username' and 'password'. username -- Either username or mobile or email address. password -- Password of the user. Author: Himanshu Shankar (https://himanshus.com) Aditya Gupta (https://github.com/ag93999) """ renderer_classes = (JSONRenderer,) permission_classes = (AllowAny,) serializer_class = JSONWebTokenSerializer def validated(self, serialized_data, *args, **kwargs): """Validates the response""" user = serialized_data.object.get("user") or self.request.user token = serialized_data.object.get("token") response_data = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER( token, user, self.request ) response = Response(response_data) if api_settings.JWT_AUTH_COOKIE: expiration = datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA response.set_cookie( api_settings.JWT_AUTH_COOKIE, token, expires=expiration, httponly=True ) user.last_login = datetime.now() user.save() AuthTransaction( created_by=user, token=token, ip_address=get_client_ip(self.request), session=user.get_session_auth_hash(), ).save() return response def post(self, request): """Overrides post method to validate serialized data""" serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(): return self.validated(serialized_data=serialized_data) else: return JsonResponse( serialized_data.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY ) class CheckUniqueView(APIView): """ Check Unique API View This view checks if the given property -> value pair is unique (or doesn't exists yet) 'prop' -- A property to check for uniqueness (username/email/mobile) 'value' -- Value against property which is to be checked for. Author: Himanshu Shankar (https://himanshus.com) Aditya Gupta (https://github.com/ag93999) """ renderer_classes = (JSONRenderer,) permission_classes = (AllowAny,) serializer_class = CheckUniqueSerializer def validated(self, serialized_data, *args, **kwargs): """Validates the response""" return ( { "unique": check_unique( serialized_data.validated_data["prop"], serialized_data.validated_data["value"], ) }, status.HTTP_200_OK, ) def post(self, request): """Overrides post method to validate serialized data""" serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(): return JsonResponse(self.validated(serialized_data=serialized_data)) else: return JsonResponse( serialized_data.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY ) class OTPView(APIView): """ OTP Validate | OTP Login FROM SERIALIZER ---------------- is_login -- Set is_login true if trying to login via OTP destination -- Required. Place where sending OTP email -- Fallback in case of destination is a mobile number verify_otp -- OTP in the 2nd step of flow Examples -------- 1. Request an OTP for verifying >>> {"destination": "me@himanshus.com"} Or for mobile number as destination >>> {"destination": "88xx6xx5xx", "email": "me@himanshus.com"} 2. Send OTP to verify >>> {"destination": "me@himanshus.com", "verify_otp": 2930432} Or for mobile number as destination >>> {"destination": "88xx6xx5xx", "email": "me@himanshus.com", >>> "verify_otp": 2930433}) For log in, just add is_login to request >>> {"destination": "me@himanshus.com", "is_login": True} >>> {"destination": "me@himanshus.com", "is_login": True, >>> "verify_otp": 1234232} Author: Himanshu Shankar (https://himanshus.com) Aditya Gupta (https://github.com/ag93999) """ permission_classes = (AllowAny,) serializer_class = OTPSerializer def post(self, request, *args, **kwargs): """Overrides post method to validate serialized data""" serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) destination = serializer.validated_data.get("destination") prop = serializer.validated_data.get("prop") user = serializer.validated_data.get("user") email = serializer.validated_data.get("email") is_login = serializer.validated_data.get("is_login") if "verify_otp" in request.data.keys(): if validate_otp(destination, request.data.get("verify_otp")): if is_login: return Response( login_user(user, self.request), status=status.HTTP_202_ACCEPTED ) else: return Response( data={ "OTP": [ _("OTP Validated successfully!"), ] }, status=status.HTTP_202_ACCEPTED, ) else: otp_obj = generate_otp(prop, destination) sentotp = send_otp(destination, otp_obj, email) if sentotp["success"]: otp_obj.send_counter += 1 otp_obj.save() return Response(sentotp, status=status.HTTP_201_CREATED) else: raise APIException( detail=_("A Server Error occurred: " + sentotp["message"]) ) class RetrieveUpdateUserAccountView(RetrieveUpdateAPIView): """ Retrieve Update User Account View get: Fetch Account Details put: Update all details patch: Update some details Author: Himanshu Shankar (https://himanshus.com) Aditya Gupta( https://github.com/ag93999) """ queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticated,) lookup_field = "created_by" def get_object(self): """Fetches user from request""" return self.request.user def update(self, request, *args, **kwargs): """Updates user's password""" if "password" in request.data.keys(): self.request.user.set_password(request.data["password"]) self.request.user.save() return super(RetrieveUpdateUserAccountView, self).update( request, *args, **kwargs ) class OTPLoginView(APIView): """ OTP Login View Used to register/login to a system where User may not be required to pre-login but needs to login in later stage or while doing a transaction. View ensures a smooth flow by sending same OTP on mobile as well as email. name -- Required email -- Required mobile -- Required verify_otp -- Not Required (only when verifying OTP) Author: Himanshu Shankar (https://himanshus.com) Aditya Gupta (https://github.com/ag93999) """ permission_classes = (AllowAny,) renderer_classes = (JSONRenderer,) parser_classes = (JSONParser,) serializer_class = OTPLoginRegisterSerializer def post(self, request, *args, **kwargs): """Overrides post method to validate serialized data""" serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) verify_otp = serializer.validated_data.get("verify_otp", None) name = serializer.validated_data.get("name") mobile = serializer.validated_data.get("mobile") email = serializer.validated_data.get("email") user = serializer.validated_data.get("user", None) message = {} if verify_otp: if validate_otp(email, verify_otp): if not user: user = User.objects.create_user( name=name, mobile=mobile, email=email, username=mobile, password=User.objects.make_random_password(), ) user.is_active = True user.save() return Response( login_user(user, self.request), status=status.HTTP_202_ACCEPTED ) else: otp_obj_email = generate_otp(EMAIL, email) otp_obj_mobile = generate_otp(MOBILE, mobile) # Set same OTP for both Email & Mobile otp_obj_mobile.otp = otp_obj_email.otp otp_obj_mobile.save() # Send OTP to Email & Mobile sentotp_email = send_otp(email, otp_obj_email, email) sentotp_mobile = send_otp(mobile, otp_obj_mobile, email) if sentotp_email["success"]: otp_obj_email.send_counter += 1 otp_obj_email.save() message["email"] = {"otp": _("OTP has been sent successfully.")} else: message["email"] = { "otp": _("OTP sending failed {}".format(sentotp_email["message"])) } if sentotp_mobile["success"]: otp_obj_mobile.send_counter += 1 otp_obj_mobile.save() message["mobile"] = {"otp": _("OTP has been sent successfully.")} else: message["mobile"] = { "otp": _("OTP sending failed {}".format(sentotp_mobile["message"])) } if sentotp_email["success"] or sentotp_mobile["success"]: curr_status = status.HTTP_201_CREATED else: raise APIException( detail=_("A Server Error occurred: " + sentotp_mobile["message"]) ) return Response(data=message, status=curr_status) class PasswordResetView(APIView): """This API can be used to reset a user's password. Usage: First send an otp to the user by making an API call to `api/user/otp/` with `is_login` parameter value false. """ permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): """Overrides post method to validate OTP and reset password""" serializer = PasswordResetSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = User.objects.get(email=serializer.validated_data["email"]) if validate_otp( serializer.validated_data["email"], serializer.validated_data["otp"] ): # OTP Validated, Change Password user.set_password(serializer.validated_data["password"]) user.save() return JsonResponse( content="Password Updated Successfully.", status=status.HTTP_202_ACCEPTED, ) class UploadImageView(APIView): """This API can be used to upload a profile picture for user. usage: Create a multipart request to this API, with your image attached to `profile_image` parameter. """ from .models import User from .serializers import ImageSerializer from rest_framework.permissions import IsAuthenticated from rest_framework.parsers import MultiPartParser queryset = User.objects.all() serializer_class = ImageSerializer permission_classes = (IsAuthenticated,) parser_class = (MultiPartParser,) def post(self, request, *args, **kwargs): """Validate serializer and upload user profile image""" from .serializers import ImageSerializer from rest_framework.response import Response from rest_framework import status image_serializer = ImageSerializer(data=request.data) if image_serializer.is_valid(): image_serializer.update( instance=request.user, validated_data=image_serializer.validated_data ) return Response( {"detail": "Profile Image Uploaded."}, status=status.HTTP_201_CREATED ) else: return Response(image_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
36
"""Models for drf-user""" from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import Group from django.contrib.auth.models import PermissionsMixin from django.db import models from django.utils.text import gettext_lazy as _ from drf_user.managers import UserManager from drf_user.variables import DESTINATION_CHOICES from drf_user.variables import EMAIL class Role(Group): """ A proxy model for Group for renaming Group to Role. """ class Meta: """Passing model metadata""" proxy = True verbose_name = _("Role") verbose_name_plural = _("Roles") class User(AbstractBaseUser, PermissionsMixin): """ Represents default user model in a Django project. Adds following extra attributes: mobile: Mobile Number of the user name: Name of the user. Replaces last_name & first_name update_date: DateTime instance when the user was updated Author: Himanshu Shankar (https://himanshus.com) """ username = models.CharField( verbose_name=_("Unique UserName"), max_length=254, unique=True ) email = models.EmailField(verbose_name=_("Email Address"), unique=True) mobile = models.CharField( verbose_name=_("Mobile Number"), max_length=150, unique=True, null=True, blank=True, ) name = models.CharField(verbose_name=_("Full Name"), max_length=500, blank=False) profile_image = models.ImageField( verbose_name=_("Profile Photo"), upload_to="user_images", null=True, blank=True ) date_joined = models.DateTimeField(verbose_name=_("Date Joined"), auto_now_add=True) update_date = models.DateTimeField(verbose_name=_("Date Modified"), auto_now=True) is_active = models.BooleanField(verbose_name=_("Activated"), default=False) is_staff = models.BooleanField(verbose_name=_("Staff Status"), default=False) # Renamed Groups to Roles groups = models.ManyToManyField( Role, verbose_name=_("Roles"), blank=True, help_text=_( "The roles this user belongs to. A user will get all permissions " "granted to each of their roles." ), related_name="user_set", related_query_name="user", ) objects = UserManager() USERNAME_FIELD = "username" REQUIRED_FIELDS = ["name", "mobile", "email"] class Meta: """Passing model metadata""" verbose_name = _("User") verbose_name_plural = _("Users") def get_full_name(self) -> str: """Method to return user's full name""" return str(self.name) def __str__(self): """String representation of model""" return str(self.name) + " | " + str(self.username) class AuthTransaction(models.Model): """ Represents all authentication in the system that took place via REST API. Author: Himanshu Shankar (https://himanshus.com) """ ip_address = models.GenericIPAddressField(blank=False, null=False) token = models.TextField(verbose_name=_("JWT Token passed")) session = models.TextField(verbose_name=_("Session Passed")) create_date = models.DateTimeField( verbose_name=_("Create Date/Time"), auto_now_add=True ) update_date = models.DateTimeField( verbose_name=_("Date/Time Modified"), auto_now=True ) created_by = models.ForeignKey(to=User, on_delete=models.PROTECT) def __str__(self): """String representation of model""" return str(self.created_by.name) + " | " + str(self.created_by.username) class Meta: """Passing model metadata""" verbose_name = _("Authentication Transaction") verbose_name_plural = _("Authentication Transactions") class OTPValidation(models.Model): """ Represents all OTP Validation in the System. Author: Himanshu Shankar (https://himanshus.com) """ otp = models.CharField(verbose_name=_("OTP Code"), max_length=10) destination = models.CharField( verbose_name=_("Destination Address (Mobile/EMail)"), max_length=254, unique=True, ) create_date = models.DateTimeField(verbose_name=_("Create Date"), auto_now_add=True) update_date = models.DateTimeField(verbose_name=_("Date Modified"), auto_now=True) is_validated = models.BooleanField(verbose_name=_("Is Validated"), default=False) validate_attempt = models.IntegerField( verbose_name=_("Attempted Validation"), default=3 ) prop = models.CharField( verbose_name=_("Destination Property"), default=EMAIL, max_length=3, choices=DESTINATION_CHOICES, ) send_counter = models.IntegerField(verbose_name=_("OTP Sent Counter"), default=0) sms_id = models.CharField( verbose_name=_("SMS ID"), max_length=254, null=True, blank=True ) reactive_at = models.DateTimeField(verbose_name=_("ReActivate Sending OTP")) def __str__(self): """String representation of model""" return self.destination class Meta: """Passing model metadata""" verbose_name = _("OTP Validation") verbose_name_plural = _("OTP Validations")
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
37
"""Django REST Framework - User! User App for Django with API Views""" __title__ = "User - Django REST Framework" __version__ = "0.0.8" __author__ = "Himanshu Shankar" __license__ = "GPLv3" from django.conf import settings default_app_config = "drf_user.apps.DRFUserConfig" user_settings = { "DEFAULT_ACTIVE_STATE": False, "OTP": { "LENGTH": 5, "ALLOWED_CHARS": "1234567890", "VALIDATION_ATTEMPTS": 3, "SUBJECT": "OTP for Verification", "COOLING_PERIOD": 3, }, "MOBILE_VALIDATION": True, "EMAIL_VALIDATION": True, "REGISTRATION": { "SEND_MAIL": False, "SEND_MESSAGE": False, "MAIL_SUBJECT": "Welcome to DRF-USER", "SMS_BODY": "Your account has been created", "TEXT_MAIL_BODY": "Your account has been created.", "HTML_MAIL_BODY": "Your account has been created.", }, } def update_user_settings() -> dict: """ Updates user setting from django default setting TODO: Think of a better way, using Signal preferably. Returns ------- user_settings: dict Author: Himanshu Shankar (https://himanshus.com) """ custom_settings = getattr(settings, "USER_SETTINGS", None) if custom_settings: if isinstance(custom_settings, dict): for key, value in custom_settings.items(): if key not in ["OTP", "REGISTRATION"]: user_settings[key] = value elif key == "OTP": if isinstance(value, dict): for otp_key, otp_value in value.items(): user_settings["OTP"][otp_key] = otp_value else: raise TypeError("USER_SETTING attribute OTP must be a" " dict.") elif key == "REGISTRATION": if isinstance(value, dict): for reg_key, reg_value in value.items(): user_settings["REGISTRATION"][reg_key] = reg_value else: raise TypeError( "USER_SETTING attribute REGISTRATION" " must be a dict." ) else: raise TypeError("USER_SETTING must be a dict.") if user_settings["REGISTRATION"]["SEND_MAIL"]: if not getattr(settings, "EMAIL_HOST", None): raise ValueError( "EMAIL_HOST must be defined in django setting" " for sending mail." ) if not getattr(settings, "EMAIL_FROM", None): raise ValueError( "EMAIL_FROM must be defined in django setting" " for sending mail. Who is sending email?" ) return user_settings
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
38
"""Collection of general helper functions.""" import datetime import pytz from django.utils import timezone from django.utils.text import gettext_lazy as _ from drfaddons.utils import get_client_ip from drfaddons.utils import send_message from rest_framework.exceptions import APIException from rest_framework.exceptions import AuthenticationFailed from rest_framework.exceptions import NotFound from rest_framework.exceptions import PermissionDenied from rest_framework_jwt.utils import jwt_encode_handler from drf_user import update_user_settings from drf_user.auth import jwt_payload_handler from drf_user.models import AuthTransaction from drf_user.models import OTPValidation from drf_user.models import User user_settings = update_user_settings() otp_settings = user_settings["OTP"] def datetime_passed_now(source): """ Compares provided datetime with current time on the basis of Django settings. Checks source is in future or in past. False if it's in future. Parameters ---------- source: datetime object than may or may not be naive Returns ------- bool Author: Himanshu Shankar (https://himanshus.com) """ if source.tzinfo is not None and source.tzinfo.utcoffset(source) is not None: return source <= datetime.datetime.utcnow().replace(tzinfo=pytz.utc) else: return source <= datetime.datetime.now() def check_unique(prop, value): """ This function checks if the value provided is present in Database or can be created in DBMS as unique data. Parameters ---------- prop: str The model property to check for. Can be:: email mobile username value: str The value of the property specified Returns ------- bool True if the data sent is doesn't exist, False otherwise. Examples -------- To check if test@testing.com email address is already present in Database >>> print(check_unique('email', 'test@testing.com')) True """ user = User.objects.extra(where=[prop + " = '" + value + "'"]) return user.count() == 0 def generate_otp(prop, value): """ This function generates an OTP and saves it into Model. It also sets various counters, such as send_counter, is_validated, validate_attempt. Parameters ---------- prop: str This specifies the type for which OTP is being created. Can be:: email mobile value: str This specifies the value for which OTP is being created. Returns ------- otp_object: OTPValidation This is the instance of OTP that is created. Examples -------- To create an OTP for an Email test@testing.com >>> print(generate_otp('email', 'test@testing.com')) OTPValidation object >>> print(generate_otp('email', 'test@testing.com').otp) 5039164 """ # Create a random number random_number = User.objects.make_random_password( length=otp_settings["LENGTH"], allowed_chars=otp_settings["ALLOWED_CHARS"] ) # Checks if random number is unique among non-validated OTPs and # creates new until it is unique. while OTPValidation.objects.filter(otp__exact=random_number).filter( is_validated=False ): random_number = User.objects.make_random_password( length=otp_settings["LENGTH"], allowed_chars=otp_settings["ALLOWED_CHARS"] ) # Get or Create new instance of Model with value of provided value # and set proper counter. try: otp_object = OTPValidation.objects.get(destination=value) except OTPValidation.DoesNotExist: otp_object = OTPValidation() otp_object.destination = value else: if not datetime_passed_now(otp_object.reactive_at): return otp_object otp_object.otp = random_number otp_object.prop = prop # Set is_validated to False otp_object.is_validated = False # Set attempt counter to OTP_VALIDATION_ATTEMPTS, user has to enter # correct OTP in 3 chances. otp_object.validate_attempt = otp_settings["VALIDATION_ATTEMPTS"] otp_object.reactive_at = timezone.now() - datetime.timedelta(minutes=1) otp_object.save() return otp_object def send_otp(value, otpobj, recip): """ This function sends OTP to specified value. Parameters ---------- value: str This is the value at which and for which OTP is to be sent. otpobj: OTPValidation This is the OTP or One Time Passcode that is to be sent to user. recip: str This is the recipient to whom EMail is being sent. This will be deprecated once SMS feature is brought in. Returns ------- """ otp = otpobj.otp if not datetime_passed_now(otpobj.reactive_at): raise PermissionDenied( detail=_("OTP sending not allowed until: " + str(otpobj.reactive_at)) ) message = ( "OTP for verifying " + otpobj.get_prop_display() + ": " + value + " is " + otp + ". Don't share this with anyone!" ) try: rdata = send_message(message, otp_settings["SUBJECT"], [value], [recip]) except ValueError as err: raise APIException(_("Server configuration error occured: %s") % str(err)) otpobj.reactive_at = timezone.now() + datetime.timedelta( minutes=otp_settings["COOLING_PERIOD"] ) otpobj.save() return rdata def login_user(user: User, request) -> (dict, int): """ This function is used to login a user. It saves the authentication in AuthTransaction model. Parameters ---------- user: django.contrib.auth.get_user_model request: HttpRequest Returns ------- tuple: data: dict status_code: int """ token = jwt_encode_handler(jwt_payload_handler(user)) user.last_login = timezone.now() user.save() AuthTransaction( created_by=user, ip_address=get_client_ip(request), token=token, session=user.get_session_auth_hash(), ).save() data = {"session": user.get_session_auth_hash(), "token": token} return data def check_validation(value): """ This functions check if given value is already validated via OTP or not. Parameters ---------- value: str This is the value for which OTP validation is to be checked. Returns ------- bool True if value is validated, False otherwise. Examples -------- To check if 'test@testing.com' has been validated! >>> print(check_validation('test@testing.com')) True """ try: otp_object = OTPValidation.objects.get(destination=value) return otp_object.is_validated except OTPValidation.DoesNotExist: return False def validate_otp(value, otp): """ This function is used to validate the OTP for a particular value. It also reduces the attempt count by 1 and resets OTP. Parameters ---------- value: str This is the unique entry for which OTP has to be validated. otp: int This is the OTP that will be validated against one in Database. Returns ------- bool: True, if OTP is validated """ try: # Try to get OTP Object from Model and initialize data dictionary otp_object = OTPValidation.objects.get(destination=value, is_validated=False) # Decrement validate_attempt otp_object.validate_attempt -= 1 if str(otp_object.otp) == str(otp): otp_object.is_validated = True otp_object.save() return True elif otp_object.validate_attempt <= 0: generate_otp(otp_object.prop, value) raise AuthenticationFailed( detail=_("Incorrect OTP. Attempt exceeded! OTP has been " "reset.") ) else: otp_object.save() raise AuthenticationFailed( detail=_( "OTP Validation failed! " + str(otp_object.validate_attempt) + " attempts left!" ) ) except OTPValidation.DoesNotExist: raise NotFound( detail=_( "No pending OTP validation request found for provided " "destination. Kindly send an OTP first" ) )
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
39
"""App Config for drf-user""" from django.apps import AppConfig class DRFUserConfig(AppConfig): """DRF User App Config""" name = "drf_user" verbose_name = "Authorization & Authentication" def ready(self): """ Register signals Call update_user_settings() to update the user setting as per django configurations Returns ------- Author: Himanshu Shankar (https://himanshus.com) """ from . import update_user_settings from .signals.handlers import post_register # noqa update_user_settings()
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
40
""" All static variables used in the system. Author: Himanshu Shankar (https://himanshus.com) Author: Aditya Gupta (https://github.com/ag93999) """ EMAIL = "E" MOBILE = "M" DESTINATION_CHOICES = [(EMAIL, "EMail Address"), (MOBILE, "Mobile Number")]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
41
""" All Admin configuration related to drf_user Author: Himanshu Shankar (https://himanshus.com) """ from django.contrib import admin from django.contrib.auth.admin import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.admin import UserAdmin from django.utils.text import gettext_lazy as _ from .models import AuthTransaction from .models import OTPValidation from .models import Role from .models import User class DRFUserAdmin(UserAdmin): """ Overrides UserAdmin to show fields name & mobile and remove fields: first_name, last_name Author: Himanshu Shankar (https://himanshus.com) """ fieldsets = ( (None, {"fields": ("username", "password")}), (_("Personal info"), {"fields": ("name", "profile_image", "email", "mobile")}), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ) }, ), ( _("Important dates"), {"fields": ("last_login", "date_joined", "update_date")}, ), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("username", "email", "mobile", "password1", "password2"), }, ), ) list_display = ("username", "email", "name", "mobile", "is_staff") search_fields = ("username", "name", "email", "mobile") readonly_fields = ("date_joined", "last_login", "update_date") class OTPValidationAdmin(admin.ModelAdmin): """OTP Validation Admin""" list_display = ("destination", "otp", "prop") class AuthTransactionAdmin(admin.ModelAdmin): """AuthTransaction Admin""" list_display = ("created_by", "ip_address", "create_date") def has_add_permission(self, request): """Limits admin to add an object.""" return False def has_change_permission(self, request, obj=None): """Limits admin to change an object.""" return False def has_delete_permission(self, request, obj=None): """Limits admin to delete an object.""" return False # UnRegister default Group & register proxy model Role # This will also remove additional display of application in admin panel. # Source: https://stackoverflow.com/a/32445368 admin.site.unregister(Group) admin.site.register(Role, GroupAdmin) admin.site.register(User, DRFUserAdmin) admin.site.register(OTPValidation, OTPValidationAdmin) admin.site.register(AuthTransaction, AuthTransactionAdmin)
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
42
"""Custom Managers for drf-user""" from django.contrib.auth.base_user import BaseUserManager from drf_user import update_user_settings class UserManager(BaseUserManager): """ UserManager class for Custom User Model Author: Himanshu Shankar (https://himanshus.com) Source: Can't find link but the following solution is inspired from a solution provided on internet. """ use_in_migrations = True def _create_user(self, username, email, password, fullname, mobile, **extra_fields): """ Creates and saves a User with the given email and password Author: Himanshu Shankar (https://himanshus.com) """ if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model( username=username, email=email, name=fullname, mobile=mobile, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email, password, name, mobile, **extra_fields): """ Creates a normal user considering the specified user settings from Django Project's settings.py Parameters ---------- username: str email: str password: str name: str mobile: str extra_fields: dict Returns ------- User Instance Author: Himanshu Shankar (https://himanshus.com) """ vals = update_user_settings() extra_fields.setdefault("is_superuser", False) extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_active", vals.get("DEFAULT_ACTIVE_STATE", False)) return self._create_user( username, email, password, name, mobile, **extra_fields ) def create_superuser(self, username, email, password, name, mobile, **extra_fields): """ Creates a super user considering the specified user settings from Django Project's settings.py Parameters ---------- username: str email: str password: str name: str mobile: str extra_fields: dict Returns ------- User Instance Author: Himanshu Shankar (https://himanshus.com) """ vals = update_user_settings() extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_active", vals.get("DEFAULT_ACTIVE_STATE", False)) if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") return self._create_user( username, email, password, name, mobile, **extra_fields )
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
43
# Generated by Django 2.0.7 on 2018-07-14 14:21 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import drf_user.managers class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('update_date', models.DateTimeField(auto_now=True, verbose_name='Date Modified')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(max_length=254, unique=True, verbose_name='Unique UserName')), ('email', models.EmailField(max_length=254, unique=True, verbose_name='EMail Address')), ('mobile', models.CharField(max_length=150, unique=True, verbose_name='Mobile Number')), ('name', models.CharField(max_length=500, verbose_name='Full Name')), ('date_joined', models.DateTimeField(auto_now_add=True, verbose_name='Date Joined')), ('is_active', models.BooleanField(default=False, verbose_name='Activated')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'User', 'verbose_name_plural': 'Users', }, managers=[ ('objects', drf_user.managers.UserManager()), ], ), migrations.CreateModel( name='AuthTransaction', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Date Created')), ('ip_address', models.GenericIPAddressField()), ('token', models.TextField(verbose_name='JWT Token passed')), ('session', models.TextField(verbose_name='Session Passed')), ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Authentication Transaction', 'verbose_name_plural': 'Authentication Transactions', }, ), migrations.CreateModel( name='OTPValidation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('update_date', models.DateTimeField(auto_now=True, verbose_name='Date Modified')), ('otp', models.CharField(max_length=10, unique=True, verbose_name='OTP Code')), ('destination', models.CharField(max_length=254, unique=True, verbose_name='Destination Address (Mobile/EMail)')), ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='Create Date')), ('is_validated', models.BooleanField(default=False, verbose_name='Is Validated')), ('validate_attempt', models.IntegerField(default=3, verbose_name='Attempted Validation')), ('type', models.CharField(choices=[('email', 'EMail Address'), ('mobile', 'Mobile Number')], default='email', max_length=15, verbose_name='EMail/Mobile')), ('send_counter', models.IntegerField(default=0, verbose_name='OTP Sent Counter')), ('sms_id', models.CharField(blank=True, max_length=254, null=True, verbose_name='SMS ID')), ('reactive_at', models.DateTimeField(verbose_name='ReActivate Sending OTP')), ], options={ 'verbose_name': 'OTP Validation', 'verbose_name_plural': 'OTP Validations', }, ), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
44
# Generated by Django 2.1.3 on 2018-11-23 06:57 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('drf_user', '0004_auto_20181015_1551'), ] operations = [ migrations.RemoveField( model_name='authtransaction', name='date_created', ), migrations.RemoveField( model_name='authtransaction', name='user', ), migrations.AddField( model_name='authtransaction', name='create_date', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now, verbose_name='Create Date/Time'), preserve_default=False, ), migrations.AddField( model_name='authtransaction', name='created_by', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL), preserve_default=False, ), migrations.AddField( model_name='authtransaction', name='update_date', field=models.DateTimeField(auto_now=True, verbose_name='Date/Time Modified'), ), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
45
# Generated by Django 2.0.8 on 2018-10-15 10:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('drf_user', '0003_auto_20180919_1516'), ] operations = [ migrations.RemoveField( model_name='otpvalidation', name='type', ), migrations.AddField( model_name='otpvalidation', name='prop', field=models.CharField(choices=[('E', 'EMail Address'), ('M', 'Mobile Number')], default='E', max_length=3, verbose_name='Destination Property'), ), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
46
# Generated by Django 2.0.8 on 2018-09-17 07:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('drf_user', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='is_staff', field=models.BooleanField(default=False, verbose_name='Staff Status'), ), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
47
# Generated by Django 3.1.2 on 2020-10-31 20:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('drf_user', '0006_auto_20181220_1911'), ] operations = [ migrations.AddField( model_name='user', name='profile_image', field=models.ImageField(blank=True, null=True, upload_to='user_images', verbose_name='Profile Photo'), ), migrations.AlterField( model_name='user', name='email', field=models.EmailField(max_length=254, unique=True, verbose_name='Email Address'), ), migrations.AlterField( model_name='user', name='mobile', field=models.CharField(blank=True, max_length=150, null=True, unique=True, verbose_name='Mobile Number'), ), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
48
# Generated by Django 2.0.8 on 2018-09-19 09:46 import django.contrib.auth.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('drf_user', '0002_user_is_staff'), ] operations = [ migrations.CreateModel( name='Role', fields=[ ], options={ 'verbose_name': 'Role', 'verbose_name_plural': 'Roles', 'proxy': True, 'indexes': [], }, bases=('auth.group',), managers=[ ('objects', django.contrib.auth.models.GroupManager()), ], ), migrations.AlterField( model_name='user', name='groups', field=models.ManyToManyField(blank=True, help_text='The roles this user belongs to. A user will get all permissions granted to each of their roles.', related_name='user_set', related_query_name='user', to='drf_user.Role', verbose_name='Roles'), ), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
49
# Generated by Django 2.1.4 on 2018-12-20 13:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('drf_user', '0005_auto_20181123_0657'), ] operations = [ migrations.AlterField( model_name='otpvalidation', name='otp', field=models.CharField(max_length=10, verbose_name='OTP Code'), ), ]
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
50
"""Config for django signals""" from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=get_user_model()) def post_register(sender, instance: get_user_model(), created, **kwargs): """Sends mail/message to users after registeration Parameters ---------- sender: get_user_model() instance: get_user_model() created: bool """ from drf_user import user_settings from drfaddons.utils import send_message if created: if user_settings["REGISTRATION"]["SEND_MAIL"]: send_message( message=user_settings["REGISTRATION"]["TEXT_MAIL_BODY"], subject=user_settings["REGISTRATION"]["MAIL_SUBJECT"], recip=[instance.email], recip_email=[instance.email], html_message=user_settings["REGISTRATION"]["HTML_MAIL_BODY"], ) if user_settings["REGISTRATION"]["SEND_MESSAGE"]: send_message( message=user_settings["REGISTRATION"]["SMS_BODY"], subject=user_settings["REGISTRATION"]["MAIL_SUBJECT"], recip=[instance.mobile], recip_email=[instance.mobile], )
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
51
"""To load django signals"""
101loop/drf-user
75
Python,Makefile
__init__.py
text/plain
52
SUBDIRS = src
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
53
#!/bin/bash bash=/bin/bash set -a # set and clear config CONFIG="configure.ac" echo "" > $CONFIG # create pkgconfig-file (.pc) if needed $bash "./debian/pkgconfig.pc.sh" > "./src/$PACKAGE_NAME.pc" echo " dnl use this file with autoconf to produce a configure script. AC_INIT([$PACKAGE_NAME], [$PACKAGE_VERSION]) AC_CONFIG_SRCDIR([README]) AC_CANONICAL_TARGET dnl Setup for automake AM_INIT_AUTOMAKE([foreign]) " >> $CONFIG for suffix in $PKGLIBSADD; do ADD=${suffix%:*} LIB=${suffix#*:} echo "PKG_CHECK_MODULES($ADD, $LIB)" >> $CONFIG done for suffix in $LIBSADD; do LIB=${suffix%:*} FUNC=${suffix#*:} echo "AC_CHECK_LIB($LIB, $FUNC,, AC_MSG_ERROR([library $LIB or $FUNC in $LIB not found!]))" >> $CONFIG done echo " dnl Some defined values AC_DEFINE(PACKAGE_DESC, \"$PACKAGE_DESC\") AC_DEFINE(PACKAGE_VERSION_MAJOR, $PACKAGE_VERSION_MAJOR) AC_DEFINE(PACKAGE_VERSION_MINOR, $PACKAGE_VERSION_MINOR) AC_DEFINE(PACKAGE_VERSION_MICRO, $PACKAGE_VERSION_MICRO) AC_DEFINE(PACKAGE_BUILD, \"$PACKAGE_BUILD\") " >> $CONFIG echo " dnl Check types and sizes AC_CHECK_SIZEOF(short, 2) AC_CHECK_SIZEOF(int, 4) AC_CHECK_SIZEOF(long, 4) AC_CHECK_SIZEOF(long long, 8) " >> $CONFIG echo " dnl Check for tools AC_PROG_CC AM_PROG_LIBTOOL CXXFLAGS=\"\" CFLAGS=\"\" AC_DEFINE(_GNU_SOURCE, 1) " >> $CONFIG echo " AC_ARG_ENABLE([debug], AC_HELP_STRING([--enable-debug], [Enable debug mode (default YES)]), [debug=[yes]], [debug=[no]]) AC_MSG_CHECKING([debug mode]) if test x\$debug == xyes ; then AC_DEFINE(_DEBUG, 1, [Debug mode]) AC_SUBST(GDB_CFLAG, \"-g\") CFLAGS=\"-g -O0 \$CFLAGS\" fi AC_MSG_RESULT([\$debug]) " >> $CONFIG echo " dnl Finally create all the generated files AC_CONFIG_FILES([ Makefile src/Makefile ]) AC_OUTPUT echo \" Configuration for \$PACKAGE_NAME \$PACKAGE_VERSION: debug mode: \$debug \" " >> $CONFIG
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
54
#!/bin/bash set -a # you need to change these values PACKAGE_AUTHORS="Antti Partanen <aehparta@iki.fi>" # examples for section: libs, utils, misc, comm, admin, base PACKAGE_SECTION="libs" PACKAGE_PRIORITY="optional" PACKAGE_NAME="ftdi-bitbang" PACKAGE_DESC="bitbang control through FTDI FTx232 chips" PACKAGE_VERSION_MAJOR="1" PACKAGE_VERSION_MINOR="1" PACKAGE_VERSION_MICRO="0" PACKAGE_VERSION="$PACKAGE_VERSION_MAJOR.$PACKAGE_VERSION_MINOR.$PACKAGE_VERSION_MICRO" # binaries/libraries to install PACKAGE_BINS="ftdi-bitbang ftdi-hd44780 ftdi-control ftdi-spi ftdi-simple-capture" PACKAGE_LIBS="libftdi-bitbang libftdi-hd44780 libftdi-spi" # get build number PACKAGE_BUILD=`cat debian/build` # libraries/binaries to be checked PKGLIBSADD="libftdi1:libftdi1 sdl2:sdl2" LIBSADD="" BINSCHECK="pkg-config:--version" # include headers when making package PACKAGE_HEADERS="ftdi-bitbang.h ftdi-hd44780.h ftdi-spi.h" # check binaries for suffix in $BINSCHECK; do BIN=${suffix%:*} ARG=${suffix#*:} if $BIN $ARG >/dev/null 2>&1; then echo "$BIN found." else echo "$BIN not found! you need to install $BIN" exit 1 fi done echo "Generating configure files... may take a while." ln -f -s README.md README if ! ./configure.ac.sh; then echo "Failed to create configure.ac!" exit 1 fi if ! autoreconf --install --force; then echo "autoreconf failed!" exit 1 fi case "$1" in deb) bash ./debian/create-deb-arch.sh $2 ;; *) ./configure echo "now 'make' to build binaries" echo "then 'make install'" ;; esac
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
55
# Description ***NOTE:*** Current master branch (version 1) will not get any updates anymore. I am working on version 2 of these tools since I got fed up with the hard maintainability of the old code written over last decade. I will release the new version to master branch when I am happy with the new code. ## Command line tools * ftdi-bitbang * ftdi-control * ftdi-hd44780 * ftdi-simple-capture * ftdi-spi *(coming, does not work yet)* ## Libraries * libftdi-bitbang * libftdi-hd44780 ## Compile ```sh ~/ftdi-bitbang$ ./autogen.sh ~/ftdi-bitbang$ make ~/ftdi-bitbang$ make install ``` Or in debian based platforms you can generate debian package: ```sh ~/ftdi-bitbang$ ./autogen.sh deb ~/ftdi-bitbang$ sudo dpkg -i debian/ftdi-bitbang-VERSION-BUILD-ARCH.deb ``` # ftdi-bitbang Simple command line bitbang interface to FTDI FTx232 chips. ``` Usage: ftdi-bitbang [options] Definitions for options: ID = hexadecimal word PIN = decimal between 0 and 15 INTERFACE = integer between 1 and 4 depending on device type Options: -h, --help display this help and exit -V, --vid=ID usb vendor id -P, --pid=ID usb product id as default vid and pid are zero, so any first compatible ftdi device is used -D, --description=STRING usb description (product) to use for opening right device, default none -S, --serial=STRING usb serial to use for opening right device, default none -I, --interface=INTERFACE ftx232 interface number, defaults to first -U, --usbid=ID usbid to use for opening right device (sysfs format, e.g. 1-2.3), default none -R, --reset do usb reset on the device at start -L, --list list devices that can be found with given parameters -s, --set=PIN given pin as output and one -c, --clr=PIN given pin as output and zero -i, --inp=PIN given pin as input multiple -s, -c and -i options can be given -r, --read read pin states, output hexadecimal word --read=PIN read single pin, output binary 0 or 1 ``` # ftdi-control Basic control and eeprom routines for FTDI FTx232 chips. ``` Usage: ftdi-control [options] Definitions for options: ID = hexadecimal word PIN = decimal between 0 and 15 INTERFACE = integer between 1 and 4 depending on device type Options: -h, --help display this help and exit -V, --vid=ID usb vendor id -P, --pid=ID usb product id as default vid and pid are zero, so any first compatible ftdi device is used -D, --description=STRING usb description (product) to use for opening right device, default none -S, --serial=STRING usb serial to use for opening right device, default none -I, --interface=INTERFACE ftx232 interface number, defaults to first -U, --usbid=ID usbid to use for opening right device (sysfs format, e.g. 1-2.3), default none -R, --reset do usb reset on the device at start -L, --list list devices that can be found with given parameters -E, --ee-erase erase eeprom, sometimes needed if eeprom has already been initialized -N, --ee-init erase and initialize eeprom with defaults -o, --ee-decode read eeprom and print decoded information -m, --ee-manufacturer=STRING write manufacturer string -d, --ee-description=STRING write description (product) string -s, --ee-serial=STRING write serial string -l, --ee-serial-len=LENGTH pad serial with randomized ascii letters and numbers to this length (upper case) -x, --ee-serial-hex=LENGTH pad serial with randomized hex to this length (upper case) -n, --ee-serial-dec=LENGTH pad serial with randomized numbers to this length -p, --ee-bus-power=INT bus power drawn by the device (100-500 mA) ``` # ftdi-hd44780 Use HD44780 based LCD displays in 4-bit mode through FTDI FTx232 chips with this command. ``` Usage: ftdi-hd44780 [options] Definitions for options: ID = hexadecimal word PIN = decimal between 0 and 15 INTERFACE = integer between 1 and 4 depending on device type Options: -h, --help display this help and exit -V, --vid=ID usb vendor id -P, --pid=ID usb product id as default vid and pid are zero, so any first compatible ftdi device is used -D, --description=STRING usb description (product) to use for opening right device, default none -S, --serial=STRING usb serial to use for opening right device, default none -I, --interface=INTERFACE ftx232 interface number, defaults to first -R, --reset do usb reset on the device at start -m, --mode=STRING set device bitmode, use 'bitbang' or 'mpsse', default is 'bitbang' for bitbang mode the baud rate is fixed to 1 MHz for now -i, --init initialize hd44780 lcd, usually needed only once at first -4, --d4=PIN data pin 4, default pin is 0 -5, --d5=PIN data pin 5, default pin is 1 -6, --d6=PIN data pin 6, default pin is 2 -7, --d7=PIN data pin 7, default pin is 3 -e, --en=PIN enable pin, default pin is 4 -r, --rw=PIN read/write pin, default pin is 5 -s, --rs=PIN register select pin, default pin is 6 -b, --command=BYTE send raw hd44780 command, decimal or hexadecimal (0x) byte multiple commands can be given, they are run before any later commands described here -C, --clear clear display -M, --home move cursor home -c, --cursor=VALUE cursor on/off and blink, accepts value between 0-3 -t, --text=STRING write given text to display -l, --line=VALUE move cursor to given line, value between 0-3 ``` # ftdi-simple-capture Do simple digital data capturing using FTDI FTx232 chips. Can be used to analyze digital circuit with or without trigger. Example use case would be to capture IR signal at pin #0, trigger on rising edge and capture 500 mS, then feeding it to external script which would filter it as ones and zeroes and so on. ``` Usage: ftdi-simple-capture [options] Definitions for options: ID = hexadecimal word PIN = decimal between 0 and 15 INTERFACE = integer between 1 and 4 depending on device type Options: -h, --help display this help and exit -V, --vid=ID usb vendor id -P, --pid=ID usb product id as default vid and pid are zero, so any first compatible ftdi device is used -D, --description=STRING usb description (product) to use for opening right device, default none -S, --serial=STRING usb serial to use for opening right device, default none -I, --interface=INTERFACE ftx232 interface number, defaults to first -U, --usbid=ID usbid to use for opening right device (sysfs format, e.g. 1-2.3), default none -R, --reset do usb reset on the device at start -L, --list list devices that can be found with given parameters -p, --pins=PINS[0-7] pins to capture, default is '0,1,2,3,4,5,6,7' -t, --trigger=PIN[0-7]:EDGE trigger from pin on rising or falling edge (EDGE = r or f), if trigger is not set, sampling will start immediately -s, --speed=INT sampling speed, default 1000000 (1 MS/s) -l, --time=FLOAT sample for this many seconds, default 1 second Simple capture command for FTDI FTx232 chips. Uses bitbang mode so only ADBUS (pins 0-7) can be sampled. ```
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
56
41
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
57
#!/bin/bash # This script builds debian packages. bash=/bin/bash set -a PACKAGE_ARCH=`uname -m` if [ `uname -m` = "x86_64" ]; then PACKAGE_ARCH="amd64" else PACKAGE_ARCH="i386" fi DEBIAN_ALL=arch/$PACKAGE_ARCH/DEBIAN DEBIAN_ARCH=arch/all/DEBIAN PKGROOT=$PWD/debian PKGDIR="$PKGROOT/$PACKAGE_NAME-$PACKAGE_VERSION-$PACKAGE_BUILD-$PACKAGE_ARCH-deb" PKGDIR_SRC=$PKGROOT/$PACKAGE_NAME-$PACKAGE_VERSION-deb-src SRCDIR=$PKGDIR_SRC/$PACKAGE_NAME-$PACKAGE_VERSION ROOT=$PWD PKGNAME="$PACKAGE_NAME-$PACKAGE_VERSION-$PACKAGE_BUILD-$PACKAGE_ARCH.deb" #PACKAGES_REMOTE_HOST="aehparta@packages.tldr.fi" #PACKAGES_REMOTE_PATH="/home/aehparta/www/tldr.fi/packages/web/ubuntu/bionic/$PACKAGE_ARCH" # Copy binary package files. copy_binpkg_files() { echo "** Copying files..." set -e # create directories mkdir -p "$PKGDIR/DEBIAN" mkdir -p "$PKGDIR/usr" mkdir -p "$PKGDIR/usr/bin" mkdir -p "$PKGDIR/usr/lib" mkdir -p "$PKGDIR/usr/lib/pkgconfig" mkdir -p "$PKGDIR/usr/share" mkdir -p "$PKGDIR/usr/include" # copy debian package files for suffix in control changelog; do if [ -e $PKGROOT/$DEBIAN_ALL/$suffix.sh ]; then $bash $PKGROOT/$DEBIAN_ALL/$suffix.sh > "$PKGDIR/DEBIAN/$suffix" fi if [ -e $PKGROOT/$DEBIAN_ARCH/$suffix.sh ]; then $bash $PKGROOT/$DEBIAN_ARCH/$suffix.sh > "$PKGDIR/DEBIAN/$suffix" fi done for suffix in copyright preinst postinst postrm prerm; do if [ -e $PKGROOT/$DEBIAN_ALL/$suffix ]; then cp $PKGROOT/$DEBIAN_ALL/$suffix "$PKGDIR/DEBIAN" fi if [ -e $PKGROOT/$DEBIAN_ARCH/$suffix ]; then cp $PKGROOT/$DEBIAN_ARCH/$suffix "$PKGDIR/DEBIAN" fi done # copy project files for libname in $PACKAGE_LIBS; do for suffix in a la so so.0 so.0.0.0; do cp -d $ROOT/src/.libs/$libname.$suffix $PKGDIR/usr/lib/ done done for binname in $PACKAGE_BINS; do cp -d $ROOT/src/.libs/$binname $PKGDIR/usr/bin/ done # copy include files for suffix in $PACKAGE_HEADERS; do cp $ROOT/src/$suffix $PKGDIR/usr/include/ done if [ -e $ROOT/src/$PACKAGE_NAME.pc ]; then cp $ROOT/src/$PACKAGE_NAME.pc $PKGDIR/usr/lib/pkgconfig fi set +e } echo "** Creating debian package ($PKGNAME)..." echo "** Build $PACKAGE_BUILD (reset this by editing ./debian/build)" if ! ./configure; then echo "** Error when running configure!" exit 1 fi rm -rf $PKGDIR rm -rf $PKGDIR_SRC if ! make clean all; then echo "** Error while running make!" exit 1 fi if ! copy_binpkg_files; then echo "** Error while copying files!" exit 1 fi echo "** Creating binary package..." cd $PKGROOT if dpkg-deb -b "$PKGDIR" "$PKGNAME"; then echo "** Successfully finished building package." else echo "** Error while building package!" fi if [ "$PACKAGES_REMOTE_HOST" != "" ]; then echo "** Releasing package to the wild" ssh "$PACKAGES_REMOTE_HOST" "rm $PACKAGES_REMOTE_PATH/$PACKAGE_NAME-*-$PACKAGE_ARCH.deb" scp "$PKGNAME" "$PACKAGES_REMOTE_HOST:$PACKAGES_REMOTE_PATH" ssh "$PACKAGES_REMOTE_HOST" "cd $PACKAGES_REMOTE_PATH && dpkg-scanpackages . | gzip -9c > Packages.gz" fi let "PACKAGE_BUILD += 1" echo $PACKAGE_BUILD > $ROOT/debian/build
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
58
#!/bin/sh prefix=/usr exec_prefix=$prefix libdir=$exec_prefix/lib includedir=$exec_prefix/include echo " prefix=$prefix exec_prefix=$exec_prefix libdir=$libdir includedir=$includedir Name: $PACKAGE_NAME Description: $PACKAGE_DESC Version: $PACKAGE_VERSION Libs: -lftdi1 -lusb Cflags: "
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
59
#!/bin/sh
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
60
Copyright (c) 2007 Antti Partanen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
61
#!/bin/sh echo " Source: $PACKAGE_NAME Version: $PACKAGE_VERSION Section: $PACKAGE_SECTION Priority: $PACKAGE_PRIORITY Maintainer: $PACKAGE_AUTHORS Package: $PACKAGE_NAME Architecture: $PACKAGE_ARCH Description: $PACKAGE_DESC Depends: libftdi1-2 "
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
62
#!/bin/sh echo " $PACKAGE_NAME ($PACKAGE_VERSION) experimental; urgency=low * Initial release -- $PACKAGE_AUTHORS "
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
63
/* * ftdi-bitbang * * Common routines for all command line utilies. * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #ifndef __CMD_COMMON_H__ #define __CMD_COMMON_H__ #include <getopt.h> #define COMMON_SHORT_OPTS "hV:P:D:S:I:U:RL" #define COMMON_LONG_OPTS \ { "help", no_argument, NULL, 'h' }, \ { "vid", required_argument, NULL, 'V' }, \ { "pid", required_argument, NULL, 'P' }, \ { "description", required_argument, NULL, 'D' }, \ { "serial", required_argument, NULL, 'S' }, \ { "interface", required_argument, NULL, 'I' }, \ { "usbid", required_argument, NULL, 'U' }, \ { "reset", no_argument, NULL, 'R' }, \ { "list", no_argument, NULL, 'L' }, /** * Command specific option parsing. * * @param c option character * @param optarg optional argument * @return 1 if match, 0 if not */ int p_options(int c, char *optarg); /** * Command specific exit. */ void p_exit(int return_code); /** * Command specific help. */ void p_help(void); /** * Print common help. */ void common_help(int argc, char *argv[]); /** * Parse common options. */ int common_options(int argc, char *argv[], const char opts[], struct option longopts[], int need_args, int no_opts_needed); /** * Print list of matching devices. */ void common_ftdi_list_print(void); /** * Initialize ftdi resources. * * @param argc Argument count. * @param argv Argument array. * @return 0 on success, -1 on errors. */ struct ftdi_context *common_ftdi_init(void); /** * Read data from stdin until whitespace if it is a pipe or file ( | or < is used ). */ unsigned char *common_stdin_read(void); #endif /* __CMD_COMMON_H__ */
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
64
/* * ftdi-hd44780 * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <math.h> #include <time.h> #include "ftdi-hd44780.h" static long double _os_time() { struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); return (long double)((long double)tp.tv_sec + (long double)tp.tv_nsec / 1e9); } static void _os_sleep(long double t) { struct timespec tp; long double integral; t += _os_time(); tp.tv_nsec = (long)(modfl(t, &integral) * 1e9); tp.tv_sec = (time_t)integral; while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &tp, NULL) == EINTR); } static int _write_nibble(struct ftdi_hd44780_context *dev, int rs, uint8_t data) { ftdi_bitbang_set_io(dev->bb, dev->d4, 1); ftdi_bitbang_set_io(dev->bb, dev->d5, 1); ftdi_bitbang_set_io(dev->bb, dev->d6, 1); ftdi_bitbang_set_io(dev->bb, dev->d7, 1); ftdi_bitbang_set_pin(dev->bb, dev->d4, data & 0x1); ftdi_bitbang_set_pin(dev->bb, dev->d5, data & 0x2); ftdi_bitbang_set_pin(dev->bb, dev->d6, data & 0x4); ftdi_bitbang_set_pin(dev->bb, dev->d7, data & 0x8); ftdi_bitbang_set_pin(dev->bb, dev->en, 1); ftdi_bitbang_set_pin(dev->bb, dev->rw, 0); ftdi_bitbang_set_pin(dev->bb, dev->rs, rs); ftdi_bitbang_write(dev->bb); ftdi_bitbang_set_pin(dev->bb, dev->en, 0); ftdi_bitbang_write(dev->bb); return 0; } struct ftdi_hd44780_context *ftdi_hd44780_init(struct ftdi_bitbang_context *bb, int reset, int d4, int d5, int d6, int d7, int en, int rw, int rs) { struct ftdi_hd44780_context *dev = malloc(sizeof(struct ftdi_hd44780_context)); if (!dev) { return NULL; } memset(dev, 0, sizeof(*dev)); /* save args */ dev->bb = bb; dev->d4 = d4; dev->d5 = d5; dev->d6 = d6; dev->d7 = d7; dev->en = en; dev->rw = rw; dev->rs = rs; /* setup io pins as outputs */ int err = 0; err += ftdi_bitbang_set_io(dev->bb, dev->d4, 1); err += ftdi_bitbang_set_io(dev->bb, dev->d5, 1); err += ftdi_bitbang_set_io(dev->bb, dev->d6, 1); err += ftdi_bitbang_set_io(dev->bb, dev->d7, 1); err += ftdi_bitbang_set_io(dev->bb, dev->en, 1); err += ftdi_bitbang_set_io(dev->bb, dev->rw, 1); err += ftdi_bitbang_set_io(dev->bb, dev->rs, 1); if (err != 0) { return NULL; } /* reset hd44780 so that it will be in 4 bit state for sure */ if (reset) { _write_nibble(dev, 0, 0x3); _os_sleep(5e-3); _write_nibble(dev, 0, 0x3); _os_sleep(5e-3); _write_nibble(dev, 0, 0x3); _os_sleep(5e-3); _write_nibble(dev, 0, 0x2); _os_sleep(5e-3); /* entry mode: move cursor right */ ftdi_hd44780_cmd(dev, 0x06); /* display on */ ftdi_hd44780_cmd(dev, 0x0c); /* cursor/shift */ ftdi_hd44780_cmd(dev, 0x10); /* clear display, set cursor home */ ftdi_hd44780_cmd(dev, 0x01); } return dev; } struct ftdi_hd44780_context *ftdi_hd44780_init_simple(struct ftdi_bitbang_context *bb) { return ftdi_hd44780_init(bb, 1, 0, 1, 2, 3, 4, 5, 6); } void ftdi_hd44780_free(struct ftdi_hd44780_context *dev) { free(dev); } int ftdi_hd44780_cmd(struct ftdi_hd44780_context *dev, uint8_t command) { _write_nibble(dev, 0, command >> 4); _write_nibble(dev, 0, command); _os_sleep(2e-3); return 0; } int ftdi_hd44780_write_data(struct ftdi_hd44780_context *dev, uint8_t data) { _write_nibble(dev, 1, data >> 4); _write_nibble(dev, 1, data); _os_sleep(37e-6); return 0; } int ftdi_hd44780_write_char(struct ftdi_hd44780_context *dev, char ch) { // if (ch == '\n') { // return 0; // } // if (dev->line_width > 0 && dev->line_chars_written >= dev->line_width) { // return -1; // } ftdi_hd44780_write_data(dev, (uint8_t)ch); // dev->line_chars_written++; return 0; } int ftdi_hd44780_write_str(struct ftdi_hd44780_context *dev, char *str) { for (int i = 0; i < strlen(str); i++) { ftdi_hd44780_write_char(dev, str[i]); } return 0; } int ftdi_hd44780_goto_xy(struct ftdi_hd44780_context *dev, int x, int y) { if (x < 0 || x > 39 || y < 0 || y > 3) { return -1; } ftdi_hd44780_cmd(dev, 0x80 | (y * 40 + x)); return 0; } int ftdi_hd44780_set_line_width(struct ftdi_hd44780_context *dev, int line_width) { dev->line_width = line_width; return 0; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
65
/* * ftdi-spi * * Only bitbang mode supported for now, built-in MPSSE maybe in the future. * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libftdi1/ftdi.h> #include "ftdi-bitbang.h" #include "ftdi-spi.h" #include "cmd-common.h" const char opts[] = COMMON_SHORT_OPTS "m:c:o:i:s:ladn:CX"; struct option longopts[] = { COMMON_LONG_OPTS { "mode", required_argument, NULL, 'm' }, { "sclk", required_argument, NULL, 'c' }, { "mosi", required_argument, NULL, 'o' }, { "miso", required_argument, NULL, 'i' }, { "ss", required_argument, NULL, 's' }, { "cpol", no_argument, NULL, 'l' }, { "cpha", no_argument, NULL, 'a' }, { "dec", no_argument, NULL, 'd' }, { "size", no_argument, NULL, 'n' }, { "csv", no_argument, NULL, 'C' }, { "0x", no_argument, NULL, 'X' }, { 0, 0, 0, 0 }, }; int sclk = 0; int mosi = 1; int miso = 2; int ss = 3; int cpol = 0; int cpha = 0; int hex_or_dec = 0; int size_of_data = 0; int csv = 0; int add_0x = 0; /* ftdi device context */ struct ftdi_context *ftdi = NULL; struct ftdi_bitbang_context *device = NULL; struct ftdi_spi_context *spi = NULL; int bitmode = 0; /** * Free resources allocated by process, quit using libraries, terminate * connections and so on. This function will use exit() to quit the process. * * @param return_code Value to be returned to parent process. */ void p_exit(int return_code) { if (spi) { ftdi_spi_free(spi); } if (device) { ftdi_bitbang_save_state(device); ftdi_bitbang_free(device); } if (ftdi) { ftdi_free(ftdi); } /* terminate program instantly */ exit(return_code); } void p_help() { printf( " -m, --mode=STRING set device bitmode, use 'bitbang' or 'mpsse', default is 'bitbang'\n" " for bitbang mode the baud rate is fixed to 1 MHz for now\n" " -c, --sclk=PIN SPI SCLK, default pin is 0\n" " -o, --mosi=PIN SPI MOSI, default pin is 1\n" " -i, --miso=PIN SPI MISO, default pin is 2\n" " -s, --ss=PIN SPI SS, default pin is 3\n" " -l, --cpol1 set SPI CPOL to 1 (default 0)\n" " -a, --cpha1 set SPI CPHA to 1 (default 0)\n" " -n, --size=INT size of data to write, default is the count of bytes given as arguments\n" " if less bytes is given as arguments than this value,\n" " the last byte is repeated to fill the size\n" " -d, --dec values use decimal, both input and printed (default is hex)\n" " -X, --0x add 0x to start of each printed hex value (use only without -d)\n" " -C, --csv output as csv\n" "\n" "Bitbang style SPI through FTDI FTx232 chips.\n" "\n" "Examples:\n" " transfer 4 bytes: ftdi-spi ff 00 ff 5a\n" " same using decimals: ftdi-spi -d 255 00 255 90\n" "\n"); } int p_options(int c, char *optarg) { switch (c) { case 'm': if (strcmp("bitbang", optarg) == 0) { bitmode = BITMODE_BITBANG; } else if (strcmp("mpsse", optarg) == 0) { bitmode = BITMODE_MPSSE; } else { fprintf(stderr, "invalid bitmode\n"); return -1; } return 1; case 'c': sclk = atoi(optarg); return 1; case 'o': mosi = atoi(optarg); return 1; case 'i': miso = atoi(optarg); return 1; case 's': ss = atoi(optarg); return 1; case 'l': cpol = 1; return 1; case 'a': cpha = 1; return 1; case 'd': hex_or_dec = 1; return 1; case 'n': size_of_data = atoi(optarg); if (size_of_data < 1) { fprintf(stderr, "invalid data size\n"); return -1; } return 1; case 'C': csv = 1; return 1; case 'X': add_0x = 1; return 1; } return 0; } int main(int argc, char *argv[]) { int err = 0, i; uint8_t *out = NULL, *in = NULL; size_t size = 0; /* parse command line options */ if (common_options(argc, argv, opts, longopts, 1, 0)) { fprintf(stderr, "invalid command line option(s)\n"); p_exit(EXIT_FAILURE); } /* parse write data */ for (i = optind; i < argc; i++) { int v = strtoul(argv[i], NULL, hex_or_dec ? 10 : 16); if (v < 0 || v > 255) { fprintf(stderr, "invalid value given: %s\n", argv[i]); p_exit(EXIT_FAILURE); } out = realloc(out, size + 1); out[size] = v; size++; } if (size > size_of_data && size_of_data > 0) { size = size_of_data; } else if (size < size_of_data) { out = realloc(out, size_of_data); memset(out + size, out[size - 1], size_of_data - size); size = size_of_data; } /* allocate input buffer (which is also used as transfer buffer, so copy output to it) */ in = malloc(size); memcpy(in, out, size); /* print data */ if (csv) { printf("send,recv\n"); for (i = 0; i < size; i++) { if (hex_or_dec) { printf("%u,%u\n", out[i], in[i]); } else { printf("%s%02X,%s%02X\n", add_0x ? "0x" : "", out[i], add_0x ? "0x" : "", in[i]); } } } else { printf("send: "); for (i = 0; i < size; i++) { if (hex_or_dec) { printf("%3u%s", out[i], ((i + 1) < size) ? " " : ""); } else { printf("%s%02X%s", add_0x ? "0x" : "", out[i], ((i + 1) < size) ? " " : ""); } } printf("\n"); printf("recv: "); for (i = 0; i < size; i++) { if (hex_or_dec) { printf("%3u%s", in[i], ((i + 1) < size) ? " " : ""); } else { printf("%s%02X%s", add_0x ? "0x" : "", in[i], ((i + 1) < size) ? " " : ""); } } printf("\n"); } return 0; /* init ftdi things */ ftdi = common_ftdi_init(); if (!ftdi) { p_exit(EXIT_FAILURE); } /* initialize to bitbang mode */ device = ftdi_bitbang_init(ftdi, bitmode, 1); if (!device) { fprintf(stderr, "ftdi_bitbang_init() failed\n"); p_exit(EXIT_FAILURE); } /* initialize spi */ spi = ftdi_spi_init(device, sclk, mosi, miso, ss); if (!spi) { fprintf(stderr, "ftdi_spi_init() failed\n"); return -1; } ftdi_spi_set_mode(spi, cpol, cpha); /* run commands */ // ftdi_spi_enable(spi); // ftdi_spi_transfer_do(spi, 0x060, 11); // printf("0x%04x\n", ftdi_spi_transfer_do(spi, 0, 13)); // ftdi_spi_disable(spi); p_exit(EXIT_SUCCESS); return EXIT_SUCCESS; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
66
/* * ftdi-bitbang * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <math.h> #include <time.h> #include <paths.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <libusb-1.0/libusb.h> #include "ftdi-bitbang.h" struct ftdi_bitbang_context *ftdi_bitbang_init(struct ftdi_context *ftdi, int mode, int load_state) { struct ftdi_bitbang_context *dev = malloc(sizeof(struct ftdi_bitbang_context)); if (!dev) { return NULL; } memset(dev, 0, sizeof(*dev)); /* save args */ dev->ftdi = ftdi; /* load state if requested */ if (load_state) { ftdi_bitbang_load_state(dev); } if (dev->state.mode != BITMODE_RESET && mode != BITMODE_RESET && dev->state.mode != mode) { /* force writing of all pins since mode was changed */ dev->state.l_changed = 0xff; dev->state.h_changed = 0xff; } if (mode != BITMODE_MPSSE && (mode == BITMODE_BITBANG || dev->state.mode == BITMODE_RESET || dev->state.mode == BITMODE_BITBANG)) { /* do not actually set bitmode here, might not know full state yet */ dev->state.mode = BITMODE_BITBANG; /* set baud rate */ /** @todo add support for changing baud rate */ if (ftdi_set_baudrate(dev->ftdi, 1e6)) { free(dev); return NULL; } } else if (ftdi->type == TYPE_4232H) { /* there is no point in supporting MPSSE within this library when using FT4232H */ free(dev); return NULL; } else { /* set bitmode to mpsse */ if (ftdi_set_bitmode(ftdi, 0x00, BITMODE_MPSSE)) { free(dev); return NULL; } dev->state.mode = BITMODE_MPSSE; } return dev; } void ftdi_bitbang_free(struct ftdi_bitbang_context *dev) { free(dev); } int ftdi_bitbang_set_pin(struct ftdi_bitbang_context *dev, int bit, int value) { /* if device is not in MPSSE mode, it only supports pins through 0-7 */ if (dev->state.mode != BITMODE_MPSSE && bit >= 8) { return -1; } /* get which byte it is, higher or lower */ uint8_t *v = bit < 8 ? &dev->state.l_value : &dev->state.h_value; uint8_t *c = bit < 8 ? &dev->state.l_changed : &dev->state.h_changed; /* get bit in byte mask */ uint8_t mask = 1 << (bit - (bit < 8 ? 0 : 8)); /* save old pin state */ uint8_t was = (*v) & mask; /* clear and set new value */ (*v) = ((*v) & ~mask) | (value ? mask : 0); /* set changed if actually changed */ (*c) |= was != ((*v) & mask) ? mask : 0; return 0; } int ftdi_bitbang_set_io(struct ftdi_bitbang_context *dev, int bit, int io) { /* if device is not in MPSSE mode, it only supports pins through 0-7 */ if (dev->state.mode != BITMODE_MPSSE && bit >= 8) { return -1; } /* get which byte it is, higher or lower */ uint8_t *v = bit < 8 ? &dev->state.l_io : &dev->state.h_io; uint8_t *c = bit < 8 ? &dev->state.l_changed : &dev->state.h_changed; /* get bit in byte mask */ uint8_t mask = 1 << (bit - (bit < 8 ? 0 : 8)); /* save old pin state */ uint8_t was = (*v) & mask; /* clear and set new value */ (*v) = ((*v) & ~mask) | (io ? mask : 0); /* set changed */ (*c) |= was != ((*v) & mask) ? mask : 0; return 0; } int ftdi_bitbang_write(struct ftdi_bitbang_context *dev) { if (dev->state.mode == BITMODE_MPSSE) { uint8_t buf[6]; int n = 0; if (dev->state.l_changed) { buf[n++] = 0x80; buf[n++] = dev->state.l_value; buf[n++] = dev->state.l_io; dev->state.l_changed = 0; } if (dev->state.h_changed) { buf[n++] = 0x82; buf[n++] = dev->state.h_value; buf[n++] = dev->state.h_io; dev->state.h_changed = 0; } if (n > 0) { return ftdi_write_data(dev->ftdi, buf, n) > 0 ? 0 : -1; } return 0; } else if (dev->state.mode == BITMODE_BITBANG) { if (!dev->state.l_changed) { return 0; } /** @todo setting bitmode every time, should fix */ if (ftdi_set_bitmode(dev->ftdi, dev->state.l_io, BITMODE_BITBANG)) { return -1; } if (ftdi_write_data(dev->ftdi, &dev->state.l_value, 1) < 1) { return -1; } dev->state.l_changed = 0; dev->state.h_changed = 0; return 0; } return -1; } int ftdi_bitbang_read_low(struct ftdi_bitbang_context *dev) { if (dev->state.mode == BITMODE_MPSSE) { uint8_t buf[1] = { 0x81 }; ftdi_usb_purge_rx_buffer(dev->ftdi); if (ftdi_write_data(dev->ftdi, &buf[0], 1) != 1) { return -1; } if (ftdi_read_data(dev->ftdi, &buf[0], 1) != 1) { return -1; } return (int)buf[0]; } else if (dev->state.mode == BITMODE_BITBANG) { /** @todo setting bitmode every time, should fix */ if (ftdi_set_bitmode(dev->ftdi, dev->state.l_io, BITMODE_BITBANG)) { return -1; } uint8_t pins; if (ftdi_read_pins(dev->ftdi, &pins)) { return -1; } return pins; } return -1; } int ftdi_bitbang_read_high(struct ftdi_bitbang_context *dev) { /* if device is not in MPSSE mode, it only supports pins through 0-7 */ if (dev->state.mode != BITMODE_MPSSE) { return -1; } uint8_t buf[1] = { 0x83 }; ftdi_usb_purge_rx_buffer(dev->ftdi); if (ftdi_write_data(dev->ftdi, &buf[0], 1) != 1) { return -1; } if (ftdi_read_data(dev->ftdi, &buf[0], 1) != 1) { return -1; } return (int)buf[0]; } int ftdi_bitbang_read(struct ftdi_bitbang_context *dev) { int h = 0, l = 0; l = ftdi_bitbang_read_low(dev); /* if device is not in MPSSE mode, it only supports pins through 0-7 */ if (dev->state.mode == BITMODE_MPSSE) { h = ftdi_bitbang_read_high(dev); } if (l < 0 || h < 0) { return -1; } return (h << 8) | l; } int ftdi_bitbang_read_pin(struct ftdi_bitbang_context *dev, uint8_t pin) { if (pin <= 7 && pin >= 0) { return (ftdi_bitbang_read_low(dev) & (1 << pin)) ? 1 : 0; } else if (pin >= 8 && pin <= 15) { /* if device is not in MPSSE mode, it only supports pins through 0-7 */ if (dev->state.mode != BITMODE_MPSSE) { return -1; } return (ftdi_bitbang_read_high(dev) & (1 << (pin - 8))) ? 1 : 0; } return -1; } static char *_generate_state_filename(struct ftdi_bitbang_context *dev) { int i; char *state_filename = NULL; uint8_t bus, addr, port; libusb_device *usb_dev = libusb_get_device(dev->ftdi->usb_dev); /* create unique device filename */ bus = libusb_get_bus_number(usb_dev); addr = libusb_get_device_address(usb_dev); port = libusb_get_port_number(usb_dev); i = asprintf(&state_filename, "%sftdi-bitbang-device-state-%03d.%03d.%03d-%d.%d-%d", _PATH_TMP, bus, addr, port, dev->ftdi->interface, dev->ftdi->type, (unsigned int)getuid()); if (i < 1 || !state_filename) { return NULL; } return state_filename; } int ftdi_bitbang_load_state(struct ftdi_bitbang_context *dev) { int fd, n; char *state_filename; struct ftdi_bitbang_state state; /* generate filename and open file */ state_filename = _generate_state_filename(dev); if (!state_filename) { return -1; } fd = open(state_filename, O_RDONLY); if (fd < 0) { free(state_filename); return -1; } /* read contents */ n = read(fd, &state, sizeof(state)); if (n == sizeof(state)) { memcpy(&dev->state, &state, sizeof(state)); } /* free resources */ free(state_filename); close(fd); return 0; } int ftdi_bitbang_save_state(struct ftdi_bitbang_context *dev) { int fd, n; char *state_filename; /* generate filename and open file */ state_filename = _generate_state_filename(dev); if (!state_filename) { return -1; } fd = open(state_filename, O_WRONLY | O_CREAT); if (fd < 0) { free(state_filename); return -1; } /* write contents */ n = write(fd, &dev->state, sizeof(dev->state)); if (n == sizeof(dev->state)) { /* set accessible only by current user */ fchmod(fd, 0600); } /* free resources */ free(state_filename); close(fd); return 0; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
67
/* * ftdi-spi * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #ifndef __FTDI_SPI_H__ #define __FTDI_SPI_H__ #include <stdlib.h> #include <ftdi.h> #include "ftdi-bitbang.h" struct ftdi_spi_context { struct ftdi_bitbang_context *bb; int sclk; int mosi; int miso; int ss; int cpol; int cpha; int sspol; }; struct ftdi_spi_context *ftdi_spi_init(struct ftdi_bitbang_context *bb, int sclk, int mosi, int miso, int ss); void ftdi_spi_free(struct ftdi_spi_context *spi); void ftdi_spi_set_mode(struct ftdi_spi_context *spi, int cpol, int cpha); /** * Enable SPI slave. * @param spi spi context * @return 0 on success or -1 on errors */ int ftdi_spi_enable(struct ftdi_spi_context *spi); /** * Disable SPI slave. * @param spi spi context * @return 0 on success or -1 on errors */ int ftdi_spi_disable(struct ftdi_spi_context *spi); /** * Transfer data to and from SPI slave. * You need to enable slave first. Use ftdi_spi_enable() or * set ss pin active manually. * * @param spi spi context * @param data data buffer, writes data from here and then saves read data here * @param size size of data in bytes * @return data bits read or -1 on errors */ int ftdi_spi_transfer_do(struct ftdi_spi_context *spi, uint8_t *data, size_t size); /** * Does same as ftdi_spi_transfer_do() but with automatic slave enable/disable. * * @param spi spi context * @param data data buffer, writes data from here and then saves read data here * @param size size of data in bytes * @return data bits read or -1 on errors */ int ftdi_spi_transfer(struct ftdi_spi_context *spi, uint8_t *data, size_t size); #endif /* __FTDI_SPI_H__ */
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
68
## Makefile.am for ftdi-something libs and commands bin_PROGRAMS = ftdi-bitbang ftdi-hd44780 ftdi-control ftdi-simple-capture ftdi-spi lib_LTLIBRARIES = libftdi-bitbang.la libftdi-hd44780.la libftdi-spi.la ftdi_bitbang_SOURCES = cmd-bitbang.c cmd-common.c ftdi_hd44780_SOURCES = cmd-hd44780.c cmd-common.c ftdi_control_SOURCES = cmd-control.c cmd-common.c ftdi_spi_SOURCES = cmd-spi.c cmd-common.c ftdi_simple_capture_SOURCES = cmd-simple-capture.c cmd-common.c # ftdi_simple_scope_SOURCES = cmd-simple-scope.c cmd-common.c libftdi_bitbang_la_SOURCES = ftdi-bitbang.c libftdi_bitbang_la_LDFLAGS = @libftdi1_LIBS@ libftdi_bitbang_la_CFLAGS = @libftdi1_CFLAGS@ libftdi_hd44780_la_SOURCES = ftdi-hd44780.c libftdi_hd44780_la_LIBADD = libftdi-bitbang.la libftdi_hd44780_la_LDFLAGS = @libftdi1_LIBS@ libftdi_hd44780_la_CFLAGS = @libftdi1_CFLAGS@ libftdi_spi_la_SOURCES = ftdi-spi.c libftdi_spi_la_LIBADD = libftdi-bitbang.la libftdi_spi_la_LDFLAGS = @libftdi1_LIBS@ libftdi_spi_la_CFLAGS = @libftdi1_CFLAGS@ ftdi_bitbang_LDADD = libftdi-bitbang.la ftdi_bitbang_LDFLAGS = @libftdi1_LIBS@ ftdi_bitbang_CFLAGS = @libftdi1_CFLAGS@ ftdi_hd44780_LDADD = libftdi-bitbang.la libftdi-hd44780.la ftdi_hd44780_LDFLAGS = @libftdi1_LIBS@ ftdi_hd44780_CFLAGS = @libftdi1_CFLAGS@ ftdi_control_LDADD = libftdi-bitbang.la ftdi_control_LDFLAGS = @libftdi1_LIBS@ ftdi_control_CFLAGS = @libftdi1_CFLAGS@ ftdi_spi_LDADD = libftdi-bitbang.la libftdi-spi.la ftdi_spi_LDFLAGS = @libftdi1_LIBS@ ftdi_spi_CFLAGS = @libftdi1_CFLAGS@ ftdi_simple_capture_LDADD = libftdi-bitbang.la ftdi_simple_capture_LDFLAGS = -lpthread @libftdi1_LIBS@ ftdi_simple_capture_CFLAGS = @libftdi1_CFLAGS@ # ftdi_simple_scope_LDADD = libftdi-bitbang.la # ftdi_simple_scope_LDFLAGS = -lpthread @libftdi1_LIBS@ @sdl2_LIBS@ # ftdi_simple_scope_CFLAGS = @libftdi1_CFLAGS@ @sdl2_CFLAGS@ include_HEADERS = ftdi-bitbang.h ftdi-hd44780.h pkgconfigdir = @libdir@/pkgconfig pkgconfig_DATA = @PACKAGE_NAME@.pc
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
69
/* * ftdi-spi * * Only bitbang mode supported for now, built-in MPSSE maybe in the future. * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "ftdi-spi.h" struct ftdi_spi_context *ftdi_spi_init(struct ftdi_bitbang_context *bb, int sclk, int mosi, int miso, int ss) { struct ftdi_spi_context *spi = malloc(sizeof(struct ftdi_spi_context)); if (!spi) { return NULL; } memset(spi, 0, sizeof(*spi)); /* save args */ spi->bb = bb; spi->sclk = sclk; spi->mosi = mosi; spi->miso = miso; spi->ss = ss; /* default clock polarity and phase */ spi->cpol = 0; spi->cpha = 0; /* default select pin polarity */ spi->sspol = 0; /* setup io pin directions */ ftdi_bitbang_set_io(spi->bb, spi->sclk, 1); ftdi_bitbang_set_io(spi->bb, spi->mosi, 1); ftdi_bitbang_set_io(spi->bb, spi->miso, 0); ftdi_bitbang_set_io(spi->bb, spi->ss, 1); /* setup initial state */ ftdi_bitbang_set_pin(spi->bb, spi->sclk, spi->cpol); if (spi->ss > -1) { ftdi_bitbang_set_pin(spi->bb, spi->ss, spi->sspol ? 0 : 1); } ftdi_bitbang_write(spi->bb); return spi; } void ftdi_spi_free(struct ftdi_spi_context *spi) { free(spi); } void ftdi_spi_set_mode(struct ftdi_spi_context *spi, int cpol, int cpha) { spi->cpol = cpol ? 1 : 0; spi->cpha = cpha ? 1 : 0; /* change initial sclk state */ ftdi_bitbang_set_pin(spi->bb, spi->sclk, spi->cpol); ftdi_bitbang_write(spi->bb); } int ftdi_spi_enable(struct ftdi_spi_context *spi) { /* enable slave */ if (spi->ss > -1) { ftdi_bitbang_set_pin(spi->bb, spi->ss, spi->sspol); return ftdi_bitbang_write(spi->bb); } return 0; } int ftdi_spi_disable(struct ftdi_spi_context *spi) { /* disable slave */ if (spi->ss > -1) { ftdi_bitbang_set_pin(spi->bb, spi->ss, spi->sspol ? 0 : 1); return ftdi_bitbang_write(spi->bb); } return 0; } int ftdi_spi_transfer_do(struct ftdi_spi_context *spi, uint8_t *data, size_t size) { int i, data_read, data_write, bit_count; /* bit count to zero indexed */ bit_count--; /* write first bit out now if phase is 0 (default) */ if (!spi->cpha) { ftdi_bitbang_set_pin(spi->bb, spi->mosi, (data_write & (1 << bit_count)) ? 1 : 0); if (ftdi_bitbang_write(spi->bb) < 0) { return -1; } } /* transfer data */ for (i = bit_count; i >= 0; i--) { /* write if phase is 1 */ if (spi->cpha) { ftdi_bitbang_set_pin(spi->bb, spi->mosi, (data_write & (1 << bit_count)) ? 1 : 0); } /* clock active (high or low depending on polarity) */ ftdi_bitbang_set_pin(spi->bb, spi->sclk, spi->cpol ? 0 : 1); if (ftdi_bitbang_write(spi->bb) < 0) { return -1; } /* read and write if phase is 0 */ if (!spi->cpha) { int v = ftdi_bitbang_read_pin(spi->bb, spi->miso); if (v < 0) { return -1; } data_read = (data_read << 1) | v; /* next bit */ if (bit_count > 0) { ftdi_bitbang_set_pin(spi->bb, spi->mosi, (data_write & (1 << (bit_count - 1))) ? 1 : 0); } } /* clock inactive */ ftdi_bitbang_set_pin(spi->bb, spi->sclk, spi->cpol); if (ftdi_bitbang_write(spi->bb) < 0) { return -1; } /* read if phase is 1 */ if (spi->cpha) { int v = ftdi_bitbang_read_pin(spi->bb, spi->miso); if (v < 0) { return -1; } data_read = (data_read << 1) | v; } } return data_read; } int ftdi_spi_transfer(struct ftdi_spi_context *spi, uint8_t *data, size_t size) { if (ftdi_spi_enable(spi) < 0) { return -1; } int err = ftdi_spi_transfer_do(spi, data, size); if (ftdi_spi_disable(spi) < 0) { return -1; } return err; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
70
/* * ftdi-bitbang * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #ifndef __FTDI_bitbang_H__ #define __FTDI_bitbang_H__ #include <stdlib.h> #include <libftdi1/ftdi.h> struct ftdi_bitbang_state { uint8_t l_value; uint8_t l_changed; uint8_t l_io; uint8_t h_value; uint8_t h_changed; uint8_t h_io; /* BITMODE_BITBANG or BITMODE_MPSSE */ int mode; }; struct ftdi_bitbang_context { struct ftdi_context *ftdi; struct ftdi_bitbang_state state; }; struct ftdi_bitbang_context *ftdi_bitbang_init(struct ftdi_context *ftdi, int mode, int load_state); void ftdi_bitbang_free(struct ftdi_bitbang_context *dev); int ftdi_bitbang_set_pin(struct ftdi_bitbang_context *dev, int bit, int value); int ftdi_bitbang_set_io(struct ftdi_bitbang_context *dev, int bit, int io); int ftdi_bitbang_write(struct ftdi_bitbang_context *dev); int ftdi_bitbang_read_low(struct ftdi_bitbang_context *dev); int ftdi_bitbang_read_high(struct ftdi_bitbang_context *dev); int ftdi_bitbang_read(struct ftdi_bitbang_context *dev); int ftdi_bitbang_read_pin(struct ftdi_bitbang_context *dev, uint8_t pin); int ftdi_bitbang_load_state(struct ftdi_bitbang_context *dev); int ftdi_bitbang_save_state(struct ftdi_bitbang_context *dev); #endif /* __FTDI_bitbang_H__ */
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
71
/* * ftdi-bitbang * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <errno.h> #include <pthread.h> #include <libftdi1/ftdi.h> #include <SDL.h> #include <signal.h> #include "cmd-common.h" #include "linkedlist.h" const char opts[] = COMMON_SHORT_OPTS "p:t:s:l:"; struct option longopts[] = { COMMON_LONG_OPTS { "pins", required_argument, NULL, 'p' }, { "trigger", required_argument, NULL, 't' }, { "speed", required_argument, NULL, 's' }, { "time", required_argument, NULL, 'l' }, { 0, 0, 0, 0 }, }; /* which pins state to read */ uint8_t pins_mask = 0xff; /* trigger type: -1 is no trigger, 0 is falling edge, 1 is rising edge */ int trigger_type = -1; /* trigger mask */ uint8_t trigger_mask = 0; /* sampling speed */ int sampling_speed = 1e6; /* sampling time */ double sampling_time = 1.0; /* ftdi device context */ struct ftdi_context *ftdi = NULL; unsigned int ftdi_chunksize; struct sample { uint8_t *data; struct sample *prev; struct sample *next; }; struct sample *sample_first = NULL; struct sample *sample_last = NULL; pthread_t sample_thread; pthread_mutex_t sample_lock; volatile int sample_exec = 0; SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; int window_w = 1280; int window_h = 720; /** * Free resources allocated by process, quit using libraries, terminate * connections and so on. This function will use exit() to quit the process. * * @param return_code Value to be returned to parent process. */ void p_exit(int return_code) { struct sample *sample; if (sample_exec) { sample_exec = 0; pthread_join(sample_thread, NULL); } pthread_mutex_destroy(&sample_lock); if (ftdi) { ftdi_free(ftdi); } LL_GET(sample_first, sample_last, sample); while (sample) { free(sample->data); free(sample); LL_GET(sample_first, sample_last, sample); } if (renderer) { SDL_DestroyRenderer(renderer); } if (window) { SDL_DestroyWindow(window); } SDL_Quit(); /* terminate program instantly */ exit(return_code); } void p_help() { printf( " -p, --pins=PINS[0-7] pins to capture, default is '0,1,2,3,4,5,6,7'\n" " -t, --trigger=PIN[0-7]:EDGE\n" " trigger from pin on rising or falling edge (EDGE = r or f),\n" " if trigger is not set, sampling will start immediately\n" " -s, --speed=INT sampling speed, default 1000000 (1 MS/s)\n" " -l, --time=FLOAT sample for this many seconds, default 1 second\n" "\n" "Simple capture command for FTDI FTx232 chips.\n" "Uses bitbang mode so only ADBUS (pins 0-7) can be sampled.\n" "\n"); } int p_options(int c, char *optarg) { int i; char *token; switch (c) { case 'p': /* clear default to no pins */ pins_mask = 0x00; for (token = strsep(&optarg, ","); token; token = strsep(&optarg, ",")) { int x = atoi(token); if (x < 0 || x > 7) { fprintf(stderr, "invalid pin: %d\n", x); return -1; } pins_mask |= (1 << x); } return 1; case 't': token = strsep(&optarg, ":"); if (!optarg) { fprintf(stderr, "invalid trigger format\n"); return -1; } i = atoi(token); if (i < 0 || i > 7) { fprintf(stderr, "invalid trigger pid: %d\n", i); return -1; } if (*optarg != 'r' && *optarg != 'f') { fprintf(stderr, "invalid trigger edge type: %s\n", optarg); return -1; } trigger_type = *optarg == 'r' ? 1 : 0; trigger_mask = (1 << i); return 1; case 's': sampling_speed = (int)atof(optarg); if (sampling_speed <= 0) { fprintf(stderr, "invalid sampling speed: %d\n", sampling_speed); return -1; } if (sampling_speed > 1e6) { fprintf(stderr, "NOTE: sampling speeds over 1 MS/s have been tested as unreliable\n"); } return 1; case 'l': sampling_time = atof(optarg); if (sampling_time <= 0) { fprintf(stderr, "invalid sampling time: %f\n", sampling_time); return -1; } return 1; } return 0; } static long double os_time() { struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); return (long double)((long double)tp.tv_sec + (long double)tp.tv_nsec / 1e9); } static void os_sleep(long double t) { struct timespec tp; long double integral; t += os_time(); tp.tv_nsec = (long)(modfl(t, &integral) * 1e9); tp.tv_sec = (time_t)integral; while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &tp, NULL) == EINTR); } static void *sample_do(void *p) { struct sample *sample = NULL; int n, c; /* capture data continuosly until told to stop */ sample_exec = 1; while (sample_exec) { /* allocate new sample buffer */ if (!sample) { sample = (struct sample *)malloc(sizeof(*sample)); sample->data = (uint8_t *)malloc(ftdi_chunksize); n = 0; } /* read data into buffer */ c = ftdi_read_data(ftdi, sample->data + n, ftdi_chunksize - n); if (c > 0) { n += c; } else if (c < 0) { fprintf(stderr, "sample read failure: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } /* continue read if buffer not full */ if (n < ftdi_chunksize) { continue; } /* append sample into queue */ pthread_mutex_lock(&sample_lock); LL_APP(sample_first, sample_last, sample); pthread_mutex_unlock(&sample_lock); sample = NULL; } return NULL; } static char *get_sampled_pins_str(uint8_t value) { static char str[128]; if (value & pins_mask) { strcpy(str, "1"); } else { strcpy(str, "0"); } return str; } static int read_samples() { int err = 0, i = 0, x_last, y_last, last_value; double t; struct sample *sample = NULL; int tt = trigger_type; /* if trigger is set, wait for it */ if (tt > -1) { fprintf(stderr, "waiting for trigger on the %s edge with mask 0x%02x\n", tt == 1 ? "rising" : "falling", trigger_mask); } for (last_value = -1; tt > -1; ) { /* check if we should exit */ SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { p_exit(EXIT_SUCCESS); } } /* if sample exists and no trigger occured */ if (sample) { free(sample->data); free(sample); } /* get sample from queue */ pthread_mutex_lock(&sample_lock); LL_GET(sample_first, sample_last, sample); pthread_mutex_unlock(&sample_lock); /* if no sample, sleep a little and try again */ if (!sample) { os_sleep(0.01); continue; } /* check for trigger */ for (i = 0; i < ftdi_chunksize; i++) { /* fill last value if this is first sample */ if (last_value < 0) { last_value = sample->data[i]; continue; } /* check for trigger by type */ if (tt == 0 && (last_value & trigger_mask) && !(sample->data[i] & trigger_mask)) { fprintf(stderr, "falling edge trigger detected\n"); tt = -1; break; } else if (tt == 1 && !(last_value & trigger_mask) && (sample->data[i] & trigger_mask)) { fprintf(stderr, "rising edge trigger detected\n"); tt = -1; break; } last_value = sample->data[i]; } } /* clear screen */ SDL_SetRenderDrawColor(renderer, 0, 32, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 0, 192, 0, SDL_ALPHA_OPAQUE); /* read samples data */ fprintf(stderr, "reading data...\n"); for (t = 0.0, x_last = -1, y_last = -1, last_value = -1; t <= sampling_time; ) { /* get next sample from queue */ if (!sample) { pthread_mutex_lock(&sample_lock); LL_GET(sample_first, sample_last, sample); pthread_mutex_unlock(&sample_lock); } /* wait for more samples */ if (!sample) { os_sleep(0.01); continue; } /* manage sample data */ for ( ; i < ftdi_chunksize; i++) { if (last_value < 0 || (last_value & pins_mask) != (sample->data[i] & pins_mask)) { if (x_last < 0) { x_last = 0; y_last = (sample->data[i] & pins_mask) ? 10 : window_h - 20; } else { int x = (int)((double)window_w * t / sampling_time); int y = (sample->data[i] & pins_mask) ? 10 : window_h - 20; SDL_RenderDrawLine(renderer, x_last, y_last, x, y); x_last = x; y_last = y; } } last_value = sample->data[i]; t += 1.0 / (double)sampling_speed; if (t > sampling_time) { break; } } i = 0; free(sample->data); free(sample); sample = NULL; } SDL_RenderPresent(renderer); } void sig_catch_int(int signum) { signal(signum, sig_catch_int); p_exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { signal(SIGINT, sig_catch_int); /* parse command line options */ if (common_options(argc, argv, opts, longopts, 0)) { fprintf(stderr, "invalid command line option(s)\n"); p_exit(EXIT_FAILURE); } /* init ftdi things */ ftdi = common_ftdi_init(); if (!ftdi) { p_exit(EXIT_FAILURE); } ftdi_set_latency_timer(ftdi, 1); // ftdi_write_data_set_chunksize(ftdi, FTDI_READ_BUFFER_SIZE); // ftdi_read_data_set_chunksize(ftdi, FTDI_READ_BUFFER_SIZE); ftdi_read_data_get_chunksize(ftdi, &ftdi_chunksize); ftdi_set_bitmode(ftdi, 0, BITMODE_RESET); if (ftdi_set_bitmode(ftdi, 0x00, BITMODE_BITBANG)) { fprintf(stderr, "unable to enable bitbang: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } if (ftdi_set_baudrate(ftdi, sampling_speed / 20)) { fprintf(stderr, "%s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } /* init graphics */ if (SDL_Init(SDL_INIT_VIDEO)) { fprintf(stderr, "SDL initialization failed"); p_exit(EXIT_FAILURE); } if (SDL_CreateWindowAndRenderer(window_w, window_h, 0, &window, &renderer)) { fprintf(stderr, "creating scope window failed"); p_exit(EXIT_FAILURE); } SDL_SetRenderDrawColor(renderer, 0, 32, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); SDL_RenderPresent(renderer); /* init sampling thread */ pthread_mutex_init(&sample_lock, NULL); pthread_create(&sample_thread, NULL, sample_do, NULL); while (!sample_exec) { os_sleep(0.01); } /* start sampling */ while (1) { read_samples(); } p_exit(EXIT_SUCCESS); return EXIT_SUCCESS; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
72
/* * ftdi-hd44780 * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #ifndef __FTDI_HD44780_H__ #define __FTDI_HD44780_H__ #include <stdlib.h> #include <ftdi.h> #include "ftdi-bitbang.h" struct ftdi_hd44780_context { struct ftdi_bitbang_context *bb; int d4; int d5; int d6; int d7; int en; int rw; int rs; int line_width; int line_chars_written; }; struct ftdi_hd44780_context *ftdi_hd44780_init(struct ftdi_bitbang_context *bb, int reset, int d4, int d5, int d6, int d7, int en, int rw, int rs); struct ftdi_hd44780_context * ftdi_hd44780_init_simple(struct ftdi_bitbang_context *bb); void ftdi_hd44780_free(struct ftdi_hd44780_context *dev); int ftdi_hd44780_cmd(struct ftdi_hd44780_context *dev, uint8_t command); int ftdi_hd44780_write_data(struct ftdi_hd44780_context *dev, uint8_t data); int ftdi_hd44780_write_char(struct ftdi_hd44780_context *dev, char ch); int ftdi_hd44780_write_str(struct ftdi_hd44780_context *dev, char *str); int ftdi_hd44780_goto_xy(struct ftdi_hd44780_context *dev, int x, int y); int ftdi_hd44780_set_line_width(struct ftdi_hd44780_context *dev, int line_width); #endif /* __FTDI_HD44780_H__ */
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
73
/* * ftdi-bitbang * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <errno.h> #include <pthread.h> #include <libftdi1/ftdi.h> #include <signal.h> #include "cmd-common.h" #include "linkedlist.h" const char opts[] = COMMON_SHORT_OPTS "p:t:s:l:"; struct option longopts[] = { COMMON_LONG_OPTS { "pins", required_argument, NULL, 'p' }, { "trigger", required_argument, NULL, 't' }, { "speed", required_argument, NULL, 's' }, { "time", required_argument, NULL, 'l' }, { 0, 0, 0, 0 }, }; /* which pins state to read */ uint8_t pins_mask = 0xff; /* trigger type: -1 is no trigger, 0 is falling edge, 1 is rising edge */ int trigger_type = -1; /* trigger mask */ uint8_t trigger_mask = 0; /* sampling speed */ int sampling_speed = 1e6; /* sampling time */ double sampling_time = 1.0; /* ftdi device context */ struct ftdi_context *ftdi = NULL; unsigned int ftdi_chunksize; struct sample { uint8_t *data; struct sample *prev; struct sample *next; }; struct sample *sample_first = NULL; struct sample *sample_last = NULL; pthread_t sample_thread; pthread_mutex_t sample_lock; volatile int sample_exec = 0; /** * Free resources allocated by process, quit using libraries, terminate * connections and so on. This function will use exit() to quit the process. * * @param return_code Value to be returned to parent process. */ void p_exit(int return_code) { struct sample *sample; if (sample_exec) { sample_exec = 0; pthread_join(sample_thread, NULL); } pthread_mutex_destroy(&sample_lock); if (ftdi) { ftdi_free(ftdi); } LL_GET(sample_first, sample_last, sample); while (sample) { free(sample->data); free(sample); LL_GET(sample_first, sample_last, sample); } /* terminate program instantly */ exit(return_code); } void p_help() { printf( " -p, --pins=PINS[0-7] pins to capture, default is '0,1,2,3,4,5,6,7'\n" " -t, --trigger=PIN[0-7]:EDGE\n" " trigger from pin on rising or falling edge (EDGE = r or f),\n" " if trigger is not set, sampling will start immediately\n" " -s, --speed=INT sampling speed, default 1000000 (1 MS/s)\n" " -l, --time=FLOAT sample for this many seconds, default 1 second\n" "\n" "Simple capture command for FTDI FTx232 chips.\n" "Uses bitbang mode so only ADBUS (pins 0-7) can be sampled.\n" "\n"); } int p_options(int c, char *optarg) { int i; char *token; switch (c) { case 'p': /* clear default to no pins */ pins_mask = 0x00; for (token = strsep(&optarg, ","); token; token = strsep(&optarg, ",")) { int x = atoi(token); if (x < 0 || x > 7) { fprintf(stderr, "invalid pin: %d\n", x); return -1; } pins_mask |= (1 << x); } return 1; case 't': token = strsep(&optarg, ":"); if (!optarg) { fprintf(stderr, "invalid trigger format\n"); return -1; } i = atoi(token); if (i < 0 || i > 7) { fprintf(stderr, "invalid trigger pid: %d\n", i); return -1; } if (*optarg != 'r' && *optarg != 'f') { fprintf(stderr, "invalid trigger edge type: %s\n", optarg); return -1; } trigger_type = *optarg == 'r' ? 1 : 0; trigger_mask = (1 << i); return 1; case 's': sampling_speed = (int)atof(optarg); if (sampling_speed <= 0) { fprintf(stderr, "invalid sampling speed: %d\n", sampling_speed); return -1; } if (sampling_speed > 1e6) { fprintf(stderr, "NOTE: sampling speeds over 1 MS/s have been tested as unreliable\n"); } return 1; case 'l': sampling_time = atof(optarg); if (sampling_time <= 0) { fprintf(stderr, "invalid sampling time: %f\n", sampling_time); return -1; } return 1; } return 0; } static long double os_time() { struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); return (long double)((long double)tp.tv_sec + (long double)tp.tv_nsec / 1e9); } static void os_sleep(long double t) { struct timespec tp; long double integral; t += os_time(); tp.tv_nsec = (long)(modfl(t, &integral) * 1e9); tp.tv_sec = (time_t)integral; while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &tp, NULL) == EINTR); } static void *sample_do(void *p) { struct sample *sample = NULL; int n, c; /* capture data continuosly until told to stop */ sample_exec = 1; while (sample_exec) { /* allocate new sample buffer */ if (!sample) { sample = (struct sample *)malloc(sizeof(*sample)); sample->data = (uint8_t *)malloc(ftdi_chunksize); n = 0; } /* read data into buffer */ c = ftdi_read_data(ftdi, sample->data + n, ftdi_chunksize - n); if (c > 0) { n += c; } else if (c < 0) { fprintf(stderr, "sample read failure: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } /* continue read if buffer not full */ if (n < ftdi_chunksize) { continue; } /* append sample into queue */ pthread_mutex_lock(&sample_lock); LL_APP(sample_first, sample_last, sample); pthread_mutex_unlock(&sample_lock); sample = NULL; } return NULL; } static char *get_sampled_pins_str(uint8_t value) { static char str[128]; if (value & pins_mask) { strcpy(str, "1"); } else { strcpy(str, "0"); } return str; } void sig_catch_int(int signum) { signal(signum, sig_catch_int); p_exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { int err = 0, i; double t; struct sample *sample = NULL; signal(SIGINT, sig_catch_int); /* parse command line options */ if (common_options(argc, argv, opts, longopts, 0, 0)) { fprintf(stderr, "invalid command line option(s)\n"); p_exit(EXIT_FAILURE); } /* init ftdi things */ ftdi = common_ftdi_init(); if (!ftdi) { p_exit(EXIT_FAILURE); } ftdi_set_latency_timer(ftdi, 1); // ftdi_write_data_set_chunksize(ftdi, FTDI_READ_BUFFER_SIZE); // ftdi_read_data_set_chunksize(ftdi, FTDI_READ_BUFFER_SIZE); ftdi_read_data_get_chunksize(ftdi, &ftdi_chunksize); ftdi_set_bitmode(ftdi, 0, BITMODE_RESET); if (ftdi_set_bitmode(ftdi, 0x00, BITMODE_BITBANG)) { fprintf(stderr, "unable to enable bitbang: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } if (ftdi_set_baudrate(ftdi, sampling_speed / 20)) { fprintf(stderr, "%s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } /* init sampling thread */ pthread_mutex_init(&sample_lock, NULL); pthread_create(&sample_thread, NULL, sample_do, NULL); while (!sample_exec) { os_sleep(0.01); } /* set i to zero here, it wont be zero later if trigger was applied */ i = 0; /* if trigger is set, wait for it */ if (trigger_type > -1) { fprintf(stderr, "waiting for trigger on the %s edge with mask 0x%02x\n", trigger_type == 1 ? "rising" : "falling", trigger_mask); } while (trigger_type > -1) { /* if sample exists and no trigger occured */ if (sample) { free(sample->data); free(sample); } /* get sample from queue */ pthread_mutex_lock(&sample_lock); LL_GET(sample_first, sample_last, sample); pthread_mutex_unlock(&sample_lock); /* if no sample, sleep a little and try again */ if (!sample) { os_sleep(0.01); continue; } /* check for trigger */ for (i = 0; i < ftdi_chunksize; i++) { static int last_value = -1; /* fill last value if this is first sample */ if (last_value < 0) { last_value = sample->data[i]; continue; } /* check for trigger by type */ if (trigger_type == 0 && (last_value & trigger_mask) && !(sample->data[i] & trigger_mask)) { fprintf(stderr, "falling edge trigger detected\n"); trigger_type = -1; break; } else if (trigger_type == 1 && !(last_value & trigger_mask) && (sample->data[i] & trigger_mask)) { fprintf(stderr, "rising edge trigger detected\n"); trigger_type = -1; break; } last_value = sample->data[i]; } } /* read samples data */ fprintf(stderr, "reading data...\n"); for (t = 0.0; t <= sampling_time; ) { /* get next sample from queue */ if (!sample) { pthread_mutex_lock(&sample_lock); LL_GET(sample_first, sample_last, sample); pthread_mutex_unlock(&sample_lock); } /* wait for more samples */ if (!sample) { os_sleep(0.01); continue; } /* manage sample data */ for ( ; i < ftdi_chunksize; i++) { static int last_value = -1; if (last_value < 0 || (last_value & pins_mask) != (sample->data[i] & pins_mask)) { fprintf(stdout, "%g,%s\n", t, get_sampled_pins_str(sample->data[i])); } last_value = sample->data[i]; t += 1.0 / (double)sampling_speed; if (t > sampling_time) { break; } } i = 0; free(sample->data); free(sample); sample = NULL; } p_exit(EXIT_SUCCESS); return EXIT_SUCCESS; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
74
/* * ftdi-hd44780 * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libftdi1/ftdi.h> #include "ftdi-bitbang.h" #include "ftdi-hd44780.h" #include "cmd-common.h" const char opts[] = COMMON_SHORT_OPTS "m:i4:5:6:7:e:r:s:b:CMc:t:l:"; struct option longopts[] = { COMMON_LONG_OPTS { "mode", required_argument, NULL, 'm' }, { "init", no_argument, NULL, 'i' }, { "d4", required_argument, NULL, '4' }, { "d5", required_argument, NULL, '5' }, { "d6", required_argument, NULL, '6' }, { "d7", required_argument, NULL, '7' }, { "en", required_argument, NULL, 'e' }, { "rw", required_argument, NULL, 'r' }, { "rs", required_argument, NULL, 's' }, { "command", required_argument, NULL, 'b' }, { "clear", no_argument, NULL, 'C' }, { "home", no_argument, NULL, 'M' }, { "cursor", required_argument, NULL, 'c' }, { "text", required_argument, NULL, 't' }, { "line", required_argument, NULL, 'l' }, { 0, 0, 0, 0 }, }; int init = 0; int d4 = 0; int d5 = 1; int d6 = 2; int d7 = 3; int en = 4; int rw = 5; int rs = 6; /* ftdi device context */ struct ftdi_context *ftdi = NULL; struct ftdi_bitbang_context *device = NULL; struct ftdi_hd44780_context *hd44780 = NULL; int bitmode = 0; uint8_t *commands = NULL; int commands_count = 0; int clear = 0; int home = 0; int cursor = -1; char *text = NULL; int line = -1; /** * Free resources allocated by process, quit using libraries, terminate * connections and so on. This function will use exit() to quit the process. * * @param return_code Value to be returned to parent process. */ void p_exit(int return_code) { if (commands) { free(commands); } if (hd44780) { ftdi_hd44780_free(hd44780); } if (device) { ftdi_bitbang_save_state(device); ftdi_bitbang_free(device); } if (ftdi) { ftdi_free(ftdi); } if (text) { free(text); } /* terminate program instantly */ exit(return_code); } void p_help() { printf( " -m, --mode=STRING set device bitmode, use 'bitbang' or 'mpsse', default is 'bitbang'\n" " for bitbang mode the baud rate is fixed to 1 MHz for now\n" " -i, --init initialize hd44780 lcd, usually needed only once at first\n" " -4, --d4=PIN data pin 4, default pin is 0\n" " -5, --d5=PIN data pin 5, default pin is 1\n" " -6, --d6=PIN data pin 6, default pin is 2\n" " -7, --d7=PIN data pin 7, default pin is 3\n" " -e, --en=PIN enable pin, default pin is 4\n" " -r, --rw=PIN read/write pin, default pin is 5\n" " -s, --rs=PIN register select pin, default pin is 6\n" " -b, --command=BYTE send raw hd44780 command, decimal or hexadecimal (0x) byte\n" " multiple commands can be given, they are run before any later commands described here\n" " -C, --clear clear display\n" " -M, --home move cursor home\n" " -c, --cursor=VALUE cursor on/off and blink, accepts value between 0-3\n" " -t, --text=STRING write given text to display\n" " -l, --line=VALUE move cursor to given line, value between 0-3\n" "\n" "Use HD44780 based LCD displays in 4-bit mode through FTDI FTx232 chips with this command.\n" "\n"); } int p_options(int c, char *optarg) { switch (c) { case 'm': if (strcmp("bitbang", optarg) == 0) { bitmode = BITMODE_BITBANG; } else if (strcmp("mpsse", optarg) == 0) { bitmode = BITMODE_MPSSE; } else { fprintf(stderr, "invalid bitmode\n"); return -1; } return 1; case 'i': init = 1; return 1; case '4': d4 = atoi(optarg); return 1; case '5': d5 = atoi(optarg); return 1; case '6': d6 = atoi(optarg); return 1; case '7': d7 = atoi(optarg); return 1; case 'e': en = atoi(optarg); return 1; case 'r': rw = atoi(optarg); return 1; case 's': rs = atoi(optarg); return 1; case 'b': commands_count++; commands = realloc(commands, commands_count); commands[commands_count - 1] = (uint8_t)strtol(optarg, NULL, 0); return 1; case 'C': clear = 1; return 1; case 'M': home = 1; return 1; case 'c': cursor = atoi(optarg); if (cursor < 0 || cursor > 3) { fprintf(stderr, "invalid cursor\n"); p_exit(1); } return 1; case 't': text = strdup(optarg); return 1; case 'l': line = atoi(optarg); if (line < 0 || line > 3) { fprintf(stderr, "invalid line\n"); p_exit(1); } return 1; } return 0; } int main(int argc, char *argv[]) { int err = 0, i; /* parse command line options */ if (common_options(argc, argv, opts, longopts, 0, 0)) { fprintf(stderr, "invalid command line option(s)\n"); p_exit(EXIT_FAILURE); } /* init ftdi things */ ftdi = common_ftdi_init(); if (!ftdi) { p_exit(EXIT_FAILURE); } /* initialize to bitbang mode */ device = ftdi_bitbang_init(ftdi, bitmode, 1); if (!device) { fprintf(stderr, "ftdi_bitbang_init() failed\n"); p_exit(EXIT_FAILURE); } /* initialize hd44780 */ hd44780 = ftdi_hd44780_init(device, init, d4, d5, d6, d7, en, rw, rs); if (!hd44780) { fprintf(stderr, "ftdi_hd44780_init() failed\n"); return -1; } /* run commands */ for (i = 0; i < commands_count; i++) { ftdi_hd44780_cmd(hd44780, commands[i]); } if (clear) { ftdi_hd44780_cmd(hd44780, 0x01); } if (home) { ftdi_hd44780_cmd(hd44780, 0x02); } if (cursor >= 0) { ftdi_hd44780_cmd(hd44780, 0x0c | cursor); } if (line >= 0 && line <= 3) { ftdi_hd44780_goto_xy(hd44780, 0, line); } if (text) { ftdi_hd44780_write_str(hd44780, text); } p_exit(EXIT_SUCCESS); return EXIT_SUCCESS; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
75
/* * ftdi-bitbang * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libftdi1/ftdi.h> #include "ftdi-bitbang.h" #include "cmd-common.h" const char opts[] = COMMON_SHORT_OPTS "m:s:c:i:r"; struct option longopts[] = { COMMON_LONG_OPTS { "mode", required_argument, NULL, 'm' }, { "set", required_argument, NULL, 's' }, { "clr", required_argument, NULL, 'c' }, { "inp", required_argument, NULL, 'i' }, { "read", optional_argument, NULL, 'r' }, { 0, 0, 0, 0 }, }; /* which pin state to read or -1 for all (hex output then) */ int read_pin = -2; int pins[16]; /* ftdi device context */ struct ftdi_context *ftdi = NULL; struct ftdi_bitbang_context *device = NULL; int bitmode = 0; /** * Free resources allocated by process, quit using libraries, terminate * connections and so on. This function will use exit() to quit the process. * * @param return_code Value to be returned to parent process. */ void p_exit(int return_code) { if (device) { ftdi_bitbang_save_state(device); ftdi_bitbang_free(device); } if (ftdi) { ftdi_free(ftdi); } /* terminate program instantly */ exit(return_code); } void p_help() { printf( " -m, --mode=STRING set device bitmode, use 'bitbang' or 'mpsse', default is 'bitbang'\n" " for bitbang mode the baud rate is fixed to 1 MHz for now\n" " -s, --set=PIN given pin as output and one\n" " -c, --clr=PIN given pin as output and zero\n" " -i, --inp=PIN given pin as input\n" " multiple -s, -c and -i options can be given\n" " -r, --read read pin states, output hexadecimal word\n" " --read=PIN read single pin, output binary 0 or 1\n" "\n" "Simple command line bitbang interface to FTDI FTx232 chips.\n" "\n"); } int p_options(int c, char *optarg) { int i; switch (c) { case 'm': if (strcmp("bitbang", optarg) == 0) { bitmode = BITMODE_BITBANG; } else if (strcmp("mpsse", optarg) == 0) { bitmode = BITMODE_MPSSE; } else { fprintf(stderr, "invalid bitmode\n"); return -1; } return 1; case 'c': case 's': case 'i': i = atoi(optarg); if (i < 0 || i > 15) { fprintf(stderr, "invalid pin number: %d\n", i); p_exit(1); } else { /* s = out&one, c = out&zero, i = input */ pins[i] = c == 's' ? 1 : (c == 'i' ? 2 : 0); } return 1; case 'r': read_pin = -1; if (optarg) { read_pin = atoi(optarg); } if (read_pin < -1 || read_pin > 15) { fprintf(stderr, "invalid pin number for read parameter: %d\n", i); p_exit(1); } return 1; } return 0; } int read_pins(int pin) { if (pin == -1) { int pins = ftdi_bitbang_read(device); if (pins < 0) { fprintf(stderr, "failed reading pin states\n"); p_exit(EXIT_FAILURE); } printf("%04x\n", pins); } else if (pin >= 0 && pin < 8) { int pins = ftdi_bitbang_read_low(device); if (pins < 0) { fprintf(stderr, "failed reading pin state\n"); p_exit(EXIT_FAILURE); } printf("%d\n", pins & (1 << pin) ? 1 : 0); } else if (pin > 7 && pin < 16) { int pins = ftdi_bitbang_read_high(device); if (pins < 0) { fprintf(stderr, "failed reading pin state\n"); p_exit(EXIT_FAILURE); } pin -= 8; printf("%d\n", pins & (1 << pin) ? 1 : 0); } return 0; } int main(int argc, char *argv[]) { int err = 0, i, changed = 0; for (i = 0; i < 16; i++) { pins[i] = -1; } /* parse command line options */ if (common_options(argc, argv, opts, longopts, 0, 1)) { fprintf(stderr, "invalid command line option(s)\n"); p_exit(EXIT_FAILURE); } /* init ftdi things */ ftdi = common_ftdi_init(); if (!ftdi) { p_exit(EXIT_FAILURE); } /* initialize to bitbang mode */ device = ftdi_bitbang_init(ftdi, bitmode, 1); if (!device) { fprintf(stderr, "ftdi_bitbang_init() failed\n"); p_exit(EXIT_FAILURE); } /* write changes */ for (i = 0; i < 16; i++) { int err = 0; if (pins[i] == 0 || pins[i] == 1) { err += ftdi_bitbang_set_io(device, i, 1); err += ftdi_bitbang_set_pin(device, i, pins[i] ? 1 : 0); changed++; } else if (pins[i] == 2) { err += ftdi_bitbang_set_io(device, i, 0); err += ftdi_bitbang_set_pin(device, i, 0); changed++; } if (err != 0) { fprintf(stderr, "invalid pin #%d (you are propably trying to use upper pins in bitbang mode)\n", i); } } if (ftdi_bitbang_write(device) < 0) { fprintf(stderr, "failed writing pin states\n"); p_exit(EXIT_FAILURE); } /* read pin(s) if set so in options */ if (read_pin > -2) { read_pins(read_pin); changed++; } /* apply arguments */ // for (int i = optind; i < argc; i++) { // printf("use: %s\n", argv[i]); // } /* apply stdin */ for (;;) { char *line = common_stdin_read(); if (!line) { break; } printf("line: \"%s\"\n", line); changed++; } /* print error if nothing was done */ if (!changed) { fprintf(stderr, "nothing done, no actions given.\n"); p_exit(EXIT_FAILURE); } p_exit(EXIT_SUCCESS); return EXIT_SUCCESS; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
76
/* * DDEBUGLIB * * Linked list macros. * * In order to use the following macros, you need to define next and prev * in struct: * struct x { struct x *next; struct x *prev; ... } * * License: MIT, see COPYING * Authors: Antti Partanen <aehparta@iki.fi, duge at IRCnet> */ #ifndef LINKEDLIST_H #define LINKEDLIST_H /** * Append new item into list. */ #define LL_APP(first, last, item) \ do { \ item->prev = NULL; \ item->next = NULL; \ if (first == NULL) first = item; \ else { \ last->next = item; \ item->prev = last; \ } \ last = item; \ } while(0) /** * Insert item into queue using field in struct to determine correct position. * field should be integer or similar and the item is inserted after first field * that has same or smaller value in list that the item being inserted. */ #define LL_INS(first, last, item, loop) \ do { \ item->prev = NULL; \ item->next = NULL; \ loop = last; \ while (loop) \ { \ if (loop->position <= item->position) \ { \ if (loop->next) \ { \ loop->next->prev = item; \ } \ item->next = loop->next; \ item->prev = loop; \ loop->next = item; \ if (last == loop) last = item; \ break; \ } \ loop = loop->prev; \ if (loop == NULL) \ { \ item->next = first; \ first->prev = item; \ first = item; \ break; \ } \ } \ if (last == NULL) \ { \ first = last = item; \ } \ } while(0) /** * Get item from end of the list. */ #define LL_POP(first, last, item) \ do { \ item = NULL; \ if (last != NULL) \ { \ item = last; \ if (last->prev == NULL) \ { \ first = NULL; \ last = NULL; \ } \ else { \ last = last->prev; \ last->next = NULL; \ } \ } \ } while (0) /** * Get item from top of the list. */ #define LL_GET(first, last, item) \ do { \ item = NULL; \ if (first != NULL) \ { \ item = first; \ if (first->next == NULL) \ { \ first = NULL; \ last = NULL; \ } \ else { \ first = first->next; \ first->prev = NULL; \ } \ } \ } while (0) /** * Remove given item from list. */ #define LL_RM(first, last, item) \ do { \ if (!item->prev) { \ first = item->next; \ if (first) { \ first->prev = NULL; \ } \ } else { \ item->prev->next = item->next; \ } \ if (!item->next) { \ last = item->prev; \ if (last) { \ last->next = NULL; \ } \ } else { \ item->next->prev = item->prev; \ } \ } while (0) /** * Count items in list. */ #define LL_COUNT(first, last, count) \ do { \ typeof(first) loop; \ count = 0; \ loop = first; \ while (loop) { \ count++; \ loop = loop->next; \ } \ } while (0) #endif /* LINKEDLIST_H */ /******************************************************************************/
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
77
/* * ftdi-bitbang * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libusb-1.0/libusb.h> #include <libftdi1/ftdi.h> #include "ftdi-bitbang.h" #include "cmd-common.h" const char opts[] = COMMON_SHORT_OPTS "ENom:d:s:l:x:n:p:"; struct option longopts[] = { COMMON_LONG_OPTS { "ee-erase", no_argument, NULL, 'E' }, { "ee-init", no_argument, NULL, 'N' }, { "ee-decode", no_argument, NULL, 'o' }, { "ee-manufacturer", required_argument, NULL, 'm' }, { "ee-description", required_argument, NULL, 'd' }, { "ee-serial", required_argument, NULL, 's' }, { "ee-serial-len", required_argument, NULL, 'l' }, { "ee-serial-hex", required_argument, NULL, 'x' }, { "ee-serial-dec", required_argument, NULL, 'n' }, { "ee-bus-power", required_argument, NULL, 'p' }, { 0, 0, 0, 0 }, }; /* ftdi device context */ struct ftdi_context *ftdi = NULL; /* if eeprom should be erased first */ int ee_erase = 0; /* initialize eeprom to default values, erases eeprom */ int ee_initialize = 0; /* if eeprom should be decoded */ int ee_decode = 0; /* if eeprom should be read first */ int ee_rd = 0; /* if eeprom should be written after */ int ee_wr = 0; char *set_description = NULL; char *set_serial = NULL; int set_serial_len = 0; int set_serial_mode = 0; char *set_manufacturer = NULL; int set_bus_power = 0; /** * Free resources allocated by process, quit using libraries, terminate * connections and so on. This function will use exit() to quit the process. * * @param return_code Value to be returned to parent process. */ void p_exit(int return_code) { if (set_description) { free(set_description); } if (set_serial) { free(set_serial); } if (set_manufacturer) { free(set_manufacturer); } if (ftdi) { ftdi_free(ftdi); } /* terminate program instantly */ exit(return_code); } void p_help() { printf( " -E, --ee-erase erase eeprom, sometimes needed if eeprom has already been initialized\n" " -N, --ee-init erase and initialize eeprom with defaults\n" " -o, --ee-decode read eeprom and print decoded information\n" " -m, --ee-manufacturer=STRING\n" " write manufacturer string\n" " -d, --ee-description=STRING\n" " write description (product) string\n" " -s, --ee-serial=STRING write serial string\n" " -l, --ee-serial-len=LENGTH pad serial with randomized ascii letters and numbers to this length (upper case)\n" " -x, --ee-serial-hex=LENGTH pad serial with randomized hex to this length (upper case)\n" " -n, --ee-serial-dec=LENGTH pad serial with randomized numbers to this length\n" " -p, --ee-bus-power=INT bus power drawn by the device (100-500 mA)\n" "\n" "Basic control and eeprom routines for FTDI FTx232 chips.\n" "\n"); } int p_options(int c, char *optarg) { switch (c) { case 'E': ee_erase = 1; return 1; case 'N': ee_erase = 1; ee_initialize = 1; ee_wr = 1; return 1; case 'o': ee_decode = 1; ee_rd = 1; return 1; case 'm': set_manufacturer = strdup(optarg); ee_rd = 1; ee_wr = 1; return 1; case 'd': set_description = strdup(optarg); ee_rd = 1; ee_wr = 1; return 1; case 's': if (set_serial) { free(set_serial); } set_serial = strdup(optarg); ee_rd = 1; ee_wr = 1; return 1; case 'l': /* mode 0 */ case 'x': /* mode 1 */ case 'n': /* mode 2 */ if (!set_serial) { set_serial = strdup(""); } set_serial_len = atoi(optarg); set_serial_mode = c == 'n' ? 2 : (c == 'x' ? 1 : 0); return 1; case 'p': set_bus_power = atoi(optarg); if (set_bus_power < 100 || set_bus_power > 500) { fprintf(stderr, "invalid bus power value, not within 100-500 mA\n"); return -1; } ee_rd = 1; ee_wr = 1; return 1; } return 0; } int main(int argc, char *argv[]) { int err = 0, i; /* random seed */ srand(time(NULL)); /* parse command line options */ if (common_options(argc, argv, opts, longopts, 0, 0)) { fprintf(stderr, "invalid command line option(s)\n"); p_exit(EXIT_FAILURE); } /* init ftdi things */ ftdi = common_ftdi_init(); if (!ftdi) { p_exit(EXIT_FAILURE); } if (ee_initialize) { /* initialize eeprom to defaults */ if (ftdi_eeprom_initdefaults(ftdi, NULL, NULL, NULL)) { fprintf(stderr, "failed to init defaults to eeprom: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } } else if (ee_rd) { /* read eeprom */ if (ftdi_read_eeprom(ftdi)) { fprintf(stderr, "failed to read eeprom: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } if (ftdi_eeprom_decode(ftdi, 0)) { fprintf(stderr, "failed to decode eeprom after read: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } } /* erase eeprom */ if (ee_erase) { if (ftdi_erase_eeprom(ftdi)) { fprintf(stderr, "failed to erase eeprom: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } } /* set strings to eeprom */ if (set_manufacturer || set_description || set_serial) { struct libusb_device_descriptor desc; libusb_get_device_descriptor(libusb_get_device(ftdi->usb_dev), &desc); if (!set_manufacturer) { set_manufacturer = calloc(1, 128); libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iManufacturer, set_manufacturer, 127); } if (!set_description) { set_description = calloc(1, 128); libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, set_description, 127); } if (!set_serial) { set_serial = calloc(1, 128); libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, set_serial, 127); } if (strlen(set_serial) < set_serial_len) { int i; set_serial = realloc(set_serial, set_serial_len + 1); for (i = strlen(set_serial); i < set_serial_len; i++) { char c; char max = set_serial_mode == 2 ? 0 : (set_serial_mode == 1 ? 'F' : 'Z'); /* generate random padding */ do { c = rand() & 0x7f; } while ((c < '0' || c > '9') && (c < 'A' || c > max)); set_serial[i] = c; } set_serial[set_serial_len] = '\0'; } ftdi_eeprom_set_strings(ftdi, set_manufacturer, set_description, set_serial); } /* bus power */ if (set_bus_power > 100) { ftdi_set_eeprom_value(ftdi, MAX_POWER, set_bus_power); } /* write eeprom data */ if (ee_wr) { if (ftdi_eeprom_build(ftdi) < 0) { fprintf(stderr, "failed to build eeprom: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } if (ftdi_write_eeprom(ftdi)) { fprintf(stderr, "failed to write eeprom: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } } /* decode eeprom */ if (ee_decode) { if (ftdi_eeprom_decode(ftdi, 1)) { fprintf(stderr, "failed to decode eeprom: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } } p_exit(EXIT_SUCCESS); return EXIT_SUCCESS; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
78
/* * ftdi-bitbang * * Common routines for all command line utilies. * * License: MIT * Authors: Antti Partanen <aehparta@iki.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <ctype.h> #include <libgen.h> #include <libusb.h> #include <errno.h> #include <libftdi1/ftdi.h> #include "cmd-common.h" /* only list */ int only_list = 1; /* usb vid */ uint16_t usb_vid = 0; /* usb pid */ uint16_t usb_pid = 0; /* usb description */ const char *usb_description = NULL; /* usb serial */ const char *usb_serial = NULL; /* usb id */ const char *usb_id = NULL; /* interface (defaults to first one) */ int interface = INTERFACE_ANY; /* reset flag, reset usb device if this is set */ int reset = 0; void common_help(int argc, char *argv[]) { printf( "\n" "Usage:\n" " %s [options]\n" "\n" "Definitions for options:\n" " ID = hexadecimal word\n" " PIN = decimal between 0 and 15\n" " INTERFACE = integer between 1 and 4 depending on device type\n" "\n" "Options:\n" " -h, --help display this help and exit\n" " -V, --vid=ID usb vendor id\n" " -P, --pid=ID usb product id\n" " as default vid and pid are zero, so any first compatible ftdi device is used\n" " -D, --description=STRING usb description (product) to use for opening right device, default none\n" " -S, --serial=STRING usb serial to use for opening right device, default none\n" " -I, --interface=INTERFACE ftx232 interface number, defaults to first\n" " -U, --usbid=ID usbid to use for opening right device (sysfs format, e.g. 1-2.3), default none\n" " -R, --reset do usb reset on the device at start\n" " -L, --list list devices that can be found with given parameters\n" "\n" , basename(argv[0])); p_help(); } int common_options(int argc, char *argv[], const char opts[], struct option longopts[], int need_args, int no_opts_needed) { int err = 0; int longindex = 0, c; int i; while ((c = getopt_long(argc, argv, opts, longopts, &longindex)) > -1) { /* check for command specific options */ err = p_options(c, optarg); if (err > 0) { only_list = only_list < 2 ? 0 : only_list; continue; } else if (err < 0) { common_help(argc, argv); p_exit(1); } /* check for common options */ switch (c) { case 'V': i = (int)strtol(optarg, NULL, 16); if (errno == ERANGE || i < 0 || i > 0xffff) { fprintf(stderr, "invalid usb vid value\n"); p_exit(1); } usb_vid = (uint16_t)i; break; case 'P': i = (int)strtol(optarg, NULL, 16); if (errno == ERANGE || i < 0 || i > 0xffff) { fprintf(stderr, "invalid usb pid value\n"); p_exit(1); } usb_pid = (uint16_t)i; break; case 'D': usb_description = strdup(optarg); break; case 'S': usb_serial = strdup(optarg); break; case 'U': usb_id = strdup(optarg); break; case 'I': interface = atoi(optarg); if (interface < 0 || interface > 4) { fprintf(stderr, "invalid interface\n"); p_exit(1); } break; case 'R': reset = 1; break; case 'L': only_list = 2; break; default: case '?': case 'h': common_help(argc, argv); p_exit(1); } } if (need_args) { if (argc <= optind) { common_help(argc, argv); p_exit(1); } only_list = 0; } else if (argc < optind) { only_list = only_list < 2 ? 0 : only_list; } if (only_list == 2 || (only_list == 1 && !no_opts_needed)) { common_ftdi_list_print(); p_exit(0); } return 0; } /* @note needs to be freed */ static char *get_usbid(struct libusb_device *dev) { int n, i = 0; uint8_t port_numbers[7]; FILE *fh; char *buf; size_t len; n = libusb_get_port_numbers(dev, port_numbers, sizeof(port_numbers) / sizeof(port_numbers[0])); if (n == LIBUSB_ERROR_OVERFLOW) { fprintf(stderr, "device has too many port numbers\n"); return NULL; } fh = open_memstream(&buf, &len); if (!fh) return NULL; fprintf(fh, "%d-", libusb_get_bus_number(dev)); for (;;) { fprintf(fh, "%d", port_numbers[i]); if (++i == n) break; fputc('.', fh); } fclose(fh); return buf; } static int usbid_is_match(struct libusb_device *dev) { char *id; int ret; if (!usb_id) return 1; id = get_usbid(dev); ret = id && strcmp(usb_id, id) == 0; free(id); return ret; } void common_ftdi_list_print() { int i, n; struct ftdi_context *ftdi = NULL; struct ftdi_device_list *list; /* initialize ftdi */ ftdi = ftdi_new(); if (!ftdi) { fprintf(stderr, "ftdi_new() failed\n"); return; } n = ftdi_usb_find_all(ftdi, &list, usb_vid, usb_pid); if (n < 1) { fprintf(stderr, "unable to find any matching device\n"); return; } for (i = 0; i < n; i++) { char m[1024], d[1024], s[1024]; char *id = get_usbid(list->dev); int usbid_match = usbid_is_match(list->dev); memset(m, 0, 1024); memset(d, 0, 1024); memset(s, 0, 1024); ftdi_usb_get_strings(ftdi, list->dev, m, 1024, d, 1024, s, 1024); list = list->next; if (usb_description) { if (strcmp(usb_description, d) != 0) { continue; } } if (usb_serial) { if (strcmp(usb_serial, s) != 0) { continue; } } if (!usbid_match) continue; printf("%s %s : %s / %s\n", id, s, d, m); free(id); } ftdi_list_free(&list); ftdi_free(ftdi); } struct ftdi_context *common_ftdi_init() { int err = 0, i, n; struct ftdi_context *ftdi = NULL; struct ftdi_device_list *list, *match; /* initialize ftdi */ ftdi = ftdi_new(); if (!ftdi) { fprintf(stderr, "ftdi_new() failed\n"); return NULL; } err = ftdi_set_interface(ftdi, interface); if (err < 0) { fprintf(stderr, "unable to set selected interface on ftdi device: %d (%s)\n", err, ftdi_get_error_string(ftdi)); return NULL; } /* find first device if vid or pid is zero */ n = ftdi_usb_find_all(ftdi, &list, usb_vid, usb_pid); if (n < 1) { fprintf(stderr, "unable to find any matching device\n"); return NULL; } match = list; if (usb_description || usb_serial || usb_id) { for (i = 0; i < n; i++) { char m[1024], d[1024], s[1024]; memset(m, 0, 1024); memset(d, 0, 1024); memset(s, 0, 1024); ftdi_usb_get_strings(ftdi, list->dev, m, 1024, d, 1024, s, 1024); if (usb_description) { if (strcmp(usb_description, d) != 0) { match = match->next; continue; } } if (usb_serial) { if (strcmp(usb_serial, s) != 0) { match = match->next; continue; } } if (!usbid_is_match(match->dev)) { match = match->next; continue; } break; } if (i >= n) { fprintf(stderr, "unable to find any matching device\n"); ftdi_list_free(&list); return NULL; } } err = ftdi_usb_open_dev(ftdi, match->dev); ftdi_list_free(&list); if (err < 0) { fprintf(stderr, "unable to open ftdi device: %s\n", ftdi_get_error_string(ftdi)); return NULL; } /* reset chip */ if (reset) { if (ftdi_usb_reset(ftdi)) { fprintf(stderr, "failed to reset device: %s\n", ftdi_get_error_string(ftdi)); p_exit(EXIT_FAILURE); } ftdi_set_bitmode(ftdi, 0x00, BITMODE_RESET); } return ftdi; } unsigned char *common_stdin_read(void) { static unsigned char data[65536]; struct stat st; size_t i; int c; if (fstat(fileno(stdin), &st)) { return NULL; } if (!S_ISFIFO(st.st_mode) && !S_ISREG(st.st_mode)) { return NULL; } /* remove whitespaces from start of data*/ for (c = fgetc(stdin); isspace(c); c = fgetc(stdin)); /* read line */ for (i = 0; c >= 0 && c <= 255 && i < (sizeof(data) - 1) && !isspace(c); i++, c = fgetc(stdin)) { data[i] = (unsigned char)c; } if (i == 0) { return NULL; } data[i] = '\0'; return data; }
aehparta/ftdi-bitbang
11
cmd-common.c
text/x-c
79
Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2008 Project("{847C3A1B-EAE1-9077-B553-C7D1A4726692}") = "TappyPlane", "Assembly-CSharp.csproj", "{FCF3EBED-1117-7C63-5D4A-C0589384D5DC}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {FCF3EBED-1117-7C63-5D4A-C0589384D5DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FCF3EBED-1117-7C63-5D4A-C0589384D5DC}.Debug|Any CPU.Build.0 = Debug|Any CPU {FCF3EBED-1117-7C63-5D4A-C0589384D5DC}.Release|Any CPU.ActiveCfg = Release|Any CPU {FCF3EBED-1117-7C63-5D4A-C0589384D5DC}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = Assembly-CSharp.csproj Policies = $0 $0.TextStylePolicy = $1 $1.inheritsSet = null $1.scope = text/x-csharp $0.CSharpFormattingPolicy = $2 $2.inheritsSet = Mono $2.inheritsScope = text/x-csharp $2.scope = text/x-csharp $0.TextStylePolicy = $3 $3.FileWidth = 120 $3.TabWidth = 4 $3.EolMarker = Unix $3.inheritsSet = Mono $3.inheritsScope = text/plain $3.scope = text/plain EndGlobalSection EndGlobal
anwell/tappyplane
62
C#
Generate.cs
text/plain
80
Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2008 Project("{847C3A1B-EAE1-9077-B553-C7D1A4726692}") = "TappyPlane", "Assembly-CSharp-vs.csproj", "{FCF3EBED-1117-7C63-5D4A-C0589384D5DC}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {FCF3EBED-1117-7C63-5D4A-C0589384D5DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FCF3EBED-1117-7C63-5D4A-C0589384D5DC}.Debug|Any CPU.Build.0 = Debug|Any CPU {FCF3EBED-1117-7C63-5D4A-C0589384D5DC}.Release|Any CPU.ActiveCfg = Release|Any CPU {FCF3EBED-1117-7C63-5D4A-C0589384D5DC}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = Assembly-CSharp.csproj Policies = $0 $0.TextStylePolicy = $1 $1.inheritsSet = null $1.scope = text/x-csharp $0.CSharpFormattingPolicy = $2 $2.inheritsSet = Mono $2.inheritsScope = text/x-csharp $2.scope = text/x-csharp $0.TextStylePolicy = $3 $3.FileWidth = 120 $3.TabWidth = 4 $3.EolMarker = Unix $3.inheritsSet = Mono $3.inheritsScope = text/plain $3.scope = text/plain EndGlobalSection EndGlobal
anwell/tappyplane
62
C#
Generate.cs
text/plain
81
TappyPlane ========== The source for a Flappy Bird clone built in Unity3D. Read the complete tutorial on [how to make a Flappy Bird clone](http://anwell.me/articles/unity3d-flappy-bird/) on my website.
anwell/tappyplane
62
C#
Generate.cs
text/plain
82
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>10.0.20506</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{FCF3EBED-1117-7C63-5D4A-C0589384D5DC}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace></RootNamespace> <AssemblyName>Assembly-CSharp</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <BaseDirectory>Assets</BaseDirectory> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>Temp\bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE;UNITY_STANDALONE_WIN;ENABLE_MICROPHONE;ENABLE_TEXTUREID_MAP;ENABLE_AUDIO_FMOD;UNITY_STANDALONE;ENABLE_MONO;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_GENERICS;ENABLE_SUBSTANCE;INCLUDE_WP8SUPPORT;ENABLE_MOVIES;ENABLE_WWW;ENABLE_IMAGEEFFECTS;ENABLE_WEBCAM;INCLUDE_METROSUPPORT;RENDER_SOFTWARE_CURSOR;ENABLE_NETWORK;ENABLE_PHYSICS;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_2D_PHYSICS;ENABLE_SHADOWS;ENABLE_AUDIO;ENABLE_NAVMESH_CARVING;ENABLE_DUCK_TYPING;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;UNITY_4_3_2;UNITY_4_3;ENABLE_PROFILER;UNITY_EDITOR;UNITY_EDITOR_WIN</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <NoWarn>0169</NoWarn> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>Temp\bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <NoWarn>0169</NoWarn> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.XML" /> <Reference Include="System.Core" /> <Reference Include="System.Xml.Linq" /> <Reference Include="UnityEngine"> <HintPath>C:/Program Files (x86)/Unity/Editor/Data/Managed/UnityEngine.dll</HintPath> </Reference> <Reference Include="UnityEditor"> <HintPath>C:/Program Files (x86)/Unity/Editor/Data/Managed/UnityEditor.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> <Compile Include="Assets\Scripts\Generate.cs" /> <Compile Include="Assets\Scripts\Obstacle.cs" /> <Compile Include="Assets\Scripts\Player.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
anwell/tappyplane
62
C#
Generate.cs
text/plain
83
<Properties> <MonoDevelop.Ide.Workspace ActiveConfiguration="Debug" /> <MonoDevelop.Ide.Workbench ActiveDocument="Assets\Scripts\Player.cs"> <Files> <File FileName="Assets\Scripts\Player.cs" Line="22" Column="4" /> <File FileName="Assets\Scripts\Obstacle.cs" Line="6" Column="24" /> <File FileName="Assets\Scripts\Generate.cs" Line="7" Column="1" /> </Files> </MonoDevelop.Ide.Workbench> <MonoDevelop.Ide.DebuggingService.Breakpoints> <BreakpointStore /> </MonoDevelop.Ide.DebuggingService.Breakpoints> <MonoDevelop.Ide.DebuggingService.PinnedWatches /> </Properties>
anwell/tappyplane
62
C#
Generate.cs
text/plain
84
Completed
anwell/tappyplane
62
C#
Generate.cs
text/plain
85
using UnityEngine; public class Player : MonoBehaviour { // The force which is added when the player jumps // This can be changed in the Inspector window public Vector2 jumpForce = new Vector2(0, 300); // Update is called once per frame void Update () { // Jump if (Input.GetKeyUp("space")) { rigidbody2D.velocity = Vector2.zero; rigidbody2D.AddForce(jumpForce); } // Die by being off screen Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position); if (screenPosition.y > Screen.height || screenPosition.y < 0) { Die(); } } // Die by collision void OnCollisionEnter2D(Collision2D other) { Die(); } void Die() { Application.LoadLevel(Application.loadedLevel); } }
anwell/tappyplane
62
C#
Generate.cs
text/plain
86
using UnityEngine; public class Obstacle : MonoBehaviour { public Vector2 velocity = new Vector2(-4, 0); public float range = 4; // Use this for initialization void Start() { rigidbody2D.velocity = velocity; transform.position = new Vector3(transform.position.x, transform.position.y - range * Random.value, transform.position.z); } }
anwell/tappyplane
62
C#
Generate.cs
text/plain
87
using UnityEngine; public class Generate : MonoBehaviour { public GameObject rocks; int score = 0; // Use this for initialization void Start() { InvokeRepeating("CreateObstacle", 1f, 1.5f); } // Update is called once per frame void OnGUI () { GUI.color = Color.black; GUILayout.Label(" Score: " + score.ToString()); } void CreateObstacle() { Instantiate(rocks); score++; } }
anwell/tappyplane
62
C#
Generate.cs
text/plain
88
# Humans Generator [![Build Status](https://travis-ci.org/AlexisTM/humans-generator.svg?branch=master)](https://travis-ci.org/AlexisTM/humans-generator) Produces a simple, valid humans.txt to be parsed by web crawlers. Adheres to the [specification](http://humanstxt.org/Standard.html) provided by Humanstxt.org. Requires Node 4+. Installed through NPM with: ```shell npm install humans-generator --save-dev ``` Simply require the module and execute it with some configuration. It can take for each information a String, an Array, an Object or any combinaison of the 3. The standard propose your those fields: - header: The ASCII art, default is Humans.txt - Team: Shoutouts to your squad. - Thanks: People you'd like to thank. - Site: Technical specifications about your site. - Note: Things you'd like to mention. ```javascript var humans = require('humans-generator'); humans({ team: [{ "Original developer": "Hayden Bleasel", Twitter: "@haydenbleasel" }, { Maintainer: "Alexis Paques", Github: "@AlexisTM" }], thanks: [ 'Node', 'Gulp' ], site: { 'Standards': 'HTML5, CSS3', 'Components': 'jQuery, Normalize.css', 'Softwares': 'Atom, SublimeText' }, note: 'Built with love by Hayden Bleasel.' }, function (error, humans) { if(error) console.log(error); else console.log(humans.join('\n')); }); ``` Outputs the following file: ``` _ _ _ _ | | | |_ _ _ __ ___ __ _ _ __ ___ | |___ _| |_ | |_| | | | | '_ ` _ \ / _` | '_ \/ __|| __\ \/ / __| | _ | |_| | | | | | | (_| | | | \__ \| |_ > <| |_ |_| |_|\__,_|_| |_| |_|\__,_|_| |_|___(_)__/_/\_\\__| /* TEAM */ Original developer: Hayden Bleasel Twitter: @haydenbleasel Maintainer: Alexis Paques Github: @AlexisTM /* THANKS */ Node Gulp /* SITE */ Standards: HTML5, CSS3 Components: jQuery, Normalize.css Softwares: Atom, SublimeText /* NOTE */ Built with love by Hayden Bleasel. ``` If you need an ES5 build for legacy purposes, just require the ES5 file: ```javascript var humans = require('humans-generator/es5'); ``` To build the ES5 version: ```sh npm install -g babel-cli babel --presets es2015 index.js --out-file es5.js ```
alexistm/humans-generator
20
gulpfile.js
text/plain
89
const path = require('path'), figlet = require('figlet'), _ = require('underscore'), cheerio = require('cheerio'), async = require('async'), through2 = require('through2'), File = require('vinyl'); (() => { 'use strict'; function humans (params, next) { const options = _.defaults(params || {}, { header: 'Humans.txt' }), configuration = []; next = next || function callback () { return true; }; function add (name, object) { configuration.push(`\n/* ${ name } */`); stringify(object, '', false) } function stringify(object, prepend, isNotFirst){ prepend = prepend || '' if (typeof object === 'string') { configuration.push(prepend + object) } else if (Array.isArray(object)) { _.each(object, (obj, index) => stringify(obj, '', index)); } else if (object instanceof Object){ if (isNotFirst) configuration.push("") _.each(object, (value, key) => { stringify(value, `${ key }: `, true) }) } else { return next(new Error(`Object type for ${ name } is not a string or array.`)); } } async.waterfall([ (callback) => figlet(options.header, (error, data) => { callback(error, data)}), (data, callback) => { configuration.push(`${ data }`); _.each(Object.keys(options), (name) => { if (name != 'header') if (options[name]) { add(name.toUpperCase(), options[name]); } }); configuration.push(""); callback(null); }, ], (error) => next(error, configuration)); } function stream (params) { params = params || {}; return through2.obj((file, enc, callback) => { const $ = cheerio.load(file.contents.toString()); if (file.isNull()) { return callback(null, file); } if (file.isStream()) { return callback(new Error('Streaming not supported')); } if (!params.team) { params.team = $('meta[name="author"]').attr('content'); } humans(params, (error, config) => callback(error, new File({ path: path.join(file.cwd, 'humans.txt'), contents: new Buffer(config.join('\n')) }))); }); } module.exports = humans; module.exports.stream = stream; })();
alexistm/humans-generator
20
gulpfile.js
text/plain
90
'use strict'; var path = require('path'), figlet = require('figlet'), _ = require('underscore'), cheerio = require('cheerio'), async = require('async'), through2 = require('through2'), File = require('vinyl'); (function () { 'use strict'; function humans(params, next) { var options = _.defaults(params || {}, { header: 'Humans.txt' }), configuration = []; next = next || function callback() { return true; }; function add(name, object) { configuration.push('\n/* ' + name + ' */'); stringify(object, '', false); } function stringify(object, prepend, isNotFirst) { prepend = prepend || ''; if (typeof object === 'string') { configuration.push(prepend + object); } else if (Array.isArray(object)) { _.each(object, function (obj, index) { return stringify(obj, '', index); }); } else if (object instanceof Object) { if (isNotFirst) configuration.push(""); _.each(object, function (value, key) { stringify(value, key + ': ', true); }); } else { return next(new Error('Object type for ' + name + ' is not a string or array.')); } } async.waterfall([function (callback) { return figlet(options.header, function (error, data) { callback(error, data); }); }, function (data, callback) { configuration.push('' + data); _.each(Object.keys(options), function (name) { if (name != 'header') if (options[name]) { add(name.toUpperCase(), options[name]); } }); configuration.push(""); callback(null); }], function (error) { return next(error, configuration); }); } function stream(params) { params = params || {}; return through2.obj(function (file, enc, callback) { var $ = cheerio.load(file.contents.toString()); if (file.isNull()) { return callback(null, file); } if (file.isStream()) { return callback(new Error('Streaming not supported')); } if (!params.team) { params.team = $('meta[name="author"]').attr('content'); } humans(params, function (error, config) { return callback(error, new File({ path: path.join(file.cwd, 'humans.txt'), contents: new Buffer(config.join('\n')) })); }); }); } module.exports = humans; module.exports.stream = stream; })();
alexistm/humans-generator
20
gulpfile.js
text/plain
91
const humans = require('../'), fs = require('fs'); (() => { 'use strict'; humans({ team: [{ "Original developer": "Hayden Bleasel", Twitter: "@haydenbleasel" }, { Maintainer: "Alexis Paques", Github: "@AlexisTM" }], thanks: [ 'Node', 'Gulp' ], site: { 'Standards': 'HTML5, CSS3', 'Components': 'jQuery, Normalize.css', 'Softwares': 'Atom, SublimeText' }, note: 'Built with love by Hayden Bleasel.' }, (error, config) => { console.log(error, config); fs.writeFile('humans.txt', config.join('\n'), { encoding: 'utf8' }, (error2) => console.log(error2)); }); })();
alexistm/humans-generator
20
gulpfile.js
text/plain
92
<!doctype html> <html> <head> <title>Testing Document</title> <meta name="author" content="Hayden Bleasel" /> </head> <body> </body> </html>
alexistm/humans-generator
20
gulpfile.js
text/plain
93
const humans = require('../es5'), fs = require('fs'); (() => { 'use strict'; humans({ team: [{ "Original developer": "Hayden Bleasel", Twitter: "@haydenbleasel" }, { Maintainer: "Alexis Paques", Github: "@AlexisTM" }], thanks: [ 'Node', 'Gulp' ], site: { 'Standards': 'HTML5, CSS3', 'Components': 'jQuery, Normalize.css', 'Softwares': 'Atom, SublimeText' }, note: 'Built with love by Hayden Bleasel.' }, (error, config) => { console.log(error, config); fs.writeFile('humans.txt', config.join('\n'), { encoding: 'utf8' }, (error2) => console.log(error2)); }); })();
alexistm/humans-generator
20
gulpfile.js
text/plain
94
const gulp = require('gulp'), humans = require('../').stream; (() => { 'use strict'; gulp.task('default', () => gulp.src('index.html') .pipe(humans({ thanks: 'Hayden Bleasel (@haydenbleasel on Twitter)', note: 'Built with love by Hayden Bleasel.' })) .pipe(gulp.dest('stream/'))); })();
alexistm/humans-generator
20
gulpfile.js
text/plain
95
ansible textfsm
ansible-network/network-engine
109
main.yml
text/plain
96
Ansible Network: Network Engine Release ---------------------------------------- The Ansible Network team is pleased to announce that the initial release of the Network Engine Ansible role is now available in Ansible Galaxy! What is an Ansible Role? ---------------------------------- An Ansible Role is a collection of related tasks, methods, plugins, and modules in a standard format. You can use Roles in tasks or playbooks. What does the Network Engine Role do? ---------------------------------- The Network Engine Role provides the fundamental building blocks for a data-model-driven approach to automated network management. Network Engine: - extracts data about your network devices - returns the data as Ansible facts in a JSON data structure, ready to be added to your inventory host facts and/or consumed by Ansible tasks and templates - works on any network platform With the Network Engine role, and other Roles built around it, you can normalize your Ansible facts across your entire network. How do I get it? ---------------------------------- Via Ansible Galaxy using the following Linux command: `ansible-galaxy install ansible-network.network-engine` How do I use it? ---------------------------------- See the [User Guide](https://github.com/ansible-network/network-engine/blob/devel/docs/user_guide/README.md) for details and examples.
ansible-network/network-engine
109
main.yml
text/plain
97
# Developer Guide This role is developed and maintained by the Ansible Network Working Group. Contributions to this role are welcomed. This document will provide individuals with information about how to contribute to the further development of this role. ## Contributing There are many ways you can contribute to this role. Adding new artifacts such as modules and plugins, testing and/or reviewing and updating documentation. ### Adding support for a new platform To add support for a new platform to this role, there are a couple of things that need to be done. 1) Create the module for the platform specific implementation in Ansible. The module can be contributed directly to Ansible core, distributed through Ansible Galaxy or added to this role. 2) (Optional) If adding the module code directly to this role, add the module to `library/` 3) (Optional) If the new platform module is distributed through another Galaxy role, please update [README](README.md) Dependencies section to include the name of the Galaxy role that includes the module. 4) Once the module has been created, the add a new task in `tasks/` for the specific platform to be supported. Use any of the existing platform implementations as a guide. 5) (Optional) If a configuration parameter is not supported, then the implementation in tasks should detect that and provide a warning message. 6) Update the `meta/main.yaml` file to add the newly provided platform to the `platforms` meta data. ### Adding platform specific arguments Sometimes there is a need to add platform specific arguments to a role for use by a platform specific module. This can be accomplished by adding the adding the arguments under a platform specific key. Note: It is the responsibility of the task writer to handle the implementation of the platform specific arguments. Here is an example that implements a platform specific argument: ```yaml tasks: - name: configure network device resource include_role: name: net_system vars: resource: foo: bar ios: foo: baz ``` ### Adding documentation for a platform specific implementation While not required, there are times when providing implementation nodes are advantageous to instructing the playbook writer how to implement platform specific arguments. In order to provide platform specific documentation, create a file in the docs directory using GitHub Markdown. The file name should be the platform name. For instance, let's assume we want to create implementation nodes for a fictitious platform call `foo`. Create a new file `docs/foo.md` and then add a link to [README](README.md) pointing to `docs/foo.md` in the `PLATFORM NOTES` section. # Note The release cadence for the network-engine role is two weeks and it will be released on every second Tuesday at 12:00 PM (GMT) from the date of prior release. For the PR to be available in the upcoming release it should be in a mergeable state that is CI is passing and all review comments fixed at least two days prior to scheduled date of release. ## Bug Reporting If you have found a bug in the with the current role please open a [GitHub issue](../../issues) ## Contact * [#ansible-network IRC channel](https://webchat.freenode.net/?channels=ansible-network) on Freenode.net
ansible-network/network-engine
109
main.yml
text/plain
98
ara flake8 yamllint
ansible-network/network-engine
109
main.yml
text/plain
99
# This is a cross-platform list tracking distribution packages needed by tests; # see http://docs.openstack.org/infra/bindep/ for additional information. gcc-c++ [test platform:rpm] python3-devel [test !platform:centos-7 platform:rpm] python3 [test !platform:centos-7 platform:rpm] python36 [test !platform:centos-7 !platform:fedora-28]
ansible-network/network-engine
109
main.yml
text/plain
End of preview (truncated to 100 rows)

Dataset Card for Code Clippy Data

Dataset Summary

This dataset was generated by selecting GitHub repositories from a large collection of repositories. These repositories were collected from https://seart-ghs.si.usi.ch/ and Github portion of The Pile (performed on July 7th, 2021). The goal of this dataset is to provide a training set for pretraining large language models on code data for helping software engineering researchers better understand their impacts on software related tasks such as autocompletion of code. The dataset is split into train, validation, and test splits. There is a version containing duplicates (209GBs compressed) and ones where exact duplicates (132GBs compressed) are removed. Contains mostly JavaScript and Python code, but other programming languages are included as well to various degrees.

Supported Tasks and Leaderboards

  • language-modeling: The dataset can be used to train a model for language modeling for modeling programming languages, which consists of pretraining/finetuning a model to predict missing tokens, either causally or masked, given some context. Success on this task is typically measured by achieving a low perplexity score.

Languages

Multiple programming languages are included in the dataset.

Dataset Structure

Data Instances

{
  "id": datasets.Value("int64"),
  "text": datasets.Value("string"),
  "repo_name": datasets.Value("string"),
  "stars": datasets.Value("string"),
  "repo_language": datasets.Value("string"),
  "file_name": datasets.Value("string"),
  "mime_type": datasets.Value("string")
}

Data Fields

  • id: A unique identifier for the data instance.
  • text: The text of the code.
  • repo_name: The name of the repository.
  • stars: The number of stars the repository has.
  • repo_language: The programming language of the repository.
  • file_name: The name of the file.
  • mime_type: The MIME type of the file.

Data Splits

Size in GBs Tain Valid Test
Duplicate 194 9 6.3
Deduplicate 126 3.3 3.1

Dataset Creation

Curation Rationale

To have a code dataset that is large enough to properly train a large language model on.

Source Data

Initial Data Collection and Normalization

Repositories were collected from both sources and the helper script from https://github.com/EleutherAI/github-downloader was used to download the repositories. Files were scrapped from the downloaded repositories, but ignored files that had certain extensions associated with binary or other non-textual/autogenerated content, and the output was converted into the LM_Dataformat format.

Who are the source language producers?

Software developers.

Annotations

Annotation process

No annotation was performed.

Who are the annotators?

N/A

Personal and Sensitive Information

Since this data was collected from public repositories, there exists potential for personal and sensitive information to be included in the data through developers accidentally or on purpose uploading their secret keys, passwords, API keys, emails, etc.

Considerations for Using the Data

Social Impact of Dataset

The paper "Evaluating Large Language Models Trained on Code" from OpenAI has a good discussion on what the impact of a large language model trained on code could be. Therefore, some parts of their discuss are highlighted here as it pertains to this dataset and models that may be trained from it. As well as some differences in views from the paper, particularly around legal implications.

  1. Over-reliance: A language model trained on large datasets such as this one for the task of autogenerating code may generate plausible solutions that may appear correct, but are not necessarily the correct solution. Not properly evaluating the generated code may cause have negative consequences such as the introduction of bugs, or the introduction of security vulnerabilities. Therefore, it is important that users are aware of the limitations and potential negative consequences of using a language model trained on this dataset.
  2. Economic and labor market impacts: Large language models trained on large code datasets such as this one that are capable of generating high-quality code have the potential to automate part of the software development process. This may negatively impact software developers. However, as discussed in the paper, as shown in the Summary Report of software developers from O*NET OnLine, developers don't just write software.
  3. Security implications: No filtering or checking of vulnerabilities or buggy code was performed. This means that the dataset may contain code that may be malicious or contain vulnerabilities. Therefore, any model trained on this dataset may generate vulnerable, buggy, or malicious code. In safety critical software, this could lead to software that may work improperly and could result in serious consequences depending on the software. Additionally, a model trained on this dataset may be used to generate malicious code on purpose in order to perform ransomware or other such attacks.
  4. Legal implications: No filtering was performed on licensed code. This means that the dataset may contain restrictive licensed code. As discussed in the paper, public Github repositories may fall under "fair use." However, there has been little to no previous cases of such usages of licensed publicly available code. Therefore, any model trained on this dataset may be required to obey license terms that align with the software it was trained on such as GPL-3.0, which is why we purposefully put this dataset under the GPL-3.0 license. It is unclear the legal ramifications of using a language model trained on this dataset.

Discussion of Biases

The programming languages most represented in this dataset are those of Javascript and Python. Therefore, other, still popular languages such as C and C++, are less represented and therefore model performance for these languages will be less comparatively. Additionally, this dataset only contains public repositories and so may not be representative of code written by private developers. No filtering was performed for potential racist, offensive, or otherwise inappropriate content. Therefore there may be such content in the dataset that will be reflected in models trained on it.

Other Known Limitations

[More Information Needed]

Additional Information

Dataset Curators

Nathan Coooper, Artashes Arutiunian, Santiago Hincapié-Potes, Ben Trevett, Arun Raja, Erfan Hossami, Mrinal Mathur, and contributors!

Licensing Information

This repository is under the GPL-3.0 license.

Citation Information

@misc{cooper-2021-code-clippy-data,
    author       = {Nathan Coooper, Artashes Arutiunian, Santiago Hincapié-Potes, Ben Trevett, Arun Raja, Erfan Hossami, Mrinal Mathur, and contributors},
    title        = {{Code Clippy Data: A large dataset of code data from Github for research into code language models}},
    month        = jul,
    year         = 2021,
    version      = {1.0},
    publisher    = {GitHub},
    url          = {https://github.com/ncoop57/gpt-code-clippy}
}

Contributions

Thanks to @ncoop57, @arampacha, @shpotes, @bentrevett, @arunraja-hub, @taisazero, @Mrinal18, and contributors for adding this dataset.

Edit dataset card
Evaluate models HF Leaderboard