Broadcast Engineer at BellMedia, Computer history buff, compulsive deprecated, disparate hardware hoarder, R/C, robots, arduino, RF, and everything in between.
4813 stories
·
5 followers

A machine-learning system that guesses whether text was produced by machine-learning systems

1 Share

Gltr is an MIT-IBM Watson Lab/Harvard NLP joint project that analyzes texts and predicts whether that text was generated by a machine-learning model.

Automatically produced texts use language models derived from statistical analysis of vast corpuses of human-generated text to produce machine-generated texts that can be very hard for a human to distinguish from text produced by another human. These models could help malicious actors in many ways, including generating convincing spam, reviews, and comments -- so it's really important to develop tools that can help us distinguish between human-generated and machine-generated texts.

Gltr uses Open AI's GPT-2 117M language model, which is also widely used by text-generating models. Gltr looks for texts that fit the GPT-2 model too well, on the basis that texts produced by humans nearly always have "surprising" word combinations that are considered highly unlikely by GPT-2's lights. In other words, if a text seems too human, it's probably machine generated.

It's not hard to think of ways to defeat this tactic: GPT-2 could be modified to inject some random word-choices that roughed up the otherwise overly smooth statistical model; but Gltr relies on human beings to review the scores it gives to text, producing confidence scores that pop up when you hover your mouse over a word in a candidate text. This makes it harder to trick Gltr with random words, but it also means that Gltr is hard to scale up to analyzing large volumes of information, like all the tweets under a popular hashtag.

Even without the benefit of scale, there are some intriguing possibilities for integrating Gltr with a browser: you could toggle it on when you encountered a text that you were suspicious of and use its analysis to help you make up your own mind.

While it is possible to paste any text into the tool, we provided some examples of fake and real texts. Notice that the fraction of red and purple words, i.e. unlikely predictions, increases when you move to the real texts. Moreover, we found that the informative snippets within a text almost always appear in red or purple since these "surprising" terms carry the message of the text.

By hovering over a word in the display, a small box presents the top 5 predicted words, their associated probabilities, as well as the position of the following word. It is a fun exercise to look into what a model would have predicted.

Finally, the tool shows three different histograms that aggregate the information over the whole text. The first one demonstrates how many words of each category appear in the text. The second one illustrates the ratio between the probabilities of the top predicted word and the following word. The last histogram shows the distribution over the entropies of the predictions. A low uncertainty implies that the model was very confident of each prediction, whereas a high uncertainty implies uncertainty. You can observe that for the academic text input, the uncertainty is generally higher than the samples from the model.

Catching a Unicorn with GLTR: A tool to detect automatically generated text [GLTR.IO]

(via Four Short Links)

Read the whole story
tekvax
10 days ago
reply
Burlington, Ontario
Share this story
Delete

Hack My House: Raspberry Pi as a Touchscreen Thermostat

1 Share

Your thermostat is some of the oldest and simplest automation in your home. For years these were one-temperature setting and nothing more. Programmable thermostats brought more control; they’re alarm clocks attached to your furnace. Then Nest came along and added beautiful design and “learning features” that felt like magic compared to the old systems. But we can have a lot more fun. I’m taking my favorite single-board computer, the Raspberry Pi, and naming it keeper of heat (and cool) by building my own touchscreen thermostat.

Mercury thermostats started it all, and were ingenious in their simplicity — a glass capsule containing mercury, attached to a wound bi-metal strip. As the temperature changes, the contraption tilts and the mercury bead moves, making or breaking contact with the wiring. More sophisticated thermostats have replaced the mercury bead with electronics, but the signaling method remains the same, just a simple contact switch.

This makes the thermostat the prime target for an aspiring home automation hacker. I’ve had this particular project in mind for quite some time, and was excited to dive into it with simple raw materials: my Raspberry Pi, a touchscreen, and a mechanical relay board.

Hot Wiring a Heater

If you replace your standard home thermostat you find the most common setup has either 4 or 5 wires running to your HVAC equipment. These include a 24 volt AC power wire, leads to switch the heater, air conditioner, and fan, and finally an optional “common” wire, which is often used to power a smart thermostat. In order to remain backwards compatible, virtually all residential HVAC units in my part of the world use a version of this layout. A common troubleshooting technique is to “hot wire” an HVAC system — directly connecting the 24 volt wire to either the heater line or the the AC line.

For the hacker, the takeaway is that a simple relay is perfect to drive the system. For my setup shown above, I bridge the red 24 volt line to the yellow heater line, and the system roars to life. I’m using the 4 channel relay module from SainSmart. Anything that has GPIO and can talk to a temperature sensor is enough to build a thermostat. As you all know, however, I have committed to a building a Raspberry Pi into every room in my house, and I’m using all that extra power to run the official 7 inch touchscreen as a display and interface for the HVAC. I’m also using some Adafruit MCP9808 temperature sensors, which talk to our Pis using the I2C bus.

I2C Gotcha: Never Cross the Streams

Partway through the build, I did run into a very strange problem. After a few minutes of working perfectly, the temperature sensor began returning 0C, the touchscreen stopped responding to touches, and i2cdetect thought there was an i2c device at every address. I knew the touchscreen and temperature sensor were sharing the I2C bus, so I began troubleshooting what was causing that bus to hang.

The display has 4 pins and a ribbon cable. Those pins are power, ground, and the two I2C pins. When connecting an original Raspberry Pi A or B, those I2C pins need to be wired to the Pi’s single I2C bus. Starting with the Pi A+ and B+, there is a second I2C bus dedicated to the display, physically connected through the ribbon cable. I was unknowingly connecting the display to both I2C buses, not to mention bridging the two buses together. When they happened to both talk at once, both went down. TLDR: Only connect the two dedicated power pins and the ribbon cable, not the I2C pins on the display.

Temperature Monitoring with Python and Flask

Last time, we used Python and Flask to send requests to the Raspberry Pi wired to the garage door. We’re expanding on that idea to build an HTTP interface for the Thermostat Pi as well. An HTTP request to the correct path will return the detected temperature value. Readers have pointed out the possibility of overheating the Raspberry Pis, so I’ve also added the Pis’ CPU temperatures to the list of monitored temperatures.

from flask import Flask
import smbus
import os
import time
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(18, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(27, GPIO.OUT, initial=GPIO.HIGH)
bus = smbus.SMBus(1)
config = [0x00, 0x00]
bus.write_i2c_block_data(0x18, 0x01, config)

@app.route("/enable/<pin>")
def enable(pin):
        GPIO.output(int(pin), GPIO.LOW)
@app.route("/disable/<pin>")
def disable(pin):
        GPIO.output(int(pin), GPIO.HIGH)
@app.route("/temp/<sensor>")
def temp(sensor):
        if sensor == "internal" :
                temp = os.popen("vcgencmd measure_temp").readline()
                ctemp = float(temp.replace("temp=","").replace("'C",""))
                return str(ctemp * 1.8 + 32)
        if sensor == "external" :
                bus.write_byte_data(0x18, 0x08, 0x03)
                time.sleep(0.5)
                data = bus.read_i2c_block_data(0x18, 0x05, 2)
                ctemp = ((data[0] & 0x1F) * 256) + data[1]
                if ctemp > 4095 :
                        ctemp -= 8192
                ctemp *= 0.0625
                ftemp = ctemp * 1.8 + 32
                return str(ftemp)
if __name__ == "__main__":
        app.run(host='0.0.0.0', port=80, debug=False)

As you can see above, we’ve exposed the two temperatures as part of our RESTful interface. Now that we have access to that data, what do we do with it? Enter RRDTool.

Round-Robin Databases and Pretty Graphs

You may not be familiar with the name, but you’ve probably seen graphs produced by RRDTool, most notably in the Cacti monitoring suite. RRDTool is a simple round-robin database built on creating pretty graphs, and the idea that older data needs less resolution than fresh data. It might be useful to track temperature minute-by-minute, but usually only the last couple hours of that data. Last week’s data doesn’t need to be as granular: an average temperature for each hour might be enough. Last month, you might just care about the daily averages, etc. RRDTool lets you specify multiple round robin archives for each data source, with different time spans and granularity.

One more trick I’ve made use of is specifying a data source to track when the heater or air conditioner is running. This allows comparing temperatures to the HVAC duty cycle, which is useful for tracking down insulation and efficiency issues. Also, this data will be important for tuning the thermostat to avoid “short cycles”, when the system doesn’t run long enough to reach full efficiency, but turns on and off several times in short succession.

Stitching Together All The Parts That Make an Automatic Thermostat

Now that we’ve sorted the connection to the heater, temperature monitoring, and database, it’s time to put them all together. I’ve opted for a one-minute cycle: polling all our data sources, recording that data, and running the heater control logic every 60 seconds. To avoid short cycling, there is a temperature width setting — you could call it the system hysteresis. I’ve settled on a four degree swing: The thermostat turns on once the observed temperature drops two degrees below the target, and runs until it’s raised two degrees above it. This is the great thing about rolling your own system: you get to decide exactly how it will work.

import time
from rrdtool import update as rrd_update
import pycurl
import json
from StringIO import StringIO
starttime=time.time()
tempSensors = ("thermostat-temp-external", "thermostat-temp-internal", "office-temp-external", "office-temp-internal",
               "office-temp-outside", "garage-temp-internal", "garage-temp-external", "livingroom-hum-external",
               "livingroom-temp-external", "livingroom-temp-internal", "office-hum-outside")
#settings = {"temp": 70, "mode": "heat", "heater-width": 2, "ac-width": 2}
c = pycurl.Curl()
c.setopt(c.URL, 'http://thermostat/disable/17')
c.perform()
c.setopt(c.URL, 'http://thermostat/disable/27')
c.perform()
c.close()
state = {"activity": "idle"}
while True:
	with open('/var/www/data/settings', 'r') as f:
        	settings = json.load(f)
	f.closed
	temperatures = {}
	c = pycurl.Curl()
	for sensor in tempSensors:
		try:
			buffer = StringIO()
			c.setopt(c.URL, 'http://' + sensor.replace("-", "/")) #change dashes to /
			c.setopt(pycurl.WRITEFUNCTION, buffer.write)
			c.perform()
			temperatures[sensor] = float(buffer.getvalue())
			rrd_update('/var/www/data/' + sensor + '.rrd', 'N:%f' %(temperatures[sensor]))
		except Exception as e:
			print(e)
	with open('/var/www/data/temps', 'w') as f:
        	json.dump(temperatures, f)
	f.closed
	if settings["mode"] == "heat": #if mode heat (auto should compare to the outside temp, to figure out heat or AC
		if state["activity"] == "idle" and temperatures["thermostat-temp-external"] < (settings["temp"] - (settings["heater-width"] / 2.0)) :
			c.setopt(c.URL, 'http://thermostat/enable/17')
			c.perform()
			c.close()
			state["activity"] = "heating"
		elif state["activity"] == "heating" and temperatures["thermostat-temp-external"] > (settings["temp"] + (settings["heater-width"] / 2.0)) :
			c.setopt(c.URL, 'http://thermostat/disable/17')
			c.perform()
			c.close()
			state["activity"] = "idle"
	with open('/var/www/data/state', 'w') as f:
        	json.dump(state, f)
	f.closed
	if state["activity"] == "heating" :
		rrd_update('/var/www/data/heater-state.rrd', 'N:100')
	else :
		rrd_update('/var/www/data/heater-state.rrd', 'N:0')
	if state["activity"] == "cooling" :
		rrd_update('/var/www/data/ac-state.rrd', 'N:100')
	else :
		rrd_update('/var/www/data/ac-state.rrd', 'N:0')
	time.sleep(60.0 - ((time.time() - starttime) % 60.0))

Touchscreens: You’re Going to Want a GUI

All that’s left is the user interface. The actual hardware is a Raspberry Pi 3 B+, booted over PXE, with the official 7 inch touchscreen, mounted on a 3-gang wall box. For software, we’re using Chromium in fullscreen mode, and building a webpage optimized for the Pi display’s small size. You may remember when wiring in the garage door opener, we put a single button on a web page. Today we’re expanding that page to make a central control panel.

<?php
  $settings = json_decode(file_get_contents('/var/www/data/settings'));
  $temps = json_decode(file_get_contents('/var/www/data/temps'));
  $state = json_decode(file_get_contents('/var/www/data/state'));
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($_POST["up"]) {
      $settings->{'temp'} += 1;
    }
    if ($_POST["down"]) {
      $settings->{'temp'} -= 1;
    }
    if ($_POST["heat"]) {
      $settings->{'mode'} = "heat";
    }
    if ($_POST["cool"]) {
      $settings->{'mode'} = "cool";
    }
    if ($_POST["auto"]) {
      $settings->{'mode'} = "auto";
    }
    if ($_POST["off"]) {
      $settings->{'mode'} = "off";
    }
    if ($_POST["GDO"]) {
      $curl_handle = curl_init();
      curl_setopt( $curl_handle, CURLOPT_URL, 'http://garage/moment/20' );
      curl_exec( $curl_handle ); // Execute the request
      curl_close( $curl_handle );
    }
    $file = fopen('/var/www/data/settings', "w") or die("Unable to open file!");
    fwrite($file, json_encode($settings, JSON_NUMERIC_CHECK));
  }
?>
<!DOCTYPE html>
<html>
<head>
 <meta http-equiv="refresh" content="60">
 <script src="functions.js"></script>
 <script>
  function startTime() {
   var today = new Date();
   document.getElementById('txt').innerHTML = formatDate(today, "dddd h:mm:ss TT d MMM yyyy");
   var t = setTimeout(startTime, 500);
  }
 </script>
</head>
<body onload="startTime()">
 <div style="width:790px; margin:auto;">
  <div style="height:140px;">
   <div style="float:left;">
    <form method="post">
     <input type="submit" name="up" value="▲" style="padding:25px 25px;">
    </form>
    <form method="post">
     <input type="submit" name="down" value="▼" style="padding:25px 25px;">
    </form>
   </div>
   <div style="float:left; margin-left:5px; margin-top:60px;">
    Thermostat set to: <?php  echo $settings->{'temp'}; ?>
   </div>
   <div style="float:left; margin-left:25px;">
    <div id="txt"></div>
    Inside: <?php echo round($temps->{'thermostat-temp-external'}, 2); ?>
    <br> Outside: <?php echo round($temps->{'office-temp-outside'}, 2); ?>
    <br> System is: <?php echo $state->{'activity'}; ?>
   </div>
   <div style="float:right;">
    <form method="post">
     <input type="submit" name="cool" value="cool" style="height:70px; width:100px;<?php if($settings->{'mode'} == "cool"){echo "color:red;";}?>">
    </form>
    <form method="post">
     <input type="submit" name="off" value="off" style="height:70px; width:100px;<?php if($settings->{'mode'} == "off"){echo "color:red;";}?>">
    </form>
   </div>
   <div style="float:right;">
    <form method="post">
     <input type="submit" name="heat" value="heat" style="height:70px; width:100px;<?php if($settings->{'mode'} == "heat"){echo "color:red;";}?>">
    </form>
    <form method="post">
     <input type="submit" name="auto" value="auto" style="height:70px; width:100px;<?php if($settings->{'mode'} == "auto"){echo "color:red;";}?>">
    </form>
   </div>
  </div>
  <div style="margin:auto; text-align:center;">
<?php
  $opts = array ( "-w", "709", "-h", "200", "-Y",
    '-a', "PNG", "--start=-14400","--end=now",
    'DEF:heater-state=/var/www/data/heater-state.rrd:state:AVERAGE',
    'AREA:heater-state#FF000050:"Heater usage"',
    'DEF:air-state=/var/www/data/ac-state.rrd:state:AVERAGE',
    'AREA:air-state#0000FF50:"air usage"',
    'DEF:livingroom-hum=/var/www/data/livingroom-hum-external.rrd:humidity:AVERAGE',
    'LINE1:livingroom-hum#000000:humidity',
    'DEF:therm-temp=/var/www/data/thermostat-temp-external.rrd:temperature:AVERAGE',
    'LINE1:therm-temp#0000FF',
    'DEF:outside-temp=/var/www/data/office-temp-outside.rrd:temperature:AVERAGE',
    'LINE1:outside-temp#FF0000'
    );
  $graphObj = new RRDGraph('-');
  $graphObj->setOptions($opts);
  try {
    $ret = $graphObj->saveVerbose();
  } catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
    echo rrd_error()."\n";
  }
  if(!$ret){
    echo rrd_error()."\n";
  } else {
    #var_dump($ret);
    echo '<img alt="My Image" src="data:image/png;base64,' . base64_encode($ret['image']) . '" />';
  }
?>
  </div>
  <div style="float:left;">
   <form method="post">
    <input type="submit" name="GDO" value="Cycle Garage" style="padding:25px 15px; margin-right:25px;">
   </form>
  </div>
</body>
</html>

Most of it is straightforward PHP and HTML. The most interesting element is the way the RRDTool graphs are dynamically generated at page load, and included in the html document. This allows future customization, like the ability to zoom out and see older data, or select other data sources to include.

The 3D printed mount finishes the project nicely. It’s rather important to get that temperature sensor away from the heat of the Pi, in order to get an accurate reading.

We have more to come, so keep your eyes peeled, and feel free to follow me over on twitter for the occasional sneak peak or suggetions for the next step in my home automation adventure!





Read the whole story
tekvax
19 days ago
reply
Burlington, Ontario
Share this story
Delete

Tiny Amplifier With ATtiny

1 Share

Small microcontrollers can pack quite a punch. With the right code optimizations and proper use of the available limited memory, even small microcontrollers can do things they were never intended to. Even within the realm of intended use, however, there are still lots of impressive uses for these tiny cheap processors like [Lukasz]’s audio amplifier which uses one of the smallest ATtiny packages around in the video embedded below.

Since the ATtiny is small, the amplifier is only capable of 8-bit resolution but thanks to internal clock settings and the fast PWM mode he can get a sampling rate of 37.5 kHz. Most commercial amplifiers shoot for 42 kHz or higher, so this is actually quite close for the limited hardware. The fact that it is a class D amplifier also helps, since it relies on switching and filtering to achieve amplification. This allows the amplifier to have a greater efficiency than an analog amplifier, with less need for heat sinks or oversized components.

All of the code that [Lukasz] used is available on the project site if you’ve ever been curious about switching amplifiers. He built this more as a curiosity in order to see what kind of quality he could get out of such a small microcontroller. It sounds pretty good to us too! If you’re more into analog amplifiers, though, we have you covered there as well.





Read the whole story
tekvax
25 days ago
reply
Burlington, Ontario
Share this story
Delete

A Network Attached Radiation Monitor

1 Share

It started as a joke, as sometimes these things do. [Marek Więcek] thought building a personal radiation detector would not only give him something to work on, but it would be like having a gadget out of the Fallout games. He would check the data from time to time and have a bit of a laugh. But then things got real. When he started seeing rumors on social media that a nearby nuclear reactor had suffered some kind of radiation leak, his “joke” radiation detector suddenly became serious business.

With the realization that having his own source of detailed environmental data might not be such a bad idea after all, [Marek] has developed a more refined version of his original detector (Google Translate). This small device includes a Geiger counter as well as sensors for more mundane data points such as temperature and barometric pressure. Since it’s intended to be a stationary monitoring device, he even designed it to be directly plugged into an Ethernet network so that it can be polled over TCP/IP.

[Marek] based the design around a Soviet-era STS-5 Geiger tube, and outfitted his board with the high voltage electronics to provide it with the required 400 volts. Temperature, barometric pressure, and humidity are read with the popular Bosch BME280 sensor. If there’s no Ethernet network available, data from the sensors can be stored on either the built-in SPI flash chip or a standard USB flash drive.

The monitor is powered by a PIC32MX270F256B microcontroller with an Ethernet interface provided by the ENC28J60 chip. In practice, [Marek] has a central Raspberry Pi that’s polling the monitors over the network and collecting their data and putting it into a web-based dashboard. He’s happy with this setup, but mentions he has plans to add an LCD display to the board so the values can be read directly off of the device. He also says that a future version might add WiFi for easier deployment in remote areas.

Over the years we’ve seen a fair number of radiation monitors, from solar-powered WiFi-connected units to the incredible work [Radu Motisan] has done building his global network of radiation detectors. It seems hackers would rather not take somebody else’s word for it when it comes to the dangers of radiation.





Read the whole story
tekvax
25 days ago
reply
Burlington, Ontario
Share this story
Delete

Hack My House: Garage Door Cryptography Meets Raspberry Pi

1 Share

Today’s story is one of victory and defeat, of mystery and adventure… It’s time to automate the garage door. Connecting the garage door to the internet was a must on my list of smart home features. Our opener has internet connection capabilities built-in. As you might guess, I’m very skeptical of connecting a device to the internet when I have no control over the software running on it.

The garage door is controlled by a button hung on the garage wall. There is only a pair of wires, so a simple relay should be all that is needed to simulate the button press from a Raspberry Pi. I wired a relay module to a GPIO on the Pi mounted in the garage ceiling, and wrote a quick and dirty test program in Python. Sure enough, the little relay was clicking happily– but the garage door wasn’t budging. Time to troubleshoot. Does the push button still work? *raises the garage door* yep. How about the relay now? *click…click* nope.

You may have figured out by now, but this garage door opener isn’t just a simple momentary contact push button. Yes, that’s a microcontroller, in a garage door button. This sort of scenario calls for forensic equipment more capable than a simple multimeter, and so I turned to Amazon for a USB oscilloscope that could do some limited signal analysis. A device with Linux support was a must, and Pico Technology fit the bill nicely.

Searching for a Secret We Don’t Actually Need

My 2 channel Picotech oscilloscope, the 2204A, finally arrived, and it was time to see what sort of alien technology was in this garage door opener. There are two leads to the button, a ground and a five volt line. When the button is pressed, the microcontroller sends data back over that line by pulling the 5 V line to ground. If this isn’t an implementation of Dallas 1-wire, it’s a very similar concept.

The wire protocol appears simple enough to reproduce, ideally with an opto-isolator. I found a suitable chip and got it on order. With the physical interface sorted, it was time to move on to the data itself.

So, what does the request to open look like? “Open Sesame”? The Picoscope software is capable of signal decoding, so some futzing with those settings got reproducible results. UART at 9.6 kbaud. 38 bytes of data were being sent over the wire, and the next step was to capture several of those packets to look for patterns.

Each packet started with a repeatable pattern that Picoscope decoded as 55 01 00. A header of sorts? A source or destination identifier? So far, I just didn’t have enough information to tell. Other than that pattern, the data appeared to be random. So where to from here?

The underside of the switch lists a couple patent numbers. Patent applications often have lots of useful information that is not available anywhere else. Patents also show off legalspeak at its worst. Wading through patents like 7,561,075 does yield the occasional nugget. It describes an encryption (or obfuscation) scheme revolving around a simple transformation. Looking at the patent documentation, I suspected it would be possible to break the encryption scheme and spoof the garage door button being pressed.

A Python script to do the data processing was my next planned move. With a little luck, I thought I could re-create the algorithm, as well as potentially recover the secrets used to generate the data. Many a project have been derailed when the needs of real life have intruded in the life of the hacker, and I’m not immune. For about a month, that’s where the project languished. We’ve moved into the house, my firstborn is a week old, and it’s time to finally get the garage door working.

Spoof the Button, Not the Cryptography

Remember how we started by looking for a simple push button switch? It turns out, there is such a switch built in to the wired opener. Soldering leads onto that small button is the fastest to implement, if not the most elegant. Yes, my solution is a Raspberry Pi running a relay, and that relay bridging the tiny physical button on the wired opener.

Elegant but complicated solutions can be major pitfalls to getting stuff done. Sometimes you have the time to dig in and put together the ideal solution, but sometimes you just have to get the project done. If it’s cheating and it works, it’s not… Ok, it’s still cheating, but it works, which is more important.

We can open the garage door from a command line on the Raspberry Pi. That’s useful, but perhaps a bit clunky. Remember way back in the first article, I mentioned using flask to create a RESTful interface? Here’s where we can really get started.

from flask import Flask
import time
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(20, GPIO.OUT)
GPIO.setup(20, GPIO.LOW)

@app.route("/")
  def hello():
  return "Hello!"

@app.route("/moment/<pin>")
  def moment(pin):
  changePin=int(pin)
  GPIO.output(changePin, GPIO.HIGH)
  time.sleep(.5)
  GPIO.output(changePin, GPIO.LOW)
  return "OK"
if __name__ == "__main__":
  app.run(host='0.0.0.0', port=80, debug=False)

This runs a rudimentary flask server, listening for http connections. Here the relay is on GPIO20, and so the server is waiting for a request for “/moment/20”, at which point, it flips that GPIO high for a half second, triggering the garage door. In order to run automatically, I’ve saved this to /usr/local/bin/gpio-flask.py, and then defined a systemd service at /lib/systemd/system/gpio-flask.service:

[Unit]
Description=Flask Service for GPIO
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/bin/python /usr/local/bin/gpio-flask.py
Restart=always

[Install]
WantedBy=multi-user.target

Telling systemctl to enable and start that service gets us in business. One last piece of the puzzle, let’s build a control page on our PXE server.

<!DOCTYPE html>
<html>
<body>
<div style="text-align:center">
<form method="post">
<input type="submit" name="GDO" value="Cycle Garage" style="padding:25px 15px;">
</form>

<?php
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($_POST["GDO"]) {
      $curl_handle = curl_init();
      curl_setopt( $curl_handle, CURLOPT_URL, 'http://garage/moment/20' );
      curl_exec( $curl_handle );
      // Execute the request
      curl_close( $curl_handle );
    }
  }
?>
</body>
</html>

We’ll expand on this PHP script more in the future, but for now it has two functions. The first builds and displays the interface page — just a single big button labelled “cycle garage”. The second part of the script only acts when a POST request is received. If the “GDO” value is present in the request, it uses curl to fire off the command to our Raspberry Pi, raising the garage door. It’s been a long road, but it finally works. A button on a web page opens my garage door. Let me relish my small victory for a moment…

Now that we’ve cheated our way past the garage door opener, next time we can work on data logging and HVAC control. Until then, happy hacking!





Read the whole story
tekvax
25 days ago
reply
Burlington, Ontario
Share this story
Delete

Palm-Sized Gatling Gun Has 32 Mini Elastics With Your Name On Them

1 Share

One thing 3D printers excel at is being able to easily create objects that would be daunting by other methods, something that also allows for rapid design iteration. That’s apparent in [Canino]’s palm-sized, gatling-style, motorized 32-elastic launcher.

The cannon has a rotary barrel driven by a small motor, and a clever sear design uses the rotation of the barrels like a worm gear. The rotating barrel has a spiral formation of hooks which anchor the stretched elastic bands. A small ramp rides that spiral gap, lifting ends of stretched bands one at a time as the assembly turns. This movement (and therefore the firing control) is done with a small continuous rotation servo. While in theory any motor would do, using a servo has the advantage of being a standardized shape, and therefore easy to integrate into the design. A video is embedded below in which you can see it work, along with some close-ups of the action.

An elastic band shooter is a common use of the rubbery rings, but we have seen some pretty unusual applications that have nothing to do with their intended use as a sort of fastener. For example, wide elastic bands form the shades in this unusual lamp design which is worth a look just to see how it all turned out.





Read the whole story
tekvax
25 days ago
reply
Burlington, Ontario
Share this story
Delete
Next Page of Stories