Launching a Flask Web App on Startup

flaskThe first few experiments with Flask has been successful. A simple user interface can be created in HTML and accessed from local as well as remote clients over HTTP. One of the downsides bit us today: a web app isn’t as easy to launch as a native local application. When running locally, we still need to get two parts up and running: the server-side code and the web browser pointing to http://localhost.

raspberry-pi-logoThis is especially problematic when the desire is to launch the app on power-up of the Raspberry Pi 3 that will run the server side. “Run on startup” is one of those tasks that have many different approaches across different flavors of Linux. Each with their advantages and disadvantages, benefits and gotchas.

The first attempt is to write a shell script that launches the Flask web server and the Chromium web browser. This works when executed interactively at the command line logged in as the default user pi. But it didn’t work when executed as a cron @reboot job, probably something to do with the fact it would run as root.

The next effort led to Raspberry Pi documentation, which pointed to the file /etc/rc.local. We seem to have better luck here – the Flask web server does launch but Chromium web browser still did not.

Further hunting eventually found this page for setting up a Raspberry Pi running Chromium web browser as a web kiosk. Not quite the project at hand, but close enough for the answer to be applicable. This meant leaving Flask startup in /etc/rc.local and editing the file /home/pi/.config/lxsession/LXDE-pi/autostart to have it launch chromium-browser with the parameter --kiosk http://localhost:5000/

Upon power-up, this Pi will now launch Flask web server and Chromium web browser to point at that server running on the same device. It works, but it’s not clear why these hoops were necessary. It’s pretty bewildering for a beginner to try to understand the why behind all these different startup mechanisms. A few hours of reading (sometimes contradictory) documentation did not make the situation any more clear. Sadly, time constraints dictate that we can’t get to the bottom of this issue today. Perhaps later.

Exploring Flask, a Python Web Framework

flaskToday’s exploration centers around Flask, a framework for building web sites with the Python programming language. The motivation was a new project that will be discussed separately, the important detail for now is that it needed to interact with some existing Python libraries and desired a user interface accessible from multiple different (and separate) devices. It seemed to make sense to turn the central device into a web server and expose the user interface to its clients using HTML.

There had been previous explorations into writing web server software using Ruby on Rails, which is not the best fit for this project. The first issue is the language – we need to talk to a Python library and there’s no need to jump through language translation layers for a simple project. The second issue is complexity – Rails is a full MVC framework for building an app on a database and we don’t need that here, either.

If we wanted the Python equivalent to Ruby on Rails, the popular choice of the day is Django. But since we don’t, Flask is the lighter-weight framework we’ll play with today. Sometime in the future, when a project is right for Django, we’ll explore using the right tool for the job.

Flask is a thin layer that’s a short step above having to call Python’s HTTP and URL classes directly, and can be very quick to get started.  A simple Hello World type of app requires only a single Python file and a few lines of code, no database configuration and project generation necessary. The developer builds up from this simple foundation. This is great for keeping things simple and easy to work with. For the most part, features that a developer would want can be added piecemeal.

The downside is that Flask also skips out on a lot of web practices that aren’t explicitly features, but are very nice to have by default. For example, the default Ruby on Rails generator for HTML <form> includes a token to prevent cross-site request forgery. This is not explicitly a feature a developer would think of adding, and could easily get overlooked especially when the forms are generated manually. Fortunately most of the Flask add-ons to generate forms – like this one – automatically includes CSRF protection.

Some caution would be warranted if the Flask application is going to be a public web site, but for a local network project prototype it should be good enough.

Twitter API Newbie Wades Into The Pool

Twitter DeveloperTwitter trends are easy to follow by searching for the hashtag. The default view given by Twitter shows the most popular tweets with that tag, and there are options to see the most recent tweets first, or browse them by photo, etc. But what if someone wants the tweets organized another way? Fortunately Twitter knows they can’t cover everybody’s desires and offers a developer API for those with creative ideas on tweets.

Twitter’s API is a “RESTful” design. It follows many of the ideas of REpresentational State Transfer (REST) but not strictly adhering to all of it. Functionally, it is built around HTTP GET and POST requests and returns information in the text-based JavaScript Object Notation (JSON) format. The details of those HTTP requests – and the JSON that it retrieves – are documented on Twitter’s developer site.

Before the aspiring Twitter app author can get anywhere, though, one needs to register with Twitter for access to these APIs. Once an app is registered, it is assigned a set of secret access keys and tokens. This allows Twitter to monitor usage and limit/disable Twitter access by individual applications.

Once registered, the code experimentation can begin. As a RESTful API communication via JSON, any web-friendly development framework can be used. (And if it is not web friendly… why would it have anything to do with Twitter?) As a starting point, Twitter has a non-exhaustive list of libraries that cater to different programming environments.

Out of this list, Python-Twitter was chosen as the first step into this world. Python language is fun and easy to experiment with. Python-Twitter installs easily via Python’s pip package manager. And yes – it also happens to be the first entry on the list.

A few commands into Python interactive console was rewarded with immediate results, though sadly also a few issues. Text of some tweets were truncated. Perhaps this has something to do with the recent increase in Twitter’s character limit? Whatever the root cause, it is tracked as an open issue in Python-Twitter’s repository.

The first few search queries returned only 15 results, even when there were definitely more than 15 answers. This turned out to be the default limit which is easily increased up to 100 results per search query. Going any further, unfortunately, is not possible with the standard search API. As of a few months ago, the only option to do more is to subscribe to the very expensive Twitter Enterprise API. This is out of the question for a hobbyist! Fortunately people have already complained and this past November Twitter responded with a premium search API to bridge the gap. Even though it is free, access is restricted so a registered developer has to apply for access.

Even if access is obtained, premium search is a new feature accessible via a new endpoint that is not yet supported by any of the Python libraries on Twitter’s list. Searching with a unique part of the API URL (“30day”) found this Python search tweet API that might be worth a look. If it doesn’t fit the bill for whatever reason, it might be time to build a custom solution.

Old ElectriFly Triton Sheds Light On Battery Condition

Today’s enlightenment comes courtesy of an old ElectriFly Triton battery charger unearthed from the dusty equipment shelf. This particular charger was purchased years ago to feed an interest in electric remote-control aircraft. At the time, the RC aircraft field was in a period of transition. The lowest-cost aircraft came with NiCad batteries, the mainstream used NiMH batteries, and the premium segments started adopting lithium-ion chemistries. To work in this world, the charger is designed to be used out at a remote control air park, hence it was designed to run on a 12 volt lead-acid battery instead of an AC outlet that might not be at the airfield.

Born into this confusion, the Triton charger was a jack of all trades. It knows how to properly charge all of the above types of batteries. It even has the capability to do a charge/discharge cycle to measure capacity. The latest models appears to have picked up even more features, but this old one is already on hand and can tell us interesting things.

Triton was first used to quantify behavior of an old 12Ah lead-acid battery dug up for solar panel investigation. It had discharged down to 6V while in storage and its voltage curve did not behave as expected. The good new is that even degraded, Triton deemed it within acceptable behavior range for a lead-acid battery. The bad news: Triton discharge test added up to only about 3.5Ah of usable capacity remaining out of the original 12Ah. There might be interesting projects where a degraded lead-acid battery can be useful, but it’s equally likely to end up in battery recycle.

After the old lead-acid battery was examined, the Triton was employed for the NiCad battery cells pulled out of the recent Dustbuster project. These cells suffered from chronic overcharging and exhibited depressed voltage levels when trying to deliver the current demanded by the Dustbuster motor. This condition might possibly be cured by individually charging and discharging the cell multiple cycles according to NiCad best practices, but that didn’t seem worth the expense of buying a NiCad charger/discharger. Fortunately, with the rediscovery of the Triton, we now have one. We’ll see if these NiCad cells can be recovered to a point to be useful for future projects, or if they should just go into battery recycle.

Triton NiCad

DSO 138 Simple Case by chibikuma2

The DSO 138 purchase was ultimately decided by seeing one in person, assembled by a local maker. That unit was first encased in an acrylic case, which cracked under use and was replaced by a 3D-printed case. Learning from the pioneer’s experience, I’ll skip the acrylic case and go straight to the 3D-printed one. If it works out, I’ll have something useful to protect the DSO 138. If it doesn’t, at least I could see one in action and decide what improvements to make.

The printer is the Monoprice Maker Ultimate, and the STL files were sliced into G-Code using Cura 3.1, printed on top of a Cura-generated raft.

DSO138 Case Bits

The author of this particular case is Thingiverse user “chibikuma2“. And the dimensions of the design looked good – all the pieces lined up well with parts on the DSO 138. The top and bottom parts of the case is held by friction. There were no fasteners and no clasps or hooks. 3D printers with loose XY accuracy may have problems creating this tight fit – if the XY “ooze” is too large, the pieces would not fit together at all. And conversely, if the printer under-extrudes, the two halves would be too loose to hold together.

The fit is good enough on the Maker Ultimate printer to fit together tightly. Once assembled, a putty knife or similar tool would be needed to pry the halves apart again.

The other printer performance dependency is first-layer performance. The labels for the controls in this design were done as lettering recessed into the surface. For these words to be legible, the first layer must be accurately positioned since slight movements are enough to spoil the lettering. Cura’s raft is what I usually use when first layer is important, sadly in this particular case it was not enough.

DSO138 Case Reset

The lettering is cosmetic, but there’s also a functional requirement for first layer precision: the 3D printed sliders that cap over the multi position switches on the DSO 138. The square hole at the base must match up to the square peg on the switches. If the holes are too large, there will be unpleasant slop in switch operation. If the holes are too small, the slider would not fit. Again this printer fell short of ideal, and had to be cleaned up with a small sharp blade.

DSO138 Case Slider

This is a decently functional case for the DSO 138, but this experience has motivated thinking towards creating a different design. Some items on the feature wish list are:

  • Move away from 3D-printed lettering. We have a label maker and we’re not afraid to use it.
  • Expose the loop of wire that generates the test square wave form.
  • Include a battery pack to supply the 9-12V DC power, with associated auxiliary components like an on/off switch.
  • A removable screen cover to protect the screen while in transit.
  • Storage for the probes.

DSO 138 Oscilloscope Kit by JYE Tech

An oscilloscope has been on the tool wish list for a while, but good ones are really expensive. But occasionally a simple basic scope would have been better than no scope at all, which is where today’s project comes into the picture.

JYE Tech makes the DSO 138 oscilloscope kit perfect for electronics hobbyists who can make use of a simple scope and also willing to put in the time and effort to assemble one out of a kit. The kit is available at a very low-cost, a fair exchange for making their customers do their own assembly.

This product is popular enough to spawn counterfeit copycats, which was a concern. Not just out of fear of a problematic product, but also the desire to support the original authors. Fortunately JYE Tech offers the option to send in the serial number for authenticity validation. The serial number of this unit purchased from Amazon vendor Kuman checked out as authentic.

There are two versions of the kit that differ by their treatment of surface-mount components: pre-installed or not. This particular example is the variant with surface mount pieces already installed, the customer just has to take care of the remaining through-hole parts. All those parts to be soldered came in a single bag and had to be sorted and identified before assembly could begin.

DSO138 parts sorted

The instructions were straightforward enough for someone already familiar with basic electronics soldering. The only complaint with this kit is that some of the mount points were not designed for easy soldering. They connect directly to large pieces of copper trace that acted as a huge heat sink making it difficult to bring the solder joint up to temperature. It would have been nice if they etched a little more. Leave one contact sufficient to carry the current, and etched around the rest to serve as a thermal break.

Apart from that minor complaint, the soldering was not difficult, only tedious. The electronics hobbyist is reminded why manual assembly of circuit boards is not considered a great career. This particular example took roughly four hours to assemble. Thankfully, when power was connected, everything started running as they should. Here is the assembled DSO 138, showing the built-in square wave test signal.

DSO138 complete

A few simple tests followed the self test, clearly showing some limits of this little oscilloscope. For one thing, the voltage scale is quite unreliable. An AA battery at 1.22 volts (according to the Fluke multi meter) was interpreted by this oscilloscope as 1.67 volts. But we didn’t get this thing to read voltages – we want to use it to graph wave forms that we couldn’t see with a multi meter. (UPDATE: On the advice of the local maker who built a DSO 138 before I did, I ran the calibration routine to align Vpos with zero volt and now voltage levels are much closer to the Fluke meter readings.)

It’s now part of the toolbox. Thanks to its low-cost, it wouldn’t take much data to throw it in either of these two buckets:

  • Positive: “That was so much easier to diagnose with a scope, even a simple one. This was well worth the money.”
  • Negative: “The inaccuracy of the scope led us down the wrong diagnosis path. This was a waste of both time and money.”

While we wait for the verdict to come in, let’s work on an enclosure for this device.

 

Dell XPS M1330 Battery Pack Teardown

We had an earlier success tearing down a Dell laptop battery pack, where the six salvaged cells still have 70% of original capacity after ten years of service. However, that was from a laptop that could still boot and run from its battery pack. This XPS M1330 battery pack is in far worse shape. How much worse, we were about to find out.

The first critical detail was realizing the battery pack was not the original Dell battery pack. It is an aftermarket type of unknown manufacture. The earlier battery pack tear down yielded Samsung cells, we’re probably not going to get anything nearly as nice this time around.

Once the case was cracked open the suspicion was confirmed: These appear to be generic 18650-sized lithium cells with no manufacturer branding. The nine cells of the battery pack were divided into three modules in series, each module had three cells wired in parallel. The module in the worst shape exhibited severe corrosion and had no voltage across their terminals.

Corroded 18650

The other two modules were in slightly better shape, but they have self-discharged down to approximately 1 volt DC, well under the recommended voltage range. A web search found some details on what happens to overly discharged lithium cells. In short: the chemistry inside the cell starts dissolving itself. If recharged, the dissolved metals may reform in inconvenient ways. Trying to use these cells has three potential outcomes:

  1. Best case: The metals dissolved into the electrolyte will hamper chemical reaction, resulting in reduced capacity.
  2. Medium case: The dissolved metals will reform in a way that damages the cell, causing it to fail as an open-circuit. (As if no battery was present.)
  3. Worst case: The dissolved metals will reform in a way that damages the cell, but causing it to fail as a closed circuit. Short-circuiting the internals will release a lot of energy very quickly, resulting in high-pressure venting and/or fire.

The corroded cells that have discharged down to zero volts have the highest risk and will be discarded. The remaining cells will be slowly (and carefully) charged back up to gauge their behavior.

Dell XPS M1330 Power Port Salvaged Using Desoldering Tool

Recently a dead Dell XPS M1330 came across the workbench. The battery was dead and the machine fails to boot. After some effort at reviving the machine, it was declared hopeless and salvage operations began. Today’s effort focuses on the motherboard port for the AC power adapter.

Dell Octagonal PowerThe power plug on this Dell different from the typical Dell laptop AC adapter: octagonal in shape rather than round. The shape meant it could not be used on other Dell laptops designed for the round plug. However, the dimensions of the octagon are such that an AC power adapter with the typical round Dell plug fits and could be used to charge the laptop. So while the laptop could be charged with any existing Dell-compatible AC adapter, the AC adapter that came with this machine is specific to this Dell.

Once the XPS M1330 died, its octagonal plug power adapter is not useful for other Dell laptops. It still functions as a power supply transforming household AC to ~19V DC so it might be useful for future projects. To preserve this possibility, the octagonal power port will be recovered from the system board.

The solder used in Dell assembly was possibly one of the lead-free types and is definitely reluctant to melt and flow. Trying to desolder the power port using hand tools (desoldering wick and hand suction pump) had no luck. So this project was chosen as a practice run of using a dedicated desoldering tool, in this case a Hakko 808. The tip of this tool heats up to melt the solder, and with a press of the trigger an electric vacuum pump pulls the melted solder through center channel of the heated tip and into a chamber for later disposal.

The desoldering pump was able to remove more solder than hand tools could, but was still not quite enough to free the port. Using a soldering iron, some user-friendly leaded solder was worked back into the joints to mix with the remaining Dell factory solder. Upon second application of the electric desoldering tool, enough solder was removed to free the port from the system board with only minimal damage.

Desoldering Tool

A test with the voltage meter confirmed this port is now ready to be used to provide ~19V DC power to a future project.

Socket Extraction Success

 

WebAssembly: A High Level Take On Low Level Concepts

webassemblyWebAssembly takes the concepts of low-level assembly language and brings them to web browsers. A likely first question is “Why would anybody want to do that?” And the short answer is: “Because not everybody loves JavaScript.”

People writing service-side “back-end” code have many options on technologies to use. There are multiple web application platforms that are built around different languages. Ruby on Rails and SinatraDjango and Flask, PHP, Node.JS, the list goes on.

In contrast, client-side “front end” code running on the user’s web browser has a far more limited choice in tools and only a single choice for language: JavaScript. The language we know today was not designed with all of its features and capabilities up front. It was a more organic growth that evolved alongside the web.

There have been multiple efforts to tame the tangle that is modern JavaScript and impose some structure. The Ruby school of thought led to CoffeeScript. Microsoft came up with TypeScript. Google invented Dart. What they all had in common was that none have direct browser support like JavaScript. As a result, they all trans-compile into JavaScript for actual execution on the browser.

Such an approach does address problems with JavaScript syntax, by staying within well-defined boundaries. Modern web browsers’ JavaScript engines have learned to look for and take advantage of such structure, enabling the resulting code to run faster. A project focused entirely on this aspect – making JavaScript easy for browsers to run fast – is asm.js. By limiting JavaScript to a very specific subset , sometimes adding hints to the browser it is so, allows JavaScript that can be parsed down to very small and efficient code. Even if it ends up being very difficult for a human to read.

Projects like asm.js make the resulting code run faster than general JavaScript, but that’s only once code starts running. Before it runs, it is still JavaScript transmitted over the network, and JavaScript that needs to be parsed and processed. The only way to reduce this overhead is to describe computation at a very low-level in a manner more compact and concise than JavaScript. This is WebAssembly.

No web developer is expected to hand-write WebAssembly on a regular basis. But once WebAssembly adoption takes hold across the major browsers (and it seems to be making good progress) it opens up the field of front-end code. Google is unlikely to build TypeScript into Chrome. Microsoft is unlikely to build Dart into Edge. Mozilla is not going to bother with CoffeeScript. But if they all agree on supporting WebAssembly, all of those languages – and more – can be built on top of WebAssembly.

The concept can be taken beyond individual programming languages to entire application frameworks. One demonstration of WebAssembly’s potential runs the Unity 3D game engine, purportedly with smaller download size and faster startup than the previous asm.js implementation.

An individual front end web developer has little direct need for WebAssembly today. But if it takes off, it has the potential to enable serious changes in the front end space. Possibly more interesting than anything since… well, JavaScript itself.

Remove Camera From Acer Aspire Switch 10

When the Acer SW5-012 (Aspire Switch 10) was received in a non-functioning state, it had a sticker covering the webcam lens applied by the previous owner. This is a common modification from owners who are concerned about malicious hackers activating the camera at unauthorized times. Some computer makers are finally meeting customer demand by placing physical shutters over webcams, but until that becomes commonplace, we’ll continue to have stickers/tabs/post-it notes covering webcams.

Removing the camera module would be a far more secure solution if the webcam is not to be used anyway. While impractical for some difficult-to-disassemble devices like an Apple iPad, we’ve already cracked open this Acer and test the concept. It turned out to be a straightforward exercise. The camera module is a distinct unit, the ribbon cable detaches from the motherboard easily, and it was only held in place by what felt like double-sided tape.

Acer Aspire Switch 10 Blinded

With five minutes of removing the back panel of the machine, the camera module was removed. The only lettering on it said CIFDF31_A2_MB and a web search on that designation returned several vendors happy to sell a replacement module. Sadly no technical information was found in a cursory search, so we won’t be trying to drive it with a PIC micro controller or anything. It’ll just sit in a zip lock bag for now.

And this intentionally-blinded Acer tablet is now available for use by house guests who are wary of hackers getting into the camera: no hacker in the world can activate a camera that is sitting in a zip lock bag in another room.

FreeNAS Successfully Recovered From Failed Drive

One of the major reasons to set up a FreeNAS machine with ZFS volume is to ensure that network storage data is always available in a redundant manner to ensure everything will still be OK after a hard drive inevitably fails. But before theory can be put into practice, we had to wait for a drive to actually fail. In that sense, today is our lucky day.

FreeNAS Critical Alert Box

A drive failed to respond to some commands and returned errors in the wee hours of the morning. Although it appears to have since recovered and is functioning, we shouldn’t be comforted by the momentary blip – it is almost certainly a sign of things to come if we continue to use this drive. So we’ll replace it instead of waiting for a catastrophic failure.

The instructions to replace a failing drive is covered in the FreeNAS manual. Following the procedures, the drive was taken offline in the Storage/Volume Status screen.

FreeNAS Volume Status

Then we go to Storage/View Disks screen to retrieve the identifying serial number. This ensures that we remove the correct physical drive from the computer by comparing this serial number against the number on the physical label on the drive.

FreeNAS Storage View Disks

Since this FreeNAS machine does not have hot swap capability, it then had to be shut down for the actual drive replacement. Once the machine restarts, we go back into Storage/Volume Status and select “Replace”. (The button next to “Offline” we clicked earlier.) If there’s any existing data on the replacement drive, FreeNAS will double-check to make sure it’s OK for the replacement drive to be overwritten.

FreeNAS Force Replace

And after that… we wait for the data from the remaining good drive to be replicated to the newly installed replacement drive.

FreeNAS Resilver In Progress

This procedure will take several hours and this time is technically a window of vulnerability – if the remaining good drive fails during this time we’ll lose data. To guard against this, ZFS allows even deeper redundancy by using more than two hard drives. In the case of this server, the data is not critical enough to warrant such protection and we’ll just cross our fingers the remaining drive does not fail during the recovery process.

Duet Display External Monitor: High Resolution and Features to Match High Price

Having multiple monitors is a great luxury. Not everyone appreciates it, but those that get used to it miss it greatly when traveling. It’s the biggest downside of using a MacBook Air as the travel laptop. It is smaller and lighter than the homebuilt external monitor, making it kind of silly to use them together. When light weight and portability is important enough to take the MacBook Air, we’ll also need the external screen to be equally portable.

The search for a thin-and-light external screen companion started with units that receive both power and data via the USB port. Sadly most of them offered only a low 1366×768 resolution at the starting $100 price range. Very few offer 1920×1080 resolution and they are in the $200 range. To get resolution any higher than that, we’ll need an iPad running Duet Display. Which means spending >$300. The good news is, for that price, the system worked very well with only two caveats:

First, Duet uses a proprietary protocol that requires a special driver running on the computer to talk to the app running on the iPad. Installing this driver triggered several warnings from MacOS and required explicit authorization to run non-Apple code signed with the name Rahul Dewan. A web search indicated this was the name of founder and CEO of Duet Display, so that matches, but it’s still a scary action from a security perspective.

Second, application windows could not span the two monitors. They can be dragged from one to the other, but each window will show only on one monitor. If a window is dragged to straddle the divide, only half of the window will show on one monitor, and the other half is not visible anywhere.

Other than that constraint, Duet Display works well to make an iPad (2017, Model A1822) serve as an external monitor for a MacBook Air (13-inch, early 2014). The speed and responsiveness are great. So far, the performance has been indistinguishable from an external monitor connected to the MacBook Air via HDMI.

It even offers something not available on other USB external monitors: the ability to hook into Apple’s Touch Bar feature and show the bar on the iPad. Even for Apple computers that aren’t equipped with the Touch Bar.

Duet+iPad has turned out to be the most expensive of the external MacBook monitor options, but it makes a compelling case to justify its price. High resolution, super lightweight, and naturally the iPad is still a perfectly good tablet when detached from the computer.

Duet in Action

 

Fusion 360 Lines Created Via API Are Not Limited To Sketch Plane

Cube on Sketch

Today’s performance tip helps avoid creating unnecessary planes and sketches when creating objects using the Fusion 360 API. First, some background: when sketching lines in Fusion 360 must be done in the context of a sketch object. This sketch object is in turn created to be aligned with a plane. It may be one of the default planes that intersect the origin (XZ plane, XY plane, or YZ plane) or a construction plane.

When sketching with the interactive UI, the user’s sketch entities are constrained to the plane of the sketch. For example, if a sketch was created on the XY plane, then all sketch entities would have a Z coordinate of zero. This makes sense to keep the data organized and easy to understand by the human looking at a 2D computer monitor.

When creating entities with the API, though, they are apparently not constrained. The first clue came from looking at the SketchLines.addByTwoPoints API – its two parameters are Point3D objects. A little experimentation confirmed the API would gladly accept 3D coordinates that lie outside the sketch plane. The example screenshot on this page is the result of drawing an one-centimeter cube on a sketch aligned to the XY plane. Only four of the eight corners (and four of the 12 edges) lie on the plane, but the API happily accepted all the information for a 3D cube.

This is very useful when creating geometries via code. Humans need to see points on a sketch stay in a plane for them to be workable on a 2D monitor screen, otherwise things get too confusing. But code doesn’t care about appearance on a screen. So go ahead – let code create complex 3D entities on a single sketch. Skipping the unnecessary planes and sketches will generate fewer API objects. Reducing object management overhead and allowing faster performance.

Accelerate Fusion 360 API Object Creation With DirectDesignType

64Cylinders

Exploring the capabilities of the Fusion 360 API will involve experiments creating objects via script. Since it’s all code, it’s easy to repeat a process many times, a natural allure of using scripts to automate repetitive tasks. The downside is that Fusion 360 (as of time of writing) has problems resulting in slow response.

The sample code below creates an array of small cylinders one at a time. (This is not the most efficient method to create an array of cylinders but merely an illustration of the problem.) The size of the array can be adjusted by changing the value of arraySize before running the script. For a 4×4 array, the results are almost instantaneous. On a modern Core i5, slowdowns can be observed in an 8×8 array. The first few cylinders are fast, but as additional cylinders appear, each new cylinder takes longer than the last.

Fusion 360 performs a lot of bookkeeping overhead to track these operations. While the majority are outside our control, we do have control over the most expensive overhead: the timeline. It is useful when we are working with hand-created designs, but unnecessary for script – if we want to change anything, we’d update the script and run it again. In the user interface, we can click on the gear in the lower right hand side and select “Do not capture Design History”. To do the same thing in script, we can set the type of the design object to DirectDesignType. (Uncomment line in sample code below.)

This mitigates but does not solve the problem. While it is now practical to generate far larger number of objects, there is still a noticeable slowdown as the object counts go up. According to this forum post, this issue has been logged as a defect for the development team. Perhaps a future release of Fusion 360 will create the last object as quickly as it created the first.

import adsk.core, adsk.fusion, adsk.cam, traceback

arraySize = 8 # Will extrude arraySize^2 objects

def run(context):
  ui = None
  try:
    app = adsk.core.Application.get()
    ui = app.userInterface

    app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)

    # adsk.fusion.Design.cast(app.activeProduct).designType = adsk.fusion.DesignTypes.DirectDesignType # Uncomment to turn off tracking timeline

    rootComp = adsk.fusion.Design.cast(app.activeProduct).rootComponent
    sketch = rootComp.sketches.add(rootComp.xYConstructionPlane)
    extrudeDistance = adsk.core.ValueInput.createByReal(1)

    rangeX = range(1-arraySize, arraySize, 2)
    rangeY = range(1-arraySize, arraySize, 2)

    for nowX in rangeX:
      for nowY in rangeY:
        sketch.sketchCurves.sketchCircles.addByCenterRadius(
          adsk.core.Point3D.create(nowX, nowY, 0), 0.5)

        rootComp.features.extrudeFeatures.addSimple(
          sketch.profiles[-1],
          extrudeDistance,
          adsk.fusion.FeatureOperations.NewBodyFeatureOperation)

        adsk.doEvents()

except:
  if ui:
    ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

This code is also available on Github.

Windows 10 Can Activate With Windows 8 Hardware Key

Our recent project with the Acer Aspire Switch 10 laptop had concluded with one mystery: how did it get the license key? Because we didn’t have the password for the installation of Windows 8 on the machine, the hard drive was wiped clean and Windows 10 installed from scratch. We expected we’d need to purchase a new license of Windows to activate on this computer. Fortunately, Windows 10 proclaimed itself activated without the need for a new license.

At the time we did not understand, but we were also not going to complain.

A second data point came in the form of a Dell laptop, which also shipped with Windows 8 but purchased by someone who decided they did not like it. A Windows 7 license was purchased and installed on this computer, which was then upgraded to Windows 10 during the free upgrade period. The original Windows 8 was lost. Recently a new SSD was installed on this computer and Windows 10 was installed from scratch. And like the Acer, Windows 10 proclaims itself to be activated even though no product license key has been entered.

Curiosity now demands a web search for answers, where we learn both of these computers participated in a new licensing scheme launched with Windows 8. Instead of a counterfeit-resistant license sticker attached to the bottom of the computer, their product license is embedded in the hardware instead. We will never have to worry about the license key becoming illegible, or getting lost and separated from the corresponding hardware.

Windows 8 could access this key and activate itself. Windows 7 installed on the Dell laptop could not. Windows 10 could access this key and, more importantly, are willing to activate on it even though the license was technically for Windows 8. The official free Windows 10 upgrade period has ended but we can still get a free step up under these circumstances.

Windows Key Sticker
The Windows Certificate of Authenticity is now a relic of the past.

Functional and Useful 100W Solar Array

Once the Monoprice PowerCache 220 was connected to the Harbor Freight 100W Solar Kit (Item #63585), we have everything we need to gather a little bit of sun power and make use of it every day. Given the non-optimal solar panel position and the fact we’re close to the winter solstice, this is just about the worst case scenario for solar power. Nevertheless this system has been gathering enough power to keep all the battery-powered electronics in the house charged up. This includes daily use & charge items like cell phones, tablets, and laptop computers. Plus the occasional items like a digital camera.

There is much more we can do to improve performance of this system, but it has met a minimum level of satisfactory performance so we can leave it running as-is for a while and switch gears to other projects. The focus will eventually return to this solar power system and here are two candidate projects for later:

Physical tracking: the panels are currently just sitting indoors vertically set against a south-facing window. It was done as an easy nondestructive way to experiment. When it comes time to improve upon this configuration, we can build a more permanent outdoor installation that angles into the sun. Maybe even motorized sun tracking throughout the day!

Electrical tracking: at the moment, the solar panel output voltage is dictated by the battery being charged. This is convenient and simple to implement but not the most efficient. We can buy (or design and build our own) a “maximum power point tracking” (MPPT) charger that keeps the solar panel voltage at its most efficient level and transform that to the correct battery charging voltage. It costs some power to do this tracking & voltage conversion, but if implemented correctly, the additional power will more than offset the cost.

We’ll add these projects to the bottom of the “to-do” list. For now, behold the glory of electronics being charged by sun power.

PowerCache 220 At Work cropped

Solar Charging Plug for Monoprice PowerCache 220

The product description page for Monoprice PowerCache 220 (Item #15278) had pictures showing its solar charging input as two round ports, but there were no connector specifications. Since it was advertised as a solar power cache, it would make sense for them to be MC4 connectors. This turned out not to be the case – they were actually two identical sockets that are electrically wired in parallel.

The device comes with an AC adapter for the charging port, but using household power would miss the point of the exercise. Neither do we want to lose the option to charge from grid power, so we don’t want to just cut off the charging plug. We should find an identical plug for solar charging.

The calipers indicate this connector has an outside diameter of 7.9mm and an inside diameter of 5.5mm. There is a small pin in the center roughly 0.5 mm in diameter. Putting those dimensions into search returned a few candidates and a large number of Lenovo laptop power adapters. A fortunate association, as there is a Kensington “Universal Laptop Power Supply” already on hand. It came with a set of interchangeable plugs to fit different laptop brands. This one was purchased to power a Dell, so the Lenovo plug has sat unused. But not for long!

Kensington Laptop Power

The Lenovo laptop plug matches all the diameters, and is slightly longer. It appeared to fit in the socket nicely. Since the two charging ports are electrically parallel, we could plug the AC adapter into the other charging port. This allowed us to read the voltage on the pins of the Lenovo plug so we know where to solder the positive and negative wire.

The plastic housing of the Lenovo plug was damaged in the soldering process so this plug will probably never fit on the Kensington laptop adapter again, but that’s fine. It now has a new purpose as solar charging plug for Monoprice PowerCache 220.

Lenovo now Solar plug

Hunt for AC Inverter Finds Monoprice PowerCache 220

Now that we have a 20 amp-hour 12 volt battery, charged by a solar array delivering up to 125 watt-hours daily. To put that power to use, we’ll need an inverter to convert battery power into household 120 volt AC power. This way the collected solar power can be used for more than just charging USB devices.

An old inverter was dug out of the old equipment collection, but it could only sustain about a minute of work before it would stop, reset, and restart. This isn’t great for the electronics, but what made it intolerable to humans were the cascade of noises that devices emit when charging began. Hearing the symphony roughly once a minute was unacceptable so the search begins for a replacement AC inverter.

The Harbor Freight lineup of AC inverters were obvious candidates. Starting from a basic model just under $20 and going up from there. While investigating options outside of Harbor Freight, one stood out: Monoprice #15278  “PowerCache 220”

It is designed exactly for the task we’re building for. It can accept power from a solar array to charge its 18 amp-hour 12 volt battery. That power can be consumed directly as 12 volts DC, as 5 volt USB power, or as 120 volt AC power.

The PowerCache mostly duplicates the components already in the current solar experiment setup. Buying one might be called wasteful, but for the sake of exploration we’ll call it redundancy. This nearly doubles the battery capacity and allows more ways to put solar power to use. It is also more user-friendly than the current maze of wires and connectors. It is an enclosed unit therefore easily portable. This might come in handy if we ever have a reason to take a little portable power source on the go.

So the search that began as a search for a simple AC inverter ended up with purchase of an integrated unit that included the AC inverter and basically everything else short of the solar panels themselves.

PowerCache 220

Initial Results of Solar Generation by 100 Watt Kit

Once the replacement battery arrived, it was possible to use the power captured by the Harbor Freight 100 watt solar kit. (Item #63585) The E-Flite Power Meter tracks the cumulative solar energy pumped back into the battery every day. Over several sunny days with minimal cloud cover, the daily tally ranged from 8 amp-hours to nearly 10 amp-hours. On an overcast day, the daily tally struggled to reach 4 amp-hours. (Reminder: the solar panels are not optimally placed to face the sun in these experiments.)

At the battery voltage range of 12 to 13 volts, this means a sunny day gives us about 125 watt-hours of electricity. (12.5 volt * 10 amp-hour) An overcast day’s output drops to about 50 watt-hours. (12.5 * 4) Since the sunniest and most productive times for solar largely overlaps with the most expensive times of the time-of-use electricity rates, we can try our best to make this solar array look good, by comparing against the highest rate of 35 cents per kilowatt-hour.

Even when using that expensive rate, a sunny day’s generation only works out to a tiny bit over 4 cents of grid electricity. A cloudy day couldn’t quite make up to 2 cents worth. Rough estimates point to a meager 10 dollars a year of savings on the electric bill.

Fortunately, we’re not doing this for money, and there is room for improvement as well. The solar array can be better aligned with the sun which, from earlier experiments, we know will make a huge difference. But a more immediate concern is the fact only a few items around the house can directly use DC power. There aren’t enough cell phones and tablets to consume 125 watt-hours a day.

In order to make solar power more useful, we’ll need an inverter to take the battery’s 12 volt DC power and turn it into household 120 volt AC.

20Ah Battery.jpg

Initial Use of 100 Watt Solar Kit Hampered By Battery

For the initial round of testing, the solar panels of the Harbor Freight kit (item #63585) was set up in a very temporary way: they were leaned against the south-facing windows of the house. To measure the output, we’re enlisting another member of the parts pile, unearthed when we were digging for the lead-acid battery: an E-Flite Power Meter designed to measure electric consumption of remote-controlled aircraft motors. It can handle the expected range of voltage and amperage and as a bonus it also tracks the total power in milliamp-hours.

E Flite Power Meter

Based on experiments with the small 1.5 watt panel, we knew not to expect the advertised 100 watt output with this sub-optimal, non sun-tracking orientation. The power meter gave confirmation: over the sunlight hours of a winter day, the panel generated power ranging from 20 to 30 watts. This is roughly in line with the small 1.5 watt panel experiment indicating sub-optimal placement returned as little as 25% of the power compared to directly facing the sun.

The solar charge controller allowed the battery voltage to rise to 14.4 to top it off, then disconnected the battery from the panel to avoid over-charging. Once the voltage dropped to 13.8 volts the controller kept the battery at this sustained charge level for as long as the solar panel could keep it there. All this fits expectation of a charge controller doing its job properly.

But something was wrong when withdrawing power from this assembly after the sun went down. Trying to charge a cell phone at night, battery voltage quickly dropped below cutoff threshold of 12 volts and the controller halted operations. There seems to be usable battery capacity remaining but the battery should have been able to hold roughly 12.5 to 13 volts for the majority of the power delivery period.

Looks like this battery did suffer some damage when it dropped down to 6 volts while sitting neglected in storage. Time to head over to Amazon and buy a replacement lead-acid battery with a good amp-hour per dollar ratio. The best ratio varies from day to day pricing fluctuation but at the moment meant this 20 Ah unit.