#Install the advanced utilities

## Setting the Real Time Clock

	$ sudo apt-get -y remove fake-hwclock
	$ sudo update-rc.d -f fake-hwclock remove
	$ sudo systemctl disable fake-hwclock

Edit file /lib/udev/hwclock-set:

	$ sudo nano /lib/udev/hwclock-set


and comment line:

	#!/bin/sh
	# Reset the System Clock to UTC if the hardware clock from which it
	# was copied by the kernel was in localtime.
	
	dev=$1
	
	#if [ -e /run/systemd/system ] ; then
	# exit 0
	#fi

Edit the file /etc/modules

	$ sudo nano /etc/modules

with these contents:

	# /etc/modules: kernel modules to load at boot time.
	#
	# This file contains the names of kernel modules that should be loaded
	# at boot time, one per line. Lines beginning with "#" are ignored.
	
	i2c-dev
	rtc-8523

Edit file /etc/rc.local:

	$ sudo nano /etc/rc.local 
	
Insert this line before the <code>exit 0</code> istruction:

	# PCF8523
	echo pcf8523 0x68 > /sys/class/i2c-adapter/i2c-1/new_device

then reboot by typing: 

	$ sudo reboot

Now run command:

	$ sudo i2cdetect -y 1

	     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
	00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
	10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
	20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
	30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
	40: -- -- -- -- -- -- -- -- -- -- -- -- -- UU -- -- 
	50: -- -- -- -- -- -- -- -- -- -- -- -- -- UU -- -- 
	60: -- -- -- -- -- -- -- -- UU -- -- -- -- -- -- -- 
	70: -- -- -- -- -- -- -- --                         

Address 0x68 is Real Time Clock

Create a directory /home/pi/app:

	$ mkdir /home/pi/app

Create the file /home/pi/app/goshd.py
with these contents:

	#!/usr/bin/python
	
	import RPi.GPIO as GPIO
	import time
	import datetime
	import os

	O_DISPLAY       =22
	I_SHD           =25
	
	GPIO.setmode(GPIO.BCM)
	GPIO.setwarnings(False)
	
	GPIO.setup(I_SHD,GPIO.IN)
	GPIO.setup(O_DISPLAY,GPIO.OUT)
	
	while True:
	        if GPIO.input(I_SHD) == 1:
	                GPIO.output(O_DISPLAY,GPIO.HIGH)        # Display Off
	                os.system("sudo shutdown -h -P now")
	
	        time.sleep(.5)

Set it as executable:

	$ chmod +x /home/pi/app/goshd.py

Create a service by editing this file:

	$ sudo nano /etc/systemd/system/goshdn.service

Save in it these contents:

	[Unit]
	Description=Set Auto shutdown
	After=systemd-user-sessions.service
	
	[Service]
	ExecStart=/home/pi/app/goshd.py
	Restart=on-abort
	User=root
	WorkingDirectory=/home/pi/app
	
	[Install]
	WantedBy=multi-user.target

Then enable the service by typing:

	$ sudo systemctl daemon-reload
	$ sudo systemctl enable goshdn.service

Create the file /home/pi/app/cm3start.py with these contents:

	#!/usr/bin/python
	
	import RPi.GPIO as GPIO
	import time
	import os
	
	SHDNDONE        = 26
	
	GPIO.setmode(GPIO.BCM)
	GPIO.setwarnings(False)
	GPIO.setup(SHDNDONE,GPIO.OUT)
	
	# On CM3 (Send message OK to Microcontroller )
	GPIO.output(SHDNDONE,GPIO.LOW)
	
	# Set Register RTC
	time.sleep(1)
	os.system("sudo i2cset -y -f 1 0x68 0x00 0x58")
	time.sleep(1)
	os.system("sudo i2cset -y -f 1 0x68 0x0f 0xff")
	time.sleep(1)
	os.system("sudo hwclock -s")

Set it as executable:

	$ chmod +x cm3start.py

Create a systemd file for this service:

	$ sudo nano /etc/systemd/system/cm3start.service

with this content:

	[Unit]
	Description=CPU to microcontroller to start regular operating system
	After=systemd-user-sessions.service
	
	[Service]
	ExecStart=/home/pi/app/cm3start.py
	Restart=on-abort
	User=root
	WorkingDirectory=/home/pi/app
	
	[Install]
	WantedBy=multi-user.target

Then enable the service by typing:

	$ sudo systemctl daemon-reload
	$ sudo systemctl enable cm3start.service
	$ sudo halt

Now Remove Jumper BYPASS

Insert Jumper to Supercap CHK

Power on board and wait charge supercap.

When the Board has been started and the operating system has been started up regulary, disconnect the board from the power supply.
The same will turn off automatically the shutdown.

Now the Power Safe is activated. !!!

Create python script set_alarm.py (Interrupt RTC)

	$ sudo raspi-config

Examples:

Set Localisation Options, L2 Timezone, Europe and Rome.

This will be used for example to set the board to switch on at a set time (MANUAL mode) at a set time through the Interrupt
Real Time Clock chip.

Python Script for setting interrupt.

	$ nano /home/pi/app/set_alarm.py

Contents:

	#!/usr/bin/python
	'''
	===============================================================================
	Description :   Set PCF8523 Alarm interrupt - Minute or Time
	Board       :   CM3-Panel V.7 POE - Acme Systems
	Autror      :   Mauro Tocci
	Version     :   1.1 - October 2019
	
	-------------------------------------------------------------------------------
	Use example :
	-------------------------------------------------------------------------------
	script.py 12:15 M N N
	script.py 12:15 T N N
	                | | |_ Y = Debug enable (Y only screen, no transfer to the chip)
	                | |
	                | |___ Y = Sync NTP server
	                |
	                |_____ M = Switching on only when the minutes indicate value 15
	                |_____ T = Start-up time 12:15
	-------------------------------------------------------------------------------
	Logic sequence:
	Time alarm example: 14:30
	
	1. Split time value to array (variable dato[x])
	2. Hour calculation (dato[0]) to time UTC
	
	3. Calculation of hexadecimal values to be set on the RTC registers
	
	Hour alarm register (address 0Bh)
	               Hour
	              __12__    <--- UTC value
	             |      |
	            DEC   UNIT
	            7654  3210  Bit registry
	            0001  0010  Binary
	             |______|
	                |    <- Concatenate
	             00010010   BCD to hex convert
	                |
	              0x12      Hexadecimal value
	                |
	sudo i2cset -f -y 0x68 0x0b 0x12    Set Hour Alarm registry
	
	Minute alarm register (address 0Ah)
	              Minute
	              __30__
	             |      |
	            DEC   UNIT
	            7654  3210  Bit registry
	            0011  0000  Binary
	             |______|
	                |    <- Concatenate
	             00110000   BCD to hex convert
	                |
	              0x30      Hexadecimal value
	                |
	sudo i2cset -f -y 0x68 0x0a 0x30    Set Minute Alarm registry
	
	4. Send final sequence data to RTC
	
	sudo ntpdate ntp1.inrim.it          # Example Sync Italian NTP Server (Y)
	sudo hwclock -w                     # Set clock hardware (Y)
	sudo i2cset -f -y 0x68 0x00 0x58    # Reset chip PC8523"
	sudo i2cset -f -y 0x68 0x00 0x02    # AIE Enable alarm INT1
	sudo i2cset -f -y 0x68 0x0f 0xff    # INT1 Off - mosfet open drain
	sudo i2cset -f -y 0x68 0x0a 0x30    # Set Minute Alarm registry
	sudo i2cset -f -y 0x68 0x0b 0x12    # Set Hour Alarm registry
	===============================================================================
	'''
	import os
	import sys
	import datetime
	from datetime import timedelta
	
	#----------------------------------------------------------------------
	# Conversion from decimal to binary
	#----------------------------------------------------------------------
	def bcddigit(sn,dgt):
	    n = int(sn)
	    bin_nr = bin(n)[2:]
	    return (('0' * dgt ) + bin_nr)[-dgt:]
	
	#----------------------------------------------------------------------
	# Clear
	#----------------------------------------------------------------------
	def cls():
	    os.system('cls' if os.name=='nt' else 'clear')
	
	try:
	    #----------------------------------------------------------------------
	    # Variables sets
	    #----------------------------------------------------------------------
	    dato  = sys.argv[1].split(':')  # Array hour
	    TYP   = sys.argv[2]             # Type of writing
	    Sync  = sys.argv[3]             # Sync to NTP server
	    Debug = sys.argv[4]             # Debug screen print value
	
	    #----------------------------------------------------------------------
	    # Data preparation to be transferred to the chip
	    #----------------------------------------------------------------------
	    cls()
	
	    delta = 0
	    ACTH  = dato[0]                 # Hour
	    ACTM  = dato[1]                 # Minute
	
	    # UTC
	    utc_h = datetime.datetime.utcnow()
	
	    # Local time
	    dat_h = datetime.datetime.now()
	
	    # I find the difference between local time and UTC
	    if ( utc_h < dat_h ):
	        delta = (int(dat_h.strftime("%H")) - int(utc_h.strftime("%H"))) *-1
	
	    #----------------------------------------------------------------------
	    # UTC Calculate
	    #----------------------------------------------------------------------
	    utc_h = datetime.datetime.now().strftime("%Y-%m-%d " + dato[0] + ":" + dato[1])
	    utc_h = datetime.datetime.strptime(utc_h, '%Y-%m-%d %H:%M')
	    utc_h = utc_h + timedelta(hours=delta)
	    dato  = utc_h.strftime("%H:%M").split(':')  # Calculated time
	
	    D = 4
	    BIN_D   = ""    # Decimal
	    BIN_U   = ""    # Unit
	    reg_0a  = ""    # Minute Register
	    reg_0b  = ""    # Hour Register
	
	    if ( Debug == 'Y' ):
	        print "==================================================================="
	        print " List of data entered and register calculation"
	        print "==================================================================="
	        print "Time             : " + sys.argv[1]
	        print "Type             : " + TYP
	        print "Sync NTP         : " + Sync
	        print "Calc UTC         : " + repr(delta) + " hours compared to Local Time"
	
	    if ( TYP == 'T' ):
	
	        if ( Debug == 'Y' ):
	            print ""
	            print "-----------------"
	            print "      HOURS"
	            print "-----------------"
	            print " Value           : " + ACTH
	            print " UTC calculation : " + dato[0]
	            print ""
	            print " Ten's place     : " + dato[0][:1]
	
	        BIN_D = bcddigit(dato[0][:1],D)
	
	        if ( Debug == 'Y' ):
	            print " Binary          : " + BIN_D
	            print " HEX             : " + hex(int(BIN_D,2)).replace("0x", "0x0")
	            print ""
	            print " Unit place      : " + dato[0][1:]
	
	        BIN_U = bcddigit(dato[0][1:],D)
	
	        if ( Debug == 'Y' ):
	            print " Binary          : " + BIN_U
	            print " HEX             : " + hex(int(BIN_U,2)).replace("0x", "0x0")
	
	            print ""
	            print " Bit registry    : 76543210 - AEN_H = 7 (0 = Enable, default 1)"
	            print " Binary          : " + BIN_D + BIN_U
	
	        BIN = BIN_D + BIN_U
	
	        if ( int(BIN,2) < 16 ):
	            reg_0b = hex(int(BIN,2)).replace("0x", "0x0")
	            if ( Debug == 'Y' ):
	                print " HEX Reg. 0Bh    : " + reg_0b
	        else:
	            reg_0b = hex(int(BIN,2))
	            if ( Debug == 'Y' ):
	                print " HEX Reg. 0Bh    : " + reg_0b
	
	    if ( Debug == 'Y' ):
	        print ""
	        print "-----------------"
	        print "    MINUTES"
	        print "-----------------"
	        print " Value           : " + ACTM
	        print ""
	        print " Ten's place     : " + dato[1][:1]
	
	    BIN_D = bcddigit(dato[1][:1],D)
	
	    if ( Debug == 'Y' ):
	        print " Binary          : " + BIN_D
	        print " HEX             : " + hex(int(BIN_D,2)).replace("0x", "0x0")
	        print ""
	        print " Unit place      : " + dato[1][1:]
	
	    BIN_U = bcddigit(dato[1][1:],D)
	
	    if ( Debug == 'Y' ):
	        print " Binary          : " + BIN_U
	        print " HEX             : " + hex(int(BIN_U,2)).replace("0x", "0x0")
	        print ""
	        print " Bit registry    : 76543210 - AEN_M = 7 (0 = Enable, default 1)"
	        print " Binary          : " + BIN_D + BIN_U
	
	    BIN = BIN_D + BIN_U
	
	    if ( int(BIN,2) < 16 ):
	        reg_0a = hex(int(BIN,2)).replace("0x", "0x0")
	        if ( Debug == 'Y' ):
	            print " HEX Reg. 0Ah    : " + reg_0a
	    else:
	        reg_0a = hex(int(BIN,2))
	        if ( Debug == 'Y' ):
	            print " HEX Reg. 0Ah    : " + reg_0a
	
	    if ( Debug == 'Y' ):
	        print ""
	        print "-------------------------------------------------------------------"
	        print " Set registry PCF8523"
	        print "-------------------------------------------------------------------"
	        if ( Sync == 'Y' ):
	            print "sudo ntpdate ntp1.inrim.it" + "       # Sync NTP Server Italiano"
	            print "sudo hwclock -w" + "                  # Set clock hardware"
	
	        print "sudo i2cset .y -f 1 0x68 0x00 0x58" + " # Reset chip PC8523"
	        print "sudo i2cset -y -f 1 0x68 0x00 0x02" + " # AIE Enable alarm INT1"
	        print "sudo i2cset -y -f 1 0x68 0x0f 0xff" + " # INT1 Off"
	
	        if ( TYP == 'T' ):
	            print "sudo i2cset -y -f 1 0x68 0x0b " + reg_0b + " # Set Hour register"
	
	        print "sudo i2cset -y -f 1 0x68 0x0a " + reg_0a + " # Set Minute register"
	        print ""
	
	    if ( Debug == 'N' ):
	        if ( Sync == 'Y' ):
	            x=os.system("sudo ntpdate ntp1.inrim.it")
	            x=os.system("sudo hwclock -w")
	
	        os.system("sudo i2cset -y -f 1 0x68 0x00 0x58")
	        os.system("sudo i2cset -y -f 1 0x68 0x00 0x02")
	        os.system("sudo i2cset -y -f 1 0x68 0x0f 0xff")
	
	        if ( TYP == 'T' ):
	            os.system("sudo i2cset -y -f 1 0x68 0x0b " + reg_0b + "")
	
	        os.system("sudo i2cset -y -f 1 0x68 0x0a " + reg_0a + "")
	
	except IndexError as e:
	    cls()
	    print "---------------------------------------------------------------------------------------"
	    print " Error insert data"
	    print "---------------------------------------------------------------------------------------"
	    print "     Example use :"
	    print ""
	    print "     Name      Time  Functions"
	    print "     script.py 12:15 M N N"
	    print "     script.py 12:15 T N N"
	    print "                     | | |_ Y = Debug enable (Y only screen, no transfer to the chip)"
	    print "                     | |"
	    print "                     | |___ Y = Sync NTP server"
	    print "                     |"
	    print "                     |_____ M = Switching on only when the minutes indicate value 15"
	    print "                     |_____ T = Start-up time 12:15 (*)"
	    print ""
	    print "     (*) Note : The time is recalculated by the script based on the UTC format."
	    print "---------------------------------------------------------------------------------------"
	    print ""

Example use:

	./set_alarm.py 16:11 T N N

This set interrupt to LOW status from hour 16:11.

## WiFi configuration USB or board adapter 5.8Ghz.

	$ sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

Contents:

	#ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
	#update_config=1
	
	ctrl_interface=/var/run/wpa_supplicant
	network={
	    ssid="SSID_NAME"
	    scan_ssid=1
	    key_mgmt=WPA-PSK
	    group=TKIP CCMP
	    pairwise=TKIP CCMP
	    #proto=WPA WPA2
	    key_mgmt=WPA-PSK
	    psk="password"
	}

Check WiFi device

	$ lsusb
	Bus 001 Device 004: ID 0e8d:7610 MediaTek Inc.

If request after reboot install driver:

Driver installation:

* <https://www.raspberrypi.org/forums/viewtopic.php?t=205240>

	$ sudo mkdir /lib/firmware/mediatek
	
	$ cd /lib/firmware/mediatek
	
	$ sudo wget http://anduin.linuxfromscratch.org/sources/linux-firmware/mediatek/mt7610u.bin
	
	$ sudo modprobe -r mt76x0
	
	$ sudo modprobe mt76x0
	
	$ sudo reboot

	$ ifconfig

Example result:

	wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
	        inet 192.168.192.109  netmask 255.255.255.0  broadcast 192.168.192.255
	        inet6 fe80::ea9:41d4:7ab4:273c  prefixlen 64  scopeid 0x20<link>
	        ether 70:f1:1c:28:af:56  txqueuelen 1000  (Ethernet)
	        RX packets 44  bytes 15932 (15.5 KiB)
	        RX errors 0  dropped 0  overruns 0  frame 0
	        TX packets 28  bytes 4601 (4.4 KiB)
	        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

@include='adv_cmpanel'


