def updateLCD(): global page global lcd global r global logger global sshConfirm global shutConfirm # Create object for getting IP addresses of interfaces ipaddress = IPAddress() if not page == 9: sshConfirm = False if not page == 11: shutConfirm = False # Now display the appropriate LCD page if page == 0: # Update ethernet eth0ip = ipaddress.get_ip_address('eth0') r.set("eth:active", bool(eth0ip)) r.set("eth:ip", eth0ip) wlan0ip = ipaddress.get_ip_address('wlan0') r.set("wlan:active", bool(wlan0ip)) if eval(r.get("eth:active")): lcd[0] = "Ethernet: YES" lcd[1] = r.get("eth:ip") elif eval(r.get("wlan:active")) or eval(r.get("gsm:active")): page += 1 else: lcd[0] = "Ethernet:" lcd[1] = "NOT CONNECTED" if page == 1: # Update wifi wlan0ip = ipaddress.get_ip_address('wlan0') r.set("wlan:active", bool(wlan0ip)) r.set("wlan:ip", wlan0ip) signallevel = 0 if wlan0ip: # wlan link status with open('/proc/net/wireless', 'r') as f: wireless = f.readlines() signals = [x.split()[3] for x in wireless if x.strip().startswith('wlan0')] if signals: signallevel = signals[0].partition('.')[0] if signallevel.startswith('-'): # Detect the alternate signal strength reporting via dBm signallevel = 2 * (int(signallevel) + 100) # Convert to percent r.set("wlan:signallevel", signallevel) if eval(r.get("wlan:active")): if int(r.get("wlan:signallevel")) > 0: lcd[0] = "WiFi: YES " + r.get("wlan:signallevel") + "%" else: if r.get("wlan:ip") == "192.168.42.1": lcd[0] = "WiFi: AP MODE" else: lcd[0] = "WiFi: YES " lcd[1] = r.get("wlan:ip") elif eval(r.get("gsm:active")) or eval(r.get("eth:active")): page += 1 else: lcd[0] = "WiFi:" lcd[1] = "NOT CONNECTED" if page == 2: # Update Hi-Link 3G Dongle - connects on eth1 if ipaddress.get_ip_address("eth1") and gsmhuaweistatus.is_hilink(hilink_device_ip): gsm_connection_status = gsmhuaweistatus.return_gsm_connection_status(hilink_device_ip) r.set("gsm:connection", gsm_connection_status[0]) r.set("gsm:signal", gsm_connection_status[1]) r.set("gsm:active", 1) else: r.set("gsm:active", 0) if eval(r.get("gsm:active")): lcd[0] = r.get("gsm:connection") lcd[1] = r.get("gsm:signal") elif eval(r.get("eth:active")) or eval(r.get("wlan:active")): page += 1 else: lcd[0] = "GSM:" lcd[1] = "NO DEVICE" if page == 3: if r.get("feed1") is not None: lcd[0] = feed1_name + ':' + r.get("feed1") + feed1_unit else: lcd[0] = feed1_name + ':' + "---" if r.get("feed2") is not None: lcd[1] = feed2_name + ':' + r.get("feed2") + feed2_unit else: lcd[1] = feed2_name + ':' + "---" elif page == 4: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'VRMS: ' + basedata[3] + "V" lcd[1] = 'Pulse: ' + basedata[10] + "p" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' page += 1 elif page == 5: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'Temp 1: ' + basedata[4] + "C" lcd[1] = 'Temp 2: ' + basedata[5] + "C" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' page += 1 elif page == 6: # Get uptime with open('/proc/uptime', 'r') as f: seconds = float(f.readline().split()[0]) r.set('uptime', seconds) lcd[0] = datetime.now().strftime('%b %d %H:%M') lcd[1] = 'Uptime %.2f days' % (seconds / 86400) elif page == 7: lcd[0] = "emonPi Build:" lcd[1] = sd_image_version elif page == 8: ret = subprocess.call(ssh_status, shell=True) if ret > 0: # ssh not running lcd[0] = "SSH Enable?" else: # ssh not running lcd[0] = "SSH Disable?" lcd[1] = "Y press & hold" sshConfirm = False elif page == 9: sshConfirm = True elif page == 10: lcd[0] = "Shutdown?" lcd[1] = "Y press & hold" shutConfirm = False elif page == 11: lcd[0] = "Shutdown?" shutConfirm = True
def main(): global longPress global shortPress # First set up logging atexit.register(logging.shutdown) if not uselogfile: loghandler = logging.StreamHandler() else: logfile = "/var/log/emonpilcd/emonpilcd.log" print "emonPiLCD logging to: " + logfile loghandler = logging.handlers.RotatingFileHandler( logfile, mode='a', maxBytes=1000 * 1024, backupCount=1, ) loghandler.setFormatter( logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger = logging.getLogger("emonPiLCD") logger.addHandler(loghandler) logger.setLevel(logging.INFO) logger.info("Starting emonPiLCD V" + version) # Now check the LCD and initialise the object lcd = LCD(logger) lcd.backlight = 1 # ------------------------------------------------------------------------------------ # Discover & display emonPi SD card image version # ------------------------------------------------------------------------------------ sd_image_version = '' sd_card_image = subprocess.call("ls /boot | grep emonSD", shell=True) if not sd_card_image: # if emonSD file exists sd_image_version = subprocess.check_output("ls /boot | grep emonSD", shell=True) else: sd_card_image = subprocess.call("ls /boot | grep emonpi", shell=True) if not sd_card_image: sd_image_version = subprocess.check_output( "ls /boot | grep emonpi", shell=True) else: sd_image_version = "N/A " sd_image_version = sd_image_version.rstrip() lcd[0] = "emonPi Build:" lcd[1] = sd_image_version logger.info("SD card image build version: " + sd_image_version) # Set up the buttons and install handlers # emonPi LCD push button Pin 16 GPIO 23 # Uses gpiozero library to handle short and long press https://gpiozero.readthedocs.io/en/stable/api_input.html?highlight=button # push_btn = Button(23, pull_up=False, hold_time=5, bounce_time=0.1) # No bounce time increases responce time but may result in switch bouncing... push_btn = Button(23, pull_up=False, hold_time=5) push_btn.when_pressed = buttonPress push_btn.when_held = buttonPressLong # emonPi Shutdown button, Pin 11 GPIO 17 GPIO.setup(17, GPIO.IN) logger.info("Connecting to redis server...") r = redis.Redis(host=redis_host, port=redis_port, db=0) # We wait here until redis has successfully started up while True: try: r.client_list() break except redis.ConnectionError: logger.error("waiting for redis-server to start...") time.sleep(1.0) logger.info("Connected to redis") logger.info("Connecting to MQTT Server: " + mqtt_host + " on port: " + str(mqtt_port) + " with user: "******"/") if int(topic_parts[2]) == emonPi_nodeID: r.set("basedata", msg.payload) def on_connect(client, userdata, flags, rc): if (rc == 0): mqttc.subscribe(mqtt_topic) mqttc = mqtt.Client() mqttc.on_message = on_message mqttc.on_connect = on_connect try: mqttc.username_pw_set(mqtt_user, mqtt_passwd) mqttc.reconnect_delay_set(min_delay=1, max_delay=120) mqttc.connect_async(mqtt_host, mqtt_port, 60) # Run MQTT background thread which handles reconnects mqttc.loop_start() except Exception: logger.error("Could not connect to MQTT") else: logger.info("Connected to MQTT") # time to show Build version time.sleep(2) buttonPress_time = time.time() page = 0 # Create object for getting IP addresses of interfaces ipaddress = IPAddress() # Enter main loop while True: now = time.time() # turn backight off after backlight_timeout seconds if now - buttonPress_time > backlight_timeout and lcd.backlight: lcd.backlight = 0 if shortPress: shortPress = False if lcd.backlight: page += 1 if page > max_number_pages: page = 0 buttonPress_time = now if not lcd.backlight: lcd.backlight = 1 logger.info("Mode button SHORT press") logger.info("Page: " + str(page)) if longPress: longPress = False logger.info("Mode button LONG press") subprocess.call("/home/pi/emonpi/lcd/enablessh.sh") logger.info("SSH Enabled") lcd[0] = 'SSH Access ' lcd[1] = 'Enabled ' time.sleep(2) lcd[0] = 'Change password ' lcd[1] = 'on first login >' time.sleep(2) if eval(r.get("eth:active")): lcd[0] = 'ss pi@' + r.get("eth:ip") if eval(r.get("wlan:active")): lcd[0] = 'pi@' + r.get("wlan:ip") lcd[1] = 'pass: emonpi2018' push_btn.wait_for_press() # Get system parameters and store in redis # Get uptime with open('/proc/uptime', 'r') as f: seconds = float(f.readline().split()[0]) r.set('uptime', seconds) # Update ethernet eth0ip = ipaddress.get_ip_address('eth0') r.set("eth:active", bool(eth0ip)) r.set("eth:ip", eth0ip) # Update wifi wlan0ip = ipaddress.get_ip_address('wlan0') r.set("wlan:active", bool(wlan0ip)) r.set("wlan:ip", wlan0ip) signallevel = 0 if wlan0ip: # wlan link status with open('/proc/net/wireless', 'r') as f: wireless = f.readlines() signals = [ x.split()[3] for x in wireless if x.strip().startswith('wlan0') ] if signals: signallevel = signals[0].partition('.')[0] if signallevel.startswith( '-' ): # Detect the alternate signal strength reporting via dBm signallevel = 2 * (int(signallevel) + 100 ) # Convert to percent r.set("wlan:signallevel", signallevel) # Update Hi-Link 3G Dongle - connects on eth1 if ipaddress.get_ip_address("eth1") and gsmhuaweistatus.is_hilink( hilink_device_ip): gsm_connection_status = gsmhuaweistatus.return_gsm_connection_status( hilink_device_ip) r.set("gsm:connection", gsm_connection_status[0]) r.set("gsm:signal", gsm_connection_status[1]) r.set("gsm:active", 1) else: r.set("gsm:active", 0) # Now display the appropriate LCD page if page == 0: if eval(r.get("eth:active")): lcd[0] = "Ethernet: YES" lcd[1] = r.get("eth:ip") elif eval(r.get("wlan:active")) or eval(r.get("gsm:active")): page += 1 else: lcd[0] = "Ethernet:" lcd[1] = "NOT CONNECTED" if page == 1: if eval(r.get("wlan:active")): lcd[0] = "WIFI: YES " + r.get("wlan:signallevel") + "%" lcd[1] = r.get("wlan:ip") elif eval(r.get("gsm:active")) or eval(r.get("eth:active")): page += 1 else: lcd[0] = "WiFi:" lcd[1] = "NOT CONNECTED" if page == 2: if eval(r.get("gsm:active")): lcd[0] = r.get("gsm:connection") lcd[1] = r.get("gsm:signal") elif eval(r.get("eth:active")) or eval(r.get("wlan:active")): page += 1 else: lcd[0] = "GSM:" lcd[1] = "NO DEVICE" if page == 3: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'Power 1: ' + basedata[0] + "W" lcd[1] = 'Power 2: ' + basedata[1] + "W" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' elif page == 4: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'VRMS: ' + basedata[3] + "V" lcd[1] = 'Temp 1: ' + basedata[4] + " C" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' elif page == 5: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'Temp 2: ' + basedata[5] + "C" lcd[1] = 'Pulse: ' + basedata[10] + "p" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' elif page == 6: lcd[0] = datetime.now().strftime('%b %d %H:%M') lcd[1] = 'Uptime %.2f days' % (seconds / 86400) elif page == 7: lcd[0] = "emonPi Build:" lcd[1] = sd_image_version # If Shutdown button is pressed initiate shutdown sequence if GPIO.input(17) == 1: logger.info("shutdown button pressed") shutdown(lcd)
def updateLCD(): global page global lcd global r global logger global sshConfirm global shutConfirm # Create object for getting IP addresses of interfaces ipaddress = IPAddress() if not page == 9: sshConfirm = False if not page == 11: shutConfirm = False # Now display the appropriate LCD page if page == 0: # Update ethernet eth0ip = ipaddress.get_ip_address('eth0') active = 1 if eth0ip == 0: active = 0 r.set("eth:active", active) r.set("eth:ip", eth0ip) wlan0ip = ipaddress.get_ip_address('wlan0') active = 1 if wlan0ip == 0: active = 0 r.set("wlan:active", active) if eval(r.get("eth:active")): lcd[0] = "Ethernet: YES" lcd[1] = r.get("eth:ip") elif eval(r.get("wlan:active")) or eval(r.get("gsm:active")): page += 1 else: lcd[0] = "Ethernet:" lcd[1] = "NOT CONNECTED" if page == 1: # Update wifi wlan0ip = ipaddress.get_ip_address('wlan0') r.set("wlan:active", bool(wlan0ip)) r.set("wlan:ip", wlan0ip) signallevel = 0 if wlan0ip: # wlan link status with open('/proc/net/wireless', 'r') as f: wireless = f.readlines() signals = [ x.split()[3] for x in wireless if x.strip().startswith('wlan0') ] if signals: signallevel = signals[0].partition('.')[0] if str(signallevel).startswith( '-' ): # Detect the alternate signal strength reporting via dBm signallevel = 2 * (int(signallevel) + 100 ) # Convert to percent r.set("wlan:signallevel", signallevel) if eval(r.get("wlan:active")): if int(r.get("wlan:signallevel")) > 0: lcd[0] = "WiFi: YES " + r.get("wlan:signallevel") + "%" else: if r.get("wlan:ip") == "192.168.42.1": lcd[0] = "WiFi: AP MODE" else: lcd[0] = "WiFi: YES " lcd[1] = r.get("wlan:ip") elif eval(r.get("gsm:active")) or eval(r.get("eth:active")): page += 1 else: lcd[0] = "WiFi:" lcd[1] = "NOT CONNECTED" if page == 2: # Update Hi-Link 3G Dongle - connects on eth1 if ipaddress.get_ip_address("eth1") and gsmhuaweistatus.is_hilink( hilink_device_ip): gsm_connection_status = gsmhuaweistatus.return_gsm_connection_status( hilink_device_ip) r.set("gsm:connection", gsm_connection_status[0]) r.set("gsm:signal", gsm_connection_status[1]) r.set("gsm:active", 1) else: r.set("gsm:active", 0) if eval(r.get("gsm:active")): lcd[0] = r.get("gsm:connection") lcd[1] = r.get("gsm:signal") elif eval(r.get("eth:active")) or eval(r.get("wlan:active")): page += 1 else: lcd[0] = "GSM:" lcd[1] = "NO DEVICE" if page == 3: if r.get("feed1") is not None: lcd[0] = feed1_name + ':' + r.get("feed1") + feed1_unit else: lcd[0] = feed1_name + ':' + "---" if r.get("feed2") is not None: lcd[1] = feed2_name + ':' + r.get("feed2") + feed2_unit else: lcd[1] = feed2_name + ':' + "---" elif page == 4: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'VRMS: ' + basedata[3] + "V" lcd[1] = 'Pulse: ' + basedata[10] + "p" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' page += 1 elif page == 5: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'Temp 1: ' + basedata[4] + "C" lcd[1] = 'Temp 2: ' + basedata[5] + "C" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' page += 1 elif page == 6: # Get uptime with open('/proc/uptime', 'r') as f: seconds = float(f.readline().split()[0]) r.set('uptime', seconds) lcd[0] = datetime.now().strftime('%b %d %H:%M') lcd[1] = 'Uptime %.2f days' % (seconds / 86400) elif page == 7: lcd[0] = "emonPi Build:" lcd[1] = sd_image_version elif page == 8: ret = subprocess.call(ssh_status, shell=True) if ret > 0: #ssh not running lcd[0] = "SSH Enable?" else: #ssh not running lcd[0] = "SSH Disable?" lcd[1] = "Y press & hold" sshConfirm = False elif page == 9: sshConfirm = True elif page == 10: lcd[0] = "Shutdown?" lcd[1] = "Y press & hold" shutConfirm = False elif page == 11: lcd[0] = "Shutdown?" shutConfirm = True
def main(): # First set up logging atexit.register(logging.shutdown) if not uselogfile: loghandler = logging.StreamHandler() else: logfile = "/var/log/emonpilcd/emonpilcd.log" print "emonPiLCD logging to: "+logfile loghandler = logging.handlers.RotatingFileHandler(logfile, mode='a', maxBytes=1000 * 1024, backupCount=1, ) loghandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger = logging.getLogger("emonPiLCD") logger.addHandler(loghandler) logger.setLevel(logging.INFO) logger.info("emonPiLCD V2 Start") # Now check the LCD and initialise the object lcd = LCD(logger) lcd.backlight = 1 # ------------------------------------------------------------------------------------ # Discover & display emonPi SD card image version # ------------------------------------------------------------------------------------ sd_image_version = '' sd_card_image = subprocess.call("ls /boot | grep emonSD", shell=True) if not sd_card_image: # if emonSD file exists sd_image_version = subprocess.check_output("ls /boot | grep emonSD", shell=True) else: sd_card_image = subprocess.call("ls /boot | grep emonpi", shell=True) if not sd_card_image: sd_image_version = subprocess.check_output("ls /boot | grep emonpi", shell=True) else: sd_image_version = "N/A " sd_image_version = sd_image_version.rstrip() lcd[0] = "emonPi Build:" lcd[1] = sd_image_version logger.info("SD card image build version: " + sd_image_version) # Set up the buttons and install handlers atexit.register(GPIO.cleanup) # Use Pi board pin numbers as these as always consistent between revisions GPIO.setmode(GPIO.BOARD) # emonPi LCD push button Pin 16 GPIO 23 GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # emonPi Shutdown button, Pin 11 GPIO 17 GPIO.setup(11, GPIO.IN) # Create a pipe with no buffering, make the read end non-blocking and pass # the other to the ButtonInput class pipe = os.pipe() pipe = (os.fdopen(pipe[0], 'r', 0), os.fdopen(pipe[1], 'w', 0)) fcntl.fcntl(pipe[0], fcntl.F_SETFL, os.O_NONBLOCK) buttoninput = ButtonInput(logger, pipe[1]) logger.info("Connecting to redis server...") r = redis.Redis(host=redis_host, port=redis_port, db=0) # We wait here until redis has successfully started up while True: try: r.client_list() break except redis.ConnectionError: logger.error("waiting for redis-server to start...") time.sleep(1.0) logger.info("Connected to redis") logger.info("Connecting to MQTT Server: " + mqtt_host + " on port: " + str(mqtt_port) + " with user: "******"/") if int(topic_parts[2]) == emonPi_nodeID: r.set("basedata", msg.payload) def on_connect(client, userdata, flags, rc): mqttc.subscribe(mqtt_topic) mqttc = mqtt.Client() mqttc.on_message = on_message mqttc.on_connect = on_connect try: mqttc.username_pw_set(mqtt_user, mqtt_passwd) mqttc.connect(mqtt_host, mqtt_port, 60) # Run MQTT background thread which handles reconnects mqttc.loop_start() except Exception: logger.error("Could not connect to MQTT") else: logger.info("Connected to MQTT") # time to show Build version time.sleep(2) buttonPress_time = time.time() page = 0 # Create object for getting IP addresses of interfaces ipaddress = IPAddress() # Enter main loop while True: now = time.time() # turn backight off after backlight_timeout seconds if now - buttonPress_time > backlight_timeout and lcd.backlight: lcd.backlight = 0 if buttoninput.pressed: buttoninput.pressed = False if lcd.backlight: page += 1 if page > max_number_pages: page = 0 buttonPress_time = now if not lcd.backlight: lcd.backlight = 1 logger.info("Mode button pressed") logger.info("Page: " + str(page)) # Get system parameters and store in redis # Get uptime with open('/proc/uptime', 'r') as f: seconds = float(f.readline().split()[0]) r.set('uptime', seconds) # Update ethernet eth0ip = ipaddress.get_ip_address('eth0') r.set("eth:active", bool(eth0ip)) r.set("eth:ip", eth0ip) # Update wifi wlan0ip = ipaddress.get_ip_address('wlan0') r.set("wlan:active", bool(wlan0ip)) r.set("wlan:ip", wlan0ip) signallevel = 0 if wlan0ip: # wlan link status with open('/proc/net/wireless', 'r') as f: wireless = f.readlines() signals = [x.split()[3] for x in wireless if x.strip().startswith('wlan0')] if signals: signallevel = signals[0].partition('.')[0] r.set("wlan:signallevel", signallevel) # Update Hi-Link 3G Dongle - connects on eth1 if ipaddress.get_ip_address("eth1") and gsmhuaweistatus.is_hilink(hilink_device_ip): gsm_connection_status = gsmhuaweistatus.return_gsm_connection_status(hilink_device_ip) r.set("gsm:connection", gsm_connection_status[0]) r.set("gsm:signal", gsm_connection_status[1]) r.set("gsm:active", 1) else: r.set("gsm:active", 0) # Now display the appropriate LCD page if page == 0: if eval(r.get("eth:active")): lcd[0] = "Ethernet: YES" lcd[1] = r.get("eth:ip") elif eval(r.get("wlan:active")) or eval(r.get("gsm:active")): page += 1 else: lcd[0] = "Ethernet:" lcd[1] = "NOT CONNECTED" if page == 1: if eval(r.get("wlan:active")): lcd[0] = "WIFI: YES " + r.get("wlan:signallevel") + "%" lcd[1] = r.get("wlan:ip") elif eval(r.get("gsm:active")) or eval(r.get("eth:active")): page += 1 else: lcd[0] = "WIFI:" lcd[1] = "NOT CONNECTED" if page == 2: if eval(r.get("gsm:active")): lcd[0] = r.get("gsm:connection") lcd[1] = r.get("gsm:signal") elif eval(r.get("eth:active")) or eval(r.get("wlan:active")): page += 1 else: lcd[0] = "GSM:" lcd[1] = "NO DEVICE" if page == 3: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'Power 1: ' + basedata[0] + "W" lcd[1] = 'Power 2: ' + basedata[1] + "W" else: lcd[0] = 'ERROR: MQTT' lcd[1] = 'Not connected' elif page == 4: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'VRMS: ' + basedata[3] + "V" lcd[1] = 'Temp 1: ' + basedata[4] + " C" else: lcd[0] = 'ERROR: MQTT' lcd[1] = 'Not connected' elif page == 5: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'Temp 2: ' + basedata[5] + "C" lcd[1] = 'Pulse: ' + basedata[10] + "p" else: lcd[0] = 'ERROR: MQTT' lcd[1] = 'Not connected' elif page == 6: lcd[0] = datetime.now().strftime('%b %d %H:%M') lcd[1] = 'Uptime %.2f days' % (seconds / 86400) elif page == 7: lcd[0] = "emonPi Build:" lcd[1] = sd_image_version # If Shutdown button is pressed initiate shutdown sequence if GPIO.input(11) == 1: logger.info("shutdown button pressed") shutdown(lcd) # Wait up to one second or until the button is pressed. read, _, _ = select([pipe[0]], [], [], 1) if read: # pipe is readable, consume the byte. try: read[0].read(1) except IOError: pass
def run(self): last1s = time.time() - 2.0 last5s = time.time() - 6.0 # Loop until we stop is false (our exit signal) while not self.stop: now = time.time() # ---------------------------------------------------------- # UPDATE EVERY 1's # ---------------------------------------------------------- if (now-last1s)>=1.0: last1s = now # Get uptime with open('/proc/uptime', 'r') as f: seconds = float(f.readline().split()[0]) array = str(timedelta(seconds = seconds)).split('.') string = array[0] r.set("uptime",seconds) # ---------------------------------------------------------- # UPDATE EVERY 5's # ---------------------------------------------------------- if (now-last5s)>=5.0: last5s = now # Ethernet eth0 # -------------------------------------------------------------------------------- eth0ip = getip.getip("eth0") #Returns '' if not configured ethactive = 1 if eth0ip == False: ethactive = 0 r.set("eth:active",ethactive) r.set("eth:ip",eth0ip) #print "Eth0: "+str(ethactive)+" "+str(eth0ip) # Hi-Link 3G Dongle - connects on eth1 # -------------------------------------------------------------------------------- eth1ip = getip.getip("eth1") eth1active = 1 if eth1ip== False: eth1active = 0 else: if not gsmhuaweistatus.is_hilink(hilink_device_ip): eth1active = 0 else: gsm_connection_status = gsmhuaweistatus.return_gsm_connection_status(hilink_device_ip) r.set("gsm:connection",gsm_connection_status[0]) r.set("gsm:signal",gsm_connection_status[1]) r.set("gsm:active",eth1active) # Wireless LAN # ---------------------------------------------------------------------------------- wlan0ip = getip.getip("wlan0") wlanactive = 1 if wlan0ip== False: wlanactive = 0 r.set("wlan:active",wlanactive) r.set("wlan:ip",wlan0ip) #print "wlan1: "+str(wlanactive)+" "+str(wlan0ip) # ---------------------------------------------------------------------------------- signallevel = 0 linklevel = 0 noiselevel = 0 if wlanactive: # wlan link status p = Popen("/sbin/iwconfig wlan0", shell=True, stdout=PIPE) iwconfig = p.communicate()[0] tmp = re.findall('(?<=Signal level=)\w+',iwconfig) if len(tmp)>0: signallevel = tmp[0] r.set("wlan:signallevel",signallevel) # this loop runs a bit faster so that ctrl-c exits are fast time.sleep(0.1)
def main(): # First set up logging atexit.register(logging.shutdown) if not uselogfile: loghandler = logging.StreamHandler() else: logfile = "/var/log/emonpilcd/emonpilcd.log" print "emonPiLCD logging to: " + logfile loghandler = logging.handlers.RotatingFileHandler( logfile, mode='a', maxBytes=1000 * 1024, backupCount=1, ) loghandler.setFormatter( logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger = logging.getLogger("emonPiLCD") logger.addHandler(loghandler) logger.setLevel(logging.INFO) logger.info("Starting emonPiLCD V" + version) # Now check the LCD and initialise the object lcd = LCD(logger) lcd.backlight = 1 # ------------------------------------------------------------------------------------ # Discover & display emonPi SD card image version # ------------------------------------------------------------------------------------ sd_image_version = '' sd_card_image = subprocess.call("ls /boot | grep emonSD", shell=True) if not sd_card_image: # if emonSD file exists sd_image_version = subprocess.check_output("ls /boot | grep emonSD", shell=True) else: sd_card_image = subprocess.call("ls /boot | grep emonpi", shell=True) if not sd_card_image: sd_image_version = subprocess.check_output( "ls /boot | grep emonpi", shell=True) else: sd_image_version = "N/A " sd_image_version = sd_image_version.rstrip() lcd[0] = "emonPi Build:" lcd[1] = sd_image_version logger.info("SD card image build version: " + sd_image_version) # Set up the buttons and install handlers atexit.register(GPIO.cleanup) # Use Pi board pin numbers as these as always consistent between revisions GPIO.setmode(GPIO.BOARD) # emonPi LCD push button Pin 16 GPIO 23 GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # emonPi Shutdown button, Pin 11 GPIO 17 GPIO.setup(11, GPIO.IN) # Create a pipe with no buffering, make the read end non-blocking and pass # the other to the ButtonInput class pipe = os.pipe() pipe = (os.fdopen(pipe[0], 'r', 0), os.fdopen(pipe[1], 'w', 0)) fcntl.fcntl(pipe[0], fcntl.F_SETFL, os.O_NONBLOCK) buttoninput = ButtonInput(logger, pipe[1]) logger.info("Connecting to redis server...") r = redis.Redis(host=redis_host, port=redis_port, db=0) # We wait here until redis has successfully started up while True: try: r.client_list() break except redis.ConnectionError: logger.error("waiting for redis-server to start...") time.sleep(1.0) logger.info("Connected to redis") logger.info("Connecting to MQTT Server: " + mqtt_host + " on port: " + str(mqtt_port) + " with user: "******"/") if int(topic_parts[2]) == emonPi_nodeID: r.set("basedata", msg.payload) def on_connect(client, userdata, flags, rc): mqttc.subscribe(mqtt_topic) mqttc = mqtt.Client() mqttc.on_message = on_message mqttc.on_connect = on_connect try: mqttc.username_pw_set(mqtt_user, mqtt_passwd) mqttc.connect(mqtt_host, mqtt_port, 60) # Run MQTT background thread which handles reconnects mqttc.loop_start() except Exception: logger.error("Could not connect to MQTT") else: logger.info("Connected to MQTT") # time to show Build version time.sleep(2) buttonPress_time = time.time() page = 0 # Create object for getting IP addresses of interfaces ipaddress = IPAddress() # Enter main loop while True: now = time.time() # turn backight off after backlight_timeout seconds if now - buttonPress_time > backlight_timeout and lcd.backlight: lcd.backlight = 0 if buttoninput.pressed: buttoninput.pressed = False if lcd.backlight: page += 1 if page > max_number_pages: page = 0 buttonPress_time = now if not lcd.backlight: lcd.backlight = 1 logger.info("Mode button pressed") logger.info("Page: " + str(page)) # Get system parameters and store in redis # Get uptime with open('/proc/uptime', 'r') as f: seconds = float(f.readline().split()[0]) r.set('uptime', seconds) # Update ethernet eth0ip = ipaddress.get_ip_address('eth0') r.set("eth:active", bool(eth0ip)) r.set("eth:ip", eth0ip) # Update wifi wlan0ip = ipaddress.get_ip_address('wlan0') r.set("wlan:active", bool(wlan0ip)) r.set("wlan:ip", wlan0ip) signallevel = 0 if wlan0ip: # wlan link status with open('/proc/net/wireless', 'r') as f: wireless = f.readlines() signals = [ x.split()[3] for x in wireless if x.strip().startswith('wlan0') ] if signals: signallevel = signals[0].partition('.')[0] if signallevel.startswith( '-' ): # Detect the alternate signal strength reporting via dBm signallevel = 2 * (int(signallevel) + 100 ) # Convert to percent r.set("wlan:signallevel", signallevel) # Update Hi-Link 3G Dongle - connects on eth1 if ipaddress.get_ip_address("eth1") and gsmhuaweistatus.is_hilink( hilink_device_ip): gsm_connection_status = gsmhuaweistatus.return_gsm_connection_status( hilink_device_ip) r.set("gsm:connection", gsm_connection_status[0]) r.set("gsm:signal", gsm_connection_status[1]) r.set("gsm:active", 1) else: r.set("gsm:active", 0) # Now display the appropriate LCD page if page == 0: if eval(r.get("eth:active")): lcd[0] = "Ethernet: YES" lcd[1] = r.get("eth:ip") elif eval(r.get("wlan:active")) or eval(r.get("gsm:active")): page += 1 else: lcd[0] = "Ethernet:" lcd[1] = "NOT CONNECTED" if page == 1: if eval(r.get("wlan:active")): lcd[0] = "WIFI: YES " + r.get("wlan:signallevel") + "%" lcd[1] = r.get("wlan:ip") elif eval(r.get("gsm:active")) or eval(r.get("eth:active")): page += 1 else: lcd[0] = "WiFi:" lcd[1] = "NOT CONNECTED" if page == 2: if eval(r.get("gsm:active")): lcd[0] = r.get("gsm:connection") lcd[1] = r.get("gsm:signal") elif eval(r.get("eth:active")) or eval(r.get("wlan:active")): page += 1 else: lcd[0] = "GSM:" lcd[1] = "NO DEVICE" if page == 3: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'Power 1: ' + basedata[0] + "W" lcd[1] = 'Power 2: ' + basedata[1] + "W" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' elif page == 4: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'VRMS: ' + basedata[3] + "V" lcd[1] = 'Temp 1: ' + basedata[4] + " C" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' elif page == 5: basedata = r.get("basedata") if basedata is not None: basedata = basedata.split(",") lcd[0] = 'Temp 2: ' + basedata[5] + "C" lcd[1] = 'Pulse: ' + basedata[10] + "p" else: lcd[0] = 'Connecting...' lcd[1] = 'Please Wait' elif page == 6: lcd[0] = datetime.now().strftime('%b %d %H:%M') lcd[1] = 'Uptime %.2f days' % (seconds / 86400) elif page == 7: lcd[0] = "emonPi Build:" lcd[1] = sd_image_version # If Shutdown button is pressed initiate shutdown sequence if GPIO.input(11) == 1: logger.info("shutdown button pressed") shutdown(lcd) # Wait up to one second or until the button is pressed. read, _, _ = select([pipe[0]], [], [], 1) if read: # pipe is readable, consume the byte. try: read[0].read(1) except IOError: pass