RaspberryPi on AWS IoT – MQTT simple PubSub Example

Simple RaspberryPi B+ with BMP180 and LED on GPIO22 for demonstration of AWS/IOT with MQTT.  The following code was modified from the Connecting your RaspberryPi to AWS IoT tutorial.

'''
/*
 * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
 '''
 
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import logging
import time
import argparse
import json
 
#import for GPIO Usage on RaspberryPi
import RPi.GPIO as GPIO
#Pins for LED Example
GPIO.setmode(GPIO.BCM)
GPIO.setup(22,GPIO.OUT)
 
# Import / Setup  BMP Sensor 
import Adafruit_BMP.BMP085 as BMP085
sensor = BMP085.BMP085()
 
AllowedActions = ['both', 'publish', 'subscribe']
 
# Custom MQTT message callback 
# Added Temp info from BMP Sensor and logic to turn on/off led
# when temp above 20.2C 
def customCallback(client, userdata, message):
    print("Received a new message: ")
    print(message.payload)
    Mytemp = json.loads(message.payload)
    print("MY TEMP IN THE OFFICE: ")
    print (Mytemp['Temp'])
    if (Mytemp['Temp'] > 20.2):
        GPIO.output(22,1)
    else:
        GPIO.output(22,0)
 
    print("from topic: ")
    print(message.topic)
    print("--------------\n\n")
 
# Read in command-line parameters
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint")
parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path")
parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path")
parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path")
parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override")
parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False,
                    help="Use MQTT over WebSocket")
parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicPubSub",
                    help="Targeted client id")
parser.add_argument("-t", "--topic", action="store", dest="topic", default="sdk/test/Python", help="Targeted topic")
parser.add_argument("-m", "--mode", action="store", dest="mode", default="both",
                    help="Operation modes: %s"%str(AllowedActions))
parser.add_argument("-M", "--message", action="store", dest="message", default="Hello World!",
                    help="Message to publish")
 
args = parser.parse_args()
host = args.host
rootCAPath = args.rootCAPath
certificatePath = args.certificatePath
privateKeyPath = args.privateKeyPath
port = args.port
useWebsocket = args.useWebsocket
clientId = args.clientId
topic = args.topic
 
if args.mode not in AllowedActions:
    parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions)))
    exit(2)
 
if args.useWebsocket and args.certificatePath and args.privateKeyPath:
    parser.error("X.509 cert authentication and WebSocket are mutual exclusive. Please pick one.")
    exit(2)
 
if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath):
    parser.error("Missing credentials for authentication.")
    exit(2)
 
# Port defaults
if args.useWebsocket and not args.port:  # When no port override for WebSocket, default to 443
    port = 443
if not args.useWebsocket and not args.port:  # When no port override for non-WebSocket, default to 8883
    port = 8883
 
# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
 
# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
if useWebsocket:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath)
else:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
 
# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
 
# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()
if args.mode == 'both' or args.mode == 'subscribe':
    myAWSIoTMQTTClient.subscribe(topic, 1, customCallback)
time.sleep(2)
 
# Publish to the same topic in a loop forever
loopCount = 10
while True:
 
    Temp = sensor.read_temperature()
    print ("TEMP: " + str(Temp))
    if args.mode == 'both' or args.mode == 'publish':
        message = {}
        message['Temp'] = Temp
        message['sequence'] = loopCount
        messageJson = json.dumps(message)
        myAWSIoTMQTTClient.publish(topic, messageJson, 1)
        if args.mode == 'publish':
            print('Published topic %s: %s\n' % (topic, messageJson))
        loopCount += 1
    time.sleep(2)

 

python basicPubSub.py -e YOURAWSIOTSHADOW.us-east-1.amazonaws.com -r root-CA.crt -c MyRasp.cert.pem -k MyRasp.private.key

I am still learning the AWS IoT basics and have posted this as a reminder to myself as to how it got setup. I planned on refining this into tutorial but really did not see the need as the AWS Samples are pretty good. Connecting your RaspberryPi to AWS IoT  is your best place to start.

American Beauty 3125 Soldering Iron

Found this soldering iron while organizing the shop.  Not sure where/when I got it.  Must have been an auction box lot.  Looked it up and found American Beauty is still going strong.  Was able to pickup some replacement tips and set screws (yes, could have got those anywhere but was too easy not to order them with the tips).

It heats up great and really gets the job done.  Posted a few pics of some initial tinning.  Certainly an industrial / production type iron, no bells and whistles, not even a switch.  Going to try tinning some thin cable (bicycle – brake and shift).

Baldor 1/3 hp Bench Grinder Cleanup

The recent Foley Belt Sander/Grinder went so well I could not help myself.  Eyed this one from the roadside at local residence close to home.  Been exposed to the weather for almost too long.  Plugged her in and she fired right up and in classic Baldor form took 10 minutes to stop spinning after turning off.  Was not going to re-paint but now I am in deep so what the heck.  Came apart relatively easily (nice to work on quality products).  Missing side covers – may have to make some or deal without.

Foley Belt Sander Grinder Model 371

Nifty little 1×42Belt Grinder/Sander made by Rockwell for Foley.  It is basically the same as the Rockwell 31-350.  Freebie from a barn clean-out (Thanks MB!).  Took some scouting around for replacement wheels but alas a shout out to James Liechty (jimliechty@yahoo.com) who has sourced replacement pulleys and other parts for these and offers them at very reasonable prices.

Took her apart, cleaned up all the saw dust cake, installed new wheels for sanding belts, replaced one v-belt pulley, replaced the power cord (not done yet) and that was pretty much it. My initial thoughts when it showed up were it was pretty flimsy construction and the plastic wheels made me skeptical but all those thoughts have passed now that it is up and running.  Runs great, hit a few pieces of metal with it, no problem.

Refurbish Complete
Refurbish Complete
Manual
Manual

First Plunge Type Form Tool for Lathe

Messing around on the turret lathe got me re-interested in creating some forming tools.  I have watched enough videos to be dangerous and gave it a shot.  First tool is pretty crude but I was glad to see it cut as well as it did.

Cut shape on mill with tapered end mill and finished up on a grinder. Got cherry red with torch and quenched with water (I know, more work to do studying heat treating – but it cuts). Finish not great but I spend zero time on the honing/sharpening.

Jack Taylor Tandem – 50th Anniversary Edition

The tandem thing has been bugging me for a while, Jamie’s 650b Conversion, Tom’s custom Ibis “Dumpster Dive” and my high school memories of Pete and I riding Mt. Wachusett and descending “Mile Hill” on a Paramount Tandem loaned from George Gamache.

Also bugging me was this Jack Taylor that Wayne has had tucked away at Velo Classique for some time.  I recall helping him move it there.

Making some minor modification to this Jack Taylor 50th Anniversary Edition tandem to entice the wife to take some leisurely rides on the W&OD or the C&O Canal.  Work in progress but addition of wider tires, fresh brake pads, fender removal and addition of riser bar for stocker is looking good.

 

Certiflat Welding Table – Complete

All Done!  Pretty happy with the final outcome of the Certiflat Welding Table kit.  Took a bit of help from their support for me to get it flat but other than that pretty nice addition to the shop.  Working on clamps now, I am turning down some 3/4 (don’t have any 5/8 lying around – and I have a lathe) for the pins and attaching some cheap harbor freight quick clamps to them – proto-type seems solid enough – usage over time will tell.

Certiflat Welding Table – Took the Plunge

Certiflat Welding Table

After years of working off the floor, make-shift benches and everything in between I ordered a Certiflat 36×48 Pro Top Kit.  Yup, felt a bit foolish for not having built my own over the years but my work never has been traditional bench/layout work.  Recently I have had been dabbling in  some fab work requiring a bit more precision.  So I took the plunge….I will do my best to chronicle the purchase/ship/assemble and usage of the Pro Top Table.

First: old faithful – lots of work done on this setup (well, there has been lots of these types over the year, this is the latest one)

Old Welding Table

Enter weldtable.com Certiflat Pro Top Kit w/Legs (shameless referral link)

Ordering was straight forward, there follow up with referral program was quick, almost annoying but at the same time understandable.  Took about 6 days until initial ship.  Shipping for me was UPS and tracking was spot on.  Packaging was done well, see pics below. (have seen some post where folks got damage tables)

Fresh off UPS Truck

Phone a Friend

Pretty damn heavy and very awkward to get out of box and onto saw horses.  Call a friend makes easy work of that!  Like I said, I have heard stories of bad packaging but this is pretty stable and had no issues.

Clean up and clamp up

Cleaned up all the pieces from left over oil and grit from the manufacturing process before clamping in place.  Note, need more clamps but so far so good and all the “light tests” are looking good.  Did have one troublesome rail (more light test failures than all the other parts of the table) and will take it off and double check for burrs and what not.

 Tacking it up! Oh Shit!

Things have gone south at this point, sent message to the folks at weldtables.com for some assistance.  I have tacked the table after removing all the gaps (no light between table and ribs) and then flipped it over to inspect for “flatness”.  Straight edge on the short 3′ side was dead on when checked all the way across from one end to the other!  Very excited at this point.  Checking the long 4′ length is a different story.  On the good end (the very edge) was real good although actually not as solid as the 3′ inspections.  When checked in the middle of the table the gap was about 3/16″ and on the opposite end it was 1/4″ off — EEEK!  There are not gaps against the table and ribs so I have not way to pull any bow out at this point as the table top is completely flush with the ribs.  Gap pics below to give an idea what I am seeing.  Hopefully the folks at weldtables let me know I did something goofy and I can fix it easily.  Maybe this turns into a “don’t do it this way” tutorial.

 Found what I think is the issue.  I cut most of the tacks out – rookie mistake I did put a few tacks in spots that I could not easily cut.  One of the longer ribs is way out of wack.  Pics below.  It has a bow in it and appears to be wonky with respect to width.

I assumed the ribs (as advertised) where accurate but the ones I got appear not to be so. So clamping to the ribs and removing the daylight between them and the top is no guarantee that the table is flat.

Going to request a set of rails/ribs from weldtables and go from there.

FWIW – I measured the other “good” rib in a similar fashion and they where within .003 – not off .021.

Will keep posted on weldtable response:

FLAT!

So after exchanging a few email with the folks at weldtables.com I learned the error of my ways.  While I still need to look at the ribs again to understand how they work exactly I did get the table flat despite discrepancies in the ribs as pictured above.  Basically clamping the untacked ribs and turning the table upright was the first step.  With use of an oak board and some “heavy persuasion” I knocked out the high spots.  Which basically seemed to just really tighten up the slot and tabs and maybe bring back the memory of the top.  Took some moving around the table with the straightedge and some fine tuning taps but all is good and flat with the table now!  More pics to follow and  leg installation coming soon…

First Wearable?

Came across this advertisement in a 1896 Bicycle News .  Certainly the earliest Wearable I have seen.  I did dig around some other ephemera I have to see if I could spot some more but came up empty.  Early 1900 Youth Companion thru 70’s Electronic Mags showed no signs of anything similar.