#Program to test the "zweibein" Robot step, with accelerometer and servo movement.
#Made for walking.
#Version with no learning, just PID control.
#Run it with:
#python3 zweibeinschrittrobo3.py
#Gerald Schuller, March 2020
#
#Includes a
#function to read accelerometer sensor MMA8452Q from the Raspberry Pi I2C port.
#See: http://ozzmaker.com/guide-to-interfacing-a-gyro-and-accelerometer-with-a-raspberry-pi/
#Based on:
#https://github.com/ControlEverythingCommunity/MMA8452Q/blob/master/Python/MMA8452Q.py
#Connections:
#http://www.pibits.net/code/mma8452q-accelerometer-and-raspberry-pi-example.php
#
#Data Sheet of MMA8452Q:
#https://www.robotshop.com/media/files/pdf/triple-axis-accelerometer-breakout-board-mma8452q-headers-datasheet.pdf
#Activate I2C bus on Raspi with "sudo raspi-config"
#Then:
#sudo apt-get install build-essential libi2c-dev i2c-tools python-dev libffi-dev
#sudo pip install cffi smbus2 (for python2, for python3 it should be smbus and pip3)
#sudo pip3 install adafruit_servokit
#Gerald Schuller, May 2019

#import smbus2 as smbus #for Python2
import smbus   #for Python3
import time


# Get I2C bus
bus = smbus.SMBus(1)
#For the servos:
from adafruit_servokit import ServoKit

#Test MMA8452Q address after connecting it with (it shows in the table):
#sudo i2cdetect -y 1
#For Velleman VMA208 accelerometer it should be 0x1D, for others other addresses
MMA8452Q= 0x1D
#Setup:
# Select Control register, 0x2A(42)
#		0x00(00)	StandBy mode
bus.write_byte_data(MMA8452Q, 0x2A, 0x00)
# MMA8452Q address, 0x1C(28)
# Select Control register, 0x2A(42)
#		0x01(01)	Active mode
bus.write_byte_data(MMA8452Q, 0x2A, 0x01)
# MMA8452Q address, 0x1C(28)
# Select Configuration register, 0x0E(14)
#		0x00(00)	Set range to +/- 2g
bus.write_byte_data(MMA8452Q, 0x0E, 0x00)
time.sleep(0.1)

def readaccelerometer():
   #Read current accelerometer values
   #returns:
   #List of 3 float acceleration-values, [x,y,z]
   
   # Read data back from 0x00(0), 7 bytes
   # Status register, X-Axis MSB, X-Axis LSB, Y-Axis MSB, Y-Axis LSB, Z-Axis MSB, Z-Axis LSB
   data = bus.read_i2c_block_data(MMA8452Q, 0x00, 7)

   # Convert the data
   xAccl = (data[1] * 256 + data[2]) / 16
   if xAccl > 2047 :
      xAccl -= 4096
   #normalize to value range of -1.0...1.0:
   X=xAccl/1024.0
      
   yAccl = (data[3] * 256 + data[4]) / 16
   if yAccl > 2047 :
      yAccl -= 4096
   #normalize to value range of -1.0...1.0:
   Y=yAccl/1024.0

   zAccl = (data[5] * 256 + data[6]) / 16
   if zAccl > 2047 :
      zAccl -= 4096 
   #normalize to value range of -1.0...1.0:
   Z=zAccl/1024.0

   return (X,Y,Z)

#Testing:
if __name__ == '__main__':
   import numpy as np
   
   # Set channels to the number of servo channels on your kit.
   # 8 for FeatherWing, 16 for Shield/HAT/Bonnet.
   kit = ServoKit(channels=16)
   huefterechts=kit.servo[8]
   huefterechts.angle=90.0-60
   hueftelinks=kit.servo[9]
   hueftelinks.angle=90.0+60
   knierechts=kit.servo[10]
   knierechts.angle=90.0+1
   knielinks=kit.servo[11]
   knielinks.angle=90.0-1
   fussrechts=kit.servo[14]
   fussrechts.angle=90.0
   fusslinks=kit.servo[15]
   fusslinks.angle=90.0
   
   timestep=0.01 #time step in seconds
   phase=0.0
   speed=0.04;  #0.24, 0.1, 0.04 phase increment in radiants for servo, speed is forward. 0.25 seems to be close to resonance.
   schrittzaehler=0
   #PID controller:
   verttilt=0.5
   hortiltadj=0.1
   omega=2*3.14*20.0/100; #20, normalized frequency of oscillation for 100 hz sampling (10ms delay)
   #Q=0.5;
   Q=0.005 #0.005, is actually 1/Q, without artifical factor 100
   k1=2*Q*np.cos(omega); #0.003
   k2=Q**2; #2.5e-5
   
   ydist=0.0;
   yold=0.0
   YLP=0.0
   YLPold=0.0
   Yvar=0.0
   Yvarold=10.0 #large value for optimization start
   hortilt=0.0    #starting horizontal tilt
   zdist=0.0;
   zold=0.0
   ZLP=0.0
   ZLPold=0.0
   Zvar=0.0 #variance of Z for horizontal oscillation
   Zvarold=0.0 
   Zerrold=10.0 #old horizontal error for optimization (some large number)
   pllphasec=0.0 #phase of horizonzal tilt correlated with steps, the cosine, like in a PLL, the more positive the faster forward, an optimization criterium!
   pllphases=0.0 #same, for the sine
   pllphasecold=0.0
   signspeed=1.0
   
   scale=1.0
   
   ampRH=0.0;ampLH=0.0; ampLK=0.0; ampRK=0.0 #amplitudes for the steps
   knierechtsbalance=0.0
   knielinksbalance=0.0
   amptilt=0.1 #0.2 0.3 amplitude of the step tilt
   #hortiltadj=0.1 #0.1horizontal tilt adjustment (depending on inbalance of battery pack) (read in from file)
   
   while True:
      #test if accelerometer works, move accelerometer, the printed values should change:
      (X,Y,Z)=readaccelerometer()
      X=-X; Z=-Z #sign change for rotated accelerometer
      #print("Accelerometer X,Y,Z=", round(X,2),round(Y,2),round(Z,2))  
      
      #Forward tilt:
      ydist+= (Y-verttilt)*(timestep);        #integral values (distance traveled, without artificial factor 100)
      #ydist: direction to front, zdist: direction to side
      #print("ydist=", ydist)
      #print("Z=", Z)  #horizontal accelerometer value: kippt wenn abs > 0.5
      #print("Y=", Y)  #vertical accelerometer value: kippt bei >0.8 und <-0.1
      zdist+= (Z-hortilt)*(timestep);
      ydist=np.clip(ydist,-1,1);
      zdist=np.clip(zdist,-1,1);
      
      yspeed=(Y-yold)/(timestep);  #differential values (speed, without artificial factor 100)
      
      #Sideways tilt:
      zspeed=(Z-zold)/(timestep);
      yold=Y;
      zold=Z;
      
      ZLPold=ZLP
      ZLP=0.99*ZLP+0.01*Z
      zlpspeed=(ZLP-ZLPold)/(timestep)  #hor. speed from low passed version
      Zvar= 0.99*Zvar+0.01*(Z**2)
      YLPold=YLP
      YLP=0.99*YLP+0.01*Y
      ylpspeed=(YLP-YLPold)/(timestep)  #vert. speed from low passed version
      Yvar=0.99*Yvar+0.01*((Z-YLP)**2)
      pllphasec=0.95 * pllphasec +0.05* Z*np.cos(phase)
      pllphases=0.95 * pllphases +0.05* Z*np.sin(phase)
      
      #frontbalance = 180/3.14* 2.6*(ydist + k1*(Y-verttilt) -k2*yspeed)*1.0; #2: schneller, without artificial factor 100
      
      frontbalance = 180/3.14* 2.6*(ydist + 0.05*(Y-verttilt) -4*2.0e-2*ylpspeed) #k2 + or -?
      #frontbalance = 149.0*ydist + 7.45*(Y-verttilt) -0.03*yspeed
      
      #sidebalance = -180/3.14* 2.9*(zdist + k1*(Z-hortilt) -k2*zspeed)*1.0; #2: schneller, without artificial factor 100
      
      sidebalance = -180/3.14* 2.9*(zdist + 0.05*(Z-hortilt) -2*4.0e-2*zlpspeed)*1.0;# k2=4e-4 #2: schneller, without artificial factor 100. k1 needs to be larger for faster steps, ca. 0.7 fuer speed 0.25. k2 was originally with - sign, but with plus seems to be better!
      
      #sidebalance = -166.2*zdist - 8.31*(Z-hortilt) -0.066*zspeed
      
      #horangle= 180/3.14*np.arcsin(np.clip(Z,-1.0,1.0)); print("horangle=",horangle)
      #hortiltangle= 180/3.14*np.arcsin(np.clip(hortilt,-1.0,1.0)); print("hortiltangle=", hortiltangle)
      #sidebalance = horangle - 0.5*(horangle-hortiltangle) #The factor is the damping
      sidebalance=np.clip(sidebalance,-50,50);
      
      
      #This should make the roboto tilt forth and back, observe the printout at which values it can balances on its own:
      #verttilt=(np.sin(phase)**2)*0.5
      #print("vertical tilt=", verttilt) 
      #Choose a stable middle verttilt value:
      #verttilt=0.43
      #Then this should make the robot periodically tilt sideways:
      hortiltoffset=0.0
      if (schrittzaehler>0):
         #periodically tilt sideways for step movement:
         #hortiltoffset=-amptilt*np.cos(phase) #amptilt=-0.2,-0.08
         """
         if Zvar> 0.03:
            amptilt=amptilt*0.99
         else:
            amptilt=np.clip(amptilt*1.01, 0,0.2)
         """
         #print("Zvar=", Zvar, "amptilt=", amptilt)
         hortiltoffset=-amptilt*np.sign(np.cos(phase))#*np.sqrt(abs(np.cos(phase)))
         #randomly move sideways for noise exitation for resonance oscillation:
         #hortiltoffset=-amptilt*((np.random.rand(1)-0.5))*1.0
         #hortiltoffset= amptilt*np.sign((np.random.rand(1)-0.5))
         #hortiltoffset=-0.08*np.sign(np.cos(phase))*(np.abs(np.cos(phase)))**0.5 #square root function
         ampLH=-5.0*np.sin(phase) #5.0
         #move when tilted: (saturates at -7! Probably because tilt is one sided.)
         #if abs(Z -hortiltadj)<0.3: #only move when not too much tilt:
         #ampLH += np.clip(Z -hortiltadj,-0.3, 0.3)*3  #move leg according to tilt, clip to stable range of Z
         #print("(Z -hortiltadj)*5=", (Z -hortiltadj)*5)
         #ampLH += np.sign(Z -hortiltadj)*5 #constant foot speed
         #print("zlpspeed=", zlpspeed)#, "Z=", Z, "ZLP=", ZLP, )
         #amplH= zlpspeed*40  #make step speed proportional to tilt speed
         ampLH= np.clip(ampLH, -5, 5)
         ampRH=-5.0*np.sin(phase) #5.0
         #if abs(Z -hortiltadj)<0.3: #only move when not too much tilt:
         #ampRH += np.clip(Z -hortiltadj, -0.3, 0.3)*3 
         #ampRH += np.sign(Z -hortiltadj)*5 #constant foot speed
         #ampRH = zlpspeed*40 #make step speed proportional to tilt speed
         ampRH = np.clip(ampRH, -5, 5)
         #print("ampLH=", ampLH, "ampRH=", ampRH)
         #avoid having feet touch when they move:
         #ampRK=1.0*np.clip(np.cos(phase),-1,0)
         #ampLK=-1.0*np.clip(np.cos(phase),0,1)
         #noise=np.random.rand(1)-0.5  #noise excitation of tilt, to start oscillation at resonance:
         #ampRK=1.0*np.clip(noise,-1,0)*0.2
         #ampLK=-1.0*np.clip(noise,0,1)*0.2
         #
      
      
      #print("Z=", Z)
      hortilt= hortiltadj+hortiltoffset
      #hortilt=+0.05+.. #somewhat to the left
      #print("horizontal tilt=", hortilt) 
      #use the maximum hortilt value for the steps
      
      #avoid fallig from too mch side tilt, abs(Z)>0.1:
      #Emergency routines agains falling:
      #print("Z=", Z, " Y=", Y)
      #"""
      #print("ylpspeed=", ylpspeed)
      """
      hortiltadj=0.1
      if abs(zlpspeed) >1:  #move center opposite if too much horizontal speed:
         print("Too much horizontal speed, zlpspeed=", zlpspeed)
         hortiltadj= 0.1-zlpspeed*0.1
      """
      falling=False
      if Z>0.5:  #falling left:
         #knielinksbalance+=8.0
         #hortiltoffset=0; #balance straight to avoid falling
         #amptilt-=0.03 #reduce amplitude of step tilt, seems t work
         #hortiltadj-=0.01; k[3]=hortiltadj
         #sidebalance=0; zdist=0 #make knees straight
         #print("knielinks fall","Z=", Z)
         falling=True
      elif Z< -0.5: #falling right
         #knierechtsbalance-=8.0
         #hortiltoffset=0; #balance straight to avoid falling
         #amptilt-=0.03
         #hortiltadj+=0.01; k[3]=hortiltadj
         #sidebalance=0; zdist=0
         #print("knierechts fall","Z=", Z)
         falling=True
      else:
         knierechtsbalance= 0 #-2.0 #legs a little to the side for more stability (makes it worse)
         knielinksbalance=0 #2.0
         #amptilt+=0.0005
      amptilt=np.clip(amptilt, 0, 0.3)
      hortiltadj=np.clip(hortiltadj, -0.2 , 0.2)
      #if abs(Z)>0.4:
      #   print("amptilt=", amptilt, "hortiltadj=", hortiltadj)
      #"""
      #"""
      if Y> 0.95: #falling forward
         print("forward fall", " Y=", Y)
         #phase+= 0.2
         #verttilt-=0.01
         falling=True
      elif Y< 0.1: #falling backward
         print("backward fall", " Y=", Y)
         #phase -=0.2
         #verttilt+=0.01
         falling=True
      verttilt=np.clip(verttilt, -0.5, 0.9)
      #if Y>0.95 or Y<0.1:
      #   print("verttilt=", verttilt)
      #"""
      angle=np.clip(int(frontbalance+90-1*ampRH),0, 180);
      huefterechts.angle=angle; #sign change because of flipping hip servos
      angle=np.clip(int(-frontbalance+90-1*ampLH),0,180);
      hueftelinks.angle=angle; #sign change because of flipping hip servos
      angle=np.clip(int(sidebalance+knierechtsbalance+90-0-ampRK),0,180);
      knierechts.angle=angle;
      angle=np.clip(int(sidebalance+knielinksbalance+90+0-ampLK),0,180);
      knielinks.angle=angle; 
      
      """
      fussrechts.angle=90.0-50*np.clip(hortiltoffset,0,1)
      fusslinks.angle=90.0-50*np.clip(hortiltoffset,-1,0)
      """
      #Negative angle of the hips for the feet, compared to 90 Degrees
      #such that the feet are always parallel to the floor:
      """
      fussrechts.angle=np.clip(int(90+0.5*(-1*ampRH)),0, 180);
      fusslinks.angle=np.clip(int(90-0.5*(-1*ampLH)),0,180);
      print("fussrechts.angle", fussrechts.angle)
      """
      #print("zdist=", zdist)
      #print("Z-hortiltadj=", Z-hortiltadj)
      #print("Z=", Z)
      phase+=speed
      #print("phase=", phase)
      if(phase>= 6.28):
         phase=0.0;
         schrittzaehler += 1;
         
         print("ZLP =", ZLP, "Zvar:", Zvar, "zspeed=", zspeed, "YLP=", YLP, "pllphasec=", pllphasec, "pllphases=", pllphases, "Yvar=", Yvar, "Yvarold=", Yvarold) 
         
         #hortiltadj = hortiltadj*0.9+0.1*ZLP #ZLP is a good paramater for adaptive horizontal tilt adjustment!
         #verttilt = verttilt*0.9 + 0.1*YLP #adaptove vertical tilt.
         print("hortiltadj =", hortiltadj, "verttilt=", verttilt)
         """
         print("hortiltadj=", hortiltadj)
         if Zvar > 0.02:
            amptilt-=0.01
         else:
            amptilt+=0.01
         print("amptilt=", amptilt)
         """
         print("schrittzaehler=", schrittzaehler)
         
         

         #speed+= signspeed*0.01
         
         speed=np.clip(speed, 0.04, 0.3)
         print("speed=", speed, "signspeed=", signspeed)
         
         
      if(phase<0 ):
         phase=6.28;
         schrittzaehler += 1;
      time.sleep(timestep)
      
