Coding Chase - Projects

My 3D Hub

Thank You For Donating:

Ikeeki (linux-sunxi@irc.freenode.net)
Computer Troubleshooters Brasil

Monday, 7 November 2016

IoT Projects - ESP8266 [CTC-3D Printer Upgrade] III

A while as passed since my last post on the blog - work, family and life in general have rolled by and although I haven't stopped experimenting and learning, not much time got left to update my humble journal.

After the CTC and lots of both tinkering and playing with materials, I got a Geeetech Prusa I3X assembling kit.

That story deserves a post of its own, but now that all is working in the office, I decided to officially declare open my personal 3D printing lab...!


Remodeling the workbench to accommodate both devices, plus re-installing the LED lighting to the workbench frame in order to light up the entire area payed off, however the small micro-controller solution I was running with the ESP8266-01 needed to grow to three relays, so I decided to upgrade to an ESP8266-12.

At this point, the web app solution I had was also quite outdated (using MEAN.js) and upgrading it was beginning to become quite the endeavor.

That was when I found out about this project on Github:

Crouton MQTT IOT Dashboard

It looked awesome and the MQTT messaging architecture seemed very well thought out, so I decided to give it a try.

However, that meant re-rewriting the ESP lua code I already had and update the solution to Crouton's way of doing things.

 Below is the sample code I came up with in order to use the ESP with Crouton (based off of Crouton's included example code). Although it was working properly, I would still have to work out some extra validations, such as reconnecting to WiFi and/or the MQTT broker:

init.lua

print('init.lua ver 1.2')
wifi.setmode(wifi.STATION)
print('set mode=STATION (mode='..wifi.getmode()..')')
print('MAC: ',wifi.sta.getmac())
print('chip: ',node.chipid())
print('heap: ',node.heap())

--include json encoder/decoder
json = require "cjson"

-- wifi config start
wifi.sta.config("ssid","password")
-- wifi config end

print('Starting up in 5 seconds!')

function startup()
    print('Starting up...')
    dofile('main.lua')
    end

tmr.alarm(0,5000,0,startup)




main.lua

-- pin stuff
print("setting up pins")
ledlightingPin = 1
toggleSwitchCTCPin = 3
toggleSwitchPrusaPin = 5

gpio.mode(ledlightingPin, gpio.OUTPUT)
gpio.write(ledlightingPin, gpio.HIGH)

gpio.mode(toggleSwitchCTCPin, gpio.OUTPUT)
gpio.write(toggleSwitchCTCPin, gpio.HIGH)

gpio.mode(toggleSwitchPrusaPin, gpio.OUTPUT)
gpio.write(toggleSwitchPrusaPin, gpio.HIGH)

-- Configuration to connect to the MQTT broker.
BROKER = "m11.cloudmqtt.com"   -- Ip/hostname of MQTT broker
BRPORT = 22002             -- MQTT broker port
SECURE = 1                  -- 1 YES / 0 NO
BRUSER = "esp8266-12-" ..  node.chipid()           -- If MQTT authenitcation is used then define the user
BRPWD  = node.chipid()            -- The above user password
CLIENTID = "esp8266-12-" ..  node.chipid() -- The MQTT ID. Change to something you like
print("Device name printed below:")
print(CLIENTID)

--deviceJson
deviceInfo = {}
deviceInfo["endPoints"] = {}
deviceInfo["endPoints"]["ledlighting"] = {}
deviceInfo["endPoints"]["ledlighting"]["values"] = {}
deviceInfo["endPoints"]["ledlighting"]["values"]["value"] = true
deviceInfo["endPoints"]["ledlighting"]["labels"] = {}
deviceInfo["endPoints"]["ledlighting"]["labels"]["true"] = "ON"
deviceInfo["endPoints"]["ledlighting"]["labels"]["false"] = "OFF"
deviceInfo["endPoints"]["ledlighting"]["card-type"] = "crouton-simple-toggle"
deviceInfo["endPoints"]["ledlighting"]["title"] = "Iluminação"

deviceInfo["endPoints"]["toggleSwitchCTC"] = {}
deviceInfo["endPoints"]["toggleSwitchCTC"]["values"] = {}
deviceInfo["endPoints"]["toggleSwitchCTC"]["values"]["value"] = true
deviceInfo["endPoints"]["toggleSwitchCTC"]["labels"] = {}
deviceInfo["endPoints"]["toggleSwitchCTC"]["labels"]["true"] = "ON"
deviceInfo["endPoints"]["toggleSwitchCTC"]["labels"]["false"] = "OFF"
deviceInfo["endPoints"]["toggleSwitchCTC"]["card-type"] = "crouton-simple-toggle"
deviceInfo["endPoints"]["toggleSwitchCTC"]["title"] = "CTC-3D"

deviceInfo["endPoints"]["toggleSwitchPrusa"] = {}
deviceInfo["endPoints"]["toggleSwitchPrusa"]["values"] = {}
deviceInfo["endPoints"]["toggleSwitchPrusa"]["values"]["value"] = true
deviceInfo["endPoints"]["toggleSwitchPrusa"]["labels"] = {}
deviceInfo["endPoints"]["toggleSwitchPrusa"]["labels"]["true"] = "ON"
deviceInfo["endPoints"]["toggleSwitchPrusa"]["labels"]["false"] = "OFF"
deviceInfo["endPoints"]["toggleSwitchPrusa"]["card-type"] = "crouton-simple-toggle"
deviceInfo["endPoints"]["toggleSwitchPrusa"]["title"] = "Prusa I3 X"

deviceInfo["endPoints"]["youTubeStreamCTC"] = {}
deviceInfo["endPoints"]["youTubeStreamCTC"]["values"] = {}
deviceInfo["endPoints"]["youTubeStreamCTC"]["values"]["youtubeID"] = "GZnb3jQ2YZo"
deviceInfo["endPoints"]["youTubeStreamCTC"]["card-type"] = "crouton-video-youtube"
deviceInfo["endPoints"]["youTubeStreamCTC"]["title"] = "CTC-3D"

deviceInfo["endPoints"]["youTubeStreamPrusa"] = {}
deviceInfo["endPoints"]["youTubeStreamPrusa"]["values"] = {}
deviceInfo["endPoints"]["youTubeStreamPrusa"]["values"]["youtubeID"] = "GZnb3jQ2YZo"
deviceInfo["endPoints"]["youTubeStreamPrusa"]["card-type"] = "crouton-video-youtube"
deviceInfo["endPoints"]["youTubeStreamPrusa"]["title"] = "Prusa I3 X"



deviceJson = {}
deviceJson["deviceInfo"] = deviceInfo


-- MQTT topics to subscribe
topics = {
  "/inbox/"..CLIENTID.."/deviceInfo",
  "/inbox/"..CLIENTID.."/ledlighting",
  "/inbox/"..CLIENTID.."/toggleSwitchCTC",
  "/inbox/"..CLIENTID.."/toggleSwitchPrusa",
  "/inbox/"..CLIENTID.."/youTubeStreamCTC",
  "/inbox/"..CLIENTID.."/youTubeStreamPrusa"
} -- Add/remove topics to the array


-- Control variables.
pub_sem = 0         -- MQTT Publish semaphore. Stops the publishing when the previous hasn't ended
current_topic  = 1  -- variable for one currently being subscribed to
topicsub_delay = 50 -- microseconds between subscription attempts, worked for me (local network) down to 5...YMMV

-- connect to the broker
print "Connecting to MQTT broker. Please wait..."
m = mqtt.Client( CLIENTID, 60, BRUSER, BRPWD)
m:connect( BROKER , BRPORT, SECURE, function(conn) end)
m:on("connect", function(con)
  print ("connected")
  publish_data("/outbox/"..CLIENTID.."/deviceInfo", json.encode(deviceJson))
  mqtt_sub()
end)

--subscribe to the list of topics
function mqtt_sub()
     if table.getn(topics) >= current_topic then
          m:subscribe(topics[current_topic] , 0, function(conn,topic,message)
            print("Subscribed a topic ...")
          end)
          current_topic = current_topic + 1  -- Goto next topic
          --set the timer to rerun the loop as long there is topics to subscribe
          tmr.alarm(5, topicsub_delay, 0, mqtt_sub )
     end
end


-- Sample publish functions:
function publish_data(topic, data)
   if pub_sem == 0 then  -- Is the semaphore set=
     pub_sem = 1  -- Nop. Let's block it
     m:publish(topic,data,0,0, function(conn)
        -- Callback function. We've sent the data
        -- print("Sending: " .. data .." to " .. topic)
        pub_sem = 0  -- Unblock the semaphore
     end)
   end
end

function explode(d,p) -- (separator,string)
  local t, ll
  t={}
  ll=0
  if(#p == 1) then return {p} end
    while true do
      l=string.find(p,d,ll,true) -- find the next d in the string
      if l~=nil then -- if "not not" found then..
        table.insert(t, string.sub(p,ll,l-1)) -- Save it in our array.
        ll=l+1 -- save just after where we found it for searching next time.
      else
        table.insert(t, string.sub(p,ll)) -- Save what's left in our array.
        break -- Break at end, as it should be, according to the lua manual.
      end
    end
  return t
end

-- Recieving data
m:on("message", function(conn, topic, msg)
  topicTable = explode("/",topic)

  box = topicTable[2]
  name = topicTable[3]
  address = topicTable[4]

  if box == "inbox" then
    if address == "ledlighting" then
      toggleLEDlighting(msg)
    end
    if address == "toggleSwitchCTC" then
      toggleSwitchCTC(msg)
    end
    if address == "toggleSwitchPrusa" then
      toggleSwitchPrusa(msg)
    end
  end

  if box == "inbox" and address == "deviceInfo" then
    deviceJson["deviceInfo"]["endPoints"]["ledlighting"]["values"]["value"] = (gpio.read(ledlightingPin) ~= 0) and true or false
    deviceJson["deviceInfo"]["endPoints"]["toggleSwitchCTC"]["values"]["value"] = (gpio.read(toggleSwitchCTCPin) ~= 0) and true or false
    deviceJson["deviceInfo"]["endPoints"]["toggleSwitchPrusa"]["values"]["value"] = (gpio.read(toggleSwitchPrusaPin) ~= 0) and true or false
    publish_data("/outbox/"..CLIENTID.."/deviceInfo", json.encode(deviceJson))
  end
end )

m:lwt("/outbox/"..CLIENTID.."/lwt", "anythinghere", 0, 0)
m:on("offline", function(con) print ("offline") end)

-------- Should split file but we will later.. above code for mqtt .. below is the esp function

function toggleLEDlighting (msg)
  msgObj = json.decode(msg)

  if msgObj["value"] then
    gpio.write(ledlightingPin, gpio.HIGH)
  else
    gpio.write(ledlightingPin, gpio.LOW)
  end
  publish_data("/outbox/"..CLIENTID.."/ledlighting", msg)
end

function toggleSwitchCTC (msg)
  msgObj = json.decode(msg)

  if msgObj["value"] then
    gpio.write(toggleSwitchCTCPin, gpio.HIGH)
  else
    gpio.write(toggleSwitchCTCPin, gpio.LOW)
  end
  publish_data("/outbox/"..CLIENTID.."/toggleSwitchCTC", msg)
end

function toggleSwitchPrusa (msg)
  msgObj = json.decode(msg)

  if msgObj["value"] then
    gpio.write(toggleSwitchPrusaPin, gpio.HIGH)
  else
    gpio.write(toggleSwitchPrusaPin, gpio.LOW)
  end
  publish_data("/outbox/"..CLIENTID.."/toggleSwitchPrusa", msg)
end


Some additional considerations:
  1. working with CloudMQTT, using a free account
  2. CloudMQTT supports secure web sockets as well as secure MQTT connection over SSL (which I decided to try out)
  3. working with NodeMCU and Lua on the ESP:
    1. used https://nodemcu-build.com/ to build my custom firmware;
    2. nodemcu-dev-11-modules-2016-10-09-19-15-15-integer;
    3. included modules: adc, cjson, file, gpio, mqtt, net, node, pwm, tmr, uart, wifi
  4. contributing for the Crouton Dashboard project to include secure web sockets support

The Crouton Dashboard project is still going, however it turned out pretty well in replacing my outdated, custom web app solution.

So at this point, the ESP8266 module (-12 variant) running NodeMCU plus the use of the Crouton Dashboard were a working solution, only requiring a basic circuit to include 3 relays in order to turn on/off both printers and the LED lighting - plus a 3d printed case.

Using a free CloudMQTT account, I set up the following users and ACLs:

crouton-client:

/inbox/esp8266-12-<chipid>/#    read - false / write - true
/outbox/esp8266-12-<chipid>/#    read - true / write - false

esp8266-12-<chipid>:

/inbox/esp8266-12-<chipid>/#    read - true / write - false
/outbox/esp8266-12-<chipid>/#    read - false / write - true


And then used CloudMQTT's own web socket client to view the messages being exchanged across topics.

All of this lead to a definitive, working solution which remained stable for several weeks non-stop, allowing me to remotely turn on/off any of the 3D printers, as well as the lighting.
The video streaming was still to be published to youtube live, so by then I would just be accessing it through the Octoprint instances.
 


... and that was when I remembered about the Oak Project by Digistump.

(to be continued)

Wednesday, 22 June 2016

SailfishOS Ports

SailfishOS - True Independent Mobile OS


A couple of years back, I had the chance to try out the Jolla Phone running SailfishOS and even do some app development for it.

Recently, and without the device at hand, I thought about updating the code, as SailfishOS has already gone 2.0 - and since I'm a proud owner of a Galaxy Samsung S4 smartphone, I went about looking for any available ROMs I could try out...

... but in the end found myself producing builds for the device, and things progressed quite well, so with big thanks to everyone else before me like JustSueMe, Simon Van der Veldt, and the porters at #sailfishos-porters@irc.freenode.net, below are several links to resources, such as ROM builds to try out, porting status and active discussion on the subject!

So if you have one of these Samsung S4 GT-I9505 LTE, a.k.a. "jfltexx" and would like to try out something different, your feedback will be very appreciated:

Mer Wiki Device Page
XDA Porting Thread
SailfishOS ROM Download
Youtube Video Gallery 


Wednesday, 30 December 2015

IoT Projects - ESP8266 [CTC-3D Printer Upgrade] ||

So, after having an ESP8266-01 control my CTC-3D printer LED lighting and Fan cooling, I decided to improve the solution further.

Moving more to ABS than PLA on prints, the fans stopped being that necessary - but what stood out as being a lot more interesting would be to actually turning the printer on or off.

Using the same principles as before, I replaced the Fan part of the solution and added the printer power cord to the available relay.

As an extra, I left cubietruck to manage Octoprint and the remaining solutions in previous posts and set out to build a nice embedded cluster:

  • 4 boards (even cubieboard A10 boards will do for this, but one might consider a cheaper alternative as the Orange Pi perhaps);
  • 4 webcams, in my case, the Hercules Twist HD as it molds perfectly to the case;
  • placing each webcam on the top corners of the printer case, pointing to the heat bed;
  •  Using cubietruck as the manager of the video solution and controlling each of the 4 boards as video feeds;

And since using the command line to issue MQTT commands wasn't actually that practical, I started working on a web platform to manage the solution.

I spent some time working with MEAN.js which I found to be brilliant by the way, integrated MQTT.js and socket.io into the base boilerplate as well as the live video feeds from the webcams.

In the end I got exactly what I wanted:

  • the ESP8266-01 connects to CloudMQTT, a cloud-based, free MQTT broker (moved to it after everything was confirmed to be working properly using mosquitto locally);
  • the MQTT broker is accessible by the MEAN.js web app (which later got published to heroku);
  • the web app uses MQTT.js to subscribe to CloudMQTT and socket.io to perform realtime UI updating if necessary (if I decide to use sensors in the future);
  • the webcams stream the video to the web app.
Using the app, either desktop or tablet or mobile, I'm able to work it:
  1. turn the printer on/off, which saves some power;
  2. turn the lighting on/off, in case there's poor lighting in the room;
  3. use a slicer remotely, like slic3r, generate gcode and upload it to Octoprint;
  4. run the prints remotely and accompany the status using the webcams.
 Some screenshots from the development phase, the web app is very crude, just the buttons and the video streams, just one stream being replicated at the time.

In spite of travelling over the web, the response time with MQTT is lightning fast, basically feels as if a local physical switch is being used...!



 
 As an alternative to MEANjs, there's also meteor.js but I haven't actually looked into that one, apparently it would have saved me some time integrating MQTT an socket.io - perhaps on my next project!
 

CTC-3D and Sitall

I've been rather busy lately but thought I'd document a few relevant pointers regarding 3D printing in general and my CTC-3D printer in particular.

First off, documenting my Octoprint settings for the CTC-3D (at least the relevant bits):










Also, while using the stock firmware + octoprint, I was using ReplicatorG as my slicer software.

After upgrading the firmware, I also moved to Slic3r. ReplicatorG is quite old and not being maintained anymore, apart from the Sailfish variant I guess - whereas Slic3r has many more options and also the possibility of exporting configs, which means I can easily use it on another machine to generate the gcode without having to set it up all over again.

Using slic3r, I just had to make sure to select Makerbot (sailfish) flavor gcode in the settings once I changed firmware.

Second, the fact that after being successful in printing with PLA and ABS using just painter tape, I decided to test printing on glass.

I decided to go with Sitall Glass since the Ebay supplier claimed it can be used without any other adherent substances like ABS goo, glue stick, painter tape, etc. - as a reference, this is seller.

Testing primarily with ABS, I found that the prints would detach from the glass plate mid-print and went on to investigate.

Other than that, the glass seems like it will do the job nicely, it is easily washable and as opposed to the painter tape, the prints won't get line marks on the bottom surface, where the tape strips meet on the plate.

I got myself an infrared thermometer, based on the youtube video below, which was very helpful


What I found out is that, as with in the video, the actual thermistor (thermal sensor) readings on the plate differ significantly from the measurements with the thermometer.

Isolating the printer case side/front panels didn't get it to 110ºC as required by the glass, as I also found out that the stock thermistor underneath the heat bed won't allow such temperatures. Also, the CTC-3D stock firmware is limited to 120ºC max.

After some investigating, two possible solutions were found:

  1. upgrade from stock firmware to sailfish firmware in order to be able to set higher heatbed temperatures, thus increasing the real bed temperature as well, and closer to 110ºC
  2. replace the heatbed thermistor sensor by another one, in order to reduce the temp difference between the one being measured and the actual temp on the bed.

I then set out to replacing the thermistor, based on a 3DHubs user advice as well as upgrade the stock firmware to the Sailfish firmware, in order to be able to set higher heatbed temperatures.

Upgrading the stock firmware wasn't without its hiccups, but no big deal:

[revised from my own post on 3DHubs]

I've recently upgraded my CTC to Sailfish 7.7 (r1432) - I followed the [sailfish firmware install] tutorial, used replicatorg-0040r33-Sailfish-linux.tgz from the thingiverse link as I'm using linux and it worked ok.

A member [on 3DHubs] helped me locate the reset button - it is a hole near the USB port in the back of the printer.

To upgrade the firmware, under linux 64bit, I had to install libusb-0.1-4 : i386 because RepG was reporting errors in the console regarding this lib not being found.

Once RepG was ok, doing the firmware update was as follows in my case:

Used RepG to scan serial devices and got /dev/ttyACM0 detected (the printer)

Machine > Machine Type (Driver) > The Replicator Dual (Sailfish)
Then Upload New Firmware > Makerbot Replicator 1 Single & Dual (v1.5) > Sailfish 7.7 (r1432)


/home/wickwire/Downloads/replicatorg-0040r33-Sailfish/tools/avrdude -C/home/wickwire/Downloads/replicatorg-0040r33-Sailfish/tools/avrdude.conf -cstk500v1 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/home/wickwire/.replicatorg/firmware/mighty_one-Sailfish-v7.7.0-r1432.hex:i -pm1280
avrdude: stk500_recv(): programmer is not responding


As RepG does a few retries before it timed out again in the log, I just pressed the reset button with a pen tip and it started flashing.

I was done in a few seconds (the terminal reported flashing success) - powered down, powered up and the LCD on the printer was working. Going through the options on the LCD to printer info I got the Sailfish info.

Did a factory reset using the printer LCD screen options, rebooted the printer, then checked the printer nozzle offsets and stuff as the guide mentions and all was ok, didn't change anything.

Printed a sample part as follow up using slic3r and being careful to update it to use makerbot (sailfish) instead of makerbot(makerware) and it worked properly.

At this point, the firmware upgrade was OK and printing with ABS on the Sitall glass works, provided I use hairspray for strong adhesion.

The infrared thermometer still registered a 95ºC max temperature on the glass, as I'm still to replace the thermistor.

Removing the heatbed was easy enough and this is what it looks like underneath:



The thermistor is highlighted in green on the photo. To replace it, I was advised to use a 100k ntc, so based on what I was looking at, I went with this model from Ebay (there are several available, mostly for Prusa and RepRap printers, but those are slightly different than what is used on this heatbed).


I'll update the blog with my findings once these parts are delivered.

Sunday, 12 July 2015

IoT Projects - ESP8266 [CTC-3D Printer Upgrade]

Based on the previous blog posts on MQTT, ESP8266-01 and NodeMCU, I decided as mentioned before to upgrade my newly acquired 3D printer, a CTC-3D dual extruder printer.

The printer is awesome and while it already operates remotely via Octoprint on Cubietruck (see previous posts), I did find it useful to add a cooling system to it as well as some lighting inside the chassis, both to be remotely controlled as well.

This post is all about the lua scripts loaded to the ESP8266-01 wifi module, in order to achieve this.

First off, I had several issues with memory usage while using a stock nodeMCU firmware, meaning, a build containing all the available modules.

Trimming the fat from the firmware proved quite valuable in memory terms (check previous posts).

Then, moving on to the lua scripts, I managed to devise a basic management system where I can now update the wifi module configurations for WiFi and MQTT broker over the air, using the MQTT messaging system.

config_wifi.lua:

wifi_ssid='wifiHotspot'
wifi_pass='w1f1P4ss'

config_mqtt.lua:

mqtt_host='192.168.1.2'
mqtt_port=1883
mqtt_topic='topic-'..node.chipid() 
 
bootup.lua:
 
function bootup()
    wifi.setmode(wifi.STATION)
    wifi.sta.config(wifi_ssid,wifi_pass)
end




mqtt_connect.lua:


function mqttActivate()
            m:connect(mqtt_host, mqtt_port, 0, function(conn)
                print("connected to mqtt broker!")
                m:subscribe("/"..mqtt_topic,0, function(conn)
                 tmr.stop(3)
                 tmr.stop(2)
                end)
            end)
end

function mqttConnect()
  m = mqtt.Client(wifi.sta.getmac(), 120, "user", "password")
  m:lwt("/lwt", wifi.sta.getmac(), 0, 0)

  m:on("offline", function(con)
       tmr.alarm(2, 10000, 1, function()
        print ("reconnecting to mqtt broker...")
        mqttActivate()
       end)
  end)

  tmr.alarm(3, 10000, 1, function()
        print("connecting to mqtt broker...")
   mqttActivate()
  end)

  mqttParse()

end

mqtt_parse.lua:


function mqttParse()
  m:on("message", function(conn, topic, data)
    if data ~= nil then
      local i=1
      local offset=0
      while string.find(data,";") do

       field = string.sub(data, offset, string.find(data,":")-1)
       dataArray[field] = string.sub(data, string.find(data,":")+1, string.find(data,";")-1)
       data = string.sub(data, string.find(data, ";") + 1, string.len(data))

       i = i + 1
      tmr.wdclr()
      end

      if dataArray['type'] == 'config-update' then 
       confUpdate()
      elseif dataArray['type'] == 'gpio-control' then
       gpioControl()
      end
    end
  end)
end
 
config_update.lua:

function confUpdate()
 print('changing configuration for module: '..dataArray['setting'])

 if dataArray['setting'] == 'wifi' then
  file.open("config_wifi.lua", "w+")
  file.writeline('wifi_ssid=\''..dataArray['ssid']..'\'')
  file.writeline('wifi_pass=\''..dataArray['pass']..'\'')
  file.close()
 elseif dataArray['setting'] == 'mqtt' then
  file.open("config_mqtt.lua", "w+")
  file.writeline('mqtt_host=\''..dataArray['host']..'\'')
  file.writeline('mqtt_port='..dataArray['port'])
  file.writeline('mqtt_topic=\'topic-'..node.chipid()..'\'')
  file.close()
 end

 node.restart()

end

gpio_control.lua:


function gpioControl()
 print('setting GPIO pin: '..dataArray['gpio'])
 
 pin=0
 
 if dataArray['gpio'] == '0' then
  pin=3
 elseif dataArray['gpio'] == '2' then
  pin=4
 end

 if dataArray['state'] == 'on' then
  gpio.write(pin, gpio.HIGH)
 elseif dataArray['state'] == 'off' then
  gpio.mode(pin, gpio.INPUT)
 end

end

init.lua: 
 
require 'config_wifi'
require 'config_mqtt'
require 'bootup'
require 'mqtt_connect'
require 'mqtt_parse'
require 'config_update'
require 'gpio_control'

dataArray={}

bootup()

gpio.mode(3, gpio.INPUT)
gpio.mode(4, gpio.INPUT)

mqttConnect()

 
The WiFi module will try to connect the the WiFi network and from there, to the
MQTT broker. Once connected, it will register to a new topic based on its ID,
which you'll be able to catch in the MQTT broker log file.
 
You'll want to compile all scripts, except for config_wifi.lua, config_mqtt.lua
and init.lua.

I'm still learning Lua, hadn't used it before, which is to say that there's
definitely room for improvement here - however, as they stand, these
scripts do the job in allowing for remote, on demand control!
 
And finally, at this point, you'll be able to publish messages
to your MQTT broker server in order to operate your wifi module:

mosquitto_pub -h 192.168.1.2 -p 1883 -t /topic-12345678 -m 'type:gpio-control;gpio:0;state:on;'
mosquitto_pub -h 192.168.1.2 -p 1883 -t /topic-12345678 -m 'type:gpio-control;gpio:0;state:off;'
mosquitto_pub -h 192.168.1.2 -p 1883 -t /topic-12345678 -m 'type:gpio-control;gpio:2;state:on;'
mosquitto_pub -h 192.168.1.2 -p 1883 -t /topic-12345678 -m 'type:gpio-control;gpio:2;state:off;'

mosquitto_pub -h 192.168.1.2 -p 1883 -t /topic-12345678 -m 'type:config-update;setting:mqtt;host:192.168.1.3;port:1883;'
mosquitto_pub -h 192.168.1.2 -p 1883 -t /topic-12345678 -m 'type:config-update;setting:wifi;ssid:wifiHotspot;pass:w1f1P4ss;'

IoT Projects - ESP8266 [programming]

Now all this is left is to program the ESP8266-01 module...!



For this part, I used one of these:

FT232RL 3.3V 5V FTDI USB to TTL Serial Adapter Module for Arduino Mini Port IDXX

Flashing the NodeMCU firmware

1) connect GPIO0 -> GND (Only for when loading the firmware because this pin is what defines the boot mode: firmware load mode or regular mode)

2) git clone https://github.com/themadinventor/esptool.git

3) get your firmware, either from github, the online custom build website from my previous post, etc.

4) sudo python esptool.py --port /dev/ttyUSB0 --baud 115200 write_flash 0x00000 /opt/ESP8266/nodemcu.firmwares/nodemcu_latest.bin

Connecting...
Erasing flash...
Writing at 0x00062000... (100 %)

Leaving...

Writing and Loading Some LUA Scripts

1) remember to disconnect GPIO0 from GND

2) git clone https://github.com/kmpm/nodemcu-uploader.git 

3) sudo ./nodemcu-uploader.py -p /dev/ttyUSB0 -b 115200 upload ../lua.scripts/webserver.lua:webserver.lua [--compile] [--restart]
 
Changing communication to 115200 baud
Preparing esp for transfer.
Transfering webserver.lua as webserver.lua
All done!
 
Using the parameter --compile will trigger lua script compiling at the wifi module:
after uploading the original lua script to the module, the python script will issue
the compile command, generating an lc binary file and deleting the original lua file
on the module.

Using the --restart parameter will issue a module reboot after uploading the script.

IoT Projects - ESP8266 [wiring]

My apologies in advance if the diagram below isn't all that proper, as mentioned before, I'm a bit of a newbie when it comes to wiring circuits...!

Anyways, the important bits to grasp here are:

1) the ESP will handle 3.3v max - going beyond that will most likely damage it
- using a 3.3v voltage regulator to ensure that the voltage being delivered to it is correct

2) the LED strip is represented by the LED on the upper part of the diagram
3) the case fans are represented by the LEDs on the lower part of the diagram
4) a couple of relays are required for wiring the fans and LED strip - and those are 5v relays, so another 5v voltage regulator is required
5) the case fans run at 12v
6) a single power supply is being used: 12v/1A
7) the wifi module's purpose is to control the relays using its two available GPIO pins, by processing MQTT messages from the broker (see previous posts on MQTT and Cubietruck)






Parts list follows:

IKEA Dioder LED strips
5V voltage regulators
3.3V voltage regulators
12V 1.0A Power Supply
5V Relay Module Board Shield
120mm Quiet Case Fans