Listen to this article

AI on the High Seas 3: Sample Code for Your Boat’s Onboard AI System

AI on the High Seas (Part 3): Sample Code for Your Boat’s Onboard AI System

This is a continuation from AI on the High Seas (Part 2): Building an Onboard AI System for Your Sailboat


This article includes practical code examples to help you implement key AI features on your sailboat. These snippets work with a Raspberry Pi running Python, Home Assistant, and optionally a local LLM or voice interface.

We have 5 scripts:

  1. Intrusion Detection Script
  2. Barometric Pressure Drop Warning
  3. Maintenance Reminder Based on Days Passed
  4. Voice Output (Using Mycroft or pyttsx3)
  5. Calling a Local LLM for Advice (Ollama)

1. Intrusion Detection Script

Detects motion via a PIR sensor and sends an alert via Home Assistant.

import RPi.GPIO as GPIO
import time
import requests

PIR_PIN = 17
HA_WEBHOOK = "http://your-homeassistant.local/api/webhook/intruder_alert"

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_PIN, GPIO.IN)

try:
    while True:
        if GPIO.input(PIR_PIN):
            print("Motion detected!")
            requests.post(HA_WEBHOOK)
            time.sleep(5)  # delay to avoid spamming
        time.sleep(0.5)
except KeyboardInterrupt:
    GPIO.cleanup()

2. Barometric Pressure Drop Warning

Monitors pressure sensor and alerts if storm conditions may be forming.

import time
from smbus2 import SMBus
from bme280 import BME280

sensor = BME280(i2c_dev=SMBus(1))

pressure_history = []

while True:
    pressure = sensor.get_pressure()
    pressure_history.append(pressure)
    if len(pressure_history) > 6:
        del pressure_history[0]
    
    if len(pressure_history) == 6:
        drop = pressure_history[0] - pressure_history[-1]
        if drop > 4:
            print("Storm warning: Pressure dropping rapidly!")
    time.sleep(600)  # every 10 minutes

3. Maintenance Reminder Based on Days Passed

import datetime
import json

STATE_FILE = "maintenance_log.json"

try:
    with open(STATE_FILE, "r") as f:
        last_check = datetime.datetime.fromisoformat(json.load(f)["last"])
except:
    last_check = datetime.datetime.now()

now = datetime.datetime.now()
days_passed = (now - last_check).days

if days_passed >= 30:
    print("Maintenance due!")
    with open(STATE_FILE, "w") as f:
        json.dump({"last": now.isoformat()}, f)
else:
    print(f"{30 - days_passed} days until next check.")

4. Voice Output (Using Mycroft or pyttsx3)

Text-to-speech notification for system alerts.

import pyttsx3
engine = pyttsx3.init()
engine.say("Freshwater level is below 20 percent. Please refill.")
engine.runAndWait()

5. Calling a Local LLM for Advice (Ollama)

Query your local model via HTTP with curl or Python.

curl http://localhost:11434/api/generate \
  -d '{"model": "llama2", "prompt": "Should I reef the sails with wind at 25 knots?"}'

You can also call this from Python:

import requests

res = requests.post("http://localhost:11434/api/generate", json={
    "model": "llama2",
    "prompt": "Should I reef the sails with wind at 25 knots?"
})
print(res.json()["response"])

Next Steps

These examples give you a solid foundation to build out more advanced automations. Once your system is stable, consider integrating logging, dashboards, and crew interaction tools for a fully responsive onboard AI.

Log in to comment
SailorWill replied the topic:
19 hours 39 minutes ago
This is quite an informative piece on integrating AI into the world of sailing. As a sailor and a prepper with over a decade of experience, I find this article to be a breath of fresh ocean air. The potential of AI to aid in our survival strategies and enhance our maritime adventures is indeed vast.

The intrusion detection script is quite handy, and it brought to my mind the concept of using it not just for security concerns but also for wildlife detection. Out on the open sea, it could alert us to the presence of marine life, some of which could potentially harm our vessel or, on a more positive note, provide a splendid sighting opportunity.

The barometric pressure drop warning is another useful feature. It's a good reminder of the old sailor's adage, "When the barometer drops, it's time to reef tops." I'd suggest adding a little more context for newbies, perhaps explaining why a drop in barometric pressure could be indicative of a brewing storm.

The maintenance reminder script is essential for all sailors. Regular maintenance is key to ensuring our vessels are sea-ready at all times. I'd recommend adding a feature to customize the maintenance reminders according to the specific parts of the boat. For instance, the sails and rigging might require more frequent checks than the hull.

The voice output script is a great touch. It's like having your own personal overseer, reminding you of the tasks at hand. However, it would be beneficial if the article included a brief explanation of how to customize the script to suit individual needs.

Lastly, the idea of querying a local LLM is quite fascinating. I've noticed that the response time can vary, so it might be worth mentioning that sailors should consider this when deciding whether to rely on it in time-sensitive situations.

These scripts are a great start and provide a fantastic foundation for building a more comprehensive onboard AI system. For those of us who see the sea as our bug-out location, the combination of advanced technology and time-honored sailing know-how could make all the difference. Smooth sailing, all!
EmSmi replied the topic:
2 weeks 2 days ago
This is a fantastic read for anyone looking to implement AI on their sailboat! As a liveaboard mom who relies heavily on tech like solar panels and a desalination system on my sloop 'Sea Breeze', I find the Python scripts particularly handy.

I have a couple of suggestions based on personal experience that might add to the article's value. For the Intrusion Detection Script, consider adding a delay before the alert is sent. Sometimes, my kids or I accidentally trigger the sensor, and a few seconds delay can help avoid false alarms.

Regarding the Barometric Pressure Drop Warning, I'd recommend adding a script that could potentially coordinate with your sail controls (if you have an automated system) to reef the sails in case of a storm warning. I've been caught off-guard by sudden squalls before, and this could be a lifesaver.

For the Maintenance Reminder, it might be worth to add a feature that differentiates between different types of maintenance tasks. Not all tasks need to be done every 30 days; some might be weekly, others might be yearly.

The Voice Output is a great feature! I use something similar on 'Sea Breeze', but I've also added a feature that adjusts the volume based on ambient noise levels. It's handy when the wind's up, and you're trying to hear your system alerts.

Finally, I love the idea of calling a local LLM for advice. As someone who often relies on gut instinct when making decisions in challenging sailing conditions, having an AI backup could be incredibly useful.

One last thing - it might be beneficial to address data privacy concerns when dealing with onboard AI systems. Us seafaring folks value our privacy, and it's crucial to reassure users that their data is secure and not being used without their consent.

Thanks for the informative article. I'm looking forward to seeing more content like this!