Thursday, September 17, 2020

(#38) RV Phone Home

 (#38) RV Phone Home

Making Connections

Part of the problem with a Computerized and Connected RV is the connected part. The promised ubiquity of wireless connectivity is still plagued with holes. Holes in coverage. 

What good is an RV loaded with Raspberry Pis doing their automation-thing if they can’t communicate with the outside world?


That’s a rhetorical question. The answer is “Not much”, of course.


Making A Connection

There are a gazillion (or thereabouts) commercial solutions to this. You’ve undoubtedly have a solution in your home. It’s called a WiFi Router. One end of the router has a cable that plugs into “The Internet”. The other end of the router has WiFi antennas that you can connect your computer(s) to.


The RV makes things a little more interesting. First there’s rarely a way to plug a “cable” into The Internet. Moreso if you’re rolling down the road; very hard to keep that wired connection to the Internet. RV owners sometimes invest in WiFi Extenders, or WiFi Repeaters to solve this.


One end of the WiFi Repeater connects, wirelessly, to another WiFi Router that, in turn, is wired to the Internet. For example, if you’re parked next to a Starbucks, your WiFi Repeater would work something like this:

 


Bob’s your uncle – your RV (and the computers inside) are connected to the Internet.


You can buy a WiFi Repeater.

And frankly you probably should.

It’ll be less work and less reading.


However, if you’re like me, and don’t want to pop $300 for something that should be $50, then you decide to roll your own.


Rolling your Own WiFi Repeater

You might be lucky enough to have an old, unused but still functional router lying around in the house. I did. Obviously, or this blog post would end right here.


I had a Netgear N750 (Model WNDR4300) going unused. This model has a couple of things going for it that’ll make it ideal to turn it into a WiFi Repeater:

  1. There are two antennas in the router – one for the 2.4GHz band and the other for 5GHz
  2. This router can run the OpenWRT firmware


Google up OpenWRT if you’re curious but it’s free and open software that will replace the Netgear software and unlock the full potential of your router.


There’s NO WAY I’m going to cover off installing OpenWRT.

Nope. If you mess it up, you could brick your router.

“Bricking” is where you screw up and render the router unusable. Turning it into an expensive “brick”.


No. Figure out how to install OpenWRT on your router if you wish.

The come back here.

If you wish.

 

Getting to the WiFi Repeating Part

OpenWRT makes it easy to turn the N750 into a wireless repeater.


What’s great about the N750 are the two wireless bands: 5GHz and 2.4GHz. You can use one band to “connect to Starbucks and out the internet” and use the other band to connect the computers in the motorhome.



I’ll quickly gloss over the steps to get things all connected, but briefly:

- in the OpenWRT setup screens you select the 5GHz radio and tell it to scan for WiFi networks.

- you pick the wireless WiFi network you want to join (e.g. Starbucks), type in the password for that network and click “Join”.

- you then flip over to the 2.4GHz radio setup screens and make it into an Access Point. This is very easy, and only needs to be done once. Give it a new SSID (it’s ‘OpenWRT’) by default. Make it password protected


Finally, For each RPi in the RV, you have it join the 2.4GHz network. And test that each Rpi can access the internet.

 

In the End

We’ve reused and old router and effectively created our own WiFi Wanderer, WiFi Explorer, WiFi Arranger. You get the drift.

In a subsequent post, I’ll cover off the OpenWRT setup in more detail. But rest assured, it’s not hard.

No, no I won't.  Because...


 

 

 

 


(#37) What a long strange trip it’s been 

 

RVs, Pandemics and Time



There are upsides to a pandemic. I’m not so callous as to gloss over the horrific impacts on people, the potential personal impact. But there are upsides. To name one, we’ve spent more time together as a family, than well, I can recall. Ever. And my kids are college age – the time when I’d expect them to be out more than in.




Another upside has been more time to work on side projects. Like making a home smarter with complex event processing (CEP) technology. So while it’s been months since I’ve written anything on this topic, it’s not been time passing without progress. Au contraire mon frère, there’s been much mischief afoot! Much raspberry-pi’ing to coin a verb.


Complex Event Processing

It was probably fifteen or so years ago when I was told about CEP technology while visiting Tibco headquarters. It was nearly ten years ago when I downloaded EsperTech’s Esper product and put together my own-non trivial project.


And as of today, my quest for a smarter home that leverages the power CEP still runs. With one tiny twist: the “home” part has become “motorhome”.









Can I make my motorhome less dumb?

Maybe.

Probably.


I've killed 12 months on this already. So let’s catch up on what I’ve done in that regard, what I’ve done to instrument the RV and leverage Esper’s CEP capabilities. There’s a lot to cover; I’ll tackle it in this order:

  1. RV Phone Home - Get the RV online! Reliable internet connectivity was a challenge. When the RV sits, it sits in a storage lot with one public access point accessible. Task 1 was to assemble a WiFi extender/repeater so the RV could “phone home”.
  2. With “phone home” complete, task 2 was to “Home - Phone RV” - reverse the connection. Make it so I could connect to the computers in the RV from the comfort of my home office.
  3. Make one RV computer a WiFi access point. All other computers in the RV would connect to this access point.
  4. Go IoT with more Sensors -- Scatter useful computers and sensor about the RV to gather data about the conditions. One would monitor the Solar Charge Controller, a second would be GPS enabled for geolocation information, a third would monitor conditions (temperature, humidity) in the coach cabin, a fourth would connect via ODB2 to the engine, and so on.
  5. Use IoT - MQTT to Publish Sensor Events. Have the sensors send their values to a broker inside the RV. The bridge the MQTT broker in the RV with my MQTT broker at home, so those values could make their way back to my desktop.
  6. Feed those sensor values into InfluxDB, a Time-Series Database. Use Telegraf to ingest the JSON formatted events, and Chronograf to create dashboards to display sensor data.
  7. Feed those sensor values as events into Esper, our Complex Event Processing engine.
  8. The coup de grâce, build up a series of Esper queries to construct “Meaningful Conclusions” from the events and patterns.




So next up – Putting the RV online.

(#36) Solar Charge Controller Update   

It's Dead, Dammit! 

Sometime around the middle of 2019, I noticed that my EPSolar Landstar 1024B controller had stopped working. I'm not sure why but it was an inexpensive proof-of-concept that showed I could command the controller and get the data out of it I wanted.


That controller, the LS1024B was also a PWM based model and only 10A.  A great baby step but not a long term solution.  So, after some thought I decided to buy another EPSolar product. [ And an extended warranty. ]



August 6th 2019, I bought the EPEver Triron 3210N Controller. This is an MPPT 30A controller and should support my projected needs for the RV.



Most of the code written for the LS1024B worked on the 3210N. EPEver/EPSolar technical support sent me a new document that outlined the new protocol.  There were a few changes, a handful of deletions and two handfuls of additions.  But it didn't take long to have the code working again.


New - A EPSolar Library

I took the time to move the base code into a library (shared and static).  That seemed like a useful step.



I'm content with the library design but already see a few things I'd do differently. The 'pound-defines' (#define) are a first attempt to abstract out the dependency on knowing Modbus. 

Yes, you'd always need to link with the libmodus library, but at least you wouldn't have to know anything about the modbus context object.


Client Applications

With the library done, the next application to recreate was the application that polls the Solar Charge Controller (SCC) for status and publishes MQTT messages to the broker.

This application can also receive MQTT based commands and change parameters in the controller.

This application is written in C and runs on a Raspberry Pi Model B+ connected by a EPEver Branded RS485/USB cable to the controller.

Status messages are published to the broker every minute.


Curses! Foiled Again

The second application was cobbled together quickly and provides a simplistic, curses-based UI for displaying SCC values and changing parameters.

Home

Here's the startup, Home Screen with the essential data displayed:

 


At a glance are data from the Solar Panel (PV), the House Battery and any load that is connected to the MPPT Controller.

The controller has a connection for an external temperature sensor. And the controller keeps tally of the stats around generated and consumed power.

One thing I noticed after short usage was that the internal clock in the controller drifts quickly.  If this was an AC based appliance, I'd suspect a 50/60Hz issue. But it's not and I'm not sure why the controller time falls behind so quickly.

 

Battery

Pressing 'B' brings you to the Battery Screen:

Battery parameters are modified here.  These are the values fo my 100AH Group 27 Sealed Lead Acid battery.

Load

Press 'L' for the Load Screen:
 

The controller has a four useful modes for turning the connected load on and off. There's full manual mode. Then there's sunrise and sunset, timers and a combination thereoff. 

The last one is hard to put into words. The manual has a pretty good picture of how it works.





Note that Dawn/Sunrise is not defined by a time but instead by a minimum threshold voltage from the solar panel. In this case, when the panel is putting out 5.0V (or better) the controller calls that "Dawn".


And the same for Dusk/Sunset. When the panel voltage output is 6.0V or less, then that means it's dusk.


[ Yes - these are the default values which makes you wonder what happens when the panel voltage is 5.5V! ]

Finally, note that if you chose to use the 'Dusk Plus Timer' mode you need to set the "Time of Night" parameters that will define Dawn.


Device / Controller

Press 'D' to see Device (the MPPT Controller) settings:

The controller can turn itself off if it gets too hot, can stop charging if the battery gets too hot, can stop draining if the battery is too cold.

You can see that the two clocks have drifted off by over an hour after about 10 days.

In a future post we'll discuss the RS485/USB adapter in more detail and the steps I took to rebuild the driver as a kernel module.


Monday, February 17, 2020

(#35) What's the Fun in That (Part Three) 

The Software   


Part one of the series "What's the Fun in That" constructed an elaborate electrical timer from a Raspberry Pi and an 8 Channel Relay board.

Here I'll quickly cover the software side.  There are a gazillion projects out there that will show you how to connect Relay Boards to the GPIO pins on a Raspberry Pi.  And, once connected, energzing the relays is simply a matter of driving the GPIO pins Low or High.

But here are a few code snippets that might help you along the way. We're doing this in Python. And we're using the RPi.GPIO library:


Import RPi.GPIO

    
import logging
import RPi.GPIO as GPIO
import time
           
class ChannelManager(object):
                             
    # ---------------------------------------------------------
    def __init__(self):
        self.socket_pin_assignments = {
            1: 2,
            2: 3,
            3: 4,
            4: 22,
            5: 10,
            6: 9,
            7: 27,
            8: 17}

   
 The "socket_pin_assignments" dictionary maps a socket number to it's connected GPIO pin number. The pin number depends on how we've wired up the relay to the Raspberry Pi.  If you choose different pins, or a smaller relay board then your values would be different.

Before going much farther, we set the library to use BCM style pin numbering and we tell the library we're going to be using the GPIO pins as outputs:


GPIO.setup()

    
try:
    GPIO.setmode(GPIO.BCM)
    for key, value in self.socket_pin_assignments.items():
        logging.info("Setting socket {} pin {} to 

                      GPIO Output".format(key, value))
        GPIO.setup(value, GPIO.OUT)
except Exception:
    logging.exception('Exception in setting up GPIO ports')

    


The Clapper!

When an "On" message comes in, this function is called:
    
def socket_on(self, socket_number, duration=900):
    if (socket_number <= 0 or socket_number > self.max_socket_num):
        logging.error('Invalid socket number {} passed to the on

                      command'.format(socket_number))
        return
            

    pin_number = self.socket_pin_assignments[socket_number]
    try:
        GPIO.output(pin_number, GPIO.LOW)
        self.socket_states[socket_number] = "on"
        self.socket_on_time[socket_number] = time.time()
        self.socket_on_max_duration[socket_number] = duration
    except Exception:
        logging.exception('Exception in setting socket {} 

                           pin {} to GPIO.LOW'
                          .format(socket_number, pin_number))
          


When an "Off" message arrives:

    
def socket_off(self, socket_number):
    if (socket_number <= 0 or socket_number > self.max_socket_num):
        logging.error('Invalid socket number {} passed to the off

                      command'.format(socket_number))
        return
            

    pin_number = self.socket_pin_assignments[socket_number]
    try:
        GPIO.output(pin_number, GPIO.HIGH)
        self.socket_states[socket_number] = "off"
        self.socket_on_time[socket_number] = 0.0
        self.socket_on_max_duration[socket_number] = 0
    except Exception:
        logging.exception('Exception in setting socket {} 

                           pin {} to GPIO.HIGH'
                          .format(socket_number, pin_number))
          

That's about all there is for 'the meat' of this software. In my code I also setup MQTT to send and receive messages (using paho-mqtt).

I use ZeroConf to locate the MQTT Broker dynamically (using zeroconf).




Meltdown Prevention

And I have a function that wakes up every five seconds to check if a socket has been left on for too long.  [ When sending an 'on' command, you also specify the maximum duration you want it left on. ]

            
def check_for_duration_exceeded(self):
  logging.debug('Checking for time exceeded on all on sockets')
  time_now = time.time()

  for socket_num, pin_number in 

            self.socket_pin_assignments.items():
  if self.socket_states[socket_num] == 'on':
     max_seconds_on = self.socket_on_max_duration[socket_num]
     total_seconds_on = time_now - self.socket_on_time[socket_num]
     if (total_seconds_on > max_seconds_on):
        logging.warning('Maximum On Time reached for 

                         socket {}. Sending off command'
                         .format(socket_num))
        self.socket_off(socket_num)

        

The MQTT Messaging

If nothing else, I'm committed to being Event Driven and Message Based. So at the core of the functionality are a handful of JSON formatted messages sent over MQTT.


Clap On!

To turn a socket on, send this message to the MQTT Broker:

   {
     "topic":"RELAY/RV8.1/CMD",
  
"datetime":"2020-02-13T13:19:16-07:00",
  
"id":"RV8.1",
  
"channel":3,
  
"command":"on",
  
"duration":3480
   }

Where Channel is the Socket Number [ 1..8 ], the command is "on" and the duration is the maximum number of seconds you want the socket left on.

Clap Off!

The off command is almost identical, with the duration parameter ignored.
   {
     "topic":"RELAY/RV8.1/CMD",
  
"datetime":"2020-02-13T13:21:21-07:00",
  
"id":"RV8.1",
  
"channel":7,
  
"command":"off",
  
"duration":0
   }

There are two more commands "allon" and "alloff" which affect all of the sockets with a single command.

The TPS Report

Lastly, the system publishes a status message, every minute with the current status of all sockets:

  {
     "topic":"RELAY/RV8.1/STATUS",
   "datetime":"2020-02-13T13:23:00-07:00",
  
"id":"RV8.1",
  
"states":[
         {
         "duration":0,
         "state":"off",
         "channel":1
         },
 
     {
         "duration":0,
         "state":"off",
         "channel":2
         },
     
{
         "duration":3480,
         "state":"on",
         "channel":3
         },
<etc...>
      {
         "duration":0,
         "state":"off",
         "channel":8
      }
    ]
  }