commit fe550429a549d15d29281338b4e6957a2d972f42 Author: Seth Date: Wed Mar 11 20:11:59 2026 +0000 Initialize piNail project with modern piNail2 web controller diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..871244d --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +__pycache__/ +*.pyc +*.pyo +*.pyd + +# Runtime artifacts +piNail2/logs/ +*.log + +# Local-only/private docs +GITEA_API.md + +# Large historical backup not needed for repo +Old_Backup/ + +# Vendored upstream development/build artifacts +ivPID-master/.idea/ +ivPID-master/docs/_build/ diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000..44734ae --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,65 @@ +# piNail Project Context + +## What this project is +- `piNail` is a Raspberry Pi e-nail temperature controller. +- Legacy scripts in project root (`piNail.py`, `logging_piNail.py`, etc.) are the old implementation. +- `piNail2/` is the active modernized implementation with a web UI and systemd service. + +## Active runtime (current) +- Host: Raspberry Pi at `192.168.0.159` (WiFi, static IP configured). +- Service: `pinail2.service` (systemd), enabled at boot. +- App directory on Pi: `/home/pi/piNail2`. +- Web UI: + - LAN: `http://192.168.0.159:5000` + - Reverse proxy: `https://nail.sethpc.xyz` (via Caddy + auth) + +## High-level architecture (`piNail2/`) +- `app.py`: Flask app, API routes, heartbeat, startup/shutdown wiring. +- `pid_controller.py`: PID loop thread, relay drive, safety logic, autotune logic. +- `thermocouple.py`: MAX6675 wrapper + spike filtering. +- `config.py` + `config.json`: config defaults + persistence. +- `templates/index.html`, `static/app.js`, `static/style.css`: dashboard UI. +- `pinail.service`: systemd unit file template. +- `deploy.sh`: deployment helper script. + +## Core API endpoints +- `GET /api/status`: full control + telemetry snapshot. +- `GET /api/history`: chart history stream. +- `POST /api/power`: on/off. +- `POST /api/setpoint`: set target temp. +- `POST /api/pid`: set PID values and proportional mode. +- `POST /api/pid/reset`: reset PID internals. +- `GET /api/autotune`: autotune status. +- `POST /api/autotune/start`: start relay-based autotune. +- `POST /api/autotune/stop`: stop autotune. +- `GET /api/heartbeat`: backend heartbeat for reconnect logic. + +## PID modes +- `P-on-Error` (`proportional_mode: error`): default, better target tracking. +- `P-on-Measurement` (`proportional_mode: measurement`): can reduce overshoot but may feel sluggish if not tuned. + +## Autotune notes +- Autotune uses relay oscillation around setpoint with hysteresis bands. +- UI shows running phase (`heating`/`cooling`) and peak progress. +- If current temp starts above setpoint, autotune may begin in cooling phase. + +## Safety behaviors +- Hard max temp cutoff. +- Thermocouple disconnect handling. +- Idle shutoff timer. +- Watchdog status exposed in heartbeat. + +## Operations quick commands +- Service status: `ssh pinail "sudo systemctl status pinail2"` +- Restart service: `ssh pinail "sudo systemctl restart pinail2"` +- Logs: `ssh pinail "sudo journalctl -u pinail2 -f"` +- Verify enabled: `ssh pinail "sudo systemctl is-enabled pinail2"` + +## Deployment workflow +- Edit files in this repo under `piNail2/`. +- Copy to Pi (`/home/pi/piNail2`) and restart service. +- Validate in browser with hard refresh to avoid stale JS/CSS. + +## Legacy code warning +- Root-level legacy scripts are preserved for reference. +- Do not mix old runtime and `pinail2.service` at the same time. diff --git a/CPU_Temp.py b/CPU_Temp.py new file mode 100644 index 0000000..218e516 --- /dev/null +++ b/CPU_Temp.py @@ -0,0 +1,10 @@ +import os +import time + +def measure_temp(): + temp = os.popen("vcgencmd measure_temp").readline() + return (temp.replace("temp=","")) + +while True: + print(measure_temp()) + time.sleep(1) \ No newline at end of file diff --git a/HARDWARE.md b/HARDWARE.md new file mode 100644 index 0000000..4bc900a --- /dev/null +++ b/HARDWARE.md @@ -0,0 +1,74 @@ +# piNail Hardware (Prototype v2) + +This file captures confirmed hardware details for the cigar-box prototype. +Unknowns are marked `TBD` instead of guessed. + +## Prototype Summary +- Enclosure: cigar box with integrated monitor in lid. +- Input power: IEC C14-style AC inlet ("computer PSU" style). +- Runtime controller: Raspberry Pi. +- Heating channels: 2 coil channels (channel 2 wired but not yet validated in operation). + +## High-Level Power Architecture + +### AC input path +1. AC inlet -> WiFi power switch. +2. From WiFi switch output -> master mains switch for system. +3. Master switch output branches: + - Branch A: to main DC switching PSU (powers Pi/control electronics). + - Branch B: to per-channel heater paths. + +### Control electronics power (DC) +- Main DC PSU output provides control-side power for: + - Raspberry Pi + - Two thermocouple interface chips + - Two SSR control sides +- Nominal rail appears to be `5V` (TBD: confirm exact PSU output voltage/current). + +### Heater power path (per channel) +- After master switch, AC route per channel is: + - fuse -> manual front-panel cutoff switch -> SSR load side -> coil connector power line +- The opposite AC pole is routed from WiFi switch output directly to coil connector corresponding pole. +- Ground/earth conductor is routed to coil connector grounds. + +## Channel/Signal Topology +- Each channel has: + - Thermocouple input (via MAX6675-type board) + - SSR-driven AC heater output + - Manual front panel power switch in series with heater path +- Raspberry Pi drives each relay channel independently. +- Thermocouple boards are connected to Pi GPIO. + +## Monitor Subsystem +- Separate 12V power supply for the built-in monitor. +- Short HDMI from Pi -> monitor. +- Monitor considered optional for future versions. + +## Grounding Notes +- Enclosure is non-metal (cigar box), so chassis bonding is not the main factor here. +- Coil grounds are connected. +- DC PSU ground is connected on the input-side ground scheme. +- `TBD`: provide explicit earth/neutral/hot naming by region and verify continuity paths. + +## Protection and Switching (Current Understanding) +- SSRs used for heater switching (`TBD`: exact model/rating). +- Fuses appear to be 1A glass tube, one per channel (`TBD`: verify rating + slow/fast blow type). +- Per-channel front switches are manual toggles. +- WiFi switch has onboard button and can keep networked power state independent of channel switches. + +## Operational Behavior (as built) +- You can power down Pi + nail supply via master mains switch while keeping WiFi switch infrastructure behavior available. +- You can cut each coil independently with front-panel switches without shutting down software. +- Channel 2 is wired but not yet fully tested under load. + +## Legacy/Prototype Context +- Prototype v1: external Pi setup (pinout/relay/thermocouple cable to Pi), no built-in monitor. +- Prototype v2: integrated Pi + wiring + optional integrated monitor. + +## Required TBDs Before Final Electrical Spec +1. Coil connector pinout (both channels, exact pin numbering/function). +2. Main DC PSU make/model and output spec (V/A). +3. SSR model and AC load ratings. +4. Fuse exact spec (amp, voltage, blow type, holder type). +5. Exact line/neutral/earth routing confirmation diagram. +6. Channel 2 validation checklist/results. diff --git a/LiveGraph_2.py b/LiveGraph_2.py new file mode 100644 index 0000000..35f0264 --- /dev/null +++ b/LiveGraph_2.py @@ -0,0 +1,44 @@ +import matplotlib.pyplot as plt +import matplotlib.animation as animation +import time + +fig = plt.figure() +ax1 = fig.add_subplot(1, 1, 1) +plt.gca().set_prop_cycle(color = ['red', 'blue', 'green', 'lightblue']) +plt.subplots_adjust(left = .05, right = .99, top =1, bottom =.05) +log_directory = './log_piNail.txt' +plt.xscale('linear') + +def animate(i): + pullData = open(log_directory, 'r') + dataArray = pullData.readlines() + temp_y = [ ] + setpoint_y = [ ] + output_y = [ ] + relay_y = [ ] + xar = [ ] + c_del_index = 0 + + ##print(len(dataArray)) + if len(dataArray) > 300: #only keep x lines in the log file + f = open(log_directory, 'w+') #Create a new log file, overwritting the previous one + f.close() + + for eachLine in dataArray[len(dataArray)-500: ]: #Only read the last x lines + if len(eachLine) > 1: + c_temp_y, c_setpoint_y, c_output_y, c_relay_y, c_xar= eachLine.split(', ') + temp_y.append(float(c_temp_y)) + setpoint_y.append(float(c_setpoint_y)) + output_y.append(float(c_output_y)) + relay_y.append(int(c_relay_y)) + xar.append(float(c_xar)) + ax1.set_xlim([float(c_xar) - 500000 ,float(c_xar) + 2000]) + + ax1.plot(xar, temp_y, linewidth = .2) + ax1.plot(xar, setpoint_y, linewidth = .2) + ax1.plot(xar, output_y, linewidth = .2) + ax1.plot(xar, relay_y) + +ani = animation.FuncAnimation(fig, animate, interval = 500) +plt.show() + diff --git a/MAX6675-master/.gitignore b/MAX6675-master/.gitignore new file mode 100644 index 0000000..22a3d90 --- /dev/null +++ b/MAX6675-master/.gitignore @@ -0,0 +1,5 @@ +build/ +dist/ +*.egg-info +*.pyc + diff --git a/MAX6675-master/MAX6675/MAX6675.py b/MAX6675-master/MAX6675/MAX6675.py new file mode 100644 index 0000000..d9bb8c1 --- /dev/null +++ b/MAX6675-master/MAX6675/MAX6675.py @@ -0,0 +1,78 @@ +# Copyright (c) 2015 Troy Dack +# Author: Troy Dack +# +# 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. +import logging + +import Adafruit_GPIO as GPIO +import Adafruit_GPIO.SPI as SPI + +class MAX6675(object): + """Class to represent a MAX6675 thermocouple temperature measurement board. + """ + + def __init__(self, clk=None, cs=None, do=None, spi=None, gpio=None): + """Initialize MAX6675 device with software SPI on the specified CLK, + CS, and DO pins. Alternatively can specify hardware SPI by sending an + Adafruit_GPIO.SPI.SpiDev device in the spi parameter. + """ + self._logger = logging.getLogger('MAX6675.MAX6675') + self._spi = None + # Handle hardware SPI + if spi is not None: + self._logger.debug('Using hardware SPI') + self._spi = spi + elif clk is not None and cs is not None and do is not None: + self._logger.debug('Using software SPI') + # Default to platform GPIO if not provided. + if gpio is None: + gpio = GPIO.get_platform_gpio() + self._spi = SPI.BitBang(gpio, clk, None, do, cs) + else: + raise ValueError('Must specify either spi for for hardware SPI or clk, cs, and do for softwrare SPI!') + self._spi.set_clock_hz(5000000) + self._spi.set_mode(0) + self._spi.set_bit_order(SPI.MSBFIRST) + + def readTempC(self): + """Return the thermocouple temperature value in degrees celsius.""" + v = self._read16() + # Check for error reading value. + if v & 0x4: + return float('NaN') + # Check if signed bit is set. + if v & 0x80000000: + # Negative value, take 2's compliment. Compute this with subtraction + # because python is a little odd about handling signed/unsigned. + v >>= 3 # only need the 12 MSB + v -= 4096 + else: + # Positive value, just shift the bits to get the value. + v >>= 3 # only need the 12 MSB + # Scale by 0.25 degrees C per bit and return value. + return v * 0.25 + + def _read16(self): + # Read 16 bits from the SPI bus. + raw = self._spi.read(2) + if raw is None or len(raw) != 2: + raise RuntimeError('Did not read expected number of bytes from device!') + value = raw[0] << 8 | raw[1] + self._logger.debug('Raw value: 0x{0:08X}'.format(value & 0xFFFFFFFF)) + return value diff --git a/MAX6675-master/MAX6675/__init__.py b/MAX6675-master/MAX6675/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/MAX6675-master/README.md b/MAX6675-master/README.md new file mode 100644 index 0000000..ea03396 --- /dev/null +++ b/MAX6675-master/README.md @@ -0,0 +1,25 @@ +Python MAX66755 +=============== + +Python library for accessing the MAX6675 thermocouple temperature sensor on a Raspberry Pi or Beaglebone Black. + +To install, first make sure some dependencies are available by running the following commands (on a Raspbian +or Beaglebone Black Debian install): + +```` +sudo apt-get update +sudo apt-get install build-essential python-dev python-smbus +```` + +Then download the library by clicking the download zip link and unzip the archive somewhere on your Raspberry Pi or Beaglebone Black. Then execute the following command in the directory of the library: + +```` +sudo python setup.py install +```` + +Make sure you have internet access on the device so it can download the required dependencies. + +See examples of usage in the examples folder. + +Written by Troy Dack. +MIT license, all text above must be included in any redistribution \ No newline at end of file diff --git a/MAX6675-master/examples/simple_test.py b/MAX6675-master/examples/simple_test.py new file mode 100644 index 0000000..0839668 --- /dev/null +++ b/MAX6675-master/examples/simple_test.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# coding: utf8 + +# Copyright (c) 2014 Adafruit Industries +# Author: Tony DiCola +# +# 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. + +# Can enable debug output by uncommenting: +#import logging +#logging.basicConfig(level=logging.DEBUG) + +import time + +import Adafruit_GPIO.SPI as SPI +import MAX6675.MAX6675 as MAX6675 + + +# Define a function to convert celsius to fahrenheit. +def c_to_f(c): + return c * 9.0 / 5.0 + 32.0 + + +# Uncomment one of the blocks of code below to configure your Pi or BBB to use +# software or hardware SPI. + +# Raspberry Pi software SPI configuration. +CLK = 25 +CS = 24 +DO = 18 +sensor = MAX6675.MAX6675(CLK, CS, DO) + +# Raspberry Pi hardware SPI configuration. +#SPI_PORT = 0 +#SPI_DEVICE = 0 +#sensor = MAX6675.MAX6675(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) + +# BeagleBone Black software SPI configuration. +#CLK = 'P9_12' +#CS = 'P9_15' +#DO = 'P9_23' +#sensor = MAX6675.MAX6675(CLK, CS, DO) + +# BeagleBone Black hardware SPI configuration. +# SPI_PORT = 1 +# SPI_DEVICE = 0 +# sensor = MAX6675.MAX6675(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) + +# Loop printing measurements every second. +print 'Press Ctrl-C to quit.' +while True: + temp = sensor.readTempC() + print 'Thermocouple Temperature: {0:0.3F}°C / {1:0.3F}°F'.format(temp, c_to_f(temp)) + time.sleep(1.0) \ No newline at end of file diff --git a/MAX6675-master/ez_setup.py b/MAX6675-master/ez_setup.py new file mode 100644 index 0000000..23ea9a2 --- /dev/null +++ b/MAX6675-master/ez_setup.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python +"""Bootstrap setuptools installation + +To use setuptools in your package's setup.py, include this +file in the same directory and add this to the top of your setup.py:: + + from ez_setup import use_setuptools + use_setuptools() + +To require a specific version of setuptools, set a download +mirror, or use an alternate download directory, simply supply +the appropriate options to ``use_setuptools()``. + +This file can also be run as a script to install or upgrade setuptools. +""" +import os +import shutil +import sys +import tempfile +import zipfile +import optparse +import subprocess +import platform +import textwrap +import contextlib + +from distutils import log + +try: + from site import USER_SITE +except ImportError: + USER_SITE = None + +DEFAULT_VERSION = "3.5.1" +DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" + +def _python_cmd(*args): + """ + Return True if the command succeeded. + """ + args = (sys.executable,) + args + return subprocess.call(args) == 0 + + +def _install(archive_filename, install_args=()): + with archive_context(archive_filename): + # installing + log.warn('Installing Setuptools') + if not _python_cmd('setup.py', 'install', *install_args): + log.warn('Something went wrong during the installation.') + log.warn('See the error message above.') + # exitcode will be 2 + return 2 + + +def _build_egg(egg, archive_filename, to_dir): + with archive_context(archive_filename): + # building an egg + log.warn('Building a Setuptools egg in %s', to_dir) + _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) + # returning the result + log.warn(egg) + if not os.path.exists(egg): + raise IOError('Could not build the egg.') + + +def get_zip_class(): + """ + Supplement ZipFile class to support context manager for Python 2.6 + """ + class ContextualZipFile(zipfile.ZipFile): + def __enter__(self): + return self + def __exit__(self, type, value, traceback): + self.close + return zipfile.ZipFile if hasattr(zipfile.ZipFile, '__exit__') else \ + ContextualZipFile + + +@contextlib.contextmanager +def archive_context(filename): + # extracting the archive + tmpdir = tempfile.mkdtemp() + log.warn('Extracting in %s', tmpdir) + old_wd = os.getcwd() + try: + os.chdir(tmpdir) + with get_zip_class()(filename) as archive: + archive.extractall() + + # going in the directory + subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) + os.chdir(subdir) + log.warn('Now working in %s', subdir) + yield + + finally: + os.chdir(old_wd) + shutil.rmtree(tmpdir) + + +def _do_download(version, download_base, to_dir, download_delay): + egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' + % (version, sys.version_info[0], sys.version_info[1])) + if not os.path.exists(egg): + archive = download_setuptools(version, download_base, + to_dir, download_delay) + _build_egg(egg, archive, to_dir) + sys.path.insert(0, egg) + + # Remove previously-imported pkg_resources if present (see + # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details). + if 'pkg_resources' in sys.modules: + del sys.modules['pkg_resources'] + + import setuptools + setuptools.bootstrap_install_from = egg + + +def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, + to_dir=os.curdir, download_delay=15): + to_dir = os.path.abspath(to_dir) + rep_modules = 'pkg_resources', 'setuptools' + imported = set(sys.modules).intersection(rep_modules) + try: + import pkg_resources + except ImportError: + return _do_download(version, download_base, to_dir, download_delay) + try: + pkg_resources.require("setuptools>=" + version) + return + except pkg_resources.DistributionNotFound: + return _do_download(version, download_base, to_dir, download_delay) + except pkg_resources.VersionConflict as VC_err: + if imported: + msg = textwrap.dedent(""" + The required version of setuptools (>={version}) is not available, + and can't be installed while this script is running. Please + install a more recent version first, using + 'easy_install -U setuptools'. + + (Currently using {VC_err.args[0]!r}) + """).format(VC_err=VC_err, version=version) + sys.stderr.write(msg) + sys.exit(2) + + # otherwise, reload ok + del pkg_resources, sys.modules['pkg_resources'] + return _do_download(version, download_base, to_dir, download_delay) + +def _clean_check(cmd, target): + """ + Run the command to download target. If the command fails, clean up before + re-raising the error. + """ + try: + subprocess.check_call(cmd) + except subprocess.CalledProcessError: + if os.access(target, os.F_OK): + os.unlink(target) + raise + +def download_file_powershell(url, target): + """ + Download the file at url to target using Powershell (which will validate + trust). Raise an exception if the command cannot complete. + """ + target = os.path.abspath(target) + cmd = [ + 'powershell', + '-Command', + "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars(), + ] + _clean_check(cmd, target) + +def has_powershell(): + if platform.system() != 'Windows': + return False + cmd = ['powershell', '-Command', 'echo test'] + devnull = open(os.path.devnull, 'wb') + try: + try: + subprocess.check_call(cmd, stdout=devnull, stderr=devnull) + except Exception: + return False + finally: + devnull.close() + return True + +download_file_powershell.viable = has_powershell + +def download_file_curl(url, target): + cmd = ['curl', url, '--silent', '--output', target] + _clean_check(cmd, target) + +def has_curl(): + cmd = ['curl', '--version'] + devnull = open(os.path.devnull, 'wb') + try: + try: + subprocess.check_call(cmd, stdout=devnull, stderr=devnull) + except Exception: + return False + finally: + devnull.close() + return True + +download_file_curl.viable = has_curl + +def download_file_wget(url, target): + cmd = ['wget', url, '--quiet', '--output-document', target] + _clean_check(cmd, target) + +def has_wget(): + cmd = ['wget', '--version'] + devnull = open(os.path.devnull, 'wb') + try: + try: + subprocess.check_call(cmd, stdout=devnull, stderr=devnull) + except Exception: + return False + finally: + devnull.close() + return True + +download_file_wget.viable = has_wget + +def download_file_insecure(url, target): + """ + Use Python to download the file, even though it cannot authenticate the + connection. + """ + try: + from urllib.request import urlopen + except ImportError: + from urllib2 import urlopen + src = dst = None + try: + src = urlopen(url) + # Read/write all in one block, so we don't create a corrupt file + # if the download is interrupted. + data = src.read() + dst = open(target, "wb") + dst.write(data) + finally: + if src: + src.close() + if dst: + dst.close() + +download_file_insecure.viable = lambda: True + +def get_best_downloader(): + downloaders = [ + download_file_powershell, + download_file_curl, + download_file_wget, + download_file_insecure, + ] + + for dl in downloaders: + if dl.viable(): + return dl + +def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, + to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): + """ + Download setuptools from a specified location and return its filename + + `version` should be a valid setuptools version number that is available + as an egg for download under the `download_base` URL (which should end + with a '/'). `to_dir` is the directory where the egg will be downloaded. + `delay` is the number of seconds to pause before an actual download + attempt. + + ``downloader_factory`` should be a function taking no arguments and + returning a function for downloading a URL to a target. + """ + # making sure we use the absolute path + to_dir = os.path.abspath(to_dir) + zip_name = "setuptools-%s.zip" % version + url = download_base + zip_name + saveto = os.path.join(to_dir, zip_name) + if not os.path.exists(saveto): # Avoid repeated downloads + log.warn("Downloading %s", url) + downloader = downloader_factory() + downloader(url, saveto) + return os.path.realpath(saveto) + +def _build_install_args(options): + """ + Build the arguments to 'python setup.py install' on the setuptools package + """ + return ['--user'] if options.user_install else [] + +def _parse_args(): + """ + Parse the command line for options + """ + parser = optparse.OptionParser() + parser.add_option( + '--user', dest='user_install', action='store_true', default=False, + help='install in user site package (requires Python 2.6 or later)') + parser.add_option( + '--download-base', dest='download_base', metavar="URL", + default=DEFAULT_URL, + help='alternative URL from where to download the setuptools package') + parser.add_option( + '--insecure', dest='downloader_factory', action='store_const', + const=lambda: download_file_insecure, default=get_best_downloader, + help='Use internal, non-validating downloader' + ) + parser.add_option( + '--version', help="Specify which version to download", + default=DEFAULT_VERSION, + ) + options, args = parser.parse_args() + # positional arguments are ignored + return options + +def main(): + """Install or upgrade setuptools and EasyInstall""" + options = _parse_args() + archive = download_setuptools( + version=options.version, + download_base=options.download_base, + downloader_factory=options.downloader_factory, + ) + return _install(archive, _build_install_args(options)) + +if __name__ == '__main__': + sys.exit(main()) diff --git a/MAX6675-master/setup.py b/MAX6675-master/setup.py new file mode 100644 index 0000000..f261664 --- /dev/null +++ b/MAX6675-master/setup.py @@ -0,0 +1,14 @@ +from ez_setup import use_setuptools +use_setuptools() +from setuptools import setup, find_packages + +setup(name = 'MAX6675', + version = '1.0.0', + author = 'Troy Dack', + author_email = 'troy@dack.com.au', + description = 'Library for accessing the MAX6675 thermocouple temperature sensor on a Raspberry Pi or Beaglebone Black.', + license = 'MIT', + url = 'https://github.com/tdack/MAX6675/', + dependency_links = ['https://github.com/adafruit/Adafruit_Python_GPIO/tarball/master#egg=Adafruit-GPIO-0.6.5'], + install_requires = ['Adafruit-GPIO>=0.6.5'], + packages = find_packages()) diff --git a/P_I_D_values.txt b/P_I_D_values.txt new file mode 100644 index 0000000..eb39b9b --- /dev/null +++ b/P_I_D_values.txt @@ -0,0 +1,7 @@ +10 +5 +1.0 +.4 +3000 +530 +1 diff --git a/P_on_E_images/10-0,1-0-5000-710.png b/P_on_E_images/10-0,1-0-5000-710.png new file mode 100644 index 0000000..85b880a Binary files /dev/null and b/P_on_E_images/10-0,1-0-5000-710.png differ diff --git a/P_on_E_images/160-0-0-5000-710.png b/P_on_E_images/160-0-0-5000-710.png new file mode 100644 index 0000000..9978533 Binary files /dev/null and b/P_on_E_images/160-0-0-5000-710.png differ diff --git a/P_on_E_images/20-0,05-0-5000-710.png b/P_on_E_images/20-0,05-0-5000-710.png new file mode 100644 index 0000000..6f3c750 Binary files /dev/null and b/P_on_E_images/20-0,05-0-5000-710.png differ diff --git a/P_on_E_images/20-0,1-0-5000-710.png b/P_on_E_images/20-0,1-0-5000-710.png new file mode 100644 index 0000000..d12d7fc Binary files /dev/null and b/P_on_E_images/20-0,1-0-5000-710.png differ diff --git a/P_on_E_images/20-0-0-5000-690.png b/P_on_E_images/20-0-0-5000-690.png new file mode 100644 index 0000000..dd87a5b Binary files /dev/null and b/P_on_E_images/20-0-0-5000-690.png differ diff --git a/P_on_E_images/30-0-0-5000-690.png b/P_on_E_images/30-0-0-5000-690.png new file mode 100644 index 0000000..bcbb455 Binary files /dev/null and b/P_on_E_images/30-0-0-5000-690.png differ diff --git a/P_on_E_images/40-0,01-0-5000-710.png b/P_on_E_images/40-0,01-0-5000-710.png new file mode 100644 index 0000000..ec03af8 Binary files /dev/null and b/P_on_E_images/40-0,01-0-5000-710.png differ diff --git a/P_on_E_images/40-0,025-0-5000-710.png b/P_on_E_images/40-0,025-0-5000-710.png new file mode 100644 index 0000000..3716f36 Binary files /dev/null and b/P_on_E_images/40-0,025-0-5000-710.png differ diff --git a/P_on_E_images/40-0,05-0-5000-710.png b/P_on_E_images/40-0,05-0-5000-710.png new file mode 100644 index 0000000..60ea808 Binary files /dev/null and b/P_on_E_images/40-0,05-0-5000-710.png differ diff --git a/P_on_E_images/40-0,1-0-5000-710.png b/P_on_E_images/40-0,1-0-5000-710.png new file mode 100644 index 0000000..127db80 Binary files /dev/null and b/P_on_E_images/40-0,1-0-5000-710.png differ diff --git a/P_on_E_images/40-0-0-5000-690.png b/P_on_E_images/40-0-0-5000-690.png new file mode 100644 index 0000000..7ce32e3 Binary files /dev/null and b/P_on_E_images/40-0-0-5000-690.png differ diff --git a/P_on_E_images/40-0-0-5000-710.png b/P_on_E_images/40-0-0-5000-710.png new file mode 100644 index 0000000..d7646e3 Binary files /dev/null and b/P_on_E_images/40-0-0-5000-710.png differ diff --git a/P_on_E_images/43-0-0-5000-710.png b/P_on_E_images/43-0-0-5000-710.png new file mode 100644 index 0000000..389bf9b Binary files /dev/null and b/P_on_E_images/43-0-0-5000-710.png differ diff --git a/P_on_E_images/45-0-0-5000-690.png b/P_on_E_images/45-0-0-5000-690.png new file mode 100644 index 0000000..b0f6f24 Binary files /dev/null and b/P_on_E_images/45-0-0-5000-690.png differ diff --git a/P_on_E_images/45-0-0-5000-710.png b/P_on_E_images/45-0-0-5000-710.png new file mode 100644 index 0000000..e45693c Binary files /dev/null and b/P_on_E_images/45-0-0-5000-710.png differ diff --git a/P_on_E_images/5-0,025-0-5000-710.png b/P_on_E_images/5-0,025-0-5000-710.png new file mode 100644 index 0000000..ab72181 Binary files /dev/null and b/P_on_E_images/5-0,025-0-5000-710.png differ diff --git a/P_on_E_images/5-0,035-0,01-5000-710.png b/P_on_E_images/5-0,035-0,01-5000-710.png new file mode 100644 index 0000000..2d0376c Binary files /dev/null and b/P_on_E_images/5-0,035-0,01-5000-710.png differ diff --git a/P_on_E_images/5-0,035-0-5000-710.png b/P_on_E_images/5-0,035-0-5000-710.png new file mode 100644 index 0000000..c8f0504 Binary files /dev/null and b/P_on_E_images/5-0,035-0-5000-710.png differ diff --git a/P_on_E_images/5-0,05-0-5000-710.png b/P_on_E_images/5-0,05-0-5000-710.png new file mode 100644 index 0000000..9fa9d3a Binary files /dev/null and b/P_on_E_images/5-0,05-0-5000-710.png differ diff --git a/P_on_E_images/5-0,1-0-5000-710.png b/P_on_E_images/5-0,1-0-5000-710.png new file mode 100644 index 0000000..888d9bf Binary files /dev/null and b/P_on_E_images/5-0,1-0-5000-710.png differ diff --git a/P_on_E_images/80-0,05-0-5000-710.png b/P_on_E_images/80-0,05-0-5000-710.png new file mode 100644 index 0000000..f5f2dee Binary files /dev/null and b/P_on_E_images/80-0,05-0-5000-710.png differ diff --git a/P_on_E_images/80-0,2-0-5000-710.png b/P_on_E_images/80-0,2-0-5000-710.png new file mode 100644 index 0000000..ef23f3a Binary files /dev/null and b/P_on_E_images/80-0,2-0-5000-710.png differ diff --git a/P_on_E_images/80-0,4-0-5000-710.png b/P_on_E_images/80-0,4-0-5000-710.png new file mode 100644 index 0000000..108c5a5 Binary files /dev/null and b/P_on_E_images/80-0,4-0-5000-710.png differ diff --git a/P_on_E_images/80-0,8-0,02-5000-710.png b/P_on_E_images/80-0,8-0,02-5000-710.png new file mode 100644 index 0000000..2516bee Binary files /dev/null and b/P_on_E_images/80-0,8-0,02-5000-710.png differ diff --git a/P_on_E_images/80-0,8-0,64-5000-710.png b/P_on_E_images/80-0,8-0,64-5000-710.png new file mode 100644 index 0000000..7a1d8c5 Binary files /dev/null and b/P_on_E_images/80-0,8-0,64-5000-710.png differ diff --git a/P_on_E_images/80-0,8-0-5000-710.png b/P_on_E_images/80-0,8-0-5000-710.png new file mode 100644 index 0000000..d9c301f Binary files /dev/null and b/P_on_E_images/80-0,8-0-5000-710.png differ diff --git a/P_on_E_images/80-0,8-5,12-5000-710.png b/P_on_E_images/80-0,8-5,12-5000-710.png new file mode 100644 index 0000000..50e2490 Binary files /dev/null and b/P_on_E_images/80-0,8-5,12-5000-710.png differ diff --git a/P_on_E_images/80-0-0-5000-710.png b/P_on_E_images/80-0-0-5000-710.png new file mode 100644 index 0000000..add1aad Binary files /dev/null and b/P_on_E_images/80-0-0-5000-710.png differ diff --git a/P_on_E_images/80-1,6--0,16-5000-710.png b/P_on_E_images/80-1,6--0,16-5000-710.png new file mode 100644 index 0000000..dfe82e5 Binary files /dev/null and b/P_on_E_images/80-1,6--0,16-5000-710.png differ diff --git a/P_on_E_images/80-1,6-0,04-5000-710.png b/P_on_E_images/80-1,6-0,04-5000-710.png new file mode 100644 index 0000000..4ea8dbb Binary files /dev/null and b/P_on_E_images/80-1,6-0,04-5000-710.png differ diff --git a/P_on_E_images/80-1,6-0,08-5000-710.png b/P_on_E_images/80-1,6-0,08-5000-710.png new file mode 100644 index 0000000..167a486 Binary files /dev/null and b/P_on_E_images/80-1,6-0,08-5000-710.png differ diff --git a/P_on_E_images/80-1,6-0,16-5000-710.png b/P_on_E_images/80-1,6-0,16-5000-710.png new file mode 100644 index 0000000..86d5158 Binary files /dev/null and b/P_on_E_images/80-1,6-0,16-5000-710.png differ diff --git a/P_on_E_images/80-1,6-0,32-5000-710.png b/P_on_E_images/80-1,6-0,32-5000-710.png new file mode 100644 index 0000000..b6d6633 Binary files /dev/null and b/P_on_E_images/80-1,6-0,32-5000-710.png differ diff --git a/P_on_E_images/80-1,6-0-5000-710.png b/P_on_E_images/80-1,6-0-5000-710.png new file mode 100644 index 0000000..ce396d4 Binary files /dev/null and b/P_on_E_images/80-1,6-0-5000-710.png differ diff --git a/P_on_E_images/80-1,6-1,28-5000-710.png b/P_on_E_images/80-1,6-1,28-5000-710.png new file mode 100644 index 0000000..ef8c567 Binary files /dev/null and b/P_on_E_images/80-1,6-1,28-5000-710.png differ diff --git a/P_on_E_images/80-1,6-10,24-5000-710.png b/P_on_E_images/80-1,6-10,24-5000-710.png new file mode 100644 index 0000000..0ade3b9 Binary files /dev/null and b/P_on_E_images/80-1,6-10,24-5000-710.png differ diff --git a/P_on_E_images/80-1,6-2,56-5000-710.png b/P_on_E_images/80-1,6-2,56-5000-710.png new file mode 100644 index 0000000..7916da3 Binary files /dev/null and b/P_on_E_images/80-1,6-2,56-5000-710.png differ diff --git a/P_on_E_images/80-1,6-20,48-5000-710.png b/P_on_E_images/80-1,6-20,48-5000-710.png new file mode 100644 index 0000000..16d9dd9 Binary files /dev/null and b/P_on_E_images/80-1,6-20,48-5000-710.png differ diff --git a/P_on_E_images/80-1,6-5,12-5000-710.png b/P_on_E_images/80-1,6-5,12-5000-710.png new file mode 100644 index 0000000..7681f2e Binary files /dev/null and b/P_on_E_images/80-1,6-5,12-5000-710.png differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..2626832 --- /dev/null +++ b/README.md @@ -0,0 +1,35 @@ +# piNail + +Raspberry Pi e-nail temperature controller. + +This repo contains: + +- Legacy root-level scripts (`piNail.py`, `logging_piNail.py`, etc.) +- Active modern implementation in `piNail2/` (Flask web UI + systemd runtime) +- Project docs (`CONTEXT.md`, `RUNBOOK.md`, hardware/theme notes) + +## Active Runtime + +- Service: `pinail2.service` +- App path on Pi: `/home/pi/piNail2` +- UI: + - LAN: `http://192.168.0.159:5000` + - Reverse proxy: `https://nail.sethpc.xyz` + +## Main Features (`piNail2/`) + +- PID heater control loop +- Real-time dashboard and chart +- Setpoint + PID tuning controls +- Autotune mode +- Safety cutoffs and watchdog behavior + +## Quick Ops + +```bash +ssh pinail "sudo systemctl status pinail2" +ssh pinail "sudo systemctl restart pinail2" +ssh pinail "sudo journalctl -u pinail2 -f" +``` + +See `RUNBOOK.md` for troubleshooting and `CONTEXT.md` for full architecture notes. diff --git a/RUNBOOK.md b/RUNBOOK.md new file mode 100644 index 0000000..399b53c --- /dev/null +++ b/RUNBOOK.md @@ -0,0 +1,42 @@ +# piNail Runbook + +Short operational steps for common issues. + +## URLs +- LAN UI: `http://192.168.0.159:5000` +- Reverse proxy: `https://nail.sethpc.xyz` + +## Service control +- Status: `ssh pinail "sudo systemctl status pinail2"` +- Restart: `ssh pinail "sudo systemctl restart pinail2"` +- Enable at boot: `ssh pinail "sudo systemctl enable pinail2"` +- Logs: `ssh pinail "sudo journalctl -u pinail2 -f"` + +## If buttons do not work +1. Hard refresh browser (`Ctrl+Shift+R` / `Cmd+Shift+R`). +2. Confirm backend is online in header (`Backend: Online`). +3. Restart service: `ssh pinail "sudo systemctl restart pinail2"`. +4. Recheck UI and verify `Last command` line updates after click. + +## If heater does not respond +1. Ensure ON state in UI and watch `Relay` status. +2. Check thermocouple status (`TC` should be `OK`). +3. Verify no safety trip banner is active. +4. Check logs for relay/GPIO errors. + +## If temperature is far off target +1. Use `P Mode = P-on-Error` for stronger tracking. +2. Click `Reset I` after major setpoint changes. +3. Start autotune and wait for completion. +4. If autotune is too aggressive, manually lower `kP`/`kI` and increase `kD`. + +## Autotune quick steps +1. Set desired target temp. +2. Turn heater ON. +3. Click `Start Autotune`. +4. Watch status (`Running heating/cooling`, peak counter). +5. Wait for `Autotune: Complete`. + +## Deploy updated code +- From this repo: `cd /root/piNail/piNail2 && ./deploy.sh` +- Then restart: `ssh pinail "sudo systemctl restart pinail2"` diff --git a/SETHPC_LOGO_GENERATOR_API.md b/SETHPC_LOGO_GENERATOR_API.md new file mode 100644 index 0000000..8b6f775 --- /dev/null +++ b/SETHPC_LOGO_GENERATOR_API.md @@ -0,0 +1,125 @@ +# SETHPC Logo Generator API + +Public API endpoint for generating SethPC/Sethflix-style logos as SVG or PNG. + +- Base URL: `https://gallery.sethpc.xyz` +- Endpoint: `POST /api/logo` +- Content types: `application/json` or `application/x-www-form-urlencoded` + +## Parameters + +Required: + +- `text` - main logo text + +Optional: + +- `color` - hex color (`#RRGGBB` or `RRGGBB`), default `#D35400` +- `mode` - `standard` or `lockup`, default `standard` +- `shape` - `normal` or `square`, default `normal` +- `subtext` - required when `mode=lockup`; automatically uppercased +- `format` - `json`, `svg`, or `png`, default `json` + +## Behavior + +- All generated logos are saved under: + - `/tank/SethFlix Visual Assets/UserGen/` +- Emoji and unsupported glyphs are omitted. +- `lockup` mode generates: + - main logo + - full-width horizontal line + - sans-serif uppercase subtext + - full-width horizontal line +- `shape=square` pads the shorter side so final width and height are equal. + +## Response Modes + +### 1) `format=json` (default) + +Returns metadata and links to the generated asset. + +Example: + +```bash +curl -sS -X POST "https://gallery.sethpc.xyz/api/logo" \ + -H "Content-Type: application/json" \ + -d '{ + "text": "SETHPC", + "mode": "lockup", + "shape": "square", + "subtext": "gallery expo", + "color": "#D35400", + "format": "json" + }' +``` + +Sample JSON response: + +```json +{ + "ok": true, + "text": "SETHPC", + "subtext": "GALLERY EXPO", + "mode": "lockup", + "shape": "square", + "color": "#D35400", + "skipped": [], + "asset_path": "UserGen/sethpc_20260311_123456_000001.svg", + "svg_url": "/asset/UserGen/sethpc_20260311_123456_000001.svg", + "png_url": "/asset-png/UserGen/sethpc_20260311_123456_000001.svg", + "svg_download_url": "/asset/UserGen/sethpc_20260311_123456_000001.svg", + "png_download_url": "/asset-png/UserGen/sethpc_20260311_123456_000001.svg" +} +``` + +### 2) `format=svg` + +Returns generated SVG file directly as attachment. + +```bash +curl -L -X POST "https://gallery.sethpc.xyz/api/logo" \ + -H "Content-Type: application/json" \ + -d '{ + "text": "SETHPC.XYZ", + "shape": "square", + "color": "#D35400", + "format": "svg" + }' \ + -o "sethpc.svg" +``` + +### 3) `format=png` + +Returns generated PNG directly as attachment. + +```bash +curl -L -X POST "https://gallery.sethpc.xyz/api/logo" \ + -H "Content-Type: application/json" \ + -d '{ + "text": "SETHPC", + "mode": "lockup", + "shape": "square", + "subtext": "GALLERY EXPO", + "format": "png" + }' \ + -o "sethpc.png" +``` + +## Error Responses + +Common `400` errors: + +- missing `text` +- invalid `mode` (must be `standard` or `lockup`) +- invalid `shape` (must be `normal` or `square`) +- invalid `format` (must be `json`, `svg`, or `png`) +- missing `subtext` when `mode=lockup` + +Error shape: + +```json +{ + "ok": false, + "error": "text is required." +} +``` diff --git a/ivPID-master/LICENSE b/ivPID-master/LICENSE new file mode 100644 index 0000000..733c072 --- /dev/null +++ b/ivPID-master/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/ivPID-master/PID.py b/ivPID-master/PID.py new file mode 100644 index 0000000..6eef0f7 --- /dev/null +++ b/ivPID-master/PID.py @@ -0,0 +1,129 @@ +#!/usr/bin/python +# +# This file is part of IvPID. +# Copyright (C) 2015 Ivmech Mechatronics Ltd. +# +# IvPID is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# IvPID is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# title :PID.py +# description :python pid controller +# author :Caner Durmusoglu +# date :20151218 +# version :0.1 +# notes : +# python_version :2.7 +# ============================================================================== + +"""Ivmech PID Controller is simple implementation of a Proportional-Integral-Derivative (PID) Controller in the Python Programming Language. +More information about PID Controller: http://en.wikipedia.org/wiki/PID_controller +""" +import time + +class PID: + """PID Controller + """ + + def __init__(self, P=0.2, I=0.0, D=0.0): + + self.Kp = P + self.Ki = I + self.Kd = D + + self.sample_time = 0.00 + self.current_time = time.time() + self.last_time = self.current_time + + self.clear() + + def clear(self): + """Clears PID computations and coefficients""" + self.SetPoint = 0.0 + + self.PTerm = 0.0 + self.ITerm = 0.0 + self.DTerm = 0.0 + self.last_error = 0.0 + + # Windup Guard + self.int_error = 0.0 + self.windup_guard = 20.0 + + self.output = 0.0 + + def update(self, feedback_value): + """Calculates PID value for given reference feedback + + .. math:: + u(t) = K_p e(t) + K_i \int_{0}^{t} e(t)dt + K_d {de}/{dt} + + .. figure:: images/pid_1.png + :align: center + + Test PID with Kp=1.2, Ki=1, Kd=0.001 (test_pid.py) + + """ + error = self.SetPoint - feedback_value + + self.current_time = time.time() + delta_time = self.current_time - self.last_time + delta_error = error - self.last_error + + if (delta_time >= self.sample_time): + self.PTerm = self.Kp * error + self.ITerm += error * delta_time + + if (self.ITerm < -self.windup_guard): + self.ITerm = -self.windup_guard + elif (self.ITerm > self.windup_guard): + self.ITerm = self.windup_guard + + self.DTerm = 0.0 + if delta_time > 0: + self.DTerm = delta_error / delta_time + + # Remember last time and last error for next calculation + self.last_time = self.current_time + self.last_error = error + + self.output = self.PTerm + (self.Ki * self.ITerm) + (self.Kd * self.DTerm) + + def setKp(self, proportional_gain): + """Determines how aggressively the PID reacts to the current error with setting Proportional Gain""" + self.Kp = proportional_gain + + def setKi(self, integral_gain): + """Determines how aggressively the PID reacts to the current error with setting Integral Gain""" + self.Ki = integral_gain + + def setKd(self, derivative_gain): + """Determines how aggressively the PID reacts to the current error with setting Derivative Gain""" + self.Kd = derivative_gain + + def setWindup(self, windup): + """Integral windup, also known as integrator windup or reset windup, + refers to the situation in a PID feedback controller where + a large change in setpoint occurs (say a positive change) + and the integral terms accumulates a significant error + during the rise (windup), thus overshooting and continuing + to increase as this accumulated error is unwound + (offset by errors in the other direction). + The specific problem is the excess overshooting. + """ + self.windup_guard = windup + + def setSampleTime(self, sample_time): + """PID that should be updated at a regular interval. + Based on a pre-determined sampe time, the PID decides if it should compute or return immediately. + """ + self.sample_time = sample_time diff --git a/ivPID-master/README.md b/ivPID-master/README.md new file mode 100644 index 0000000..9bc6113 --- /dev/null +++ b/ivPID-master/README.md @@ -0,0 +1,14 @@ +# ivPID + +http://ivmech.github.io/ivPID + +Ivmech PID Controller is simple implementation of a Proportional-Integral-Derivative (PID) Controller in the Python Programming Language. + +![alt pid](https://raw.githubusercontent.com/ivmech/ivPID/master/docs/images/pid_control.png) + +More information about PID Controller: http://en.wikipedia.org/wiki/PID_controller + + +![alt test_pid](https://raw.githubusercontent.com/ivmech/ivPID/master/docs/images/pid_1.png) + +Test PID with Kp=1.2, Ki=1, Kd=0.001 ([test_pid.py](/ivmech/ivPID/blob/master/test_pid.py)) \ No newline at end of file diff --git a/ivPID-master/docs/Makefile b/ivPID-master/docs/Makefile new file mode 100644 index 0000000..9de1f5e --- /dev/null +++ b/ivPID-master/docs/Makefile @@ -0,0 +1,193 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build +BUILDDIR = ../../ivPID-docs + +# 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 + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " applehelp to make an Apple Help Book" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + @echo " coverage to run coverage check of the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ivPID.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ivPID.qhc" + +applehelp: + $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp + @echo + @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." + @echo "N.B. You won't be able to view it unless you put it in" \ + "~/Library/Documentation/Help or install it in your application" \ + "bundle." + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/ivPID" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ivPID" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +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." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +coverage: + $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage + @echo "Testing of coverage in the sources finished, look at the " \ + "results in $(BUILDDIR)/coverage/python.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/ivPID-master/docs/conf.py b/ivPID-master/docs/conf.py new file mode 100644 index 0000000..82c85a8 --- /dev/null +++ b/ivPID-master/docs/conf.py @@ -0,0 +1,285 @@ +# -*- coding: utf-8 -*- +# +# ivPID documentation build configuration file, created by +# sphinx-quickstart on Fri Dec 18 12:30:42 2015. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# 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. +sys.path.insert(0, os.path.abspath('../.')) + + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.mathjax', "sphinxtogithub"] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'ivPID' +copyright = u'2015, Caner Durmusoglu' +author = u'Caner Durmusoglu' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = u'0.1' +# The full version, including alpha/beta/rc tags. +release = u'0.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- 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' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# 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'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +#html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +#html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +#html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'ivPIDdoc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', + +# Latex figure (float) alignment +#'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'ivPID.tex', u'ivPID Documentation', + u'Caner Durmusoglu', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'ivpid', u'ivPID Documentation', + [author], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'ivPID', u'ivPID Documentation', + author, 'ivPID', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/ivPID-master/docs/images/logo.png b/ivPID-master/docs/images/logo.png new file mode 100644 index 0000000..76dd5c6 Binary files /dev/null and b/ivPID-master/docs/images/logo.png differ diff --git a/ivPID-master/docs/images/pid_1.png b/ivPID-master/docs/images/pid_1.png new file mode 100644 index 0000000..14bc1d1 Binary files /dev/null and b/ivPID-master/docs/images/pid_1.png differ diff --git a/ivPID-master/docs/images/pid_control.png b/ivPID-master/docs/images/pid_control.png new file mode 100644 index 0000000..9fb8d07 Binary files /dev/null and b/ivPID-master/docs/images/pid_control.png differ diff --git a/ivPID-master/docs/index.rst b/ivPID-master/docs/index.rst new file mode 100644 index 0000000..e10bf5e --- /dev/null +++ b/ivPID-master/docs/index.rst @@ -0,0 +1,30 @@ +.. ivPID documentation master file, created by + sphinx-quickstart on Fri Dec 18 12:30:42 2015. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +ivPID Ivmech Python PID Controller +================================= + +.. figure:: images/pid_control.png + :align: center + + PID Controller + + +.. toctree:: + :maxdepth: 2 + +.. automodule:: PID + +.. autoclass:: PID + :members: + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/ivPID-master/docs/make.bat b/ivPID-master/docs/make.bat new file mode 100644 index 0000000..aa851dc --- /dev/null +++ b/ivPID-master/docs/make.bat @@ -0,0 +1,263 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + echo. coverage to run coverage check of the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +REM Check if sphinx-build is available and fallback to Python version if any +%SPHINXBUILD% 1>NUL 2>NUL +if errorlevel 9009 goto sphinx_python +goto sphinx_ok + +:sphinx_python + +set SPHINXBUILD=python -m sphinx.__init__ +%SPHINXBUILD% 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 +) + +:sphinx_ok + + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\ivPID.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\ivPID.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "coverage" ( + %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage + if errorlevel 1 exit /b 1 + echo. + echo.Testing of coverage in the sources finished, look at the ^ +results in %BUILDDIR%/coverage/python.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/ivPID-master/test_pid.py b/ivPID-master/test_pid.py new file mode 100644 index 0000000..761f261 --- /dev/null +++ b/ivPID-master/test_pid.py @@ -0,0 +1,94 @@ +#!/usr/bin/python +# +# This file is part of IvPID. +# Copyright (C) 2015 Ivmech Mechatronics Ltd. +# +# IvPID is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# IvPID is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +#title :test_pid.py +#description :python pid controller test +#author :Caner Durmusoglu +#date :20151218 +#version :0.1 +#notes : +#python_version :2.7 +#dependencies : matplotlib, numpy, scipy +#============================================================================== + +import PID +import time +import matplotlib.pyplot as plt +import numpy as np +from scipy.interpolate import spline + +def test_pid(P = 0.2, I = 0.0, D= 0.0, L=100): + """Self-test PID class + + .. note:: + ... + for i in range(1, END): + pid.update(feedback) + output = pid.output + if pid.SetPoint > 0: + feedback += (output - (1/i)) + if i>9: + pid.SetPoint = 1 + time.sleep(0.02) + --- + """ + pid = PID.PID(P, I, D) + + pid.SetPoint=0.0 + pid.setSampleTime(0.01) + + END = L + feedback = 0 + + feedback_list = [] + time_list = [] + setpoint_list = [] + + for i in range(1, END): + pid.update(feedback) + output = pid.output + if pid.SetPoint > 0: + feedback += (output - (1/i)) + if i>9: + pid.SetPoint = 1 + time.sleep(0.02) + + feedback_list.append(feedback) + setpoint_list.append(pid.SetPoint) + time_list.append(i) + + time_sm = np.array(time_list) + time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300) + feedback_smooth = spline(time_list, feedback_list, time_smooth) + + plt.plot(time_smooth, feedback_smooth) + plt.plot(time_list, setpoint_list) + plt.xlim((0, L)) + plt.ylim((min(feedback_list)-0.5, max(feedback_list)+0.5)) + plt.xlabel('time (s)') + plt.ylabel('PID (PV)') + plt.title('TEST PID') + + plt.ylim((1-0.5, 1+0.5)) + + plt.grid(True) + plt.show() + +if __name__ == "__main__": + test_pid(1.2, 1, 0.001, L=50) +# test_pid(0.8, L=50) \ No newline at end of file diff --git a/log_piNail.txt b/log_piNail.txt new file mode 100644 index 0000000..22af8b6 --- /dev/null +++ b/log_piNail.txt @@ -0,0 +1,131 @@ +208.40, 530.00, 164.70, 250, 1773211819773 +242.15, 530.00, 299.69, 250, 1773211820978 +239.90, 530.00, 299.82, 250, 1773211822183 +243.95, 530.00, 300.00, 250, 1773211823389 +252.05, 530.00, 299.64, 250, 1773211824594 +260.60, 530.00, 299.82, 250, 1773211825799 +271.85, 530.00, 299.59, 250, 1773211827005 +281.75, 530.00, 299.82, 250, 1773211828210 +299.30, 530.00, 299.55, 250, 1773211829415 +308.75, 530.00, 299.64, 250, 1773211830620 +330.80, 530.00, 299.42, 250, 1773211831825 +342.95, 530.00, 299.46, 250, 1773211833030 +365.90, 530.00, 299.37, 250, 1773211834236 +381.20, 530.00, 299.24, 250, 1773211835441 +398.30, 530.00, 299.46, 250, 1773211836646 +423.50, 530.00, 299.10, 250, 1773211837852 +434.30, 530.00, 299.24, 250, 1773211839056 +451.40, 530.00, 299.42, 250, 1773211840261 +471.65, 530.00, 299.06, 250, 1773211841467 +491.00, 530.00, 299.77, 250, 1773211842672 +512.15, 530.00, 289.08, 250, 1773211843877 +521.60, 530.00, 286.05, 250, 1773211845083 +547.70, 530.00, 253.68, 250, 1773211846288 +565.70, 530.00, 218.06, 200, 1773211847492 +579.65, 530.00, 178.25, 250, 1773211848698 +596.30, 530.00, 124.60, 200, 1773211849908 +613.40, 530.00, 60.11, 200, 1773211851112 +628.70, 530.00, 0.00, 200, 1773211852318 +648.95, 530.00, 0.00, 200, 1773211853523 +654.35, 530.00, 0.27, 200, 1773211854728 +664.70, 530.00, 0.00, 200, 1773211855934 +673.25, 530.00, 0.00, 200, 1773211857139 +681.80, 530.00, 0.00, 200, 1773211858344 +681.80, 530.00, 0.00, 200, 1773211859549 +690.35, 530.00, 0.00, 200, 1773211860754 +684.05, 530.00, 0.00, 200, 1773211861964 +699.80, 530.00, 0.00, 200, 1773211863169 +690.80, 530.00, 0.54, 200, 1773211864374 +690.80, 530.00, 0.09, 200, 1773211865579 +695.75, 530.00, 0.00, 200, 1773211866785 +687.20, 530.00, 0.58, 200, 1773211867993 +684.50, 530.00, 0.54, 200, 1773211869197 +691.25, 530.00, 0.00, 200, 1773211870402 +697.10, 530.00, 0.00, 200, 1773211871607 +687.20, 530.00, 0.04, 200, 1773211872812 +683.15, 530.00, 0.23, 200, 1773211874017 +687.20, 530.00, 0.00, 200, 1773211875222 +682.70, 530.00, 0.49, 200, 1773211876427 +678.65, 530.00, 0.00, 200, 1773211877633 +675.95, 530.00, 0.00, 200, 1773211878838 +869.90, 530.00, 0.00, 200, 1773211880043 +676.40, 530.00, 155.64, 250, 1773211881249 +670.10, 530.00, 76.77, 200, 1773211882453 +677.75, 530.00, 0.00, 200, 1773211883658 +674.15, 530.00, 0.14, 200, 1773211884864 +671.00, 530.00, 0.00, 200, 1773211886069 +673.25, 530.00, 0.00, 200, 1773211887274 +675.50, 530.00, 0.36, 200, 1773211888480 +670.10, 530.00, 0.09, 200, 1773211889685 +667.40, 530.00, 0.00, 200, 1773211890889 +675.05, 530.00, 0.00, 200, 1773211892095 +661.55, 530.00, 0.00, 200, 1773211893300 +657.95, 530.00, 0.23, 200, 1773211894505 +668.30, 530.00, 0.00, 200, 1773211895711 +657.05, 530.00, 0.23, 200, 1773211896916 +650.30, 530.00, 0.32, 200, 1773211898121 +657.05, 530.00, 0.00, 200, 1773211899326 +647.60, 530.00, 0.23, 200, 1773211900531 +640.85, 530.00, 0.23, 200, 1773211901736 +644.00, 530.00, 0.00, 200, 1773211902942 +635.00, 530.00, 0.45, 200, 1773211904147 +630.95, 530.00, 0.18, 200, 1773211905352 +628.70, 530.00, 0.31, 200, 1773211906557 +629.15, 530.00, 0.27, 200, 1773211907762 +622.40, 530.00, 0.23, 200, 1773211908966 +624.65, 530.00, 0.00, 200, 1773211910172 +621.05, 530.00, 0.41, 200, 1773211911377 +615.65, 530.00, 0.14, 200, 1773211912582 +619.70, 530.00, 0.00, 200, 1773211913788 +617.00, 530.00, 0.23, 200, 1773211914993 +611.15, 530.00, 0.14, 200, 1773211916198 +614.75, 530.00, 0.00, 200, 1773211917404 +604.40, 530.00, 123.66, 200, 1773211918608 +610.25, 530.00, 82.34, 200, 1773211919813 +606.65, 530.00, 40.05, 200, 1773211921019 +603.95, 530.00, 0.00, 200, 1773211922224 +611.15, 530.00, 0.36, 200, 1773211923429 +603.05, 530.00, 0.00, 200, 1773211924635 +604.40, 530.00, 0.00, 200, 1773211925840 +608.45, 530.00, 0.45, 200, 1773211927045 +600.80, 530.00, 0.05, 200, 1773211928251 +606.65, 530.00, 0.00, 200, 1773211929456 +609.80, 530.00, 0.45, 200, 1773211930660 +713.30, 530.00, 0.00, 200, 1773211931867 +604.40, 530.00, 66.60, 200, 1773211933071 +612.95, 530.00, 8.39, 200, 1773211934275 +605.30, 530.00, 0.00, 200, 1773211935481 +612.95, 530.00, 0.00, 200, 1773211936686 +606.20, 530.00, 0.40, 200, 1773211937890 +598.55, 530.00, 0.00, 200, 1773211939096 +605.75, 530.00, 0.00, 200, 1773211940300 +617.00, 530.00, 0.00, 200, 1773211941504 +602.15, 530.00, 0.99, 200, 1773211942708 +607.10, 530.00, 0.04, 200, 1773211943913 +608.00, 530.00, 0.00, 200, 1773211945117 +603.95, 530.00, 0.13, 200, 1773211946322 +608.00, 530.00, 0.00, 200, 1773211947527 +598.10, 530.00, 0.36, 200, 1773211948731 +619.70, 530.00, 0.00, 200, 1773211949937 +606.65, 530.00, 0.00, 200, 1773211951141 +596.30, 530.00, 0.00, 200, 1773211952345 +611.60, 530.00, 0.00, 200, 1773211953550 +603.05, 530.00, 0.18, 200, 1773211954754 +598.10, 530.00, 0.09, 200, 1773211955959 +602.60, 530.00, 0.00, 200, 1773211957165 +597.65, 530.00, 110.65, 200, 1773211958371 +594.05, 530.00, 64.84, 200, 1773211959576 +599.90, 530.00, 17.54, 200, 1773211960783 +592.25, 530.00, 0.00, 200, 1773211961989 +595.85, 530.00, 0.00, 200, 1773211963195 +580.10, 530.00, 9.75, 200, 1773211964401 +584.60, 530.00, 0.40, 200, 1773211965606 +591.35, 530.00, 0.00, 200, 1773211966810 +589.55, 530.00, 0.45, 200, 1773211968016 +586.85, 530.00, 0.14, 200, 1773211969222 +593.15, 530.00, 0.00, 200, 1773211970427 +582.80, 530.00, 0.00, 200, 1773211971633 +582.80, 530.00, 0.00, 200, 1773211972838 +589.10, 530.00, 0.00, 200, 1773211974043 +580.10, 530.00, 0.49, 200, 1773211975249 +578.75, 530.00, 0.00, 200, 1773211976453 diff --git a/logging_piNail.py b/logging_piNail.py new file mode 100644 index 0000000..c44b6d3 --- /dev/null +++ b/logging_piNail.py @@ -0,0 +1,87 @@ +# Can enable debug output by uncommenting: +#import logging +#logging.basicConfig(level=logging.DEBUG) + +import time + +import Adafruit_GPIO.SPI as SPI +import MAX6675.MAX6675 as MAX6675 + +from simple_pid import PID +kP =100 +kI = 0 +kD = .0 +setpoint = 675 +temp = -1000 +output = -1 +current_milli_time = -1 +pid = PID(kP, kI, kD, setpoint) +loop_size = int(1000) +sleep_time = 0.3 +counter = 0 +##pid.sample_time = .3 # update every 0.5 seconds +pid.proportional_on_measurement = True +pid.output_limits = (0, loop_size) # output value will be between 0 and 5000 +log_directory = "./log_piNail.txt" +f = open(log_directory, 'w+') #Create a new log file, overwritting the previous one +f.close() + + +# Raspberry Pi software SPI configuration. +CLK = 3 +CS = 14 +DO = 4 +sensor = MAX6675.MAX6675(CLK, CS, DO) + +relayPin = 2 + +import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library +GPIO.setwarnings(False) # Ignore warning for now +GPIO.setmode(GPIO.BCM) # Use physical pin numbering +GPIO.setup(relayPin, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off) + +# Define a function to convert celsius to fahrenheit. +def c_to_f(c): + return c * 9.0 / 5.0 + 32.0 + +def logToFile(directory): + f = open(directory, "a+") + f.write("{0:.2f}, {1:.2f}, {2:.2f}, {3}, {4} \n".format(temp, setpoint, output/10, GPIO.input(relayPin) * 50+ 200, current_milli_time)) + f.close() + +def loadPID_params(directory): + PID_values = open(directory, 'r').read() + values = PID_values.split("\n") + return float(values[0]), float(values[1]), float(values[2]), float(values[3]), int(values[4]), int(values[5]), int(values[6]) + + +print('Press Ctrl-C to quit.') +try: + while True: + kP, kI, kD, sleep_time, loop_size, setpoint, log_resolution = loadPID_params("./P_I_D_values.txt") + pid.output_limits = (0, loop_size) + pid.setpoint = setpoint + pid.tunings = (kP, kI, kD) + temp = c_to_f(sensor.readTempC()) + start_milli_time = int(round(time.time() * 1000)) + current_milli_time = int(round(time.time() * 1000)) + current_loop_end = start_milli_time + loop_size + + while current_milli_time < current_loop_end: + temp = c_to_f(sensor.readTempC()) + output = pid(temp) + if current_milli_time < start_milli_time + output: + GPIO.output(relayPin, GPIO.HIGH) + else: + GPIO.output(relayPin, GPIO.LOW) + current_milli_time = int(round(time.time() * 1000)) + print("Temp: {0:06.2f}, PWR: {1:07.2f}/{2}, {3}, {4}, {5}, {6}".format(temp, output, loop_size, GPIO.input(relayPin), pid.Kp, pid.Ki, pid.Kd)) + if counter > log_resolution: + logToFile(log_directory) + counter = 0 + else: + counter = counter + 1 + time.sleep(sleep_time) +except: + GPIO.output(relayPin, GPIO.LOW) + print("Exiting properly") diff --git a/piNail.py b/piNail.py new file mode 100644 index 0000000..acab472 --- /dev/null +++ b/piNail.py @@ -0,0 +1,58 @@ +# Can enable debug output by uncommenting: +#import logging +#logging.basicConfig(level=logging.DEBUG) + +import time + +import Adafruit_GPIO.SPI as SPI +import MAX6675.MAX6675 as MAX6675 + +from simple_pid import PID +kP =150 +kI = 5 +kD = 1 + +setpoint = 580 +pid = PID(kP, kI, kD, setpoint) +loop_size = int(3000) +pid.output_limits = (0, loop_size) # output value will be between 0 and 5000 + + +# Raspberry Pi software SPI configuration. +CLK = 3 +CS = 14 +DO = 4 +sensor = MAX6675.MAX6675(CLK, CS, DO) + +relayPin = 2 + +import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library +GPIO.setwarnings(False) # Ignore warning for now +GPIO.setmode(GPIO.BCM) # Use physical pin numbering +GPIO.setup(relayPin, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off) + +# Define a function to convert celsius to fahrenheit. +def c_to_f(c): + return c * 9.0 / 5.0 + 32.0 + +print('Press Ctrl-C to quit.') +try: + while True: + temp = c_to_f(sensor.readTempC()) + start_milli_time = int(round(time.time() * 1000)) + current_milli_time = int(round(time.time() * 1000)) + current_loop_end = start_milli_time + loop_size + + while current_milli_time < current_loop_end: + temp = c_to_f(sensor.readTempC()) + output = pid(temp) + if current_milli_time < start_milli_time + output: + GPIO.output(relayPin, GPIO.HIGH) + else: + GPIO.output(relayPin, GPIO.LOW) + current_milli_time = int(round(time.time() * 1000)) + time.sleep(0.3) + print("Temp: {0:.2f}, PWR: {1:.2f}, {2}".format(temp, output, GPIO.input(relayPin))) +except: + GPIO.output(relayPin, GPIO.LOW) + print("Exiting properly") diff --git a/piNail2/app.py b/piNail2/app.py new file mode 100644 index 0000000..dd2011d --- /dev/null +++ b/piNail2/app.py @@ -0,0 +1,331 @@ +""" +piNail2 — Flask Web Application + +Main entry point. Runs the Flask web server and initializes the PID controller. +Provides REST API endpoints and serves the single-page dashboard. + +Usage: + python3 app.py + python3 app.py --config /path/to/config.json +""" + +import sys +import os +import signal +import atexit +import logging +import argparse +import json +import time +from datetime import datetime + +from flask import Flask, render_template, jsonify, request + +from config import Config +from thermocouple import Thermocouple +from pid_controller import PIDController + +# --------------------------------------------------------------------------- +# Logging setup +# --------------------------------------------------------------------------- +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", + handlers=[ + logging.StreamHandler(sys.stdout), + ] +) +log = logging.getLogger("piNail2") +APP_INSTANCE_ID = str(int(time.time())) +APP_VERSION = "v2.1.0" + +# --------------------------------------------------------------------------- +# Flask app +# --------------------------------------------------------------------------- +app = Flask(__name__) + +# These are set in main() before the app starts +config = None # type: Config +controller = None # type: PIDController +tc = None # type: Thermocouple + +# --------------------------------------------------------------------------- +# Routes — Pages +# --------------------------------------------------------------------------- + +@app.route("/") +def index(): + """Serve the main dashboard.""" + return render_template( + "index.html", + app_version=APP_VERSION, + copyright_year=datetime.now().year, + ) + + +# --------------------------------------------------------------------------- +# Routes — API +# --------------------------------------------------------------------------- + +@app.route("/api/status") +def api_status(): + """Return current controller state.""" + status = controller.status + status["instance_id"] = APP_INSTANCE_ID + status["thermocouple"] = tc.stats + status["presets"] = config.get("presets") + status["config"] = { + "loop_size_ms": config.get("control", "loop_size_ms"), + "sleep_time": config.get("control", "sleep_time"), + "safety": config.get("safety"), + } + return jsonify(status) + + +@app.route("/api/heartbeat") +def api_heartbeat(): + """Lightweight health endpoint for frontend reconnect logic.""" + return jsonify({ + "ok": True, + "instance_id": APP_INSTANCE_ID, + "ts": time.time(), + "controller_alive": controller.is_alive, + "watchdog_ok": controller.watchdog_ok, + }) + + +@app.route("/api/history") +def api_history(): + """Return recent temperature history for charting.""" + since = request.args.get("since", 0, type=float) + if since > 0: + data = controller.get_history_since(since) + else: + data = controller.history + return jsonify(data) + + +@app.route("/api/power", methods=["POST"]) +def api_power(): + """Toggle controller on/off.""" + body = request.get_json(force=True, silent=True) or {} + enable = body.get("enabled") + + if enable is None: + # Toggle + enable = not controller.status["enabled"] + + if enable: + controller.start() + else: + controller.stop() + + return jsonify({"enabled": enable, "ok": True}) + + +@app.route("/api/setpoint", methods=["POST"]) +def api_setpoint(): + """Change the target temperature.""" + body = request.get_json(force=True, silent=True) or {} + value = body.get("setpoint") + if value is None: + return jsonify({"error": "Missing 'setpoint' field"}), 400 + + try: + value = float(value) + except (TypeError, ValueError): + return jsonify({"error": "Invalid setpoint value"}), 400 + + safety = config.get("safety") + if value > safety["max_temp_f"]: + return jsonify({"error": "Setpoint {} exceeds max {}F".format(value, safety['max_temp_f'])}), 400 + if value < safety["min_temp_f"]: + return jsonify({"error": "Setpoint {} below min {}F".format(value, safety['min_temp_f'])}), 400 + + controller.set_setpoint(value) + return jsonify({"setpoint": value, "ok": True}) + + +@app.route("/api/pid", methods=["POST"]) +def api_pid(): + """Update PID tuning parameters.""" + body = request.get_json(force=True, silent=True) or {} + + kp = body.get("kP") + ki = body.get("kI") + kd = body.get("kD") + p_on_m = body.get("proportional_on_measurement") + p_mode = body.get("proportional_mode") + + if kp is None or ki is None or kd is None: + return jsonify({"error": "Missing kP, kI, or kD"}), 400 + + try: + kp, ki, kd = float(kp), float(ki), float(kd) + except (TypeError, ValueError): + return jsonify({"error": "Invalid PID values"}), 400 + + controller.set_pid_tuning(kp, ki, kd, p_on_m, p_mode) + mode_out = "measurement" if controller.status["pid"]["proportional_on_measurement"] else "error" + return jsonify({ + "kP": kp, + "kI": ki, + "kD": kd, + "proportional_on_measurement": controller.status["pid"]["proportional_on_measurement"], + "proportional_mode": mode_out, + "ok": True, + }) + + +@app.route("/api/preset/", methods=["POST"]) +def api_preset(name): + """Apply a named temperature preset.""" + presets = config.get("presets") + if name not in presets: + return jsonify({"error": "Unknown preset '{}'".format(name), "available": list(presets.keys())}), 404 + + value = presets[name] + controller.set_setpoint(value) + return jsonify({"preset": name, "setpoint": value, "ok": True}) + + +@app.route("/api/presets", methods=["GET"]) +def api_presets(): + """List all presets.""" + return jsonify(config.get("presets")) + + +@app.route("/api/presets", methods=["POST"]) +def api_presets_update(): + """Add or update a preset.""" + body = request.get_json(force=True, silent=True) or {} + name = body.get("name") + value = body.get("setpoint") + if not name or value is None: + return jsonify({"error": "Missing 'name' or 'setpoint'"}), 400 + try: + value = float(value) + except (TypeError, ValueError): + return jsonify({"error": "Invalid setpoint value"}), 400 + + presets = config.get("presets") + presets[name] = value + config.update_section("presets", presets) + return jsonify({"ok": True, "presets": presets}) + + +@app.route("/api/presets/", methods=["DELETE"]) +def api_preset_delete(name): + """Delete a preset.""" + presets = config.get("presets") + if name not in presets: + return jsonify({"error": "Unknown preset '{}'".format(name)}), 404 + del presets[name] + # Overwrite entire presets section + config._data["presets"] = presets + config.save() + return jsonify({"ok": True, "presets": presets}) + + +@app.route("/api/config", methods=["GET"]) +def api_config(): + """Return full config (read-only view).""" + return jsonify(config.data) + + +@app.route("/api/pid/reset", methods=["POST"]) +def api_pid_reset(): + """Reset PID controller internals (clears integral windup).""" + controller._pid.reset() + return jsonify({"ok": True, "message": "PID reset"}) + + +@app.route("/api/autotune", methods=["GET"]) +def api_autotune_status(): + """Return current autotune state.""" + return jsonify(controller.autotune_status) + + +@app.route("/api/autotune/start", methods=["POST"]) +def api_autotune_start(): + """Start relay-based PID autotune.""" + if not controller.status.get("enabled"): + controller.start() + time.sleep(0.2) + body = request.get_json(force=True, silent=True) or {} + setpoint = body.get("setpoint") + hysteresis = body.get("hysteresis") + cycles = body.get("cycles") + controller.start_autotune(setpoint=setpoint, hysteresis=hysteresis, cycles=cycles) + return jsonify({"ok": True, "autotune": controller.autotune_status}) + + +@app.route("/api/autotune/stop", methods=["POST"]) +def api_autotune_stop(): + """Stop PID autotune.""" + controller.stop_autotune("Autotune stopped by user") + return jsonify({"ok": True, "autotune": controller.autotune_status}) + + +@app.route("/api/safety/reset", methods=["POST"]) +def api_safety_reset(): + """Reset safety trip (clears the safety flag so controller can be restarted).""" + controller._safety_tripped = False + controller._safety_reason = "" + return jsonify({"ok": True}) + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def shutdown_handler(*args): + """Handle SIGTERM/SIGINT gracefully.""" + log.info("Shutdown signal received") + if controller: + controller.cleanup() + sys.exit(0) + + +def main(): + global config, controller, tc + + parser = argparse.ArgumentParser(description="piNail2 — E-Nail Temperature Controller") + parser.add_argument("--config", default="config.json", help="Path to config file") + args = parser.parse_args() + + # Load config + config = Config(args.config) + log.info("Configuration loaded from %s", args.config) + + # Initialize thermocouple + gpio_cfg = config.get("gpio") + safety_cfg = config.get("safety") + tc = Thermocouple( + clk=gpio_cfg["clk"], + cs=gpio_cfg["cs"], + do=gpio_cfg["do"], + spike_threshold=safety_cfg["spike_threshold_f"] + ) + + # Initialize PID controller + controller = PIDController(config, tc) + + # Register cleanup + signal.signal(signal.SIGTERM, shutdown_handler) + signal.signal(signal.SIGINT, shutdown_handler) + atexit.register(controller.cleanup) + + # Start Flask + web_cfg = config.get("web") + log.info("Starting web server on %s:%d", web_cfg["host"], web_cfg["port"]) + app.run( + host=web_cfg["host"], + port=web_cfg["port"], + debug=False, + threaded=True + ) + + +if __name__ == "__main__": + main() diff --git a/piNail2/config.json b/piNail2/config.json new file mode 100644 index 0000000..c6a3281 --- /dev/null +++ b/piNail2/config.json @@ -0,0 +1,46 @@ +{ + "pid": { + "kP": 10.0, + "kI": 5.0, + "kD": 1.0, + "proportional_on_measurement": false + }, + "control": { + "setpoint": 530, + "loop_size_ms": 3000, + "sleep_time": 0.4, + "enabled": false + }, + "safety": { + "max_temp_f": 800, + "spike_threshold_f": 50.0, + "idle_shutoff_minutes": 30, + "watchdog_timeout_s": 10, + "min_temp_f": 0 + }, + "gpio": { + "relay_pin": 2, + "clk": 3, + "cs": 14, + "do": 4 + }, + "logging": { + "log_resolution": 1, + "log_directory": "./logs", + "max_log_lines": 10000 + }, + "presets": { + "Low Temp": 450, + "Medium": 530, + "High": 650 + }, + "web": { + "host": "0.0.0.0", + "port": 5000, + "update_interval_ms": 500 + }, + "autotune": { + "hysteresis_f": 8.0, + "cycles": 4 + } +} diff --git a/piNail2/config.py b/piNail2/config.py new file mode 100644 index 0000000..bfb96e7 --- /dev/null +++ b/piNail2/config.py @@ -0,0 +1,145 @@ +""" +piNail2 Configuration Management + +JSON-based config with named fields, load/save, defaults, and hot-reload support. +Replaces the old positional P_I_D_values.txt format. +""" + +import json +import os +import logging +import copy + +log = logging.getLogger(__name__) + +DEFAULT_CONFIG = { + "pid": { + "kP": 10.0, + "kI": 5.0, + "kD": 1.0, + "proportional_on_measurement": False + }, + "control": { + "setpoint": 530, + "loop_size_ms": 3000, + "sleep_time": 0.4, + "enabled": False + }, + "safety": { + "max_temp_f": 800, + "spike_threshold_f": 50.0, + "idle_shutoff_minutes": 30, + "watchdog_timeout_s": 10, + "min_temp_f": 0 + }, + "gpio": { + "relay_pin": 2, + "clk": 3, + "cs": 14, + "do": 4 + }, + "logging": { + "log_resolution": 1, + "log_directory": "./logs", + "max_log_lines": 10000 + }, + "presets": { + "Low Temp": 450, + "Medium": 530, + "High": 650 + }, + "web": { + "host": "0.0.0.0", + "port": 5000, + "update_interval_ms": 500 + }, + "autotune": { + "hysteresis_f": 8.0, + "cycles": 4 + } +} + + +class Config: + """Thread-safe configuration manager with file persistence.""" + + def __init__(self, config_path="config.json"): + self._path = config_path + self._data = copy.deepcopy(DEFAULT_CONFIG) + self._mtime = 0 + self.load() + + def load(self): + """Load config from disk, merging with defaults for any missing keys.""" + if not os.path.exists(self._path): + log.info("No config file found at %s, creating with defaults", self._path) + self.save() + return + + try: + with open(self._path, 'r') as f: + user_config = json.load(f) + self._data = self._deep_merge(copy.deepcopy(DEFAULT_CONFIG), user_config) + self._mtime = os.path.getmtime(self._path) + log.info("Config loaded from %s", self._path) + except (json.JSONDecodeError, IOError) as e: + log.error("Failed to load config from %s: %s. Using defaults.", self._path, e) + self._data = copy.deepcopy(DEFAULT_CONFIG) + + def save(self): + """Write current config to disk.""" + try: + with open(self._path, 'w') as f: + json.dump(self._data, f, indent=2) + self._mtime = os.path.getmtime(self._path) + log.info("Config saved to %s", self._path) + except IOError as e: + log.error("Failed to save config to %s: %s", self._path, e) + + def reload_if_changed(self): + """Reload config from disk if the file has been modified externally.""" + try: + current_mtime = os.path.getmtime(self._path) + if current_mtime > self._mtime: + log.info("Config file changed on disk, reloading") + self.load() + return True + except OSError: + pass + return False + + def get(self, section, key=None): + """Get a config value. If key is None, returns the entire section.""" + if key is None: + return copy.deepcopy(self._data.get(section, {})) + return self._data.get(section, {}).get(key) + + def set(self, section, key, value): + """Set a config value and save to disk.""" + if section not in self._data: + self._data[section] = {} + self._data[section][key] = value + self.save() + + def update_section(self, section, values): + """Update multiple keys in a section and save to disk.""" + if section not in self._data: + self._data[section] = {} + self._data[section].update(values) + self.save() + + @property + def data(self): + """Return a deep copy of the full config dict.""" + return copy.deepcopy(self._data) + + @staticmethod + def _deep_merge(base, override): + """Recursively merge override into base. Override values win.""" + result = base.copy() + for key, value in override.items(): + if key in result and isinstance(result[key], dict) and isinstance(value, dict): + result[key] = Config._deep_merge(result[key], value) + else: + result[key] = value + return result diff --git a/piNail2/deploy.sh b/piNail2/deploy.sh new file mode 100755 index 0000000..b48898a --- /dev/null +++ b/piNail2/deploy.sh @@ -0,0 +1,120 @@ +#!/bin/bash +# +# piNail2 Deploy Script +# +# Deploys piNail2 to the Raspberry Pi. Steps: +# 1. Copy piNail2 files to ~/piNail2/ on the Pi +# 2. Copy the MAX6675 library from the old project +# 3. Install pip dependencies (system-wide for Python 3.5) +# 4. Optionally install and enable the systemd service +# +# Usage: ./deploy.sh [--service] +# --service Also install and enable the systemd service +# + +set -euo pipefail + +PI_HOST="pinail" # SSH alias from ~/.ssh/config +PI_USER="pi" +REMOTE_DIR="/home/${PI_USER}/piNail2" +LOCAL_DIR="$(cd "$(dirname "$0")" && pwd)" +INSTALL_SERVICE=false + +if [[ "${1:-}" == "--service" ]]; then + INSTALL_SERVICE=true +fi + +echo "=== piNail2 Deployment ===" +echo "Target: ${PI_HOST} -> ${REMOTE_DIR}" +echo "" + +# ------------------------------------------------------------------- +# Step 1: Copy project files +# ------------------------------------------------------------------- +echo "--- Step 1: Copying piNail2 to Pi ---" + +ssh ${PI_HOST} "mkdir -p ${REMOTE_DIR}/static ${REMOTE_DIR}/templates ${REMOTE_DIR}/logs" + +# Copy Python source files +scp -q "${LOCAL_DIR}/app.py" \ + "${LOCAL_DIR}/config.py" \ + "${LOCAL_DIR}/thermocouple.py" \ + "${LOCAL_DIR}/pid_controller.py" \ + "${LOCAL_DIR}/config.json" \ + "${LOCAL_DIR}/requirements.txt" \ + "${LOCAL_DIR}/pinail.service" \ + "${PI_HOST}:${REMOTE_DIR}/" + +# Copy static + templates +scp -q "${LOCAL_DIR}/static/app.js" \ + "${LOCAL_DIR}/static/style.css" \ + "${PI_HOST}:${REMOTE_DIR}/static/" + +scp -q "${LOCAL_DIR}/templates/index.html" \ + "${PI_HOST}:${REMOTE_DIR}/templates/" + +echo "Files copied." +echo "" + +# ------------------------------------------------------------------- +# Step 2: Copy MAX6675 library from old project +# ------------------------------------------------------------------- +echo "--- Step 2: Copying MAX6675 library ---" + +ssh ${PI_HOST} bash -s <<'REMOTE_SCRIPT' +# Copy the MAX6675 Python package from the old piNail project +if [ -d /home/pi/piNail/MAX6675-master/MAX6675 ]; then + cp -r /home/pi/piNail/MAX6675-master/MAX6675 /home/pi/piNail2/MAX6675 + echo "MAX6675 library copied from old project" +else + echo "WARNING: MAX6675 library not found in old project!" +fi +REMOTE_SCRIPT + +echo "" + +# ------------------------------------------------------------------- +# Step 3: Install pip dependencies +# ------------------------------------------------------------------- +echo "--- Step 3: Installing dependencies ---" + +ssh ${PI_HOST} bash -s <<'REMOTE_SCRIPT' +cd /home/pi/piNail2 + +echo "Installing dependencies with pip3..." +pip3 install --user -r requirements.txt 2>&1 | tail -10 + +echo "" +echo "Key packages:" +pip3 show Flask simple-pid RPi.GPIO Adafruit-GPIO 2>/dev/null | grep -E '^(Name|Version):' +REMOTE_SCRIPT + +echo "" + +# ------------------------------------------------------------------- +# Step 4: Systemd service (optional) +# ------------------------------------------------------------------- +if $INSTALL_SERVICE; then + echo "--- Step 4: Installing systemd service ---" + + ssh ${PI_HOST} bash -s <<'REMOTE_SCRIPT' +sudo cp /home/pi/piNail2/pinail.service /etc/systemd/system/pinail2.service +sudo systemctl daemon-reload +sudo systemctl enable pinail2.service +echo "Service installed and enabled (pinail2.service)" +echo "Start with: sudo systemctl start pinail2" +echo "Logs with: sudo journalctl -u pinail2 -f" +REMOTE_SCRIPT +else + echo "--- Step 4: Skipping systemd service (use --service flag to install) ---" +fi + +echo "" +echo "=== Deployment complete! ===" +echo "" +echo "To run manually:" +echo " ssh ${PI_HOST}" +echo " cd ~/piNail2" +echo " python3 app.py" +echo "" +echo "Web UI will be at: http://192.168.0.159:5000" diff --git a/piNail2/pid_controller.py b/piNail2/pid_controller.py new file mode 100644 index 0000000..c24a721 --- /dev/null +++ b/piNail2/pid_controller.py @@ -0,0 +1,575 @@ +""" +piNail2 PID Controller + +Runs the PID control loop in a background thread. Controls a relay via GPIO +using software PWM (duty cycle within a time window) to maintain a target +temperature on an e-nail heating coil. + +Safety features: +- Hard max temperature cutoff +- Thermocouple disconnect detection -> relay OFF +- Idle auto-shutoff after configurable timeout +- Watchdog: detects if control loop stalls +- Proper GPIO cleanup on shutdown +""" + +import time +import threading +import logging +import os +import csv +import math +from datetime import datetime + +log = logging.getLogger(__name__) + + +class PIDController: + """ + Threaded PID temperature controller for e-nail heating. + + The control loop runs in a background daemon thread. It reads temperature + from a Thermocouple object, computes PID output, and drives a relay GPIO + pin using software PWM (time-proportional control within each loop cycle). + + Thread-safe properties expose current state to the Flask web server. + """ + + def __init__(self, config, thermocouple): + """ + Args: + config: Config instance + thermocouple: Thermocouple instance + """ + self._config = config + self._tc = thermocouple + self._lock = threading.Lock() + + # State + self._enabled = False + self._temp = 0.0 + self._setpoint = config.get("control", "setpoint") + self._output = 0.0 + self._relay_on = False + self._loop_count = 0 + self._start_time = None + self._last_loop_time = None + self._idle_since = None # timestamp when temp first reached setpoint vicinity + self._safety_tripped = False + self._safety_reason = "" + self._thread = None + self._stop_event = threading.Event() + + # Autotune state + self._autotune_active = False + self._autotune_target = self._setpoint + self._autotune_hysteresis = config.get("autotune", "hysteresis_f") + self._autotune_cycles = config.get("autotune", "cycles") + self._autotune_heating = False + self._autotune_phase_started = None + self._autotune_phase_extreme = None + self._autotune_high_peaks = [] + self._autotune_low_peaks = [] + self._autotune_last_result = None + self._autotune_message = "" + + # PID instance + from simple_pid import PID + pid_cfg = config.get("pid") + self._pid = PID( + pid_cfg["kP"], + pid_cfg["kI"], + pid_cfg["kD"], + setpoint=self._setpoint + ) + self._pid.proportional_on_measurement = pid_cfg.get("proportional_on_measurement", True) + loop_size = config.get("control", "loop_size_ms") + self._pid.output_limits = (0, loop_size) + + # GPIO setup + self._relay_pin = config.get("gpio", "relay_pin") + self._gpio = None + try: + import RPi.GPIO as GPIO + self._gpio = GPIO + GPIO.setwarnings(False) + GPIO.setmode(GPIO.BCM) + GPIO.setup(self._relay_pin, GPIO.OUT, initial=GPIO.LOW) + log.info("GPIO initialized, relay pin %d set LOW", self._relay_pin) + except Exception as e: + log.error("Failed to initialize GPIO: %s", e) + + # Logging setup + self._log_dir = config.get("logging", "log_directory") + os.makedirs(self._log_dir, exist_ok=True) + self._log_file = None + self._log_writer = None + self._log_counter = 0 + self._history = [] # Recent data points for the web UI + self._history_max = 1000 + self._init_log_file() + + def _init_log_file(self): + """Create a new CSV log file with a timestamp in the filename.""" + try: + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + path = os.path.join(self._log_dir, "pinail_{}.csv".format(timestamp)) + self._log_file = open(path, 'w', newline='') + self._log_writer = csv.writer(self._log_file) + self._log_writer.writerow([ + "timestamp", "temp_f", "setpoint_f", "output", "relay", + "kP", "kI", "kD", "loop_size_ms" + ]) + log.info("Log file created: %s", path) + except Exception as e: + log.error("Failed to create log file: %s", e) + + def start(self): + """Enable the controller and start the background control loop.""" + with self._lock: + if self._thread is not None and self._thread.is_alive(): + log.warning("Controller is already running") + return + + self._enabled = True + self._safety_tripped = False + self._safety_reason = "" + self._start_time = time.monotonic() + self._idle_since = None + self._stop_event.clear() + self._pid.reset() + + self._thread = threading.Thread(target=self._control_loop, daemon=True, name="pid-loop") + self._thread.start() + log.info("PID controller started (setpoint=%.0fF)", self._setpoint) + + def stop(self): + """Stop the controller and turn off the relay.""" + log.info("Stopping PID controller") + self._stop_event.set() + with self._lock: + self._enabled = False + self._autotune_active = False + self._relay_off() + if self._thread is not None: + self._thread.join(timeout=5) + log.info("PID controller stopped") + + def _relay_off(self): + """Ensure relay is OFF.""" + if self._gpio is not None: + try: + self._gpio.output(self._relay_pin, self._gpio.LOW) + except Exception as e: + log.error("Failed to turn relay off: %s", e) + self._relay_on = False + + def _relay_set(self, on): + """Set relay state.""" + if self._gpio is not None: + try: + self._gpio.output( + self._relay_pin, + self._gpio.HIGH if on else self._gpio.LOW + ) + except Exception as e: + log.error("Failed to set relay: %s", e) + self._relay_on = on + + def _reset_autotune_state(self): + self._autotune_heating = False + self._autotune_phase_started = None + self._autotune_phase_extreme = None + self._autotune_high_peaks = [] + self._autotune_low_peaks = [] + + def start_autotune(self, setpoint=None, hysteresis=None, cycles=None): + with self._lock: + if setpoint is not None: + self._setpoint = float(setpoint) + self._config.set("control", "setpoint", float(setpoint)) + self._autotune_target = self._setpoint + if hysteresis is not None: + self._autotune_hysteresis = float(hysteresis) + if cycles is not None: + self._autotune_cycles = int(cycles) + self._autotune_active = True + self._autotune_message = "Autotune running" + self._autotune_last_result = None + self._reset_autotune_state() + self._pid.reset() + log.info( + "Autotune started target=%.1fF hysteresis=%.1f cycles=%d", + self._autotune_target, + self._autotune_hysteresis, + self._autotune_cycles, + ) + + def stop_autotune(self, message="Autotune stopped"): + with self._lock: + self._autotune_active = False + self._autotune_message = message + self._relay_off() + + def _update_autotune(self, temp, loop_size): + target = self._autotune_target + h = self._autotune_hysteresis + now = time.monotonic() + + if self._autotune_phase_started is None: + self._autotune_phase_started = now + self._autotune_phase_extreme = temp + self._autotune_heating = temp < target + + if self._autotune_heating: + if self._autotune_phase_extreme is None or temp > self._autotune_phase_extreme: + self._autotune_phase_extreme = temp + if temp >= target + h: + self._autotune_high_peaks.append((now, self._autotune_phase_extreme)) + self._autotune_heating = False + self._autotune_phase_started = now + self._autotune_phase_extreme = temp + else: + if self._autotune_phase_extreme is None or temp < self._autotune_phase_extreme: + self._autotune_phase_extreme = temp + if temp <= target - h: + self._autotune_low_peaks.append((now, self._autotune_phase_extreme)) + self._autotune_heating = True + self._autotune_phase_started = now + self._autotune_phase_extreme = temp + + highs = len(self._autotune_high_peaks) + lows = len(self._autotune_low_peaks) + if min(highs, lows) >= self._autotune_cycles and highs >= 2: + high_vals = [v for _, v in self._autotune_high_peaks[-self._autotune_cycles:]] + low_vals = [v for _, v in self._autotune_low_peaks[-self._autotune_cycles:]] + amp = (sum(high_vals) / float(len(high_vals)) - sum(low_vals) / float(len(low_vals))) / 2.0 + if amp <= 0: + self.stop_autotune("Autotune failed: invalid oscillation amplitude") + return 0.0 + + high_times = [t for t, _ in self._autotune_high_peaks[-self._autotune_cycles:]] + periods = [] + for i in range(1, len(high_times)): + periods.append(high_times[i] - high_times[i - 1]) + if not periods: + self.stop_autotune("Autotune failed: not enough periods") + return 0.0 + + pu = sum(periods) / float(len(periods)) + if pu <= 0: + self.stop_autotune("Autotune failed: invalid period") + return 0.0 + + d = loop_size / 2.0 + ku = (4.0 * d) / (math.pi * amp) + + kp = 0.6 * ku + ki = (1.2 * ku) / pu + kd = 0.075 * ku * pu + + # Safety clamp for aggressive/unstable autotune outputs. + kp = max(0.0, min(kp, 300.0)) + ki = max(0.0, min(ki, 50.0)) + kd = max(0.0, min(kd, 500.0)) + + self._pid.tunings = (kp, ki, kd) + self._pid.reset() + self._config.update_section("pid", { + "kP": round(kp, 4), + "kI": round(ki, 4), + "kD": round(kd, 4), + }) + + self._autotune_last_result = { + "kP": round(kp, 4), + "kI": round(ki, 4), + "kD": round(kd, 4), + "Ku": round(ku, 4), + "Pu": round(pu, 4), + "amplitude": round(amp, 4), + } + self.stop_autotune("Autotune complete") + log.info("Autotune complete: %s", self._autotune_last_result) + return 0.0 + + return float(loop_size if self._autotune_heating else 0.0) + + def _control_loop(self): + """ + Main PID control loop. Runs in a background thread. + + Each iteration is one "loop cycle" of loop_size_ms milliseconds. + Within each cycle, the relay is ON for a proportion of time equal to + the PID output, implementing time-proportional software PWM. + """ + log.info("Control loop thread started") + + try: + while not self._stop_event.is_set(): + # Reload config if file changed + self._config.reload_if_changed() + + # Apply current PID tuning + pid_cfg = self._config.get("pid") + self._pid.tunings = (pid_cfg["kP"], pid_cfg["kI"], pid_cfg["kD"]) + self._pid.proportional_on_measurement = pid_cfg.get( + "proportional_on_measurement", True + ) + + control_cfg = self._config.get("control") + loop_size = control_cfg["loop_size_ms"] + sleep_time = control_cfg["sleep_time"] + log_resolution = self._config.get("logging", "log_resolution") + + self._pid.output_limits = (0, loop_size) + + with self._lock: + self._pid.setpoint = self._setpoint + + # Read temperature + temp = self._tc.read() + if temp is None: + log.error("Thermocouple read returned None, disabling for safety") + self._trip_safety("Thermocouple disconnected") + break + + with self._lock: + self._temp = temp + + # Safety checks + safety = self._config.get("safety") + + if temp > safety["max_temp_f"]: + self._trip_safety("Temperature {:.0f}F exceeds max {}F".format(temp, safety['max_temp_f'])) + break + + if not self._tc.is_connected: + self._trip_safety("Thermocouple disconnected") + break + + # Idle shutoff check + idle_minutes = safety.get("idle_shutoff_minutes", 0) + if idle_minutes > 0: + near_setpoint = abs(temp - self._setpoint) < 20 + if near_setpoint: + if self._idle_since is None: + self._idle_since = time.monotonic() + elif (time.monotonic() - self._idle_since) > (idle_minutes * 60): + self._trip_safety( + "Idle shutoff: at setpoint for {} minutes".format(idle_minutes) + ) + break + else: + self._idle_since = None + + # PID compute and software PWM cycle + start_ms = time.monotonic() * 1000 + end_ms = start_ms + loop_size + + while time.monotonic() * 1000 < end_ms: + if self._stop_event.is_set(): + break + + temp = self._tc.read() + if temp is not None: + with self._lock: + self._temp = temp + + if self._autotune_active: + output = self._update_autotune(temp, loop_size) + else: + output = self._pid(temp) + with self._lock: + self._output = output + + # Software PWM: relay ON for first `output` ms of the cycle + elapsed_ms = time.monotonic() * 1000 - start_ms + should_be_on = elapsed_ms < output + self._relay_set(should_be_on) + + # Logging + self._log_counter += 1 + if self._log_counter >= log_resolution: + self._log_data_point(temp, output) + self._log_counter = 0 + + with self._lock: + self._last_loop_time = time.monotonic() + self._loop_count += 1 + + time.sleep(sleep_time) + + except Exception as e: + log.exception("Control loop crashed: %s", e) + self._trip_safety("Control loop error: {}".format(e)) + finally: + self._relay_off() + log.info("Control loop thread exiting, relay OFF") + + def _trip_safety(self, reason): + """Trip safety shutdown.""" + log.warning("SAFETY TRIP: %s", reason) + with self._lock: + self._safety_tripped = True + self._safety_reason = reason + self._enabled = False + self._relay_off() + + def _log_data_point(self, temp, output): + """Write a data point to the CSV log and in-memory history.""" + now = time.time() + row = [ + "{:.3f}".format(now), + "{:.2f}".format(temp), + "{:.2f}".format(self._setpoint), + "{:.2f}".format(output), + 1 if self._relay_on else 0, + "{:.4f}".format(self._pid.Kp), + "{:.4f}".format(self._pid.Ki), + "{:.4f}".format(self._pid.Kd), + self._config.get("control", "loop_size_ms") + ] + + # CSV file + if self._log_writer: + try: + self._log_writer.writerow(row) + self._log_file.flush() + except Exception as e: + log.error("Failed to write log: %s", e) + + # In-memory history for web UI + data_point = { + "timestamp": now, + "temp": round(temp, 2), + "setpoint": round(self._setpoint, 2), + "output": round(output, 2), + "relay": self._relay_on + } + with self._lock: + self._history.append(data_point) + if len(self._history) > self._history_max: + self._history = self._history[-self._history_max:] + + # --- Public API (thread-safe) --- + + def set_setpoint(self, value): + """Change the target temperature.""" + with self._lock: + old_setpoint = self._setpoint + self._setpoint = float(value) + self._idle_since = None # Reset idle timer on setpoint change + if abs(self._setpoint - old_setpoint) >= 10: + self._pid.reset() + self._config.set("control", "setpoint", float(value)) + log.info("Setpoint changed to %.0fF", value) + + def set_pid_tuning(self, kp, ki, kd, proportional_on_measurement=None, proportional_mode=None): + """Update PID gains.""" + section = {"kP": kp, "kI": ki, "kD": kd} + if proportional_mode in ("error", "measurement"): + proportional_on_measurement = (proportional_mode == "measurement") + if proportional_on_measurement is not None: + section["proportional_on_measurement"] = bool(proportional_on_measurement) + self._pid.proportional_on_measurement = bool(proportional_on_measurement) + self._config.update_section("pid", section) + self._pid.tunings = (kp, ki, kd) + self._pid.reset() + log.info("PID tuning updated: kP=%.4f, kI=%.4f, kD=%.4f", kp, ki, kd) + + @property + def status(self): + """Return a dict of current controller state (thread-safe snapshot).""" + with self._lock: + uptime = None + if self._start_time is not None and self._enabled: + uptime = round(time.monotonic() - self._start_time, 1) + + return { + "enabled": self._enabled, + "temp": round(self._temp, 2), + "setpoint": round(self._setpoint, 2), + "output": round(self._output, 2), + "relay_on": self._relay_on, + "loop_count": self._loop_count, + "uptime_seconds": uptime, + "safety_tripped": self._safety_tripped, + "safety_reason": self._safety_reason, + "thermocouple_connected": self._tc.is_connected, + "pid": { + "kP": self._pid.Kp, + "kI": self._pid.Ki, + "kD": self._pid.Kd, + "proportional_on_measurement": self._pid.proportional_on_measurement, + "proportional_mode": "measurement" if self._pid.proportional_on_measurement else "error", + }, + "autotune": { + "active": self._autotune_active, + "target": round(self._autotune_target, 2), + "hysteresis": round(self._autotune_hysteresis, 2), + "cycles": self._autotune_cycles, + "high_peaks": len(self._autotune_high_peaks), + "low_peaks": len(self._autotune_low_peaks), + "phase": "heating" if self._autotune_heating else "cooling", + "message": self._autotune_message, + "last_result": self._autotune_last_result, + }, + } + + @property + def autotune_status(self): + with self._lock: + return { + "active": self._autotune_active, + "target": round(self._autotune_target, 2), + "hysteresis": round(self._autotune_hysteresis, 2), + "cycles": self._autotune_cycles, + "high_peaks": len(self._autotune_high_peaks), + "low_peaks": len(self._autotune_low_peaks), + "phase": "heating" if self._autotune_heating else "cooling", + "message": self._autotune_message, + "last_result": self._autotune_last_result, + } + + @property + def history(self): + """Return recent data points for charting.""" + with self._lock: + return list(self._history) + + def get_history_since(self, since_timestamp): + """Return data points newer than the given timestamp.""" + with self._lock: + return [p for p in self._history if p["timestamp"] > since_timestamp] + + @property + def is_alive(self): + """Check if the control loop thread is alive.""" + return self._thread is not None and self._thread.is_alive() + + @property + def watchdog_ok(self): + """Check if the control loop has updated recently.""" + if not self._enabled: + return True + with self._lock: + if self._last_loop_time is None: + return True + timeout = self._config.get("safety", "watchdog_timeout_s") + return (time.monotonic() - self._last_loop_time) < timeout + + def cleanup(self): + """Clean up GPIO and close log file. Call on application shutdown.""" + self.stop() + if self._log_file: + try: + self._log_file.close() + except Exception: + pass + if self._gpio is not None: + try: + self._gpio.cleanup() + log.info("GPIO cleaned up") + except Exception as e: + log.error("GPIO cleanup error: %s", e) diff --git a/piNail2/pinail.service b/piNail2/pinail.service new file mode 100644 index 0000000..3112e21 --- /dev/null +++ b/piNail2/pinail.service @@ -0,0 +1,20 @@ +[Unit] +Description=piNail2 E-Nail Temperature Controller +After=network.target + +[Service] +Type=simple +User=pi +WorkingDirectory=/home/pi/piNail2 +ExecStart=/usr/bin/python3 app.py +Restart=on-failure +RestartSec=5 +StandardOutput=journal +StandardError=journal + +# Safety: if the service crashes, GPIO cleanup happens in the app. +# But as an extra safety net, run a one-shot relay-off on stop. +ExecStopPost=/bin/bash -c 'echo "2" > /sys/class/gpio/unexport 2>/dev/null || true' + +[Install] +WantedBy=multi-user.target diff --git a/piNail2/requirements.txt b/piNail2/requirements.txt new file mode 100644 index 0000000..a290205 --- /dev/null +++ b/piNail2/requirements.txt @@ -0,0 +1,6 @@ +# piNail2 dependencies +# Compatible with Python 3.5 on Raspbian Stretch +Flask>=0.12,<1.0 +simple-pid>=0.1,<2.0 +RPi.GPIO>=0.6 +Adafruit-GPIO>=1.0 diff --git a/piNail2/static/app.js b/piNail2/static/app.js new file mode 100644 index 0000000..1b8c229 --- /dev/null +++ b/piNail2/static/app.js @@ -0,0 +1,564 @@ +/** + * piNail2 Frontend — Dashboard Controller + * + * Polls the REST API for status updates, renders a live Chart.js chart, + * and provides controls for setpoint, PID tuning, and power toggle. + */ + +// --------------------------------------------------------------------------- +// State +// --------------------------------------------------------------------------- +let pollInterval = 500; // ms between status polls +let chartMaxPoints = 300; // max data points on chart +let lastTimestamp = 0; // for incremental history fetches +let isEnabled = false; +let currentSetpoint = 530; +let chart = null; +let lastApiError = ''; +let actionBannerTimer = null; +let heartbeatMisses = 0; +let heartbeatInstanceId = null; +let controlsEnabled = true; + +function nowHms() { + const d = new Date(); + return d.toLocaleTimeString(); +} + +function setLastAck(message, ok=true) { + const el = document.getElementById('last-ack'); + if (!el) return; + el.className = 'last-ack ' + (ok ? 'ok' : 'err'); + el.textContent = 'Last command: ' + message + ' at ' + nowHms(); +} + +function showAction(message, type='info', timeoutMs=3000) { + const banner = document.getElementById('action-banner'); + const msg = document.getElementById('action-message'); + if (!banner || !msg) return; + msg.textContent = message; + banner.className = 'action-banner ' + type; + if (actionBannerTimer) clearTimeout(actionBannerTimer); + if (timeoutMs > 0) { + actionBannerTimer = setTimeout(function() { + banner.className = 'action-banner hidden'; + }, timeoutMs); + } +} + +function setControlsEnabled(enabled) { + if (controlsEnabled === enabled) return; + controlsEnabled = enabled; + const btns = document.querySelectorAll('button'); + btns.forEach(function(b) { + if (b.id === 'autotune-stop-btn' && enabled) { + // stop button is governed by autotune state in setAutotuneUi() + return; + } + b.disabled = !enabled; + }); +} + +function setBackendStatus(mode, text) { + const el = document.getElementById('backend-status'); + if (!el) return; + el.className = 'backend-status ' + mode; + el.textContent = text; +} + +function setAutotuneUi(tune) { + const statusEl = document.getElementById('autotune-status'); + const startBtn = document.getElementById('autotune-start-btn'); + const stopBtn = document.getElementById('autotune-stop-btn'); + const pill = document.getElementById('autotune-pill'); + if (!statusEl || !startBtn || !stopBtn) return; + + if (tune && tune.active) { + statusEl.className = 'autotune-status running'; + const phase = tune.phase ? (' ' + tune.phase) : ''; + statusEl.textContent = 'Running' + phase + ' (' + tune.high_peaks + '/' + tune.cycles + ' peaks)'; + if (pill) { + pill.className = 'autotune-pill running'; + pill.textContent = 'Autotune: Running' + phase; + } + startBtn.disabled = true; + stopBtn.disabled = false; + return; + } + + startBtn.disabled = false; + stopBtn.disabled = true; + + if (tune && tune.last_result) { + statusEl.className = 'autotune-status done'; + statusEl.textContent = 'Complete: kP ' + tune.last_result.kP + ', kI ' + tune.last_result.kI + ', kD ' + tune.last_result.kD; + if (pill) { + pill.className = 'autotune-pill done'; + pill.textContent = 'Autotune: Complete'; + } + } else if (tune && tune.message) { + const lower = String(tune.message).toLowerCase(); + statusEl.className = 'autotune-status ' + (lower.indexOf('failed') >= 0 ? 'error' : 'idle'); + statusEl.textContent = tune.message; + if (pill) { + const failed = lower.indexOf('failed') >= 0 || lower.indexOf('error') >= 0; + pill.className = 'autotune-pill ' + (failed ? 'error' : 'idle'); + pill.textContent = failed ? 'Autotune: Error' : 'Autotune: Idle'; + } + } else { + statusEl.className = 'autotune-status idle'; + statusEl.textContent = 'Idle'; + if (pill) { + pill.className = 'autotune-pill idle'; + pill.textContent = 'Autotune: Idle'; + } + } +} + +// --------------------------------------------------------------------------- +// Chart Setup +// --------------------------------------------------------------------------- +function initChart() { + const ctx = document.getElementById('temp-chart').getContext('2d'); + chart = new Chart(ctx, { + type: 'line', + data: { + datasets: [ + { + label: 'Temperature (F)', + borderColor: '#ff6b35', + backgroundColor: 'rgba(255, 107, 53, 0.1)', + borderWidth: 2, + pointRadius: 0, + fill: true, + data: [], + yAxisID: 'y' + }, + { + label: 'Setpoint (F)', + borderColor: '#4ecdc4', + borderWidth: 1.5, + borderDash: [5, 5], + pointRadius: 0, + fill: false, + data: [], + yAxisID: 'y' + }, + { + label: 'Output', + borderColor: '#45b7d1', + backgroundColor: 'rgba(69, 183, 209, 0.1)', + borderWidth: 1, + pointRadius: 0, + fill: true, + data: [], + yAxisID: 'y1' + } + ] + }, + options: { + responsive: true, + maintainAspectRatio: false, + animation: false, + interaction: { + mode: 'index', + intersect: false + }, + scales: { + x: { + type: 'linear', + display: true, + title: { display: false }, + ticks: { + color: '#888', + callback: function(value) { + // Show relative seconds + return Math.round(value) + 's'; + }, + maxTicksLimit: 10 + }, + grid: { color: 'rgba(255,255,255,0.05)' } + }, + y: { + type: 'linear', + display: true, + position: 'left', + title: { display: true, text: 'Temperature (F)', color: '#aaa' }, + ticks: { color: '#ff6b35' }, + grid: { color: 'rgba(255,255,255,0.05)' }, + suggestedMin: 0, + suggestedMax: 700 + }, + y1: { + type: 'linear', + display: true, + position: 'right', + title: { display: true, text: 'PID Output', color: '#aaa' }, + ticks: { color: '#45b7d1' }, + grid: { drawOnChartArea: false }, + suggestedMin: 0 + } + }, + plugins: { + legend: { + labels: { color: '#ccc', boxWidth: 12 } + } + } + } + }); +} + +// --------------------------------------------------------------------------- +// Data Update +// --------------------------------------------------------------------------- +let firstTimestamp = null; + +function addChartData(points) { + if (!chart || !points.length) return; + + if (firstTimestamp === null) { + firstTimestamp = points[0].timestamp; + } + + for (const p of points) { + const x = p.timestamp - firstTimestamp; // relative seconds + chart.data.datasets[0].data.push({ x: x, y: p.temp }); + chart.data.datasets[1].data.push({ x: x, y: p.setpoint }); + chart.data.datasets[2].data.push({ x: x, y: p.output }); + } + + // Trim to max points + for (const ds of chart.data.datasets) { + if (ds.data.length > chartMaxPoints) { + ds.data = ds.data.slice(ds.data.length - chartMaxPoints); + } + } + + chart.update('none'); // skip animation for performance +} + +// --------------------------------------------------------------------------- +// API Calls +// --------------------------------------------------------------------------- +async function fetchJSON(url, options) { + try { + const resp = await fetch(url, options); + const payload = await resp.json(); + if (!resp.ok) { + throw new Error(payload.error || ('HTTP ' + resp.status)); + } + lastApiError = ''; + return payload; + } catch (e) { + console.error('API error:', url, e); + lastApiError = String(e); + if (String(e).indexOf('HTTP') >= 0) { + // API-level error, connection is still fine. + } else { + setConnectionStatus(false); + } + return null; + } +} + +async function pollStatus() { + const status = await fetchJSON('/api/status'); + if (!status) return; + + setConnectionStatus(true); + + // Temperature display + const tempEl = document.getElementById('current-temp'); + tempEl.textContent = status.temp.toFixed(1); + + // Color the temp based on proximity to setpoint + const delta = Math.abs(status.temp - status.setpoint); + if (!status.enabled) { + tempEl.className = 'temp-value'; + } else if (delta < 15) { + tempEl.className = 'temp-value temp-good'; + } else if (delta < 50) { + tempEl.className = 'temp-value temp-warming'; + } else { + tempEl.className = 'temp-value temp-cold'; + } + + // Setpoint display + document.getElementById('current-setpoint').textContent = status.setpoint.toFixed(0); + currentSetpoint = status.setpoint; + + // Power button + isEnabled = status.enabled; + const powerBtn = document.getElementById('power-btn'); + if (isEnabled) { + powerBtn.textContent = 'ON'; + powerBtn.className = 'power-btn on'; + } else { + powerBtn.textContent = 'OFF'; + powerBtn.className = 'power-btn off'; + } + + // Safety banner + const banner = document.getElementById('safety-banner'); + if (status.safety_tripped) { + banner.classList.remove('hidden'); + document.getElementById('safety-message').textContent = + 'SAFETY TRIP: ' + status.safety_reason; + } else { + banner.classList.add('hidden'); + } + + // Status bar + document.getElementById('status-output').textContent = + status.output.toFixed(1) + ' / ' + (status.config.loop_size_ms || '?'); + + const relayEl = document.getElementById('status-relay'); + relayEl.textContent = status.relay_on ? 'ON' : 'OFF'; + relayEl.className = 'value ' + (status.relay_on ? 'relay-on' : 'relay-off'); + + if (status.uptime_seconds !== null) { + const mins = Math.floor(status.uptime_seconds / 60); + const secs = Math.floor(status.uptime_seconds % 60); + document.getElementById('status-uptime').textContent = + mins + 'm ' + secs + 's'; + } else { + document.getElementById('status-uptime').textContent = '--'; + } + + document.getElementById('status-loops').textContent = status.loop_count; + + const tcEl = document.getElementById('status-tc'); + tcEl.textContent = status.thermocouple_connected ? 'OK' : 'DISCONNECTED'; + tcEl.className = 'value ' + (status.thermocouple_connected ? 'tc-ok' : 'tc-err'); + + // PID fields (only update if user isn't focused on them) + if (document.activeElement.id !== 'pid-kp') + document.getElementById('pid-kp').value = status.pid.kP; + if (document.activeElement.id !== 'pid-ki') + document.getElementById('pid-ki').value = status.pid.kI; + if (document.activeElement.id !== 'pid-kd') + document.getElementById('pid-kd').value = status.pid.kD; + if (document.activeElement.id !== 'pid-pmode') { + const mode = status.pid.proportional_mode || (status.pid.proportional_on_measurement ? 'measurement' : 'error'); + document.getElementById('pid-pmode').value = mode; + } + + const tune = status.autotune || {}; + setAutotuneUi(tune); + + // Setpoint input (only update if user isn't focused) + if (document.activeElement.id !== 'setpoint-input') + document.getElementById('setpoint-input').value = status.setpoint; + + // Presets + if (status.presets) { + renderPresets(status.presets); + } +} + +async function pollHistory() { + const data = await fetchJSON('/api/history?since=' + lastTimestamp); + if (!data || !data.length) return; + lastTimestamp = data[data.length - 1].timestamp; + addChartData(data); +} + +function setConnectionStatus(connected) { + const dot = document.getElementById('connection-status'); + if (connected) { + dot.className = 'status-dot connected'; + dot.title = 'Connected'; + setBackendStatus('online', 'Backend: Online'); + } else { + dot.className = 'status-dot disconnected'; + dot.title = 'Disconnected'; + setBackendStatus('offline', 'Backend: Offline'); + } +} + +async function pollHeartbeat() { + const hb = await fetchJSON('/api/heartbeat?ts=' + Date.now()); + if (!hb || !hb.ok) { + heartbeatMisses += 1; + if (heartbeatMisses >= 2) { + setBackendStatus('reconnecting', 'Backend: Reconnecting...'); + setControlsEnabled(false); + } + return; + } + + if (heartbeatMisses >= 2) { + showAction('Backend reconnected.', 'success', 2500); + } + heartbeatMisses = 0; + setConnectionStatus(true); + setControlsEnabled(true); + + if (heartbeatInstanceId === null) { + heartbeatInstanceId = hb.instance_id; + } else if (heartbeatInstanceId !== hb.instance_id) { + showAction('Backend restarted. Reloading UI...', 'info', 1500); + setTimeout(function() { window.location.reload(); }, 1200); + } +} + +// --------------------------------------------------------------------------- +// User Actions +// --------------------------------------------------------------------------- +async function togglePower() { + const result = await fetchJSON('/api/power', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ enabled: !isEnabled }) + }); + if (!result) { + setLastAck('power failed', false); + return; + } + setLastAck('power ' + (result.enabled ? 'ON' : 'OFF'), true); + // Reset chart on power toggle + if (!isEnabled) { + firstTimestamp = null; + lastTimestamp = 0; + if (chart) { + for (const ds of chart.data.datasets) ds.data = []; + chart.update('none'); + } + } +} + +async function applySetpoint() { + const value = parseFloat(document.getElementById('setpoint-input').value); + if (isNaN(value)) return; + const result = await fetchJSON('/api/setpoint', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ setpoint: value }) + }); + if (!result) { + setLastAck('setpoint failed', false); + return; + } + setLastAck('setpoint ' + value + 'F', true); +} + +function adjustSetpoint(delta) { + const input = document.getElementById('setpoint-input'); + const newVal = parseFloat(input.value) + delta; + input.value = newVal; + applySetpoint(); +} + +async function applyPID() { + const kp = parseFloat(document.getElementById('pid-kp').value); + const ki = parseFloat(document.getElementById('pid-ki').value); + const kd = parseFloat(document.getElementById('pid-kd').value); + const pMode = document.getElementById('pid-pmode').value; + if (isNaN(kp) || isNaN(ki) || isNaN(kd)) return; + const result = await fetchJSON('/api/pid', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ kP: kp, kI: ki, kD: kd, proportional_mode: pMode }) + }); + if (!result) { + setLastAck('PID apply failed', false); + return; + } + setLastAck('PID applied (' + pMode + ')', true); +} + +async function resetPID() { + const result = await fetchJSON('/api/pid/reset', { method: 'POST' }); + if (!result) { + setLastAck('PID reset failed', false); + return; + } + setLastAck('PID reset', true); +} + +async function startAutotune() { + const target = parseFloat(document.getElementById('setpoint-input').value); + showAction('Starting autotune at ' + target + 'F (auto-enables heater if needed)...', 'info', 5000); + setAutotuneUi({ message: 'Starting autotune...', last_result: null, active: true, high_peaks: 0, cycles: 0 }); + const result = await fetchJSON('/api/autotune/start', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + setpoint: target + }) + }); + if (!result) { + setAutotuneUi({ message: lastApiError || 'Failed to start autotune', active: false, last_result: null }); + showAction(lastApiError || 'Failed to start autotune', 'error', 6000); + setLastAck('autotune start failed', false); + return; + } + showAction('Autotune started. Watch peaks progress.', 'success', 5000); + setAutotuneUi(result.autotune || { message: 'Autotune started', active: true }); + setLastAck('autotune started', true); +} + +async function stopAutotune() { + setAutotuneUi({ message: 'Stopping autotune...', last_result: null, active: false }); + showAction('Stopping autotune...', 'info', 3000); + const result = await fetchJSON('/api/autotune/stop', { method: 'POST' }); + if (!result) { + setAutotuneUi({ message: lastApiError || 'Failed to stop autotune', active: false, last_result: null }); + showAction(lastApiError || 'Failed to stop autotune', 'error', 6000); + setLastAck('autotune stop failed', false); + return; + } + showAction('Autotune stopped.', 'success', 4000); + setAutotuneUi(result.autotune || { message: 'Autotune stopped', active: false, last_result: null }); + setLastAck('autotune stopped', true); +} + +async function applyPreset(name) { + const result = await fetchJSON('/api/preset/' + encodeURIComponent(name), { method: 'POST' }); + if (!result) { + setLastAck('preset failed', false); + return; + } + setLastAck('preset ' + name, true); +} + +async function resetSafety() { + const result = await fetchJSON('/api/safety/reset', { method: 'POST' }); + if (!result) { + setLastAck('safety reset failed', false); + return; + } + setLastAck('safety reset', true); +} + +function renderPresets(presets) { + const container = document.getElementById('presets-container'); + const buttons = Object.entries(presets).map(([name, temp]) => + '' + ).join(''); + container.innerHTML = buttons; +} + +// Handle Enter key in setpoint input +document.addEventListener('DOMContentLoaded', function() { + document.getElementById('setpoint-input').addEventListener('keydown', function(e) { + if (e.key === 'Enter') applySetpoint(); + }); + setAutotuneUi({ active: false, message: 'Idle', last_result: null }); +}); + +// --------------------------------------------------------------------------- +// Init +// --------------------------------------------------------------------------- +initChart(); + +// Start polling loops +setInterval(pollStatus, pollInterval); +setInterval(pollHistory, pollInterval); +setInterval(pollHeartbeat, 2000); + +// Initial fetch +pollStatus(); +pollHistory(); +pollHeartbeat(); diff --git a/piNail2/static/img/pi_favicon.png b/piNail2/static/img/pi_favicon.png new file mode 100644 index 0000000..ba3eb6d Binary files /dev/null and b/piNail2/static/img/pi_favicon.png differ diff --git a/piNail2/static/img/pinail_logo.png b/piNail2/static/img/pinail_logo.png new file mode 100644 index 0000000..23885e8 Binary files /dev/null and b/piNail2/static/img/pinail_logo.png differ diff --git a/piNail2/static/img/pinail_logo.svg b/piNail2/static/img/pinail_logo.svg new file mode 100644 index 0000000..622c309 --- /dev/null +++ b/piNail2/static/img/pinail_logo.svg @@ -0,0 +1,23 @@ + + + PINAIL + + + + + + + + + + + + + + + + + + + + diff --git a/piNail2/static/style.css b/piNail2/static/style.css new file mode 100644 index 0000000..bd335fd --- /dev/null +++ b/piNail2/static/style.css @@ -0,0 +1,571 @@ +/* piNail2 — Dark theme dashboard */ + +:root { + --bg: #1a1a1a; + --bg-card: #252525; + --bg-input: #2a2a2a; + --text: #e0e0e0; + --text-dim: #cccccc; + --accent-orange: #d35400; + --accent-orange-hover: #e65c00; + --accent-orange-deep: #a84300; + --accent-teal: #d35400; + --accent-blue: #d35400; + --accent-red: #e74c3c; + --accent-green: #2ecc71; + --border: #333333; + --radius: 8px; +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, monospace; + background: radial-gradient(circle at 20% 0%, #222 0%, #1a1a1a 35%, #000 100%); + color: var(--text); + min-height: 100vh; +} + +/* Header */ +header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 20px; + background: #000; + border-bottom: 1px solid var(--border); +} + +.brand { + display: flex; + align-items: center; + gap: 10px; +} + +.brand-logo { + height: 34px; + width: auto; + max-width: 42vw; + border: none; + border-radius: 0; + object-fit: contain; +} + +.conn-wrap { + display: flex; + align-items: center; + gap: 10px; +} + +.backend-status { + font-size: 0.8rem; + color: var(--text-dim); +} + +.last-ack { + font-size: 0.8rem; + color: var(--text-dim); +} + +.last-ack.ok { + color: var(--accent-green); +} + +.last-ack.err { + color: var(--accent-red); +} + +.backend-status.online { color: var(--accent-green); } +.backend-status.reconnecting { color: var(--accent-orange); } +.backend-status.offline { color: var(--accent-red); } + +header h1 { + font-size: 1rem; + font-weight: 600; + color: var(--text-dim); + text-transform: uppercase; + letter-spacing: 0.1em; +} + +.status-dot { + width: 12px; + height: 12px; + border-radius: 50%; +} + +.status-dot.connected { background: var(--accent-green); } +.status-dot.disconnected { background: var(--accent-red); } + +/* Main */ +main { + max-width: 900px; + margin: 0 auto; + padding: 16px; +} + +/* Hero: temp + power */ +.hero { + display: flex; + align-items: center; + justify-content: space-between; + background: var(--bg-card); + border-radius: var(--radius); + padding: 20px 30px; + margin-bottom: 12px; + border: 1px solid var(--border); +} + +.temp-display { + display: flex; + align-items: baseline; +} + +.temp-value { + font-size: 4rem; + font-weight: 700; + font-variant-numeric: tabular-nums; + color: var(--text-dim); + transition: color 0.3s; +} + +.temp-unit { + font-size: 1.5rem; + color: var(--text-dim); + margin-left: 4px; +} + +.temp-good { color: var(--accent-green); } +.temp-warming { color: var(--accent-orange); } +.temp-cold { color: var(--accent-blue); } + +.hero-right { + text-align: right; + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 12px; +} + +.autotune-pill { + font-size: 0.8rem; + padding: 4px 10px; + border-radius: 999px; + border: 1px solid var(--border); + letter-spacing: 0.02em; +} + +.autotune-pill.idle { + color: var(--text-dim); + background: rgba(255, 255, 255, 0.05); +} + +.autotune-pill.running { + color: #111; + background: var(--accent-orange); + border-color: var(--accent-orange); + animation: autotunePulse 1.2s infinite; +} + +.autotune-pill.done { + color: #111; + background: var(--accent-green); + border-color: var(--accent-green); +} + +.autotune-pill.error { + color: #fff; + background: var(--accent-red); + border-color: var(--accent-red); +} + +.setpoint-display { + font-size: 1.1rem; + color: var(--accent-teal); +} + +.power-btn { + width: 80px; + height: 80px; + border-radius: 50%; + border: 3px solid; + font-size: 1.2rem; + font-weight: 700; + cursor: pointer; + transition: all 0.2s; +} + +.power-btn.off { + background: transparent; + border-color: var(--text-dim); + color: var(--text-dim); +} + +.power-btn.on { + background: rgba(46, 204, 113, 0.15); + border-color: var(--accent-green); + color: var(--accent-green); + box-shadow: 0 0 20px rgba(46, 204, 113, 0.3); +} + +.power-btn:hover { opacity: 0.8; } +.power-btn:active { transform: scale(0.95); } + +/* Safety Banner */ +.safety-banner { + background: rgba(231, 76, 60, 0.15); + border: 1px solid var(--accent-red); + border-radius: var(--radius); + padding: 12px 20px; + margin-bottom: 12px; + display: flex; + align-items: center; + justify-content: space-between; + color: var(--accent-red); + font-weight: 600; +} + +.safety-banner.hidden { display: none; } + +.safety-banner button { + background: var(--accent-red); + color: white; + border: none; + padding: 6px 16px; + border-radius: 4px; + cursor: pointer; + font-weight: 600; +} + +.action-banner { + border-radius: var(--radius); + padding: 10px 14px; + margin-bottom: 12px; + border: 1px solid var(--border); + background: rgba(255, 255, 255, 0.06); + color: var(--text); + font-weight: 600; +} + +.action-banner.hidden { display: none; } +.action-banner.info { border-color: var(--accent-blue); color: var(--accent-blue); } +.action-banner.success { border-color: var(--accent-green); color: var(--accent-green); } +.action-banner.error { border-color: var(--accent-red); color: var(--accent-red); } + +/* Chart */ +.chart-section { + background: var(--bg-card); + border-radius: var(--radius); + border: 1px solid var(--border); + padding: 12px; + margin-bottom: 12px; + height: 280px; +} + +.chart-section { + box-shadow: inset 0 0 0 1px rgba(211, 84, 0, 0.12); +} + +.chart-section canvas { + width: 100% !important; + height: 100% !important; +} + +/* Controls */ +.controls { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; + margin-bottom: 12px; +} + +.control-group { + background: var(--bg-card); + border-radius: var(--radius); + border: 1px solid var(--border); + padding: 16px; +} + +.control-group h3 { + font-size: 0.85rem; + text-transform: uppercase; + color: var(--text-dim); + margin-bottom: 12px; + letter-spacing: 0.05em; +} + +/* Setpoint controls */ +.setpoint-controls { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; +} + +.adj-btn { + background: var(--bg-input); + color: var(--text); + border: 1px solid var(--border); + padding: 8px 12px; + border-radius: 4px; + cursor: pointer; + font-size: 0.9rem; + font-weight: 600; +} + +.adj-btn:hover { background: var(--accent-orange-deep); color: #fff; } +.adj-btn:active { transform: scale(0.95); } + +input[type="number"] { + background: var(--bg-input); + color: var(--text); + border: 1px solid var(--border); + padding: 8px 10px; + border-radius: 4px; + width: 80px; + text-align: center; + font-size: 1rem; + font-family: inherit; +} + +select { + background: var(--bg-input); + color: var(--text); + border: 1px solid var(--border); + padding: 8px 10px; + border-radius: 4px; + font-size: 0.9rem; + font-family: inherit; +} + +select:focus { + outline: none; + border-color: var(--accent-teal); +} + +input[type="number"]:focus { + outline: none; + border-color: var(--accent-teal); +} + +.apply-btn { + background: var(--accent-teal); + color: #fff; + border: none; + padding: 8px 16px; + border-radius: 4px; + cursor: pointer; + font-weight: 700; + font-size: 0.9rem; +} + +.apply-btn:hover { background: var(--accent-orange-hover); opacity: 1; } +.apply-btn:active { transform: scale(0.95); } + +button:disabled { + opacity: 0.45; + cursor: not-allowed; + transform: none !important; +} + +/* Presets */ +.presets { + margin-top: 10px; + display: flex; + gap: 6px; + flex-wrap: wrap; +} + +.preset-btn { + background: var(--bg-input); + color: var(--accent-teal); + border: 1px solid var(--accent-teal); + padding: 6px 12px; + border-radius: 4px; + cursor: pointer; + font-size: 0.8rem; +} + +.preset-btn:hover { + background: var(--accent-teal); + color: #000; +} + +/* PID controls */ +.pid-controls { + display: flex; + align-items: flex-end; + gap: 10px; + flex-wrap: wrap; +} + +.pid-controls label { + display: flex; + flex-direction: column; + font-size: 0.8rem; + color: var(--text-dim); + gap: 4px; +} + +.checkbox-label { + flex-direction: row !important; + align-items: center; + gap: 6px; + color: var(--text); +} + +.checkbox-label input { + width: auto; +} + +.autotune-controls { + margin-top: 12px; + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.autotune-status { + font-size: 0.85rem; + color: var(--text-dim); + font-weight: 600; +} + +.autotune-status.idle { + color: var(--text-dim); +} + +.autotune-status.running { + color: var(--accent-orange); + animation: autotunePulse 1.2s infinite; +} + +.autotune-status.done { + color: var(--accent-green); +} + +.autotune-status.error { + color: var(--accent-red); +} + +@keyframes autotunePulse { + 0% { opacity: 0.6; } + 50% { opacity: 1; } + 100% { opacity: 0.6; } +} + +.pid-controls input { + width: 70px; +} + +/* Status Bar */ +.status-bar { + display: flex; + gap: 12px; + flex-wrap: wrap; +} + +.status-item { + background: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 10px 16px; + flex: 1; + min-width: 100px; + text-align: center; +} + +.status-item .label { + display: block; + font-size: 0.7rem; + text-transform: uppercase; + color: var(--text-dim); + margin-bottom: 4px; +} + +.status-item .value { + font-size: 1rem; + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.app-footer { + margin-top: 14px; + padding: 12px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: rgba(0, 0, 0, 0.4); + color: var(--text-dim); + font-size: 0.78rem; + display: flex; + justify-content: space-between; + gap: 10px; +} + +.relay-on { color: var(--accent-green); } +.relay-off { color: var(--text-dim); } +.tc-ok { color: var(--accent-green); } +.tc-err { color: var(--accent-red); } + +/* Mobile responsive */ +@media (max-width: 600px) { + .hero { + flex-direction: column; + text-align: center; + gap: 16px; + padding: 16px; + } + + .brand-logo { + height: 28px; + max-width: 46vw; + } + + header h1 { + display: none; + } + + .app-footer { + flex-direction: column; + text-align: center; + } + + .hero-right { + align-items: center; + } + + .temp-value { + font-size: 3rem; + } + + .power-btn { + width: 64px; + height: 64px; + font-size: 1rem; + } + + .controls { + grid-template-columns: 1fr; + } + + .chart-section { + height: 220px; + } + + .setpoint-controls { + justify-content: center; + } + + .pid-controls { + justify-content: center; + } + + .status-bar { + display: grid; + grid-template-columns: 1fr 1fr; + } +} diff --git a/piNail2/templates/index.html b/piNail2/templates/index.html new file mode 100644 index 0000000..9433ee2 --- /dev/null +++ b/piNail2/templates/index.html @@ -0,0 +1,139 @@ + + + + + + piNail2 Controller + + + + + +
+
+ +

Controller

+
+
+ Last command: none + Backend: Online +
+
+
+ +
+ +
+
+ --- + °F +
+
+
+ Target: ---°F +
+
Autotune: Idle
+ +
+
+ + + + + + + +
+ +
+ + +
+ +
+

Setpoint

+
+ + + + + + +
+
+ +
+
+ + +
+

PID Tuning

+
+ + + + + + +
+
+ + + Idle +
+
+
+ + +
+
+ Output + 0 +
+
+ Relay + OFF +
+
+ Uptime + -- +
+
+ Loops + 0 +
+
+ TC + -- +
+
+ +
+ {{ app_version }} + Copyright © {{ copyright_year }} SethPC Labs +
+
+ + + + diff --git a/piNail2/thermocouple.py b/piNail2/thermocouple.py new file mode 100644 index 0000000..0d20f3c --- /dev/null +++ b/piNail2/thermocouple.py @@ -0,0 +1,158 @@ +""" +piNail2 Thermocouple Driver + +Wraps the MAX6675 thermocouple reader with: +- Celsius to Fahrenheit conversion +- Spike/outlier filtering (median of recent readings) +- Open thermocouple detection +- Error handling +""" + +import logging +import collections + +log = logging.getLogger(__name__) + + +def c_to_f(c): + """Convert Celsius to Fahrenheit.""" + return c * 9.0 / 5.0 + 32.0 + + +class Thermocouple: + """ + MAX6675 thermocouple reader with spike filtering. + + The MAX6675 occasionally returns spurious readings (we've seen 869F spikes + in otherwise stable ~680F data). This class maintains a sliding window of + recent readings and rejects outliers. + """ + + def __init__(self, clk, cs, do, spike_threshold=50.0, window_size=5): + """ + Args: + clk: GPIO pin for SPI clock + cs: GPIO pin for chip select + do: GPIO pin for data out (MISO) + spike_threshold: Maximum allowed jump between filtered readings (in F) + window_size: Number of recent readings to keep for median filtering + """ + self._spike_threshold = spike_threshold + self._window_size = window_size + self._readings = collections.deque(maxlen=window_size) + self._last_good_temp = None + self._raw_temp = 0.0 + self._filtered_temp = 0.0 + self._is_connected = False + self._spike_count = 0 + self._total_reads = 0 + + try: + import MAX6675.MAX6675 as MAX6675 + self._sensor = MAX6675.MAX6675(clk, cs, do) + self._is_connected = True + log.info("MAX6675 thermocouple initialized (CLK=%d, CS=%d, DO=%d)", clk, cs, do) + except Exception as e: + log.error("Failed to initialize MAX6675: %s", e) + self._sensor = None + self._is_connected = False + + def read(self): + """ + Read temperature from the thermocouple. + + Returns: + float: Filtered temperature in Fahrenheit, or None if sensor is disconnected. + """ + if self._sensor is None: + return None + + self._total_reads += 1 + + try: + raw_c = self._sensor.readTempC() + except Exception as e: + log.error("Thermocouple read error: %s", e) + self._is_connected = False + return self._last_good_temp + + # Check for open thermocouple (MAX6675 returns very high values or specific error codes) + if raw_c is None or raw_c > 1023: + log.warning("Thermocouple appears disconnected (raw_c=%s)", raw_c) + self._is_connected = False + return self._last_good_temp + + self._is_connected = True + raw_f = c_to_f(raw_c) + self._raw_temp = raw_f + + # Spike detection: if we have a previous good reading, check for unreasonable jumps + if self._last_good_temp is not None: + delta = abs(raw_f - self._last_good_temp) + if delta > self._spike_threshold: + self._spike_count += 1 + log.warning( + "Spike detected: %.1fF -> %.1fF (delta=%.1fF, count=%d). Using last good value.", + self._last_good_temp, raw_f, delta, self._spike_count + ) + # Still add to window but return last good — if multiple consecutive + # readings are in the "spike" range, they'll become the new normal + # via the median filter + self._readings.append(raw_f) + # If we've had many consecutive "spikes", the temperature probably + # genuinely changed fast (e.g., touching the nail with concentrate) + if self._spike_count >= self._window_size: + log.info("Spike count exceeded window size, accepting new baseline %.1fF", raw_f) + self._spike_count = 0 + self._last_good_temp = raw_f + self._filtered_temp = raw_f + return raw_f + self._filtered_temp = self._last_good_temp + return self._last_good_temp + + # Normal reading — reset spike counter, add to window + self._spike_count = 0 + self._readings.append(raw_f) + + # Median filter + if len(self._readings) >= 3: + sorted_readings = sorted(self._readings) + median = sorted_readings[len(sorted_readings) // 2] + self._filtered_temp = median + self._last_good_temp = median + else: + self._filtered_temp = raw_f + self._last_good_temp = raw_f + + return self._filtered_temp + + @property + def raw_temp(self): + """Last raw (unfiltered) temperature reading in Fahrenheit.""" + return self._raw_temp + + @property + def filtered_temp(self): + """Last filtered temperature reading in Fahrenheit.""" + return self._filtered_temp + + @property + def is_connected(self): + """Whether the thermocouple appears to be connected.""" + return self._is_connected + + @property + def spike_count(self): + """Number of spike events detected since last normal reading.""" + return self._spike_count + + @property + def stats(self): + """Return diagnostic stats.""" + return { + "raw_temp": round(self._raw_temp, 2), + "filtered_temp": round(self._filtered_temp, 2), + "is_connected": self._is_connected, + "total_reads": self._total_reads, + "recent_readings": [round(r, 2) for r in self._readings], + } diff --git a/sethflix_theme.md b/sethflix_theme.md new file mode 100644 index 0000000..af93af9 --- /dev/null +++ b/sethflix_theme.md @@ -0,0 +1,133 @@ +# Sethflix Theme Context + +This file defines the standard "Sethflix" visual theme (Dark Mode with Orange Accents) for use in all web applications. + +## 1. Core Identity + +* **Theme Name:** Sethflix Dark +* **Primary Background:** Black (`#000000`) or Dark Gray (`#1a1a1a` / `#252525`) +* **Primary Text:** Light Gray (`#e0e0e0`) +* **Accent Color:** Orange (`#D35400`) +* **Hover/Active Color:** Lighter/Darker Orange (`#e65c00` / `#a84300`) +* **Border Color:** Dark Gray (`#333333`) or Orange (`#D35400` for emphasis) + +## 2. Assets + +* **Logo (Square/Favicon):** `https://storage.googleapis.com/sethfreiberg.com/sethflix/favicon.png` + * *Usage:* Sidebar icon, Favicon, Mobile Navbar. + * *Dimensions:* 55px width (sidebar), 32px-55px (navbar). +* **Full Logo (Login):** Same image used for login (`login.png`), typically scaled to 150px width. + +## 3. CSS Color Palette + +| Element | Color Hex | Description | +| :--- | :--- | :--- | +| **Global Background** | `#1a1a1a` | Main body, panels, modals, cards | +| **Sidebar/Navbar** | `#000000` | Navigation bars | +| **Panel/Card (Comfortable)** | `#252525` | Content containers, wells | +| **Primary Text** | `#e0e0e0` | Body text, headings | +| **Secondary Text** | `#cccccc` | Muted text, paragraphs in wells | +| **Accent (Strong/Bold)** | `#D35400` | Links, ``, Buttons, Active States | +| **Inputs/Forms** | `#2a2a2a` | Text inputs, search bars (Text: `#fff`) | +| **Borders (Subtle)** | `#333333` | Dividers, panel borders | +| **Borders (Highlight)** | `#D35400` | Images, Active Inputs | + +## 4. Reusable CSS Snippets + +### Global Resets & Typography +```css +body, html { + background-color: #1a1a1a !important; + color: #e0e0e0 !important; +} + +h1, h2, h3, h4, h5, h6, strong, b, a { + color: #D35400 !important; +} + +p, span, div { + color: #e0e0e0; +} +``` + +### Components (Cards/Panels) +```css +.panel, .card, .well, .modal-content { + background-color: #252525 !important; + border: 1px solid #333 !important; + color: #e0e0e0 !important; +} +``` + +### Forms & Inputs +```css +input, textarea, select, .form-control { + background-color: #2a2a2a !important; + color: #fff !important; + border: 1px solid #444 !important; +} + +input:focus { + border-color: #D35400 !important; + box-shadow: 0 0 5px rgba(211, 84, 0, 0.5) !important; +} +``` + +### Buttons +```css +.btn-primary, .btn-ghost { + background-color: #D35400 !important; + color: #fff !important; + border-color: #D35400 !important; +} + +.btn-primary:hover, .btn-ghost:hover { + background-color: #e65c00 !important; +} +``` + +### Navigation & Menus +```css +.navbar, .sidebar { + background-color: #000000 !important; +} + +.nav-link:hover, .nav-item.active { + background-color: #333 !important; + color: #D35400 !important; +} + +.dropdown-menu { + background-color: #1a1a1a !important; + border-color: #333 !important; +} +``` + +### Images +```css +img { + border: 2px solid #D35400 !important; +} + +.noborder, .logo-img { + border: none !important; +} +``` + +## 5. Mautic Specifics (Reference) +* **Sidebar Logo:** 55px width, 4px top margin, centered. +* **Navbar:** Flexbox centering, left-aligned logo with margin. +* **Alerts:** Dark background, left-border accent matching alert type color (Orange/Red/Blue/Green). + + +## Network Inventory +The master source of truth for all device IPs, LXC IDs, and service mappings can be found at: + on Node 173. + +## Network Inventory +The master source of truth for all device IPs, LXC IDs, and service mappings can be found at: + on Node 173. + +## Network Inventory +The master source of truth for all device IPs, LXC IDs, and service mappings can be found at: +`/root/network_inventory.md` on Node 173.